title
stringlengths
3
56
author
stringclasses
3 values
hostname
stringclasses
1 value
date
stringclasses
3 values
fingerprint
stringlengths
15
16
id
null
license
null
comments
stringclasses
1 value
raw_text
stringlengths
518
796k
text
stringlengths
514
592k
language
null
image
null
pagetype
null
source
stringlengths
68
116
source-hostname
stringclasses
1 value
excerpt
null
categories
stringclasses
1 value
tags
stringclasses
1 value
API Conventions
null
espressif.com
2016-01-01
bc127268662167db
null
null
API Conventions This document describes conventions and assumptions common to ESP-IDF Application Programming Interfaces (APIs). ESP-IDF provides several kinds of programming interfaces: C functions, structures, enums, type definitions, and preprocessor macros declared in public header files of ESP-IDF components. Various pages in the API Reference section of the programming guide contain descriptions of these functions, structures, and types. Build system functions, predefined variables, and options. These are documented in the ESP-IDF CMake Build System API. Kconfig options can be used in code and in the build system ( CMakeLists.txt ) files. Host tools and their command line parameters are also part of the ESP-IDF interfaces. ESP-IDF is made up of multiple components where these components either contain code specifically written for ESP chips, or contain a third-party library (i.e., a third-party component). In some cases, third-party components contain an "ESP-IDF specific" wrapper in order to provide an interface that is either simpler or better integrated with the rest of ESP-IDF's features. In other cases, third-party components present the original API of the underlying library directly. The following sections explain some of the aspects of ESP-IDF APIs and their usage. Error Handling Most ESP-IDF APIs return error codes defined with the esp_err_t type. See Error Handling section for more information about error handling approaches. Error Codes Reference contains the list of error codes returned by ESP-IDF components. Configuration Structures Important Correct initialization of configuration structures is an important part of making the application compatible with future versions of ESP-IDF. Most initialization, configuration, and installation functions in ESP-IDF (typically named ..._init() , ..._config() , and ..._install() ) take a configuration structure pointer as an argument. For example: const esp_timer_create_args_t my_timer_args = { .callback = &my_timer_callback, .arg = callback_arg, .name = "my_timer" }; esp_timer_handle_t my_timer; esp_err_t err = esp_timer_create(&my_timer_args, &my_timer); These functions never store the pointer to the configuration structure, so it is safe to allocate the structure on the stack. The application must initialize all fields of the structure. The following is incorrect: esp_timer_create_args_t my_timer_args; my_timer_args.callback = &my_timer_callback; /* Incorrect! Fields .arg and .name are not initialized */ esp_timer_create(&my_timer_args, &my_timer); Most ESP-IDF examples use C99 designated initializers for structure initialization since they provide a concise way of setting a subset of fields, and zero-initializing the remaining fields: const esp_timer_create_args_t my_timer_args = { .callback = &my_timer_callback, /* Correct, fields .arg and .name are zero-initialized */ }; The C++ language supports designated initializer syntax, too, but the initializers must be in the order of declaration. When using ESP-IDF APIs in C++ code, you may consider using the following pattern: /* Correct, fields .dispatch_method, .name and .skip_unhandled_events are zero-initialized */ const esp_timer_create_args_t my_timer_args = { .callback = &my_timer_callback, .arg = &my_arg, }; ///* Incorrect, .arg is declared after .callback in esp_timer_create_args_t */ //const esp_timer_create_args_t my_timer_args = { // .arg = &my_arg, // .callback = &my_timer_callback, //}; For more information on designated initializers, see Designated Initializers. Note that C++ language versions older than C++20, which are not the default in the current version of ESP-IDF, do not support designated initializers. If you have to compile code with an older C++ standard than C++20, you may use GCC extensions to produce the following pattern: esp_timer_create_args_t my_timer_args = {}; /* All the fields are zero-initialized */ my_timer_args.callback = &my_timer_callback; Default Initializers For some configuration structures, ESP-IDF provides macros for setting default values of fields: httpd_config_t config = HTTPD_DEFAULT_CONFIG(); /* HTTPD_DEFAULT_CONFIG expands to a designated initializer. Now all fields are set to the default values, and any field can still be modified: */ config.server_port = 8081; httpd_handle_t server; esp_err_t err = httpd_start(&server, &config); It is recommended to use default initializer macros whenever they are provided for a particular configuration structure. Private APIs Certain header files in ESP-IDF contain APIs intended to be used only in ESP-IDF source code rather than by the applications. Such header files often contain private or esp_private in their name or path. Certain components, such as hal only contain private APIs. Private APIs may be removed or changed in an incompatible way between minor or patch releases. Components in Example Projects ESP-IDF examples contain a variety of projects demonstrating the usage of ESP-IDF APIs. In order to reduce code duplication in the examples, a few common helpers are defined inside components that are used by multiple examples. This includes components located in common_components directory, as well as some of the components located in the examples themselves. These components are not considered to be part of the ESP-IDF API. It is not recommended to reference these components directly in custom projects (via EXTRA_COMPONENT_DIRS build system variable), as they may change significantly between ESP-IDF versions. When starting a new project based on an ESP-IDF example, copy both the project and the common components it depends on out of ESP-IDF, and treat the common components as part of the project. Note that the common components are written with examples in mind, and might not include all the error handling required for production applications. Before using, take time to read the code and understand if it is applicable to your use case. API Stability ESP-IDF uses Semantic Versioning as explained in the Versioning Scheme. Minor and bugfix releases of ESP-IDF guarantee compatibility with previous releases. The sections below explain different aspects and limitations to compatibility. Source-level Compatibility ESP-IDF guarantees source-level compatibility of C functions, structures, enums, type definitions, and preprocessor macros declared in public header files of ESP-IDF components. Source-level compatibility implies that the application source code can be recompiled with the newer version of ESP-IDF without changes. The following changes are allowed between minor versions and do not break source-level compatibility: Deprecating functions (using the deprecated attribute) and header files (using a preprocessor #warning ). Deprecations are listed in ESP-IDF release notes. It is recommended to update the source code to use the newer functions or files that replace the deprecated ones, however, this is not mandatory. Deprecated functions and files can be removed from major versions of ESP-IDF. Renaming components, moving source and header files between components — provided that the build system ensures that correct files are still found. Renaming Kconfig options. Kconfig system's backward compatibility ensures that the original Kconfig option names can still be used by the application in sdkconfig file, CMake files, and source code. Lack of Binary Compatibility ESP-IDF does not guarantee binary compatibility between releases. This means that if a precompiled library is built with one ESP-IDF version, it is not guaranteed to work the same way with the next minor or bugfix release. The following are the possible changes that keep source-level compatibility but not binary compatibility: Changing numerical values for C enum members. Adding new structure members or changing the order of members. See Configuration Structures for tips that help ensure compatibility. Replacing an extern function with a static inline one with the same signature, or vice versa. Replacing a function-like macro with a compatible C function. Other Exceptions from Compatibility While we try to make upgrading to a new ESP-IDF version easy, there are parts of ESP-IDF that may change between minor versions in an incompatible way. We appreciate issuing reports about any unintended breaking changes that do not fall into the categories below. Features clearly marked as "beta", "preview", or "experimental". Changes made to mitigate security issues or to replace insecure default behaviors with secure ones. Features that were never functional. For example, if it was never possible to use a certain function or an enumeration value, it may get renamed (as part of fixing it) or removed. This includes software features that depend on non-functional chip hardware features. Unexpected or undefined behavior that is not documented explicitly may be fixed/changed, such as due to missing validation of argument ranges. Location of Kconfig options in menuconfig. Location and names of example projects.
API Conventions This document describes conventions and assumptions common to ESP-IDF Application Programming Interfaces (APIs). ESP-IDF provides several kinds of programming interfaces: C functions, structures, enums, type definitions, and preprocessor macros declared in public header files of ESP-IDF components. Various pages in the API Reference section of the programming guide contain descriptions of these functions, structures, and types. Build system functions, predefined variables, and options. These are documented in the ESP-IDF CMake Build System API. Kconfig options can be used in code and in the build system ( CMakeLists.txt) files. Host tools and their command line parameters are also part of the ESP-IDF interfaces. ESP-IDF is made up of multiple components where these components either contain code specifically written for ESP chips, or contain a third-party library (i.e., a third-party component). In some cases, third-party components contain an "ESP-IDF specific" wrapper in order to provide an interface that is either simpler or better integrated with the rest of ESP-IDF's features. In other cases, third-party components present the original API of the underlying library directly. The following sections explain some of the aspects of ESP-IDF APIs and their usage. Error Handling Most ESP-IDF APIs return error codes defined with the esp_err_t type. See Error Handling section for more information about error handling approaches. Error Codes Reference contains the list of error codes returned by ESP-IDF components. Configuration Structures Important Correct initialization of configuration structures is an important part of making the application compatible with future versions of ESP-IDF. Most initialization, configuration, and installation functions in ESP-IDF (typically named ..._init(), ..._config(), and ..._install()) take a configuration structure pointer as an argument. For example: const esp_timer_create_args_t my_timer_args = { .callback = &my_timer_callback, .arg = callback_arg, .name = "my_timer" }; esp_timer_handle_t my_timer; esp_err_t err = esp_timer_create(&my_timer_args, &my_timer); These functions never store the pointer to the configuration structure, so it is safe to allocate the structure on the stack. The application must initialize all fields of the structure. The following is incorrect: esp_timer_create_args_t my_timer_args; my_timer_args.callback = &my_timer_callback; /* Incorrect! Fields .arg and .name are not initialized */ esp_timer_create(&my_timer_args, &my_timer); Most ESP-IDF examples use C99 designated initializers for structure initialization since they provide a concise way of setting a subset of fields, and zero-initializing the remaining fields: const esp_timer_create_args_t my_timer_args = { .callback = &my_timer_callback, /* Correct, fields .arg and .name are zero-initialized */ }; The C++ language supports designated initializer syntax, too, but the initializers must be in the order of declaration. When using ESP-IDF APIs in C++ code, you may consider using the following pattern: /* Correct, fields .dispatch_method, .name and .skip_unhandled_events are zero-initialized */ const esp_timer_create_args_t my_timer_args = { .callback = &my_timer_callback, .arg = &my_arg, }; ///* Incorrect, .arg is declared after .callback in esp_timer_create_args_t */ //const esp_timer_create_args_t my_timer_args = { // .arg = &my_arg, // .callback = &my_timer_callback, //}; For more information on designated initializers, see Designated Initializers. Note that C++ language versions older than C++20, which are not the default in the current version of ESP-IDF, do not support designated initializers. If you have to compile code with an older C++ standard than C++20, you may use GCC extensions to produce the following pattern: esp_timer_create_args_t my_timer_args = {}; /* All the fields are zero-initialized */ my_timer_args.callback = &my_timer_callback; Default Initializers For some configuration structures, ESP-IDF provides macros for setting default values of fields: httpd_config_t config = HTTPD_DEFAULT_CONFIG(); /* HTTPD_DEFAULT_CONFIG expands to a designated initializer. Now all fields are set to the default values, and any field can still be modified: */ config.server_port = 8081; httpd_handle_t server; esp_err_t err = httpd_start(&server, &config); It is recommended to use default initializer macros whenever they are provided for a particular configuration structure. Private APIs Certain header files in ESP-IDF contain APIs intended to be used only in ESP-IDF source code rather than by the applications. Such header files often contain private or esp_private in their name or path. Certain components, such as hal only contain private APIs. Private APIs may be removed or changed in an incompatible way between minor or patch releases. Components in Example Projects ESP-IDF examples contain a variety of projects demonstrating the usage of ESP-IDF APIs. In order to reduce code duplication in the examples, a few common helpers are defined inside components that are used by multiple examples. This includes components located in common_components directory, as well as some of the components located in the examples themselves. These components are not considered to be part of the ESP-IDF API. It is not recommended to reference these components directly in custom projects (via EXTRA_COMPONENT_DIRS build system variable), as they may change significantly between ESP-IDF versions. When starting a new project based on an ESP-IDF example, copy both the project and the common components it depends on out of ESP-IDF, and treat the common components as part of the project. Note that the common components are written with examples in mind, and might not include all the error handling required for production applications. Before using, take time to read the code and understand if it is applicable to your use case. API Stability ESP-IDF uses Semantic Versioning as explained in the Versioning Scheme. Minor and bugfix releases of ESP-IDF guarantee compatibility with previous releases. The sections below explain different aspects and limitations to compatibility. Source-level Compatibility ESP-IDF guarantees source-level compatibility of C functions, structures, enums, type definitions, and preprocessor macros declared in public header files of ESP-IDF components. Source-level compatibility implies that the application source code can be recompiled with the newer version of ESP-IDF without changes. The following changes are allowed between minor versions and do not break source-level compatibility: Deprecating functions (using the deprecatedattribute) and header files (using a preprocessor #warning). Deprecations are listed in ESP-IDF release notes. It is recommended to update the source code to use the newer functions or files that replace the deprecated ones, however, this is not mandatory. Deprecated functions and files can be removed from major versions of ESP-IDF. Renaming components, moving source and header files between components — provided that the build system ensures that correct files are still found. Renaming Kconfig options. Kconfig system's backward compatibility ensures that the original Kconfig option names can still be used by the application in sdkconfigfile, CMake files, and source code. Lack of Binary Compatibility ESP-IDF does not guarantee binary compatibility between releases. This means that if a precompiled library is built with one ESP-IDF version, it is not guaranteed to work the same way with the next minor or bugfix release. The following are the possible changes that keep source-level compatibility but not binary compatibility: Changing numerical values for C enum members. Adding new structure members or changing the order of members. See Configuration Structures for tips that help ensure compatibility. Replacing an externfunction with a static inlineone with the same signature, or vice versa. Replacing a function-like macro with a compatible C function. Other Exceptions from Compatibility While we try to make upgrading to a new ESP-IDF version easy, there are parts of ESP-IDF that may change between minor versions in an incompatible way. We appreciate issuing reports about any unintended breaking changes that do not fall into the categories below. Features clearly marked as "beta", "preview", or "experimental". Changes made to mitigate security issues or to replace insecure default behaviors with secure ones. Features that were never functional. For example, if it was never possible to use a certain function or an enumeration value, it may get renamed (as part of fixing it) or removed. This includes software features that depend on non-functional chip hardware features. Unexpected or undefined behavior that is not documented explicitly may be fixed/changed, such as due to missing validation of argument ranges. Location of Kconfig options in menuconfig. Location and names of example projects.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/api-conventions.html
ESP-IDF Programming Guide v5.2.1 documentation
null
ESP-MQTT
null
espressif.com
2016-01-01
6e59fd1e6a0bfa18
null
null
ESP-MQTT Overview ESP-MQTT is an implementation of MQTT protocol client, which is a lightweight publish/subscribe messaging protocol. Now ESP-MQTT supports MQTT v5.0. Features Support MQTT over TCP, SSL with Mbed TLS, MQTT over WebSocket, and MQTT over WebSocket Secure Easy to setup with URI Multiple instances (multiple clients in one application) Support subscribing, publishing, authentication, last will messages, keep alive pings, and all 3 Quality of Service (QoS) levels (it should be a fully functional client) Application Examples protocols/mqtt/tcp: MQTT over TCP, default port 1883 protocols/mqtt/ssl: MQTT over TLS, default port 8883 protocols/mqtt/ssl_ds: MQTT over TLS using digital signature peripheral for authentication, default port 8883 protocols/mqtt/ssl_mutual_auth: MQTT over TLS using certificates for authentication, default port 8883 protocols/mqtt/ssl_psk: MQTT over TLS using pre-shared keys for authentication, default port 8883 protocols/mqtt/ws: MQTT over WebSocket, default port 80 protocols/mqtt/wss: MQTT over WebSocket Secure, default port 443 protocols/mqtt5: Uses ESP-MQTT library to connect to broker with MQTT v5.0 MQTT Message Retransmission A new MQTT message is created by calling esp_mqtt_client_publish or its non blocking counterpart esp_mqtt_client_enqueue . Messages with QoS 0 is sent only once. QoS 1 and 2 have different behaviors since the protocol requires extra steps to complete the process. The ESP-MQTT library opts to always retransmit unacknowledged QoS 1 and 2 publish messages to avoid losses in faulty connections, even though the MQTT specification requires the re-transmission only on reconnect with Clean Session flag been set to 0 (set disable_clean_session to true for this behavior). QoS 1 and 2 messages that may need retransmission are always enqueued, but first transmission try occurs immediately if esp_mqtt_client_publish is used. A transmission retry for unacknowledged messages will occur after message_retransmit_timeout . After CONFIG_MQTT_OUTBOX_EXPIRED_TIMEOUT_MS messages will expire and be deleted. If CONFIG_MQTT_REPORT_DELETED_MESSAGES is set, an event will be sent to notify the user. Configuration The configuration is made by setting fields in esp_mqtt_client_config_t struct. The configuration struct has the following sub structs to configure different aspects of the client operation. esp_mqtt_client_config_t::broker_t - Allow to set address and security verification. esp_mqtt_client_config_t::credentials_t - Client credentials for authentication. esp_mqtt_client_config_t::session_t - Configuration for MQTT session aspects. esp_mqtt_client_config_t::network_t - Networking related configuration. esp_mqtt_client_config_t::task_t - Allow to configure FreeRTOS task. esp_mqtt_client_config_t::buffer_t - Buffer size for input and output. In the following sections, the most common aspects are detailed. Broker Address Broker address can be set by usage of address struct. The configuration can be made by usage of uri field or the combination of hostname , transport and port . Optionally, path could be set, this field is useful in WebSocket connections. The uri field is used in the format scheme://hostname:port/path . Curently support mqtt , mqtts , ws , wss schemes MQTT over TCP samples: mqtt://mqtt.eclipseprojects.io : MQTT over TCP, default port 1883 mqtt://mqtt.eclipseprojects.io:1884 : MQTT over TCP, port 1884 mqtt://username:password@mqtt.eclipseprojects.io:1884 : MQTT over TCP, port 1884, with username and password mqtt://mqtt.eclipseprojects.io : MQTT over TCP, default port 1883 mqtt://mqtt.eclipseprojects.io:1884 : MQTT over TCP, port 1884 mqtt://username:password@mqtt.eclipseprojects.io:1884 : MQTT over TCP, port 1884, with username and password mqtt://mqtt.eclipseprojects.io : MQTT over TCP, default port 1883 MQTT over SSL samples: mqtts://mqtt.eclipseprojects.io : MQTT over SSL, port 8883 mqtts://mqtt.eclipseprojects.io:8884 : MQTT over SSL, port 8884 mqtts://mqtt.eclipseprojects.io : MQTT over SSL, port 8883 mqtts://mqtt.eclipseprojects.io:8884 : MQTT over SSL, port 8884 mqtts://mqtt.eclipseprojects.io : MQTT over SSL, port 8883 MQTT over WebSocket samples: ws://mqtt.eclipseprojects.io:80/mqtt ws://mqtt.eclipseprojects.io:80/mqtt ws://mqtt.eclipseprojects.io:80/mqtt MQTT over WebSocket Secure samples: wss://mqtt.eclipseprojects.io:443/mqtt wss://mqtt.eclipseprojects.io:443/mqtt wss://mqtt.eclipseprojects.io:443/mqtt Minimal configurations: const esp_mqtt_client_config_t mqtt_cfg = { .broker.address.uri = "mqtt://mqtt.eclipseprojects.io", }; esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg); esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client); esp_mqtt_client_start(client); Note By default MQTT client uses event loop library to post related MQTT events (connected, subscribed, published, etc.). Verification For secure connections with TLS used, and to guarantee Broker's identity, the verification struct must be set. The broker certificate may be set in PEM or DER format. To select DER, the equivalent certificate_len field must be set. Otherwise, a null-terminated string in PEM format should be provided to certificate field. Get certificate from server, example: mqtt.eclipseprojects.io openssl s_client -showcerts -connect mqtt.eclipseprojects.io:8883 < /dev/null \ 2> /dev/null | openssl x509 -outform PEM > mqtt_eclipse_org.pem Get certificate from server, example: mqtt.eclipseprojects.io openssl s_client -showcerts -connect mqtt.eclipseprojects.io:8883 < /dev/null \ 2> /dev/null | openssl x509 -outform PEM > mqtt_eclipse_org.pem Get certificate from server, example: mqtt.eclipseprojects.io Check the sample application: protocols/mqtt/ssl Configuration: const esp_mqtt_client_config_t mqtt_cfg = { .broker = { .address.uri = "mqtts://mqtt.eclipseprojects.io:8883", .verification.certificate = (const char *)mqtt_eclipse_org_pem_start, }, }; For details about other fields, please check the API Reference and TLS Server Verification. Client Credentials All client related credentials are under the credentials field. Authentication It is possible to set authentication parameters through the authentication field. The client supports the following authentication methods: password : use a password by setting certificate and key : mutual authentication with TLS, and both can be provided in PEM or DER format use_secure_element : use secure element available in ESP32-WROOM-32SE ds_data : use Digital Signature Peripheral available in some Espressif devices Session For MQTT session related configurations, session fields should be used. Last Will and Testament MQTT allows for a last will and testament (LWT) message to notify other clients when a client ungracefully disconnects. This is configured by the following fields in the last_will struct. Events The following events may be posted by the MQTT client: MQTT_EVENT_BEFORE_CONNECT : The client is initialized and about to start connecting to the broker. MQTT_EVENT_CONNECTED : The client has successfully established a connection to the broker. The client is now ready to send and receive data. MQTT_EVENT_DISCONNECTED : The client has aborted the connection due to being unable to read or write data, e.g., because the server is unavailable. MQTT_EVENT_SUBSCRIBED : The broker has acknowledged the client's subscribe request. The event data contains the message ID of the subscribe message. MQTT_EVENT_UNSUBSCRIBED : The broker has acknowledged the client's unsubscribe request. The event data contains the message ID of the unsubscribe message. MQTT_EVENT_PUBLISHED : The broker has acknowledged the client's publish message. This is only posted for QoS level 1 and 2, as level 0 does not use acknowledgements. The event data contains the message ID of the publish message. MQTT_EVENT_DATA : The client has received a publish message. The event data contains: message ID, name of the topic it was published to, received data and its length. For data that exceeds the internal buffer, multiple MQTT_EVENT_DATA events are posted and current_data_offset and total_data_len from event data updated to keep track of the fragmented message. MQTT_EVENT_ERROR : The client has encountered an error. The field error_handle in the event data contains error_type that can be used to identify the error. The type of error determines which parts of the error_handle struct is filled. API Reference Header File This header file can be included with: #include "mqtt_client.h" This header file is a part of the API provided by the mqtt component. To declare that your component depends on mqtt , add the following to your CMakeLists.txt: REQUIRES mqtt or PRIV_REQUIRES mqtt Functions esp_mqtt_client_handle_t esp_mqtt_client_init(const esp_mqtt_client_config_t *config) Creates MQTT client handle based on the configuration. Parameters config -- MQTT configuration structure Returns mqtt_client_handle if successfully created, NULL on error Parameters config -- MQTT configuration structure Returns mqtt_client_handle if successfully created, NULL on error esp_err_t esp_mqtt_client_set_uri(esp_mqtt_client_handle_t client, const char *uri) Sets MQTT connection URI. This API is usually used to overrides the URI configured in esp_mqtt_client_init. Parameters client -- MQTT client handle uri -- client -- MQTT client handle uri -- client -- MQTT client handle Returns ESP_FAIL if URI parse error, ESP_OK on success Parameters client -- MQTT client handle uri -- Returns ESP_FAIL if URI parse error, ESP_OK on success esp_err_t esp_mqtt_client_start(esp_mqtt_client_handle_t client) Starts MQTT client with already created client handle. Parameters client -- MQTT client handle Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization ESP_FAIL on other error Parameters client -- MQTT client handle Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization ESP_FAIL on other error esp_err_t esp_mqtt_client_reconnect(esp_mqtt_client_handle_t client) This api is typically used to force reconnection upon a specific event. Parameters client -- MQTT client handle Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization ESP_FAIL if client is in invalid state Parameters client -- MQTT client handle Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization ESP_FAIL if client is in invalid state esp_err_t esp_mqtt_client_disconnect(esp_mqtt_client_handle_t client) This api is typically used to force disconnection from the broker. Parameters client -- MQTT client handle Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization Parameters client -- MQTT client handle Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization esp_err_t esp_mqtt_client_stop(esp_mqtt_client_handle_t client) Stops MQTT client tasks. Notes: Cannot be called from the MQTT event handler Notes: Cannot be called from the MQTT event handler Parameters client -- MQTT client handle Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization ESP_FAIL if client is in invalid state Parameters client -- MQTT client handle Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization ESP_FAIL if client is in invalid state Notes: int esp_mqtt_client_subscribe_single(esp_mqtt_client_handle_t client, const char *topic, int qos) Subscribe the client to defined topic with defined qos. Notes: Client must be connected to send subscribe message This API is could be executed from a user task or from a MQTT event callback i.e. internal MQTT task (API is protected by internal mutex, so it might block if a longer data receive operation is in progress. esp_mqtt_client_subscribe could be used to call this function. Client must be connected to send subscribe message This API is could be executed from a user task or from a MQTT event callback i.e. internal MQTT task (API is protected by internal mutex, so it might block if a longer data receive operation is in progress. esp_mqtt_client_subscribe could be used to call this function. Parameters client -- MQTT client handle topic -- topic filter to subscribe qos -- Max qos level of the subscription client -- MQTT client handle topic -- topic filter to subscribe qos -- Max qos level of the subscription client -- MQTT client handle Returns message_id of the subscribe message on success -1 on failure -2 in case of full outbox. Parameters client -- MQTT client handle topic -- topic filter to subscribe qos -- Max qos level of the subscription Returns message_id of the subscribe message on success -1 on failure -2 in case of full outbox. Client must be connected to send subscribe message int esp_mqtt_client_subscribe_multiple(esp_mqtt_client_handle_t client, const esp_mqtt_topic_t *topic_list, int size) Subscribe the client to a list of defined topics with defined qos. Notes: Client must be connected to send subscribe message This API is could be executed from a user task or from a MQTT event callback i.e. internal MQTT task (API is protected by internal mutex, so it might block if a longer data receive operation is in progress. esp_mqtt_client_subscribe could be used to call this function. Client must be connected to send subscribe message This API is could be executed from a user task or from a MQTT event callback i.e. internal MQTT task (API is protected by internal mutex, so it might block if a longer data receive operation is in progress. esp_mqtt_client_subscribe could be used to call this function. Parameters client -- MQTT client handle topic_list -- List of topics to subscribe size -- size of topic_list client -- MQTT client handle topic_list -- List of topics to subscribe size -- size of topic_list client -- MQTT client handle Returns message_id of the subscribe message on success -1 on failure -2 in case of full outbox. Parameters client -- MQTT client handle topic_list -- List of topics to subscribe size -- size of topic_list Returns message_id of the subscribe message on success -1 on failure -2 in case of full outbox. Client must be connected to send subscribe message int esp_mqtt_client_unsubscribe(esp_mqtt_client_handle_t client, const char *topic) Unsubscribe the client from defined topic. Notes: Client must be connected to send unsubscribe message It is thread safe, please refer to esp_mqtt_client_subscribe_single for details Client must be connected to send unsubscribe message It is thread safe, please refer to esp_mqtt_client_subscribe_single for details Parameters client -- MQTT client handle topic -- client -- MQTT client handle topic -- client -- MQTT client handle Returns message_id of the subscribe message on success -1 on failure Parameters client -- MQTT client handle topic -- Returns message_id of the subscribe message on success -1 on failure Client must be connected to send unsubscribe message int esp_mqtt_client_publish(esp_mqtt_client_handle_t client, const char *topic, const char *data, int len, int qos, int retain) Client to send a publish message to the broker. Notes: This API might block for several seconds, either due to network timeout (10s) or if publishing payloads longer than internal buffer (due to message fragmentation) Client doesn't have to be connected for this API to work, enqueueing the messages with qos>1 (returning -1 for all the qos=0 messages if disconnected). If MQTT_SKIP_PUBLISH_IF_DISCONNECTED is enabled, this API will not attempt to publish when the client is not connected and will always return -1. It is thread safe, please refer to esp_mqtt_client_subscribe for details This API might block for several seconds, either due to network timeout (10s) or if publishing payloads longer than internal buffer (due to message fragmentation) Client doesn't have to be connected for this API to work, enqueueing the messages with qos>1 (returning -1 for all the qos=0 messages if disconnected). If MQTT_SKIP_PUBLISH_IF_DISCONNECTED is enabled, this API will not attempt to publish when the client is not connected and will always return -1. It is thread safe, please refer to esp_mqtt_client_subscribe for details Parameters client -- MQTT client handle topic -- topic string data -- payload string (set to NULL, sending empty payload message) len -- data length, if set to 0, length is calculated from payload string qos -- QoS of publish message retain -- retain flag client -- MQTT client handle topic -- topic string data -- payload string (set to NULL, sending empty payload message) len -- data length, if set to 0, length is calculated from payload string qos -- QoS of publish message retain -- retain flag client -- MQTT client handle Returns message_id of the publish message (for QoS 0 message_id will always be zero) on success. -1 on failure, -2 in case of full outbox. Parameters client -- MQTT client handle topic -- topic string data -- payload string (set to NULL, sending empty payload message) len -- data length, if set to 0, length is calculated from payload string qos -- QoS of publish message retain -- retain flag Returns message_id of the publish message (for QoS 0 message_id will always be zero) on success. -1 on failure, -2 in case of full outbox. This API might block for several seconds, either due to network timeout (10s) or if publishing payloads longer than internal buffer (due to message fragmentation) int esp_mqtt_client_enqueue(esp_mqtt_client_handle_t client, const char *topic, const char *data, int len, int qos, int retain, bool store) Enqueue a message to the outbox, to be sent later. Typically used for messages with qos>0, but could be also used for qos=0 messages if store=true. This API generates and stores the publish message into the internal outbox and the actual sending to the network is performed in the mqtt-task context (in contrast to the esp_mqtt_client_publish() which sends the publish message immediately in the user task's context). Thus, it could be used as a non blocking version of esp_mqtt_client_publish(). Parameters client -- MQTT client handle topic -- topic string data -- payload string (set to NULL, sending empty payload message) len -- data length, if set to 0, length is calculated from payload string qos -- QoS of publish message retain -- retain flag store -- if true, all messages are enqueued; otherwise only QoS 1 and QoS 2 are enqueued client -- MQTT client handle topic -- topic string data -- payload string (set to NULL, sending empty payload message) len -- data length, if set to 0, length is calculated from payload string qos -- QoS of publish message retain -- retain flag store -- if true, all messages are enqueued; otherwise only QoS 1 and QoS 2 are enqueued client -- MQTT client handle Returns message_id if queued successfully, -1 on failure, -2 in case of full outbox. Parameters client -- MQTT client handle topic -- topic string data -- payload string (set to NULL, sending empty payload message) len -- data length, if set to 0, length is calculated from payload string qos -- QoS of publish message retain -- retain flag store -- if true, all messages are enqueued; otherwise only QoS 1 and QoS 2 are enqueued Returns message_id if queued successfully, -1 on failure, -2 in case of full outbox. esp_err_t esp_mqtt_client_destroy(esp_mqtt_client_handle_t client) Destroys the client handle. Notes: Cannot be called from the MQTT event handler Cannot be called from the MQTT event handler Parameters client -- MQTT client handle Returns ESP_OK ESP_ERR_INVALID_ARG on wrong initialization Parameters client -- MQTT client handle Returns ESP_OK ESP_ERR_INVALID_ARG on wrong initialization Cannot be called from the MQTT event handler esp_err_t esp_mqtt_set_config(esp_mqtt_client_handle_t client, const esp_mqtt_client_config_t *config) Set configuration structure, typically used when updating the config (i.e. on "before_connect" event. Parameters client -- MQTT client handle config -- MQTT configuration structure client -- MQTT client handle config -- MQTT configuration structure client -- MQTT client handle Returns ESP_ERR_NO_MEM if failed to allocate ESP_ERR_INVALID_ARG if conflicts on transport configuration. ESP_OK on success Parameters client -- MQTT client handle config -- MQTT configuration structure Returns ESP_ERR_NO_MEM if failed to allocate ESP_ERR_INVALID_ARG if conflicts on transport configuration. ESP_OK on success esp_err_t esp_mqtt_client_register_event(esp_mqtt_client_handle_t client, esp_mqtt_event_id_t event, esp_event_handler_t event_handler, void *event_handler_arg) Registers MQTT event. Parameters client -- MQTT client handle event -- event type event_handler -- handler callback event_handler_arg -- handlers context client -- MQTT client handle event -- event type event_handler -- handler callback event_handler_arg -- handlers context client -- MQTT client handle Returns ESP_ERR_NO_MEM if failed to allocate ESP_ERR_INVALID_ARG on wrong initialization ESP_OK on success Parameters client -- MQTT client handle event -- event type event_handler -- handler callback event_handler_arg -- handlers context Returns ESP_ERR_NO_MEM if failed to allocate ESP_ERR_INVALID_ARG on wrong initialization ESP_OK on success esp_err_t esp_mqtt_client_unregister_event(esp_mqtt_client_handle_t client, esp_mqtt_event_id_t event, esp_event_handler_t event_handler) Unregisters mqtt event. Parameters client -- mqtt client handle event -- event ID event_handler -- handler to unregister client -- mqtt client handle event -- event ID event_handler -- handler to unregister client -- mqtt client handle Returns ESP_ERR_NO_MEM if failed to allocate ESP_ERR_INVALID_ARG on invalid event ID ESP_OK on success Parameters client -- mqtt client handle event -- event ID event_handler -- handler to unregister Returns ESP_ERR_NO_MEM if failed to allocate ESP_ERR_INVALID_ARG on invalid event ID ESP_OK on success int esp_mqtt_client_get_outbox_size(esp_mqtt_client_handle_t client) Get outbox size. Parameters client -- MQTT client handle Returns outbox size 0 on wrong initialization Parameters client -- MQTT client handle Returns outbox size 0 on wrong initialization esp_err_t esp_mqtt_dispatch_custom_event(esp_mqtt_client_handle_t client, esp_mqtt_event_t *event) Dispatch user event to the mqtt internal event loop. Parameters client -- MQTT client handle event -- MQTT event handle structure client -- MQTT client handle event -- MQTT event handle structure client -- MQTT client handle Returns ESP_OK on success ESP_ERR_TIMEOUT if the event couldn't be queued (ref also CONFIG_MQTT_EVENT_QUEUE_SIZE) Parameters client -- MQTT client handle event -- MQTT event handle structure Returns ESP_OK on success ESP_ERR_TIMEOUT if the event couldn't be queued (ref also CONFIG_MQTT_EVENT_QUEUE_SIZE) Structures struct esp_mqtt_error_codes MQTT error code structure to be passed as a contextual information into ERROR event Important: This structure extends esp_tls_last_error error structure and is backward compatible with it (so might be down-casted and treated as esp_tls_last_error error, but recommended to update applications if used this way previously) Use this structure directly checking error_type first and then appropriate error code depending on the source of the error: | error_type | related member variables | note | | MQTT_ERROR_TYPE_TCP_TRANSPORT | esp_tls_last_esp_err, esp_tls_stack_err, esp_tls_cert_verify_flags, sock_errno | Error reported from tcp_transport/esp-tls | | MQTT_ERROR_TYPE_CONNECTION_REFUSED | connect_return_code | Internal error reported from MQTT broker on connection | Public Members int esp_tls_stack_err tls specific error code reported from underlying tls stack int esp_tls_stack_err tls specific error code reported from underlying tls stack int esp_tls_cert_verify_flags tls flags reported from underlying tls stack during certificate verification int esp_tls_cert_verify_flags tls flags reported from underlying tls stack during certificate verification esp_mqtt_error_type_t error_type error type referring to the source of the error esp_mqtt_error_type_t error_type error type referring to the source of the error esp_mqtt_connect_return_code_t connect_return_code connection refused error code reported from MQTT* broker on connection esp_mqtt_connect_return_code_t connect_return_code connection refused error code reported from MQTT* broker on connection int esp_transport_sock_errno errno from the underlying socket int esp_transport_sock_errno errno from the underlying socket int esp_tls_stack_err struct esp_mqtt_event_t MQTT event configuration structure Public Members esp_mqtt_event_id_t event_id MQTT event type esp_mqtt_event_id_t event_id MQTT event type esp_mqtt_client_handle_t client MQTT client handle for this event esp_mqtt_client_handle_t client MQTT client handle for this event char *data Data associated with this event char *data Data associated with this event int data_len Length of the data for this event int data_len Length of the data for this event int total_data_len Total length of the data (longer data are supplied with multiple events) int total_data_len Total length of the data (longer data are supplied with multiple events) int current_data_offset Actual offset for the data associated with this event int current_data_offset Actual offset for the data associated with this event char *topic Topic associated with this event char *topic Topic associated with this event int topic_len Length of the topic for this event associated with this event int topic_len Length of the topic for this event associated with this event int msg_id MQTT messaged id of message int msg_id MQTT messaged id of message int session_present MQTT session_present flag for connection event int session_present MQTT session_present flag for connection event esp_mqtt_error_codes_t *error_handle esp-mqtt error handle including esp-tls errors as well as internal MQTT errors esp_mqtt_error_codes_t *error_handle esp-mqtt error handle including esp-tls errors as well as internal MQTT errors bool retain Retained flag of the message associated with this event bool retain Retained flag of the message associated with this event int qos QoS of the messages associated with this event int qos QoS of the messages associated with this event bool dup dup flag of the message associated with this event bool dup dup flag of the message associated with this event esp_mqtt_protocol_ver_t protocol_ver MQTT protocol version used for connection, defaults to value from menuconfig esp_mqtt_protocol_ver_t protocol_ver MQTT protocol version used for connection, defaults to value from menuconfig esp_mqtt_event_id_t event_id struct esp_mqtt_client_config_t MQTT client configuration structure Default values can be set via menuconfig All certificates and key data could be passed in PEM or DER format. PEM format must have a terminating NULL character and the related len field set to 0. DER format requires a related len field set to the correct length. Default values can be set via menuconfig All certificates and key data could be passed in PEM or DER format. PEM format must have a terminating NULL character and the related len field set to 0. DER format requires a related len field set to the correct length. Public Members struct esp_mqtt_client_config_t::broker_t broker Broker address and security verification struct esp_mqtt_client_config_t::broker_t broker Broker address and security verification struct esp_mqtt_client_config_t::credentials_t credentials User credentials for broker struct esp_mqtt_client_config_t::credentials_t credentials User credentials for broker struct esp_mqtt_client_config_t::session_t session MQTT session configuration. struct esp_mqtt_client_config_t::session_t session MQTT session configuration. struct esp_mqtt_client_config_t::network_t network Network configuration struct esp_mqtt_client_config_t::network_t network Network configuration struct esp_mqtt_client_config_t::task_t task FreeRTOS task configuration. struct esp_mqtt_client_config_t::task_t task FreeRTOS task configuration. struct esp_mqtt_client_config_t::buffer_t buffer Buffer size configuration. struct esp_mqtt_client_config_t::buffer_t buffer Buffer size configuration. struct esp_mqtt_client_config_t::outbox_config_t outbox Outbox configuration. struct esp_mqtt_client_config_t::outbox_config_t outbox Outbox configuration. struct broker_t Broker related configuration Public Members struct esp_mqtt_client_config_t::broker_t::address_t address Broker address configuration struct esp_mqtt_client_config_t::broker_t::address_t address Broker address configuration struct esp_mqtt_client_config_t::broker_t::verification_t verification Security verification of the broker struct esp_mqtt_client_config_t::broker_t::verification_t verification Security verification of the broker struct address_t Broker address uri have precedence over other fields If uri isn't set at least hostname, transport and port should. uri have precedence over other fields If uri isn't set at least hostname, transport and port should. uri have precedence over other fields struct address_t Broker address uri have precedence over other fields If uri isn't set at least hostname, transport and port should. struct verification_t Broker identity verification If fields are not set broker's identity isn't verified. it's recommended to set the options in this struct for security reasons. Public Members bool use_global_ca_store Use a global ca_store, look esp-tls documentation for details. bool use_global_ca_store Use a global ca_store, look esp-tls documentation for details. esp_err_t (*crt_bundle_attach)(void *conf) Pointer to ESP x509 Certificate Bundle attach function for the usage of certificate bundles. esp_err_t (*crt_bundle_attach)(void *conf) Pointer to ESP x509 Certificate Bundle attach function for the usage of certificate bundles. const char *certificate Certificate data, default is NULL, not required to verify the server. const char *certificate Certificate data, default is NULL, not required to verify the server. size_t certificate_len Length of the buffer pointed to by certificate. size_t certificate_len Length of the buffer pointed to by certificate. const struct psk_key_hint *psk_hint_key Pointer to PSK struct defined in esp_tls.h to enable PSK authentication (as alternative to certificate verification). PSK is enabled only if there are no other ways to verify broker. const struct psk_key_hint *psk_hint_key Pointer to PSK struct defined in esp_tls.h to enable PSK authentication (as alternative to certificate verification). PSK is enabled only if there are no other ways to verify broker. bool skip_cert_common_name_check Skip any validation of server certificate CN field, this reduces the security of TLS and makes the MQTT client susceptible to MITM attacks bool skip_cert_common_name_check Skip any validation of server certificate CN field, this reduces the security of TLS and makes the MQTT client susceptible to MITM attacks const char **alpn_protos NULL-terminated list of supported application protocols to be used for ALPN const char **alpn_protos NULL-terminated list of supported application protocols to be used for ALPN const char *common_name Pointer to the string containing server certificate common name. If non-NULL, server certificate CN must match this name, If NULL, server certificate CN must match hostname. This is ignored if skip_cert_common_name_check=true. const char *common_name Pointer to the string containing server certificate common name. If non-NULL, server certificate CN must match this name, If NULL, server certificate CN must match hostname. This is ignored if skip_cert_common_name_check=true. bool use_global_ca_store struct verification_t Broker identity verification If fields are not set broker's identity isn't verified. it's recommended to set the options in this struct for security reasons. Public Members bool use_global_ca_store Use a global ca_store, look esp-tls documentation for details. esp_err_t (*crt_bundle_attach)(void *conf) Pointer to ESP x509 Certificate Bundle attach function for the usage of certificate bundles. const char *certificate Certificate data, default is NULL, not required to verify the server. size_t certificate_len Length of the buffer pointed to by certificate. const struct psk_key_hint *psk_hint_key Pointer to PSK struct defined in esp_tls.h to enable PSK authentication (as alternative to certificate verification). PSK is enabled only if there are no other ways to verify broker. bool skip_cert_common_name_check Skip any validation of server certificate CN field, this reduces the security of TLS and makes the MQTT client susceptible to MITM attacks const char **alpn_protos NULL-terminated list of supported application protocols to be used for ALPN const char *common_name Pointer to the string containing server certificate common name. If non-NULL, server certificate CN must match this name, If NULL, server certificate CN must match hostname. This is ignored if skip_cert_common_name_check=true. struct esp_mqtt_client_config_t::broker_t::address_t address struct broker_t Broker related configuration Public Members struct esp_mqtt_client_config_t::broker_t::address_t address Broker address configuration struct esp_mqtt_client_config_t::broker_t::verification_t verification Security verification of the broker struct address_t Broker address uri have precedence over other fields If uri isn't set at least hostname, transport and port should. struct verification_t Broker identity verification If fields are not set broker's identity isn't verified. it's recommended to set the options in this struct for security reasons. Public Members bool use_global_ca_store Use a global ca_store, look esp-tls documentation for details. esp_err_t (*crt_bundle_attach)(void *conf) Pointer to ESP x509 Certificate Bundle attach function for the usage of certificate bundles. const char *certificate Certificate data, default is NULL, not required to verify the server. size_t certificate_len Length of the buffer pointed to by certificate. const struct psk_key_hint *psk_hint_key Pointer to PSK struct defined in esp_tls.h to enable PSK authentication (as alternative to certificate verification). PSK is enabled only if there are no other ways to verify broker. bool skip_cert_common_name_check Skip any validation of server certificate CN field, this reduces the security of TLS and makes the MQTT client susceptible to MITM attacks const char **alpn_protos NULL-terminated list of supported application protocols to be used for ALPN const char *common_name Pointer to the string containing server certificate common name. If non-NULL, server certificate CN must match this name, If NULL, server certificate CN must match hostname. This is ignored if skip_cert_common_name_check=true. struct buffer_t Client buffer size configuration Client have two buffers for input and output respectivelly. struct buffer_t Client buffer size configuration Client have two buffers for input and output respectivelly. struct credentials_t Client related credentials for authentication. Public Members const char *username MQTT username const char *username MQTT username const char *client_id Set MQTT client identifier. Ignored if set_null_client_id == true If NULL set the default client id. Default client id is ESP32_CHIPID% where CHIPID% are last 3 bytes of MAC address in hex format const char *client_id Set MQTT client identifier. Ignored if set_null_client_id == true If NULL set the default client id. Default client id is ESP32_CHIPID% where CHIPID% are last 3 bytes of MAC address in hex format bool set_null_client_id Selects a NULL client id bool set_null_client_id Selects a NULL client id struct esp_mqtt_client_config_t::credentials_t::authentication_t authentication Client authentication struct esp_mqtt_client_config_t::credentials_t::authentication_t authentication Client authentication struct authentication_t Client authentication Fields related to client authentication by broker For mutual authentication using TLS, user could select certificate and key, secure element or digital signature peripheral if available. Public Members const char *password MQTT password const char *password MQTT password const char *certificate Certificate for ssl mutual authentication, not required if mutual authentication is not needed. Must be provided with key . const char *certificate Certificate for ssl mutual authentication, not required if mutual authentication is not needed. Must be provided with key . size_t certificate_len Length of the buffer pointed to by certificate. size_t certificate_len Length of the buffer pointed to by certificate. const char *key Private key for SSL mutual authentication, not required if mutual authentication is not needed. If it is not NULL, also certificate has to be provided. const char *key Private key for SSL mutual authentication, not required if mutual authentication is not needed. If it is not NULL, also certificate has to be provided. size_t key_len Length of the buffer pointed to by key. size_t key_len Length of the buffer pointed to by key. const char *key_password Client key decryption password, not PEM nor DER, if provided key_password_len must be correctly set. const char *key_password Client key decryption password, not PEM nor DER, if provided key_password_len must be correctly set. int key_password_len Length of the password pointed to by key_password int key_password_len Length of the password pointed to by key_password bool use_secure_element Enable secure element, available in ESP32-ROOM-32SE, for SSL connection bool use_secure_element Enable secure element, available in ESP32-ROOM-32SE, for SSL connection void *ds_data Carrier of handle for digital signature parameters, digital signature peripheral is available in some Espressif devices. void *ds_data Carrier of handle for digital signature parameters, digital signature peripheral is available in some Espressif devices. const char *password struct authentication_t Client authentication Fields related to client authentication by broker For mutual authentication using TLS, user could select certificate and key, secure element or digital signature peripheral if available. Public Members const char *password MQTT password const char *certificate Certificate for ssl mutual authentication, not required if mutual authentication is not needed. Must be provided with key . size_t certificate_len Length of the buffer pointed to by certificate. const char *key Private key for SSL mutual authentication, not required if mutual authentication is not needed. If it is not NULL, also certificate has to be provided. size_t key_len Length of the buffer pointed to by key. const char *key_password Client key decryption password, not PEM nor DER, if provided key_password_len must be correctly set. int key_password_len Length of the password pointed to by key_password bool use_secure_element Enable secure element, available in ESP32-ROOM-32SE, for SSL connection void *ds_data Carrier of handle for digital signature parameters, digital signature peripheral is available in some Espressif devices. const char *username struct credentials_t Client related credentials for authentication. Public Members const char *username MQTT username const char *client_id Set MQTT client identifier. Ignored if set_null_client_id == true If NULL set the default client id. Default client id is ESP32_CHIPID% where CHIPID% are last 3 bytes of MAC address in hex format bool set_null_client_id Selects a NULL client id struct esp_mqtt_client_config_t::credentials_t::authentication_t authentication Client authentication struct authentication_t Client authentication Fields related to client authentication by broker For mutual authentication using TLS, user could select certificate and key, secure element or digital signature peripheral if available. Public Members const char *password MQTT password const char *certificate Certificate for ssl mutual authentication, not required if mutual authentication is not needed. Must be provided with key . size_t certificate_len Length of the buffer pointed to by certificate. const char *key Private key for SSL mutual authentication, not required if mutual authentication is not needed. If it is not NULL, also certificate has to be provided. size_t key_len Length of the buffer pointed to by key. const char *key_password Client key decryption password, not PEM nor DER, if provided key_password_len must be correctly set. int key_password_len Length of the password pointed to by key_password bool use_secure_element Enable secure element, available in ESP32-ROOM-32SE, for SSL connection void *ds_data Carrier of handle for digital signature parameters, digital signature peripheral is available in some Espressif devices. struct network_t Network related configuration Public Members int reconnect_timeout_ms Reconnect to the broker after this value in miliseconds if auto reconnect is not disabled (defaults to 10s) int reconnect_timeout_ms Reconnect to the broker after this value in miliseconds if auto reconnect is not disabled (defaults to 10s) int timeout_ms Abort network operation if it is not completed after this value, in milliseconds (defaults to 10s). int timeout_ms Abort network operation if it is not completed after this value, in milliseconds (defaults to 10s). int refresh_connection_after_ms Refresh connection after this value (in milliseconds) int refresh_connection_after_ms Refresh connection after this value (in milliseconds) bool disable_auto_reconnect Client will reconnect to server (when errors/disconnect). Set disable_auto_reconnect=true to disable bool disable_auto_reconnect Client will reconnect to server (when errors/disconnect). Set disable_auto_reconnect=true to disable esp_transport_handle_t transport Custom transport handle to use. Warning: The transport should be valid during the client lifetime and is destroyed when esp_mqtt_client_destroy is called. esp_transport_handle_t transport Custom transport handle to use. Warning: The transport should be valid during the client lifetime and is destroyed when esp_mqtt_client_destroy is called. struct ifreq *if_name The name of interface for data to go through. Use the default interface without setting struct ifreq *if_name The name of interface for data to go through. Use the default interface without setting int reconnect_timeout_ms struct network_t Network related configuration Public Members int reconnect_timeout_ms Reconnect to the broker after this value in miliseconds if auto reconnect is not disabled (defaults to 10s) int timeout_ms Abort network operation if it is not completed after this value, in milliseconds (defaults to 10s). int refresh_connection_after_ms Refresh connection after this value (in milliseconds) bool disable_auto_reconnect Client will reconnect to server (when errors/disconnect). Set disable_auto_reconnect=true to disable esp_transport_handle_t transport Custom transport handle to use. Warning: The transport should be valid during the client lifetime and is destroyed when esp_mqtt_client_destroy is called. struct ifreq *if_name The name of interface for data to go through. Use the default interface without setting struct outbox_config_t Client outbox configuration options. Public Members uint64_t limit Size limit for the outbox in bytes. uint64_t limit Size limit for the outbox in bytes. uint64_t limit struct outbox_config_t Client outbox configuration options. Public Members uint64_t limit Size limit for the outbox in bytes. struct session_t MQTT Session related configuration Public Members struct esp_mqtt_client_config_t::session_t::last_will_t last_will Last will configuration struct esp_mqtt_client_config_t::session_t::last_will_t last_will Last will configuration bool disable_clean_session MQTT clean session, default clean_session is true bool disable_clean_session MQTT clean session, default clean_session is true int keepalive MQTT keepalive, default is 120 seconds When configuring this value, keep in mind that the client attempts to communicate with the broker at half the interval that is actually set. This conservative approach allows for more attempts before the broker's timeout occurs int keepalive MQTT keepalive, default is 120 seconds When configuring this value, keep in mind that the client attempts to communicate with the broker at half the interval that is actually set. This conservative approach allows for more attempts before the broker's timeout occurs bool disable_keepalive Set disable_keepalive=true to turn off keep-alive mechanism, keepalive is active by default. Note: setting the config value keepalive to 0 doesn't disable keepalive feature, but uses a default keepalive period bool disable_keepalive Set disable_keepalive=true to turn off keep-alive mechanism, keepalive is active by default. Note: setting the config value keepalive to 0 doesn't disable keepalive feature, but uses a default keepalive period esp_mqtt_protocol_ver_t protocol_ver MQTT protocol version used for connection. esp_mqtt_protocol_ver_t protocol_ver MQTT protocol version used for connection. int message_retransmit_timeout timeout for retransmitting of failed packet int message_retransmit_timeout timeout for retransmitting of failed packet struct last_will_t Last Will and Testament message configuration. struct last_will_t Last Will and Testament message configuration. struct esp_mqtt_client_config_t::session_t::last_will_t last_will struct session_t MQTT Session related configuration Public Members struct esp_mqtt_client_config_t::session_t::last_will_t last_will Last will configuration bool disable_clean_session MQTT clean session, default clean_session is true int keepalive MQTT keepalive, default is 120 seconds When configuring this value, keep in mind that the client attempts to communicate with the broker at half the interval that is actually set. This conservative approach allows for more attempts before the broker's timeout occurs bool disable_keepalive Set disable_keepalive=true to turn off keep-alive mechanism, keepalive is active by default. Note: setting the config value keepalive to 0 doesn't disable keepalive feature, but uses a default keepalive period esp_mqtt_protocol_ver_t protocol_ver MQTT protocol version used for connection. int message_retransmit_timeout timeout for retransmitting of failed packet struct last_will_t Last Will and Testament message configuration. struct task_t Client task configuration struct task_t Client task configuration Default values can be set via menuconfig struct topic_t Topic definition struct Macros MQTT_ERROR_TYPE_ESP_TLS MQTT_ERROR_TYPE_TCP_TRANSPORT error type hold all sorts of transport layer errors, including ESP-TLS error, but in the past only the errors from MQTT_ERROR_TYPE_ESP_TLS layer were reported, so the ESP-TLS error type is re-defined here for backward compatibility esp_mqtt_client_subscribe(client_handle, topic_type, qos_or_size) Convenience macro to select subscribe function to use. Notes: Usage of esp_mqtt_client_subscribe_single is the same as previous esp_mqtt_client_subscribe, refer to it for details. Usage of esp_mqtt_client_subscribe_single is the same as previous esp_mqtt_client_subscribe, refer to it for details. Parameters client_handle -- MQTT client handle topic_type -- Needs to be char* for single subscription or esp_mqtt_topic_t for multiple topics qos_or_size -- It's either a qos when subscribing to a single topic or the size of the subscription array when subscribing to multiple topics. client_handle -- MQTT client handle topic_type -- Needs to be char* for single subscription or esp_mqtt_topic_t for multiple topics qos_or_size -- It's either a qos when subscribing to a single topic or the size of the subscription array when subscribing to multiple topics. client_handle -- MQTT client handle Returns message_id of the subscribe message on success -1 on failure -2 in case of full outbox. Parameters client_handle -- MQTT client handle topic_type -- Needs to be char* for single subscription or esp_mqtt_topic_t for multiple topics qos_or_size -- It's either a qos when subscribing to a single topic or the size of the subscription array when subscribing to multiple topics. Returns message_id of the subscribe message on success -1 on failure -2 in case of full outbox. Usage of esp_mqtt_client_subscribe_single is the same as previous esp_mqtt_client_subscribe, refer to it for details. Type Definitions typedef struct esp_mqtt_client *esp_mqtt_client_handle_t typedef enum esp_mqtt_event_id_t esp_mqtt_event_id_t MQTT event types. User event handler receives context data in esp_mqtt_event_t structure with client - MQTT client handle various other data depending on event type client - MQTT client handle various other data depending on event type client - MQTT client handle typedef enum esp_mqtt_connect_return_code_t esp_mqtt_connect_return_code_t MQTT connection error codes propagated via ERROR event typedef enum esp_mqtt_error_type_t esp_mqtt_error_type_t MQTT connection error codes propagated via ERROR event typedef enum esp_mqtt_transport_t esp_mqtt_transport_t typedef enum esp_mqtt_protocol_ver_t esp_mqtt_protocol_ver_t MQTT protocol version used for connection typedef struct esp_mqtt_error_codes esp_mqtt_error_codes_t MQTT error code structure to be passed as a contextual information into ERROR event Important: This structure extends esp_tls_last_error error structure and is backward compatible with it (so might be down-casted and treated as esp_tls_last_error error, but recommended to update applications if used this way previously) Use this structure directly checking error_type first and then appropriate error code depending on the source of the error: | error_type | related member variables | note | | MQTT_ERROR_TYPE_TCP_TRANSPORT | esp_tls_last_esp_err, esp_tls_stack_err, esp_tls_cert_verify_flags, sock_errno | Error reported from tcp_transport/esp-tls | | MQTT_ERROR_TYPE_CONNECTION_REFUSED | connect_return_code | Internal error reported from MQTT broker on connection | typedef struct esp_mqtt_event_t esp_mqtt_event_t MQTT event configuration structure typedef esp_mqtt_event_t *esp_mqtt_event_handle_t typedef struct esp_mqtt_client_config_t esp_mqtt_client_config_t MQTT client configuration structure Default values can be set via menuconfig All certificates and key data could be passed in PEM or DER format. PEM format must have a terminating NULL character and the related len field set to 0. DER format requires a related len field set to the correct length. Default values can be set via menuconfig All certificates and key data could be passed in PEM or DER format. PEM format must have a terminating NULL character and the related len field set to 0. DER format requires a related len field set to the correct length. Default values can be set via menuconfig Enumerations enum esp_mqtt_event_id_t MQTT event types. User event handler receives context data in esp_mqtt_event_t structure with client - MQTT client handle various other data depending on event type client - MQTT client handle various other data depending on event type Values: enumerator MQTT_EVENT_ANY enumerator MQTT_EVENT_ANY enumerator MQTT_EVENT_ERROR on error event, additional context: connection return code, error handle from esp_tls (if supported) enumerator MQTT_EVENT_ERROR on error event, additional context: connection return code, error handle from esp_tls (if supported) enumerator MQTT_EVENT_CONNECTED connected event, additional context: session_present flag enumerator MQTT_EVENT_CONNECTED connected event, additional context: session_present flag enumerator MQTT_EVENT_DISCONNECTED disconnected event enumerator MQTT_EVENT_DISCONNECTED disconnected event enumerator MQTT_EVENT_SUBSCRIBED subscribed event, additional context: msg_id message id error_handle error_type in case subscribing failed data pointer to broker response, check for errors. data_len length of the data for this event msg_id message id error_handle error_type in case subscribing failed data pointer to broker response, check for errors. data_len length of the data for this event msg_id message id enumerator MQTT_EVENT_SUBSCRIBED subscribed event, additional context: msg_id message id error_handle error_type in case subscribing failed data pointer to broker response, check for errors. data_len length of the data for this event enumerator MQTT_EVENT_UNSUBSCRIBED unsubscribed event, additional context: msg_id enumerator MQTT_EVENT_UNSUBSCRIBED unsubscribed event, additional context: msg_id enumerator MQTT_EVENT_PUBLISHED published event, additional context: msg_id enumerator MQTT_EVENT_PUBLISHED published event, additional context: msg_id enumerator MQTT_EVENT_DATA data event, additional context: msg_id message id topic pointer to the received topic topic_len length of the topic data pointer to the received data data_len length of the data for this event current_data_offset offset of the current data for this event total_data_len total length of the data received retain retain flag of the message qos QoS level of the message dup dup flag of the message Note: Multiple MQTT_EVENT_DATA could be fired for one message, if it is longer than internal buffer. In that case only first event contains topic pointer and length, other contain data only with current data length and current data offset updating. msg_id message id topic pointer to the received topic topic_len length of the topic data pointer to the received data data_len length of the data for this event current_data_offset offset of the current data for this event total_data_len total length of the data received retain retain flag of the message qos QoS level of the message dup dup flag of the message Note: Multiple MQTT_EVENT_DATA could be fired for one message, if it is longer than internal buffer. In that case only first event contains topic pointer and length, other contain data only with current data length and current data offset updating. msg_id message id enumerator MQTT_EVENT_DATA data event, additional context: msg_id message id topic pointer to the received topic topic_len length of the topic data pointer to the received data data_len length of the data for this event current_data_offset offset of the current data for this event total_data_len total length of the data received retain retain flag of the message qos QoS level of the message dup dup flag of the message Note: Multiple MQTT_EVENT_DATA could be fired for one message, if it is longer than internal buffer. In that case only first event contains topic pointer and length, other contain data only with current data length and current data offset updating. enumerator MQTT_EVENT_BEFORE_CONNECT The event occurs before connecting enumerator MQTT_EVENT_BEFORE_CONNECT The event occurs before connecting enumerator MQTT_EVENT_DELETED Notification on delete of one message from the internal outbox, if the message couldn't have been sent and acknowledged before expiring defined in OUTBOX_EXPIRED_TIMEOUT_MS. (events are not posted upon deletion of successfully acknowledged messages) This event id is posted only if MQTT_REPORT_DELETED_MESSAGES==1 Additional context: msg_id (id of the deleted message). This event id is posted only if MQTT_REPORT_DELETED_MESSAGES==1 Additional context: msg_id (id of the deleted message). This event id is posted only if MQTT_REPORT_DELETED_MESSAGES==1 enumerator MQTT_EVENT_DELETED Notification on delete of one message from the internal outbox, if the message couldn't have been sent and acknowledged before expiring defined in OUTBOX_EXPIRED_TIMEOUT_MS. (events are not posted upon deletion of successfully acknowledged messages) This event id is posted only if MQTT_REPORT_DELETED_MESSAGES==1 Additional context: msg_id (id of the deleted message). enumerator MQTT_USER_EVENT Custom event used to queue tasks into mqtt event handler All fields from the esp_mqtt_event_t type could be used to pass an additional context data to the handler. enumerator MQTT_USER_EVENT Custom event used to queue tasks into mqtt event handler All fields from the esp_mqtt_event_t type could be used to pass an additional context data to the handler. client - MQTT client handle enum esp_mqtt_connect_return_code_t MQTT connection error codes propagated via ERROR event Values: enumerator MQTT_CONNECTION_ACCEPTED Connection accepted enumerator MQTT_CONNECTION_ACCEPTED Connection accepted enumerator MQTT_CONNECTION_REFUSE_PROTOCOL MQTT connection refused reason: Wrong protocol enumerator MQTT_CONNECTION_REFUSE_PROTOCOL MQTT connection refused reason: Wrong protocol enumerator MQTT_CONNECTION_REFUSE_ID_REJECTED MQTT connection refused reason: ID rejected enumerator MQTT_CONNECTION_REFUSE_ID_REJECTED MQTT connection refused reason: ID rejected enumerator MQTT_CONNECTION_REFUSE_SERVER_UNAVAILABLE MQTT connection refused reason: Server unavailable enumerator MQTT_CONNECTION_REFUSE_SERVER_UNAVAILABLE MQTT connection refused reason: Server unavailable enumerator MQTT_CONNECTION_REFUSE_BAD_USERNAME MQTT connection refused reason: Wrong user enumerator MQTT_CONNECTION_REFUSE_BAD_USERNAME MQTT connection refused reason: Wrong user enumerator MQTT_CONNECTION_REFUSE_NOT_AUTHORIZED MQTT connection refused reason: Wrong username or password enumerator MQTT_CONNECTION_REFUSE_NOT_AUTHORIZED MQTT connection refused reason: Wrong username or password enumerator MQTT_CONNECTION_ACCEPTED enum esp_mqtt_error_type_t MQTT connection error codes propagated via ERROR event Values: enumerator MQTT_ERROR_TYPE_NONE enumerator MQTT_ERROR_TYPE_NONE enumerator MQTT_ERROR_TYPE_TCP_TRANSPORT enumerator MQTT_ERROR_TYPE_TCP_TRANSPORT enumerator MQTT_ERROR_TYPE_CONNECTION_REFUSED enumerator MQTT_ERROR_TYPE_CONNECTION_REFUSED enumerator MQTT_ERROR_TYPE_SUBSCRIBE_FAILED enumerator MQTT_ERROR_TYPE_SUBSCRIBE_FAILED enumerator MQTT_ERROR_TYPE_NONE enum esp_mqtt_transport_t Values: enumerator MQTT_TRANSPORT_UNKNOWN enumerator MQTT_TRANSPORT_UNKNOWN enumerator MQTT_TRANSPORT_OVER_TCP MQTT over TCP, using scheme: MQTT enumerator MQTT_TRANSPORT_OVER_TCP MQTT over TCP, using scheme: MQTT enumerator MQTT_TRANSPORT_OVER_SSL MQTT over SSL, using scheme: MQTTS enumerator MQTT_TRANSPORT_OVER_SSL MQTT over SSL, using scheme: MQTTS enumerator MQTT_TRANSPORT_OVER_WS MQTT over Websocket, using scheme:: ws enumerator MQTT_TRANSPORT_OVER_WS MQTT over Websocket, using scheme:: ws enumerator MQTT_TRANSPORT_OVER_WSS MQTT over Websocket Secure, using scheme: wss enumerator MQTT_TRANSPORT_OVER_WSS MQTT over Websocket Secure, using scheme: wss enumerator MQTT_TRANSPORT_UNKNOWN
ESP-MQTT Overview ESP-MQTT is an implementation of MQTT protocol client, which is a lightweight publish/subscribe messaging protocol. Now ESP-MQTT supports MQTT v5.0. Features - Support MQTT over TCP, SSL with Mbed TLS, MQTT over WebSocket, and MQTT over WebSocket Secure - Easy to setup with URI - Multiple instances (multiple clients in one application) - Support subscribing, publishing, authentication, last will messages, keep alive pings, and all 3 Quality of Service (QoS) levels (it should be a fully functional client) Application Examples - protocols/mqtt/tcp: MQTT over TCP, default port 1883 - protocols/mqtt/ssl: MQTT over TLS, default port 8883 - protocols/mqtt/ssl_ds: MQTT over TLS using digital signature peripheral for authentication, default port 8883 - protocols/mqtt/ssl_mutual_auth: MQTT over TLS using certificates for authentication, default port 8883 - protocols/mqtt/ssl_psk: MQTT over TLS using pre-shared keys for authentication, default port 8883 - protocols/mqtt/ws: MQTT over WebSocket, default port 80 - protocols/mqtt/wss: MQTT over WebSocket Secure, default port 443 - protocols/mqtt5: Uses ESP-MQTT library to connect to broker with MQTT v5.0 MQTT Message Retransmission A new MQTT message is created by calling esp_mqtt_client_publish or its non blocking counterpart esp_mqtt_client_enqueue. Messages with QoS 0 is sent only once. QoS 1 and 2 have different behaviors since the protocol requires extra steps to complete the process. The ESP-MQTT library opts to always retransmit unacknowledged QoS 1 and 2 publish messages to avoid losses in faulty connections, even though the MQTT specification requires the re-transmission only on reconnect with Clean Session flag been set to 0 (set disable_clean_session to true for this behavior). QoS 1 and 2 messages that may need retransmission are always enqueued, but first transmission try occurs immediately if esp_mqtt_client_publish is used. A transmission retry for unacknowledged messages will occur after message_retransmit_timeout. After CONFIG_MQTT_OUTBOX_EXPIRED_TIMEOUT_MS messages will expire and be deleted. If CONFIG_MQTT_REPORT_DELETED_MESSAGES is set, an event will be sent to notify the user. Configuration The configuration is made by setting fields in esp_mqtt_client_config_t struct. The configuration struct has the following sub structs to configure different aspects of the client operation. - esp_mqtt_client_config_t::broker_t- Allow to set address and security verification. - esp_mqtt_client_config_t::credentials_t- Client credentials for authentication. - esp_mqtt_client_config_t::session_t- Configuration for MQTT session aspects. - esp_mqtt_client_config_t::network_t- Networking related configuration. - esp_mqtt_client_config_t::task_t- Allow to configure FreeRTOS task. - esp_mqtt_client_config_t::buffer_t- Buffer size for input and output. In the following sections, the most common aspects are detailed. Broker Address Broker address can be set by usage of address struct. The configuration can be made by usage of uri field or the combination of hostname, transport and port. Optionally, path could be set, this field is useful in WebSocket connections. The uri field is used in the format scheme://hostname:port/path. Curently support mqtt, mqtts, ws, wssschemes MQTT over TCP samples: mqtt://mqtt.eclipseprojects.io: MQTT over TCP, default port 1883 mqtt://mqtt.eclipseprojects.io:1884: MQTT over TCP, port 1884 mqtt://username:password@mqtt.eclipseprojects.io:1884: MQTT over TCP, port 1884, with username and password - MQTT over SSL samples: mqtts://mqtt.eclipseprojects.io: MQTT over SSL, port 8883 mqtts://mqtt.eclipseprojects.io:8884: MQTT over SSL, port 8884 - MQTT over WebSocket samples: ws://mqtt.eclipseprojects.io:80/mqtt - MQTT over WebSocket Secure samples: wss://mqtt.eclipseprojects.io:443/mqtt - Minimal configurations: const esp_mqtt_client_config_t mqtt_cfg = { .broker.address.uri = "mqtt://mqtt.eclipseprojects.io", }; esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg); esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client); esp_mqtt_client_start(client); Note By default MQTT client uses event loop library to post related MQTT events (connected, subscribed, published, etc.). Verification For secure connections with TLS used, and to guarantee Broker's identity, the verification struct must be set. The broker certificate may be set in PEM or DER format. To select DER, the equivalent certificate_len field must be set. Otherwise, a null-terminated string in PEM format should be provided to certificate field. - Get certificate from server, example: mqtt.eclipseprojects.io openssl s_client -showcerts -connect mqtt.eclipseprojects.io:8883 < /dev/null \ 2> /dev/null | openssl x509 -outform PEM > mqtt_eclipse_org.pem - Get certificate from server, example: Check the sample application: protocols/mqtt/ssl Configuration: const esp_mqtt_client_config_t mqtt_cfg = { .broker = { .address.uri = "mqtts://mqtt.eclipseprojects.io:8883", .verification.certificate = (const char *)mqtt_eclipse_org_pem_start, }, }; For details about other fields, please check the API Reference and TLS Server Verification. Client Credentials All client related credentials are under the credentials field. Authentication It is possible to set authentication parameters through the authentication field. The client supports the following authentication methods: - password: use a password by setting - certificateand key: mutual authentication with TLS, and both can be provided in PEM or DER format - use_secure_element: use secure element available in ESP32-WROOM-32SE - ds_data: use Digital Signature Peripheral available in some Espressif devices Session For MQTT session related configurations, session fields should be used. Last Will and Testament MQTT allows for a last will and testament (LWT) message to notify other clients when a client ungracefully disconnects. This is configured by the following fields in the last_will struct. Events The following events may be posted by the MQTT client: MQTT_EVENT_BEFORE_CONNECT: The client is initialized and about to start connecting to the broker. MQTT_EVENT_CONNECTED: The client has successfully established a connection to the broker. The client is now ready to send and receive data. MQTT_EVENT_DISCONNECTED: The client has aborted the connection due to being unable to read or write data, e.g., because the server is unavailable. MQTT_EVENT_SUBSCRIBED: The broker has acknowledged the client's subscribe request. The event data contains the message ID of the subscribe message. MQTT_EVENT_UNSUBSCRIBED: The broker has acknowledged the client's unsubscribe request. The event data contains the message ID of the unsubscribe message. MQTT_EVENT_PUBLISHED: The broker has acknowledged the client's publish message. This is only posted for QoS level 1 and 2, as level 0 does not use acknowledgements. The event data contains the message ID of the publish message. MQTT_EVENT_DATA: The client has received a publish message. The event data contains: message ID, name of the topic it was published to, received data and its length. For data that exceeds the internal buffer, multiple MQTT_EVENT_DATAevents are posted and current_data_offsetand total_data_lenfrom event data updated to keep track of the fragmented message. MQTT_EVENT_ERROR: The client has encountered an error. The field error_handlein the event data contains error_typethat can be used to identify the error. The type of error determines which parts of the error_handlestruct is filled. API Reference Header File This header file can be included with: #include "mqtt_client.h" This header file is a part of the API provided by the mqttcomponent. To declare that your component depends on mqtt, add the following to your CMakeLists.txt: REQUIRES mqtt or PRIV_REQUIRES mqtt Functions - esp_mqtt_client_handle_t esp_mqtt_client_init(const esp_mqtt_client_config_t *config) Creates MQTT client handle based on the configuration. - Parameters config -- MQTT configuration structure - Returns mqtt_client_handle if successfully created, NULL on error - esp_err_t esp_mqtt_client_set_uri(esp_mqtt_client_handle_t client, const char *uri) Sets MQTT connection URI. This API is usually used to overrides the URI configured in esp_mqtt_client_init. - Parameters client -- MQTT client handle uri -- - - Returns ESP_FAIL if URI parse error, ESP_OK on success - esp_err_t esp_mqtt_client_start(esp_mqtt_client_handle_t client) Starts MQTT client with already created client handle. - Parameters client -- MQTT client handle - Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization ESP_FAIL on other error - esp_err_t esp_mqtt_client_reconnect(esp_mqtt_client_handle_t client) This api is typically used to force reconnection upon a specific event. - Parameters client -- MQTT client handle - Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization ESP_FAIL if client is in invalid state - esp_err_t esp_mqtt_client_disconnect(esp_mqtt_client_handle_t client) This api is typically used to force disconnection from the broker. - Parameters client -- MQTT client handle - Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization - esp_err_t esp_mqtt_client_stop(esp_mqtt_client_handle_t client) Stops MQTT client tasks. Notes: Cannot be called from the MQTT event handler - Parameters client -- MQTT client handle - Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization ESP_FAIL if client is in invalid state - - int esp_mqtt_client_subscribe_single(esp_mqtt_client_handle_t client, const char *topic, int qos) Subscribe the client to defined topic with defined qos. Notes: Client must be connected to send subscribe message This API is could be executed from a user task or from a MQTT event callback i.e. internal MQTT task (API is protected by internal mutex, so it might block if a longer data receive operation is in progress. esp_mqtt_client_subscribecould be used to call this function. - Parameters client -- MQTT client handle topic -- topic filter to subscribe qos -- Max qos level of the subscription - - Returns message_id of the subscribe message on success -1 on failure -2 in case of full outbox. - - int esp_mqtt_client_subscribe_multiple(esp_mqtt_client_handle_t client, const esp_mqtt_topic_t *topic_list, int size) Subscribe the client to a list of defined topics with defined qos. Notes: Client must be connected to send subscribe message This API is could be executed from a user task or from a MQTT event callback i.e. internal MQTT task (API is protected by internal mutex, so it might block if a longer data receive operation is in progress. esp_mqtt_client_subscribecould be used to call this function. - Parameters client -- MQTT client handle topic_list -- List of topics to subscribe size -- size of topic_list - - Returns message_id of the subscribe message on success -1 on failure -2 in case of full outbox. - - int esp_mqtt_client_unsubscribe(esp_mqtt_client_handle_t client, const char *topic) Unsubscribe the client from defined topic. Notes: Client must be connected to send unsubscribe message It is thread safe, please refer to esp_mqtt_client_subscribe_singlefor details - Parameters client -- MQTT client handle topic -- - - Returns message_id of the subscribe message on success -1 on failure - - int esp_mqtt_client_publish(esp_mqtt_client_handle_t client, const char *topic, const char *data, int len, int qos, int retain) Client to send a publish message to the broker. Notes: This API might block for several seconds, either due to network timeout (10s) or if publishing payloads longer than internal buffer (due to message fragmentation) Client doesn't have to be connected for this API to work, enqueueing the messages with qos>1 (returning -1 for all the qos=0 messages if disconnected). If MQTT_SKIP_PUBLISH_IF_DISCONNECTED is enabled, this API will not attempt to publish when the client is not connected and will always return -1. It is thread safe, please refer to esp_mqtt_client_subscribefor details - Parameters client -- MQTT client handle topic -- topic string data -- payload string (set to NULL, sending empty payload message) len -- data length, if set to 0, length is calculated from payload string qos -- QoS of publish message retain -- retain flag - - Returns message_id of the publish message (for QoS 0 message_id will always be zero) on success. -1 on failure, -2 in case of full outbox. - - int esp_mqtt_client_enqueue(esp_mqtt_client_handle_t client, const char *topic, const char *data, int len, int qos, int retain, bool store) Enqueue a message to the outbox, to be sent later. Typically used for messages with qos>0, but could be also used for qos=0 messages if store=true. This API generates and stores the publish message into the internal outbox and the actual sending to the network is performed in the mqtt-task context (in contrast to the esp_mqtt_client_publish() which sends the publish message immediately in the user task's context). Thus, it could be used as a non blocking version of esp_mqtt_client_publish(). - Parameters client -- MQTT client handle topic -- topic string data -- payload string (set to NULL, sending empty payload message) len -- data length, if set to 0, length is calculated from payload string qos -- QoS of publish message retain -- retain flag store -- if true, all messages are enqueued; otherwise only QoS 1 and QoS 2 are enqueued - - Returns message_id if queued successfully, -1 on failure, -2 in case of full outbox. - esp_err_t esp_mqtt_client_destroy(esp_mqtt_client_handle_t client) Destroys the client handle. Notes: Cannot be called from the MQTT event handler - Parameters client -- MQTT client handle - Returns ESP_OK ESP_ERR_INVALID_ARG on wrong initialization - - esp_err_t esp_mqtt_set_config(esp_mqtt_client_handle_t client, const esp_mqtt_client_config_t *config) Set configuration structure, typically used when updating the config (i.e. on "before_connect" event. - Parameters client -- MQTT client handle config -- MQTT configuration structure - - Returns ESP_ERR_NO_MEM if failed to allocate ESP_ERR_INVALID_ARG if conflicts on transport configuration. ESP_OK on success - esp_err_t esp_mqtt_client_register_event(esp_mqtt_client_handle_t client, esp_mqtt_event_id_t event, esp_event_handler_t event_handler, void *event_handler_arg) Registers MQTT event. - Parameters client -- MQTT client handle event -- event type event_handler -- handler callback event_handler_arg -- handlers context - - Returns ESP_ERR_NO_MEM if failed to allocate ESP_ERR_INVALID_ARG on wrong initialization ESP_OK on success - esp_err_t esp_mqtt_client_unregister_event(esp_mqtt_client_handle_t client, esp_mqtt_event_id_t event, esp_event_handler_t event_handler) Unregisters mqtt event. - Parameters client -- mqtt client handle event -- event ID event_handler -- handler to unregister - - Returns ESP_ERR_NO_MEM if failed to allocate ESP_ERR_INVALID_ARG on invalid event ID ESP_OK on success - int esp_mqtt_client_get_outbox_size(esp_mqtt_client_handle_t client) Get outbox size. - Parameters client -- MQTT client handle - Returns outbox size 0 on wrong initialization - esp_err_t esp_mqtt_dispatch_custom_event(esp_mqtt_client_handle_t client, esp_mqtt_event_t *event) Dispatch user event to the mqtt internal event loop. - Parameters client -- MQTT client handle event -- MQTT event handle structure - - Returns ESP_OK on success ESP_ERR_TIMEOUT if the event couldn't be queued (ref also CONFIG_MQTT_EVENT_QUEUE_SIZE) Structures - struct esp_mqtt_error_codes MQTT error code structure to be passed as a contextual information into ERROR event Important: This structure extends esp_tls_last_errorerror structure and is backward compatible with it (so might be down-casted and treated as esp_tls_last_errorerror, but recommended to update applications if used this way previously) Use this structure directly checking error_type first and then appropriate error code depending on the source of the error: | error_type | related member variables | note | | MQTT_ERROR_TYPE_TCP_TRANSPORT | esp_tls_last_esp_err, esp_tls_stack_err, esp_tls_cert_verify_flags, sock_errno | Error reported from tcp_transport/esp-tls | | MQTT_ERROR_TYPE_CONNECTION_REFUSED | connect_return_code | Internal error reported from MQTT broker on connection | Public Members - int esp_tls_stack_err tls specific error code reported from underlying tls stack - int esp_tls_cert_verify_flags tls flags reported from underlying tls stack during certificate verification - esp_mqtt_error_type_t error_type error type referring to the source of the error - esp_mqtt_connect_return_code_t connect_return_code connection refused error code reported from MQTT* broker on connection - int esp_transport_sock_errno errno from the underlying socket - int esp_tls_stack_err - struct esp_mqtt_event_t MQTT event configuration structure Public Members - esp_mqtt_event_id_t event_id MQTT event type - esp_mqtt_client_handle_t client MQTT client handle for this event - char *data Data associated with this event - int data_len Length of the data for this event - int total_data_len Total length of the data (longer data are supplied with multiple events) - int current_data_offset Actual offset for the data associated with this event - char *topic Topic associated with this event - int topic_len Length of the topic for this event associated with this event - int msg_id MQTT messaged id of message - int session_present MQTT session_present flag for connection event - esp_mqtt_error_codes_t *error_handle esp-mqtt error handle including esp-tls errors as well as internal MQTT errors - bool retain Retained flag of the message associated with this event - int qos QoS of the messages associated with this event - bool dup dup flag of the message associated with this event - esp_mqtt_protocol_ver_t protocol_ver MQTT protocol version used for connection, defaults to value from menuconfig - esp_mqtt_event_id_t event_id - struct esp_mqtt_client_config_t MQTT client configuration structure Default values can be set via menuconfig All certificates and key data could be passed in PEM or DER format. PEM format must have a terminating NULL character and the related len field set to 0. DER format requires a related len field set to the correct length. Public Members - struct esp_mqtt_client_config_t::broker_t broker Broker address and security verification - struct esp_mqtt_client_config_t::credentials_t credentials User credentials for broker - struct esp_mqtt_client_config_t::session_t session MQTT session configuration. - struct esp_mqtt_client_config_t::network_t network Network configuration - struct esp_mqtt_client_config_t::task_t task FreeRTOS task configuration. - struct esp_mqtt_client_config_t::buffer_t buffer Buffer size configuration. - struct esp_mqtt_client_config_t::outbox_config_t outbox Outbox configuration. - struct broker_t Broker related configuration Public Members - struct esp_mqtt_client_config_t::broker_t::address_t address Broker address configuration - struct esp_mqtt_client_config_t::broker_t::verification_t verification Security verification of the broker - struct address_t Broker address uri have precedence over other fields If uri isn't set at least hostname, transport and port should. - - struct verification_t Broker identity verification If fields are not set broker's identity isn't verified. it's recommended to set the options in this struct for security reasons. Public Members - bool use_global_ca_store Use a global ca_store, look esp-tls documentation for details. - esp_err_t (*crt_bundle_attach)(void *conf) Pointer to ESP x509 Certificate Bundle attach function for the usage of certificate bundles. - const char *certificate Certificate data, default is NULL, not required to verify the server. - size_t certificate_len Length of the buffer pointed to by certificate. - const struct psk_key_hint *psk_hint_key Pointer to PSK struct defined in esp_tls.h to enable PSK authentication (as alternative to certificate verification). PSK is enabled only if there are no other ways to verify broker. - bool skip_cert_common_name_check Skip any validation of server certificate CN field, this reduces the security of TLS and makes the MQTT client susceptible to MITM attacks - const char **alpn_protos NULL-terminated list of supported application protocols to be used for ALPN - const char *common_name Pointer to the string containing server certificate common name. If non-NULL, server certificate CN must match this name, If NULL, server certificate CN must match hostname. This is ignored if skip_cert_common_name_check=true. - bool use_global_ca_store - struct esp_mqtt_client_config_t::broker_t::address_t address - struct buffer_t Client buffer size configuration Client have two buffers for input and output respectivelly. - struct credentials_t Client related credentials for authentication. Public Members - const char *username MQTT username - const char *client_id Set MQTT client identifier. Ignored if set_null_client_id == true If NULL set the default client id. Default client id is ESP32_CHIPID%where CHIPID%are last 3 bytes of MAC address in hex format - bool set_null_client_id Selects a NULL client id - struct esp_mqtt_client_config_t::credentials_t::authentication_t authentication Client authentication - struct authentication_t Client authentication Fields related to client authentication by broker For mutual authentication using TLS, user could select certificate and key, secure element or digital signature peripheral if available. Public Members - const char *password MQTT password - const char *certificate Certificate for ssl mutual authentication, not required if mutual authentication is not needed. Must be provided with key. - size_t certificate_len Length of the buffer pointed to by certificate. - const char *key Private key for SSL mutual authentication, not required if mutual authentication is not needed. If it is not NULL, also certificatehas to be provided. - size_t key_len Length of the buffer pointed to by key. - const char *key_password Client key decryption password, not PEM nor DER, if provided key_password_lenmust be correctly set. - int key_password_len Length of the password pointed to by key_password - bool use_secure_element Enable secure element, available in ESP32-ROOM-32SE, for SSL connection - void *ds_data Carrier of handle for digital signature parameters, digital signature peripheral is available in some Espressif devices. - const char *password - const char *username - struct network_t Network related configuration Public Members - int reconnect_timeout_ms Reconnect to the broker after this value in miliseconds if auto reconnect is not disabled (defaults to 10s) - int timeout_ms Abort network operation if it is not completed after this value, in milliseconds (defaults to 10s). - int refresh_connection_after_ms Refresh connection after this value (in milliseconds) - bool disable_auto_reconnect Client will reconnect to server (when errors/disconnect). Set disable_auto_reconnect=trueto disable - esp_transport_handle_t transport Custom transport handle to use. Warning: The transport should be valid during the client lifetime and is destroyed when esp_mqtt_client_destroy is called. - struct ifreq *if_name The name of interface for data to go through. Use the default interface without setting - int reconnect_timeout_ms - struct outbox_config_t Client outbox configuration options. Public Members - uint64_t limit Size limit for the outbox in bytes. - uint64_t limit - struct session_t MQTT Session related configuration Public Members - struct esp_mqtt_client_config_t::session_t::last_will_t last_will Last will configuration - bool disable_clean_session MQTT clean session, default clean_session is true - int keepalive MQTT keepalive, default is 120 seconds When configuring this value, keep in mind that the client attempts to communicate with the broker at half the interval that is actually set. This conservative approach allows for more attempts before the broker's timeout occurs - bool disable_keepalive Set disable_keepalive=trueto turn off keep-alive mechanism, keepalive is active by default. Note: setting the config value keepaliveto 0doesn't disable keepalive feature, but uses a default keepalive period - esp_mqtt_protocol_ver_t protocol_ver MQTT protocol version used for connection. - int message_retransmit_timeout timeout for retransmitting of failed packet - struct last_will_t Last Will and Testament message configuration. - struct esp_mqtt_client_config_t::session_t::last_will_t last_will - struct task_t Client task configuration - - struct topic_t Topic definition struct Macros - MQTT_ERROR_TYPE_ESP_TLS MQTT_ERROR_TYPE_TCP_TRANSPORT error type hold all sorts of transport layer errors, including ESP-TLS error, but in the past only the errors from MQTT_ERROR_TYPE_ESP_TLS layer were reported, so the ESP-TLS error type is re-defined here for backward compatibility - esp_mqtt_client_subscribe(client_handle, topic_type, qos_or_size) Convenience macro to select subscribe function to use. Notes: Usage of esp_mqtt_client_subscribe_singleis the same as previous esp_mqtt_client_subscribe, refer to it for details. - Parameters client_handle -- MQTT client handle topic_type -- Needs to be char* for single subscription or esp_mqtt_topic_tfor multiple topics qos_or_size -- It's either a qos when subscribing to a single topic or the size of the subscription array when subscribing to multiple topics. - - Returns message_id of the subscribe message on success -1 on failure -2 in case of full outbox. - Type Definitions - typedef struct esp_mqtt_client *esp_mqtt_client_handle_t - typedef enum esp_mqtt_event_id_t esp_mqtt_event_id_t MQTT event types. User event handler receives context data in esp_mqtt_event_tstructure with client - MQTT client handle various other data depending on event type - - typedef enum esp_mqtt_connect_return_code_t esp_mqtt_connect_return_code_t MQTT connection error codes propagated via ERROR event - typedef enum esp_mqtt_error_type_t esp_mqtt_error_type_t MQTT connection error codes propagated via ERROR event - typedef enum esp_mqtt_transport_t esp_mqtt_transport_t - typedef enum esp_mqtt_protocol_ver_t esp_mqtt_protocol_ver_t MQTT protocol version used for connection - typedef struct esp_mqtt_error_codes esp_mqtt_error_codes_t MQTT error code structure to be passed as a contextual information into ERROR event Important: This structure extends esp_tls_last_errorerror structure and is backward compatible with it (so might be down-casted and treated as esp_tls_last_errorerror, but recommended to update applications if used this way previously) Use this structure directly checking error_type first and then appropriate error code depending on the source of the error: | error_type | related member variables | note | | MQTT_ERROR_TYPE_TCP_TRANSPORT | esp_tls_last_esp_err, esp_tls_stack_err, esp_tls_cert_verify_flags, sock_errno | Error reported from tcp_transport/esp-tls | | MQTT_ERROR_TYPE_CONNECTION_REFUSED | connect_return_code | Internal error reported from MQTT broker on connection | - typedef struct esp_mqtt_event_t esp_mqtt_event_t MQTT event configuration structure - typedef esp_mqtt_event_t *esp_mqtt_event_handle_t - typedef struct esp_mqtt_client_config_t esp_mqtt_client_config_t MQTT client configuration structure Default values can be set via menuconfig All certificates and key data could be passed in PEM or DER format. PEM format must have a terminating NULL character and the related len field set to 0. DER format requires a related len field set to the correct length. - Enumerations - enum esp_mqtt_event_id_t MQTT event types. User event handler receives context data in esp_mqtt_event_tstructure with client - MQTT client handle various other data depending on event type Values: - enumerator MQTT_EVENT_ANY - enumerator MQTT_EVENT_ERROR on error event, additional context: connection return code, error handle from esp_tls (if supported) - enumerator MQTT_EVENT_CONNECTED connected event, additional context: session_present flag - enumerator MQTT_EVENT_DISCONNECTED disconnected event - enumerator MQTT_EVENT_SUBSCRIBED subscribed event, additional context: msg_id message id error_handle error_typein case subscribing failed data pointer to broker response, check for errors. data_len length of the data for this event - - enumerator MQTT_EVENT_UNSUBSCRIBED unsubscribed event, additional context: msg_id - enumerator MQTT_EVENT_PUBLISHED published event, additional context: msg_id - enumerator MQTT_EVENT_DATA data event, additional context: msg_id message id topic pointer to the received topic topic_len length of the topic data pointer to the received data data_len length of the data for this event current_data_offset offset of the current data for this event total_data_len total length of the data received retain retain flag of the message qos QoS level of the message dup dup flag of the message Note: Multiple MQTT_EVENT_DATA could be fired for one message, if it is longer than internal buffer. In that case only first event contains topic pointer and length, other contain data only with current data length and current data offset updating. - - enumerator MQTT_EVENT_BEFORE_CONNECT The event occurs before connecting - enumerator MQTT_EVENT_DELETED Notification on delete of one message from the internal outbox, if the message couldn't have been sent and acknowledged before expiring defined in OUTBOX_EXPIRED_TIMEOUT_MS. (events are not posted upon deletion of successfully acknowledged messages) This event id is posted only if MQTT_REPORT_DELETED_MESSAGES==1 Additional context: msg_id (id of the deleted message). - - enumerator MQTT_USER_EVENT Custom event used to queue tasks into mqtt event handler All fields from the esp_mqtt_event_t type could be used to pass an additional context data to the handler. - - enum esp_mqtt_connect_return_code_t MQTT connection error codes propagated via ERROR event Values: - enumerator MQTT_CONNECTION_ACCEPTED Connection accepted - enumerator MQTT_CONNECTION_REFUSE_PROTOCOL MQTT connection refused reason: Wrong protocol - enumerator MQTT_CONNECTION_REFUSE_ID_REJECTED MQTT connection refused reason: ID rejected - enumerator MQTT_CONNECTION_REFUSE_SERVER_UNAVAILABLE MQTT connection refused reason: Server unavailable - enumerator MQTT_CONNECTION_REFUSE_BAD_USERNAME MQTT connection refused reason: Wrong user - enumerator MQTT_CONNECTION_REFUSE_NOT_AUTHORIZED MQTT connection refused reason: Wrong username or password - enumerator MQTT_CONNECTION_ACCEPTED - enum esp_mqtt_error_type_t MQTT connection error codes propagated via ERROR event Values: - enumerator MQTT_ERROR_TYPE_NONE - enumerator MQTT_ERROR_TYPE_TCP_TRANSPORT - enumerator MQTT_ERROR_TYPE_CONNECTION_REFUSED - enumerator MQTT_ERROR_TYPE_SUBSCRIBE_FAILED - enumerator MQTT_ERROR_TYPE_NONE - enum esp_mqtt_transport_t Values: - enumerator MQTT_TRANSPORT_UNKNOWN - enumerator MQTT_TRANSPORT_OVER_TCP MQTT over TCP, using scheme: MQTT - enumerator MQTT_TRANSPORT_OVER_SSL MQTT over SSL, using scheme: MQTTS - enumerator MQTT_TRANSPORT_OVER_WS MQTT over Websocket, using scheme:: ws - enumerator MQTT_TRANSPORT_OVER_WSS MQTT over Websocket Secure, using scheme: wss - enumerator MQTT_TRANSPORT_UNKNOWN
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/protocols/mqtt.html
ESP-IDF Programming Guide v5.2.1 documentation
null
ESP-TLS
null
espressif.com
2016-01-01
745bfc5af690d090
null
null
ESP-TLS Overview The ESP-TLS component provides a simplified API interface for accessing the commonly used TLS functions. It supports common scenarios like CA certification validation, SNI, ALPN negotiation, and non-blocking connection among others. All the configurations can be specified in the esp_tls_cfg_t data structure. Once done, TLS communication can be conducted using the following APIs: esp_tls_init() : for initializing the TLS connection handle. esp_tls_conn_new_sync() : for opening a new blocking TLS connection. esp_tls_conn_new_async() : for opening a new non-blocking TLS connection. esp_tls_conn_read() : for reading from the connection. esp_tls_conn_write() : for writing into the connection. esp_tls_conn_destroy() : for freeing up the connection. Any application layer protocol like HTTP1, HTTP2, etc can be executed on top of this layer. Application Example Simple HTTPS example that uses ESP-TLS to establish a secure socket connection: protocols/https_request. Tree Structure for ESP-TLS Component ├── esp_tls.c ├── esp_tls.h ├── esp_tls_mbedtls.c ├── esp_tls_wolfssl.c └── private_include ├── esp_tls_mbedtls.h └── esp_tls_wolfssl.h The ESP-TLS component has a file esp-tls/esp_tls.h which contains the public API headers for the component. Internally, the ESP-TLS component operates using either MbedTLS or WolfSSL, which are SSL/TLS libraries. APIs specific to MbedTLS are present in esp-tls/private_include/esp_tls_mbedtls.h and APIs specific to WolfSSL are present in esp-tls/private_include/esp_tls_wolfssl.h. TLS Server Verification ESP-TLS provides multiple options for TLS server verification on the client side. The ESP-TLS client can verify the server by validating the peer's server certificate or with the help of pre-shared keys. The user should select only one of the following options in the esp_tls_cfg_t structure for TLS server verification. If no option is selected, the client will return a fatal error by default during the TLS connection setup. cacert_buf and cacert_bytes: The CA certificate can be provided in a buffer to the esp_tls_cfg_t structure. The ESP-TLS uses the CA certificate present in the buffer to verify the server. The following variables in the esp_tls_cfg_t structure must be set. cacert_buf - pointer to the buffer which contains the CA certification. cacert_bytes - the size of the CA certificate in bytes. use_global_ca_store: The global_ca_store can be initialized and set at once. Then it can be used to verify the server for all the ESP-TLS connections which have set use_global_ca_store = true in their respective esp_tls_cfg_t structure. See the API Reference section below for information regarding different APIs used for initializing and setting up the global_ca_store . crt_bundle_attach: The ESP x509 Certificate Bundle API provides an easy way to include a bundle of custom x509 root certificates for TLS server verification. More details can be found at ESP x509 Certificate Bundle. psk_hint_key: To use pre-shared keys for server verification, CONFIG_ESP_TLS_PSK_VERIFICATION should be enabled in the ESP-TLS menuconfig. Then the pointer to the PSK hint and key should be provided to the esp_tls_cfg_t structure. The ESP-TLS will use the PSK for server verification only when no other option regarding server verification is selected. skip server verification: This is an insecure option provided in the ESP-TLS for testing purposes. The option can be set by enabling CONFIG_ESP_TLS_INSECURE and CONFIG_ESP_TLS_SKIP_SERVER_CERT_VERIFY in the ESP-TLS menuconfig. When this option is enabled the ESP-TLS will skip server verification by default when no other options for server verification are selected in the esp_tls_cfg_t structure. Warning Enabling this option comes with a potential risk of establishing a TLS connection with a server that has a fake identity, provided that the server certificate is not provided either through API or other mechanisms like ca_store etc. ESP-TLS Server Cert Selection Hook The ESP-TLS component provides an option to set the server certification selection hook when using the MbedTLS stack. This provides an ability to configure and use a certificate selection callback during server handshake. The callback helps to select a certificate to present to the client based on the TLS extensions supplied in the client hello message, such as ALPN and SNI. To enable this feature, please enable CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK in the ESP-TLS menuconfig. The certificate selection callback can be configured in the esp_tls_cfg_t structure as follows: int cert_selection_callback(mbedtls_ssl_context *ssl) { /* Code that the callback should execute */ return 0; } esp_tls_cfg_t cfg = { cert_select_cb = cert_section_callback, }; Underlying SSL/TLS Library Options The ESP-TLS component offers the option to use MbedTLS or WolfSSL as its underlying SSL/TLS library. By default, only MbedTLS is available and used, WolfSSL SSL/TLS library is also available publicly at https://github.com/espressif/esp-wolfssl. The repository provides the WolfSSL component in binary format, and it also provides a few examples that are useful for understanding the API. Please refer to the repository README.md for information on licensing and other options. Please see the below section for instructions on how to use WolfSSL in your project. Note As the library options are internal to ESP-TLS, switching the libraries will not change ESP-TLS specific code for a project. How to Use WolfSSL with ESP-IDF There are two ways to use WolfSSL in your project: Directly add WolfSSL as a component in your project with the following three commands: (First, change the directory (cd) to your project directory) mkdir components cd components git clone --recursive https://github.com/espressif/esp-wolfssl.git Add WolfSSL as an extra component in your project. Download WolfSSL with: git clone --recursive https://github.com/espressif/esp-wolfssl.git Include ESP-WolfSSL in ESP-IDF with setting EXTRA_COMPONENT_DIRS in CMakeLists.txt of your project as done in wolfssl/examples. For reference see Optional Project Variables in build-system.. After the above steps, you will have the option to choose WolfSSL as the underlying SSL/TLS library in the configuration menu of your project as follows: idf.py menuconfig > ESP-TLS > SSL/TLS Library > Mbedtls/Wolfssl Comparison Between MbedTLS and WolfSSL The following table shows a typical comparison between WolfSSL and MbedTLS when the protocols/https_request example (which includes server authentication) is running with both SSL/TLS libraries and with all respective configurations set to default. For MbedTLS, the IN_CONTENT length and OUT_CONTENT length are set to 16384 bytes and 4096 bytes respectively. Property WolfSSL MbedTLS Total Heap Consumed ~ 19 KB ~ 37 KB Task Stack Used ~ 2.2 KB ~ 3.6 KB Bin size ~ 858 KB ~ 736 KB Note These values can vary based on configuration options and version of respective libraries. ATECC608A (Secure Element) with ESP-TLS ESP-TLS provides support for using ATECC608A cryptoauth chip with ESP32-WROOM-32SE. The use of ATECC608A is supported only when ESP-TLS is used with MbedTLS as its underlying SSL/TLS stack. ESP-TLS uses MbedTLS as its underlying TLS/SSL stack by default unless changed manually. Note ATECC608A chip on ESP32-WROOM-32SE must be already configured, for details refer esp_cryptoauth_utility. To enable the secure element support, and use it in your project for TLS connection, you have to follow the below steps: Add esp-cryptoauthlib in your project, for details please refer how to use esp-cryptoauthlib with ESP-IDF. Enable the following menuconfig option: menuconfig > Component config > ESP-TLS > Use Secure Element (ATECC608A) with ESP-TLS Select type of ATECC608A chip with following option: menuconfig > Component config > esp-cryptoauthlib > Choose Type of ATECC608A chip To know more about different types of ATECC608A chips and how to obtain the type of ATECC608A connected to your ESP module, please visit ATECC608A chip type. Enable the use of ATECC608A in ESP-TLS by providing the following config option in esp_tls_cfg_t . esp_tls_cfg_t cfg = { /* other configurations options */ .use_secure_element = true, }; TLS Ciphersuites ESP-TLS provides the ability to set a ciphersuites list in client mode. The TLS ciphersuites list informs the server about the supported ciphersuites for the specific TLS connection regardless of the TLS stack configuration. If the server supports any ciphersuite from this list, then the TLS connection will succeed; otherwise, it will fail. You can set ciphersuites_list in the esp_tls_cfg_t structure during client connection as follows: /* ciphersuites_list must end with 0 and must be available in the memory scope active during the entire TLS connection */ static const int ciphersuites_list[] = {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 0}; esp_tls_cfg_t cfg = { .ciphersuites_list = ciphersuites_list, }; ESP-TLS will not check the validity of ciphersuites_list that was set, you should call esp_tls_get_ciphersuites_list() to get ciphersuites list supported in the TLS stack and cross-check it against the supplied list. Note This feature is supported only in the MbedTLS stack. API Reference Header File This header file can be included with: #include "esp_tls.h" This header file is a part of the API provided by the esp-tls component. To declare that your component depends on esp-tls , add the following to your CMakeLists.txt: REQUIRES esp-tls or PRIV_REQUIRES esp-tls Functions esp_tls_t *esp_tls_init(void) Create TLS connection. This function allocates and initializes esp-tls structure handle. Returns tls Pointer to esp-tls as esp-tls handle if successfully initialized, NULL if allocation error Returns tls Pointer to esp-tls as esp-tls handle if successfully initialized, NULL if allocation error esp_tls_t *esp_tls_conn_http_new(const char *url, const esp_tls_cfg_t *cfg) Create a new blocking TLS/SSL connection with a given "HTTP" url. Note: This API is present for backward compatibility reasons. Alternative function with the same functionality is esp_tls_conn_http_new_sync (and its asynchronous version esp_tls_conn_http_new_async ) Parameters url -- [in] url of host. cfg -- [in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection, keep this NULL. For TLS connection, a pass pointer to 'esp_tls_cfg_t'. At a minimum, this structure should be zero-initialized. url -- [in] url of host. cfg -- [in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection, keep this NULL. For TLS connection, a pass pointer to 'esp_tls_cfg_t'. At a minimum, this structure should be zero-initialized. url -- [in] url of host. Returns pointer to esp_tls_t, or NULL if connection couldn't be opened. Parameters url -- [in] url of host. cfg -- [in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection, keep this NULL. For TLS connection, a pass pointer to 'esp_tls_cfg_t'. At a minimum, this structure should be zero-initialized. Returns pointer to esp_tls_t, or NULL if connection couldn't be opened. int esp_tls_conn_new_sync(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls) Create a new blocking TLS/SSL connection. This function establishes a TLS/SSL connection with the specified host in blocking manner. Parameters hostname -- [in] Hostname of the host. hostlen -- [in] Length of hostname. port -- [in] Port number of the host. cfg -- [in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection, keep this NULL. For TLS connection, a pass pointer to esp_tls_cfg_t. At a minimum, this structure should be zero-initialized. tls -- [in] Pointer to esp-tls as esp-tls handle. hostname -- [in] Hostname of the host. hostlen -- [in] Length of hostname. port -- [in] Port number of the host. cfg -- [in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection, keep this NULL. For TLS connection, a pass pointer to esp_tls_cfg_t. At a minimum, this structure should be zero-initialized. tls -- [in] Pointer to esp-tls as esp-tls handle. hostname -- [in] Hostname of the host. Returns -1 If connection establishment fails. 1 If connection establishment is successful. 0 If connection state is in progress. -1 If connection establishment fails. 1 If connection establishment is successful. 0 If connection state is in progress. -1 If connection establishment fails. Parameters hostname -- [in] Hostname of the host. hostlen -- [in] Length of hostname. port -- [in] Port number of the host. cfg -- [in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection, keep this NULL. For TLS connection, a pass pointer to esp_tls_cfg_t. At a minimum, this structure should be zero-initialized. tls -- [in] Pointer to esp-tls as esp-tls handle. Returns -1 If connection establishment fails. 1 If connection establishment is successful. 0 If connection state is in progress. int esp_tls_conn_http_new_sync(const char *url, const esp_tls_cfg_t *cfg, esp_tls_t *tls) Create a new blocking TLS/SSL connection with a given "HTTP" url. The behaviour is same as esp_tls_conn_new_sync() API. However this API accepts host's url. Parameters url -- [in] url of host. cfg -- [in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection, keep this NULL. For TLS connection, a pass pointer to 'esp_tls_cfg_t'. At a minimum, this structure should be zero-initialized. tls -- [in] Pointer to esp-tls as esp-tls handle. url -- [in] url of host. cfg -- [in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection, keep this NULL. For TLS connection, a pass pointer to 'esp_tls_cfg_t'. At a minimum, this structure should be zero-initialized. tls -- [in] Pointer to esp-tls as esp-tls handle. url -- [in] url of host. Returns -1 If connection establishment fails. 1 If connection establishment is successful. 0 If connection state is in progress. -1 If connection establishment fails. 1 If connection establishment is successful. 0 If connection state is in progress. -1 If connection establishment fails. Parameters url -- [in] url of host. cfg -- [in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection, keep this NULL. For TLS connection, a pass pointer to 'esp_tls_cfg_t'. At a minimum, this structure should be zero-initialized. tls -- [in] Pointer to esp-tls as esp-tls handle. Returns -1 If connection establishment fails. 1 If connection establishment is successful. 0 If connection state is in progress. int esp_tls_conn_new_async(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls) Create a new non-blocking TLS/SSL connection. This function initiates a non-blocking TLS/SSL connection with the specified host, but due to its non-blocking nature, it doesn't wait for the connection to get established. Parameters hostname -- [in] Hostname of the host. hostlen -- [in] Length of hostname. port -- [in] Port number of the host. cfg -- [in] TLS configuration as esp_tls_cfg_t. non_block member of this structure should be set to be true. tls -- [in] pointer to esp-tls as esp-tls handle. hostname -- [in] Hostname of the host. hostlen -- [in] Length of hostname. port -- [in] Port number of the host. cfg -- [in] TLS configuration as esp_tls_cfg_t. non_block member of this structure should be set to be true. tls -- [in] pointer to esp-tls as esp-tls handle. hostname -- [in] Hostname of the host. Returns -1 If connection establishment fails. 0 If connection establishment is in progress. 1 If connection establishment is successful. -1 If connection establishment fails. 0 If connection establishment is in progress. 1 If connection establishment is successful. -1 If connection establishment fails. Parameters hostname -- [in] Hostname of the host. hostlen -- [in] Length of hostname. port -- [in] Port number of the host. cfg -- [in] TLS configuration as esp_tls_cfg_t. non_block member of this structure should be set to be true. tls -- [in] pointer to esp-tls as esp-tls handle. Returns -1 If connection establishment fails. 0 If connection establishment is in progress. 1 If connection establishment is successful. int esp_tls_conn_http_new_async(const char *url, const esp_tls_cfg_t *cfg, esp_tls_t *tls) Create a new non-blocking TLS/SSL connection with a given "HTTP" url. The behaviour is same as esp_tls_conn_new_async() API. However this API accepts host's url. Parameters url -- [in] url of host. cfg -- [in] TLS configuration as esp_tls_cfg_t. tls -- [in] pointer to esp-tls as esp-tls handle. url -- [in] url of host. cfg -- [in] TLS configuration as esp_tls_cfg_t. tls -- [in] pointer to esp-tls as esp-tls handle. url -- [in] url of host. Returns -1 If connection establishment fails. 0 If connection establishment is in progress. 1 If connection establishment is successful. -1 If connection establishment fails. 0 If connection establishment is in progress. 1 If connection establishment is successful. -1 If connection establishment fails. Parameters url -- [in] url of host. cfg -- [in] TLS configuration as esp_tls_cfg_t. tls -- [in] pointer to esp-tls as esp-tls handle. Returns -1 If connection establishment fails. 0 If connection establishment is in progress. 1 If connection establishment is successful. ssize_t esp_tls_conn_write(esp_tls_t *tls, const void *data, size_t datalen) Write from buffer 'data' into specified tls connection. Parameters tls -- [in] pointer to esp-tls as esp-tls handle. data -- [in] Buffer from which data will be written. datalen -- [in] Length of data buffer. tls -- [in] pointer to esp-tls as esp-tls handle. data -- [in] Buffer from which data will be written. datalen -- [in] Length of data buffer. tls -- [in] pointer to esp-tls as esp-tls handle. Returns >=0 if write operation was successful, the return value is the number of bytes actually written to the TLS/SSL connection. <0 if write operation was not successful, because either an error occured or an action must be taken by the calling process. ESP_TLS_ERR_SSL_WANT_READ/ ESP_TLS_ERR_SSL_WANT_WRITE. if the handshake is incomplete and waiting for data to be available for reading. In this case this functions needs to be called again when the underlying transport is ready for operation. >=0 if write operation was successful, the return value is the number of bytes actually written to the TLS/SSL connection. <0 if write operation was not successful, because either an error occured or an action must be taken by the calling process. ESP_TLS_ERR_SSL_WANT_READ/ ESP_TLS_ERR_SSL_WANT_WRITE. if the handshake is incomplete and waiting for data to be available for reading. In this case this functions needs to be called again when the underlying transport is ready for operation. >=0 if write operation was successful, the return value is the number of bytes actually written to the TLS/SSL connection. Parameters tls -- [in] pointer to esp-tls as esp-tls handle. data -- [in] Buffer from which data will be written. datalen -- [in] Length of data buffer. Returns >=0 if write operation was successful, the return value is the number of bytes actually written to the TLS/SSL connection. <0 if write operation was not successful, because either an error occured or an action must be taken by the calling process. ESP_TLS_ERR_SSL_WANT_READ/ ESP_TLS_ERR_SSL_WANT_WRITE. if the handshake is incomplete and waiting for data to be available for reading. In this case this functions needs to be called again when the underlying transport is ready for operation. ssize_t esp_tls_conn_read(esp_tls_t *tls, void *data, size_t datalen) Read from specified tls connection into the buffer 'data'. Parameters tls -- [in] pointer to esp-tls as esp-tls handle. data -- [in] Buffer to hold read data. datalen -- [in] Length of data buffer. tls -- [in] pointer to esp-tls as esp-tls handle. data -- [in] Buffer to hold read data. datalen -- [in] Length of data buffer. tls -- [in] pointer to esp-tls as esp-tls handle. Returns >0 if read operation was successful, the return value is the number of bytes actually read from the TLS/SSL connection. 0 if read operation was not successful. The underlying connection was closed. <0 if read operation was not successful, because either an error occured or an action must be taken by the calling process. >0 if read operation was successful, the return value is the number of bytes actually read from the TLS/SSL connection. 0 if read operation was not successful. The underlying connection was closed. <0 if read operation was not successful, because either an error occured or an action must be taken by the calling process. >0 if read operation was successful, the return value is the number of bytes actually read from the TLS/SSL connection. Parameters tls -- [in] pointer to esp-tls as esp-tls handle. data -- [in] Buffer to hold read data. datalen -- [in] Length of data buffer. Returns >0 if read operation was successful, the return value is the number of bytes actually read from the TLS/SSL connection. 0 if read operation was not successful. The underlying connection was closed. <0 if read operation was not successful, because either an error occured or an action must be taken by the calling process. int esp_tls_conn_destroy(esp_tls_t *tls) Close the TLS/SSL connection and free any allocated resources. This function should be called to close each tls connection opened with esp_tls_conn_new_sync() (or esp_tls_conn_http_new_sync()) and esp_tls_conn_new_async() (or esp_tls_conn_http_new_async()) APIs. Parameters tls -- [in] pointer to esp-tls as esp-tls handle. Returns - 0 on success -1 if socket error or an invalid argument -1 if socket error or an invalid argument -1 if socket error or an invalid argument Parameters tls -- [in] pointer to esp-tls as esp-tls handle. Returns - 0 on success -1 if socket error or an invalid argument ssize_t esp_tls_get_bytes_avail(esp_tls_t *tls) Return the number of application data bytes remaining to be read from the current record. This API is a wrapper over mbedtls's mbedtls_ssl_get_bytes_avail() API. Parameters tls -- [in] pointer to esp-tls as esp-tls handle. Returns -1 in case of invalid arg bytes available in the application data record read buffer -1 in case of invalid arg bytes available in the application data record read buffer -1 in case of invalid arg Parameters tls -- [in] pointer to esp-tls as esp-tls handle. Returns -1 in case of invalid arg bytes available in the application data record read buffer esp_err_t esp_tls_get_conn_sockfd(esp_tls_t *tls, int *sockfd) Returns the connection socket file descriptor from esp_tls session. Parameters tls -- [in] handle to esp_tls context sockfd -- [out] int pointer to sockfd value. tls -- [in] handle to esp_tls context sockfd -- [out] int pointer to sockfd value. tls -- [in] handle to esp_tls context Returns - ESP_OK on success and value of sockfd will be updated with socket file descriptor for connection ESP_ERR_INVALID_ARG if (tls == NULL || sockfd == NULL) ESP_ERR_INVALID_ARG if (tls == NULL || sockfd == NULL) ESP_ERR_INVALID_ARG if (tls == NULL || sockfd == NULL) Parameters tls -- [in] handle to esp_tls context sockfd -- [out] int pointer to sockfd value. Returns - ESP_OK on success and value of sockfd will be updated with socket file descriptor for connection ESP_ERR_INVALID_ARG if (tls == NULL || sockfd == NULL) esp_err_t esp_tls_set_conn_sockfd(esp_tls_t *tls, int sockfd) Sets the connection socket file descriptor for the esp_tls session. Parameters tls -- [in] handle to esp_tls context sockfd -- [in] sockfd value to set. tls -- [in] handle to esp_tls context sockfd -- [in] sockfd value to set. tls -- [in] handle to esp_tls context Returns - ESP_OK on success and value of sockfd for the tls connection shall updated withthe provided value ESP_ERR_INVALID_ARG if (tls == NULL || sockfd < 0) ESP_ERR_INVALID_ARG if (tls == NULL || sockfd < 0) ESP_ERR_INVALID_ARG if (tls == NULL || sockfd < 0) Parameters tls -- [in] handle to esp_tls context sockfd -- [in] sockfd value to set. Returns - ESP_OK on success and value of sockfd for the tls connection shall updated withthe provided value ESP_ERR_INVALID_ARG if (tls == NULL || sockfd < 0) esp_err_t esp_tls_get_conn_state(esp_tls_t *tls, esp_tls_conn_state_t *conn_state) Gets the connection state for the esp_tls session. Parameters tls -- [in] handle to esp_tls context conn_state -- [out] pointer to the connection state value. tls -- [in] handle to esp_tls context conn_state -- [out] pointer to the connection state value. tls -- [in] handle to esp_tls context Returns - ESP_OK on success and value of sockfd for the tls connection shall updated withthe provided value ESP_ERR_INVALID_ARG (Invalid arguments) ESP_ERR_INVALID_ARG (Invalid arguments) ESP_ERR_INVALID_ARG (Invalid arguments) Parameters tls -- [in] handle to esp_tls context conn_state -- [out] pointer to the connection state value. Returns - ESP_OK on success and value of sockfd for the tls connection shall updated withthe provided value ESP_ERR_INVALID_ARG (Invalid arguments) esp_err_t esp_tls_set_conn_state(esp_tls_t *tls, esp_tls_conn_state_t conn_state) Sets the connection state for the esp_tls session. Parameters tls -- [in] handle to esp_tls context conn_state -- [in] connection state value to set. tls -- [in] handle to esp_tls context conn_state -- [in] connection state value to set. tls -- [in] handle to esp_tls context Returns - ESP_OK on success and value of sockfd for the tls connection shall updated withthe provided value ESP_ERR_INVALID_ARG (Invalid arguments) ESP_ERR_INVALID_ARG (Invalid arguments) ESP_ERR_INVALID_ARG (Invalid arguments) Parameters tls -- [in] handle to esp_tls context conn_state -- [in] connection state value to set. Returns - ESP_OK on success and value of sockfd for the tls connection shall updated withthe provided value ESP_ERR_INVALID_ARG (Invalid arguments) void *esp_tls_get_ssl_context(esp_tls_t *tls) Returns the ssl context. Parameters tls -- [in] handle to esp_tls context Returns - ssl_ctx pointer to ssl context of underlying TLS layer on success NULL in case of error NULL in case of error NULL in case of error Parameters tls -- [in] handle to esp_tls context Returns - ssl_ctx pointer to ssl context of underlying TLS layer on success NULL in case of error esp_err_t esp_tls_init_global_ca_store(void) Create a global CA store, initially empty. This function should be called if the application wants to use the same CA store for multiple connections. This function initialises the global CA store which can be then set by calling esp_tls_set_global_ca_store(). To be effective, this function must be called before any call to esp_tls_set_global_ca_store(). Returns ESP_OK if creating global CA store was successful. ESP_ERR_NO_MEM if an error occured when allocating the mbedTLS resources. ESP_OK if creating global CA store was successful. ESP_ERR_NO_MEM if an error occured when allocating the mbedTLS resources. ESP_OK if creating global CA store was successful. Returns ESP_OK if creating global CA store was successful. ESP_ERR_NO_MEM if an error occured when allocating the mbedTLS resources. esp_err_t esp_tls_set_global_ca_store(const unsigned char *cacert_pem_buf, const unsigned int cacert_pem_bytes) Set the global CA store with the buffer provided in pem format. This function should be called if the application wants to set the global CA store for multiple connections i.e. to add the certificates in the provided buffer to the certificate chain. This function implicitly calls esp_tls_init_global_ca_store() if it has not already been called. The application must call this function before calling esp_tls_conn_new(). Parameters cacert_pem_buf -- [in] Buffer which has certificates in pem format. This buffer is used for creating a global CA store, which can be used by other tls connections. cacert_pem_bytes -- [in] Length of the buffer. cacert_pem_buf -- [in] Buffer which has certificates in pem format. This buffer is used for creating a global CA store, which can be used by other tls connections. cacert_pem_bytes -- [in] Length of the buffer. cacert_pem_buf -- [in] Buffer which has certificates in pem format. This buffer is used for creating a global CA store, which can be used by other tls connections. Returns ESP_OK if adding certificates was successful. Other if an error occured or an action must be taken by the calling process. ESP_OK if adding certificates was successful. Other if an error occured or an action must be taken by the calling process. ESP_OK if adding certificates was successful. Parameters cacert_pem_buf -- [in] Buffer which has certificates in pem format. This buffer is used for creating a global CA store, which can be used by other tls connections. cacert_pem_bytes -- [in] Length of the buffer. Returns ESP_OK if adding certificates was successful. Other if an error occured or an action must be taken by the calling process. void esp_tls_free_global_ca_store(void) Free the global CA store currently being used. The memory being used by the global CA store to store all the parsed certificates is freed up. The application can call this API if it no longer needs the global CA store. esp_err_t esp_tls_get_and_clear_last_error(esp_tls_error_handle_t h, int *esp_tls_code, int *esp_tls_flags) Returns last error in esp_tls with detailed mbedtls related error codes. The error information is cleared internally upon return. Parameters h -- [in] esp-tls error handle. esp_tls_code -- [out] last error code returned from mbedtls api (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code esp_tls_flags -- [out] last certification verification flags (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code h -- [in] esp-tls error handle. esp_tls_code -- [out] last error code returned from mbedtls api (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code esp_tls_flags -- [out] last certification verification flags (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code h -- [in] esp-tls error handle. Returns ESP_ERR_INVALID_STATE if invalid parameters ESP_OK (0) if no error occurred specific error code (based on ESP_ERR_ESP_TLS_BASE) otherwise ESP_ERR_INVALID_STATE if invalid parameters ESP_OK (0) if no error occurred specific error code (based on ESP_ERR_ESP_TLS_BASE) otherwise ESP_ERR_INVALID_STATE if invalid parameters Parameters h -- [in] esp-tls error handle. esp_tls_code -- [out] last error code returned from mbedtls api (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code esp_tls_flags -- [out] last certification verification flags (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code Returns ESP_ERR_INVALID_STATE if invalid parameters ESP_OK (0) if no error occurred specific error code (based on ESP_ERR_ESP_TLS_BASE) otherwise esp_err_t esp_tls_get_and_clear_error_type(esp_tls_error_handle_t h, esp_tls_error_type_t err_type, int *error_code) Returns the last error captured in esp_tls of a specific type The error information is cleared internally upon return. Parameters h -- [in] esp-tls error handle. err_type -- [in] specific error type error_code -- [out] last error code returned from mbedtls api (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code h -- [in] esp-tls error handle. err_type -- [in] specific error type error_code -- [out] last error code returned from mbedtls api (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code h -- [in] esp-tls error handle. Returns ESP_ERR_INVALID_STATE if invalid parameters ESP_OK if a valid error returned and was cleared ESP_ERR_INVALID_STATE if invalid parameters ESP_OK if a valid error returned and was cleared ESP_ERR_INVALID_STATE if invalid parameters Parameters h -- [in] esp-tls error handle. err_type -- [in] specific error type error_code -- [out] last error code returned from mbedtls api (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code Returns ESP_ERR_INVALID_STATE if invalid parameters ESP_OK if a valid error returned and was cleared esp_err_t esp_tls_get_error_handle(esp_tls_t *tls, esp_tls_error_handle_t *error_handle) Returns the ESP-TLS error_handle. Parameters tls -- [in] handle to esp_tls context error_handle -- [out] pointer to the error handle. tls -- [in] handle to esp_tls context error_handle -- [out] pointer to the error handle. tls -- [in] handle to esp_tls context Returns ESP_OK on success and error_handle will be updated with the ESP-TLS error handle. ESP_ERR_INVALID_ARG if (tls == NULL || error_handle == NULL) ESP_OK on success and error_handle will be updated with the ESP-TLS error handle. ESP_ERR_INVALID_ARG if (tls == NULL || error_handle == NULL) ESP_OK on success and error_handle will be updated with the ESP-TLS error handle. Parameters tls -- [in] handle to esp_tls context error_handle -- [out] pointer to the error handle. Returns ESP_OK on success and error_handle will be updated with the ESP-TLS error handle. ESP_ERR_INVALID_ARG if (tls == NULL || error_handle == NULL) mbedtls_x509_crt *esp_tls_get_global_ca_store(void) Get the pointer to the global CA store currently being used. The application must first call esp_tls_set_global_ca_store(). Then the same CA store could be used by the application for APIs other than esp_tls. Note Modifying the pointer might cause a failure in verifying the certificates. Returns Pointer to the global CA store currently being used if successful. NULL if there is no global CA store set. Pointer to the global CA store currently being used if successful. NULL if there is no global CA store set. Pointer to the global CA store currently being used if successful. Returns Pointer to the global CA store currently being used if successful. NULL if there is no global CA store set. const int *esp_tls_get_ciphersuites_list(void) Get supported TLS ciphersuites list. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4 for the list of ciphersuites Returns Pointer to a zero-terminated array of IANA identifiers of TLS ciphersuites. Returns Pointer to a zero-terminated array of IANA identifiers of TLS ciphersuites. esp_err_t esp_tls_plain_tcp_connect(const char *host, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_error_handle_t error_handle, int *sockfd) Creates a plain TCP connection, returning a valid socket fd on success or an error handle. Parameters host -- [in] Hostname of the host. hostlen -- [in] Length of hostname. port -- [in] Port number of the host. cfg -- [in] ESP-TLS configuration as esp_tls_cfg_t. error_handle -- [out] ESP-TLS error handle holding potential errors occurred during connection sockfd -- [out] Socket descriptor if successfully connected on TCP layer host -- [in] Hostname of the host. hostlen -- [in] Length of hostname. port -- [in] Port number of the host. cfg -- [in] ESP-TLS configuration as esp_tls_cfg_t. error_handle -- [out] ESP-TLS error handle holding potential errors occurred during connection sockfd -- [out] Socket descriptor if successfully connected on TCP layer host -- [in] Hostname of the host. Returns ESP_OK on success ESP_ERR_INVALID_ARG if invalid output parameters ESP-TLS based error codes on failure Parameters host -- [in] Hostname of the host. hostlen -- [in] Length of hostname. port -- [in] Port number of the host. cfg -- [in] ESP-TLS configuration as esp_tls_cfg_t. error_handle -- [out] ESP-TLS error handle holding potential errors occurred during connection sockfd -- [out] Socket descriptor if successfully connected on TCP layer Returns ESP_OK on success ESP_ERR_INVALID_ARG if invalid output parameters ESP-TLS based error codes on failure Structures struct psk_key_hint ESP-TLS preshared key and hint structure. struct tls_keep_alive_cfg esp-tls client session ticket ctx Keep alive parameters structure struct esp_tls_cfg ESP-TLS configuration parameters. Note Note about format of certificates: This structure includes certificates of a Certificate Authority, of client or server as well as private keys, which may be of PEM or DER format. In case of PEM format, the buffer must be NULL terminated (with NULL character included in certificate size). Certificate Authority's certificate may be a chain of certificates in case of PEM format, but could be only one certificate in case of DER format Variables names of certificates and private key buffers and sizes are defined as unions providing backward compatibility for legacy *_pem_buf and *_pem_bytes names which suggested only PEM format was supported. It is encouraged to use generic names such as cacert_buf and cacert_bytes. This structure includes certificates of a Certificate Authority, of client or server as well as private keys, which may be of PEM or DER format. In case of PEM format, the buffer must be NULL terminated (with NULL character included in certificate size). Certificate Authority's certificate may be a chain of certificates in case of PEM format, but could be only one certificate in case of DER format Variables names of certificates and private key buffers and sizes are defined as unions providing backward compatibility for legacy *_pem_buf and *_pem_bytes names which suggested only PEM format was supported. It is encouraged to use generic names such as cacert_buf and cacert_bytes. Public Members const char **alpn_protos Application protocols required for HTTP2. If HTTP2/ALPN support is required, a list of protocols that should be negotiated. The format is length followed by protocol name. For the most common cases the following is ok: const char **alpn_protos = { "h2", NULL }; where 'h2' is the protocol name where 'h2' is the protocol name where 'h2' is the protocol name const char **alpn_protos Application protocols required for HTTP2. If HTTP2/ALPN support is required, a list of protocols that should be negotiated. The format is length followed by protocol name. For the most common cases the following is ok: const char **alpn_protos = { "h2", NULL }; where 'h2' is the protocol name const unsigned char *cacert_buf Certificate Authority's certificate in a buffer. Format may be PEM or DER, depending on mbedtls-support This buffer should be NULL terminated in case of PEM const unsigned char *cacert_buf Certificate Authority's certificate in a buffer. Format may be PEM or DER, depending on mbedtls-support This buffer should be NULL terminated in case of PEM const unsigned char *cacert_pem_buf CA certificate buffer legacy name const unsigned char *cacert_pem_buf CA certificate buffer legacy name unsigned int cacert_bytes Size of Certificate Authority certificate pointed to by cacert_buf (including NULL-terminator in case of PEM format) unsigned int cacert_bytes Size of Certificate Authority certificate pointed to by cacert_buf (including NULL-terminator in case of PEM format) unsigned int cacert_pem_bytes Size of Certificate Authority certificate legacy name unsigned int cacert_pem_bytes Size of Certificate Authority certificate legacy name const unsigned char *clientcert_buf Client certificate in a buffer Format may be PEM or DER, depending on mbedtls-support This buffer should be NULL terminated in case of PEM const unsigned char *clientcert_buf Client certificate in a buffer Format may be PEM or DER, depending on mbedtls-support This buffer should be NULL terminated in case of PEM const unsigned char *clientcert_pem_buf Client certificate legacy name const unsigned char *clientcert_pem_buf Client certificate legacy name unsigned int clientcert_bytes Size of client certificate pointed to by clientcert_pem_buf (including NULL-terminator in case of PEM format) unsigned int clientcert_bytes Size of client certificate pointed to by clientcert_pem_buf (including NULL-terminator in case of PEM format) unsigned int clientcert_pem_bytes Size of client certificate legacy name unsigned int clientcert_pem_bytes Size of client certificate legacy name const unsigned char *clientkey_buf Client key in a buffer Format may be PEM or DER, depending on mbedtls-support This buffer should be NULL terminated in case of PEM const unsigned char *clientkey_buf Client key in a buffer Format may be PEM or DER, depending on mbedtls-support This buffer should be NULL terminated in case of PEM const unsigned char *clientkey_pem_buf Client key legacy name const unsigned char *clientkey_pem_buf Client key legacy name unsigned int clientkey_bytes Size of client key pointed to by clientkey_pem_buf (including NULL-terminator in case of PEM format) unsigned int clientkey_bytes Size of client key pointed to by clientkey_pem_buf (including NULL-terminator in case of PEM format) unsigned int clientkey_pem_bytes Size of client key legacy name unsigned int clientkey_pem_bytes Size of client key legacy name const unsigned char *clientkey_password Client key decryption password string const unsigned char *clientkey_password Client key decryption password string unsigned int clientkey_password_len String length of the password pointed to by clientkey_password unsigned int clientkey_password_len String length of the password pointed to by clientkey_password bool use_ecdsa_peripheral Use the ECDSA peripheral for the private key operations bool use_ecdsa_peripheral Use the ECDSA peripheral for the private key operations uint8_t ecdsa_key_efuse_blk The efuse block where the ECDSA key is stored uint8_t ecdsa_key_efuse_blk The efuse block where the ECDSA key is stored bool non_block Configure non-blocking mode. If set to true the underneath socket will be configured in non blocking mode after tls session is established bool non_block Configure non-blocking mode. If set to true the underneath socket will be configured in non blocking mode after tls session is established bool use_secure_element Enable this option to use secure element or atecc608a chip ( Integrated with ESP32-WROOM-32SE ) bool use_secure_element Enable this option to use secure element or atecc608a chip ( Integrated with ESP32-WROOM-32SE ) int timeout_ms Network timeout in milliseconds. Note: If this value is not set, by default the timeout is set to 10 seconds. If you wish that the session should wait indefinitely then please use a larger value e.g., INT32_MAX int timeout_ms Network timeout in milliseconds. Note: If this value is not set, by default the timeout is set to 10 seconds. If you wish that the session should wait indefinitely then please use a larger value e.g., INT32_MAX bool use_global_ca_store Use a global ca_store for all the connections in which this bool is set. bool use_global_ca_store Use a global ca_store for all the connections in which this bool is set. const char *common_name If non-NULL, server certificate CN must match this name. If NULL, server certificate CN must match hostname. const char *common_name If non-NULL, server certificate CN must match this name. If NULL, server certificate CN must match hostname. bool skip_common_name Skip any validation of server certificate CN field bool skip_common_name Skip any validation of server certificate CN field tls_keep_alive_cfg_t *keep_alive_cfg Enable TCP keep-alive timeout for SSL connection tls_keep_alive_cfg_t *keep_alive_cfg Enable TCP keep-alive timeout for SSL connection const psk_hint_key_t *psk_hint_key Pointer to PSK hint and key. if not NULL (and certificates are NULL) then PSK authentication is enabled with configured setup. Important note: the pointer must be valid for connection const psk_hint_key_t *psk_hint_key Pointer to PSK hint and key. if not NULL (and certificates are NULL) then PSK authentication is enabled with configured setup. Important note: the pointer must be valid for connection esp_err_t (*crt_bundle_attach)(void *conf) Function pointer to esp_crt_bundle_attach. Enables the use of certification bundle for server verification, must be enabled in menuconfig esp_err_t (*crt_bundle_attach)(void *conf) Function pointer to esp_crt_bundle_attach. Enables the use of certification bundle for server verification, must be enabled in menuconfig void *ds_data Pointer for digital signature peripheral context void *ds_data Pointer for digital signature peripheral context bool is_plain_tcp Use non-TLS connection: When set to true, the esp-tls uses plain TCP transport rather then TLS/SSL connection. Note, that it is possible to connect using a plain tcp transport directly with esp_tls_plain_tcp_connect() API bool is_plain_tcp Use non-TLS connection: When set to true, the esp-tls uses plain TCP transport rather then TLS/SSL connection. Note, that it is possible to connect using a plain tcp transport directly with esp_tls_plain_tcp_connect() API struct ifreq *if_name The name of interface for data to go through. Use the default interface without setting struct ifreq *if_name The name of interface for data to go through. Use the default interface without setting esp_tls_addr_family_t addr_family The address family to use when connecting to a host. esp_tls_addr_family_t addr_family The address family to use when connecting to a host. const int *ciphersuites_list Pointer to a zero-terminated array of IANA identifiers of TLS ciphersuites. Please check the list validity by esp_tls_get_ciphersuites_list() API const int *ciphersuites_list Pointer to a zero-terminated array of IANA identifiers of TLS ciphersuites. Please check the list validity by esp_tls_get_ciphersuites_list() API esp_tls_proto_ver_t tls_version TLS protocol version of the connection, e.g., TLS 1.2, TLS 1.3 (default - no preference) esp_tls_proto_ver_t tls_version TLS protocol version of the connection, e.g., TLS 1.2, TLS 1.3 (default - no preference) This structure includes certificates of a Certificate Authority, of client or server as well as private keys, which may be of PEM or DER format. In case of PEM format, the buffer must be NULL terminated (with NULL character included in certificate size). Type Definitions typedef enum esp_tls_conn_state esp_tls_conn_state_t ESP-TLS Connection State. typedef enum esp_tls_role esp_tls_role_t typedef struct psk_key_hint psk_hint_key_t ESP-TLS preshared key and hint structure. typedef struct tls_keep_alive_cfg tls_keep_alive_cfg_t esp-tls client session ticket ctx Keep alive parameters structure typedef enum esp_tls_addr_family esp_tls_addr_family_t typedef struct esp_tls_cfg esp_tls_cfg_t ESP-TLS configuration parameters. Note Note about format of certificates: This structure includes certificates of a Certificate Authority, of client or server as well as private keys, which may be of PEM or DER format. In case of PEM format, the buffer must be NULL terminated (with NULL character included in certificate size). Certificate Authority's certificate may be a chain of certificates in case of PEM format, but could be only one certificate in case of DER format Variables names of certificates and private key buffers and sizes are defined as unions providing backward compatibility for legacy *_pem_buf and *_pem_bytes names which suggested only PEM format was supported. It is encouraged to use generic names such as cacert_buf and cacert_bytes. This structure includes certificates of a Certificate Authority, of client or server as well as private keys, which may be of PEM or DER format. In case of PEM format, the buffer must be NULL terminated (with NULL character included in certificate size). Certificate Authority's certificate may be a chain of certificates in case of PEM format, but could be only one certificate in case of DER format Variables names of certificates and private key buffers and sizes are defined as unions providing backward compatibility for legacy *_pem_buf and *_pem_bytes names which suggested only PEM format was supported. It is encouraged to use generic names such as cacert_buf and cacert_bytes. This structure includes certificates of a Certificate Authority, of client or server as well as private keys, which may be of PEM or DER format. In case of PEM format, the buffer must be NULL terminated (with NULL character included in certificate size). typedef struct esp_tls esp_tls_t Enumerations enum esp_tls_conn_state ESP-TLS Connection State. Values: enumerator ESP_TLS_INIT enumerator ESP_TLS_INIT enumerator ESP_TLS_CONNECTING enumerator ESP_TLS_CONNECTING enumerator ESP_TLS_HANDSHAKE enumerator ESP_TLS_HANDSHAKE enumerator ESP_TLS_FAIL enumerator ESP_TLS_FAIL enumerator ESP_TLS_DONE enumerator ESP_TLS_DONE enumerator ESP_TLS_INIT enum esp_tls_addr_family Values: enumerator ESP_TLS_AF_UNSPEC Unspecified address family. enumerator ESP_TLS_AF_UNSPEC Unspecified address family. enumerator ESP_TLS_AF_INET IPv4 address family. enumerator ESP_TLS_AF_INET IPv4 address family. enumerator ESP_TLS_AF_INET6 IPv6 address family. enumerator ESP_TLS_AF_INET6 IPv6 address family. enumerator ESP_TLS_AF_UNSPEC Header File This header file can be included with: #include "esp_tls_errors.h" This header file is a part of the API provided by the esp-tls component. To declare that your component depends on esp-tls , add the following to your CMakeLists.txt: REQUIRES esp-tls or PRIV_REQUIRES esp-tls Structures struct esp_tls_last_error Error structure containing relevant errors in case tls error occurred. Macros ESP_ERR_ESP_TLS_BASE Starting number of ESP-TLS error codes ESP_ERR_ESP_TLS_CANNOT_RESOLVE_HOSTNAME Error if hostname couldn't be resolved upon tls connection ESP_ERR_ESP_TLS_CANNOT_CREATE_SOCKET Failed to create socket ESP_ERR_ESP_TLS_UNSUPPORTED_PROTOCOL_FAMILY Unsupported protocol family ESP_ERR_ESP_TLS_FAILED_CONNECT_TO_HOST Failed to connect to host ESP_ERR_ESP_TLS_SOCKET_SETOPT_FAILED failed to set/get socket option ESP_ERR_ESP_TLS_CONNECTION_TIMEOUT new connection in esp_tls_low_level_conn connection timeouted ESP_ERR_ESP_TLS_SE_FAILED ESP_ERR_ESP_TLS_TCP_CLOSED_FIN ESP_ERR_MBEDTLS_CERT_PARTLY_OK mbedtls parse certificates was partly successful ESP_ERR_MBEDTLS_CTR_DRBG_SEED_FAILED mbedtls api returned error ESP_ERR_MBEDTLS_SSL_SET_HOSTNAME_FAILED mbedtls api returned error ESP_ERR_MBEDTLS_SSL_CONFIG_DEFAULTS_FAILED mbedtls api returned error ESP_ERR_MBEDTLS_SSL_CONF_ALPN_PROTOCOLS_FAILED mbedtls api returned error ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED mbedtls api returned error ESP_ERR_MBEDTLS_SSL_CONF_OWN_CERT_FAILED mbedtls api returned error ESP_ERR_MBEDTLS_SSL_SETUP_FAILED mbedtls api returned error ESP_ERR_MBEDTLS_SSL_WRITE_FAILED mbedtls api returned error ESP_ERR_MBEDTLS_PK_PARSE_KEY_FAILED mbedtls api returned failed ESP_ERR_MBEDTLS_SSL_HANDSHAKE_FAILED mbedtls api returned failed ESP_ERR_MBEDTLS_SSL_CONF_PSK_FAILED mbedtls api returned failed ESP_ERR_MBEDTLS_SSL_TICKET_SETUP_FAILED mbedtls api returned failed ESP_ERR_WOLFSSL_SSL_SET_HOSTNAME_FAILED wolfSSL api returned error ESP_ERR_WOLFSSL_SSL_CONF_ALPN_PROTOCOLS_FAILED wolfSSL api returned error ESP_ERR_WOLFSSL_CERT_VERIFY_SETUP_FAILED wolfSSL api returned error ESP_ERR_WOLFSSL_KEY_VERIFY_SETUP_FAILED wolfSSL api returned error ESP_ERR_WOLFSSL_SSL_HANDSHAKE_FAILED wolfSSL api returned failed ESP_ERR_WOLFSSL_CTX_SETUP_FAILED wolfSSL api returned failed ESP_ERR_WOLFSSL_SSL_SETUP_FAILED wolfSSL api returned failed ESP_ERR_WOLFSSL_SSL_WRITE_FAILED wolfSSL api returned failed ESP_TLS_ERR_SSL_WANT_READ Definition of errors reported from IO API (potentially non-blocking) in case of error: esp_tls_conn_read() esp_tls_conn_write() esp_tls_conn_read() esp_tls_conn_write() esp_tls_conn_read() ESP_TLS_ERR_SSL_WANT_WRITE ESP_TLS_ERR_SSL_TIMEOUT Type Definitions typedef struct esp_tls_last_error *esp_tls_error_handle_t typedef struct esp_tls_last_error esp_tls_last_error_t Error structure containing relevant errors in case tls error occurred. Enumerations enum esp_tls_error_type_t Definition of different types/sources of error codes reported from different components Values: enumerator ESP_TLS_ERR_TYPE_UNKNOWN enumerator ESP_TLS_ERR_TYPE_UNKNOWN enumerator ESP_TLS_ERR_TYPE_SYSTEM System error – errno enumerator ESP_TLS_ERR_TYPE_SYSTEM System error – errno enumerator ESP_TLS_ERR_TYPE_MBEDTLS Error code from mbedTLS library enumerator ESP_TLS_ERR_TYPE_MBEDTLS Error code from mbedTLS library enumerator ESP_TLS_ERR_TYPE_MBEDTLS_CERT_FLAGS Certificate flags defined in mbedTLS enumerator ESP_TLS_ERR_TYPE_MBEDTLS_CERT_FLAGS Certificate flags defined in mbedTLS enumerator ESP_TLS_ERR_TYPE_ESP ESP-IDF error type – esp_err_t enumerator ESP_TLS_ERR_TYPE_ESP ESP-IDF error type – esp_err_t enumerator ESP_TLS_ERR_TYPE_WOLFSSL Error code from wolfSSL library enumerator ESP_TLS_ERR_TYPE_WOLFSSL Error code from wolfSSL library enumerator ESP_TLS_ERR_TYPE_WOLFSSL_CERT_FLAGS Certificate flags defined in wolfSSL enumerator ESP_TLS_ERR_TYPE_WOLFSSL_CERT_FLAGS Certificate flags defined in wolfSSL enumerator ESP_TLS_ERR_TYPE_MAX Last err type – invalid entry enumerator ESP_TLS_ERR_TYPE_MAX Last err type – invalid entry enumerator ESP_TLS_ERR_TYPE_UNKNOWN
ESP-TLS Overview The ESP-TLS component provides a simplified API interface for accessing the commonly used TLS functions. It supports common scenarios like CA certification validation, SNI, ALPN negotiation, and non-blocking connection among others. All the configurations can be specified in the esp_tls_cfg_t data structure. Once done, TLS communication can be conducted using the following APIs: - esp_tls_init(): for initializing the TLS connection handle. - esp_tls_conn_new_sync(): for opening a new blocking TLS connection. - esp_tls_conn_new_async(): for opening a new non-blocking TLS connection. - esp_tls_conn_read(): for reading from the connection. - esp_tls_conn_write(): for writing into the connection. - esp_tls_conn_destroy(): for freeing up the connection. Any application layer protocol like HTTP1, HTTP2, etc can be executed on top of this layer. Application Example Simple HTTPS example that uses ESP-TLS to establish a secure socket connection: protocols/https_request. Tree Structure for ESP-TLS Component ├── esp_tls.c ├── esp_tls.h ├── esp_tls_mbedtls.c ├── esp_tls_wolfssl.c └── private_include ├── esp_tls_mbedtls.h └── esp_tls_wolfssl.h The ESP-TLS component has a file esp-tls/esp_tls.h which contains the public API headers for the component. Internally, the ESP-TLS component operates using either MbedTLS or WolfSSL, which are SSL/TLS libraries. APIs specific to MbedTLS are present in esp-tls/private_include/esp_tls_mbedtls.h and APIs specific to WolfSSL are present in esp-tls/private_include/esp_tls_wolfssl.h. TLS Server Verification ESP-TLS provides multiple options for TLS server verification on the client side. The ESP-TLS client can verify the server by validating the peer's server certificate or with the help of pre-shared keys. The user should select only one of the following options in the esp_tls_cfg_t structure for TLS server verification. If no option is selected, the client will return a fatal error by default during the TLS connection setup. - cacert_buf and cacert_bytes: The CA certificate can be provided in a buffer to the esp_tls_cfg_tstructure. The ESP-TLS uses the CA certificate present in the buffer to verify the server. The following variables in the esp_tls_cfg_tstructure must be set. - cacert_buf- pointer to the buffer which contains the CA certification. - cacert_bytes- the size of the CA certificate in bytes. - use_global_ca_store: The global_ca_storecan be initialized and set at once. Then it can be used to verify the server for all the ESP-TLS connections which have set use_global_ca_store = truein their respective esp_tls_cfg_tstructure. See the API Reference section below for information regarding different APIs used for initializing and setting up the global_ca_store. - crt_bundle_attach: The ESP x509 Certificate Bundle API provides an easy way to include a bundle of custom x509 root certificates for TLS server verification. More details can be found at ESP x509 Certificate Bundle. - psk_hint_key: To use pre-shared keys for server verification, CONFIG_ESP_TLS_PSK_VERIFICATION should be enabled in the ESP-TLS menuconfig. Then the pointer to the PSK hint and key should be provided to the esp_tls_cfg_tstructure. The ESP-TLS will use the PSK for server verification only when no other option regarding server verification is selected. - skip server verification: This is an insecure option provided in the ESP-TLS for testing purposes. The option can be set by enabling CONFIG_ESP_TLS_INSECURE and CONFIG_ESP_TLS_SKIP_SERVER_CERT_VERIFY in the ESP-TLS menuconfig. When this option is enabled the ESP-TLS will skip server verification by default when no other options for server verification are selected in the esp_tls_cfg_tstructure. Warning Enabling this option comes with a potential risk of establishing a TLS connection with a server that has a fake identity, provided that the server certificate is not provided either through API or other mechanisms like ca_store etc. ESP-TLS Server Cert Selection Hook The ESP-TLS component provides an option to set the server certification selection hook when using the MbedTLS stack. This provides an ability to configure and use a certificate selection callback during server handshake. The callback helps to select a certificate to present to the client based on the TLS extensions supplied in the client hello message, such as ALPN and SNI. To enable this feature, please enable CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK in the ESP-TLS menuconfig. The certificate selection callback can be configured in the esp_tls_cfg_t structure as follows: int cert_selection_callback(mbedtls_ssl_context *ssl) { /* Code that the callback should execute */ return 0; } esp_tls_cfg_t cfg = { cert_select_cb = cert_section_callback, }; Underlying SSL/TLS Library Options The ESP-TLS component offers the option to use MbedTLS or WolfSSL as its underlying SSL/TLS library. By default, only MbedTLS is available and used, WolfSSL SSL/TLS library is also available publicly at https://github.com/espressif/esp-wolfssl. The repository provides the WolfSSL component in binary format, and it also provides a few examples that are useful for understanding the API. Please refer to the repository README.md for information on licensing and other options. Please see the below section for instructions on how to use WolfSSL in your project. Note As the library options are internal to ESP-TLS, switching the libraries will not change ESP-TLS specific code for a project. How to Use WolfSSL with ESP-IDF There are two ways to use WolfSSL in your project: Directly add WolfSSL as a component in your project with the following three commands: (First, change the directory (cd) to your project directory) mkdir components cd components git clone --recursive https://github.com/espressif/esp-wolfssl.git Add WolfSSL as an extra component in your project. Download WolfSSL with: git clone --recursive https://github.com/espressif/esp-wolfssl.git Include ESP-WolfSSL in ESP-IDF with setting EXTRA_COMPONENT_DIRSin CMakeLists.txtof your project as done in wolfssl/examples. For reference see Optional Project Variables in build-system.. After the above steps, you will have the option to choose WolfSSL as the underlying SSL/TLS library in the configuration menu of your project as follows: idf.py menuconfig > ESP-TLS > SSL/TLS Library > Mbedtls/Wolfssl Comparison Between MbedTLS and WolfSSL The following table shows a typical comparison between WolfSSL and MbedTLS when the protocols/https_request example (which includes server authentication) is running with both SSL/TLS libraries and with all respective configurations set to default. For MbedTLS, the IN_CONTENT length and OUT_CONTENT length are set to 16384 bytes and 4096 bytes respectively. | Property | WolfSSL | MbedTLS | Total Heap Consumed | ~ 19 KB | ~ 37 KB | Task Stack Used | ~ 2.2 KB | ~ 3.6 KB | Bin size | ~ 858 KB | ~ 736 KB Note These values can vary based on configuration options and version of respective libraries. ATECC608A (Secure Element) with ESP-TLS ESP-TLS provides support for using ATECC608A cryptoauth chip with ESP32-WROOM-32SE. The use of ATECC608A is supported only when ESP-TLS is used with MbedTLS as its underlying SSL/TLS stack. ESP-TLS uses MbedTLS as its underlying TLS/SSL stack by default unless changed manually. Note ATECC608A chip on ESP32-WROOM-32SE must be already configured, for details refer esp_cryptoauth_utility. To enable the secure element support, and use it in your project for TLS connection, you have to follow the below steps: Add esp-cryptoauthlib in your project, for details please refer how to use esp-cryptoauthlib with ESP-IDF. Enable the following menuconfig option: menuconfig > Component config > ESP-TLS > Use Secure Element (ATECC608A) with ESP-TLS Select type of ATECC608A chip with following option: menuconfig > Component config > esp-cryptoauthlib > Choose Type of ATECC608A chip To know more about different types of ATECC608A chips and how to obtain the type of ATECC608A connected to your ESP module, please visit ATECC608A chip type. Enable the use of ATECC608A in ESP-TLS by providing the following config option in esp_tls_cfg_t. esp_tls_cfg_t cfg = { /* other configurations options */ .use_secure_element = true, }; TLS Ciphersuites ESP-TLS provides the ability to set a ciphersuites list in client mode. The TLS ciphersuites list informs the server about the supported ciphersuites for the specific TLS connection regardless of the TLS stack configuration. If the server supports any ciphersuite from this list, then the TLS connection will succeed; otherwise, it will fail. You can set ciphersuites_list in the esp_tls_cfg_t structure during client connection as follows: /* ciphersuites_list must end with 0 and must be available in the memory scope active during the entire TLS connection */ static const int ciphersuites_list[] = {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 0}; esp_tls_cfg_t cfg = { .ciphersuites_list = ciphersuites_list, }; ESP-TLS will not check the validity of ciphersuites_list that was set, you should call esp_tls_get_ciphersuites_list() to get ciphersuites list supported in the TLS stack and cross-check it against the supplied list. Note This feature is supported only in the MbedTLS stack. API Reference Header File This header file can be included with: #include "esp_tls.h" This header file is a part of the API provided by the esp-tlscomponent. To declare that your component depends on esp-tls, add the following to your CMakeLists.txt: REQUIRES esp-tls or PRIV_REQUIRES esp-tls Functions - esp_tls_t *esp_tls_init(void) Create TLS connection. This function allocates and initializes esp-tls structure handle. - Returns tls Pointer to esp-tls as esp-tls handle if successfully initialized, NULL if allocation error - esp_tls_t *esp_tls_conn_http_new(const char *url, const esp_tls_cfg_t *cfg) Create a new blocking TLS/SSL connection with a given "HTTP" url. Note: This API is present for backward compatibility reasons. Alternative function with the same functionality is esp_tls_conn_http_new_sync(and its asynchronous version esp_tls_conn_http_new_async) - Parameters url -- [in] url of host. cfg -- [in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection, keep this NULL. For TLS connection, a pass pointer to 'esp_tls_cfg_t'. At a minimum, this structure should be zero-initialized. - - Returns pointer to esp_tls_t, or NULL if connection couldn't be opened. - int esp_tls_conn_new_sync(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls) Create a new blocking TLS/SSL connection. This function establishes a TLS/SSL connection with the specified host in blocking manner. - Parameters hostname -- [in] Hostname of the host. hostlen -- [in] Length of hostname. port -- [in] Port number of the host. cfg -- [in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection, keep this NULL. For TLS connection, a pass pointer to esp_tls_cfg_t. At a minimum, this structure should be zero-initialized. tls -- [in] Pointer to esp-tls as esp-tls handle. - - Returns -1 If connection establishment fails. 1 If connection establishment is successful. 0 If connection state is in progress. - - int esp_tls_conn_http_new_sync(const char *url, const esp_tls_cfg_t *cfg, esp_tls_t *tls) Create a new blocking TLS/SSL connection with a given "HTTP" url. The behaviour is same as esp_tls_conn_new_sync() API. However this API accepts host's url. - Parameters url -- [in] url of host. cfg -- [in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection, keep this NULL. For TLS connection, a pass pointer to 'esp_tls_cfg_t'. At a minimum, this structure should be zero-initialized. tls -- [in] Pointer to esp-tls as esp-tls handle. - - Returns -1 If connection establishment fails. 1 If connection establishment is successful. 0 If connection state is in progress. - - int esp_tls_conn_new_async(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls) Create a new non-blocking TLS/SSL connection. This function initiates a non-blocking TLS/SSL connection with the specified host, but due to its non-blocking nature, it doesn't wait for the connection to get established. - Parameters hostname -- [in] Hostname of the host. hostlen -- [in] Length of hostname. port -- [in] Port number of the host. cfg -- [in] TLS configuration as esp_tls_cfg_t. non_blockmember of this structure should be set to be true. tls -- [in] pointer to esp-tls as esp-tls handle. - - Returns -1 If connection establishment fails. 0 If connection establishment is in progress. 1 If connection establishment is successful. - - int esp_tls_conn_http_new_async(const char *url, const esp_tls_cfg_t *cfg, esp_tls_t *tls) Create a new non-blocking TLS/SSL connection with a given "HTTP" url. The behaviour is same as esp_tls_conn_new_async() API. However this API accepts host's url. - Parameters url -- [in] url of host. cfg -- [in] TLS configuration as esp_tls_cfg_t. tls -- [in] pointer to esp-tls as esp-tls handle. - - Returns -1 If connection establishment fails. 0 If connection establishment is in progress. 1 If connection establishment is successful. - - ssize_t esp_tls_conn_write(esp_tls_t *tls, const void *data, size_t datalen) Write from buffer 'data' into specified tls connection. - Parameters tls -- [in] pointer to esp-tls as esp-tls handle. data -- [in] Buffer from which data will be written. datalen -- [in] Length of data buffer. - - Returns >=0 if write operation was successful, the return value is the number of bytes actually written to the TLS/SSL connection. <0 if write operation was not successful, because either an error occured or an action must be taken by the calling process. ESP_TLS_ERR_SSL_WANT_READ/ ESP_TLS_ERR_SSL_WANT_WRITE. if the handshake is incomplete and waiting for data to be available for reading. In this case this functions needs to be called again when the underlying transport is ready for operation. - - ssize_t esp_tls_conn_read(esp_tls_t *tls, void *data, size_t datalen) Read from specified tls connection into the buffer 'data'. - Parameters tls -- [in] pointer to esp-tls as esp-tls handle. data -- [in] Buffer to hold read data. datalen -- [in] Length of data buffer. - - Returns >0 if read operation was successful, the return value is the number of bytes actually read from the TLS/SSL connection. 0 if read operation was not successful. The underlying connection was closed. <0 if read operation was not successful, because either an error occured or an action must be taken by the calling process. - - int esp_tls_conn_destroy(esp_tls_t *tls) Close the TLS/SSL connection and free any allocated resources. This function should be called to close each tls connection opened with esp_tls_conn_new_sync() (or esp_tls_conn_http_new_sync()) and esp_tls_conn_new_async() (or esp_tls_conn_http_new_async()) APIs. - Parameters tls -- [in] pointer to esp-tls as esp-tls handle. - Returns - 0 on success -1 if socket error or an invalid argument - - ssize_t esp_tls_get_bytes_avail(esp_tls_t *tls) Return the number of application data bytes remaining to be read from the current record. This API is a wrapper over mbedtls's mbedtls_ssl_get_bytes_avail() API. - Parameters tls -- [in] pointer to esp-tls as esp-tls handle. - Returns -1 in case of invalid arg bytes available in the application data record read buffer - - esp_err_t esp_tls_get_conn_sockfd(esp_tls_t *tls, int *sockfd) Returns the connection socket file descriptor from esp_tls session. - Parameters tls -- [in] handle to esp_tls context sockfd -- [out] int pointer to sockfd value. - - Returns - ESP_OK on success and value of sockfd will be updated with socket file descriptor for connection ESP_ERR_INVALID_ARG if (tls == NULL || sockfd == NULL) - - esp_err_t esp_tls_set_conn_sockfd(esp_tls_t *tls, int sockfd) Sets the connection socket file descriptor for the esp_tls session. - Parameters tls -- [in] handle to esp_tls context sockfd -- [in] sockfd value to set. - - Returns - ESP_OK on success and value of sockfd for the tls connection shall updated withthe provided value ESP_ERR_INVALID_ARG if (tls == NULL || sockfd < 0) - - esp_err_t esp_tls_get_conn_state(esp_tls_t *tls, esp_tls_conn_state_t *conn_state) Gets the connection state for the esp_tls session. - Parameters tls -- [in] handle to esp_tls context conn_state -- [out] pointer to the connection state value. - - Returns - ESP_OK on success and value of sockfd for the tls connection shall updated withthe provided value ESP_ERR_INVALID_ARG (Invalid arguments) - - esp_err_t esp_tls_set_conn_state(esp_tls_t *tls, esp_tls_conn_state_t conn_state) Sets the connection state for the esp_tls session. - Parameters tls -- [in] handle to esp_tls context conn_state -- [in] connection state value to set. - - Returns - ESP_OK on success and value of sockfd for the tls connection shall updated withthe provided value ESP_ERR_INVALID_ARG (Invalid arguments) - - void *esp_tls_get_ssl_context(esp_tls_t *tls) Returns the ssl context. - Parameters tls -- [in] handle to esp_tls context - Returns - ssl_ctx pointer to ssl context of underlying TLS layer on success NULL in case of error - - esp_err_t esp_tls_init_global_ca_store(void) Create a global CA store, initially empty. This function should be called if the application wants to use the same CA store for multiple connections. This function initialises the global CA store which can be then set by calling esp_tls_set_global_ca_store(). To be effective, this function must be called before any call to esp_tls_set_global_ca_store(). - Returns ESP_OK if creating global CA store was successful. ESP_ERR_NO_MEM if an error occured when allocating the mbedTLS resources. - - esp_err_t esp_tls_set_global_ca_store(const unsigned char *cacert_pem_buf, const unsigned int cacert_pem_bytes) Set the global CA store with the buffer provided in pem format. This function should be called if the application wants to set the global CA store for multiple connections i.e. to add the certificates in the provided buffer to the certificate chain. This function implicitly calls esp_tls_init_global_ca_store() if it has not already been called. The application must call this function before calling esp_tls_conn_new(). - Parameters cacert_pem_buf -- [in] Buffer which has certificates in pem format. This buffer is used for creating a global CA store, which can be used by other tls connections. cacert_pem_bytes -- [in] Length of the buffer. - - Returns ESP_OK if adding certificates was successful. Other if an error occured or an action must be taken by the calling process. - - void esp_tls_free_global_ca_store(void) Free the global CA store currently being used. The memory being used by the global CA store to store all the parsed certificates is freed up. The application can call this API if it no longer needs the global CA store. - esp_err_t esp_tls_get_and_clear_last_error(esp_tls_error_handle_t h, int *esp_tls_code, int *esp_tls_flags) Returns last error in esp_tls with detailed mbedtls related error codes. The error information is cleared internally upon return. - Parameters h -- [in] esp-tls error handle. esp_tls_code -- [out] last error code returned from mbedtls api (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code esp_tls_flags -- [out] last certification verification flags (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code - - Returns ESP_ERR_INVALID_STATE if invalid parameters ESP_OK (0) if no error occurred specific error code (based on ESP_ERR_ESP_TLS_BASE) otherwise - - esp_err_t esp_tls_get_and_clear_error_type(esp_tls_error_handle_t h, esp_tls_error_type_t err_type, int *error_code) Returns the last error captured in esp_tls of a specific type The error information is cleared internally upon return. - Parameters h -- [in] esp-tls error handle. err_type -- [in] specific error type error_code -- [out] last error code returned from mbedtls api (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code - - Returns ESP_ERR_INVALID_STATE if invalid parameters ESP_OK if a valid error returned and was cleared - - esp_err_t esp_tls_get_error_handle(esp_tls_t *tls, esp_tls_error_handle_t *error_handle) Returns the ESP-TLS error_handle. - Parameters tls -- [in] handle to esp_tls context error_handle -- [out] pointer to the error handle. - - Returns ESP_OK on success and error_handle will be updated with the ESP-TLS error handle. ESP_ERR_INVALID_ARG if (tls == NULL || error_handle == NULL) - - mbedtls_x509_crt *esp_tls_get_global_ca_store(void) Get the pointer to the global CA store currently being used. The application must first call esp_tls_set_global_ca_store(). Then the same CA store could be used by the application for APIs other than esp_tls. Note Modifying the pointer might cause a failure in verifying the certificates. - Returns Pointer to the global CA store currently being used if successful. NULL if there is no global CA store set. - - const int *esp_tls_get_ciphersuites_list(void) Get supported TLS ciphersuites list. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4 for the list of ciphersuites - Returns Pointer to a zero-terminated array of IANA identifiers of TLS ciphersuites. - esp_err_t esp_tls_plain_tcp_connect(const char *host, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_error_handle_t error_handle, int *sockfd) Creates a plain TCP connection, returning a valid socket fd on success or an error handle. - Parameters host -- [in] Hostname of the host. hostlen -- [in] Length of hostname. port -- [in] Port number of the host. cfg -- [in] ESP-TLS configuration as esp_tls_cfg_t. error_handle -- [out] ESP-TLS error handle holding potential errors occurred during connection sockfd -- [out] Socket descriptor if successfully connected on TCP layer - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if invalid output parameters ESP-TLS based error codes on failure Structures - struct psk_key_hint ESP-TLS preshared key and hint structure. - struct tls_keep_alive_cfg esp-tls client session ticket ctx Keep alive parameters structure - struct esp_tls_cfg ESP-TLS configuration parameters. Note Note about format of certificates: This structure includes certificates of a Certificate Authority, of client or server as well as private keys, which may be of PEM or DER format. In case of PEM format, the buffer must be NULL terminated (with NULL character included in certificate size). Certificate Authority's certificate may be a chain of certificates in case of PEM format, but could be only one certificate in case of DER format Variables names of certificates and private key buffers and sizes are defined as unions providing backward compatibility for legacy *_pem_buf and *_pem_bytes names which suggested only PEM format was supported. It is encouraged to use generic names such as cacert_buf and cacert_bytes. Public Members - const char **alpn_protos Application protocols required for HTTP2. If HTTP2/ALPN support is required, a list of protocols that should be negotiated. The format is length followed by protocol name. For the most common cases the following is ok: const char **alpn_protos = { "h2", NULL }; where 'h2' is the protocol name - - const unsigned char *cacert_buf Certificate Authority's certificate in a buffer. Format may be PEM or DER, depending on mbedtls-support This buffer should be NULL terminated in case of PEM - const unsigned char *cacert_pem_buf CA certificate buffer legacy name - unsigned int cacert_bytes Size of Certificate Authority certificate pointed to by cacert_buf (including NULL-terminator in case of PEM format) - unsigned int cacert_pem_bytes Size of Certificate Authority certificate legacy name - const unsigned char *clientcert_buf Client certificate in a buffer Format may be PEM or DER, depending on mbedtls-support This buffer should be NULL terminated in case of PEM - const unsigned char *clientcert_pem_buf Client certificate legacy name - unsigned int clientcert_bytes Size of client certificate pointed to by clientcert_pem_buf (including NULL-terminator in case of PEM format) - unsigned int clientcert_pem_bytes Size of client certificate legacy name - const unsigned char *clientkey_buf Client key in a buffer Format may be PEM or DER, depending on mbedtls-support This buffer should be NULL terminated in case of PEM - const unsigned char *clientkey_pem_buf Client key legacy name - unsigned int clientkey_bytes Size of client key pointed to by clientkey_pem_buf (including NULL-terminator in case of PEM format) - unsigned int clientkey_pem_bytes Size of client key legacy name - const unsigned char *clientkey_password Client key decryption password string - unsigned int clientkey_password_len String length of the password pointed to by clientkey_password - bool use_ecdsa_peripheral Use the ECDSA peripheral for the private key operations - uint8_t ecdsa_key_efuse_blk The efuse block where the ECDSA key is stored - bool non_block Configure non-blocking mode. If set to true the underneath socket will be configured in non blocking mode after tls session is established - bool use_secure_element Enable this option to use secure element or atecc608a chip ( Integrated with ESP32-WROOM-32SE ) - int timeout_ms Network timeout in milliseconds. Note: If this value is not set, by default the timeout is set to 10 seconds. If you wish that the session should wait indefinitely then please use a larger value e.g., INT32_MAX - bool use_global_ca_store Use a global ca_store for all the connections in which this bool is set. - const char *common_name If non-NULL, server certificate CN must match this name. If NULL, server certificate CN must match hostname. - bool skip_common_name Skip any validation of server certificate CN field - tls_keep_alive_cfg_t *keep_alive_cfg Enable TCP keep-alive timeout for SSL connection - const psk_hint_key_t *psk_hint_key Pointer to PSK hint and key. if not NULL (and certificates are NULL) then PSK authentication is enabled with configured setup. Important note: the pointer must be valid for connection - esp_err_t (*crt_bundle_attach)(void *conf) Function pointer to esp_crt_bundle_attach. Enables the use of certification bundle for server verification, must be enabled in menuconfig - void *ds_data Pointer for digital signature peripheral context - bool is_plain_tcp Use non-TLS connection: When set to true, the esp-tls uses plain TCP transport rather then TLS/SSL connection. Note, that it is possible to connect using a plain tcp transport directly with esp_tls_plain_tcp_connect() API - struct ifreq *if_name The name of interface for data to go through. Use the default interface without setting - esp_tls_addr_family_t addr_family The address family to use when connecting to a host. - const int *ciphersuites_list Pointer to a zero-terminated array of IANA identifiers of TLS ciphersuites. Please check the list validity by esp_tls_get_ciphersuites_list() API - esp_tls_proto_ver_t tls_version TLS protocol version of the connection, e.g., TLS 1.2, TLS 1.3 (default - no preference) - Type Definitions - typedef enum esp_tls_conn_state esp_tls_conn_state_t ESP-TLS Connection State. - typedef enum esp_tls_role esp_tls_role_t - typedef struct psk_key_hint psk_hint_key_t ESP-TLS preshared key and hint structure. - typedef struct tls_keep_alive_cfg tls_keep_alive_cfg_t esp-tls client session ticket ctx Keep alive parameters structure - typedef enum esp_tls_addr_family esp_tls_addr_family_t - typedef struct esp_tls_cfg esp_tls_cfg_t ESP-TLS configuration parameters. Note Note about format of certificates: This structure includes certificates of a Certificate Authority, of client or server as well as private keys, which may be of PEM or DER format. In case of PEM format, the buffer must be NULL terminated (with NULL character included in certificate size). Certificate Authority's certificate may be a chain of certificates in case of PEM format, but could be only one certificate in case of DER format Variables names of certificates and private key buffers and sizes are defined as unions providing backward compatibility for legacy *_pem_buf and *_pem_bytes names which suggested only PEM format was supported. It is encouraged to use generic names such as cacert_buf and cacert_bytes. - - typedef struct esp_tls esp_tls_t Enumerations - enum esp_tls_conn_state ESP-TLS Connection State. Values: - enumerator ESP_TLS_INIT - enumerator ESP_TLS_CONNECTING - enumerator ESP_TLS_HANDSHAKE - enumerator ESP_TLS_FAIL - enumerator ESP_TLS_DONE - enumerator ESP_TLS_INIT - enum esp_tls_addr_family Values: - enumerator ESP_TLS_AF_UNSPEC Unspecified address family. - enumerator ESP_TLS_AF_INET IPv4 address family. - enumerator ESP_TLS_AF_INET6 IPv6 address family. - enumerator ESP_TLS_AF_UNSPEC Header File This header file can be included with: #include "esp_tls_errors.h" This header file is a part of the API provided by the esp-tlscomponent. To declare that your component depends on esp-tls, add the following to your CMakeLists.txt: REQUIRES esp-tls or PRIV_REQUIRES esp-tls Structures - struct esp_tls_last_error Error structure containing relevant errors in case tls error occurred. Macros - ESP_ERR_ESP_TLS_BASE Starting number of ESP-TLS error codes - ESP_ERR_ESP_TLS_CANNOT_RESOLVE_HOSTNAME Error if hostname couldn't be resolved upon tls connection - ESP_ERR_ESP_TLS_CANNOT_CREATE_SOCKET Failed to create socket - ESP_ERR_ESP_TLS_UNSUPPORTED_PROTOCOL_FAMILY Unsupported protocol family - ESP_ERR_ESP_TLS_FAILED_CONNECT_TO_HOST Failed to connect to host - ESP_ERR_ESP_TLS_SOCKET_SETOPT_FAILED failed to set/get socket option - ESP_ERR_ESP_TLS_CONNECTION_TIMEOUT new connection in esp_tls_low_level_conn connection timeouted - ESP_ERR_ESP_TLS_SE_FAILED - ESP_ERR_ESP_TLS_TCP_CLOSED_FIN - ESP_ERR_MBEDTLS_CERT_PARTLY_OK mbedtls parse certificates was partly successful - ESP_ERR_MBEDTLS_CTR_DRBG_SEED_FAILED mbedtls api returned error - ESP_ERR_MBEDTLS_SSL_SET_HOSTNAME_FAILED mbedtls api returned error - ESP_ERR_MBEDTLS_SSL_CONFIG_DEFAULTS_FAILED mbedtls api returned error - ESP_ERR_MBEDTLS_SSL_CONF_ALPN_PROTOCOLS_FAILED mbedtls api returned error - ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED mbedtls api returned error - ESP_ERR_MBEDTLS_SSL_CONF_OWN_CERT_FAILED mbedtls api returned error - ESP_ERR_MBEDTLS_SSL_SETUP_FAILED mbedtls api returned error - ESP_ERR_MBEDTLS_SSL_WRITE_FAILED mbedtls api returned error - ESP_ERR_MBEDTLS_PK_PARSE_KEY_FAILED mbedtls api returned failed - ESP_ERR_MBEDTLS_SSL_HANDSHAKE_FAILED mbedtls api returned failed - ESP_ERR_MBEDTLS_SSL_CONF_PSK_FAILED mbedtls api returned failed - ESP_ERR_MBEDTLS_SSL_TICKET_SETUP_FAILED mbedtls api returned failed - ESP_ERR_WOLFSSL_SSL_SET_HOSTNAME_FAILED wolfSSL api returned error - ESP_ERR_WOLFSSL_SSL_CONF_ALPN_PROTOCOLS_FAILED wolfSSL api returned error - ESP_ERR_WOLFSSL_CERT_VERIFY_SETUP_FAILED wolfSSL api returned error - ESP_ERR_WOLFSSL_KEY_VERIFY_SETUP_FAILED wolfSSL api returned error - ESP_ERR_WOLFSSL_SSL_HANDSHAKE_FAILED wolfSSL api returned failed - ESP_ERR_WOLFSSL_CTX_SETUP_FAILED wolfSSL api returned failed - ESP_ERR_WOLFSSL_SSL_SETUP_FAILED wolfSSL api returned failed - ESP_ERR_WOLFSSL_SSL_WRITE_FAILED wolfSSL api returned failed - ESP_TLS_ERR_SSL_WANT_READ Definition of errors reported from IO API (potentially non-blocking) in case of error: esp_tls_conn_read() esp_tls_conn_write() - - ESP_TLS_ERR_SSL_WANT_WRITE - ESP_TLS_ERR_SSL_TIMEOUT Type Definitions - typedef struct esp_tls_last_error *esp_tls_error_handle_t - typedef struct esp_tls_last_error esp_tls_last_error_t Error structure containing relevant errors in case tls error occurred. Enumerations - enum esp_tls_error_type_t Definition of different types/sources of error codes reported from different components Values: - enumerator ESP_TLS_ERR_TYPE_UNKNOWN - enumerator ESP_TLS_ERR_TYPE_SYSTEM System error – errno - enumerator ESP_TLS_ERR_TYPE_MBEDTLS Error code from mbedTLS library - enumerator ESP_TLS_ERR_TYPE_MBEDTLS_CERT_FLAGS Certificate flags defined in mbedTLS - enumerator ESP_TLS_ERR_TYPE_ESP ESP-IDF error type – esp_err_t - enumerator ESP_TLS_ERR_TYPE_WOLFSSL Error code from wolfSSL library - enumerator ESP_TLS_ERR_TYPE_WOLFSSL_CERT_FLAGS Certificate flags defined in wolfSSL - enumerator ESP_TLS_ERR_TYPE_MAX Last err type – invalid entry - enumerator ESP_TLS_ERR_TYPE_UNKNOWN
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/protocols/esp_tls.html
ESP-IDF Programming Guide v5.2.1 documentation
null
ESP HTTP Client
Int Max Authorization Retries
espressif.com
2016-01-01
b25bfd1e6219ee90
null
null
ESP HTTP Client Overview esp_http_client component provides a set of APIs for making HTTP/S requests from ESP-IDF applications. The steps to use these APIs are as follows: esp_http_client_init() : Creates an esp_http_client_handle_t instance, i.e., an HTTP client handle based on the given esp_http_client_config_t configuration. This function must be the first to be called; default values are assumed for the configuration values that are not explicitly defined by the user. esp_http_client_perform() : Performs all operations of the esp_http_client - opening the connection, exchanging data, and closing the connection (as required), while blocking the current task before its completion. All related events are invoked through the event handler (as specified in esp_http_client_config_t ). esp_http_client_cleanup() : Closes the connection (if any) and frees up all the memory allocated to the HTTP client instance. This must be the last function to be called after the completion of operations. Application Example Simple example that uses ESP HTTP Client to make HTTP/S requests can be found at protocols/esp_http_client. Basic HTTP Request Check out the example functions http_rest_with_url and http_rest_with_hostname_path in the application example for implementation details. Persistent Connections Persistent connection means that the HTTP client can re-use the same connection for several exchanges. If the server does not request to close the connection with the Connection: close header, the connection is not dropped but is instead kept open and used for further requests. To allow ESP HTTP client to take full advantage of persistent connections, one should make as many requests as possible using the same handle instance. Check out the example functions http_rest_with_url and http_rest_with_hostname_path in the application example. Here, once the connection is created, multiple requests ( GET , POST , PUT , etc.) are made before the connection is closed. Use Secure Element (ATECC608) for TLS A secure element (ATECC608) can be also used for the underlying TLS connection in the HTTP client connection. Please refer to the ATECC608A (Secure Element) with ESP-TLS section in the ESP-TLS documentation for more details. The secure element support has to be first enabled in menuconfig through CONFIG_ESP_TLS_USE_SECURE_ELEMENT. Then the HTTP client can be configured to use secure element as follows: esp_http_client_config_t cfg = { /* other configurations options */ .use_secure_element = true, }; HTTPS Request ESP HTTP client supports SSL connections using mbedTLS, with the url configuration starting with https scheme or transport_type set to HTTP_TRANSPORT_OVER_SSL . HTTPS support can be configured via CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS (enabled by default). Note While making HTTPS requests, if server verification is needed, an additional root certificate (in PEM format) needs to be provided to the cert_pem member in the esp_http_client_config_t configuration. Users can also use the ESP x509 Certificate Bundle for server verification using the crt_bundle_attach member of the esp_http_client_config_t configuration. Check out the example functions https_with_url and https_with_hostname_path in the application example for implementation details of the above note. HTTP Stream Some applications need to open the connection and control the exchange of data actively (data streaming). In such cases, the application flow is different from regular requests. Example flow is given below: esp_http_client_init() : Create a HTTP client handle. esp_http_client_set_* or esp_http_client_delete_* : Modify the HTTP connection parameters (optional). esp_http_client_open() : Open the HTTP connection with write_len parameter (content length that needs to be written to server), set write_len=0 for read-only connection. esp_http_client_write() : Write data to server with a maximum length equal to write_len of esp_http_client_open() function; no need to call this function for write_len=0 . esp_http_client_fetch_headers() : Read the HTTP Server response headers, after sending the request headers and server data (if any). Returns the content-length from the server and can be succeeded by esp_http_client_get_status_code() for getting the HTTP status of the connection. esp_http_client_read() : Read the HTTP stream. esp_http_client_close() : Close the connection. esp_http_client_cleanup() : Release allocated resources. Check out the example function http_perform_as_stream_reader in the application example for implementation details. HTTP Authentication ESP HTTP client supports both Basic and Digest Authentication. Users can provide the username and password in the url or the username and password members of the esp_http_client_config_t configuration. For auth_type = HTTP_AUTH_TYPE_BASIC , the HTTP client takes only one perform operation to pass the authentication process. If auth_type = HTTP_AUTH_TYPE_NONE , but the username and password fields are present in the configuration, the HTTP client takes two perform operations. The client will receive the 401 Unauthorized header in its first attempt to connect to the server. Based on this information, it decides which authentication method to choose and performs it in the second operation. Check out the example functions http_auth_basic , http_auth_basic_redirect (for Basic authentication) and http_auth_digest (for Digest authentication) in the application example for implementation details. Users can provide the username and password in the url or the username and password members of the esp_http_client_config_t configuration. For auth_type = HTTP_AUTH_TYPE_BASIC , the HTTP client takes only one perform operation to pass the authentication process. If auth_type = HTTP_AUTH_TYPE_NONE , but the username and password fields are present in the configuration, the HTTP client takes two perform operations. The client will receive the 401 Unauthorized header in its first attempt to connect to the server. Based on this information, it decides which authentication method to choose and performs it in the second operation. Check out the example functions http_auth_basic , http_auth_basic_redirect (for Basic authentication) and http_auth_digest (for Digest authentication) in the application example for implementation details. Users can provide the username and password in the url or the username and password members of the esp_http_client_config_t configuration. For auth_type = HTTP_AUTH_TYPE_BASIC , the HTTP client takes only one perform operation to pass the authentication process. Examples of Authentication Configuration Authentication with URI esp_http_client_config_t config = { .url = "http://user:passwd@httpbin.org/basic-auth/user/passwd", .auth_type = HTTP_AUTH_TYPE_BASIC, }; Authentication with username and password entry esp_http_client_config_t config = { .url = "http://httpbin.org/basic-auth/user/passwd", .username = "user", .password = "passwd", .auth_type = HTTP_AUTH_TYPE_BASIC, }; Event Handling ESP HTTP Client supports event handling by triggering an event handler corresponding to the event which takes place. esp_http_client_event_id_t contains all the events which could occur while performing an HTTP request using the ESP HTTP Client. To enable event handling, you just need to set a callback function using the esp_http_client_config_t::event_handler member. ESP HTTP Client Diagnostic Information Diagnostic information could be helpful to gain insights into a problem. In the case of ESP HTTP Client, the diagnostic information can be collected by registering an event handler with the Event Loop library. This feature has been added by keeping in mind the ESP Insights framework which collects the diagnostic information. However, this feature can also be used without any dependency on the ESP Insights framework for the diagnostic purpose. Event handler can be registered to the event loop using the esp_event_handler_register() function. Expected data types for different HTTP Client events in the event loop are as follows: HTTP_EVENT_ERROR : esp_http_client_handle_t HTTP_EVENT_ON_CONNECTED : esp_http_client_handle_t HTTP_EVENT_HEADERS_SENT : esp_http_client_handle_t HTTP_EVENT_ON_HEADER : esp_http_client_handle_t HTTP_EVENT_ON_DATA : esp_http_client_on_data_t HTTP_EVENT_ON_FINISH : esp_http_client_handle_t HTTP_EVENT_DISCONNECTED : esp_http_client_handle_t HTTP_EVENT_REDIRECT : esp_http_client_redirect_event_data_t The esp_http_client_handle_t received along with the event data will be valid until HTTP_EVENT_DISCONNECTED is not received. This handle has been sent primarily to differentiate between different client connections and must not be used for any other purpose, as it may change based on client connection state. API Reference Header File This header file can be included with: #include "esp_http_client.h" This header file is a part of the API provided by the esp_http_client component. To declare that your component depends on esp_http_client , add the following to your CMakeLists.txt: REQUIRES esp_http_client or PRIV_REQUIRES esp_http_client Functions esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *config) Start a HTTP session This function must be the first function to call, and it returns a esp_http_client_handle_t that you must use as input to other functions in the interface. This call MUST have a corresponding call to esp_http_client_cleanup when the operation is complete. Parameters config -- [in] The configurations, see http_client_config_t Returns esp_http_client_handle_t NULL if any errors esp_http_client_handle_t NULL if any errors esp_http_client_handle_t Parameters config -- [in] The configurations, see http_client_config_t Returns esp_http_client_handle_t NULL if any errors esp_err_t esp_http_client_perform(esp_http_client_handle_t client) Invoke this function after esp_http_client_init and all the options calls are made, and will perform the transfer as described in the options. It must be called with the same esp_http_client_handle_t as input as the esp_http_client_init call returned. esp_http_client_perform performs the entire request in either blocking or non-blocking manner. By default, the API performs request in a blocking manner and returns when done, or if it failed, and in non-blocking manner, it returns if EAGAIN/EWOULDBLOCK or EINPROGRESS is encountered, or if it failed. And in case of non-blocking request, the user may call this API multiple times unless request & response is complete or there is a failure. To enable non-blocking esp_http_client_perform(), is_async member of esp_http_client_config_t must be set while making a call to esp_http_client_init() API. You can do any amount of calls to esp_http_client_perform while using the same esp_http_client_handle_t. The underlying connection may be kept open if the server allows it. If you intend to transfer more than one file, you are even encouraged to do so. esp_http_client will then attempt to re-use the same connection for the following transfers, thus making the operations faster, less CPU intense and using less network resources. Just note that you will have to use esp_http_client_set_** between the invokes to set options for the following esp_http_client_perform. Note You must never call this function simultaneously from two places using the same client handle. Let the function return first before invoking it another time. If you want parallel transfers, you must use several esp_http_client_handle_t. This function include esp_http_client_open -> esp_http_client_write -> esp_http_client_fetch_headers -> esp_http_client_read (and option) esp_http_client_close . Parameters client -- The esp_http_client handle Returns ESP_OK on successful ESP_FAIL on error ESP_OK on successful ESP_FAIL on error ESP_OK on successful Parameters client -- The esp_http_client handle Returns ESP_OK on successful ESP_FAIL on error esp_err_t esp_http_client_cancel_request(esp_http_client_handle_t client) Cancel an ongoing HTTP request. This API closes the current socket and opens a new socket with the same esp_http_client context. Parameters client -- The esp_http_client handle Returns ESP_OK on successful ESP_FAIL on error ESP_ERR_INVALID_ARG ESP_ERR_INVALID_STATE ESP_OK on successful ESP_FAIL on error ESP_ERR_INVALID_ARG ESP_ERR_INVALID_STATE ESP_OK on successful Parameters client -- The esp_http_client handle Returns ESP_OK on successful ESP_FAIL on error ESP_ERR_INVALID_ARG ESP_ERR_INVALID_STATE esp_err_t esp_http_client_set_url(esp_http_client_handle_t client, const char *url) Set URL for client, when performing this behavior, the options in the URL will replace the old ones. Parameters client -- [in] The esp_http_client handle url -- [in] The url client -- [in] The esp_http_client handle url -- [in] The url client -- [in] The esp_http_client handle Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters client -- [in] The esp_http_client handle url -- [in] The url Returns ESP_OK ESP_FAIL esp_err_t esp_http_client_set_post_field(esp_http_client_handle_t client, const char *data, int len) Set post data, this function must be called before esp_http_client_perform . Note: The data parameter passed to this function is a pointer and this function will not copy the data. Parameters client -- [in] The esp_http_client handle data -- [in] post data pointer len -- [in] post length client -- [in] The esp_http_client handle data -- [in] post data pointer len -- [in] post length client -- [in] The esp_http_client handle Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters client -- [in] The esp_http_client handle data -- [in] post data pointer len -- [in] post length Returns ESP_OK ESP_FAIL int esp_http_client_get_post_field(esp_http_client_handle_t client, char **data) Get current post field information. Parameters client -- [in] The client data -- [out] Point to post data pointer client -- [in] The client data -- [out] Point to post data pointer client -- [in] The client Returns Size of post data Parameters client -- [in] The client data -- [out] Point to post data pointer Returns Size of post data esp_err_t esp_http_client_set_header(esp_http_client_handle_t client, const char *key, const char *value) Set http request header, this function must be called after esp_http_client_init and before any perform function. Parameters client -- [in] The esp_http_client handle key -- [in] The header key value -- [in] The header value client -- [in] The esp_http_client handle key -- [in] The header key value -- [in] The header value client -- [in] The esp_http_client handle Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters client -- [in] The esp_http_client handle key -- [in] The header key value -- [in] The header value Returns ESP_OK ESP_FAIL esp_err_t esp_http_client_get_header(esp_http_client_handle_t client, const char *key, char **value) Get http request header. The value parameter will be set to NULL if there is no header which is same as the key specified, otherwise the address of header value will be assigned to value parameter. This function must be called after esp_http_client_init . Parameters client -- [in] The esp_http_client handle key -- [in] The header key value -- [out] The header value client -- [in] The esp_http_client handle key -- [in] The header key value -- [out] The header value client -- [in] The esp_http_client handle Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters client -- [in] The esp_http_client handle key -- [in] The header key value -- [out] The header value Returns ESP_OK ESP_FAIL esp_err_t esp_http_client_get_username(esp_http_client_handle_t client, char **value) Get http request username. The address of username buffer will be assigned to value parameter. This function must be called after esp_http_client_init . Parameters client -- [in] The esp_http_client handle value -- [out] The username value client -- [in] The esp_http_client handle value -- [out] The username value client -- [in] The esp_http_client handle Returns ESP_OK ESP_ERR_INVALID_ARG ESP_OK ESP_ERR_INVALID_ARG ESP_OK Parameters client -- [in] The esp_http_client handle value -- [out] The username value Returns ESP_OK ESP_ERR_INVALID_ARG esp_err_t esp_http_client_set_username(esp_http_client_handle_t client, const char *username) Set http request username. The value of username parameter will be assigned to username buffer. If the username parameter is NULL then username buffer will be freed. Parameters client -- [in] The esp_http_client handle username -- [in] The username value client -- [in] The esp_http_client handle username -- [in] The username value client -- [in] The esp_http_client handle Returns ESP_OK ESP_ERR_INVALID_ARG ESP_OK ESP_ERR_INVALID_ARG ESP_OK Parameters client -- [in] The esp_http_client handle username -- [in] The username value Returns ESP_OK ESP_ERR_INVALID_ARG esp_err_t esp_http_client_get_password(esp_http_client_handle_t client, char **value) Get http request password. The address of password buffer will be assigned to value parameter. This function must be called after esp_http_client_init . Parameters client -- [in] The esp_http_client handle value -- [out] The password value client -- [in] The esp_http_client handle value -- [out] The password value client -- [in] The esp_http_client handle Returns ESP_OK ESP_ERR_INVALID_ARG ESP_OK ESP_ERR_INVALID_ARG ESP_OK Parameters client -- [in] The esp_http_client handle value -- [out] The password value Returns ESP_OK ESP_ERR_INVALID_ARG esp_err_t esp_http_client_set_password(esp_http_client_handle_t client, const char *password) Set http request password. The value of password parameter will be assigned to password buffer. If the password parameter is NULL then password buffer will be freed. Parameters client -- [in] The esp_http_client handle password -- [in] The password value client -- [in] The esp_http_client handle password -- [in] The password value client -- [in] The esp_http_client handle Returns ESP_OK ESP_ERR_INVALID_ARG ESP_OK ESP_ERR_INVALID_ARG ESP_OK Parameters client -- [in] The esp_http_client handle password -- [in] The password value Returns ESP_OK ESP_ERR_INVALID_ARG esp_err_t esp_http_client_set_authtype(esp_http_client_handle_t client, esp_http_client_auth_type_t auth_type) Set http request auth_type. Parameters client -- [in] The esp_http_client handle auth_type -- [in] The esp_http_client auth type client -- [in] The esp_http_client handle auth_type -- [in] The esp_http_client auth type client -- [in] The esp_http_client handle Returns ESP_OK ESP_ERR_INVALID_ARG ESP_OK ESP_ERR_INVALID_ARG ESP_OK Parameters client -- [in] The esp_http_client handle auth_type -- [in] The esp_http_client auth type Returns ESP_OK ESP_ERR_INVALID_ARG esp_err_t esp_http_client_get_user_data(esp_http_client_handle_t client, void **data) Get http request user_data. The value stored from the esp_http_client_config_t will be written to the address passed into data. Parameters client -- [in] The esp_http_client handle data -- [out] A pointer to the pointer that will be set to user_data. client -- [in] The esp_http_client handle data -- [out] A pointer to the pointer that will be set to user_data. client -- [in] The esp_http_client handle Returns ESP_OK ESP_ERR_INVALID_ARG ESP_OK ESP_ERR_INVALID_ARG ESP_OK Parameters client -- [in] The esp_http_client handle data -- [out] A pointer to the pointer that will be set to user_data. Returns ESP_OK ESP_ERR_INVALID_ARG esp_err_t esp_http_client_set_user_data(esp_http_client_handle_t client, void *data) Set http request user_data. The value passed in +data+ will be available during event callbacks. No memory management will be performed on the user's behalf. Parameters client -- [in] The esp_http_client handle data -- [in] The pointer to the user data client -- [in] The esp_http_client handle data -- [in] The pointer to the user data client -- [in] The esp_http_client handle Returns ESP_OK ESP_ERR_INVALID_ARG ESP_OK ESP_ERR_INVALID_ARG ESP_OK Parameters client -- [in] The esp_http_client handle data -- [in] The pointer to the user data Returns ESP_OK ESP_ERR_INVALID_ARG int esp_http_client_get_errno(esp_http_client_handle_t client) Get HTTP client session errno. Parameters client -- [in] The esp_http_client handle Returns (-1) if invalid argument errno (-1) if invalid argument errno (-1) if invalid argument Parameters client -- [in] The esp_http_client handle Returns (-1) if invalid argument errno esp_err_t esp_http_client_set_method(esp_http_client_handle_t client, esp_http_client_method_t method) Set http request method. Parameters client -- [in] The esp_http_client handle method -- [in] The method client -- [in] The esp_http_client handle method -- [in] The method client -- [in] The esp_http_client handle Returns ESP_OK ESP_ERR_INVALID_ARG ESP_OK ESP_ERR_INVALID_ARG ESP_OK Parameters client -- [in] The esp_http_client handle method -- [in] The method Returns ESP_OK ESP_ERR_INVALID_ARG esp_err_t esp_http_client_set_timeout_ms(esp_http_client_handle_t client, int timeout_ms) Set http request timeout. Parameters client -- [in] The esp_http_client handle timeout_ms -- [in] The timeout value client -- [in] The esp_http_client handle timeout_ms -- [in] The timeout value client -- [in] The esp_http_client handle Returns ESP_OK ESP_ERR_INVALID_ARG ESP_OK ESP_ERR_INVALID_ARG ESP_OK Parameters client -- [in] The esp_http_client handle timeout_ms -- [in] The timeout value Returns ESP_OK ESP_ERR_INVALID_ARG esp_err_t esp_http_client_delete_header(esp_http_client_handle_t client, const char *key) Delete http request header. Parameters client -- [in] The esp_http_client handle key -- [in] The key client -- [in] The esp_http_client handle key -- [in] The key client -- [in] The esp_http_client handle Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters client -- [in] The esp_http_client handle key -- [in] The key Returns ESP_OK ESP_FAIL esp_err_t esp_http_client_open(esp_http_client_handle_t client, int write_len) This function will be open the connection, write all header strings and return. Parameters client -- [in] The esp_http_client handle write_len -- [in] HTTP Content length need to write to the server client -- [in] The esp_http_client handle write_len -- [in] HTTP Content length need to write to the server client -- [in] The esp_http_client handle Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters client -- [in] The esp_http_client handle write_len -- [in] HTTP Content length need to write to the server Returns ESP_OK ESP_FAIL int esp_http_client_write(esp_http_client_handle_t client, const char *buffer, int len) This function will write data to the HTTP connection previously opened by esp_http_client_open() Parameters client -- [in] The esp_http_client handle buffer -- The buffer len -- [in] This value must not be larger than the write_len parameter provided to esp_http_client_open() client -- [in] The esp_http_client handle buffer -- The buffer len -- [in] This value must not be larger than the write_len parameter provided to esp_http_client_open() client -- [in] The esp_http_client handle Returns (-1) if any errors Length of data written (-1) if any errors Length of data written (-1) if any errors Parameters client -- [in] The esp_http_client handle buffer -- The buffer len -- [in] This value must not be larger than the write_len parameter provided to esp_http_client_open() Returns (-1) if any errors Length of data written int64_t esp_http_client_fetch_headers(esp_http_client_handle_t client) This function need to call after esp_http_client_open, it will read from http stream, process all receive headers. Parameters client -- [in] The esp_http_client handle Returns (0) if stream doesn't contain content-length header, or chunked encoding (checked by esp_http_client_is_chunked response) (-1: ESP_FAIL) if any errors (-ESP_ERR_HTTP_EAGAIN = -0x7007) if call is timed-out before any data was ready Download data length defined by content-length header (0) if stream doesn't contain content-length header, or chunked encoding (checked by esp_http_client_is_chunked response) (-1: ESP_FAIL) if any errors (-ESP_ERR_HTTP_EAGAIN = -0x7007) if call is timed-out before any data was ready Download data length defined by content-length header (0) if stream doesn't contain content-length header, or chunked encoding (checked by esp_http_client_is_chunked response) Parameters client -- [in] The esp_http_client handle Returns (0) if stream doesn't contain content-length header, or chunked encoding (checked by esp_http_client_is_chunked response) (-1: ESP_FAIL) if any errors (-ESP_ERR_HTTP_EAGAIN = -0x7007) if call is timed-out before any data was ready Download data length defined by content-length header bool esp_http_client_is_chunked_response(esp_http_client_handle_t client) Check response data is chunked. Parameters client -- [in] The esp_http_client handle Returns true or false Parameters client -- [in] The esp_http_client handle Returns true or false int esp_http_client_read(esp_http_client_handle_t client, char *buffer, int len) Read data from http stream. Note (-ESP_ERR_HTTP_EAGAIN = -0x7007) is returned when call is timed-out before any data was ready Parameters client -- [in] The esp_http_client handle buffer -- The buffer len -- [in] The length client -- [in] The esp_http_client handle buffer -- The buffer len -- [in] The length client -- [in] The esp_http_client handle Returns (-1) if any errors Length of data was read (-1) if any errors Length of data was read (-1) if any errors Parameters client -- [in] The esp_http_client handle buffer -- The buffer len -- [in] The length Returns (-1) if any errors Length of data was read int esp_http_client_get_status_code(esp_http_client_handle_t client) Get http response status code, the valid value if this function invoke after esp_http_client_perform Parameters client -- [in] The esp_http_client handle Returns Status code Parameters client -- [in] The esp_http_client handle Returns Status code int64_t esp_http_client_get_content_length(esp_http_client_handle_t client) Get http response content length (from header Content-Length) the valid value if this function invoke after esp_http_client_perform Parameters client -- [in] The esp_http_client handle Returns (-1) Chunked transfer Content-Length value as bytes (-1) Chunked transfer Content-Length value as bytes (-1) Chunked transfer Parameters client -- [in] The esp_http_client handle Returns (-1) Chunked transfer Content-Length value as bytes esp_err_t esp_http_client_close(esp_http_client_handle_t client) Close http connection, still kept all http request resources. Parameters client -- [in] The esp_http_client handle Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters client -- [in] The esp_http_client handle Returns ESP_OK ESP_FAIL esp_err_t esp_http_client_cleanup(esp_http_client_handle_t client) This function must be the last function to call for an session. It is the opposite of the esp_http_client_init function and must be called with the same handle as input that a esp_http_client_init call returned. This might close all connections this handle has used and possibly has kept open until now. Don't call this function if you intend to transfer more files, re-using handles is a key to good performance with esp_http_client. Parameters client -- [in] The esp_http_client handle Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters client -- [in] The esp_http_client handle Returns ESP_OK ESP_FAIL esp_http_client_transport_t esp_http_client_get_transport_type(esp_http_client_handle_t client) Get transport type. Parameters client -- [in] The esp_http_client handle Returns HTTP_TRANSPORT_UNKNOWN HTTP_TRANSPORT_OVER_TCP HTTP_TRANSPORT_OVER_SSL HTTP_TRANSPORT_UNKNOWN HTTP_TRANSPORT_OVER_TCP HTTP_TRANSPORT_OVER_SSL HTTP_TRANSPORT_UNKNOWN Parameters client -- [in] The esp_http_client handle Returns HTTP_TRANSPORT_UNKNOWN HTTP_TRANSPORT_OVER_TCP HTTP_TRANSPORT_OVER_SSL esp_err_t esp_http_client_set_redirection(esp_http_client_handle_t client) Set redirection URL. When received the 30x code from the server, the client stores the redirect URL provided by the server. This function will set the current URL to redirect to enable client to execute the redirection request. When disable_auto_redirect is set, the client will not call this function but the event HTTP_EVENT_REDIRECT will be dispatched giving the user contol over the redirection event. Parameters client -- [in] The esp_http_client handle Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters client -- [in] The esp_http_client handle Returns ESP_OK ESP_FAIL esp_err_t esp_http_client_set_auth_data(esp_http_client_handle_t client, const char *auth_data, int len) On receiving a custom authentication header, this API can be invoked to set the authentication information from the header. This API can be called from the event handler. Parameters client -- [in] The esp_http_client handle auth_data -- [in] The authentication data received in the header len -- [in] length of auth_data. client -- [in] The esp_http_client handle auth_data -- [in] The authentication data received in the header len -- [in] length of auth_data. client -- [in] The esp_http_client handle Returns ESP_ERR_INVALID_ARG ESP_OK ESP_ERR_INVALID_ARG ESP_OK ESP_ERR_INVALID_ARG Parameters client -- [in] The esp_http_client handle auth_data -- [in] The authentication data received in the header len -- [in] length of auth_data. Returns ESP_ERR_INVALID_ARG ESP_OK void esp_http_client_add_auth(esp_http_client_handle_t client) On receiving HTTP Status code 401, this API can be invoked to add authorization information. Note There is a possibility of receiving body message with redirection status codes, thus make sure to flush off body data after calling this API. Parameters client -- [in] The esp_http_client handle Parameters client -- [in] The esp_http_client handle bool esp_http_client_is_complete_data_received(esp_http_client_handle_t client) Checks if entire data in the response has been read without any error. Parameters client -- [in] The esp_http_client handle Returns true false true false true Parameters client -- [in] The esp_http_client handle Returns true false int esp_http_client_read_response(esp_http_client_handle_t client, char *buffer, int len) Helper API to read larger data chunks This is a helper API which internally calls esp_http_client_read multiple times till the end of data is reached or till the buffer gets full. Parameters client -- [in] The esp_http_client handle buffer -- The buffer len -- [in] The buffer length client -- [in] The esp_http_client handle buffer -- The buffer len -- [in] The buffer length client -- [in] The esp_http_client handle Returns Length of data was read Length of data was read Length of data was read Parameters client -- [in] The esp_http_client handle buffer -- The buffer len -- [in] The buffer length Returns Length of data was read esp_err_t esp_http_client_flush_response(esp_http_client_handle_t client, int *len) Process all remaining response data This uses an internal buffer to repeatedly receive, parse, and discard response data until complete data is processed. As no additional user-supplied buffer is required, this may be preferrable to esp_http_client_read_response in situations where the content of the response may be ignored. Parameters client -- [in] The esp_http_client handle len -- Length of data discarded client -- [in] The esp_http_client handle len -- Length of data discarded client -- [in] The esp_http_client handle Returns ESP_OK If successful, len will have discarded length ESP_FAIL If failed to read response ESP_ERR_INVALID_ARG If the client is NULL ESP_OK If successful, len will have discarded length ESP_FAIL If failed to read response ESP_ERR_INVALID_ARG If the client is NULL ESP_OK If successful, len will have discarded length Parameters client -- [in] The esp_http_client handle len -- Length of data discarded Returns ESP_OK If successful, len will have discarded length ESP_FAIL If failed to read response ESP_ERR_INVALID_ARG If the client is NULL esp_err_t esp_http_client_get_url(esp_http_client_handle_t client, char *url, const int len) Get URL from client. Parameters client -- [in] The esp_http_client handle url -- [inout] The buffer to store URL len -- [in] The buffer length client -- [in] The esp_http_client handle url -- [inout] The buffer to store URL len -- [in] The buffer length client -- [in] The esp_http_client handle Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters client -- [in] The esp_http_client handle url -- [inout] The buffer to store URL len -- [in] The buffer length Returns ESP_OK ESP_FAIL esp_err_t esp_http_client_get_chunk_length(esp_http_client_handle_t client, int *len) Get Chunk-Length from client. Parameters client -- [in] The esp_http_client handle len -- [out] Variable to store length client -- [in] The esp_http_client handle len -- [out] Variable to store length client -- [in] The esp_http_client handle Returns ESP_OK If successful, len will have length of current chunk ESP_FAIL If the server is not a chunked server ESP_ERR_INVALID_ARG If the client or len are NULL ESP_OK If successful, len will have length of current chunk ESP_FAIL If the server is not a chunked server ESP_ERR_INVALID_ARG If the client or len are NULL ESP_OK If successful, len will have length of current chunk Parameters client -- [in] The esp_http_client handle len -- [out] Variable to store length Returns ESP_OK If successful, len will have length of current chunk ESP_FAIL If the server is not a chunked server ESP_ERR_INVALID_ARG If the client or len are NULL Structures struct esp_http_client_event HTTP Client events data. Public Members esp_http_client_event_id_t event_id event_id, to know the cause of the event esp_http_client_event_id_t event_id event_id, to know the cause of the event esp_http_client_handle_t client esp_http_client_handle_t context esp_http_client_handle_t client esp_http_client_handle_t context void *data data of the event void *data data of the event int data_len data length of data int data_len data length of data void *user_data user_data context, from esp_http_client_config_t user_data void *user_data user_data context, from esp_http_client_config_t user_data char *header_key For HTTP_EVENT_ON_HEADER event_id, it's store current http header key char *header_key For HTTP_EVENT_ON_HEADER event_id, it's store current http header key char *header_value For HTTP_EVENT_ON_HEADER event_id, it's store current http header value char *header_value For HTTP_EVENT_ON_HEADER event_id, it's store current http header value esp_http_client_event_id_t event_id struct esp_http_client_on_data Argument structure for HTTP_EVENT_ON_DATA event. Public Members esp_http_client_handle_t client Client handle esp_http_client_handle_t client Client handle int64_t data_process Total data processed int64_t data_process Total data processed esp_http_client_handle_t client struct esp_http_client_redirect_event_data Argument structure for HTTP_EVENT_REDIRECT event. Public Members esp_http_client_handle_t client Client handle esp_http_client_handle_t client Client handle int status_code Status Code int status_code Status Code esp_http_client_handle_t client struct esp_http_client_config_t HTTP configuration. Public Members const char *url HTTP URL, the information on the URL is most important, it overrides the other fields below, if any const char *url HTTP URL, the information on the URL is most important, it overrides the other fields below, if any const char *host Domain or IP as string const char *host Domain or IP as string int port Port to connect, default depend on esp_http_client_transport_t (80 or 443) int port Port to connect, default depend on esp_http_client_transport_t (80 or 443) const char *username Using for Http authentication const char *username Using for Http authentication const char *password Using for Http authentication const char *password Using for Http authentication esp_http_client_auth_type_t auth_type Http authentication type, see esp_http_client_auth_type_t esp_http_client_auth_type_t auth_type Http authentication type, see esp_http_client_auth_type_t const char *path HTTP Path, if not set, default is / const char *path HTTP Path, if not set, default is / const char *query HTTP query const char *query HTTP query const char *cert_pem SSL server certification, PEM format as string, if the client requires to verify server const char *cert_pem SSL server certification, PEM format as string, if the client requires to verify server size_t cert_len Length of the buffer pointed to by cert_pem. May be 0 for null-terminated pem size_t cert_len Length of the buffer pointed to by cert_pem. May be 0 for null-terminated pem const char *client_cert_pem SSL client certification, PEM format as string, if the server requires to verify client const char *client_cert_pem SSL client certification, PEM format as string, if the server requires to verify client size_t client_cert_len Length of the buffer pointed to by client_cert_pem. May be 0 for null-terminated pem size_t client_cert_len Length of the buffer pointed to by client_cert_pem. May be 0 for null-terminated pem const char *client_key_pem SSL client key, PEM format as string, if the server requires to verify client const char *client_key_pem SSL client key, PEM format as string, if the server requires to verify client size_t client_key_len Length of the buffer pointed to by client_key_pem. May be 0 for null-terminated pem size_t client_key_len Length of the buffer pointed to by client_key_pem. May be 0 for null-terminated pem const char *client_key_password Client key decryption password string const char *client_key_password Client key decryption password string size_t client_key_password_len String length of the password pointed to by client_key_password size_t client_key_password_len String length of the password pointed to by client_key_password esp_http_client_proto_ver_t tls_version TLS protocol version of the connection, e.g., TLS 1.2, TLS 1.3 (default - no preference) esp_http_client_proto_ver_t tls_version TLS protocol version of the connection, e.g., TLS 1.2, TLS 1.3 (default - no preference) const char *user_agent The User Agent string to send with HTTP requests const char *user_agent The User Agent string to send with HTTP requests esp_http_client_method_t method HTTP Method esp_http_client_method_t method HTTP Method int timeout_ms Network timeout in milliseconds int timeout_ms Network timeout in milliseconds bool disable_auto_redirect Disable HTTP automatic redirects bool disable_auto_redirect Disable HTTP automatic redirects int max_redirection_count Max number of redirections on receiving HTTP redirect status code, using default value if zero int max_redirection_count Max number of redirections on receiving HTTP redirect status code, using default value if zero Max connection retries on receiving HTTP unauthorized status code, using default value if zero. Disables authorization retry if -1 Max connection retries on receiving HTTP unauthorized status code, using default value if zero. Disables authorization retry if -1 http_event_handle_cb event_handler HTTP Event Handle http_event_handle_cb event_handler HTTP Event Handle esp_http_client_transport_t transport_type HTTP transport type, see esp_http_client_transport_t esp_http_client_transport_t transport_type HTTP transport type, see esp_http_client_transport_t int buffer_size HTTP receive buffer size int buffer_size HTTP receive buffer size int buffer_size_tx HTTP transmit buffer size int buffer_size_tx HTTP transmit buffer size void *user_data HTTP user_data context void *user_data HTTP user_data context bool is_async Set asynchronous mode, only supported with HTTPS for now bool is_async Set asynchronous mode, only supported with HTTPS for now bool use_global_ca_store Use a global ca_store for all the connections in which this bool is set. bool use_global_ca_store Use a global ca_store for all the connections in which this bool is set. bool skip_cert_common_name_check Skip any validation of server certificate CN field bool skip_cert_common_name_check Skip any validation of server certificate CN field const char *common_name Pointer to the string containing server certificate common name. If non-NULL, server certificate CN must match this name, If NULL, server certificate CN must match hostname. const char *common_name Pointer to the string containing server certificate common name. If non-NULL, server certificate CN must match this name, If NULL, server certificate CN must match hostname. esp_err_t (*crt_bundle_attach)(void *conf) Function pointer to esp_crt_bundle_attach. Enables the use of certification bundle for server verification, must be enabled in menuconfig esp_err_t (*crt_bundle_attach)(void *conf) Function pointer to esp_crt_bundle_attach. Enables the use of certification bundle for server verification, must be enabled in menuconfig bool keep_alive_enable Enable keep-alive timeout bool keep_alive_enable Enable keep-alive timeout int keep_alive_idle Keep-alive idle time. Default is 5 (second) int keep_alive_idle Keep-alive idle time. Default is 5 (second) int keep_alive_interval Keep-alive interval time. Default is 5 (second) int keep_alive_interval Keep-alive interval time. Default is 5 (second) int keep_alive_count Keep-alive packet retry send count. Default is 3 counts int keep_alive_count Keep-alive packet retry send count. Default is 3 counts struct ifreq *if_name The name of interface for data to go through. Use the default interface without setting struct ifreq *if_name The name of interface for data to go through. Use the default interface without setting const char *url Macros DEFAULT_HTTP_BUF_SIZE ESP_ERR_HTTP_BASE Starting number of HTTP error codes ESP_ERR_HTTP_MAX_REDIRECT The error exceeds the number of HTTP redirects ESP_ERR_HTTP_CONNECT Error open the HTTP connection ESP_ERR_HTTP_WRITE_DATA Error write HTTP data ESP_ERR_HTTP_FETCH_HEADER Error read HTTP header from server ESP_ERR_HTTP_INVALID_TRANSPORT There are no transport support for the input scheme ESP_ERR_HTTP_CONNECTING HTTP connection hasn't been established yet ESP_ERR_HTTP_EAGAIN Mapping of errno EAGAIN to esp_err_t ESP_ERR_HTTP_CONNECTION_CLOSED Read FIN from peer and the connection closed Type Definitions typedef struct esp_http_client *esp_http_client_handle_t typedef struct esp_http_client_event *esp_http_client_event_handle_t typedef struct esp_http_client_event esp_http_client_event_t HTTP Client events data. typedef struct esp_http_client_on_data esp_http_client_on_data_t Argument structure for HTTP_EVENT_ON_DATA event. typedef struct esp_http_client_redirect_event_data esp_http_client_redirect_event_data_t Argument structure for HTTP_EVENT_REDIRECT event. typedef esp_err_t (*http_event_handle_cb)(esp_http_client_event_t *evt) Enumerations enum esp_http_client_event_id_t HTTP Client events id. Values: enumerator HTTP_EVENT_ERROR This event occurs when there are any errors during execution enumerator HTTP_EVENT_ERROR This event occurs when there are any errors during execution enumerator HTTP_EVENT_ON_CONNECTED Once the HTTP has been connected to the server, no data exchange has been performed enumerator HTTP_EVENT_ON_CONNECTED Once the HTTP has been connected to the server, no data exchange has been performed enumerator HTTP_EVENT_HEADERS_SENT After sending all the headers to the server enumerator HTTP_EVENT_HEADERS_SENT After sending all the headers to the server enumerator HTTP_EVENT_HEADER_SENT This header has been kept for backward compatability and will be deprecated in future versions esp-idf enumerator HTTP_EVENT_HEADER_SENT This header has been kept for backward compatability and will be deprecated in future versions esp-idf enumerator HTTP_EVENT_ON_HEADER Occurs when receiving each header sent from the server enumerator HTTP_EVENT_ON_HEADER Occurs when receiving each header sent from the server enumerator HTTP_EVENT_ON_DATA Occurs when receiving data from the server, possibly multiple portions of the packet enumerator HTTP_EVENT_ON_DATA Occurs when receiving data from the server, possibly multiple portions of the packet enumerator HTTP_EVENT_ON_FINISH Occurs when finish a HTTP session enumerator HTTP_EVENT_ON_FINISH Occurs when finish a HTTP session enumerator HTTP_EVENT_DISCONNECTED The connection has been disconnected enumerator HTTP_EVENT_DISCONNECTED The connection has been disconnected enumerator HTTP_EVENT_REDIRECT Intercepting HTTP redirects to handle them manually enumerator HTTP_EVENT_REDIRECT Intercepting HTTP redirects to handle them manually enumerator HTTP_EVENT_ERROR enum esp_http_client_transport_t HTTP Client transport. Values: enumerator HTTP_TRANSPORT_UNKNOWN Unknown enumerator HTTP_TRANSPORT_UNKNOWN Unknown enumerator HTTP_TRANSPORT_OVER_TCP Transport over tcp enumerator HTTP_TRANSPORT_OVER_TCP Transport over tcp enumerator HTTP_TRANSPORT_OVER_SSL Transport over ssl enumerator HTTP_TRANSPORT_OVER_SSL Transport over ssl enumerator HTTP_TRANSPORT_UNKNOWN enum esp_http_client_proto_ver_t Values: enumerator ESP_HTTP_CLIENT_TLS_VER_ANY enumerator ESP_HTTP_CLIENT_TLS_VER_ANY enumerator ESP_HTTP_CLIENT_TLS_VER_TLS_1_2 enumerator ESP_HTTP_CLIENT_TLS_VER_TLS_1_2 enumerator ESP_HTTP_CLIENT_TLS_VER_TLS_1_3 enumerator ESP_HTTP_CLIENT_TLS_VER_TLS_1_3 enumerator ESP_HTTP_CLIENT_TLS_VER_MAX enumerator ESP_HTTP_CLIENT_TLS_VER_MAX enumerator ESP_HTTP_CLIENT_TLS_VER_ANY enum esp_http_client_method_t HTTP method. Values: enumerator HTTP_METHOD_GET HTTP GET Method enumerator HTTP_METHOD_GET HTTP GET Method enumerator HTTP_METHOD_POST HTTP POST Method enumerator HTTP_METHOD_POST HTTP POST Method enumerator HTTP_METHOD_PUT HTTP PUT Method enumerator HTTP_METHOD_PUT HTTP PUT Method enumerator HTTP_METHOD_PATCH HTTP PATCH Method enumerator HTTP_METHOD_PATCH HTTP PATCH Method enumerator HTTP_METHOD_DELETE HTTP DELETE Method enumerator HTTP_METHOD_DELETE HTTP DELETE Method enumerator HTTP_METHOD_HEAD HTTP HEAD Method enumerator HTTP_METHOD_HEAD HTTP HEAD Method enumerator HTTP_METHOD_NOTIFY HTTP NOTIFY Method enumerator HTTP_METHOD_NOTIFY HTTP NOTIFY Method enumerator HTTP_METHOD_SUBSCRIBE HTTP SUBSCRIBE Method enumerator HTTP_METHOD_SUBSCRIBE HTTP SUBSCRIBE Method enumerator HTTP_METHOD_UNSUBSCRIBE HTTP UNSUBSCRIBE Method enumerator HTTP_METHOD_UNSUBSCRIBE HTTP UNSUBSCRIBE Method enumerator HTTP_METHOD_OPTIONS HTTP OPTIONS Method enumerator HTTP_METHOD_OPTIONS HTTP OPTIONS Method enumerator HTTP_METHOD_COPY HTTP COPY Method enumerator HTTP_METHOD_COPY HTTP COPY Method enumerator HTTP_METHOD_MOVE HTTP MOVE Method enumerator HTTP_METHOD_MOVE HTTP MOVE Method enumerator HTTP_METHOD_LOCK HTTP LOCK Method enumerator HTTP_METHOD_LOCK HTTP LOCK Method enumerator HTTP_METHOD_UNLOCK HTTP UNLOCK Method enumerator HTTP_METHOD_UNLOCK HTTP UNLOCK Method enumerator HTTP_METHOD_PROPFIND HTTP PROPFIND Method enumerator HTTP_METHOD_PROPFIND HTTP PROPFIND Method enumerator HTTP_METHOD_PROPPATCH HTTP PROPPATCH Method enumerator HTTP_METHOD_PROPPATCH HTTP PROPPATCH Method enumerator HTTP_METHOD_MKCOL HTTP MKCOL Method enumerator HTTP_METHOD_MKCOL HTTP MKCOL Method enumerator HTTP_METHOD_MAX enumerator HTTP_METHOD_MAX enumerator HTTP_METHOD_GET enum esp_http_client_auth_type_t HTTP Authentication type. Values: enumerator HTTP_AUTH_TYPE_NONE No authention enumerator HTTP_AUTH_TYPE_NONE No authention enumerator HTTP_AUTH_TYPE_BASIC HTTP Basic authentication enumerator HTTP_AUTH_TYPE_BASIC HTTP Basic authentication enumerator HTTP_AUTH_TYPE_DIGEST HTTP Disgest authentication enumerator HTTP_AUTH_TYPE_DIGEST HTTP Disgest authentication enumerator HTTP_AUTH_TYPE_NONE enum HttpStatus_Code Enum for the HTTP status codes. Values: enumerator HttpStatus_Ok enumerator HttpStatus_Ok enumerator HttpStatus_MultipleChoices enumerator HttpStatus_MultipleChoices enumerator HttpStatus_MovedPermanently enumerator HttpStatus_MovedPermanently enumerator HttpStatus_Found enumerator HttpStatus_Found enumerator HttpStatus_SeeOther enumerator HttpStatus_SeeOther enumerator HttpStatus_TemporaryRedirect enumerator HttpStatus_TemporaryRedirect enumerator HttpStatus_PermanentRedirect enumerator HttpStatus_PermanentRedirect enumerator HttpStatus_BadRequest enumerator HttpStatus_BadRequest enumerator HttpStatus_Forbidden enumerator HttpStatus_Forbidden enumerator HttpStatus_NotFound enumerator HttpStatus_NotFound enumerator HttpStatus_InternalError enumerator HttpStatus_InternalError enumerator HttpStatus_Ok
ESP HTTP Client Overview esp_http_client component provides a set of APIs for making HTTP/S requests from ESP-IDF applications. The steps to use these APIs are as follows: - esp_http_client_init(): Creates an esp_http_client_handle_tinstance, i.e., an HTTP client handle based on the given esp_http_client_config_tconfiguration. This function must be the first to be called; default values are assumed for the configuration values that are not explicitly defined by the user. - esp_http_client_perform(): Performs all operations of the esp_http_client- opening the connection, exchanging data, and closing the connection (as required), while blocking the current task before its completion. All related events are invoked through the event handler (as specified in esp_http_client_config_t). - esp_http_client_cleanup(): Closes the connection (if any) and frees up all the memory allocated to the HTTP client instance. This must be the last function to be called after the completion of operations. Application Example Simple example that uses ESP HTTP Client to make HTTP/S requests can be found at protocols/esp_http_client. Basic HTTP Request Check out the example functions http_rest_with_url and http_rest_with_hostname_path in the application example for implementation details. Persistent Connections Persistent connection means that the HTTP client can re-use the same connection for several exchanges. If the server does not request to close the connection with the Connection: close header, the connection is not dropped but is instead kept open and used for further requests. To allow ESP HTTP client to take full advantage of persistent connections, one should make as many requests as possible using the same handle instance. Check out the example functions http_rest_with_url and http_rest_with_hostname_path in the application example. Here, once the connection is created, multiple requests ( GET, POST, PUT, etc.) are made before the connection is closed. Use Secure Element (ATECC608) for TLS A secure element (ATECC608) can be also used for the underlying TLS connection in the HTTP client connection. Please refer to the ATECC608A (Secure Element) with ESP-TLS section in the ESP-TLS documentation for more details. The secure element support has to be first enabled in menuconfig through CONFIG_ESP_TLS_USE_SECURE_ELEMENT. Then the HTTP client can be configured to use secure element as follows: esp_http_client_config_t cfg = { /* other configurations options */ .use_secure_element = true, }; HTTPS Request ESP HTTP client supports SSL connections using mbedTLS, with the url configuration starting with https scheme or transport_type set to HTTP_TRANSPORT_OVER_SSL. HTTPS support can be configured via CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS (enabled by default). Note While making HTTPS requests, if server verification is needed, an additional root certificate (in PEM format) needs to be provided to the cert_pem member in the esp_http_client_config_t configuration. Users can also use the ESP x509 Certificate Bundle for server verification using the crt_bundle_attach member of the esp_http_client_config_t configuration. Check out the example functions https_with_url and https_with_hostname_path in the application example for implementation details of the above note. HTTP Stream Some applications need to open the connection and control the exchange of data actively (data streaming). In such cases, the application flow is different from regular requests. Example flow is given below: - esp_http_client_init(): Create a HTTP client handle. - esp_http_client_set_*or esp_http_client_delete_*: Modify the HTTP connection parameters (optional). - esp_http_client_open(): Open the HTTP connection with write_lenparameter (content length that needs to be written to server), set write_len=0for read-only connection. - esp_http_client_write(): Write data to server with a maximum length equal to write_lenof esp_http_client_open()function; no need to call this function for write_len=0. - esp_http_client_fetch_headers(): Read the HTTP Server response headers, after sending the request headers and server data (if any). Returns the content-lengthfrom the server and can be succeeded by esp_http_client_get_status_code()for getting the HTTP status of the connection. - esp_http_client_read(): Read the HTTP stream. - esp_http_client_close(): Close the connection. - esp_http_client_cleanup(): Release allocated resources. Check out the example function http_perform_as_stream_reader in the application example for implementation details. HTTP Authentication - ESP HTTP client supports both Basic and Digest Authentication. Users can provide the username and password in the urlor the usernameand passwordmembers of the esp_http_client_config_tconfiguration. For auth_type = HTTP_AUTH_TYPE_BASIC, the HTTP client takes only one perform operation to pass the authentication process. If auth_type = HTTP_AUTH_TYPE_NONE, but the usernameand passwordfields are present in the configuration, the HTTP client takes two perform operations. The client will receive the 401 Unauthorizedheader in its first attempt to connect to the server. Based on this information, it decides which authentication method to choose and performs it in the second operation. Check out the example functions http_auth_basic, http_auth_basic_redirect(for Basic authentication) and http_auth_digest(for Digest authentication) in the application example for implementation details. - Examples of Authentication Configuration - Authentication with URIesp_http_client_config_t config = { .url = "http://user:passwd@httpbin.org/basic-auth/user/passwd", .auth_type = HTTP_AUTH_TYPE_BASIC, }; - Authentication with username and password entryesp_http_client_config_t config = { .url = "http://httpbin.org/basic-auth/user/passwd", .username = "user", .password = "passwd", .auth_type = HTTP_AUTH_TYPE_BASIC, }; Event Handling ESP HTTP Client supports event handling by triggering an event handler corresponding to the event which takes place. esp_http_client_event_id_t contains all the events which could occur while performing an HTTP request using the ESP HTTP Client. To enable event handling, you just need to set a callback function using the esp_http_client_config_t::event_handler member. ESP HTTP Client Diagnostic Information Diagnostic information could be helpful to gain insights into a problem. In the case of ESP HTTP Client, the diagnostic information can be collected by registering an event handler with the Event Loop library. This feature has been added by keeping in mind the ESP Insights framework which collects the diagnostic information. However, this feature can also be used without any dependency on the ESP Insights framework for the diagnostic purpose. Event handler can be registered to the event loop using the esp_event_handler_register() function. Expected data types for different HTTP Client events in the event loop are as follows: - HTTP_EVENT_ERROR : esp_http_client_handle_t - HTTP_EVENT_ON_CONNECTED : esp_http_client_handle_t - HTTP_EVENT_HEADERS_SENT : esp_http_client_handle_t - HTTP_EVENT_ON_HEADER : esp_http_client_handle_t - HTTP_EVENT_ON_DATA : esp_http_client_on_data_t - HTTP_EVENT_ON_FINISH : esp_http_client_handle_t - HTTP_EVENT_DISCONNECTED : esp_http_client_handle_t - HTTP_EVENT_REDIRECT : esp_http_client_redirect_event_data_t The esp_http_client_handle_t received along with the event data will be valid until HTTP_EVENT_DISCONNECTED is not received. This handle has been sent primarily to differentiate between different client connections and must not be used for any other purpose, as it may change based on client connection state. API Reference Header File This header file can be included with: #include "esp_http_client.h" This header file is a part of the API provided by the esp_http_clientcomponent. To declare that your component depends on esp_http_client, add the following to your CMakeLists.txt: REQUIRES esp_http_client or PRIV_REQUIRES esp_http_client Functions - esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *config) Start a HTTP session This function must be the first function to call, and it returns a esp_http_client_handle_t that you must use as input to other functions in the interface. This call MUST have a corresponding call to esp_http_client_cleanup when the operation is complete. - Parameters config -- [in] The configurations, see http_client_config_t - Returns esp_http_client_handle_t NULL if any errors - - esp_err_t esp_http_client_perform(esp_http_client_handle_t client) Invoke this function after esp_http_client_initand all the options calls are made, and will perform the transfer as described in the options. It must be called with the same esp_http_client_handle_t as input as the esp_http_client_init call returned. esp_http_client_perform performs the entire request in either blocking or non-blocking manner. By default, the API performs request in a blocking manner and returns when done, or if it failed, and in non-blocking manner, it returns if EAGAIN/EWOULDBLOCK or EINPROGRESS is encountered, or if it failed. And in case of non-blocking request, the user may call this API multiple times unless request & response is complete or there is a failure. To enable non-blocking esp_http_client_perform(), is_asyncmember of esp_http_client_config_t must be set while making a call to esp_http_client_init() API. You can do any amount of calls to esp_http_client_perform while using the same esp_http_client_handle_t. The underlying connection may be kept open if the server allows it. If you intend to transfer more than one file, you are even encouraged to do so. esp_http_client will then attempt to re-use the same connection for the following transfers, thus making the operations faster, less CPU intense and using less network resources. Just note that you will have to use esp_http_client_set_**between the invokes to set options for the following esp_http_client_perform. Note You must never call this function simultaneously from two places using the same client handle. Let the function return first before invoking it another time. If you want parallel transfers, you must use several esp_http_client_handle_t. This function include esp_http_client_open-> esp_http_client_write-> esp_http_client_fetch_headers-> esp_http_client_read(and option) esp_http_client_close. - Parameters client -- The esp_http_client handle - Returns ESP_OK on successful ESP_FAIL on error - - esp_err_t esp_http_client_cancel_request(esp_http_client_handle_t client) Cancel an ongoing HTTP request. This API closes the current socket and opens a new socket with the same esp_http_client context. - Parameters client -- The esp_http_client handle - Returns ESP_OK on successful ESP_FAIL on error ESP_ERR_INVALID_ARG ESP_ERR_INVALID_STATE - - esp_err_t esp_http_client_set_url(esp_http_client_handle_t client, const char *url) Set URL for client, when performing this behavior, the options in the URL will replace the old ones. - Parameters client -- [in] The esp_http_client handle url -- [in] The url - - Returns ESP_OK ESP_FAIL - - esp_err_t esp_http_client_set_post_field(esp_http_client_handle_t client, const char *data, int len) Set post data, this function must be called before esp_http_client_perform. Note: The data parameter passed to this function is a pointer and this function will not copy the data. - Parameters client -- [in] The esp_http_client handle data -- [in] post data pointer len -- [in] post length - - Returns ESP_OK ESP_FAIL - - int esp_http_client_get_post_field(esp_http_client_handle_t client, char **data) Get current post field information. - Parameters client -- [in] The client data -- [out] Point to post data pointer - - Returns Size of post data - esp_err_t esp_http_client_set_header(esp_http_client_handle_t client, const char *key, const char *value) Set http request header, this function must be called after esp_http_client_init and before any perform function. - Parameters client -- [in] The esp_http_client handle key -- [in] The header key value -- [in] The header value - - Returns ESP_OK ESP_FAIL - - esp_err_t esp_http_client_get_header(esp_http_client_handle_t client, const char *key, char **value) Get http request header. The value parameter will be set to NULL if there is no header which is same as the key specified, otherwise the address of header value will be assigned to value parameter. This function must be called after esp_http_client_init. - Parameters client -- [in] The esp_http_client handle key -- [in] The header key value -- [out] The header value - - Returns ESP_OK ESP_FAIL - - esp_err_t esp_http_client_get_username(esp_http_client_handle_t client, char **value) Get http request username. The address of username buffer will be assigned to value parameter. This function must be called after esp_http_client_init. - Parameters client -- [in] The esp_http_client handle value -- [out] The username value - - Returns ESP_OK ESP_ERR_INVALID_ARG - - esp_err_t esp_http_client_set_username(esp_http_client_handle_t client, const char *username) Set http request username. The value of username parameter will be assigned to username buffer. If the username parameter is NULL then username buffer will be freed. - Parameters client -- [in] The esp_http_client handle username -- [in] The username value - - Returns ESP_OK ESP_ERR_INVALID_ARG - - esp_err_t esp_http_client_get_password(esp_http_client_handle_t client, char **value) Get http request password. The address of password buffer will be assigned to value parameter. This function must be called after esp_http_client_init. - Parameters client -- [in] The esp_http_client handle value -- [out] The password value - - Returns ESP_OK ESP_ERR_INVALID_ARG - - esp_err_t esp_http_client_set_password(esp_http_client_handle_t client, const char *password) Set http request password. The value of password parameter will be assigned to password buffer. If the password parameter is NULL then password buffer will be freed. - Parameters client -- [in] The esp_http_client handle password -- [in] The password value - - Returns ESP_OK ESP_ERR_INVALID_ARG - - esp_err_t esp_http_client_set_authtype(esp_http_client_handle_t client, esp_http_client_auth_type_t auth_type) Set http request auth_type. - Parameters client -- [in] The esp_http_client handle auth_type -- [in] The esp_http_client auth type - - Returns ESP_OK ESP_ERR_INVALID_ARG - - esp_err_t esp_http_client_get_user_data(esp_http_client_handle_t client, void **data) Get http request user_data. The value stored from the esp_http_client_config_t will be written to the address passed into data. - Parameters client -- [in] The esp_http_client handle data -- [out] A pointer to the pointer that will be set to user_data. - - Returns ESP_OK ESP_ERR_INVALID_ARG - - esp_err_t esp_http_client_set_user_data(esp_http_client_handle_t client, void *data) Set http request user_data. The value passed in +data+ will be available during event callbacks. No memory management will be performed on the user's behalf. - Parameters client -- [in] The esp_http_client handle data -- [in] The pointer to the user data - - Returns ESP_OK ESP_ERR_INVALID_ARG - - int esp_http_client_get_errno(esp_http_client_handle_t client) Get HTTP client session errno. - Parameters client -- [in] The esp_http_client handle - Returns (-1) if invalid argument errno - - esp_err_t esp_http_client_set_method(esp_http_client_handle_t client, esp_http_client_method_t method) Set http request method. - Parameters client -- [in] The esp_http_client handle method -- [in] The method - - Returns ESP_OK ESP_ERR_INVALID_ARG - - esp_err_t esp_http_client_set_timeout_ms(esp_http_client_handle_t client, int timeout_ms) Set http request timeout. - Parameters client -- [in] The esp_http_client handle timeout_ms -- [in] The timeout value - - Returns ESP_OK ESP_ERR_INVALID_ARG - - esp_err_t esp_http_client_delete_header(esp_http_client_handle_t client, const char *key) Delete http request header. - Parameters client -- [in] The esp_http_client handle key -- [in] The key - - Returns ESP_OK ESP_FAIL - - esp_err_t esp_http_client_open(esp_http_client_handle_t client, int write_len) This function will be open the connection, write all header strings and return. - Parameters client -- [in] The esp_http_client handle write_len -- [in] HTTP Content length need to write to the server - - Returns ESP_OK ESP_FAIL - - int esp_http_client_write(esp_http_client_handle_t client, const char *buffer, int len) This function will write data to the HTTP connection previously opened by esp_http_client_open() - Parameters client -- [in] The esp_http_client handle buffer -- The buffer len -- [in] This value must not be larger than the write_len parameter provided to esp_http_client_open() - - Returns (-1) if any errors Length of data written - - int64_t esp_http_client_fetch_headers(esp_http_client_handle_t client) This function need to call after esp_http_client_open, it will read from http stream, process all receive headers. - Parameters client -- [in] The esp_http_client handle - Returns (0) if stream doesn't contain content-length header, or chunked encoding (checked by esp_http_client_is_chunkedresponse) (-1: ESP_FAIL) if any errors (-ESP_ERR_HTTP_EAGAIN = -0x7007) if call is timed-out before any data was ready Download data length defined by content-length header - - bool esp_http_client_is_chunked_response(esp_http_client_handle_t client) Check response data is chunked. - Parameters client -- [in] The esp_http_client handle - Returns true or false - int esp_http_client_read(esp_http_client_handle_t client, char *buffer, int len) Read data from http stream. Note (-ESP_ERR_HTTP_EAGAIN = -0x7007) is returned when call is timed-out before any data was ready - Parameters client -- [in] The esp_http_client handle buffer -- The buffer len -- [in] The length - - Returns (-1) if any errors Length of data was read - - int esp_http_client_get_status_code(esp_http_client_handle_t client) Get http response status code, the valid value if this function invoke after esp_http_client_perform - Parameters client -- [in] The esp_http_client handle - Returns Status code - int64_t esp_http_client_get_content_length(esp_http_client_handle_t client) Get http response content length (from header Content-Length) the valid value if this function invoke after esp_http_client_perform - Parameters client -- [in] The esp_http_client handle - Returns (-1) Chunked transfer Content-Length value as bytes - - esp_err_t esp_http_client_close(esp_http_client_handle_t client) Close http connection, still kept all http request resources. - Parameters client -- [in] The esp_http_client handle - Returns ESP_OK ESP_FAIL - - esp_err_t esp_http_client_cleanup(esp_http_client_handle_t client) This function must be the last function to call for an session. It is the opposite of the esp_http_client_init function and must be called with the same handle as input that a esp_http_client_init call returned. This might close all connections this handle has used and possibly has kept open until now. Don't call this function if you intend to transfer more files, re-using handles is a key to good performance with esp_http_client. - Parameters client -- [in] The esp_http_client handle - Returns ESP_OK ESP_FAIL - - esp_http_client_transport_t esp_http_client_get_transport_type(esp_http_client_handle_t client) Get transport type. - Parameters client -- [in] The esp_http_client handle - Returns HTTP_TRANSPORT_UNKNOWN HTTP_TRANSPORT_OVER_TCP HTTP_TRANSPORT_OVER_SSL - - esp_err_t esp_http_client_set_redirection(esp_http_client_handle_t client) Set redirection URL. When received the 30x code from the server, the client stores the redirect URL provided by the server. This function will set the current URL to redirect to enable client to execute the redirection request. When disable_auto_redirectis set, the client will not call this function but the event HTTP_EVENT_REDIRECTwill be dispatched giving the user contol over the redirection event. - Parameters client -- [in] The esp_http_client handle - Returns ESP_OK ESP_FAIL - - esp_err_t esp_http_client_set_auth_data(esp_http_client_handle_t client, const char *auth_data, int len) On receiving a custom authentication header, this API can be invoked to set the authentication information from the header. This API can be called from the event handler. - Parameters client -- [in] The esp_http_client handle auth_data -- [in] The authentication data received in the header len -- [in] length of auth_data. - - Returns ESP_ERR_INVALID_ARG ESP_OK - - void esp_http_client_add_auth(esp_http_client_handle_t client) On receiving HTTP Status code 401, this API can be invoked to add authorization information. Note There is a possibility of receiving body message with redirection status codes, thus make sure to flush off body data after calling this API. - Parameters client -- [in] The esp_http_client handle - bool esp_http_client_is_complete_data_received(esp_http_client_handle_t client) Checks if entire data in the response has been read without any error. - Parameters client -- [in] The esp_http_client handle - Returns true false - - int esp_http_client_read_response(esp_http_client_handle_t client, char *buffer, int len) Helper API to read larger data chunks This is a helper API which internally calls esp_http_client_readmultiple times till the end of data is reached or till the buffer gets full. - Parameters client -- [in] The esp_http_client handle buffer -- The buffer len -- [in] The buffer length - - Returns Length of data was read - - esp_err_t esp_http_client_flush_response(esp_http_client_handle_t client, int *len) Process all remaining response data This uses an internal buffer to repeatedly receive, parse, and discard response data until complete data is processed. As no additional user-supplied buffer is required, this may be preferrable to esp_http_client_read_responsein situations where the content of the response may be ignored. - Parameters client -- [in] The esp_http_client handle len -- Length of data discarded - - Returns ESP_OK If successful, len will have discarded length ESP_FAIL If failed to read response ESP_ERR_INVALID_ARG If the client is NULL - - esp_err_t esp_http_client_get_url(esp_http_client_handle_t client, char *url, const int len) Get URL from client. - Parameters client -- [in] The esp_http_client handle url -- [inout] The buffer to store URL len -- [in] The buffer length - - Returns ESP_OK ESP_FAIL - - esp_err_t esp_http_client_get_chunk_length(esp_http_client_handle_t client, int *len) Get Chunk-Length from client. - Parameters client -- [in] The esp_http_client handle len -- [out] Variable to store length - - Returns ESP_OK If successful, len will have length of current chunk ESP_FAIL If the server is not a chunked server ESP_ERR_INVALID_ARG If the client or len are NULL - Structures - struct esp_http_client_event HTTP Client events data. Public Members - esp_http_client_event_id_t event_id event_id, to know the cause of the event - esp_http_client_handle_t client esp_http_client_handle_t context - void *data data of the event - int data_len data length of data - void *user_data user_data context, from esp_http_client_config_t user_data - char *header_key For HTTP_EVENT_ON_HEADER event_id, it's store current http header key - char *header_value For HTTP_EVENT_ON_HEADER event_id, it's store current http header value - esp_http_client_event_id_t event_id - struct esp_http_client_on_data Argument structure for HTTP_EVENT_ON_DATA event. Public Members - esp_http_client_handle_t client Client handle - int64_t data_process Total data processed - esp_http_client_handle_t client - struct esp_http_client_redirect_event_data Argument structure for HTTP_EVENT_REDIRECT event. Public Members - esp_http_client_handle_t client Client handle - int status_code Status Code - esp_http_client_handle_t client - struct esp_http_client_config_t HTTP configuration. Public Members - const char *url HTTP URL, the information on the URL is most important, it overrides the other fields below, if any - const char *host Domain or IP as string - int port Port to connect, default depend on esp_http_client_transport_t (80 or 443) - const char *username Using for Http authentication - const char *password Using for Http authentication - esp_http_client_auth_type_t auth_type Http authentication type, see esp_http_client_auth_type_t - const char *path HTTP Path, if not set, default is / - const char *query HTTP query - const char *cert_pem SSL server certification, PEM format as string, if the client requires to verify server - size_t cert_len Length of the buffer pointed to by cert_pem. May be 0 for null-terminated pem - const char *client_cert_pem SSL client certification, PEM format as string, if the server requires to verify client - size_t client_cert_len Length of the buffer pointed to by client_cert_pem. May be 0 for null-terminated pem - const char *client_key_pem SSL client key, PEM format as string, if the server requires to verify client - size_t client_key_len Length of the buffer pointed to by client_key_pem. May be 0 for null-terminated pem - const char *client_key_password Client key decryption password string - size_t client_key_password_len String length of the password pointed to by client_key_password - esp_http_client_proto_ver_t tls_version TLS protocol version of the connection, e.g., TLS 1.2, TLS 1.3 (default - no preference) - const char *user_agent The User Agent string to send with HTTP requests - esp_http_client_method_t method HTTP Method - int timeout_ms Network timeout in milliseconds - bool disable_auto_redirect Disable HTTP automatic redirects - int max_redirection_count Max number of redirections on receiving HTTP redirect status code, using default value if zero Max connection retries on receiving HTTP unauthorized status code, using default value if zero. Disables authorization retry if -1 - http_event_handle_cb event_handler HTTP Event Handle - esp_http_client_transport_t transport_type HTTP transport type, see esp_http_client_transport_t - int buffer_size HTTP receive buffer size - int buffer_size_tx HTTP transmit buffer size - void *user_data HTTP user_data context - bool is_async Set asynchronous mode, only supported with HTTPS for now - bool use_global_ca_store Use a global ca_store for all the connections in which this bool is set. - bool skip_cert_common_name_check Skip any validation of server certificate CN field - const char *common_name Pointer to the string containing server certificate common name. If non-NULL, server certificate CN must match this name, If NULL, server certificate CN must match hostname. - esp_err_t (*crt_bundle_attach)(void *conf) Function pointer to esp_crt_bundle_attach. Enables the use of certification bundle for server verification, must be enabled in menuconfig - bool keep_alive_enable Enable keep-alive timeout - int keep_alive_idle Keep-alive idle time. Default is 5 (second) - int keep_alive_interval Keep-alive interval time. Default is 5 (second) - int keep_alive_count Keep-alive packet retry send count. Default is 3 counts - struct ifreq *if_name The name of interface for data to go through. Use the default interface without setting - const char *url Macros - DEFAULT_HTTP_BUF_SIZE - ESP_ERR_HTTP_BASE Starting number of HTTP error codes - ESP_ERR_HTTP_MAX_REDIRECT The error exceeds the number of HTTP redirects - ESP_ERR_HTTP_CONNECT Error open the HTTP connection - ESP_ERR_HTTP_WRITE_DATA Error write HTTP data - ESP_ERR_HTTP_FETCH_HEADER Error read HTTP header from server - ESP_ERR_HTTP_INVALID_TRANSPORT There are no transport support for the input scheme - ESP_ERR_HTTP_CONNECTING HTTP connection hasn't been established yet - ESP_ERR_HTTP_EAGAIN Mapping of errno EAGAIN to esp_err_t - ESP_ERR_HTTP_CONNECTION_CLOSED Read FIN from peer and the connection closed Type Definitions - typedef struct esp_http_client *esp_http_client_handle_t - typedef struct esp_http_client_event *esp_http_client_event_handle_t - typedef struct esp_http_client_event esp_http_client_event_t HTTP Client events data. - typedef struct esp_http_client_on_data esp_http_client_on_data_t Argument structure for HTTP_EVENT_ON_DATA event. - typedef struct esp_http_client_redirect_event_data esp_http_client_redirect_event_data_t Argument structure for HTTP_EVENT_REDIRECT event. - typedef esp_err_t (*http_event_handle_cb)(esp_http_client_event_t *evt) Enumerations - enum esp_http_client_event_id_t HTTP Client events id. Values: - enumerator HTTP_EVENT_ERROR This event occurs when there are any errors during execution - enumerator HTTP_EVENT_ON_CONNECTED Once the HTTP has been connected to the server, no data exchange has been performed - enumerator HTTP_EVENT_HEADERS_SENT After sending all the headers to the server - enumerator HTTP_EVENT_HEADER_SENT This header has been kept for backward compatability and will be deprecated in future versions esp-idf - enumerator HTTP_EVENT_ON_HEADER Occurs when receiving each header sent from the server - enumerator HTTP_EVENT_ON_DATA Occurs when receiving data from the server, possibly multiple portions of the packet - enumerator HTTP_EVENT_ON_FINISH Occurs when finish a HTTP session - enumerator HTTP_EVENT_DISCONNECTED The connection has been disconnected - enumerator HTTP_EVENT_REDIRECT Intercepting HTTP redirects to handle them manually - enumerator HTTP_EVENT_ERROR - enum esp_http_client_transport_t HTTP Client transport. Values: - enumerator HTTP_TRANSPORT_UNKNOWN Unknown - enumerator HTTP_TRANSPORT_OVER_TCP Transport over tcp - enumerator HTTP_TRANSPORT_OVER_SSL Transport over ssl - enumerator HTTP_TRANSPORT_UNKNOWN - enum esp_http_client_proto_ver_t Values: - enumerator ESP_HTTP_CLIENT_TLS_VER_ANY - enumerator ESP_HTTP_CLIENT_TLS_VER_TLS_1_2 - enumerator ESP_HTTP_CLIENT_TLS_VER_TLS_1_3 - enumerator ESP_HTTP_CLIENT_TLS_VER_MAX - enumerator ESP_HTTP_CLIENT_TLS_VER_ANY - enum esp_http_client_method_t HTTP method. Values: - enumerator HTTP_METHOD_GET HTTP GET Method - enumerator HTTP_METHOD_POST HTTP POST Method - enumerator HTTP_METHOD_PUT HTTP PUT Method - enumerator HTTP_METHOD_PATCH HTTP PATCH Method - enumerator HTTP_METHOD_DELETE HTTP DELETE Method - enumerator HTTP_METHOD_HEAD HTTP HEAD Method - enumerator HTTP_METHOD_NOTIFY HTTP NOTIFY Method - enumerator HTTP_METHOD_SUBSCRIBE HTTP SUBSCRIBE Method - enumerator HTTP_METHOD_UNSUBSCRIBE HTTP UNSUBSCRIBE Method - enumerator HTTP_METHOD_OPTIONS HTTP OPTIONS Method - enumerator HTTP_METHOD_COPY HTTP COPY Method - enumerator HTTP_METHOD_MOVE HTTP MOVE Method - enumerator HTTP_METHOD_LOCK HTTP LOCK Method - enumerator HTTP_METHOD_UNLOCK HTTP UNLOCK Method - enumerator HTTP_METHOD_PROPFIND HTTP PROPFIND Method - enumerator HTTP_METHOD_PROPPATCH HTTP PROPPATCH Method - enumerator HTTP_METHOD_MKCOL HTTP MKCOL Method - enumerator HTTP_METHOD_MAX - enumerator HTTP_METHOD_GET - enum esp_http_client_auth_type_t HTTP Authentication type. Values: - enumerator HTTP_AUTH_TYPE_NONE No authention - enumerator HTTP_AUTH_TYPE_BASIC HTTP Basic authentication - enumerator HTTP_AUTH_TYPE_DIGEST HTTP Disgest authentication - enumerator HTTP_AUTH_TYPE_NONE - enum HttpStatus_Code Enum for the HTTP status codes. Values: - enumerator HttpStatus_Ok - enumerator HttpStatus_MultipleChoices - enumerator HttpStatus_MovedPermanently - enumerator HttpStatus_Found - enumerator HttpStatus_SeeOther - enumerator HttpStatus_TemporaryRedirect - enumerator HttpStatus_PermanentRedirect - enumerator HttpStatus_BadRequest - enumerator HttpStatus_Forbidden - enumerator HttpStatus_NotFound - enumerator HttpStatus_InternalError - enumerator HttpStatus_Ok
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/protocols/esp_http_client.html
ESP-IDF Programming Guide v5.2.1 documentation
null
ESP Local Control
null
espressif.com
2016-01-01
2289ac90e489fa49
null
null
ESP Local Control Overview ESP Local Control (esp_local_ctrl) component in ESP-IDF provides capability to control an ESP device over HTTPS or Bluetooth® Low Energy. It provides access to application defined properties that are available for reading/writing via a set of configurable handlers. Initialization of the esp_local_ctrl service over Bluetooth Low Energy transport is performed as follows: esp_local_ctrl_config_t config = { .transport = ESP_LOCAL_CTRL_TRANSPORT_BLE, .transport_config = { .ble = & (protocomm_ble_config_t) { .device_name = SERVICE_NAME, .service_uuid = { /* LSB <--------------------------------------- * ---------------------------------------> MSB */ 0x21, 0xd5, 0x3b, 0x8d, 0xbd, 0x75, 0x68, 0x8a, 0xb4, 0x42, 0xeb, 0x31, 0x4a, 0x1e, 0x98, 0x3d } } }, .proto_sec = { .version = PROTOCOM_SEC0, .custom_handle = NULL, .sec_params = NULL, }, .handlers = { /* User defined handler functions */ .get_prop_values = get_property_values, .set_prop_values = set_property_values, .usr_ctx = NULL, .usr_ctx_free_fn = NULL }, /* Maximum number of properties that may be set */ .max_properties = 10 }; /* Start esp_local_ctrl service */ ESP_ERROR_CHECK(esp_local_ctrl_start(&config)); Similarly for HTTPS transport: /* Set the configuration */ httpd_ssl_config_t https_conf = HTTPD_SSL_CONFIG_DEFAULT(); /* Load server certificate */ extern const unsigned char servercert_start[] asm("_binary_servercert_pem_start"); extern const unsigned char servercert_end[] asm("_binary_servercert_pem_end"); https_conf.servercert = servercert_start; https_conf.servercert_len = servercert_end - servercert_start; /* Load server private key */ extern const unsigned char prvtkey_pem_start[] asm("_binary_prvtkey_pem_start"); extern const unsigned char prvtkey_pem_end[] asm("_binary_prvtkey_pem_end"); https_conf.prvtkey_pem = prvtkey_pem_start; https_conf.prvtkey_len = prvtkey_pem_end - prvtkey_pem_start; esp_local_ctrl_config_t config = { .transport = ESP_LOCAL_CTRL_TRANSPORT_HTTPD, .transport_config = { .httpd = &https_conf }, .proto_sec = { .version = PROTOCOM_SEC0, .custom_handle = NULL, .sec_params = NULL, }, .handlers = { /* User defined handler functions */ .get_prop_values = get_property_values, .set_prop_values = set_property_values, .usr_ctx = NULL, .usr_ctx_free_fn = NULL }, /* Maximum number of properties that may be set */ .max_properties = 10 }; /* Start esp_local_ctrl service */ ESP_ERROR_CHECK(esp_local_ctrl_start(&config)); You may set security for transport in ESP local control using following options: PROTOCOM_SEC2 : specifies that SRP6a-based key exchange and end-to-end encryption based on AES-GCM are used. This is the most preferred option as it adds a robust security with Augmented PAKE protocol, i.e., SRP6a. PROTOCOM_SEC1 : specifies that Curve25519-based key exchange and end-to-end encryption based on AES-CTR are used. PROTOCOM_SEC0 : specifies that data will be exchanged as a plain text (no security). PROTOCOM_SEC_CUSTOM : you can define your own security requirement. Please note that you will also have to provide custom_handle of type protocomm_security_t * in this context. Note The respective security schemes need to be enabled through the project configuration menu. Please refer to the Enabling protocom security version section in Protocol Communication for more details. Creating a Property Now that we know how to start the esp_local_ctrl service, let's add a property to it. Each property must have a unique `name` (string), a type (e.g., enum), flags` (bit fields) and size` . The size is to be kept 0, if we want our property value to be of variable length (e.g., if it is a string or bytestream). For data types with fixed-length property value, like int, float, etc., setting the size field to the right value helps esp_local_ctrl to perform internal checks on arguments received with write requests. The interpretation of type and flags fields is totally upto the application, hence they may be used as enumerations, bitfields, or even simple integers. One way is to use type values to classify properties, while flags to specify characteristics of a property. Here is an example property which is to function as a timestamp. It is assumed that the application defines TYPE_TIMESTAMP and READONLY , which are used for setting the type and flags fields here. /* Create a timestamp property */ esp_local_ctrl_prop_t timestamp = { .name = "timestamp", .type = TYPE_TIMESTAMP, .size = sizeof(int32_t), .flags = READONLY, .ctx = func_get_time, .ctx_free_fn = NULL }; /* Now register the property */ esp_local_ctrl_add_property(&timestamp); Also notice that there is a ctx field, which is set to point to some custom func_get_time(). This can be used inside the property get/set handlers to retrieve timestamp. Here is an example of get_prop_values() handler, which is used for retrieving the timestamp. static esp_err_t get_property_values(size_t props_count, const esp_local_ctrl_prop_t *props, esp_local_ctrl_prop_val_t *prop_values, void *usr_ctx) { for (uint32_t i = 0; i < props_count; i++) { ESP_LOGI(TAG, "Reading %s", props[i].name); if (props[i].type == TYPE_TIMESTAMP) { /* Obtain the timer function from ctx */ int32_t (*func_get_time)(void) = props[i].ctx; /* Use static variable for saving the value. This is essential because the value has to be valid even after this function returns. Alternative is to use dynamic allocation and set the free_fn field */ static int32_t ts = func_get_time(); prop_values[i].data = &ts; } } return ESP_OK; } Here is an example of set_prop_values() handler. Notice how we restrict from writing to read-only properties. static esp_err_t set_property_values(size_t props_count, const esp_local_ctrl_prop_t *props, const esp_local_ctrl_prop_val_t *prop_values, void *usr_ctx) { for (uint32_t i = 0; i < props_count; i++) { if (props[i].flags & READONLY) { ESP_LOGE(TAG, "Cannot write to read-only property %s", props[i].name); return ESP_ERR_INVALID_ARG; } else { ESP_LOGI(TAG, "Setting %s", props[i].name); /* For keeping it simple, lets only log the incoming data */ ESP_LOG_BUFFER_HEX_LEVEL(TAG, prop_values[i].data, prop_values[i].size, ESP_LOG_INFO); } } return ESP_OK; } For complete example see protocols/esp_local_ctrl. Client Side Implementation The client side implementation establishes a protocomm session with the device first, over the supported mode of transport, and then send and receive protobuf messages understood by the esp_local_ctrl service. The service translates these messages into requests and then call the appropriate handlers (set/get). Then, the generated response for each handler is again packed into a protobuf message and transmitted back to the client. See below the various protobuf messages understood by the esp_local_ctrl service: get_prop_count : This should simply return the total number of properties supported by the service. get_prop_values : This accepts an array of indices and should return the information (name, type, flags) and values of the properties corresponding to those indices. set_prop_values : This accepts an array of indices and an array of new values, which are used for setting the values of the properties corresponding to the indices. Note that indices may or may not be the same for a property, across multiple sessions. Therefore, the client must only use the names of the properties to uniquely identify them. So, every time a new session is established, the client should first call get_prop_count and then get_prop_values , hence form an index-to-name mapping for all properties. Now when calling set_prop_values for a set of properties, it must first convert the names to indexes, using the created mapping. As emphasized earlier, the client must refresh the index-to-name mapping every time a new session is established with the same device. The various protocomm endpoints provided by esp_local_ctrl are listed below: Endpoint Name (Bluetooth Low Energy + GATT Server) URI (HTTPS Server + mDNS) Description esp_local_ctrl/version https://<mdns-hostname>.local/esp_local_ctrl/version Endpoint used for retrieving version string esp_local_ctrl/control https://<mdns-hostname>.local/esp_local_ctrl/control Endpoint used for sending or receiving control messages API Reference Header File This header file can be included with: #include "esp_local_ctrl.h" This header file is a part of the API provided by the esp_local_ctrl component. To declare that your component depends on esp_local_ctrl , add the following to your CMakeLists.txt: REQUIRES esp_local_ctrl or PRIV_REQUIRES esp_local_ctrl Functions const esp_local_ctrl_transport_t *esp_local_ctrl_get_transport_ble(void) Function for obtaining BLE transport mode. const esp_local_ctrl_transport_t *esp_local_ctrl_get_transport_httpd(void) Function for obtaining HTTPD transport mode. esp_err_t esp_local_ctrl_start(const esp_local_ctrl_config_t *config) Start local control service. Parameters config -- [in] Pointer to configuration structure Returns ESP_OK : Success ESP_FAIL : Failure ESP_OK : Success ESP_FAIL : Failure ESP_OK : Success Parameters config -- [in] Pointer to configuration structure Returns ESP_OK : Success ESP_FAIL : Failure esp_err_t esp_local_ctrl_add_property(const esp_local_ctrl_prop_t *prop) Add a new property. This adds a new property and allocates internal resources for it. The total number of properties that could be added is limited by configuration option max_properties Parameters prop -- [in] Property description structure Returns ESP_OK : Success ESP_FAIL : Failure ESP_OK : Success ESP_FAIL : Failure ESP_OK : Success Parameters prop -- [in] Property description structure Returns ESP_OK : Success ESP_FAIL : Failure esp_err_t esp_local_ctrl_remove_property(const char *name) Remove a property. This finds a property by name, and releases the internal resources which are associated with it. Parameters name -- [in] Name of the property to remove Returns ESP_OK : Success ESP_ERR_NOT_FOUND : Failure ESP_OK : Success ESP_ERR_NOT_FOUND : Failure ESP_OK : Success Parameters name -- [in] Name of the property to remove Returns ESP_OK : Success ESP_ERR_NOT_FOUND : Failure const esp_local_ctrl_prop_t *esp_local_ctrl_get_property(const char *name) Get property description structure by name. This API may be used to get a property's context structure esp_local_ctrl_prop_t when its name is known Parameters name -- [in] Name of the property to find Returns Pointer to property NULL if not found Pointer to property NULL if not found Pointer to property Parameters name -- [in] Name of the property to find Returns Pointer to property NULL if not found esp_err_t esp_local_ctrl_set_handler(const char *ep_name, protocomm_req_handler_t handler, void *user_ctx) Register protocomm handler for a custom endpoint. This API can be called by the application to register a protocomm handler for an endpoint after the local control service has started. Note In case of BLE transport the names and uuids of all custom endpoints must be provided beforehand as a part of the protocomm_ble_config_t structure set in esp_local_ctrl_config_t , and passed to esp_local_ctrl_start() . Parameters ep_name -- [in] Name of the endpoint handler -- [in] Endpoint handler function user_ctx -- [in] User data ep_name -- [in] Name of the endpoint handler -- [in] Endpoint handler function user_ctx -- [in] User data ep_name -- [in] Name of the endpoint Returns ESP_OK : Success ESP_FAIL : Failure ESP_OK : Success ESP_FAIL : Failure ESP_OK : Success Parameters ep_name -- [in] Name of the endpoint handler -- [in] Endpoint handler function user_ctx -- [in] User data Returns ESP_OK : Success ESP_FAIL : Failure Unions union esp_local_ctrl_transport_config_t #include <esp_local_ctrl.h> Transport mode (BLE / HTTPD) configuration. Public Members esp_local_ctrl_transport_config_ble_t *ble This is same as protocomm_ble_config_t . See protocomm_ble.h for available configuration parameters. esp_local_ctrl_transport_config_ble_t *ble This is same as protocomm_ble_config_t . See protocomm_ble.h for available configuration parameters. esp_local_ctrl_transport_config_httpd_t *httpd This is same as httpd_ssl_config_t . See esp_https_server.h for available configuration parameters. esp_local_ctrl_transport_config_httpd_t *httpd This is same as httpd_ssl_config_t . See esp_https_server.h for available configuration parameters. esp_local_ctrl_transport_config_ble_t *ble Structures struct esp_local_ctrl_prop Property description data structure, which is to be populated and passed to the esp_local_ctrl_add_property() function. Once a property is added, its structure is available for read-only access inside get_prop_values() and set_prop_values() handlers. Public Members char *name Unique name of property char *name Unique name of property uint32_t type Type of property. This may be set to application defined enums uint32_t type Type of property. This may be set to application defined enums size_t size Size of the property value, which: if zero, the property can have values of variable size if non-zero, the property can have values of fixed size only, therefore, checks are performed internally by esp_local_ctrl when setting the value of such a property if zero, the property can have values of variable size if non-zero, the property can have values of fixed size only, therefore, checks are performed internally by esp_local_ctrl when setting the value of such a property if zero, the property can have values of variable size size_t size Size of the property value, which: if zero, the property can have values of variable size if non-zero, the property can have values of fixed size only, therefore, checks are performed internally by esp_local_ctrl when setting the value of such a property uint32_t flags Flags set for this property. This could be a bit field. A flag may indicate property behavior, e.g. read-only / constant uint32_t flags Flags set for this property. This could be a bit field. A flag may indicate property behavior, e.g. read-only / constant void *ctx Pointer to some context data relevant for this property. This will be available for use inside the get_prop_values and set_prop_values handlers as a part of this property structure. When set, this is valid throughout the lifetime of a property, till either the property is removed or the esp_local_ctrl service is stopped. void *ctx Pointer to some context data relevant for this property. This will be available for use inside the get_prop_values and set_prop_values handlers as a part of this property structure. When set, this is valid throughout the lifetime of a property, till either the property is removed or the esp_local_ctrl service is stopped. void (*ctx_free_fn)(void *ctx) Function used by esp_local_ctrl to internally free the property context when esp_local_ctrl_remove_property() or esp_local_ctrl_stop() is called. void (*ctx_free_fn)(void *ctx) Function used by esp_local_ctrl to internally free the property context when esp_local_ctrl_remove_property() or esp_local_ctrl_stop() is called. char *name struct esp_local_ctrl_prop_val Property value data structure. This gets passed to the get_prop_values() and set_prop_values() handlers for the purpose of retrieving or setting the present value of a property. Public Members void *data Pointer to memory holding property value void *data Pointer to memory holding property value size_t size Size of property value size_t size Size of property value void (*free_fn)(void *data) This may be set by the application in get_prop_values() handler to tell esp_local_ctrl to call this function on the data pointer above, for freeing its resources after sending the get_prop_values response. void (*free_fn)(void *data) This may be set by the application in get_prop_values() handler to tell esp_local_ctrl to call this function on the data pointer above, for freeing its resources after sending the get_prop_values response. void *data struct esp_local_ctrl_handlers Handlers for receiving and responding to local control commands for getting and setting properties. Public Members esp_err_t (*get_prop_values)(size_t props_count, const esp_local_ctrl_prop_t props[], esp_local_ctrl_prop_val_t prop_values[], void *usr_ctx) Handler function to be implemented for retrieving current values of properties. Note If any of the properties have fixed sizes, the size field of corresponding element in prop_values need to be set Param props_count [in] Total elements in the props array Param props [in] Array of properties, the current values for which have been requested by the client Param prop_values [out] Array of empty property values, the elements of which need to be populated with the current values of those properties specified by props argument Param usr_ctx [in] This provides value of the usr_ctx field of esp_local_ctrl_handlers_t structure Return Returning different error codes will convey the corresponding protocol level errors to the client : ESP_OK : Success ESP_ERR_INVALID_ARG : InvalidArgument ESP_ERR_INVALID_STATE : InvalidProto All other error codes : InternalError ESP_OK : Success ESP_ERR_INVALID_ARG : InvalidArgument ESP_ERR_INVALID_STATE : InvalidProto All other error codes : InternalError ESP_OK : Success Param props_count [in] Total elements in the props array Param props [in] Array of properties, the current values for which have been requested by the client Param prop_values [out] Array of empty property values, the elements of which need to be populated with the current values of those properties specified by props argument Param usr_ctx [in] This provides value of the usr_ctx field of esp_local_ctrl_handlers_t structure Return Returning different error codes will convey the corresponding protocol level errors to the client : ESP_OK : Success ESP_ERR_INVALID_ARG : InvalidArgument ESP_ERR_INVALID_STATE : InvalidProto All other error codes : InternalError esp_err_t (*get_prop_values)(size_t props_count, const esp_local_ctrl_prop_t props[], esp_local_ctrl_prop_val_t prop_values[], void *usr_ctx) Handler function to be implemented for retrieving current values of properties. Note If any of the properties have fixed sizes, the size field of corresponding element in prop_values need to be set Param props_count [in] Total elements in the props array Param props [in] Array of properties, the current values for which have been requested by the client Param prop_values [out] Array of empty property values, the elements of which need to be populated with the current values of those properties specified by props argument Param usr_ctx [in] This provides value of the usr_ctx field of esp_local_ctrl_handlers_t structure Return Returning different error codes will convey the corresponding protocol level errors to the client : ESP_OK : Success ESP_ERR_INVALID_ARG : InvalidArgument ESP_ERR_INVALID_STATE : InvalidProto All other error codes : InternalError esp_err_t (*set_prop_values)(size_t props_count, const esp_local_ctrl_prop_t props[], const esp_local_ctrl_prop_val_t prop_values[], void *usr_ctx) Handler function to be implemented for changing values of properties. Note If any of the properties have variable sizes, the size field of the corresponding element in prop_values must be checked explicitly before making any assumptions on the size. Param props_count [in] Total elements in the props array Param props [in] Array of properties, the values for which the client requests to change Param prop_values [in] Array of property values, the elements of which need to be used for updating those properties specified by props argument Param usr_ctx [in] This provides value of the usr_ctx field of esp_local_ctrl_handlers_t structure Return Returning different error codes will convey the corresponding protocol level errors to the client : ESP_OK : Success ESP_ERR_INVALID_ARG : InvalidArgument ESP_ERR_INVALID_STATE : InvalidProto All other error codes : InternalError ESP_OK : Success ESP_ERR_INVALID_ARG : InvalidArgument ESP_ERR_INVALID_STATE : InvalidProto All other error codes : InternalError ESP_OK : Success Param props_count [in] Total elements in the props array Param props [in] Array of properties, the values for which the client requests to change Param prop_values [in] Array of property values, the elements of which need to be used for updating those properties specified by props argument Param usr_ctx [in] This provides value of the usr_ctx field of esp_local_ctrl_handlers_t structure Return Returning different error codes will convey the corresponding protocol level errors to the client : ESP_OK : Success ESP_ERR_INVALID_ARG : InvalidArgument ESP_ERR_INVALID_STATE : InvalidProto All other error codes : InternalError esp_err_t (*set_prop_values)(size_t props_count, const esp_local_ctrl_prop_t props[], const esp_local_ctrl_prop_val_t prop_values[], void *usr_ctx) Handler function to be implemented for changing values of properties. Note If any of the properties have variable sizes, the size field of the corresponding element in prop_values must be checked explicitly before making any assumptions on the size. Param props_count [in] Total elements in the props array Param props [in] Array of properties, the values for which the client requests to change Param prop_values [in] Array of property values, the elements of which need to be used for updating those properties specified by props argument Param usr_ctx [in] This provides value of the usr_ctx field of esp_local_ctrl_handlers_t structure Return Returning different error codes will convey the corresponding protocol level errors to the client : ESP_OK : Success ESP_ERR_INVALID_ARG : InvalidArgument ESP_ERR_INVALID_STATE : InvalidProto All other error codes : InternalError void *usr_ctx Context pointer to be passed to above handler functions upon invocation. This is different from the property level context, as this is valid throughout the lifetime of the esp_local_ctrl service, and freed only when the service is stopped. void *usr_ctx Context pointer to be passed to above handler functions upon invocation. This is different from the property level context, as this is valid throughout the lifetime of the esp_local_ctrl service, and freed only when the service is stopped. void (*usr_ctx_free_fn)(void *usr_ctx) Pointer to function which will be internally invoked on usr_ctx for freeing the context resources when esp_local_ctrl_stop() is called. void (*usr_ctx_free_fn)(void *usr_ctx) Pointer to function which will be internally invoked on usr_ctx for freeing the context resources when esp_local_ctrl_stop() is called. esp_err_t (*get_prop_values)(size_t props_count, const esp_local_ctrl_prop_t props[], esp_local_ctrl_prop_val_t prop_values[], void *usr_ctx) struct esp_local_ctrl_proto_sec_cfg Protocom security configs Public Members esp_local_ctrl_proto_sec_t version This sets protocom security version, sec0/sec1 or custom If custom, user must provide handle via proto_sec_custom_handle below esp_local_ctrl_proto_sec_t version This sets protocom security version, sec0/sec1 or custom If custom, user must provide handle via proto_sec_custom_handle below void *custom_handle Custom security handle if security is set custom via proto_sec above This handle must follow protocomm_security_t signature void *custom_handle Custom security handle if security is set custom via proto_sec above This handle must follow protocomm_security_t signature const void *pop Proof of possession to be used for local control. Could be NULL. const void *pop Proof of possession to be used for local control. Could be NULL. const void *sec_params Pointer to security params (NULL if not needed). This is not needed for protocomm security 0 This pointer should hold the struct of type esp_local_ctrl_security1_params_t for protocomm security 1 and esp_local_ctrl_security2_params_t for protocomm security 2 respectively. Could be NULL. const void *sec_params Pointer to security params (NULL if not needed). This is not needed for protocomm security 0 This pointer should hold the struct of type esp_local_ctrl_security1_params_t for protocomm security 1 and esp_local_ctrl_security2_params_t for protocomm security 2 respectively. Could be NULL. esp_local_ctrl_proto_sec_t version struct esp_local_ctrl_config Configuration structure to pass to esp_local_ctrl_start() Public Members const esp_local_ctrl_transport_t *transport Transport layer over which service will be provided const esp_local_ctrl_transport_t *transport Transport layer over which service will be provided esp_local_ctrl_transport_config_t transport_config Transport layer over which service will be provided esp_local_ctrl_transport_config_t transport_config Transport layer over which service will be provided esp_local_ctrl_proto_sec_cfg_t proto_sec Security version and POP esp_local_ctrl_proto_sec_cfg_t proto_sec Security version and POP esp_local_ctrl_handlers_t handlers Register handlers for responding to get/set requests on properties esp_local_ctrl_handlers_t handlers Register handlers for responding to get/set requests on properties size_t max_properties This limits the number of properties that are available at a time size_t max_properties This limits the number of properties that are available at a time const esp_local_ctrl_transport_t *transport Macros ESP_LOCAL_CTRL_TRANSPORT_BLE ESP_LOCAL_CTRL_TRANSPORT_HTTPD Type Definitions typedef struct esp_local_ctrl_prop esp_local_ctrl_prop_t Property description data structure, which is to be populated and passed to the esp_local_ctrl_add_property() function. Once a property is added, its structure is available for read-only access inside get_prop_values() and set_prop_values() handlers. typedef struct esp_local_ctrl_prop_val esp_local_ctrl_prop_val_t Property value data structure. This gets passed to the get_prop_values() and set_prop_values() handlers for the purpose of retrieving or setting the present value of a property. typedef struct esp_local_ctrl_handlers esp_local_ctrl_handlers_t Handlers for receiving and responding to local control commands for getting and setting properties. typedef struct esp_local_ctrl_transport esp_local_ctrl_transport_t Transport mode (BLE / HTTPD) over which the service will be provided. This is forward declaration of a private structure, implemented internally by esp_local_ctrl . typedef struct protocomm_ble_config esp_local_ctrl_transport_config_ble_t Configuration for transport mode BLE. This is a forward declaration for protocomm_ble_config_t . To use this, application must set CONFIG_BT_BLUEDROID_ENABLED and include protocomm_ble.h . typedef struct httpd_config esp_local_ctrl_transport_config_httpd_t Configuration for transport mode HTTPD. This is a forward declaration for httpd_ssl_config_t (for HTTPS) or httpd_config_t (for HTTP) typedef enum esp_local_ctrl_proto_sec esp_local_ctrl_proto_sec_t Security types for esp_local_control. typedef protocomm_security1_params_t esp_local_ctrl_security1_params_t typedef protocomm_security2_params_t esp_local_ctrl_security2_params_t typedef struct esp_local_ctrl_proto_sec_cfg esp_local_ctrl_proto_sec_cfg_t Protocom security configs typedef struct esp_local_ctrl_config esp_local_ctrl_config_t Configuration structure to pass to esp_local_ctrl_start()
ESP Local Control Overview ESP Local Control (esp_local_ctrl) component in ESP-IDF provides capability to control an ESP device over HTTPS or Bluetooth® Low Energy. It provides access to application defined properties that are available for reading/writing via a set of configurable handlers. Initialization of the esp_local_ctrl service over Bluetooth Low Energy transport is performed as follows: esp_local_ctrl_config_t config = { .transport = ESP_LOCAL_CTRL_TRANSPORT_BLE, .transport_config = { .ble = & (protocomm_ble_config_t) { .device_name = SERVICE_NAME, .service_uuid = { /* LSB <--------------------------------------- * ---------------------------------------> MSB */ 0x21, 0xd5, 0x3b, 0x8d, 0xbd, 0x75, 0x68, 0x8a, 0xb4, 0x42, 0xeb, 0x31, 0x4a, 0x1e, 0x98, 0x3d } } }, .proto_sec = { .version = PROTOCOM_SEC0, .custom_handle = NULL, .sec_params = NULL, }, .handlers = { /* User defined handler functions */ .get_prop_values = get_property_values, .set_prop_values = set_property_values, .usr_ctx = NULL, .usr_ctx_free_fn = NULL }, /* Maximum number of properties that may be set */ .max_properties = 10 }; /* Start esp_local_ctrl service */ ESP_ERROR_CHECK(esp_local_ctrl_start(&config)); Similarly for HTTPS transport: /* Set the configuration */ httpd_ssl_config_t https_conf = HTTPD_SSL_CONFIG_DEFAULT(); /* Load server certificate */ extern const unsigned char servercert_start[] asm("_binary_servercert_pem_start"); extern const unsigned char servercert_end[] asm("_binary_servercert_pem_end"); https_conf.servercert = servercert_start; https_conf.servercert_len = servercert_end - servercert_start; /* Load server private key */ extern const unsigned char prvtkey_pem_start[] asm("_binary_prvtkey_pem_start"); extern const unsigned char prvtkey_pem_end[] asm("_binary_prvtkey_pem_end"); https_conf.prvtkey_pem = prvtkey_pem_start; https_conf.prvtkey_len = prvtkey_pem_end - prvtkey_pem_start; esp_local_ctrl_config_t config = { .transport = ESP_LOCAL_CTRL_TRANSPORT_HTTPD, .transport_config = { .httpd = &https_conf }, .proto_sec = { .version = PROTOCOM_SEC0, .custom_handle = NULL, .sec_params = NULL, }, .handlers = { /* User defined handler functions */ .get_prop_values = get_property_values, .set_prop_values = set_property_values, .usr_ctx = NULL, .usr_ctx_free_fn = NULL }, /* Maximum number of properties that may be set */ .max_properties = 10 }; /* Start esp_local_ctrl service */ ESP_ERROR_CHECK(esp_local_ctrl_start(&config)); You may set security for transport in ESP local control using following options: PROTOCOM_SEC2: specifies that SRP6a-based key exchange and end-to-end encryption based on AES-GCM are used. This is the most preferred option as it adds a robust security with Augmented PAKE protocol, i.e., SRP6a. PROTOCOM_SEC1: specifies that Curve25519-based key exchange and end-to-end encryption based on AES-CTR are used. PROTOCOM_SEC0: specifies that data will be exchanged as a plain text (no security). PROTOCOM_SEC_CUSTOM: you can define your own security requirement. Please note that you will also have to provide custom_handleof type protocomm_security_t *in this context. Note The respective security schemes need to be enabled through the project configuration menu. Please refer to the Enabling protocom security version section in Protocol Communication for more details. Creating a Property Now that we know how to start the esp_local_ctrl service, let's add a property to it. Each property must have a unique `name` (string), a type (e.g., enum), flags` (bit fields) and size`. The size is to be kept 0, if we want our property value to be of variable length (e.g., if it is a string or bytestream). For data types with fixed-length property value, like int, float, etc., setting the size field to the right value helps esp_local_ctrl to perform internal checks on arguments received with write requests. The interpretation of type and flags fields is totally upto the application, hence they may be used as enumerations, bitfields, or even simple integers. One way is to use type values to classify properties, while flags to specify characteristics of a property. Here is an example property which is to function as a timestamp. It is assumed that the application defines TYPE_TIMESTAMP and READONLY, which are used for setting the type and flags fields here. /* Create a timestamp property */ esp_local_ctrl_prop_t timestamp = { .name = "timestamp", .type = TYPE_TIMESTAMP, .size = sizeof(int32_t), .flags = READONLY, .ctx = func_get_time, .ctx_free_fn = NULL }; /* Now register the property */ esp_local_ctrl_add_property(×tamp); Also notice that there is a ctx field, which is set to point to some custom func_get_time(). This can be used inside the property get/set handlers to retrieve timestamp. Here is an example of get_prop_values() handler, which is used for retrieving the timestamp. static esp_err_t get_property_values(size_t props_count, const esp_local_ctrl_prop_t *props, esp_local_ctrl_prop_val_t *prop_values, void *usr_ctx) { for (uint32_t i = 0; i < props_count; i++) { ESP_LOGI(TAG, "Reading %s", props[i].name); if (props[i].type == TYPE_TIMESTAMP) { /* Obtain the timer function from ctx */ int32_t (*func_get_time)(void) = props[i].ctx; /* Use static variable for saving the value. This is essential because the value has to be valid even after this function returns. Alternative is to use dynamic allocation and set the free_fn field */ static int32_t ts = func_get_time(); prop_values[i].data = &ts; } } return ESP_OK; } Here is an example of set_prop_values() handler. Notice how we restrict from writing to read-only properties. static esp_err_t set_property_values(size_t props_count, const esp_local_ctrl_prop_t *props, const esp_local_ctrl_prop_val_t *prop_values, void *usr_ctx) { for (uint32_t i = 0; i < props_count; i++) { if (props[i].flags & READONLY) { ESP_LOGE(TAG, "Cannot write to read-only property %s", props[i].name); return ESP_ERR_INVALID_ARG; } else { ESP_LOGI(TAG, "Setting %s", props[i].name); /* For keeping it simple, lets only log the incoming data */ ESP_LOG_BUFFER_HEX_LEVEL(TAG, prop_values[i].data, prop_values[i].size, ESP_LOG_INFO); } } return ESP_OK; } For complete example see protocols/esp_local_ctrl. Client Side Implementation The client side implementation establishes a protocomm session with the device first, over the supported mode of transport, and then send and receive protobuf messages understood by the esp_local_ctrl service. The service translates these messages into requests and then call the appropriate handlers (set/get). Then, the generated response for each handler is again packed into a protobuf message and transmitted back to the client. See below the various protobuf messages understood by the esp_local_ctrl service: get_prop_count: This should simply return the total number of properties supported by the service. get_prop_values: This accepts an array of indices and should return the information (name, type, flags) and values of the properties corresponding to those indices. set_prop_values: This accepts an array of indices and an array of new values, which are used for setting the values of the properties corresponding to the indices. Note that indices may or may not be the same for a property, across multiple sessions. Therefore, the client must only use the names of the properties to uniquely identify them. So, every time a new session is established, the client should first call get_prop_count and then get_prop_values, hence form an index-to-name mapping for all properties. Now when calling set_prop_values for a set of properties, it must first convert the names to indexes, using the created mapping. As emphasized earlier, the client must refresh the index-to-name mapping every time a new session is established with the same device. The various protocomm endpoints provided by esp_local_ctrl are listed below: | Endpoint Name (Bluetooth Low Energy + GATT Server) | URI (HTTPS Server + mDNS) | Description | esp_local_ctrl/version | https://<mdns-hostname>.local/esp_local_ctrl/version | Endpoint used for retrieving version string | esp_local_ctrl/control | https://<mdns-hostname>.local/esp_local_ctrl/control | Endpoint used for sending or receiving control messages API Reference Header File This header file can be included with: #include "esp_local_ctrl.h" This header file is a part of the API provided by the esp_local_ctrlcomponent. To declare that your component depends on esp_local_ctrl, add the following to your CMakeLists.txt: REQUIRES esp_local_ctrl or PRIV_REQUIRES esp_local_ctrl Functions - const esp_local_ctrl_transport_t *esp_local_ctrl_get_transport_ble(void) Function for obtaining BLE transport mode. - const esp_local_ctrl_transport_t *esp_local_ctrl_get_transport_httpd(void) Function for obtaining HTTPD transport mode. - esp_err_t esp_local_ctrl_start(const esp_local_ctrl_config_t *config) Start local control service. - Parameters config -- [in] Pointer to configuration structure - Returns ESP_OK : Success ESP_FAIL : Failure - - esp_err_t esp_local_ctrl_add_property(const esp_local_ctrl_prop_t *prop) Add a new property. This adds a new property and allocates internal resources for it. The total number of properties that could be added is limited by configuration option max_properties - Parameters prop -- [in] Property description structure - Returns ESP_OK : Success ESP_FAIL : Failure - - esp_err_t esp_local_ctrl_remove_property(const char *name) Remove a property. This finds a property by name, and releases the internal resources which are associated with it. - Parameters name -- [in] Name of the property to remove - Returns ESP_OK : Success ESP_ERR_NOT_FOUND : Failure - - const esp_local_ctrl_prop_t *esp_local_ctrl_get_property(const char *name) Get property description structure by name. This API may be used to get a property's context structure esp_local_ctrl_prop_twhen its name is known - Parameters name -- [in] Name of the property to find - Returns Pointer to property NULL if not found - - esp_err_t esp_local_ctrl_set_handler(const char *ep_name, protocomm_req_handler_t handler, void *user_ctx) Register protocomm handler for a custom endpoint. This API can be called by the application to register a protocomm handler for an endpoint after the local control service has started. Note In case of BLE transport the names and uuids of all custom endpoints must be provided beforehand as a part of the protocomm_ble_config_tstructure set in esp_local_ctrl_config_t, and passed to esp_local_ctrl_start(). - Parameters ep_name -- [in] Name of the endpoint handler -- [in] Endpoint handler function user_ctx -- [in] User data - - Returns ESP_OK : Success ESP_FAIL : Failure - Unions - union esp_local_ctrl_transport_config_t - #include <esp_local_ctrl.h> Transport mode (BLE / HTTPD) configuration. Public Members - esp_local_ctrl_transport_config_ble_t *ble This is same as protocomm_ble_config_t. See protocomm_ble.hfor available configuration parameters. - esp_local_ctrl_transport_config_httpd_t *httpd This is same as httpd_ssl_config_t. See esp_https_server.hfor available configuration parameters. - esp_local_ctrl_transport_config_ble_t *ble Structures - struct esp_local_ctrl_prop Property description data structure, which is to be populated and passed to the esp_local_ctrl_add_property()function. Once a property is added, its structure is available for read-only access inside get_prop_values()and set_prop_values()handlers. Public Members - char *name Unique name of property - uint32_t type Type of property. This may be set to application defined enums - size_t size Size of the property value, which: if zero, the property can have values of variable size if non-zero, the property can have values of fixed size only, therefore, checks are performed internally by esp_local_ctrl when setting the value of such a property - - uint32_t flags Flags set for this property. This could be a bit field. A flag may indicate property behavior, e.g. read-only / constant - void *ctx Pointer to some context data relevant for this property. This will be available for use inside the get_prop_valuesand set_prop_valueshandlers as a part of this property structure. When set, this is valid throughout the lifetime of a property, till either the property is removed or the esp_local_ctrl service is stopped. - void (*ctx_free_fn)(void *ctx) Function used by esp_local_ctrl to internally free the property context when esp_local_ctrl_remove_property()or esp_local_ctrl_stop()is called. - char *name - struct esp_local_ctrl_prop_val Property value data structure. This gets passed to the get_prop_values()and set_prop_values()handlers for the purpose of retrieving or setting the present value of a property. Public Members - void *data Pointer to memory holding property value - size_t size Size of property value - void (*free_fn)(void *data) This may be set by the application in get_prop_values()handler to tell esp_local_ctrlto call this function on the data pointer above, for freeing its resources after sending the get_prop_valuesresponse. - void *data - struct esp_local_ctrl_handlers Handlers for receiving and responding to local control commands for getting and setting properties. Public Members - esp_err_t (*get_prop_values)(size_t props_count, const esp_local_ctrl_prop_t props[], esp_local_ctrl_prop_val_t prop_values[], void *usr_ctx) Handler function to be implemented for retrieving current values of properties. Note If any of the properties have fixed sizes, the size field of corresponding element in prop_valuesneed to be set - Param props_count [in] Total elements in the props array - Param props [in] Array of properties, the current values for which have been requested by the client - Param prop_values [out] Array of empty property values, the elements of which need to be populated with the current values of those properties specified by props argument - Param usr_ctx [in] This provides value of the usr_ctxfield of esp_local_ctrl_handlers_tstructure - Return Returning different error codes will convey the corresponding protocol level errors to the client : ESP_OK : Success ESP_ERR_INVALID_ARG : InvalidArgument ESP_ERR_INVALID_STATE : InvalidProto All other error codes : InternalError - - esp_err_t (*set_prop_values)(size_t props_count, const esp_local_ctrl_prop_t props[], const esp_local_ctrl_prop_val_t prop_values[], void *usr_ctx) Handler function to be implemented for changing values of properties. Note If any of the properties have variable sizes, the size field of the corresponding element in prop_valuesmust be checked explicitly before making any assumptions on the size. - Param props_count [in] Total elements in the props array - Param props [in] Array of properties, the values for which the client requests to change - Param prop_values [in] Array of property values, the elements of which need to be used for updating those properties specified by props argument - Param usr_ctx [in] This provides value of the usr_ctxfield of esp_local_ctrl_handlers_tstructure - Return Returning different error codes will convey the corresponding protocol level errors to the client : ESP_OK : Success ESP_ERR_INVALID_ARG : InvalidArgument ESP_ERR_INVALID_STATE : InvalidProto All other error codes : InternalError - - void *usr_ctx Context pointer to be passed to above handler functions upon invocation. This is different from the property level context, as this is valid throughout the lifetime of the esp_local_ctrlservice, and freed only when the service is stopped. - void (*usr_ctx_free_fn)(void *usr_ctx) Pointer to function which will be internally invoked on usr_ctxfor freeing the context resources when esp_local_ctrl_stop()is called. - esp_err_t (*get_prop_values)(size_t props_count, const esp_local_ctrl_prop_t props[], esp_local_ctrl_prop_val_t prop_values[], void *usr_ctx) - struct esp_local_ctrl_proto_sec_cfg Protocom security configs Public Members - esp_local_ctrl_proto_sec_t version This sets protocom security version, sec0/sec1 or custom If custom, user must provide handle via proto_sec_custom_handlebelow - void *custom_handle Custom security handle if security is set custom via proto_secabove This handle must follow protocomm_security_tsignature - const void *pop Proof of possession to be used for local control. Could be NULL. - const void *sec_params Pointer to security params (NULL if not needed). This is not needed for protocomm security 0 This pointer should hold the struct of type esp_local_ctrl_security1_params_t for protocomm security 1 and esp_local_ctrl_security2_params_t for protocomm security 2 respectively. Could be NULL. - esp_local_ctrl_proto_sec_t version - struct esp_local_ctrl_config Configuration structure to pass to esp_local_ctrl_start() Public Members - const esp_local_ctrl_transport_t *transport Transport layer over which service will be provided - esp_local_ctrl_transport_config_t transport_config Transport layer over which service will be provided - esp_local_ctrl_proto_sec_cfg_t proto_sec Security version and POP - esp_local_ctrl_handlers_t handlers Register handlers for responding to get/set requests on properties - size_t max_properties This limits the number of properties that are available at a time - const esp_local_ctrl_transport_t *transport Macros - ESP_LOCAL_CTRL_TRANSPORT_BLE - ESP_LOCAL_CTRL_TRANSPORT_HTTPD Type Definitions - typedef struct esp_local_ctrl_prop esp_local_ctrl_prop_t Property description data structure, which is to be populated and passed to the esp_local_ctrl_add_property()function. Once a property is added, its structure is available for read-only access inside get_prop_values()and set_prop_values()handlers. - typedef struct esp_local_ctrl_prop_val esp_local_ctrl_prop_val_t Property value data structure. This gets passed to the get_prop_values()and set_prop_values()handlers for the purpose of retrieving or setting the present value of a property. - typedef struct esp_local_ctrl_handlers esp_local_ctrl_handlers_t Handlers for receiving and responding to local control commands for getting and setting properties. - typedef struct esp_local_ctrl_transport esp_local_ctrl_transport_t Transport mode (BLE / HTTPD) over which the service will be provided. This is forward declaration of a private structure, implemented internally by esp_local_ctrl. - typedef struct protocomm_ble_config esp_local_ctrl_transport_config_ble_t Configuration for transport mode BLE. This is a forward declaration for protocomm_ble_config_t. To use this, application must set CONFIG_BT_BLUEDROID_ENABLED and include protocomm_ble.h. - typedef struct httpd_config esp_local_ctrl_transport_config_httpd_t Configuration for transport mode HTTPD. This is a forward declaration for httpd_ssl_config_t(for HTTPS) or httpd_config_t(for HTTP) - typedef enum esp_local_ctrl_proto_sec esp_local_ctrl_proto_sec_t Security types for esp_local_control. - typedef protocomm_security1_params_t esp_local_ctrl_security1_params_t - typedef protocomm_security2_params_t esp_local_ctrl_security2_params_t - typedef struct esp_local_ctrl_proto_sec_cfg esp_local_ctrl_proto_sec_cfg_t Protocom security configs - typedef struct esp_local_ctrl_config esp_local_ctrl_config_t Configuration structure to pass to esp_local_ctrl_start()
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/protocols/esp_local_ctrl.html
ESP-IDF Programming Guide v5.2.1 documentation
null
ESP Serial Slave Link
null
espressif.com
2016-01-01
9edb9e9ee3429119
null
null
ESP Serial Slave Link Overview Espressif provides several chips that can work as slaves. These slave devices rely on some common buses, and have their own communication protocols over those buses. The esp_serial_slave_link component is designed for the master to communicate with ESP slave devices through those protocols over the bus drivers. After an esp_serial_slave_link device is initialized properly, the application can use it to communicate with the ESP slave devices conveniently. Note The ESP-IDF component esp_serial_slave_link has been moved from ESP-IDF since version v5.0 to a separate repository: To add ESSL component in your project, please run idf.py add-dependency espressif/esp_serial_slave_link . Espressif Device Protocols For more details about Espressif device protocols, see the following documents. Terminology ESSL: Abbreviation for ESP Serial Slave Link, the component described by this document. Master: The device running the esp_serial_slave_link component. ESSL device: a virtual device on the master associated with an ESP slave device. The device context has the knowledge of the slave protocol above the bus, relying on some bus drivers to communicate with the slave. ESSL device handle: a handle to ESSL device context containing the configuration, status and data required by the ESSL component. The context stores the driver configurations, communication state, data shared by master and slave, etc. The context should be initialized before it is used, and get deinitialized if not used any more. The master application operates on the ESSL device through this handle. The context should be initialized before it is used, and get deinitialized if not used any more. The master application operates on the ESSL device through this handle. The context should be initialized before it is used, and get deinitialized if not used any more. The master application operates on the ESSL device through this handle. ESP slave: the slave device connected to the bus, which ESSL component is designed to communicate with. Bus: The bus over which the master and the slave communicate with each other. Slave protocol: The special communication protocol specified by Espressif HW/SW over the bus. TX buffer num: a counter, which is on the slave and can be read by the master, indicates the accumulated buffer numbers that the slave has loaded to the hardware to receive data from the master. RX data size: a counter, which is on the slave and can be read by the master, indicates the accumulated data size that the slave has loaded to the hardware to send to the master. Services Provided by ESP Slave There are some common services provided by the Espressif slaves: Tohost Interrupts: The slave can inform the master about certain events by the interrupt line. (optional) Frhost Interrupts: The master can inform the slave about certain events. TX FIFO (master to slave): The slave can receive data from the master in units of receiving buffers. The slave updates the TX buffer num to inform the master how much data it can receive, and the master then read the TX buffer num, and take off the used buffer number to know how many buffers are remaining. RX FIFO (slave to master): The slave can send data in stream to the master. The SDIO slave can also indicate it has new data to send to master by the interrupt line. The slave updates the RX data size to inform the master how much data it has prepared to send, and then the master read the data size, and take off the data length it has already received to know how many data is remaining. Shared registers: The master can read some part of the registers on the slave, and also write these registers to let the slave read. The services provided by the slave depends on the slave's model. See SDIO Slave Capabilities of Espressif Chips and SPI Slave Capabilities of Espressif Chips for more details. Initialization of ESP Serial Slave Link ESP SDIO Slave The ESP SDIO slave link (ESSL SDIO) devices relies on the SDMMC component. It includes the usage of communicating with ESP SDIO Slave device via the SDMMC Host or SDSPI Host feature. The ESSL device should be initialized as below: Initialize a SDMMC card (see :doc:` Document of SDMMC driver </api-reference/storage/sdmmc>`) structure. Call sdmmc_card_init() to initialize the card. Initialize the ESSL device with essl_sdio_config_t . The card member should be the sdmmc_card_t got in step 2, and the recv_buffer_size member should be filled correctly according to pre-negotiated value. Call essl_init() to do initialization of the SDIO part. Call essl_wait_for_ready() to wait for the slave to be ready. ESP SPI Slave Note If you are communicating with the ESP SDIO Slave device through SPI interface, you should use the SDIO interface instead. Has not been supported yet. APIs After the initialization process above is performed, you can call the APIs below to make use of the services provided by the slave: Tohost Interrupts (Optional) Call essl_get_intr_ena() to know which events trigger the interrupts to the master. Call essl_set_intr_ena() to set the events that trigger interrupts to the master. Call essl_wait_int() to wait until interrupt from the slave, or timeout. When interrupt is triggered, call essl_get_intr() to know which events are active, and call essl_clear_intr() to clear them. Frhost Interrupts Call essl_send_slave_intr() to trigger general purpose interrupt of the slave. TX FIFO Call essl_get_tx_buffer_num() to know how many buffers the slave has prepared to receive data from the master. This is optional. The master will poll tx_buffer_num when it tries to send packets to the slave, until the slave has enough buffer or timeout. Call essl_send_packet() to send data to the slave. RX FIFO Call essl_get_rx_data_size() to know how many data the slave has prepared to send to the master. This is optional. When the master tries to receive data from the slave, it updates the rx_data_size for once, if the current rx_data_size is shorter than the buffer size the master prepared to receive. And it may poll the rx_data_size if the rx_data_size keeps 0, until timeout. Call essl_get_packet() to receive data from the slave. Reset Counters (Optional) Call essl_reset_cnt() to reset the internal counter if you find the slave has reset its counter. Application Example The example below shows how ESP32 SDIO host and slave communicate with each other. The host uses the ESSL SDIO: Please refer to the specific example README.md for details. API Reference Header File Functions esp_err_t essl_init(essl_handle_t handle, uint32_t wait_ms) Initialize the slave. Parameters handle -- Handle of an ESSL device. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. Returns ESP_OK: If success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. Other value returned from lower layer init . ESP_OK: If success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. Other value returned from lower layer init . ESP_OK: If success Parameters handle -- Handle of an ESSL device. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. Returns ESP_OK: If success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. Other value returned from lower layer init . esp_err_t essl_wait_for_ready(essl_handle_t handle, uint32_t wait_ms) Wait for interrupt of an ESSL slave device. Parameters handle -- Handle of an ESSL device. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. Returns ESP_OK: If success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller ESP_OK: If success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller ESP_OK: If success Parameters handle -- Handle of an ESSL device. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. Returns ESP_OK: If success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller esp_err_t essl_get_tx_buffer_num(essl_handle_t handle, uint32_t *out_tx_num, uint32_t wait_ms) Get buffer num for the host to send data to the slave. The buffers are size of buffer_size . Parameters handle -- Handle of a ESSL device. out_tx_num -- Output of buffer num that host can send data to ESSL slave. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of a ESSL device. out_tx_num -- Output of buffer num that host can send data to ESSL slave. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of a ESSL device. Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller ESP_OK: Success ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller ESP_OK: Success Parameters handle -- Handle of a ESSL device. out_tx_num -- Output of buffer num that host can send data to ESSL slave. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller esp_err_t essl_get_rx_data_size(essl_handle_t handle, uint32_t *out_rx_size, uint32_t wait_ms) Get the size, in bytes, of the data that the ESSL slave is ready to send Parameters handle -- Handle of an ESSL device. out_rx_size -- Output of data size to read from slave, in bytes wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. out_rx_size -- Output of data size to read from slave, in bytes wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller ESP_OK: Success ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller ESP_OK: Success Parameters handle -- Handle of an ESSL device. out_rx_size -- Output of data size to read from slave, in bytes wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller esp_err_t essl_reset_cnt(essl_handle_t handle) Reset the counters of this component. Usually you don't need to do this unless you know the slave is reset. Parameters handle -- Handle of an ESSL device. Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode ESP_ERR_INVALID_ARG: Invalid argument, handle is not init. ESP_OK: Success ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode ESP_ERR_INVALID_ARG: Invalid argument, handle is not init. ESP_OK: Success Parameters handle -- Handle of an ESSL device. Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode ESP_ERR_INVALID_ARG: Invalid argument, handle is not init. esp_err_t essl_send_packet(essl_handle_t handle, const void *start, size_t length, uint32_t wait_ms) Send a packet to the ESSL Slave. The Slave receives the packet into buffers whose size is buffer_size (configured during initialization). Parameters handle -- Handle of an ESSL device. start -- Start address of the packet to send length -- Length of data to send, if the packet is over-size, the it will be divided into blocks and hold into different buffers automatically. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. start -- Start address of the packet to send length -- Length of data to send, if the packet is over-size, the it will be divided into blocks and hold into different buffers automatically. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. Returns ESP_OK Success ESP_ERR_INVALID_ARG: Invalid argument, handle is not init or other argument is not valid. ESP_ERR_TIMEOUT: No buffer to use, or error ftrom SDMMC host controller. ESP_ERR_NOT_FOUND: Slave is not ready for receiving. ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller. ESP_OK Success ESP_ERR_INVALID_ARG: Invalid argument, handle is not init or other argument is not valid. ESP_ERR_TIMEOUT: No buffer to use, or error ftrom SDMMC host controller. ESP_ERR_NOT_FOUND: Slave is not ready for receiving. ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller. ESP_OK Success Parameters handle -- Handle of an ESSL device. start -- Start address of the packet to send length -- Length of data to send, if the packet is over-size, the it will be divided into blocks and hold into different buffers automatically. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. Returns ESP_OK Success ESP_ERR_INVALID_ARG: Invalid argument, handle is not init or other argument is not valid. ESP_ERR_TIMEOUT: No buffer to use, or error ftrom SDMMC host controller. ESP_ERR_NOT_FOUND: Slave is not ready for receiving. ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller. esp_err_t essl_get_packet(essl_handle_t handle, void *out_data, size_t size, size_t *out_length, uint32_t wait_ms) Get a packet from ESSL slave. Parameters handle -- Handle of an ESSL device. out_data -- [out] Data output address size -- The size of the output buffer, if the buffer is smaller than the size of data to receive from slave, the driver returns ESP_ERR_NOT_FINISHED out_length -- [out] Output of length the data actually received from slave. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. out_data -- [out] Data output address size -- The size of the output buffer, if the buffer is smaller than the size of data to receive from slave, the driver returns ESP_ERR_NOT_FINISHED out_length -- [out] Output of length the data actually received from slave. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. Returns ESP_OK Success: All the data has been read from the slave. ESP_ERR_INVALID_ARG: Invalid argument, The handle is not initialized or the other arguments are invalid. ESP_ERR_NOT_FINISHED: Read was successful, but there is still data remaining. ESP_ERR_NOT_FOUND: Slave is not ready to send data. ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller. ESP_OK Success: All the data has been read from the slave. ESP_ERR_INVALID_ARG: Invalid argument, The handle is not initialized or the other arguments are invalid. ESP_ERR_NOT_FINISHED: Read was successful, but there is still data remaining. ESP_ERR_NOT_FOUND: Slave is not ready to send data. ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller. ESP_OK Success: All the data has been read from the slave. Parameters handle -- Handle of an ESSL device. out_data -- [out] Data output address size -- The size of the output buffer, if the buffer is smaller than the size of data to receive from slave, the driver returns ESP_ERR_NOT_FINISHED out_length -- [out] Output of length the data actually received from slave. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. Returns ESP_OK Success: All the data has been read from the slave. ESP_ERR_INVALID_ARG: Invalid argument, The handle is not initialized or the other arguments are invalid. ESP_ERR_NOT_FINISHED: Read was successful, but there is still data remaining. ESP_ERR_NOT_FOUND: Slave is not ready to send data. ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller. esp_err_t essl_write_reg(essl_handle_t handle, uint8_t addr, uint8_t value, uint8_t *value_o, uint32_t wait_ms) Write general purpose R/W registers (8-bit) of ESSL slave. Note sdio 28-31 are reserved, the lower API helps to skip. Parameters handle -- Handle of an ESSL device. addr -- Address of register to write. For SDIO, valid address: 0-59. For SPI, see essl_spi.h value -- Value to write to the register. value_o -- Output of the returned written value. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. addr -- Address of register to write. For SDIO, valid address: 0-59. For SPI, see essl_spi.h value -- Value to write to the register. value_o -- Output of the returned written value. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. Returns ESP_OK Success One of the error codes from SDMMC/SPI host controller ESP_OK Success One of the error codes from SDMMC/SPI host controller ESP_OK Success Parameters handle -- Handle of an ESSL device. addr -- Address of register to write. For SDIO, valid address: 0-59. For SPI, see essl_spi.h value -- Value to write to the register. value_o -- Output of the returned written value. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. Returns ESP_OK Success One of the error codes from SDMMC/SPI host controller esp_err_t essl_read_reg(essl_handle_t handle, uint8_t add, uint8_t *value_o, uint32_t wait_ms) Read general purpose R/W registers (8-bit) of ESSL slave. Parameters handle -- Handle of a essl device. add -- Address of register to read. For SDIO, Valid address: 0-27, 32-63 (28-31 reserved, return interrupt bits on read). For SPI, see essl_spi.h value_o -- Output value read from the register. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of a essl device. add -- Address of register to read. For SDIO, Valid address: 0-27, 32-63 (28-31 reserved, return interrupt bits on read). For SPI, see essl_spi.h value_o -- Output value read from the register. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of a essl device. Returns ESP_OK Success One of the error codes from SDMMC/SPI host controller ESP_OK Success One of the error codes from SDMMC/SPI host controller ESP_OK Success Parameters handle -- Handle of a essl device. add -- Address of register to read. For SDIO, Valid address: 0-27, 32-63 (28-31 reserved, return interrupt bits on read). For SPI, see essl_spi.h value_o -- Output value read from the register. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. Returns ESP_OK Success One of the error codes from SDMMC/SPI host controller esp_err_t essl_wait_int(essl_handle_t handle, uint32_t wait_ms) wait for an interrupt of the slave Parameters handle -- Handle of an ESSL device. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. Returns ESP_OK: If interrupt is triggered. ESP_ERR_NOT_SUPPORTED: Current device does not support this function. ESP_ERR_TIMEOUT: No interrupts before timeout. ESP_OK: If interrupt is triggered. ESP_ERR_NOT_SUPPORTED: Current device does not support this function. ESP_ERR_TIMEOUT: No interrupts before timeout. ESP_OK: If interrupt is triggered. Parameters handle -- Handle of an ESSL device. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. Returns ESP_OK: If interrupt is triggered. ESP_ERR_NOT_SUPPORTED: Current device does not support this function. ESP_ERR_TIMEOUT: No interrupts before timeout. esp_err_t essl_clear_intr(essl_handle_t handle, uint32_t intr_mask, uint32_t wait_ms) Clear interrupt bits of ESSL slave. All the bits set in the mask will be cleared, while other bits will stay the same. Parameters handle -- Handle of an ESSL device. intr_mask -- Mask of interrupt bits to clear. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. intr_mask -- Mask of interrupt bits to clear. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller ESP_OK: Success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller ESP_OK: Success Parameters handle -- Handle of an ESSL device. intr_mask -- Mask of interrupt bits to clear. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller esp_err_t essl_get_intr(essl_handle_t handle, uint32_t *intr_raw, uint32_t *intr_st, uint32_t wait_ms) Get interrupt bits of ESSL slave. Parameters handle -- Handle of an ESSL device. intr_raw -- Output of the raw interrupt bits. Set to NULL if only masked bits are read. intr_st -- Output of the masked interrupt bits. set to NULL if only raw bits are read. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. intr_raw -- Output of the raw interrupt bits. Set to NULL if only masked bits are read. intr_st -- Output of the masked interrupt bits. set to NULL if only raw bits are read. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. Returns ESP_OK: Success ESP_INVALID_ARG: If both intr_raw and intr_st are NULL. ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller ESP_OK: Success ESP_INVALID_ARG: If both intr_raw and intr_st are NULL. ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller ESP_OK: Success Parameters handle -- Handle of an ESSL device. intr_raw -- Output of the raw interrupt bits. Set to NULL if only masked bits are read. intr_st -- Output of the masked interrupt bits. set to NULL if only raw bits are read. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. Returns ESP_OK: Success ESP_INVALID_ARG: If both intr_raw and intr_st are NULL. ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller esp_err_t essl_set_intr_ena(essl_handle_t handle, uint32_t ena_mask, uint32_t wait_ms) Set interrupt enable bits of ESSL slave. The slave only sends interrupt on the line when there is a bit both the raw status and the enable are set. Parameters handle -- Handle of an ESSL device. ena_mask -- Mask of the interrupt bits to enable. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. ena_mask -- Mask of the interrupt bits to enable. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller ESP_OK: Success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller ESP_OK: Success Parameters handle -- Handle of an ESSL device. ena_mask -- Mask of the interrupt bits to enable. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller esp_err_t essl_get_intr_ena(essl_handle_t handle, uint32_t *ena_mask_o, uint32_t wait_ms) Get interrupt enable bits of ESSL slave. Parameters handle -- Handle of an ESSL device. ena_mask_o -- Output of interrupt bit enable mask. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. ena_mask_o -- Output of interrupt bit enable mask. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. Returns ESP_OK Success One of the error codes from SDMMC host controller ESP_OK Success One of the error codes from SDMMC host controller ESP_OK Success Parameters handle -- Handle of an ESSL device. ena_mask_o -- Output of interrupt bit enable mask. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. Returns ESP_OK Success One of the error codes from SDMMC host controller esp_err_t essl_send_slave_intr(essl_handle_t handle, uint32_t intr_mask, uint32_t wait_ms) Send interrupts to slave. Each bit of the interrupt will be triggered. Parameters handle -- Handle of an ESSL device. intr_mask -- Mask of interrupt bits to send to slave. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. intr_mask -- Mask of interrupt bits to send to slave. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. handle -- Handle of an ESSL device. Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller ESP_OK: Success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller ESP_OK: Success Parameters handle -- Handle of an ESSL device. intr_mask -- Mask of interrupt bits to send to slave. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller Type Definitions typedef struct essl_dev_t *essl_handle_t Handle of an ESSL device. Header File Functions esp_err_t essl_sdio_init_dev(essl_handle_t *out_handle, const essl_sdio_config_t *config) Initialize the ESSL SDIO device and get its handle. Parameters out_handle -- Output of the handle. config -- Configuration for the ESSL SDIO device. out_handle -- Output of the handle. config -- Configuration for the ESSL SDIO device. out_handle -- Output of the handle. Returns ESP_OK: on success ESP_ERR_NO_MEM: memory exhausted. ESP_OK: on success ESP_ERR_NO_MEM: memory exhausted. ESP_OK: on success Parameters out_handle -- Output of the handle. config -- Configuration for the ESSL SDIO device. Returns ESP_OK: on success ESP_ERR_NO_MEM: memory exhausted. esp_err_t essl_sdio_deinit_dev(essl_handle_t handle) Deinitialize and free the space used by the ESSL SDIO device. Parameters handle -- Handle of the ESSL SDIO device to deinit. Returns ESP_OK: on success ESP_ERR_INVALID_ARG: wrong handle passed ESP_OK: on success ESP_ERR_INVALID_ARG: wrong handle passed ESP_OK: on success Parameters handle -- Handle of the ESSL SDIO device to deinit. Returns ESP_OK: on success ESP_ERR_INVALID_ARG: wrong handle passed Structures struct essl_sdio_config_t Configuration for the ESSL SDIO device. Public Members sdmmc_card_t *card The initialized sdmmc card pointer of the slave. sdmmc_card_t *card The initialized sdmmc card pointer of the slave. int recv_buffer_size The pre-negotiated recv buffer size used by both the host and the slave. int recv_buffer_size The pre-negotiated recv buffer size used by both the host and the slave. sdmmc_card_t *card Header File Functions esp_err_t essl_spi_init_dev(essl_handle_t *out_handle, const essl_spi_config_t *init_config) Initialize the ESSL SPI device function list and get its handle. Parameters out_handle -- [out] Output of the handle init_config -- Configuration for the ESSL SPI device out_handle -- [out] Output of the handle init_config -- Configuration for the ESSL SPI device out_handle -- [out] Output of the handle Returns ESP_OK: On success ESP_ERR_NO_MEM: Memory exhausted ESP_ERR_INVALID_STATE: SPI driver is not initialized ESP_ERR_INVALID_ARG: Wrong register ID ESP_OK: On success ESP_ERR_NO_MEM: Memory exhausted ESP_ERR_INVALID_STATE: SPI driver is not initialized ESP_ERR_INVALID_ARG: Wrong register ID ESP_OK: On success Parameters out_handle -- [out] Output of the handle init_config -- Configuration for the ESSL SPI device Returns ESP_OK: On success ESP_ERR_NO_MEM: Memory exhausted ESP_ERR_INVALID_STATE: SPI driver is not initialized ESP_ERR_INVALID_ARG: Wrong register ID esp_err_t essl_spi_deinit_dev(essl_handle_t handle) Deinitialize the ESSL SPI device and free the memory used by the device. Parameters handle -- Handle of the ESSL SPI device Returns ESP_OK: On success ESP_ERR_INVALID_STATE: ESSL SPI is not in use ESP_OK: On success ESP_ERR_INVALID_STATE: ESSL SPI is not in use ESP_OK: On success Parameters handle -- Handle of the ESSL SPI device Returns ESP_OK: On success ESP_ERR_INVALID_STATE: ESSL SPI is not in use esp_err_t essl_spi_read_reg(void *arg, uint8_t addr, uint8_t *out_value, uint32_t wait_ms) Read from the shared registers. Note The registers for Master/Slave synchronization are reserved. Do not use them. (see rx_sync_reg in essl_spi_config_t ) Parameters arg -- Context of the component. (Member arg from essl_handle_t ) addr -- Address of the shared registers. (Valid: 0 ~ SOC_SPI_MAXIMUM_BUFFER_SIZE, registers for M/S sync are reserved, see note1). out_value -- [out] Read buffer for the shared registers. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). arg -- Context of the component. (Member arg from essl_handle_t ) addr -- Address of the shared registers. (Valid: 0 ~ SOC_SPI_MAXIMUM_BUFFER_SIZE, registers for M/S sync are reserved, see note1). out_value -- [out] Read buffer for the shared registers. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). arg -- Context of the component. (Member arg from essl_handle_t ) Returns ESP_OK: success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The address argument is not valid. See note 1. or other return value from :cpp:func: spi_device_transmit . ESP_OK: success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The address argument is not valid. See note 1. or other return value from :cpp:func: spi_device_transmit . ESP_OK: success Parameters arg -- Context of the component. (Member arg from essl_handle_t ) addr -- Address of the shared registers. (Valid: 0 ~ SOC_SPI_MAXIMUM_BUFFER_SIZE, registers for M/S sync are reserved, see note1). out_value -- [out] Read buffer for the shared registers. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). Returns ESP_OK: success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The address argument is not valid. See note 1. or other return value from :cpp:func: spi_device_transmit . esp_err_t essl_spi_get_packet(void *arg, void *out_data, size_t size, uint32_t wait_ms) Get a packet from Slave. Parameters arg -- Context of the component. (Member arg from essl_handle_t ) out_data -- [out] Output data address size -- The size of the output data. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). arg -- Context of the component. (Member arg from essl_handle_t ) out_data -- [out] Output data address size -- The size of the output data. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). arg -- Context of the component. (Member arg from essl_handle_t ) Returns ESP_OK: On Success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The output data address is neither DMA capable nor 4 byte-aligned ESP_ERR_INVALID_SIZE: Master requires size bytes of data but Slave did not load enough bytes. ESP_OK: On Success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The output data address is neither DMA capable nor 4 byte-aligned ESP_ERR_INVALID_SIZE: Master requires size bytes of data but Slave did not load enough bytes. ESP_OK: On Success Parameters arg -- Context of the component. (Member arg from essl_handle_t ) out_data -- [out] Output data address size -- The size of the output data. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). Returns ESP_OK: On Success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The output data address is neither DMA capable nor 4 byte-aligned ESP_ERR_INVALID_SIZE: Master requires size bytes of data but Slave did not load enough bytes. esp_err_t essl_spi_write_reg(void *arg, uint8_t addr, uint8_t value, uint8_t *out_value, uint32_t wait_ms) Write to the shared registers. Note The registers for Master/Slave synchronization are reserved. Do not use them. (see tx_sync_reg in essl_spi_config_t ) Note Feature of checking the actual written value ( out_value ) is not supported. Parameters arg -- Context of the component. (Member arg from essl_handle_t ) addr -- Address of the shared registers. (Valid: 0 ~ SOC_SPI_MAXIMUM_BUFFER_SIZE, registers for M/S sync are reserved, see note1) value -- Buffer for data to send, should be align to 4. out_value -- [out] Not supported, should be set to NULL. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). arg -- Context of the component. (Member arg from essl_handle_t ) addr -- Address of the shared registers. (Valid: 0 ~ SOC_SPI_MAXIMUM_BUFFER_SIZE, registers for M/S sync are reserved, see note1) value -- Buffer for data to send, should be align to 4. out_value -- [out] Not supported, should be set to NULL. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). arg -- Context of the component. (Member arg from essl_handle_t ) Returns ESP_OK: success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The address argument is not valid. See note 1. ESP_ERR_NOT_SUPPORTED: Should set out_value to NULL. See note 2. or other return value from :cpp:func: spi_device_transmit . ESP_OK: success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The address argument is not valid. See note 1. ESP_ERR_NOT_SUPPORTED: Should set out_value to NULL. See note 2. or other return value from :cpp:func: spi_device_transmit . ESP_OK: success Parameters arg -- Context of the component. (Member arg from essl_handle_t ) addr -- Address of the shared registers. (Valid: 0 ~ SOC_SPI_MAXIMUM_BUFFER_SIZE, registers for M/S sync are reserved, see note1) value -- Buffer for data to send, should be align to 4. out_value -- [out] Not supported, should be set to NULL. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). Returns ESP_OK: success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The address argument is not valid. See note 1. ESP_ERR_NOT_SUPPORTED: Should set out_value to NULL. See note 2. or other return value from :cpp:func: spi_device_transmit . esp_err_t essl_spi_send_packet(void *arg, const void *data, size_t size, uint32_t wait_ms) Send a packet to Slave. Parameters arg -- Context of the component. (Member arg from essl_handle_t ) data -- Address of the data to send size -- Size of the data to send. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). arg -- Context of the component. (Member arg from essl_handle_t ) data -- Address of the data to send size -- Size of the data to send. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). arg -- Context of the component. (Member arg from essl_handle_t ) Returns ESP_OK: On success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The data address is not DMA capable ESP_ERR_INVALID_SIZE: Master will send size bytes of data but Slave did not load enough RX buffer ESP_OK: On success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The data address is not DMA capable ESP_ERR_INVALID_SIZE: Master will send size bytes of data but Slave did not load enough RX buffer ESP_OK: On success Parameters arg -- Context of the component. (Member arg from essl_handle_t ) data -- Address of the data to send size -- Size of the data to send. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). Returns ESP_OK: On success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The data address is not DMA capable ESP_ERR_INVALID_SIZE: Master will send size bytes of data but Slave did not load enough RX buffer void essl_spi_reset_cnt(void *arg) Reset the counter in Master context. Note Shall only be called if the slave has reset its counter. Else, Slave and Master would be desynchronized Parameters arg -- Context of the component. (Member arg from essl_handle_t ) Parameters arg -- Context of the component. (Member arg from essl_handle_t ) esp_err_t essl_spi_rdbuf(spi_device_handle_t spi, uint8_t *out_data, int addr, int len, uint32_t flags) Read the shared buffer from the slave in ISR way. Note The slave's HW doesn't guarantee the data in one SPI transaction is consistent. It sends data in unit of byte. In other words, if the slave SW attempts to update the shared register when a rdbuf SPI transaction is in-flight, the data got by the master will be the combination of bytes of different writes of slave SW. Note out_data should be prepared in words and in the DRAM. The buffer may be written in words by the DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the len is shorter than a word. Parameters spi -- SPI device handle representing the slave out_data -- [out] Buffer for read data, strongly suggested to be in the DRAM and aligned to 4 addr -- Address of the slave shared buffer len -- Length to read flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave out_data -- [out] Buffer for read data, strongly suggested to be in the DRAM and aligned to 4 addr -- Address of the slave shared buffer len -- Length to read flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave Returns ESP_OK: on success or other return value from :cpp:func: spi_device_transmit . ESP_OK: on success or other return value from :cpp:func: spi_device_transmit . ESP_OK: on success Parameters spi -- SPI device handle representing the slave out_data -- [out] Buffer for read data, strongly suggested to be in the DRAM and aligned to 4 addr -- Address of the slave shared buffer len -- Length to read flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. Returns ESP_OK: on success or other return value from :cpp:func: spi_device_transmit . esp_err_t essl_spi_rdbuf_polling(spi_device_handle_t spi, uint8_t *out_data, int addr, int len, uint32_t flags) Read the shared buffer from the slave in polling way. Note out_data should be prepared in words and in the DRAM. The buffer may be written in words by the DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the len is shorter than a word. Parameters spi -- SPI device handle representing the slave out_data -- [out] Buffer for read data, strongly suggested to be in the DRAM and aligned to 4 addr -- Address of the slave shared buffer len -- Length to read flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave out_data -- [out] Buffer for read data, strongly suggested to be in the DRAM and aligned to 4 addr -- Address of the slave shared buffer len -- Length to read flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave Returns ESP_OK: on success or other return value from :cpp:func: spi_device_transmit . ESP_OK: on success or other return value from :cpp:func: spi_device_transmit . ESP_OK: on success Parameters spi -- SPI device handle representing the slave out_data -- [out] Buffer for read data, strongly suggested to be in the DRAM and aligned to 4 addr -- Address of the slave shared buffer len -- Length to read flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. Returns ESP_OK: on success or other return value from :cpp:func: spi_device_transmit . esp_err_t essl_spi_wrbuf(spi_device_handle_t spi, const uint8_t *data, int addr, int len, uint32_t flags) Write the shared buffer of the slave in ISR way. Note out_data should be prepared in words and in the DRAM. The buffer may be written in words by the DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the len is shorter than a word. Parameters spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM addr -- Address of the slave shared buffer, len -- Length to write flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM addr -- Address of the slave shared buffer, len -- Length to write flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit . ESP_OK: success or other return value from :cpp:func: spi_device_transmit . ESP_OK: success Parameters spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM addr -- Address of the slave shared buffer, len -- Length to write flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit . esp_err_t essl_spi_wrbuf_polling(spi_device_handle_t spi, const uint8_t *data, int addr, int len, uint32_t flags) Write the shared buffer of the slave in polling way. Note out_data should be prepared in words and in the DRAM. The buffer may be written in words by the DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the len is shorter than a word. Parameters spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM addr -- Address of the slave shared buffer, len -- Length to write flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM addr -- Address of the slave shared buffer, len -- Length to write flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave Returns ESP_OK: success or other return value from :cpp:func: spi_device_polling_transmit . ESP_OK: success or other return value from :cpp:func: spi_device_polling_transmit . ESP_OK: success Parameters spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM addr -- Address of the slave shared buffer, len -- Length to write flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. Returns ESP_OK: success or other return value from :cpp:func: spi_device_polling_transmit . esp_err_t essl_spi_rddma(spi_device_handle_t spi, uint8_t *out_data, int len, int seg_len, uint32_t flags) Receive long buffer in segments from the slave through its DMA. Note This function combines several :cpp:func: essl_spi_rddma_seg and one :cpp:func: essl_spi_rddma_done at the end. Used when the slave is working in segment mode. Parameters spi -- SPI device handle representing the slave out_data -- [out] Buffer to hold the received data, strongly suggested to be in the DRAM and aligned to 4 len -- Total length of data to receive. seg_len -- Length of each segment, which is not larger than the maximum transaction length allowed for the spi device. Suggested to be multiples of 4. When set < 0, means send all data in one segment (the rddma_done will still be sent.) flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave out_data -- [out] Buffer to hold the received data, strongly suggested to be in the DRAM and aligned to 4 len -- Total length of data to receive. seg_len -- Length of each segment, which is not larger than the maximum transaction length allowed for the spi device. Suggested to be multiples of 4. When set < 0, means send all data in one segment (the rddma_done will still be sent.) flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit . ESP_OK: success or other return value from :cpp:func: spi_device_transmit . ESP_OK: success Parameters spi -- SPI device handle representing the slave out_data -- [out] Buffer to hold the received data, strongly suggested to be in the DRAM and aligned to 4 len -- Total length of data to receive. seg_len -- Length of each segment, which is not larger than the maximum transaction length allowed for the spi device. Suggested to be multiples of 4. When set < 0, means send all data in one segment (the rddma_done will still be sent.) flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit . esp_err_t essl_spi_rddma_seg(spi_device_handle_t spi, uint8_t *out_data, int seg_len, uint32_t flags) Read one data segment from the slave through its DMA. Note To read long buffer, call :cpp:func: essl_spi_rddma instead. Parameters spi -- SPI device handle representing the slave out_data -- [out] Buffer to hold the received data. strongly suggested to be in the DRAM and aligned to 4 seg_len -- Length of this segment flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave out_data -- [out] Buffer to hold the received data. strongly suggested to be in the DRAM and aligned to 4 seg_len -- Length of this segment flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit . ESP_OK: success or other return value from :cpp:func: spi_device_transmit . ESP_OK: success Parameters spi -- SPI device handle representing the slave out_data -- [out] Buffer to hold the received data. strongly suggested to be in the DRAM and aligned to 4 seg_len -- Length of this segment flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit . esp_err_t essl_spi_rddma_done(spi_device_handle_t spi, uint32_t flags) Send the rddma_done command to the slave. Upon receiving this command, the slave will stop sending the current buffer even there are data unsent, and maybe prepare the next buffer to send. Note This is required only when the slave is working in segment mode. Parameters spi -- SPI device handle representing the slave flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit . ESP_OK: success or other return value from :cpp:func: spi_device_transmit . ESP_OK: success Parameters spi -- SPI device handle representing the slave flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit . esp_err_t essl_spi_wrdma(spi_device_handle_t spi, const uint8_t *data, int len, int seg_len, uint32_t flags) Send long buffer in segments to the slave through its DMA. Note This function combines several :cpp:func: essl_spi_wrdma_seg and one :cpp:func: essl_spi_wrdma_done at the end. Used when the slave is working in segment mode. Parameters spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM len -- Total length of data to send. seg_len -- Length of each segment, which is not larger than the maximum transaction length allowed for the spi device. Suggested to be multiples of 4. When set < 0, means send all data in one segment (the wrdma_done will still be sent.) flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM len -- Total length of data to send. seg_len -- Length of each segment, which is not larger than the maximum transaction length allowed for the spi device. Suggested to be multiples of 4. When set < 0, means send all data in one segment (the wrdma_done will still be sent.) flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit . ESP_OK: success or other return value from :cpp:func: spi_device_transmit . ESP_OK: success Parameters spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM len -- Total length of data to send. seg_len -- Length of each segment, which is not larger than the maximum transaction length allowed for the spi device. Suggested to be multiples of 4. When set < 0, means send all data in one segment (the wrdma_done will still be sent.) flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit . esp_err_t essl_spi_wrdma_seg(spi_device_handle_t spi, const uint8_t *data, int seg_len, uint32_t flags) Send one data segment to the slave through its DMA. Note To send long buffer, call :cpp:func: essl_spi_wrdma instead. Parameters spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM seg_len -- Length of this segment flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM seg_len -- Length of this segment flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit . ESP_OK: success or other return value from :cpp:func: spi_device_transmit . ESP_OK: success Parameters spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM seg_len -- Length of this segment flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit . esp_err_t essl_spi_wrdma_done(spi_device_handle_t spi, uint32_t flags) Send the wrdma_done command to the slave. Upon receiving this command, the slave will stop receiving, process the received data, and maybe prepare the next buffer to receive. Note This is required only when the slave is working in segment mode. Parameters spi -- SPI device handle representing the slave flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. spi -- SPI device handle representing the slave Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit . ESP_OK: success or other return value from :cpp:func: spi_device_transmit . ESP_OK: success Parameters spi -- SPI device handle representing the slave flags -- SPI_TRANS_* flags to control the transaction mode of the transaction to send. Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit . Structures struct essl_spi_config_t Configuration of ESSL SPI device. Public Members spi_device_handle_t *spi Pointer to SPI device handle. spi_device_handle_t *spi Pointer to SPI device handle. uint32_t tx_buf_size The pre-negotiated Master TX buffer size used by both the host and the slave. uint32_t tx_buf_size The pre-negotiated Master TX buffer size used by both the host and the slave. uint8_t tx_sync_reg The pre-negotiated register ID for Master-TX-SLAVE-RX synchronization. 1 word (4 Bytes) will be reserved for the synchronization. uint8_t tx_sync_reg The pre-negotiated register ID for Master-TX-SLAVE-RX synchronization. 1 word (4 Bytes) will be reserved for the synchronization. uint8_t rx_sync_reg The pre-negotiated register ID for Master-RX-Slave-TX synchronization. 1 word (4 Bytes) will be reserved for the synchronization. uint8_t rx_sync_reg The pre-negotiated register ID for Master-RX-Slave-TX synchronization. 1 word (4 Bytes) will be reserved for the synchronization. spi_device_handle_t *spi
ESP Serial Slave Link Overview Espressif provides several chips that can work as slaves. These slave devices rely on some common buses, and have their own communication protocols over those buses. The esp_serial_slave_link component is designed for the master to communicate with ESP slave devices through those protocols over the bus drivers. After an esp_serial_slave_link device is initialized properly, the application can use it to communicate with the ESP slave devices conveniently. Note The ESP-IDF component esp_serial_slave_link has been moved from ESP-IDF since version v5.0 to a separate repository: To add ESSL component in your project, please run idf.py add-dependency espressif/esp_serial_slave_link. Espressif Device Protocols For more details about Espressif device protocols, see the following documents. Terminology ESSL: Abbreviation for ESP Serial Slave Link, the component described by this document. Master: The device running the esp_serial_slave_linkcomponent. ESSL device: a virtual device on the master associated with an ESP slave device. The device context has the knowledge of the slave protocol above the bus, relying on some bus drivers to communicate with the slave. ESSL device handle: a handle to ESSL device context containing the configuration, status and data required by the ESSL component. The context stores the driver configurations, communication state, data shared by master and slave, etc. The context should be initialized before it is used, and get deinitialized if not used any more. The master application operates on the ESSL device through this handle. - ESP slave: the slave device connected to the bus, which ESSL component is designed to communicate with. Bus: The bus over which the master and the slave communicate with each other. Slave protocol: The special communication protocol specified by Espressif HW/SW over the bus. TX buffer num: a counter, which is on the slave and can be read by the master, indicates the accumulated buffer numbers that the slave has loaded to the hardware to receive data from the master. RX data size: a counter, which is on the slave and can be read by the master, indicates the accumulated data size that the slave has loaded to the hardware to send to the master. Services Provided by ESP Slave There are some common services provided by the Espressif slaves: Tohost Interrupts: The slave can inform the master about certain events by the interrupt line. (optional) Frhost Interrupts: The master can inform the slave about certain events. TX FIFO (master to slave): The slave can receive data from the master in units of receiving buffers. The slave updates the TX buffer num to inform the master how much data it can receive, and the master then read the TX buffer num, and take off the used buffer number to know how many buffers are remaining. RX FIFO (slave to master): The slave can send data in stream to the master. The SDIO slave can also indicate it has new data to send to master by the interrupt line. The slave updates the RX data size to inform the master how much data it has prepared to send, and then the master read the data size, and take off the data length it has already received to know how many data is remaining. Shared registers: The master can read some part of the registers on the slave, and also write these registers to let the slave read. The services provided by the slave depends on the slave's model. See SDIO Slave Capabilities of Espressif Chips and SPI Slave Capabilities of Espressif Chips for more details. Initialization of ESP Serial Slave Link ESP SDIO Slave The ESP SDIO slave link (ESSL SDIO) devices relies on the SDMMC component. It includes the usage of communicating with ESP SDIO Slave device via the SDMMC Host or SDSPI Host feature. The ESSL device should be initialized as below: Initialize a SDMMC card (see :doc:` Document of SDMMC driver </api-reference/storage/sdmmc>`) structure. Call sdmmc_card_init()to initialize the card. Initialize the ESSL device with essl_sdio_config_t. The cardmember should be the sdmmc_card_tgot in step 2, and the recv_buffer_sizemember should be filled correctly according to pre-negotiated value. Call essl_init()to do initialization of the SDIO part. Call essl_wait_for_ready()to wait for the slave to be ready. ESP SPI Slave Note If you are communicating with the ESP SDIO Slave device through SPI interface, you should use the SDIO interface instead. Has not been supported yet. APIs After the initialization process above is performed, you can call the APIs below to make use of the services provided by the slave: Tohost Interrupts (Optional) Call essl_get_intr_ena()to know which events trigger the interrupts to the master. Call essl_set_intr_ena()to set the events that trigger interrupts to the master. Call essl_wait_int()to wait until interrupt from the slave, or timeout. When interrupt is triggered, call essl_get_intr()to know which events are active, and call essl_clear_intr()to clear them. Frhost Interrupts Call essl_send_slave_intr()to trigger general purpose interrupt of the slave. TX FIFO Call essl_get_tx_buffer_num()to know how many buffers the slave has prepared to receive data from the master. This is optional. The master will poll tx_buffer_numwhen it tries to send packets to the slave, until the slave has enough buffer or timeout. Call essl_send_packet()to send data to the slave. RX FIFO Call essl_get_rx_data_size()to know how many data the slave has prepared to send to the master. This is optional. When the master tries to receive data from the slave, it updates the rx_data_sizefor once, if the current rx_data_sizeis shorter than the buffer size the master prepared to receive. And it may poll the rx_data_sizeif the rx_data_sizekeeps 0, until timeout. Call essl_get_packet()to receive data from the slave. Reset Counters (Optional) Call essl_reset_cnt() to reset the internal counter if you find the slave has reset its counter. Application Example The example below shows how ESP32 SDIO host and slave communicate with each other. The host uses the ESSL SDIO: Please refer to the specific example README.md for details. API Reference Header File Functions - esp_err_t essl_init(essl_handle_t handle, uint32_t wait_ms) Initialize the slave. - Parameters handle -- Handle of an ESSL device. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. - - Returns ESP_OK: If success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. Other value returned from lower layer init. - - esp_err_t essl_wait_for_ready(essl_handle_t handle, uint32_t wait_ms) Wait for interrupt of an ESSL slave device. - Parameters handle -- Handle of an ESSL device. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. - - Returns ESP_OK: If success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller - - esp_err_t essl_get_tx_buffer_num(essl_handle_t handle, uint32_t *out_tx_num, uint32_t wait_ms) Get buffer num for the host to send data to the slave. The buffers are size of buffer_size. - Parameters handle -- Handle of a ESSL device. out_tx_num -- Output of buffer num that host can send data to ESSL slave. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. - - Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller - - esp_err_t essl_get_rx_data_size(essl_handle_t handle, uint32_t *out_rx_size, uint32_t wait_ms) Get the size, in bytes, of the data that the ESSL slave is ready to send - Parameters handle -- Handle of an ESSL device. out_rx_size -- Output of data size to read from slave, in bytes wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. - - Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller - - esp_err_t essl_reset_cnt(essl_handle_t handle) Reset the counters of this component. Usually you don't need to do this unless you know the slave is reset. - Parameters handle -- Handle of an ESSL device. - Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode ESP_ERR_INVALID_ARG: Invalid argument, handle is not init. - - esp_err_t essl_send_packet(essl_handle_t handle, const void *start, size_t length, uint32_t wait_ms) Send a packet to the ESSL Slave. The Slave receives the packet into buffers whose size is buffer_size(configured during initialization). - Parameters handle -- Handle of an ESSL device. start -- Start address of the packet to send length -- Length of data to send, if the packet is over-size, the it will be divided into blocks and hold into different buffers automatically. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. - - Returns ESP_OK Success ESP_ERR_INVALID_ARG: Invalid argument, handle is not init or other argument is not valid. ESP_ERR_TIMEOUT: No buffer to use, or error ftrom SDMMC host controller. ESP_ERR_NOT_FOUND: Slave is not ready for receiving. ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller. - - esp_err_t essl_get_packet(essl_handle_t handle, void *out_data, size_t size, size_t *out_length, uint32_t wait_ms) Get a packet from ESSL slave. - Parameters handle -- Handle of an ESSL device. out_data -- [out] Data output address size -- The size of the output buffer, if the buffer is smaller than the size of data to receive from slave, the driver returns ESP_ERR_NOT_FINISHED out_length -- [out] Output of length the data actually received from slave. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. - - Returns ESP_OK Success: All the data has been read from the slave. ESP_ERR_INVALID_ARG: Invalid argument, The handle is not initialized or the other arguments are invalid. ESP_ERR_NOT_FINISHED: Read was successful, but there is still data remaining. ESP_ERR_NOT_FOUND: Slave is not ready to send data. ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode One of the error codes from SDMMC/SPI host controller. - - esp_err_t essl_write_reg(essl_handle_t handle, uint8_t addr, uint8_t value, uint8_t *value_o, uint32_t wait_ms) Write general purpose R/W registers (8-bit) of ESSL slave. Note sdio 28-31 are reserved, the lower API helps to skip. - Parameters handle -- Handle of an ESSL device. addr -- Address of register to write. For SDIO, valid address: 0-59. For SPI, see essl_spi.h value -- Value to write to the register. value_o -- Output of the returned written value. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. - - Returns ESP_OK Success One of the error codes from SDMMC/SPI host controller - - esp_err_t essl_read_reg(essl_handle_t handle, uint8_t add, uint8_t *value_o, uint32_t wait_ms) Read general purpose R/W registers (8-bit) of ESSL slave. - Parameters handle -- Handle of a essldevice. add -- Address of register to read. For SDIO, Valid address: 0-27, 32-63 (28-31 reserved, return interrupt bits on read). For SPI, see essl_spi.h value_o -- Output value read from the register. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. - - Returns ESP_OK Success One of the error codes from SDMMC/SPI host controller - - esp_err_t essl_wait_int(essl_handle_t handle, uint32_t wait_ms) wait for an interrupt of the slave - Parameters handle -- Handle of an ESSL device. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. - - Returns ESP_OK: If interrupt is triggered. ESP_ERR_NOT_SUPPORTED: Current device does not support this function. ESP_ERR_TIMEOUT: No interrupts before timeout. - - esp_err_t essl_clear_intr(essl_handle_t handle, uint32_t intr_mask, uint32_t wait_ms) Clear interrupt bits of ESSL slave. All the bits set in the mask will be cleared, while other bits will stay the same. - Parameters handle -- Handle of an ESSL device. intr_mask -- Mask of interrupt bits to clear. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. - - Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller - - esp_err_t essl_get_intr(essl_handle_t handle, uint32_t *intr_raw, uint32_t *intr_st, uint32_t wait_ms) Get interrupt bits of ESSL slave. - Parameters handle -- Handle of an ESSL device. intr_raw -- Output of the raw interrupt bits. Set to NULL if only masked bits are read. intr_st -- Output of the masked interrupt bits. set to NULL if only raw bits are read. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. - - Returns ESP_OK: Success ESP_INVALID_ARG: If both intr_rawand intr_stare NULL. ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller - - esp_err_t essl_set_intr_ena(essl_handle_t handle, uint32_t ena_mask, uint32_t wait_ms) Set interrupt enable bits of ESSL slave. The slave only sends interrupt on the line when there is a bit both the raw status and the enable are set. - Parameters handle -- Handle of an ESSL device. ena_mask -- Mask of the interrupt bits to enable. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. - - Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller - - esp_err_t essl_get_intr_ena(essl_handle_t handle, uint32_t *ena_mask_o, uint32_t wait_ms) Get interrupt enable bits of ESSL slave. - Parameters handle -- Handle of an ESSL device. ena_mask_o -- Output of interrupt bit enable mask. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. - - Returns ESP_OK Success One of the error codes from SDMMC host controller - - esp_err_t essl_send_slave_intr(essl_handle_t handle, uint32_t intr_mask, uint32_t wait_ms) Send interrupts to slave. Each bit of the interrupt will be triggered. - Parameters handle -- Handle of an ESSL device. intr_mask -- Mask of interrupt bits to send to slave. wait_ms -- Millisecond to wait before timeout, will not wait at all if set to 0-9. - - Returns ESP_OK: Success ESP_ERR_NOT_SUPPORTED: Current device does not support this function. One of the error codes from SDMMC host controller - Type Definitions - typedef struct essl_dev_t *essl_handle_t Handle of an ESSL device. Header File Functions - esp_err_t essl_sdio_init_dev(essl_handle_t *out_handle, const essl_sdio_config_t *config) Initialize the ESSL SDIO device and get its handle. - Parameters out_handle -- Output of the handle. config -- Configuration for the ESSL SDIO device. - - Returns ESP_OK: on success ESP_ERR_NO_MEM: memory exhausted. - - esp_err_t essl_sdio_deinit_dev(essl_handle_t handle) Deinitialize and free the space used by the ESSL SDIO device. - Parameters handle -- Handle of the ESSL SDIO device to deinit. - Returns ESP_OK: on success ESP_ERR_INVALID_ARG: wrong handle passed - Structures - struct essl_sdio_config_t Configuration for the ESSL SDIO device. Public Members - sdmmc_card_t *card The initialized sdmmc card pointer of the slave. - int recv_buffer_size The pre-negotiated recv buffer size used by both the host and the slave. - sdmmc_card_t *card Header File Functions - esp_err_t essl_spi_init_dev(essl_handle_t *out_handle, const essl_spi_config_t *init_config) Initialize the ESSL SPI device function list and get its handle. - Parameters out_handle -- [out] Output of the handle init_config -- Configuration for the ESSL SPI device - - Returns ESP_OK: On success ESP_ERR_NO_MEM: Memory exhausted ESP_ERR_INVALID_STATE: SPI driver is not initialized ESP_ERR_INVALID_ARG: Wrong register ID - - esp_err_t essl_spi_deinit_dev(essl_handle_t handle) Deinitialize the ESSL SPI device and free the memory used by the device. - Parameters handle -- Handle of the ESSL SPI device - Returns ESP_OK: On success ESP_ERR_INVALID_STATE: ESSL SPI is not in use - - esp_err_t essl_spi_read_reg(void *arg, uint8_t addr, uint8_t *out_value, uint32_t wait_ms) Read from the shared registers. Note The registers for Master/Slave synchronization are reserved. Do not use them. (see rx_sync_regin essl_spi_config_t) - Parameters arg -- Context of the component. (Member argfrom essl_handle_t) addr -- Address of the shared registers. (Valid: 0 ~ SOC_SPI_MAXIMUM_BUFFER_SIZE, registers for M/S sync are reserved, see note1). out_value -- [out] Read buffer for the shared registers. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). - - Returns ESP_OK: success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The address argument is not valid. See note 1. or other return value from :cpp:func: spi_device_transmit. - - esp_err_t essl_spi_get_packet(void *arg, void *out_data, size_t size, uint32_t wait_ms) Get a packet from Slave. - Parameters arg -- Context of the component. (Member argfrom essl_handle_t) out_data -- [out] Output data address size -- The size of the output data. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). - - Returns ESP_OK: On Success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The output data address is neither DMA capable nor 4 byte-aligned ESP_ERR_INVALID_SIZE: Master requires sizebytes of data but Slave did not load enough bytes. - - esp_err_t essl_spi_write_reg(void *arg, uint8_t addr, uint8_t value, uint8_t *out_value, uint32_t wait_ms) Write to the shared registers. Note The registers for Master/Slave synchronization are reserved. Do not use them. (see tx_sync_regin essl_spi_config_t) Note Feature of checking the actual written value ( out_value) is not supported. - Parameters arg -- Context of the component. (Member argfrom essl_handle_t) addr -- Address of the shared registers. (Valid: 0 ~ SOC_SPI_MAXIMUM_BUFFER_SIZE, registers for M/S sync are reserved, see note1) value -- Buffer for data to send, should be align to 4. out_value -- [out] Not supported, should be set to NULL. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). - - Returns ESP_OK: success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The address argument is not valid. See note 1. ESP_ERR_NOT_SUPPORTED: Should set out_valueto NULL. See note 2. or other return value from :cpp:func: spi_device_transmit. - - esp_err_t essl_spi_send_packet(void *arg, const void *data, size_t size, uint32_t wait_ms) Send a packet to Slave. - Parameters arg -- Context of the component. (Member argfrom essl_handle_t) data -- Address of the data to send size -- Size of the data to send. wait_ms -- Time to wait before timeout (reserved for future use, user should set this to 0). - - Returns ESP_OK: On success ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized. ESP_ERR_INVALID_ARG: The data address is not DMA capable ESP_ERR_INVALID_SIZE: Master will send sizebytes of data but Slave did not load enough RX buffer - - void essl_spi_reset_cnt(void *arg) Reset the counter in Master context. Note Shall only be called if the slave has reset its counter. Else, Slave and Master would be desynchronized - Parameters arg -- Context of the component. (Member argfrom essl_handle_t) - esp_err_t essl_spi_rdbuf(spi_device_handle_t spi, uint8_t *out_data, int addr, int len, uint32_t flags) Read the shared buffer from the slave in ISR way. Note The slave's HW doesn't guarantee the data in one SPI transaction is consistent. It sends data in unit of byte. In other words, if the slave SW attempts to update the shared register when a rdbuf SPI transaction is in-flight, the data got by the master will be the combination of bytes of different writes of slave SW. Note out_datashould be prepared in words and in the DRAM. The buffer may be written in words by the DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the lenis shorter than a word. - Parameters spi -- SPI device handle representing the slave out_data -- [out] Buffer for read data, strongly suggested to be in the DRAM and aligned to 4 addr -- Address of the slave shared buffer len -- Length to read flags -- SPI_TRANS_*flags to control the transaction mode of the transaction to send. - - Returns ESP_OK: on success or other return value from :cpp:func: spi_device_transmit. - - esp_err_t essl_spi_rdbuf_polling(spi_device_handle_t spi, uint8_t *out_data, int addr, int len, uint32_t flags) Read the shared buffer from the slave in polling way. Note out_datashould be prepared in words and in the DRAM. The buffer may be written in words by the DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the lenis shorter than a word. - Parameters spi -- SPI device handle representing the slave out_data -- [out] Buffer for read data, strongly suggested to be in the DRAM and aligned to 4 addr -- Address of the slave shared buffer len -- Length to read flags -- SPI_TRANS_*flags to control the transaction mode of the transaction to send. - - Returns ESP_OK: on success or other return value from :cpp:func: spi_device_transmit. - - esp_err_t essl_spi_wrbuf(spi_device_handle_t spi, const uint8_t *data, int addr, int len, uint32_t flags) Write the shared buffer of the slave in ISR way. Note out_datashould be prepared in words and in the DRAM. The buffer may be written in words by the DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the lenis shorter than a word. - Parameters spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM addr -- Address of the slave shared buffer, len -- Length to write flags -- SPI_TRANS_*flags to control the transaction mode of the transaction to send. - - Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit. - - esp_err_t essl_spi_wrbuf_polling(spi_device_handle_t spi, const uint8_t *data, int addr, int len, uint32_t flags) Write the shared buffer of the slave in polling way. Note out_datashould be prepared in words and in the DRAM. The buffer may be written in words by the DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the lenis shorter than a word. - Parameters spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM addr -- Address of the slave shared buffer, len -- Length to write flags -- SPI_TRANS_*flags to control the transaction mode of the transaction to send. - - Returns ESP_OK: success or other return value from :cpp:func: spi_device_polling_transmit. - - esp_err_t essl_spi_rddma(spi_device_handle_t spi, uint8_t *out_data, int len, int seg_len, uint32_t flags) Receive long buffer in segments from the slave through its DMA. Note This function combines several :cpp:func: essl_spi_rddma_segand one :cpp:func: essl_spi_rddma_doneat the end. Used when the slave is working in segment mode. - Parameters spi -- SPI device handle representing the slave out_data -- [out] Buffer to hold the received data, strongly suggested to be in the DRAM and aligned to 4 len -- Total length of data to receive. seg_len -- Length of each segment, which is not larger than the maximum transaction length allowed for the spi device. Suggested to be multiples of 4. When set < 0, means send all data in one segment (the rddma_donewill still be sent.) flags -- SPI_TRANS_*flags to control the transaction mode of the transaction to send. - - Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit. - - esp_err_t essl_spi_rddma_seg(spi_device_handle_t spi, uint8_t *out_data, int seg_len, uint32_t flags) Read one data segment from the slave through its DMA. Note To read long buffer, call :cpp:func: essl_spi_rddmainstead. - Parameters spi -- SPI device handle representing the slave out_data -- [out] Buffer to hold the received data. strongly suggested to be in the DRAM and aligned to 4 seg_len -- Length of this segment flags -- SPI_TRANS_*flags to control the transaction mode of the transaction to send. - - Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit. - - esp_err_t essl_spi_rddma_done(spi_device_handle_t spi, uint32_t flags) Send the rddma_donecommand to the slave. Upon receiving this command, the slave will stop sending the current buffer even there are data unsent, and maybe prepare the next buffer to send. Note This is required only when the slave is working in segment mode. - Parameters spi -- SPI device handle representing the slave flags -- SPI_TRANS_*flags to control the transaction mode of the transaction to send. - - Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit. - - esp_err_t essl_spi_wrdma(spi_device_handle_t spi, const uint8_t *data, int len, int seg_len, uint32_t flags) Send long buffer in segments to the slave through its DMA. Note This function combines several :cpp:func: essl_spi_wrdma_segand one :cpp:func: essl_spi_wrdma_doneat the end. Used when the slave is working in segment mode. - Parameters spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM len -- Total length of data to send. seg_len -- Length of each segment, which is not larger than the maximum transaction length allowed for the spi device. Suggested to be multiples of 4. When set < 0, means send all data in one segment (the wrdma_donewill still be sent.) flags -- SPI_TRANS_*flags to control the transaction mode of the transaction to send. - - Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit. - - esp_err_t essl_spi_wrdma_seg(spi_device_handle_t spi, const uint8_t *data, int seg_len, uint32_t flags) Send one data segment to the slave through its DMA. Note To send long buffer, call :cpp:func: essl_spi_wrdmainstead. - Parameters spi -- SPI device handle representing the slave data -- Buffer for data to send, strongly suggested to be in the DRAM seg_len -- Length of this segment flags -- SPI_TRANS_*flags to control the transaction mode of the transaction to send. - - Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit. - - esp_err_t essl_spi_wrdma_done(spi_device_handle_t spi, uint32_t flags) Send the wrdma_donecommand to the slave. Upon receiving this command, the slave will stop receiving, process the received data, and maybe prepare the next buffer to receive. Note This is required only when the slave is working in segment mode. - Parameters spi -- SPI device handle representing the slave flags -- SPI_TRANS_*flags to control the transaction mode of the transaction to send. - - Returns ESP_OK: success or other return value from :cpp:func: spi_device_transmit. - Structures - struct essl_spi_config_t Configuration of ESSL SPI device. Public Members - spi_device_handle_t *spi Pointer to SPI device handle. - uint32_t tx_buf_size The pre-negotiated Master TX buffer size used by both the host and the slave. - uint8_t tx_sync_reg The pre-negotiated register ID for Master-TX-SLAVE-RX synchronization. 1 word (4 Bytes) will be reserved for the synchronization. - uint8_t rx_sync_reg The pre-negotiated register ID for Master-RX-Slave-TX synchronization. 1 word (4 Bytes) will be reserved for the synchronization. - spi_device_handle_t *spi
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/protocols/esp_serial_slave_link.html
ESP-IDF Programming Guide v5.2.1 documentation
null
ESP x509 Certificate Bundle
null
espressif.com
2016-01-01
2d29627b1e191694
null
null
ESP x509 Certificate Bundle Overview The ESP x509 Certificate Bundle API provides an easy way to include a bundle of custom x509 root certificates for TLS server verification. Note The bundle is currently not available when using WolfSSL. The bundle comes with the complete list of root certificates from Mozilla's NSS root certificate store. Using the gen_crt_bundle.py python utility, the certificates' subject name and public key are stored in a file and embedded in the ESP32 binary. When generating the bundle you may choose between: The full root certificate bundle from Mozilla, containing more than 130 certificates. The current bundle was updated Tue Jan 10 04:12:06 2023 GMT. A pre-selected filter list of the name of the most commonly used root certificates, reducing the amount of certificates to around 41 while still having around 90% absolute usage coverage and 99% market share coverage according to SSL certificate authorities statistics. In addition, it is possible to specify a path to a certificate file or a directory containing certificates which then will be added to the generated bundle. Note Trusting all root certificates means the list will have to be updated if any of the certificates are retracted. This includes removing them from cacrt_all.pem . Configuration Most configuration is done through menuconfig. CMake generates the bundle according to the configuration and embed it. CONFIG_MBEDTLS_CERTIFICATE_BUNDLE: automatically build and attach the bundle. CONFIG_MBEDTLS_DEFAULT_CERTIFICATE_BUNDLE: decide which certificates to include from the complete root certificate list. CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE_PATH: specify the path of any additional certificates to embed in the bundle. To enable the bundle when using ESP-TLS simply pass the function pointer to the bundle attach function: esp_tls_cfg_t cfg = { .crt_bundle_attach = esp_crt_bundle_attach, }; This is done to avoid embedding the certificate bundle unless activated by the user. If using mbedTLS directly then the bundle may be activated by directly calling the attach function during the setup process: mbedtls_ssl_config conf; mbedtls_ssl_config_init(&conf); esp_crt_bundle_attach(&conf); Generating the List of Root Certificates The list of root certificates comes from Mozilla's NSS root certificate store, which can be found here The list can be downloaded and created by running the script mk-ca-bundle.pl that is distributed as a part of curl. Another alternative would be to download the finished list directly from the curl website: CA certificates extracted from Mozilla The common certificates bundle were made by selecting the authorities with a market share of more than 1% from w3tech's SSL Survey. These authorities were then used to pick the names of the certificates for the filter list, cmn_crt_authorities.csv , from this list provided by Mozilla. Updating the Certificate Bundle The bundle is embedded into the app and can be updated along with the app by an OTA update. If you want to include a more up-to-date bundle than the bundle currently included in ESP-IDF, then the certificate list can be downloaded from Mozilla as described in Generating the List of Root Certificates. Application Examples Simple HTTPS example that uses ESP-TLS to establish a secure socket connection using the certificate bundle with two custom certificates added for verification: protocols/https_x509_bundle. HTTPS example that uses ESP-TLS and the default bundle: protocols/https_request. HTTPS example that uses mbedTLS and the default bundle: protocols/https_mbedtls. API Reference Header File This header file can be included with: #include "esp_crt_bundle.h" This header file is a part of the API provided by the mbedtls component. To declare that your component depends on mbedtls , add the following to your CMakeLists.txt: REQUIRES mbedtls or PRIV_REQUIRES mbedtls Functions esp_err_t esp_crt_bundle_attach(void *conf) Attach and enable use of a bundle for certificate verification. Attach and enable use of a bundle for certificate verification through a verification callback. If no specific bundle has been set through esp_crt_bundle_set() it will default to the bundle defined in menuconfig and embedded in the binary. Parameters conf -- [in] The config struct for the SSL connection. Returns ESP_OK if adding certificates was successful. Other if an error occured or an action must be taken by the calling process. ESP_OK if adding certificates was successful. Other if an error occured or an action must be taken by the calling process. ESP_OK if adding certificates was successful. Parameters conf -- [in] The config struct for the SSL connection. Returns ESP_OK if adding certificates was successful. Other if an error occured or an action must be taken by the calling process. void esp_crt_bundle_detach(mbedtls_ssl_config *conf) Disable and dealloc the certification bundle. Removes the certificate verification callback and deallocates used resources Parameters conf -- [in] The config struct for the SSL connection. Parameters conf -- [in] The config struct for the SSL connection. esp_err_t esp_crt_bundle_set(const uint8_t *x509_bundle, size_t bundle_size) Set the default certificate bundle used for verification. Overrides the default certificate bundle only in case of successful initialization. In most use cases the bundle should be set through menuconfig. The bundle needs to be sorted by subject name since binary search is used to find certificates. Parameters x509_bundle -- [in] A pointer to the certificate bundle. bundle_size -- [in] Size of the certificate bundle in bytes. x509_bundle -- [in] A pointer to the certificate bundle. bundle_size -- [in] Size of the certificate bundle in bytes. x509_bundle -- [in] A pointer to the certificate bundle. Returns ESP_OK if adding certificates was successful. Other if an error occured or an action must be taken by the calling process. ESP_OK if adding certificates was successful. Other if an error occured or an action must be taken by the calling process. ESP_OK if adding certificates was successful. Parameters x509_bundle -- [in] A pointer to the certificate bundle. bundle_size -- [in] Size of the certificate bundle in bytes. Returns ESP_OK if adding certificates was successful. Other if an error occured or an action must be taken by the calling process.
ESP x509 Certificate Bundle Overview The ESP x509 Certificate Bundle API provides an easy way to include a bundle of custom x509 root certificates for TLS server verification. Note The bundle is currently not available when using WolfSSL. The bundle comes with the complete list of root certificates from Mozilla's NSS root certificate store. Using the gen_crt_bundle.py python utility, the certificates' subject name and public key are stored in a file and embedded in the ESP32 binary. When generating the bundle you may choose between: - The full root certificate bundle from Mozilla, containing more than 130 certificates. The current bundle was updated Tue Jan 10 04:12:06 2023 GMT. - A pre-selected filter list of the name of the most commonly used root certificates, reducing the amount of certificates to around 41 while still having around 90% absolute usage coverage and 99% market share coverage according to SSL certificate authorities statistics. In addition, it is possible to specify a path to a certificate file or a directory containing certificates which then will be added to the generated bundle. Note Trusting all root certificates means the list will have to be updated if any of the certificates are retracted. This includes removing them from cacrt_all.pem. Configuration Most configuration is done through menuconfig. CMake generates the bundle according to the configuration and embed it. - CONFIG_MBEDTLS_CERTIFICATE_BUNDLE: automatically build and attach the bundle. - CONFIG_MBEDTLS_DEFAULT_CERTIFICATE_BUNDLE: decide which certificates to include from the complete root certificate list. - CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE_PATH: specify the path of any additional certificates to embed in the bundle. To enable the bundle when using ESP-TLS simply pass the function pointer to the bundle attach function: esp_tls_cfg_t cfg = { .crt_bundle_attach = esp_crt_bundle_attach, }; This is done to avoid embedding the certificate bundle unless activated by the user. If using mbedTLS directly then the bundle may be activated by directly calling the attach function during the setup process: mbedtls_ssl_config conf; mbedtls_ssl_config_init(&conf); esp_crt_bundle_attach(&conf); Generating the List of Root Certificates The list of root certificates comes from Mozilla's NSS root certificate store, which can be found here The list can be downloaded and created by running the script mk-ca-bundle.pl that is distributed as a part of curl. Another alternative would be to download the finished list directly from the curl website: CA certificates extracted from Mozilla The common certificates bundle were made by selecting the authorities with a market share of more than 1% from w3tech's SSL Survey. These authorities were then used to pick the names of the certificates for the filter list, cmn_crt_authorities.csv, from this list provided by Mozilla. Updating the Certificate Bundle The bundle is embedded into the app and can be updated along with the app by an OTA update. If you want to include a more up-to-date bundle than the bundle currently included in ESP-IDF, then the certificate list can be downloaded from Mozilla as described in Generating the List of Root Certificates. Application Examples Simple HTTPS example that uses ESP-TLS to establish a secure socket connection using the certificate bundle with two custom certificates added for verification: protocols/https_x509_bundle. HTTPS example that uses ESP-TLS and the default bundle: protocols/https_request. HTTPS example that uses mbedTLS and the default bundle: protocols/https_mbedtls. API Reference Header File This header file can be included with: #include "esp_crt_bundle.h" This header file is a part of the API provided by the mbedtlscomponent. To declare that your component depends on mbedtls, add the following to your CMakeLists.txt: REQUIRES mbedtls or PRIV_REQUIRES mbedtls Functions - esp_err_t esp_crt_bundle_attach(void *conf) Attach and enable use of a bundle for certificate verification. Attach and enable use of a bundle for certificate verification through a verification callback. If no specific bundle has been set through esp_crt_bundle_set() it will default to the bundle defined in menuconfig and embedded in the binary. - Parameters conf -- [in] The config struct for the SSL connection. - Returns ESP_OK if adding certificates was successful. Other if an error occured or an action must be taken by the calling process. - - void esp_crt_bundle_detach(mbedtls_ssl_config *conf) Disable and dealloc the certification bundle. Removes the certificate verification callback and deallocates used resources - Parameters conf -- [in] The config struct for the SSL connection. - esp_err_t esp_crt_bundle_set(const uint8_t *x509_bundle, size_t bundle_size) Set the default certificate bundle used for verification. Overrides the default certificate bundle only in case of successful initialization. In most use cases the bundle should be set through menuconfig. The bundle needs to be sorted by subject name since binary search is used to find certificates. - Parameters x509_bundle -- [in] A pointer to the certificate bundle. bundle_size -- [in] Size of the certificate bundle in bytes. - - Returns ESP_OK if adding certificates was successful. Other if an error occured or an action must be taken by the calling process. -
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/protocols/esp_crt_bundle.html
ESP-IDF Programming Guide v5.2.1 documentation
null
HTTP Server
null
espressif.com
2016-01-01
e753bdcbfc02d09f
null
null
HTTP Server Overview The HTTP Server component provides an ability for running a lightweight web server on ESP32. Following are detailed steps to use the API exposed by HTTP Server: httpd_start() : Creates an instance of HTTP server, allocate memory/resources for it depending upon the specified configuration and outputs a handle to the server instance. The server has both, a listening socket (TCP) for HTTP traffic, and a control socket (UDP) for control signals, which are selected in a round robin fashion in the server task loop. The task priority and stack size are configurable during server instance creation by passing httpd_config_t structure to httpd_start() . TCP traffic is parsed as HTTP requests and, depending on the requested URI, user registered handlers are invoked which are supposed to send back HTTP response packets. httpd_stop() : This stops the server with the provided handle and frees up any associated memory/resources. This is a blocking function that first signals a halt to the server task and then waits for the task to terminate. While stopping, the task closes all open connections, removes registered URI handlers and resets all session context data to empty. httpd_register_uri_handler() : A URI handler is registered by passing object of type httpd_uri_t structure which has members including uri name, method type (eg. HTTPD_GET/HTTPD_POST/HTTPD_PUT etc.), function pointer of type esp_err_t *handler (httpd_req_t *req) and user_ctx pointer to user context data. Application Example /* Our URI handler function to be called during GET /uri request */ esp_err_t get_handler(httpd_req_t *req) { /* Send a simple response */ const char resp[] = "URI GET Response"; httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN); return ESP_OK; } /* Our URI handler function to be called during POST /uri request */ esp_err_t post_handler(httpd_req_t *req) { /* Destination buffer for content of HTTP POST request. * httpd_req_recv() accepts char* only, but content could * as well be any binary data (needs type casting). * In case of string data, null termination will be absent, and * content length would give length of string */ char content[100]; /* Truncate if content length larger than the buffer */ size_t recv_size = MIN(req->content_len, sizeof(content)); int ret = httpd_req_recv(req, content, recv_size); if (ret <= 0) { /* 0 return value indicates connection closed */ /* Check if timeout occurred */ if (ret == HTTPD_SOCK_ERR_TIMEOUT) { /* In case of timeout one can choose to retry calling * httpd_req_recv(), but to keep it simple, here we * respond with an HTTP 408 (Request Timeout) error */ httpd_resp_send_408(req); } /* In case of error, returning ESP_FAIL will * ensure that the underlying socket is closed */ return ESP_FAIL; } /* Send a simple response */ const char resp[] = "URI POST Response"; httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN); return ESP_OK; } /* URI handler structure for GET /uri */ httpd_uri_t uri_get = { .uri = "/uri", .method = HTTP_GET, .handler = get_handler, .user_ctx = NULL }; /* URI handler structure for POST /uri */ httpd_uri_t uri_post = { .uri = "/uri", .method = HTTP_POST, .handler = post_handler, .user_ctx = NULL }; /* Function for starting the webserver */ httpd_handle_t start_webserver(void) { /* Generate default configuration */ httpd_config_t config = HTTPD_DEFAULT_CONFIG(); /* Empty handle to esp_http_server */ httpd_handle_t server = NULL; /* Start the httpd server */ if (httpd_start(&server, &config) == ESP_OK) { /* Register URI handlers */ httpd_register_uri_handler(server, &uri_get); httpd_register_uri_handler(server, &uri_post); } /* If server failed to start, handle will be NULL */ return server; } /* Function for stopping the webserver */ void stop_webserver(httpd_handle_t server) { if (server) { /* Stop the httpd server */ httpd_stop(server); } } Simple HTTP Server Example Check HTTP server example under protocols/http_server/simple where handling of arbitrary content lengths, reading request headers and URL query parameters, and setting response headers is demonstrated. Persistent Connections HTTP server features persistent connections, allowing for the re-use of the same connection (session) for several transfers, all the while maintaining context specific data for the session. Context data may be allocated dynamically by the handler in which case a custom function may need to be specified for freeing this data when the connection/session is closed. Persistent Connections Example /* Custom function to free context */ void free_ctx_func(void *ctx) { /* Could be something other than free */ free(ctx); } esp_err_t adder_post_handler(httpd_req_t *req) { /* Create session's context if not already available */ if (! req->sess_ctx) { req->sess_ctx = malloc(sizeof(ANY_DATA_TYPE)); /*!< Pointer to context data */ req->free_ctx = free_ctx_func; /*!< Function to free context data */ } /* Access context data */ ANY_DATA_TYPE *ctx_data = (ANY_DATA_TYPE *)req->sess_ctx; /* Respond */ ............... ............... ............... return ESP_OK; } Check the example under protocols/http_server/persistent_sockets. Websocket Server The HTTP server component provides websocket support. The websocket feature can be enabled in menuconfig using the CONFIG_HTTPD_WS_SUPPORT option. Please refer to the protocols/http_server/ws_echo_server example which demonstrates usage of the websocket feature. Event Handling ESP HTTP server has various events for which a handler can be triggered by the Event Loop library when the particular event occurs. The handler has to be registered using esp_event_handler_register() . This helps in event handling for ESP HTTP server. esp_http_server_event_id_t has all the events which can happen for ESP HTTP server. Expected data type for different ESP HTTP server events in event loop: HTTP_SERVER_EVENT_ERROR : httpd_err_code_t HTTP_SERVER_EVENT_START : NULL HTTP_SERVER_EVENT_ON_CONNECTED : int HTTP_SERVER_EVENT_ON_HEADER : int HTTP_SERVER_EVENT_HEADERS_SENT : int HTTP_SERVER_EVENT_ON_DATA : esp_http_server_event_data HTTP_SERVER_EVENT_SENT_DATA : esp_http_server_event_data HTTP_SERVER_EVENT_DISCONNECTED : int HTTP_SERVER_EVENT_STOP : NULL API Reference Header File This header file can be included with: #include "esp_http_server.h" This header file is a part of the API provided by the esp_http_server component. To declare that your component depends on esp_http_server , add the following to your CMakeLists.txt: REQUIRES esp_http_server or PRIV_REQUIRES esp_http_server Functions esp_err_t httpd_register_uri_handler(httpd_handle_t handle, const httpd_uri_t *uri_handler) Registers a URI handler. Example usage: esp_err_t my_uri_handler(httpd_req_t* req) { // Recv , Process and Send .... .... .... // Fail condition if (....) { // Return fail to close session // return ESP_FAIL; } // On success return ESP_OK; } // URI handler structure httpd_uri_t my_uri { .uri = "/my_uri/path/xyz", .method = HTTPD_GET, .handler = my_uri_handler, .user_ctx = NULL }; // Register handler if (httpd_register_uri_handler(server_handle, &my_uri) != ESP_OK) { // If failed to register handler .... } Note URI handlers can be registered in real time as long as the server handle is valid. Parameters handle -- [in] handle to HTTPD server instance uri_handler -- [in] pointer to handler that needs to be registered handle -- [in] handle to HTTPD server instance uri_handler -- [in] pointer to handler that needs to be registered handle -- [in] handle to HTTPD server instance Returns ESP_OK : On successfully registering the handler ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_HANDLERS_FULL : If no slots left for new handler ESP_ERR_HTTPD_HANDLER_EXISTS : If handler with same URI and method is already registered ESP_OK : On successfully registering the handler ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_HANDLERS_FULL : If no slots left for new handler ESP_ERR_HTTPD_HANDLER_EXISTS : If handler with same URI and method is already registered ESP_OK : On successfully registering the handler Parameters handle -- [in] handle to HTTPD server instance uri_handler -- [in] pointer to handler that needs to be registered Returns ESP_OK : On successfully registering the handler ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_HANDLERS_FULL : If no slots left for new handler ESP_ERR_HTTPD_HANDLER_EXISTS : If handler with same URI and method is already registered esp_err_t httpd_unregister_uri_handler(httpd_handle_t handle, const char *uri, httpd_method_t method) Unregister a URI handler. Parameters handle -- [in] handle to HTTPD server instance uri -- [in] URI string method -- [in] HTTP method handle -- [in] handle to HTTPD server instance uri -- [in] URI string method -- [in] HTTP method handle -- [in] handle to HTTPD server instance Returns ESP_OK : On successfully deregistering the handler ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_NOT_FOUND : Handler with specified URI and method not found ESP_OK : On successfully deregistering the handler ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_NOT_FOUND : Handler with specified URI and method not found ESP_OK : On successfully deregistering the handler Parameters handle -- [in] handle to HTTPD server instance uri -- [in] URI string method -- [in] HTTP method Returns ESP_OK : On successfully deregistering the handler ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_NOT_FOUND : Handler with specified URI and method not found esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char *uri) Unregister all URI handlers with the specified uri string. Parameters handle -- [in] handle to HTTPD server instance uri -- [in] uri string specifying all handlers that need to be deregisterd handle -- [in] handle to HTTPD server instance uri -- [in] uri string specifying all handlers that need to be deregisterd handle -- [in] handle to HTTPD server instance Returns ESP_OK : On successfully deregistering all such handlers ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_NOT_FOUND : No handler registered with specified uri string ESP_OK : On successfully deregistering all such handlers ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_NOT_FOUND : No handler registered with specified uri string ESP_OK : On successfully deregistering all such handlers Parameters handle -- [in] handle to HTTPD server instance uri -- [in] uri string specifying all handlers that need to be deregisterd Returns ESP_OK : On successfully deregistering all such handlers ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_NOT_FOUND : No handler registered with specified uri string esp_err_t httpd_sess_set_recv_override(httpd_handle_t hd, int sockfd, httpd_recv_func_t recv_func) Override web server's receive function (by session FD) This function overrides the web server's receive function. This same function is used to read HTTP request packets. Note This API is supposed to be called either from the context of an http session APIs where sockfd is a valid parameter a URI handler where sockfd is obtained using httpd_req_to_sockfd() an http session APIs where sockfd is a valid parameter a URI handler where sockfd is obtained using httpd_req_to_sockfd() Parameters hd -- [in] HTTPD instance handle sockfd -- [in] Session socket FD recv_func -- [in] The receive function to be set for this session hd -- [in] HTTPD instance handle sockfd -- [in] Session socket FD recv_func -- [in] The receive function to be set for this session hd -- [in] HTTPD instance handle Returns ESP_OK : On successfully registering override ESP_ERR_INVALID_ARG : Null arguments ESP_OK : On successfully registering override ESP_ERR_INVALID_ARG : Null arguments ESP_OK : On successfully registering override Parameters hd -- [in] HTTPD instance handle sockfd -- [in] Session socket FD recv_func -- [in] The receive function to be set for this session Returns ESP_OK : On successfully registering override ESP_ERR_INVALID_ARG : Null arguments an http session APIs where sockfd is a valid parameter esp_err_t httpd_sess_set_send_override(httpd_handle_t hd, int sockfd, httpd_send_func_t send_func) Override web server's send function (by session FD) This function overrides the web server's send function. This same function is used to send out any response to any HTTP request. Note This API is supposed to be called either from the context of an http session APIs where sockfd is a valid parameter a URI handler where sockfd is obtained using httpd_req_to_sockfd() an http session APIs where sockfd is a valid parameter a URI handler where sockfd is obtained using httpd_req_to_sockfd() Parameters hd -- [in] HTTPD instance handle sockfd -- [in] Session socket FD send_func -- [in] The send function to be set for this session hd -- [in] HTTPD instance handle sockfd -- [in] Session socket FD send_func -- [in] The send function to be set for this session hd -- [in] HTTPD instance handle Returns ESP_OK : On successfully registering override ESP_ERR_INVALID_ARG : Null arguments ESP_OK : On successfully registering override ESP_ERR_INVALID_ARG : Null arguments ESP_OK : On successfully registering override Parameters hd -- [in] HTTPD instance handle sockfd -- [in] Session socket FD send_func -- [in] The send function to be set for this session Returns ESP_OK : On successfully registering override ESP_ERR_INVALID_ARG : Null arguments an http session APIs where sockfd is a valid parameter esp_err_t httpd_sess_set_pending_override(httpd_handle_t hd, int sockfd, httpd_pending_func_t pending_func) Override web server's pending function (by session FD) This function overrides the web server's pending function. This function is used to test for pending bytes in a socket. Note This API is supposed to be called either from the context of an http session APIs where sockfd is a valid parameter a URI handler where sockfd is obtained using httpd_req_to_sockfd() an http session APIs where sockfd is a valid parameter a URI handler where sockfd is obtained using httpd_req_to_sockfd() Parameters hd -- [in] HTTPD instance handle sockfd -- [in] Session socket FD pending_func -- [in] The receive function to be set for this session hd -- [in] HTTPD instance handle sockfd -- [in] Session socket FD pending_func -- [in] The receive function to be set for this session hd -- [in] HTTPD instance handle Returns ESP_OK : On successfully registering override ESP_ERR_INVALID_ARG : Null arguments ESP_OK : On successfully registering override ESP_ERR_INVALID_ARG : Null arguments ESP_OK : On successfully registering override Parameters hd -- [in] HTTPD instance handle sockfd -- [in] Session socket FD pending_func -- [in] The receive function to be set for this session Returns ESP_OK : On successfully registering override ESP_ERR_INVALID_ARG : Null arguments an http session APIs where sockfd is a valid parameter esp_err_t httpd_req_async_handler_begin(httpd_req_t *r, httpd_req_t **out) Start an asynchronous request. This function can be called in a request handler to get a request copy that can be used on a async thread. Note This function is necessary in order to handle multiple requests simultaneously. See examples/async_requests for example usage. You must call httpd_req_async_handler_complete() when you are done with the request. This function is necessary in order to handle multiple requests simultaneously. See examples/async_requests for example usage. You must call httpd_req_async_handler_complete() when you are done with the request. Parameters r -- [in] The request to create an async copy of out -- [out] A newly allocated request which can be used on an async thread r -- [in] The request to create an async copy of out -- [out] A newly allocated request which can be used on an async thread r -- [in] The request to create an async copy of Returns ESP_OK : async request object created ESP_OK : async request object created ESP_OK : async request object created Parameters r -- [in] The request to create an async copy of out -- [out] A newly allocated request which can be used on an async thread Returns ESP_OK : async request object created This function is necessary in order to handle multiple requests simultaneously. See examples/async_requests for example usage. esp_err_t httpd_req_async_handler_complete(httpd_req_t *r) Mark an asynchronous request as completed. This will. free the request memory relinquish ownership of the underlying socket, so it can be reused. allow the http server to close our socket if needed (lru_purge_enable) free the request memory relinquish ownership of the underlying socket, so it can be reused. allow the http server to close our socket if needed (lru_purge_enable) Note If async requests are not marked completed, eventually the server will no longer accept incoming connections. The server will log a "httpd_accept_conn: error in accept (23)" message if this happens. Parameters r -- [in] The request to mark async work as completed Returns ESP_OK : async request was marked completed ESP_OK : async request was marked completed ESP_OK : async request was marked completed Parameters r -- [in] The request to mark async work as completed Returns ESP_OK : async request was marked completed free the request memory int httpd_req_to_sockfd(httpd_req_t *r) Get the Socket Descriptor from the HTTP request. This API will return the socket descriptor of the session for which URI handler was executed on reception of HTTP request. This is useful when user wants to call functions that require session socket fd, from within a URI handler, ie. : httpd_sess_get_ctx(), httpd_sess_trigger_close(), httpd_sess_update_lru_counter(). Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Parameters r -- [in] The request whose socket descriptor should be found Returns Socket descriptor : The socket descriptor for this request -1 : Invalid/NULL request pointer Socket descriptor : The socket descriptor for this request -1 : Invalid/NULL request pointer Socket descriptor : The socket descriptor for this request Parameters r -- [in] The request whose socket descriptor should be found Returns Socket descriptor : The socket descriptor for this request -1 : Invalid/NULL request pointer int httpd_req_recv(httpd_req_t *r, char *buf, size_t buf_len) API to read content data from the HTTP request. This API will read HTTP content data from the HTTP request into provided buffer. Use content_len provided in httpd_req_t structure to know the length of data to be fetched. If content_len is too large for the buffer then user may have to make multiple calls to this function, each time fetching 'buf_len' number of bytes, while the pointer to content data is incremented internally by the same number. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. If an error is returned, the URI handler must further return an error. This will ensure that the erroneous socket is closed and cleaned up by the web server. Presently Chunked Encoding is not supported This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. If an error is returned, the URI handler must further return an error. This will ensure that the erroneous socket is closed and cleaned up by the web server. Presently Chunked Encoding is not supported Parameters r -- [in] The request being responded to buf -- [in] Pointer to a buffer that the data will be read into buf_len -- [in] Length of the buffer r -- [in] The request being responded to buf -- [in] Pointer to a buffer that the data will be read into buf_len -- [in] Length of the buffer r -- [in] The request being responded to Returns Bytes : Number of bytes read into the buffer successfully 0 : Buffer length parameter is zero / connection closed by peer HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv() Bytes : Number of bytes read into the buffer successfully 0 : Buffer length parameter is zero / connection closed by peer HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv() Bytes : Number of bytes read into the buffer successfully Parameters r -- [in] The request being responded to buf -- [in] Pointer to a buffer that the data will be read into buf_len -- [in] Length of the buffer Returns Bytes : Number of bytes read into the buffer successfully 0 : Buffer length parameter is zero / connection closed by peer HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv() This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. size_t httpd_req_get_hdr_value_len(httpd_req_t *r, const char *field) Search for a field in request headers and return the string length of it's value. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once httpd_resp_send() API is called all request headers are purged, so request headers need be copied into separate buffers if they are required later. This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once httpd_resp_send() API is called all request headers are purged, so request headers need be copied into separate buffers if they are required later. Parameters r -- [in] The request being responded to field -- [in] The header field to be searched in the request r -- [in] The request being responded to field -- [in] The header field to be searched in the request r -- [in] The request being responded to Returns Length : If field is found in the request URL Zero : Field not found / Invalid request / Null arguments Length : If field is found in the request URL Zero : Field not found / Invalid request / Null arguments Length : If field is found in the request URL Parameters r -- [in] The request being responded to field -- [in] The header field to be searched in the request Returns Length : If field is found in the request URL Zero : Field not found / Invalid request / Null arguments This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. esp_err_t httpd_req_get_hdr_value_str(httpd_req_t *r, const char *field, char *val, size_t val_size) Get the value string of a field from the request headers. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once httpd_resp_send() API is called all request headers are purged, so request headers need be copied into separate buffers if they are required later. If output size is greater than input, then the value is truncated, accompanied by truncation error as return value. Use httpd_req_get_hdr_value_len() to know the right buffer length This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once httpd_resp_send() API is called all request headers are purged, so request headers need be copied into separate buffers if they are required later. If output size is greater than input, then the value is truncated, accompanied by truncation error as return value. Use httpd_req_get_hdr_value_len() to know the right buffer length Parameters r -- [in] The request being responded to field -- [in] The field to be searched in the header val -- [out] Pointer to the buffer into which the value will be copied if the field is found val_size -- [in] Size of the user buffer "val" r -- [in] The request being responded to field -- [in] The field to be searched in the header val -- [out] Pointer to the buffer into which the value will be copied if the field is found val_size -- [in] Size of the user buffer "val" r -- [in] The request being responded to Returns ESP_OK : Field found in the request header and value string copied ESP_ERR_NOT_FOUND : Key not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated ESP_OK : Field found in the request header and value string copied ESP_ERR_NOT_FOUND : Key not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated ESP_OK : Field found in the request header and value string copied Parameters r -- [in] The request being responded to field -- [in] The field to be searched in the header val -- [out] Pointer to the buffer into which the value will be copied if the field is found val_size -- [in] Size of the user buffer "val" Returns ESP_OK : Field found in the request header and value string copied ESP_ERR_NOT_FOUND : Key not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. size_t httpd_req_get_url_query_len(httpd_req_t *r) Get Query string length from the request URL. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid Parameters r -- [in] The request being responded to Returns Length : Query is found in the request URL Zero : Query not found / Null arguments / Invalid request Length : Query is found in the request URL Zero : Query not found / Null arguments / Invalid request Length : Query is found in the request URL Parameters r -- [in] The request being responded to Returns Length : Query is found in the request URL Zero : Query not found / Null arguments / Invalid request esp_err_t httpd_req_get_url_query_str(httpd_req_t *r, char *buf, size_t buf_len) Get Query string from the request URL. Note Presently, the user can fetch the full URL query string, but decoding will have to be performed by the user. Request headers can be read using httpd_req_get_hdr_value_str() to know the 'Content-Type' (eg. Content-Type: application/x-www-form-urlencoded) and then the appropriate decoding algorithm needs to be applied. This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid If output size is greater than input, then the value is truncated, accompanied by truncation error as return value Prior to calling this function, one can use httpd_req_get_url_query_len() to know the query string length beforehand and hence allocate the buffer of right size (usually query string length + 1 for null termination) for storing the query string Presently, the user can fetch the full URL query string, but decoding will have to be performed by the user. Request headers can be read using httpd_req_get_hdr_value_str() to know the 'Content-Type' (eg. Content-Type: application/x-www-form-urlencoded) and then the appropriate decoding algorithm needs to be applied. This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid If output size is greater than input, then the value is truncated, accompanied by truncation error as return value Prior to calling this function, one can use httpd_req_get_url_query_len() to know the query string length beforehand and hence allocate the buffer of right size (usually query string length + 1 for null termination) for storing the query string Parameters r -- [in] The request being responded to buf -- [out] Pointer to the buffer into which the query string will be copied (if found) buf_len -- [in] Length of output buffer r -- [in] The request being responded to buf -- [out] Pointer to the buffer into which the query string will be copied (if found) buf_len -- [in] Length of output buffer r -- [in] The request being responded to Returns ESP_OK : Query is found in the request URL and copied to buffer ESP_ERR_NOT_FOUND : Query not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer ESP_ERR_HTTPD_RESULT_TRUNC : Query string truncated ESP_OK : Query is found in the request URL and copied to buffer ESP_ERR_NOT_FOUND : Query not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer ESP_ERR_HTTPD_RESULT_TRUNC : Query string truncated ESP_OK : Query is found in the request URL and copied to buffer Parameters r -- [in] The request being responded to buf -- [out] Pointer to the buffer into which the query string will be copied (if found) buf_len -- [in] Length of output buffer Returns ESP_OK : Query is found in the request URL and copied to buffer ESP_ERR_NOT_FOUND : Query not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer ESP_ERR_HTTPD_RESULT_TRUNC : Query string truncated Presently, the user can fetch the full URL query string, but decoding will have to be performed by the user. Request headers can be read using httpd_req_get_hdr_value_str() to know the 'Content-Type' (eg. Content-Type: application/x-www-form-urlencoded) and then the appropriate decoding algorithm needs to be applied. esp_err_t httpd_query_key_value(const char *qry, const char *key, char *val, size_t val_size) Helper function to get a URL query tag from a query string of the type param1=val1&param2=val2. Note The components of URL query string (keys and values) are not URLdecoded. The user must check for 'Content-Type' field in the request headers and then depending upon the specified encoding (URLencoded or otherwise) apply the appropriate decoding algorithm. If actual value size is greater than val_size, then the value is truncated, accompanied by truncation error as return value. The components of URL query string (keys and values) are not URLdecoded. The user must check for 'Content-Type' field in the request headers and then depending upon the specified encoding (URLencoded or otherwise) apply the appropriate decoding algorithm. If actual value size is greater than val_size, then the value is truncated, accompanied by truncation error as return value. Parameters qry -- [in] Pointer to query string key -- [in] The key to be searched in the query string val -- [out] Pointer to the buffer into which the value will be copied if the key is found val_size -- [in] Size of the user buffer "val" qry -- [in] Pointer to query string key -- [in] The key to be searched in the query string val -- [out] Pointer to the buffer into which the value will be copied if the key is found val_size -- [in] Size of the user buffer "val" qry -- [in] Pointer to query string Returns ESP_OK : Key is found in the URL query string and copied to buffer ESP_ERR_NOT_FOUND : Key not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated ESP_OK : Key is found in the URL query string and copied to buffer ESP_ERR_NOT_FOUND : Key not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated ESP_OK : Key is found in the URL query string and copied to buffer Parameters qry -- [in] Pointer to query string key -- [in] The key to be searched in the query string val -- [out] Pointer to the buffer into which the value will be copied if the key is found val_size -- [in] Size of the user buffer "val" Returns ESP_OK : Key is found in the URL query string and copied to buffer ESP_ERR_NOT_FOUND : Key not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated The components of URL query string (keys and values) are not URLdecoded. The user must check for 'Content-Type' field in the request headers and then depending upon the specified encoding (URLencoded or otherwise) apply the appropriate decoding algorithm. Get the value string of a cookie value from the "Cookie" request headers by cookie name. Parameters req -- [in] Pointer to the HTTP request cookie_name -- [in] The cookie name to be searched in the request val -- [out] Pointer to the buffer into which the value of cookie will be copied if the cookie is found val_size -- [inout] Pointer to size of the user buffer "val". This variable will contain cookie length if ESP_OK is returned and required buffer length incase ESP_ERR_HTTPD_RESULT_TRUNC is returned. req -- [in] Pointer to the HTTP request cookie_name -- [in] The cookie name to be searched in the request val -- [out] Pointer to the buffer into which the value of cookie will be copied if the cookie is found val_size -- [inout] Pointer to size of the user buffer "val". This variable will contain cookie length if ESP_OK is returned and required buffer length incase ESP_ERR_HTTPD_RESULT_TRUNC is returned. req -- [in] Pointer to the HTTP request Returns ESP_OK : Key is found in the cookie string and copied to buffer ESP_ERR_NOT_FOUND : Key not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated ESP_ERR_NO_MEM : Memory allocation failure ESP_OK : Key is found in the cookie string and copied to buffer ESP_ERR_NOT_FOUND : Key not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated ESP_ERR_NO_MEM : Memory allocation failure ESP_OK : Key is found in the cookie string and copied to buffer Parameters req -- [in] Pointer to the HTTP request cookie_name -- [in] The cookie name to be searched in the request val -- [out] Pointer to the buffer into which the value of cookie will be copied if the cookie is found val_size -- [inout] Pointer to size of the user buffer "val". This variable will contain cookie length if ESP_OK is returned and required buffer length incase ESP_ERR_HTTPD_RESULT_TRUNC is returned. Returns ESP_OK : Key is found in the cookie string and copied to buffer ESP_ERR_NOT_FOUND : Key not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated ESP_ERR_NO_MEM : Memory allocation failure bool httpd_uri_match_wildcard(const char *uri_template, const char *uri_to_match, size_t match_upto) Test if a URI matches the given wildcard template. Template may end with "?" to make the previous character optional (typically a slash), "*" for a wildcard match, and "?*" to make the previous character optional, and if present, allow anything to follow. Example: * matches everything /foo/? matches /foo and /foo/ /foo/* (sans the backslash) matches /foo/ and /foo/bar, but not /foo or /fo /foo/?* or /foo/*? (sans the backslash) matches /foo/, /foo/bar, and also /foo, but not /foox or /fo * matches everything /foo/? matches /foo and /foo/ /foo/* (sans the backslash) matches /foo/ and /foo/bar, but not /foo or /fo /foo/?* or /foo/*? (sans the backslash) matches /foo/, /foo/bar, and also /foo, but not /foox or /fo The special characters "?" and "*" anywhere else in the template will be taken literally. Parameters uri_template -- [in] URI template (pattern) uri_to_match -- [in] URI to be matched match_upto -- [in] how many characters of the URI buffer to test (there may be trailing query string etc.) uri_template -- [in] URI template (pattern) uri_to_match -- [in] URI to be matched match_upto -- [in] how many characters of the URI buffer to test (there may be trailing query string etc.) uri_template -- [in] URI template (pattern) Returns true if a match was found Parameters uri_template -- [in] URI template (pattern) uri_to_match -- [in] URI to be matched match_upto -- [in] how many characters of the URI buffer to test (there may be trailing query string etc.) Returns true if a match was found * matches everything esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, ssize_t buf_len) API to send a complete HTTP response. This API will send the data as an HTTP response to the request. This assumes that you have the entire response ready in a single buffer. If you wish to send response in incremental chunks use httpd_resp_send_chunk() instead. If no status code and content-type were set, by default this will send 200 OK status code and content type as text/html. You may call the following functions before this API to configure the response headers : httpd_resp_set_status() - for setting the HTTP status string, httpd_resp_set_type() - for setting the Content Type, httpd_resp_set_hdr() - for appending any additional field value entries in the response header Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once this API is called, the request has been responded to. No additional data can then be sent for the request. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once this API is called, the request has been responded to. No additional data can then be sent for the request. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. Parameters r -- [in] The request being responded to buf -- [in] Buffer from where the content is to be fetched buf_len -- [in] Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen() r -- [in] The request being responded to buf -- [in] Buffer from where the content is to be fetched buf_len -- [in] Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen() r -- [in] The request being responded to Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request ESP_OK : On successfully sending the response packet Parameters r -- [in] The request being responded to buf -- [in] Buffer from where the content is to be fetched buf_len -- [in] Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen() Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. esp_err_t httpd_resp_send_chunk(httpd_req_t *r, const char *buf, ssize_t buf_len) API to send one HTTP chunk. This API will send the data as an HTTP response to the request. This API will use chunked-encoding and send the response in the form of chunks. If you have the entire response contained in a single buffer, please use httpd_resp_send() instead. If no status code and content-type were set, by default this will send 200 OK status code and content type as text/html. You may call the following functions before this API to configure the response headers httpd_resp_set_status() - for setting the HTTP status string, httpd_resp_set_type() - for setting the Content Type, httpd_resp_set_hdr() - for appending any additional field value entries in the response header Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. When you are finished sending all your chunks, you must call this function with buf_len as 0. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. When you are finished sending all your chunks, you must call this function with buf_len as 0. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. Parameters r -- [in] The request being responded to buf -- [in] Pointer to a buffer that stores the data buf_len -- [in] Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen() r -- [in] The request being responded to buf -- [in] Pointer to a buffer that stores the data buf_len -- [in] Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen() r -- [in] The request being responded to Returns ESP_OK : On successfully sending the response packet chunk ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On successfully sending the response packet chunk ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On successfully sending the response packet chunk Parameters r -- [in] The request being responded to buf -- [in] Pointer to a buffer that stores the data buf_len -- [in] Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen() Returns ESP_OK : On successfully sending the response packet chunk ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. static inline esp_err_t httpd_resp_sendstr(httpd_req_t *r, const char *str) API to send a complete string as HTTP response. This API simply calls http_resp_send with buffer length set to string length assuming the buffer contains a null terminated string Parameters r -- [in] The request being responded to str -- [in] String to be sent as response body r -- [in] The request being responded to str -- [in] String to be sent as response body r -- [in] The request being responded to Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request ESP_OK : On successfully sending the response packet Parameters r -- [in] The request being responded to str -- [in] String to be sent as response body Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request static inline esp_err_t httpd_resp_sendstr_chunk(httpd_req_t *r, const char *str) API to send a string as an HTTP response chunk. This API simply calls http_resp_send_chunk with buffer length set to string length assuming the buffer contains a null terminated string Parameters r -- [in] The request being responded to str -- [in] String to be sent as response body (NULL to finish response packet) r -- [in] The request being responded to str -- [in] String to be sent as response body (NULL to finish response packet) r -- [in] The request being responded to Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request ESP_OK : On successfully sending the response packet Parameters r -- [in] The request being responded to str -- [in] String to be sent as response body (NULL to finish response packet) Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request esp_err_t httpd_resp_set_status(httpd_req_t *r, const char *status) API to set the HTTP status code. This API sets the status of the HTTP response to the value specified. By default, the '200 OK' response is sent as the response. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. This API only sets the status to this value. The status isn't sent out until any of the send APIs is executed. Make sure that the lifetime of the status string is valid till send function is called. This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. This API only sets the status to this value. The status isn't sent out until any of the send APIs is executed. Make sure that the lifetime of the status string is valid till send function is called. Parameters r -- [in] The request being responded to status -- [in] The HTTP status code of this response r -- [in] The request being responded to status -- [in] The HTTP status code of this response r -- [in] The request being responded to Returns ESP_OK : On success ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On success ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On success Parameters r -- [in] The request being responded to status -- [in] The HTTP status code of this response Returns ESP_OK : On success ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. esp_err_t httpd_resp_set_type(httpd_req_t *r, const char *type) API to set the HTTP content type. This API sets the 'Content Type' field of the response. The default content type is 'text/html'. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. This API only sets the content type to this value. The type isn't sent out until any of the send APIs is executed. Make sure that the lifetime of the type string is valid till send function is called. This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. This API only sets the content type to this value. The type isn't sent out until any of the send APIs is executed. Make sure that the lifetime of the type string is valid till send function is called. Parameters r -- [in] The request being responded to type -- [in] The Content Type of the response r -- [in] The request being responded to type -- [in] The Content Type of the response r -- [in] The request being responded to Returns ESP_OK : On success ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On success ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On success Parameters r -- [in] The request being responded to type -- [in] The Content Type of the response Returns ESP_OK : On success ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. esp_err_t httpd_resp_set_hdr(httpd_req_t *r, const char *field, const char *value) API to append any additional headers. This API sets any additional header fields that need to be sent in the response. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. The header isn't sent out until any of the send APIs is executed. The maximum allowed number of additional headers is limited to value of max_resp_headers in config structure. Make sure that the lifetime of the field value strings are valid till send function is called. This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. The header isn't sent out until any of the send APIs is executed. The maximum allowed number of additional headers is limited to value of max_resp_headers in config structure. Make sure that the lifetime of the field value strings are valid till send function is called. Parameters r -- [in] The request being responded to field -- [in] The field name of the HTTP header value -- [in] The value of this HTTP header r -- [in] The request being responded to field -- [in] The field name of the HTTP header value -- [in] The value of this HTTP header r -- [in] The request being responded to Returns ESP_OK : On successfully appending new header ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_HDR : Total additional headers exceed max allowed ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On successfully appending new header ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_HDR : Total additional headers exceed max allowed ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On successfully appending new header Parameters r -- [in] The request being responded to field -- [in] The field name of the HTTP header value -- [in] The value of this HTTP header Returns ESP_OK : On successfully appending new header ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_HDR : Total additional headers exceed max allowed ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. esp_err_t httpd_resp_send_err(httpd_req_t *req, httpd_err_code_t error, const char *msg) For sending out error code in response to HTTP request. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. If you wish to send additional data in the body of the response, please use the lower-level functions directly. This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. If you wish to send additional data in the body of the response, please use the lower-level functions directly. Parameters req -- [in] Pointer to the HTTP request for which the response needs to be sent error -- [in] Error type to send msg -- [in] Error message string (pass NULL for default message) req -- [in] Pointer to the HTTP request for which the response needs to be sent error -- [in] Error type to send msg -- [in] Error message string (pass NULL for default message) req -- [in] Pointer to the HTTP request for which the response needs to be sent Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On successfully sending the response packet Parameters req -- [in] Pointer to the HTTP request for which the response needs to be sent error -- [in] Error type to send msg -- [in] Error message string (pass NULL for default message) Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. static inline esp_err_t httpd_resp_send_404(httpd_req_t *r) Helper function for HTTP 404. Send HTTP 404 message. If you wish to send additional data in the body of the response, please use the lower-level functions directly. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. Parameters r -- [in] The request being responded to Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On successfully sending the response packet Parameters r -- [in] The request being responded to Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. static inline esp_err_t httpd_resp_send_408(httpd_req_t *r) Helper function for HTTP 408. Send HTTP 408 message. If you wish to send additional data in the body of the response, please use the lower-level functions directly. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. Parameters r -- [in] The request being responded to Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On successfully sending the response packet Parameters r -- [in] The request being responded to Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. static inline esp_err_t httpd_resp_send_500(httpd_req_t *r) Helper function for HTTP 500. Send HTTP 500 message. If you wish to send additional data in the body of the response, please use the lower-level functions directly. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. Parameters r -- [in] The request being responded to Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer ESP_OK : On successfully sending the response packet Parameters r -- [in] The request being responded to Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. int httpd_send(httpd_req_t *r, const char *buf, size_t buf_len) Raw HTTP send. Call this API if you wish to construct your custom response packet. When using this, all essential header, eg. HTTP version, Status Code, Content Type and Length, Encoding, etc. will have to be constructed manually, and HTTP delimeters (CRLF) will need to be placed correctly for separating sub-sections of the HTTP response packet. If the send override function is set, this API will end up calling that function eventually to send data out. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Unless the response has the correct HTTP structure (which the user must now ensure) it is not guaranteed that it will be recognized by the client. For most cases, you wouldn't have to call this API, but you would rather use either of : httpd_resp_send(), httpd_resp_send_chunk() This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Unless the response has the correct HTTP structure (which the user must now ensure) it is not guaranteed that it will be recognized by the client. For most cases, you wouldn't have to call this API, but you would rather use either of : httpd_resp_send(), httpd_resp_send_chunk() Parameters r -- [in] The request being responded to buf -- [in] Buffer from where the fully constructed packet is to be read buf_len -- [in] Length of the buffer r -- [in] The request being responded to buf -- [in] Buffer from where the fully constructed packet is to be read buf_len -- [in] Length of the buffer r -- [in] The request being responded to Returns Bytes : Number of bytes that were sent successfully HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() Bytes : Number of bytes that were sent successfully HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() Bytes : Number of bytes that were sent successfully Parameters r -- [in] The request being responded to buf -- [in] Buffer from where the fully constructed packet is to be read buf_len -- [in] Length of the buffer Returns Bytes : Number of bytes that were sent successfully HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. int httpd_socket_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags) A low level API to send data on a given socket This internally calls the default send function, or the function registered by httpd_sess_set_send_override(). Note This API is not recommended to be used in any request handler. Use this only for advanced use cases, wherein some asynchronous data is to be sent over a socket. Parameters hd -- [in] server instance sockfd -- [in] session socket file descriptor buf -- [in] buffer with bytes to send buf_len -- [in] data size flags -- [in] flags for the send() function hd -- [in] server instance sockfd -- [in] session socket file descriptor buf -- [in] buffer with bytes to send buf_len -- [in] data size flags -- [in] flags for the send() function hd -- [in] server instance Returns Bytes : The number of bytes sent successfully HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() Bytes : The number of bytes sent successfully HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() Bytes : The number of bytes sent successfully Parameters hd -- [in] server instance sockfd -- [in] session socket file descriptor buf -- [in] buffer with bytes to send buf_len -- [in] data size flags -- [in] flags for the send() function Returns Bytes : The number of bytes sent successfully HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() int httpd_socket_recv(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags) A low level API to receive data from a given socket This internally calls the default recv function, or the function registered by httpd_sess_set_recv_override(). Note This API is not recommended to be used in any request handler. Use this only for advanced use cases, wherein some asynchronous communication is required. Parameters hd -- [in] server instance sockfd -- [in] session socket file descriptor buf -- [in] buffer with bytes to send buf_len -- [in] data size flags -- [in] flags for the send() function hd -- [in] server instance sockfd -- [in] session socket file descriptor buf -- [in] buffer with bytes to send buf_len -- [in] data size flags -- [in] flags for the send() function hd -- [in] server instance Returns Bytes : The number of bytes received successfully 0 : Buffer length parameter is zero / connection closed by peer HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv() Bytes : The number of bytes received successfully 0 : Buffer length parameter is zero / connection closed by peer HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv() Bytes : The number of bytes received successfully Parameters hd -- [in] server instance sockfd -- [in] session socket file descriptor buf -- [in] buffer with bytes to send buf_len -- [in] data size flags -- [in] flags for the send() function Returns Bytes : The number of bytes received successfully 0 : Buffer length parameter is zero / connection closed by peer HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv() esp_err_t httpd_register_err_handler(httpd_handle_t handle, httpd_err_code_t error, httpd_err_handler_func_t handler_fn) Function for registering HTTP error handlers. This function maps a handler function to any supported error code given by httpd_err_code_t . See prototype httpd_err_handler_func_t above for details. Parameters handle -- [in] HTTP server handle error -- [in] Error type handler_fn -- [in] User implemented handler function (Pass NULL to unset any previously set handler) handle -- [in] HTTP server handle error -- [in] Error type handler_fn -- [in] User implemented handler function (Pass NULL to unset any previously set handler) handle -- [in] HTTP server handle Returns ESP_OK : handler registered successfully ESP_ERR_INVALID_ARG : invalid error code or server handle ESP_OK : handler registered successfully ESP_ERR_INVALID_ARG : invalid error code or server handle ESP_OK : handler registered successfully Parameters handle -- [in] HTTP server handle error -- [in] Error type handler_fn -- [in] User implemented handler function (Pass NULL to unset any previously set handler) Returns ESP_OK : handler registered successfully ESP_ERR_INVALID_ARG : invalid error code or server handle esp_err_t httpd_start(httpd_handle_t *handle, const httpd_config_t *config) Starts the web server. Create an instance of HTTP server and allocate memory/resources for it depending upon the specified configuration. Example usage: //Function for starting the webserver httpd_handle_t start_webserver(void) { // Generate default configuration httpd_config_t config = HTTPD_DEFAULT_CONFIG(); // Empty handle to http_server httpd_handle_t server = NULL; // Start the httpd server if (httpd_start(&server, &config) == ESP_OK) { // Register URI handlers httpd_register_uri_handler(server, &uri_get); httpd_register_uri_handler(server, &uri_post); } // If server failed to start, handle will be NULL return server; } Parameters config -- [in] Configuration for new instance of the server handle -- [out] Handle to newly created instance of the server. NULL on error config -- [in] Configuration for new instance of the server handle -- [out] Handle to newly created instance of the server. NULL on error config -- [in] Configuration for new instance of the server Returns ESP_OK : Instance created successfully ESP_ERR_INVALID_ARG : Null argument(s) ESP_ERR_HTTPD_ALLOC_MEM : Failed to allocate memory for instance ESP_ERR_HTTPD_TASK : Failed to launch server task ESP_OK : Instance created successfully ESP_ERR_INVALID_ARG : Null argument(s) ESP_ERR_HTTPD_ALLOC_MEM : Failed to allocate memory for instance ESP_ERR_HTTPD_TASK : Failed to launch server task ESP_OK : Instance created successfully Parameters config -- [in] Configuration for new instance of the server handle -- [out] Handle to newly created instance of the server. NULL on error Returns ESP_OK : Instance created successfully ESP_ERR_INVALID_ARG : Null argument(s) ESP_ERR_HTTPD_ALLOC_MEM : Failed to allocate memory for instance ESP_ERR_HTTPD_TASK : Failed to launch server task esp_err_t httpd_stop(httpd_handle_t handle) Stops the web server. Deallocates memory/resources used by an HTTP server instance and deletes it. Once deleted the handle can no longer be used for accessing the instance. Example usage: // Function for stopping the webserver void stop_webserver(httpd_handle_t server) { // Ensure handle is non NULL if (server != NULL) { // Stop the httpd server httpd_stop(server); } } Parameters handle -- [in] Handle to server returned by httpd_start Returns ESP_OK : Server stopped successfully ESP_ERR_INVALID_ARG : Handle argument is Null ESP_OK : Server stopped successfully ESP_ERR_INVALID_ARG : Handle argument is Null ESP_OK : Server stopped successfully Parameters handle -- [in] Handle to server returned by httpd_start Returns ESP_OK : Server stopped successfully ESP_ERR_INVALID_ARG : Handle argument is Null esp_err_t httpd_queue_work(httpd_handle_t handle, httpd_work_fn_t work, void *arg) Queue execution of a function in HTTPD's context. This API queues a work function for asynchronous execution Note Some protocols require that the web server generate some asynchronous data and send it to the persistently opened connection. This facility is for use by such protocols. Parameters handle -- [in] Handle to server returned by httpd_start work -- [in] Pointer to the function to be executed in the HTTPD's context arg -- [in] Pointer to the arguments that should be passed to this function handle -- [in] Handle to server returned by httpd_start work -- [in] Pointer to the function to be executed in the HTTPD's context arg -- [in] Pointer to the arguments that should be passed to this function handle -- [in] Handle to server returned by httpd_start Returns ESP_OK : On successfully queueing the work ESP_FAIL : Failure in ctrl socket ESP_ERR_INVALID_ARG : Null arguments ESP_OK : On successfully queueing the work ESP_FAIL : Failure in ctrl socket ESP_ERR_INVALID_ARG : Null arguments ESP_OK : On successfully queueing the work Parameters handle -- [in] Handle to server returned by httpd_start work -- [in] Pointer to the function to be executed in the HTTPD's context arg -- [in] Pointer to the arguments that should be passed to this function Returns ESP_OK : On successfully queueing the work ESP_FAIL : Failure in ctrl socket ESP_ERR_INVALID_ARG : Null arguments void *httpd_sess_get_ctx(httpd_handle_t handle, int sockfd) Get session context from socket descriptor. Typically if a session context is created, it is available to URI handlers through the httpd_req_t structure. But, there are cases where the web server's send/receive functions may require the context (for example, for accessing keying information etc). Since the send/receive function only have the socket descriptor at their disposal, this API provides them with a way to retrieve the session context. Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. handle -- [in] Handle to server returned by httpd_start Returns void* : Pointer to the context associated with this session NULL : Empty context / Invalid handle / Invalid socket fd void* : Pointer to the context associated with this session NULL : Empty context / Invalid handle / Invalid socket fd void* : Pointer to the context associated with this session Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. Returns void* : Pointer to the context associated with this session NULL : Empty context / Invalid handle / Invalid socket fd void httpd_sess_set_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn) Set session context by socket descriptor. Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. ctx -- [in] Context object to assign to the session free_fn -- [in] Function that should be called to free the context handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. ctx -- [in] Context object to assign to the session free_fn -- [in] Function that should be called to free the context handle -- [in] Handle to server returned by httpd_start Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. ctx -- [in] Context object to assign to the session free_fn -- [in] Function that should be called to free the context void *httpd_sess_get_transport_ctx(httpd_handle_t handle, int sockfd) Get session 'transport' context by socket descriptor. This context is used by the send/receive functions, for example to manage SSL context. See also httpd_sess_get_ctx() Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. handle -- [in] Handle to server returned by httpd_start Returns void* : Pointer to the transport context associated with this session NULL : Empty context / Invalid handle / Invalid socket fd void* : Pointer to the transport context associated with this session NULL : Empty context / Invalid handle / Invalid socket fd void* : Pointer to the transport context associated with this session Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. Returns void* : Pointer to the transport context associated with this session NULL : Empty context / Invalid handle / Invalid socket fd void httpd_sess_set_transport_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn) Set session 'transport' context by socket descriptor. See also httpd_sess_set_ctx() Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. ctx -- [in] Transport context object to assign to the session free_fn -- [in] Function that should be called to free the transport context handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. ctx -- [in] Transport context object to assign to the session free_fn -- [in] Function that should be called to free the transport context handle -- [in] Handle to server returned by httpd_start Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. ctx -- [in] Transport context object to assign to the session free_fn -- [in] Function that should be called to free the transport context void *httpd_get_global_user_ctx(httpd_handle_t handle) Get HTTPD global user context (it was set in the server config struct) Parameters handle -- [in] Handle to server returned by httpd_start Returns global user context Parameters handle -- [in] Handle to server returned by httpd_start Returns global user context void *httpd_get_global_transport_ctx(httpd_handle_t handle) Get HTTPD global transport context (it was set in the server config struct) Parameters handle -- [in] Handle to server returned by httpd_start Returns global transport context Parameters handle -- [in] Handle to server returned by httpd_start Returns global transport context esp_err_t httpd_sess_trigger_close(httpd_handle_t handle, int sockfd) Trigger an httpd session close externally. Note Calling this API is only required in special circumstances wherein some application requires to close an httpd client session asynchronously. Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor of the session to be closed handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor of the session to be closed handle -- [in] Handle to server returned by httpd_start Returns ESP_OK : On successfully initiating closure ESP_FAIL : Failure to queue work ESP_ERR_NOT_FOUND : Socket fd not found ESP_ERR_INVALID_ARG : Null arguments ESP_OK : On successfully initiating closure ESP_FAIL : Failure to queue work ESP_ERR_NOT_FOUND : Socket fd not found ESP_ERR_INVALID_ARG : Null arguments ESP_OK : On successfully initiating closure Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor of the session to be closed Returns ESP_OK : On successfully initiating closure ESP_FAIL : Failure to queue work ESP_ERR_NOT_FOUND : Socket fd not found ESP_ERR_INVALID_ARG : Null arguments esp_err_t httpd_sess_update_lru_counter(httpd_handle_t handle, int sockfd) Update LRU counter for a given socket. LRU Counters are internally associated with each session to monitor how recently a session exchanged traffic. When LRU purge is enabled, if a client is requesting for connection but maximum number of sockets/sessions is reached, then the session having the earliest LRU counter is closed automatically. Updating the LRU counter manually prevents the socket from being purged due to the Least Recently Used (LRU) logic, even though it might not have received traffic for some time. This is useful when all open sockets/session are frequently exchanging traffic but the user specifically wants one of the sessions to be kept open, irrespective of when it last exchanged a packet. Note Calling this API is only necessary if the LRU Purge Enable option is enabled. Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor of the session for which LRU counter is to be updated handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor of the session for which LRU counter is to be updated handle -- [in] Handle to server returned by httpd_start Returns ESP_OK : Socket found and LRU counter updated ESP_ERR_NOT_FOUND : Socket not found ESP_ERR_INVALID_ARG : Null arguments ESP_OK : Socket found and LRU counter updated ESP_ERR_NOT_FOUND : Socket not found ESP_ERR_INVALID_ARG : Null arguments ESP_OK : Socket found and LRU counter updated Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor of the session for which LRU counter is to be updated Returns ESP_OK : Socket found and LRU counter updated ESP_ERR_NOT_FOUND : Socket not found ESP_ERR_INVALID_ARG : Null arguments esp_err_t httpd_get_client_list(httpd_handle_t handle, size_t *fds, int *client_fds) Returns list of current socket descriptors of active sessions. Note Size of provided array has to be equal or greater then maximum number of opened sockets, configured upon initialization with max_open_sockets field in httpd_config_t structure. Parameters handle -- [in] Handle to server returned by httpd_start fds -- [inout] In: Size of provided client_fds array Out: Number of valid client fds returned in client_fds, client_fds -- [out] Array of client fds handle -- [in] Handle to server returned by httpd_start fds -- [inout] In: Size of provided client_fds array Out: Number of valid client fds returned in client_fds, client_fds -- [out] Array of client fds handle -- [in] Handle to server returned by httpd_start Returns ESP_OK : Successfully retrieved session list ESP_ERR_INVALID_ARG : Wrong arguments or list is longer than provided array ESP_OK : Successfully retrieved session list ESP_ERR_INVALID_ARG : Wrong arguments or list is longer than provided array ESP_OK : Successfully retrieved session list Parameters handle -- [in] Handle to server returned by httpd_start fds -- [inout] In: Size of provided client_fds array Out: Number of valid client fds returned in client_fds, client_fds -- [out] Array of client fds Returns ESP_OK : Successfully retrieved session list ESP_ERR_INVALID_ARG : Wrong arguments or list is longer than provided array Structures struct esp_http_server_event_data Argument structure for HTTP_SERVER_EVENT_ON_DATA and HTTP_SERVER_EVENT_SENT_DATA event struct httpd_config HTTP Server Configuration Structure. Note Use HTTPD_DEFAULT_CONFIG() to initialize the configuration to a default value and then modify only those fields that are specifically determined by the use case. Public Members unsigned task_priority Priority of FreeRTOS task which runs the server unsigned task_priority Priority of FreeRTOS task which runs the server size_t stack_size The maximum stack size allowed for the server task size_t stack_size The maximum stack size allowed for the server task BaseType_t core_id The core the HTTP server task will run on BaseType_t core_id The core the HTTP server task will run on uint16_t server_port TCP Port number for receiving and transmitting HTTP traffic uint16_t server_port TCP Port number for receiving and transmitting HTTP traffic uint16_t ctrl_port UDP Port number for asynchronously exchanging control signals between various components of the server uint16_t ctrl_port UDP Port number for asynchronously exchanging control signals between various components of the server uint16_t max_open_sockets Max number of sockets/clients connected at any time (3 sockets are reserved for internal working of the HTTP server) uint16_t max_open_sockets Max number of sockets/clients connected at any time (3 sockets are reserved for internal working of the HTTP server) uint16_t max_uri_handlers Maximum allowed uri handlers uint16_t max_uri_handlers Maximum allowed uri handlers uint16_t max_resp_headers Maximum allowed additional headers in HTTP response uint16_t max_resp_headers Maximum allowed additional headers in HTTP response uint16_t backlog_conn Number of backlog connections uint16_t backlog_conn Number of backlog connections bool lru_purge_enable Purge "Least Recently Used" connection bool lru_purge_enable Purge "Least Recently Used" connection uint16_t recv_wait_timeout Timeout for recv function (in seconds) uint16_t recv_wait_timeout Timeout for recv function (in seconds) uint16_t send_wait_timeout Timeout for send function (in seconds) uint16_t send_wait_timeout Timeout for send function (in seconds) void *global_user_ctx Global user context. This field can be used to store arbitrary user data within the server context. The value can be retrieved using the server handle, available e.g. in the httpd_req_t struct. When shutting down, the server frees up the user context by calling free() on the global_user_ctx field. If you wish to use a custom function for freeing the global user context, please specify that here. void *global_user_ctx Global user context. This field can be used to store arbitrary user data within the server context. The value can be retrieved using the server handle, available e.g. in the httpd_req_t struct. When shutting down, the server frees up the user context by calling free() on the global_user_ctx field. If you wish to use a custom function for freeing the global user context, please specify that here. httpd_free_ctx_fn_t global_user_ctx_free_fn Free function for global user context httpd_free_ctx_fn_t global_user_ctx_free_fn Free function for global user context void *global_transport_ctx Global transport context. Similar to global_user_ctx, but used for session encoding or encryption (e.g. to hold the SSL context). It will be freed using free(), unless global_transport_ctx_free_fn is specified. void *global_transport_ctx Global transport context. Similar to global_user_ctx, but used for session encoding or encryption (e.g. to hold the SSL context). It will be freed using free(), unless global_transport_ctx_free_fn is specified. httpd_free_ctx_fn_t global_transport_ctx_free_fn Free function for global transport context httpd_free_ctx_fn_t global_transport_ctx_free_fn Free function for global transport context bool enable_so_linger bool to enable/disable linger bool enable_so_linger bool to enable/disable linger int linger_timeout linger timeout (in seconds) int linger_timeout linger timeout (in seconds) bool keep_alive_enable Enable keep-alive timeout bool keep_alive_enable Enable keep-alive timeout int keep_alive_idle Keep-alive idle time. Default is 5 (second) int keep_alive_idle Keep-alive idle time. Default is 5 (second) int keep_alive_interval Keep-alive interval time. Default is 5 (second) int keep_alive_interval Keep-alive interval time. Default is 5 (second) int keep_alive_count Keep-alive packet retry send count. Default is 3 counts int keep_alive_count Keep-alive packet retry send count. Default is 3 counts httpd_open_func_t open_fn Custom session opening callback. Called on a new session socket just after accept(), but before reading any data. This is an opportunity to set up e.g. SSL encryption using global_transport_ctx and the send/recv/pending session overrides. If a context needs to be maintained between these functions, store it in the session using httpd_sess_set_transport_ctx() and retrieve it later with httpd_sess_get_transport_ctx() Returning a value other than ESP_OK will immediately close the new socket. httpd_open_func_t open_fn Custom session opening callback. Called on a new session socket just after accept(), but before reading any data. This is an opportunity to set up e.g. SSL encryption using global_transport_ctx and the send/recv/pending session overrides. If a context needs to be maintained between these functions, store it in the session using httpd_sess_set_transport_ctx() and retrieve it later with httpd_sess_get_transport_ctx() Returning a value other than ESP_OK will immediately close the new socket. httpd_close_func_t close_fn Custom session closing callback. Called when a session is deleted, before freeing user and transport contexts and before closing the socket. This is a place for custom de-init code common to all sockets. The server will only close the socket if no custom session closing callback is set. If a custom callback is used, close(sockfd) should be called in here for most cases. Set the user or transport context to NULL if it was freed here, so the server does not try to free it again. This function is run for all terminated sessions, including sessions where the socket was closed by the network stack - that is, the file descriptor may not be valid anymore. httpd_close_func_t close_fn Custom session closing callback. Called when a session is deleted, before freeing user and transport contexts and before closing the socket. This is a place for custom de-init code common to all sockets. The server will only close the socket if no custom session closing callback is set. If a custom callback is used, close(sockfd) should be called in here for most cases. Set the user or transport context to NULL if it was freed here, so the server does not try to free it again. This function is run for all terminated sessions, including sessions where the socket was closed by the network stack - that is, the file descriptor may not be valid anymore. httpd_uri_match_func_t uri_match_fn URI matcher function. Called when searching for a matching URI: 1) whose request handler is to be executed right after an HTTP request is successfully parsed 2) in order to prevent duplication while registering a new URI handler using httpd_register_uri_handler() Available options are: 1) NULL : Internally do basic matching using strncmp() 2) httpd_uri_match_wildcard() : URI wildcard matcher Users can implement their own matching functions (See description of the httpd_uri_match_func_t function prototype) httpd_uri_match_func_t uri_match_fn URI matcher function. Called when searching for a matching URI: 1) whose request handler is to be executed right after an HTTP request is successfully parsed 2) in order to prevent duplication while registering a new URI handler using httpd_register_uri_handler() Available options are: 1) NULL : Internally do basic matching using strncmp() 2) httpd_uri_match_wildcard() : URI wildcard matcher Users can implement their own matching functions (See description of the httpd_uri_match_func_t function prototype) unsigned task_priority struct httpd_req HTTP Request Data Structure. Public Members httpd_handle_t handle Handle to server instance httpd_handle_t handle Handle to server instance int method The type of HTTP request, -1 if unsupported method int method The type of HTTP request, -1 if unsupported method const char uri[HTTPD_MAX_URI_LEN + 1] The URI of this request (1 byte extra for null termination) const char uri[HTTPD_MAX_URI_LEN + 1] The URI of this request (1 byte extra for null termination) size_t content_len Length of the request body size_t content_len Length of the request body void *aux Internally used members void *aux Internally used members void *user_ctx User context pointer passed during URI registration. void *user_ctx User context pointer passed during URI registration. void *sess_ctx Session Context Pointer A session context. Contexts are maintained across 'sessions' for a given open TCP connection. One session could have multiple request responses. The web server will ensure that the context persists across all these request and responses. By default, this is NULL. URI Handlers can set this to any meaningful value. If the underlying socket gets closed, and this pointer is non-NULL, the web server will free up the context by calling free(), unless free_ctx function is set. void *sess_ctx Session Context Pointer A session context. Contexts are maintained across 'sessions' for a given open TCP connection. One session could have multiple request responses. The web server will ensure that the context persists across all these request and responses. By default, this is NULL. URI Handlers can set this to any meaningful value. If the underlying socket gets closed, and this pointer is non-NULL, the web server will free up the context by calling free(), unless free_ctx function is set. httpd_free_ctx_fn_t free_ctx Pointer to free context hook Function to free session context If the web server's socket closes, it frees up the session context by calling free() on the sess_ctx member. If you wish to use a custom function for freeing the session context, please specify that here. httpd_free_ctx_fn_t free_ctx Pointer to free context hook Function to free session context If the web server's socket closes, it frees up the session context by calling free() on the sess_ctx member. If you wish to use a custom function for freeing the session context, please specify that here. bool ignore_sess_ctx_changes Flag indicating if Session Context changes should be ignored By default, if you change the sess_ctx in some URI handler, the http server will internally free the earlier context (if non NULL), after the URI handler returns. If you want to manage the allocation/reallocation/freeing of sess_ctx yourself, set this flag to true, so that the server will not perform any checks on it. The context will be cleared by the server (by calling free_ctx or free()) only if the socket gets closed. bool ignore_sess_ctx_changes Flag indicating if Session Context changes should be ignored By default, if you change the sess_ctx in some URI handler, the http server will internally free the earlier context (if non NULL), after the URI handler returns. If you want to manage the allocation/reallocation/freeing of sess_ctx yourself, set this flag to true, so that the server will not perform any checks on it. The context will be cleared by the server (by calling free_ctx or free()) only if the socket gets closed. httpd_handle_t handle struct httpd_uri Structure for URI handler. Public Members const char *uri The URI to handle const char *uri The URI to handle httpd_method_t method Method supported by the URI httpd_method_t method Method supported by the URI esp_err_t (*handler)(httpd_req_t *r) Handler to call for supported request method. This must return ESP_OK, or else the underlying socket will be closed. esp_err_t (*handler)(httpd_req_t *r) Handler to call for supported request method. This must return ESP_OK, or else the underlying socket will be closed. void *user_ctx Pointer to user context data which will be available to handler void *user_ctx Pointer to user context data which will be available to handler const char *uri Macros HTTPD_MAX_REQ_HDR_LEN HTTPD_MAX_URI_LEN HTTPD_SOCK_ERR_FAIL HTTPD_SOCK_ERR_INVALID HTTPD_SOCK_ERR_TIMEOUT HTTPD_200 HTTP Response 200 HTTPD_204 HTTP Response 204 HTTPD_207 HTTP Response 207 HTTPD_400 HTTP Response 400 HTTPD_404 HTTP Response 404 HTTPD_408 HTTP Response 408 HTTPD_500 HTTP Response 500 HTTPD_TYPE_JSON HTTP Content type JSON HTTPD_TYPE_TEXT HTTP Content type text/HTML HTTPD_TYPE_OCTET HTTP Content type octext-stream ESP_HTTPD_DEF_CTRL_PORT HTTP Server control socket port HTTPD_DEFAULT_CONFIG() ESP_ERR_HTTPD_BASE Starting number of HTTPD error codes ESP_ERR_HTTPD_HANDLERS_FULL All slots for registering URI handlers have been consumed ESP_ERR_HTTPD_HANDLER_EXISTS URI handler with same method and target URI already registered ESP_ERR_HTTPD_INVALID_REQ Invalid request pointer ESP_ERR_HTTPD_RESULT_TRUNC Result string truncated ESP_ERR_HTTPD_RESP_HDR Response header field larger than supported ESP_ERR_HTTPD_RESP_SEND Error occured while sending response packet ESP_ERR_HTTPD_ALLOC_MEM Failed to dynamically allocate memory for resource ESP_ERR_HTTPD_TASK Failed to launch server task/thread HTTPD_RESP_USE_STRLEN Type Definitions typedef int (*httpd_send_func_t)(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags) Prototype for HTTPDs low-level send function. Note User specified send function must handle errors internally, depending upon the set value of errno, and return specific HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as return value of httpd_send() function Param hd [in] server instance Param sockfd [in] session socket file descriptor Param buf [in] buffer with bytes to send Param buf_len [in] data size Param flags [in] flags for the send() function Return Bytes : The number of bytes sent successfully HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() Bytes : The number of bytes sent successfully HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() Bytes : The number of bytes sent successfully Param hd [in] server instance Param sockfd [in] session socket file descriptor Param buf [in] buffer with bytes to send Param buf_len [in] data size Param flags [in] flags for the send() function Return Bytes : The number of bytes sent successfully HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() typedef int (*httpd_recv_func_t)(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags) Prototype for HTTPDs low-level recv function. Note User specified recv function must handle errors internally, depending upon the set value of errno, and return specific HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as return value of httpd_req_recv() function Param hd [in] server instance Param sockfd [in] session socket file descriptor Param buf [in] buffer with bytes to send Param buf_len [in] data size Param flags [in] flags for the send() function Return Bytes : The number of bytes received successfully 0 : Buffer length parameter is zero / connection closed by peer HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv() Bytes : The number of bytes received successfully 0 : Buffer length parameter is zero / connection closed by peer HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv() Bytes : The number of bytes received successfully Param hd [in] server instance Param sockfd [in] session socket file descriptor Param buf [in] buffer with bytes to send Param buf_len [in] data size Param flags [in] flags for the send() function Return Bytes : The number of bytes received successfully 0 : Buffer length parameter is zero / connection closed by peer HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv() typedef int (*httpd_pending_func_t)(httpd_handle_t hd, int sockfd) Prototype for HTTPDs low-level "get pending bytes" function. Note User specified pending function must handle errors internally, depending upon the set value of errno, and return specific HTTPD_SOCK_ERR_ codes, which will be handled accordingly in the server task. Param hd [in] server instance Param sockfd [in] session socket file descriptor Return Bytes : The number of bytes waiting to be received HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket pending() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket pending() Bytes : The number of bytes waiting to be received HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket pending() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket pending() Bytes : The number of bytes waiting to be received Param hd [in] server instance Param sockfd [in] session socket file descriptor Return Bytes : The number of bytes waiting to be received HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket pending() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket pending() typedef esp_err_t (*httpd_err_handler_func_t)(httpd_req_t *req, httpd_err_code_t error) Function prototype for HTTP error handling. This function is executed upon HTTP errors generated during internal processing of an HTTP request. This is used to override the default behavior on error, which is to send HTTP error response and close the underlying socket. Note If implemented, the server will not automatically send out HTTP error response codes, therefore, httpd_resp_send_err() must be invoked inside this function if user wishes to generate HTTP error responses. When invoked, the validity of uri , method , content_len and user_ctx fields of the httpd_req_t parameter is not guaranteed as the HTTP request may be partially received/parsed. The function must return ESP_OK if underlying socket needs to be kept open. Any other value will ensure that the socket is closed. The return value is ignored when error is of type HTTPD_500_INTERNAL_SERVER_ERROR and the socket closed anyway. If implemented, the server will not automatically send out HTTP error response codes, therefore, httpd_resp_send_err() must be invoked inside this function if user wishes to generate HTTP error responses. When invoked, the validity of uri , method , content_len and user_ctx fields of the httpd_req_t parameter is not guaranteed as the HTTP request may be partially received/parsed. The function must return ESP_OK if underlying socket needs to be kept open. Any other value will ensure that the socket is closed. The return value is ignored when error is of type HTTPD_500_INTERNAL_SERVER_ERROR and the socket closed anyway. Param req [in] HTTP request for which the error needs to be handled Param error [in] Error type Return ESP_OK : error handled successful ESP_FAIL : failure indicates that the underlying socket needs to be closed ESP_OK : error handled successful ESP_FAIL : failure indicates that the underlying socket needs to be closed ESP_OK : error handled successful Param req [in] HTTP request for which the error needs to be handled Param error [in] Error type Return ESP_OK : error handled successful ESP_FAIL : failure indicates that the underlying socket needs to be closed If implemented, the server will not automatically send out HTTP error response codes, therefore, httpd_resp_send_err() must be invoked inside this function if user wishes to generate HTTP error responses. typedef void *httpd_handle_t HTTP Server Instance Handle. Every instance of the server will have a unique handle. typedef enum http_method httpd_method_t HTTP Method Type wrapper over "enum http_method" available in "http_parser" library. typedef void (*httpd_free_ctx_fn_t)(void *ctx) Prototype for freeing context data (if any) Param ctx [in] object to free Param ctx [in] object to free typedef esp_err_t (*httpd_open_func_t)(httpd_handle_t hd, int sockfd) Function prototype for opening a session. Called immediately after the socket was opened to set up the send/recv functions and other parameters of the socket. Param hd [in] server instance Param sockfd [in] session socket file descriptor Return ESP_OK : On success Any value other than ESP_OK will signal the server to close the socket immediately ESP_OK : On success Any value other than ESP_OK will signal the server to close the socket immediately ESP_OK : On success Param hd [in] server instance Param sockfd [in] session socket file descriptor Return ESP_OK : On success Any value other than ESP_OK will signal the server to close the socket immediately typedef void (*httpd_close_func_t)(httpd_handle_t hd, int sockfd) Function prototype for closing a session. Note It's possible that the socket descriptor is invalid at this point, the function is called for all terminated sessions. Ensure proper handling of return codes. Param hd [in] server instance Param sockfd [in] session socket file descriptor Param hd [in] server instance Param sockfd [in] session socket file descriptor typedef bool (*httpd_uri_match_func_t)(const char *reference_uri, const char *uri_to_match, size_t match_upto) Function prototype for URI matching. Param reference_uri [in] URI/template with respect to which the other URI is matched Param uri_to_match [in] URI/template being matched to the reference URI/template Param match_upto [in] For specifying the actual length of uri_to_match up to which the matching algorithm is to be applied (The maximum value is strlen(uri_to_match) , independent of the length of reference_uri ) Return true on match Param reference_uri [in] URI/template with respect to which the other URI is matched Param uri_to_match [in] URI/template being matched to the reference URI/template Param match_upto [in] For specifying the actual length of uri_to_match up to which the matching algorithm is to be applied (The maximum value is strlen(uri_to_match) , independent of the length of reference_uri ) Return true on match typedef struct httpd_config httpd_config_t HTTP Server Configuration Structure. Note Use HTTPD_DEFAULT_CONFIG() to initialize the configuration to a default value and then modify only those fields that are specifically determined by the use case. typedef void (*httpd_work_fn_t)(void *arg) Prototype of the HTTPD work function Please refer to httpd_queue_work() for more details. Param arg [in] The arguments for this work function Param arg [in] The arguments for this work function Enumerations enum httpd_err_code_t Error codes sent as HTTP response in case of errors encountered during processing of an HTTP request. Values: enumerator HTTPD_500_INTERNAL_SERVER_ERROR enumerator HTTPD_500_INTERNAL_SERVER_ERROR enumerator HTTPD_501_METHOD_NOT_IMPLEMENTED enumerator HTTPD_501_METHOD_NOT_IMPLEMENTED enumerator HTTPD_505_VERSION_NOT_SUPPORTED enumerator HTTPD_505_VERSION_NOT_SUPPORTED enumerator HTTPD_400_BAD_REQUEST enumerator HTTPD_400_BAD_REQUEST enumerator HTTPD_401_UNAUTHORIZED enumerator HTTPD_401_UNAUTHORIZED enumerator HTTPD_403_FORBIDDEN enumerator HTTPD_403_FORBIDDEN enumerator HTTPD_404_NOT_FOUND enumerator HTTPD_404_NOT_FOUND enumerator HTTPD_405_METHOD_NOT_ALLOWED enumerator HTTPD_405_METHOD_NOT_ALLOWED enumerator HTTPD_408_REQ_TIMEOUT enumerator HTTPD_408_REQ_TIMEOUT enumerator HTTPD_411_LENGTH_REQUIRED enumerator HTTPD_411_LENGTH_REQUIRED enumerator HTTPD_414_URI_TOO_LONG enumerator HTTPD_414_URI_TOO_LONG enumerator HTTPD_431_REQ_HDR_FIELDS_TOO_LARGE enumerator HTTPD_431_REQ_HDR_FIELDS_TOO_LARGE enumerator HTTPD_ERR_CODE_MAX enumerator HTTPD_ERR_CODE_MAX enumerator HTTPD_500_INTERNAL_SERVER_ERROR enum esp_http_server_event_id_t HTTP Server events id. Values: enumerator HTTP_SERVER_EVENT_ERROR This event occurs when there are any errors during execution enumerator HTTP_SERVER_EVENT_ERROR This event occurs when there are any errors during execution enumerator HTTP_SERVER_EVENT_START This event occurs when HTTP Server is started enumerator HTTP_SERVER_EVENT_START This event occurs when HTTP Server is started enumerator HTTP_SERVER_EVENT_ON_CONNECTED Once the HTTP Server has been connected to the client, no data exchange has been performed enumerator HTTP_SERVER_EVENT_ON_CONNECTED Once the HTTP Server has been connected to the client, no data exchange has been performed enumerator HTTP_SERVER_EVENT_ON_HEADER Occurs when receiving each header sent from the client enumerator HTTP_SERVER_EVENT_ON_HEADER Occurs when receiving each header sent from the client enumerator HTTP_SERVER_EVENT_HEADERS_SENT After sending all the headers to the client enumerator HTTP_SERVER_EVENT_HEADERS_SENT After sending all the headers to the client enumerator HTTP_SERVER_EVENT_ON_DATA Occurs when receiving data from the client enumerator HTTP_SERVER_EVENT_ON_DATA Occurs when receiving data from the client enumerator HTTP_SERVER_EVENT_SENT_DATA Occurs when an ESP HTTP server session is finished enumerator HTTP_SERVER_EVENT_SENT_DATA Occurs when an ESP HTTP server session is finished enumerator HTTP_SERVER_EVENT_DISCONNECTED The connection has been disconnected enumerator HTTP_SERVER_EVENT_DISCONNECTED The connection has been disconnected enumerator HTTP_SERVER_EVENT_STOP This event occurs when HTTP Server is stopped enumerator HTTP_SERVER_EVENT_STOP This event occurs when HTTP Server is stopped enumerator HTTP_SERVER_EVENT_ERROR
HTTP Server Overview The HTTP Server component provides an ability for running a lightweight web server on ESP32. Following are detailed steps to use the API exposed by HTTP Server: - httpd_start(): Creates an instance of HTTP server, allocate memory/resources for it depending upon the specified configuration and outputs a handle to the server instance. The server has both, a listening socket (TCP) for HTTP traffic, and a control socket (UDP) for control signals, which are selected in a round robin fashion in the server task loop. The task priority and stack size are configurable during server instance creation by passing httpd_config_tstructure to httpd_start(). TCP traffic is parsed as HTTP requests and, depending on the requested URI, user registered handlers are invoked which are supposed to send back HTTP response packets. - httpd_stop(): This stops the server with the provided handle and frees up any associated memory/resources. This is a blocking function that first signals a halt to the server task and then waits for the task to terminate. While stopping, the task closes all open connections, removes registered URI handlers and resets all session context data to empty. - httpd_register_uri_handler(): A URI handler is registered by passing object of type httpd_uri_tstructure which has members including uriname, methodtype (eg. HTTPD_GET/HTTPD_POST/HTTPD_PUTetc.), function pointer of type esp_err_t *handler (httpd_req_t *req)and user_ctxpointer to user context data. Application Example /* Our URI handler function to be called during GET /uri request */ esp_err_t get_handler(httpd_req_t *req) { /* Send a simple response */ const char resp[] = "URI GET Response"; httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN); return ESP_OK; } /* Our URI handler function to be called during POST /uri request */ esp_err_t post_handler(httpd_req_t *req) { /* Destination buffer for content of HTTP POST request. * httpd_req_recv() accepts char* only, but content could * as well be any binary data (needs type casting). * In case of string data, null termination will be absent, and * content length would give length of string */ char content[100]; /* Truncate if content length larger than the buffer */ size_t recv_size = MIN(req->content_len, sizeof(content)); int ret = httpd_req_recv(req, content, recv_size); if (ret <= 0) { /* 0 return value indicates connection closed */ /* Check if timeout occurred */ if (ret == HTTPD_SOCK_ERR_TIMEOUT) { /* In case of timeout one can choose to retry calling * httpd_req_recv(), but to keep it simple, here we * respond with an HTTP 408 (Request Timeout) error */ httpd_resp_send_408(req); } /* In case of error, returning ESP_FAIL will * ensure that the underlying socket is closed */ return ESP_FAIL; } /* Send a simple response */ const char resp[] = "URI POST Response"; httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN); return ESP_OK; } /* URI handler structure for GET /uri */ httpd_uri_t uri_get = { .uri = "/uri", .method = HTTP_GET, .handler = get_handler, .user_ctx = NULL }; /* URI handler structure for POST /uri */ httpd_uri_t uri_post = { .uri = "/uri", .method = HTTP_POST, .handler = post_handler, .user_ctx = NULL }; /* Function for starting the webserver */ httpd_handle_t start_webserver(void) { /* Generate default configuration */ httpd_config_t config = HTTPD_DEFAULT_CONFIG(); /* Empty handle to esp_http_server */ httpd_handle_t server = NULL; /* Start the httpd server */ if (httpd_start(&server, &config) == ESP_OK) { /* Register URI handlers */ httpd_register_uri_handler(server, &uri_get); httpd_register_uri_handler(server, &uri_post); } /* If server failed to start, handle will be NULL */ return server; } /* Function for stopping the webserver */ void stop_webserver(httpd_handle_t server) { if (server) { /* Stop the httpd server */ httpd_stop(server); } } Simple HTTP Server Example Check HTTP server example under protocols/http_server/simple where handling of arbitrary content lengths, reading request headers and URL query parameters, and setting response headers is demonstrated. Persistent Connections HTTP server features persistent connections, allowing for the re-use of the same connection (session) for several transfers, all the while maintaining context specific data for the session. Context data may be allocated dynamically by the handler in which case a custom function may need to be specified for freeing this data when the connection/session is closed. Persistent Connections Example /* Custom function to free context */ void free_ctx_func(void *ctx) { /* Could be something other than free */ free(ctx); } esp_err_t adder_post_handler(httpd_req_t *req) { /* Create session's context if not already available */ if (! req->sess_ctx) { req->sess_ctx = malloc(sizeof(ANY_DATA_TYPE)); /*!< Pointer to context data */ req->free_ctx = free_ctx_func; /*!< Function to free context data */ } /* Access context data */ ANY_DATA_TYPE *ctx_data = (ANY_DATA_TYPE *)req->sess_ctx; /* Respond */ ............... ............... ............... return ESP_OK; } Check the example under protocols/http_server/persistent_sockets. Websocket Server The HTTP server component provides websocket support. The websocket feature can be enabled in menuconfig using the CONFIG_HTTPD_WS_SUPPORT option. Please refer to the protocols/http_server/ws_echo_server example which demonstrates usage of the websocket feature. Event Handling ESP HTTP server has various events for which a handler can be triggered by the Event Loop library when the particular event occurs. The handler has to be registered using esp_event_handler_register(). This helps in event handling for ESP HTTP server. esp_http_server_event_id_t has all the events which can happen for ESP HTTP server. Expected data type for different ESP HTTP server events in event loop: - HTTP_SERVER_EVENT_ERROR : httpd_err_code_t - HTTP_SERVER_EVENT_START : NULL - HTTP_SERVER_EVENT_ON_CONNECTED : int - HTTP_SERVER_EVENT_ON_HEADER : int - HTTP_SERVER_EVENT_HEADERS_SENT : int - HTTP_SERVER_EVENT_ON_DATA : esp_http_server_event_data - HTTP_SERVER_EVENT_SENT_DATA : esp_http_server_event_data - HTTP_SERVER_EVENT_DISCONNECTED : int - HTTP_SERVER_EVENT_STOP : NULL API Reference Header File This header file can be included with: #include "esp_http_server.h" This header file is a part of the API provided by the esp_http_servercomponent. To declare that your component depends on esp_http_server, add the following to your CMakeLists.txt: REQUIRES esp_http_server or PRIV_REQUIRES esp_http_server Functions - esp_err_t httpd_register_uri_handler(httpd_handle_t handle, const httpd_uri_t *uri_handler) Registers a URI handler. Example usage: esp_err_t my_uri_handler(httpd_req_t* req) { // Recv , Process and Send .... .... .... // Fail condition if (....) { // Return fail to close session // return ESP_FAIL; } // On success return ESP_OK; } // URI handler structure httpd_uri_t my_uri { .uri = "/my_uri/path/xyz", .method = HTTPD_GET, .handler = my_uri_handler, .user_ctx = NULL }; // Register handler if (httpd_register_uri_handler(server_handle, &my_uri) != ESP_OK) { // If failed to register handler .... } Note URI handlers can be registered in real time as long as the server handle is valid. - Parameters handle -- [in] handle to HTTPD server instance uri_handler -- [in] pointer to handler that needs to be registered - - Returns ESP_OK : On successfully registering the handler ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_HANDLERS_FULL : If no slots left for new handler ESP_ERR_HTTPD_HANDLER_EXISTS : If handler with same URI and method is already registered - - esp_err_t httpd_unregister_uri_handler(httpd_handle_t handle, const char *uri, httpd_method_t method) Unregister a URI handler. - Parameters handle -- [in] handle to HTTPD server instance uri -- [in] URI string method -- [in] HTTP method - - Returns ESP_OK : On successfully deregistering the handler ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_NOT_FOUND : Handler with specified URI and method not found - - esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char *uri) Unregister all URI handlers with the specified uri string. - Parameters handle -- [in] handle to HTTPD server instance uri -- [in] uri string specifying all handlers that need to be deregisterd - - Returns ESP_OK : On successfully deregistering all such handlers ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_NOT_FOUND : No handler registered with specified uri string - - esp_err_t httpd_sess_set_recv_override(httpd_handle_t hd, int sockfd, httpd_recv_func_t recv_func) Override web server's receive function (by session FD) This function overrides the web server's receive function. This same function is used to read HTTP request packets. Note This API is supposed to be called either from the context of an http session APIs where sockfd is a valid parameter a URI handler where sockfd is obtained using httpd_req_to_sockfd() - Parameters hd -- [in] HTTPD instance handle sockfd -- [in] Session socket FD recv_func -- [in] The receive function to be set for this session - - Returns ESP_OK : On successfully registering override ESP_ERR_INVALID_ARG : Null arguments - - - esp_err_t httpd_sess_set_send_override(httpd_handle_t hd, int sockfd, httpd_send_func_t send_func) Override web server's send function (by session FD) This function overrides the web server's send function. This same function is used to send out any response to any HTTP request. Note This API is supposed to be called either from the context of an http session APIs where sockfd is a valid parameter a URI handler where sockfd is obtained using httpd_req_to_sockfd() - Parameters hd -- [in] HTTPD instance handle sockfd -- [in] Session socket FD send_func -- [in] The send function to be set for this session - - Returns ESP_OK : On successfully registering override ESP_ERR_INVALID_ARG : Null arguments - - - esp_err_t httpd_sess_set_pending_override(httpd_handle_t hd, int sockfd, httpd_pending_func_t pending_func) Override web server's pending function (by session FD) This function overrides the web server's pending function. This function is used to test for pending bytes in a socket. Note This API is supposed to be called either from the context of an http session APIs where sockfd is a valid parameter a URI handler where sockfd is obtained using httpd_req_to_sockfd() - Parameters hd -- [in] HTTPD instance handle sockfd -- [in] Session socket FD pending_func -- [in] The receive function to be set for this session - - Returns ESP_OK : On successfully registering override ESP_ERR_INVALID_ARG : Null arguments - - - esp_err_t httpd_req_async_handler_begin(httpd_req_t *r, httpd_req_t **out) Start an asynchronous request. This function can be called in a request handler to get a request copy that can be used on a async thread. Note This function is necessary in order to handle multiple requests simultaneously. See examples/async_requests for example usage. You must call httpd_req_async_handler_complete() when you are done with the request. - Parameters r -- [in] The request to create an async copy of out -- [out] A newly allocated request which can be used on an async thread - - Returns ESP_OK : async request object created - - - esp_err_t httpd_req_async_handler_complete(httpd_req_t *r) Mark an asynchronous request as completed. This will. free the request memory relinquish ownership of the underlying socket, so it can be reused. allow the http server to close our socket if needed (lru_purge_enable) Note If async requests are not marked completed, eventually the server will no longer accept incoming connections. The server will log a "httpd_accept_conn: error in accept (23)" message if this happens. - Parameters r -- [in] The request to mark async work as completed - Returns ESP_OK : async request was marked completed - - - int httpd_req_to_sockfd(httpd_req_t *r) Get the Socket Descriptor from the HTTP request. This API will return the socket descriptor of the session for which URI handler was executed on reception of HTTP request. This is useful when user wants to call functions that require session socket fd, from within a URI handler, ie. : httpd_sess_get_ctx(), httpd_sess_trigger_close(), httpd_sess_update_lru_counter(). Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. - Parameters r -- [in] The request whose socket descriptor should be found - Returns Socket descriptor : The socket descriptor for this request -1 : Invalid/NULL request pointer - - int httpd_req_recv(httpd_req_t *r, char *buf, size_t buf_len) API to read content data from the HTTP request. This API will read HTTP content data from the HTTP request into provided buffer. Use content_len provided in httpd_req_t structure to know the length of data to be fetched. If content_len is too large for the buffer then user may have to make multiple calls to this function, each time fetching 'buf_len' number of bytes, while the pointer to content data is incremented internally by the same number. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. If an error is returned, the URI handler must further return an error. This will ensure that the erroneous socket is closed and cleaned up by the web server. Presently Chunked Encoding is not supported - Parameters r -- [in] The request being responded to buf -- [in] Pointer to a buffer that the data will be read into buf_len -- [in] Length of the buffer - - Returns Bytes : Number of bytes read into the buffer successfully 0 : Buffer length parameter is zero / connection closed by peer HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv() - - - size_t httpd_req_get_hdr_value_len(httpd_req_t *r, const char *field) Search for a field in request headers and return the string length of it's value. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once httpd_resp_send() API is called all request headers are purged, so request headers need be copied into separate buffers if they are required later. - Parameters r -- [in] The request being responded to field -- [in] The header field to be searched in the request - - Returns Length : If field is found in the request URL Zero : Field not found / Invalid request / Null arguments - - - esp_err_t httpd_req_get_hdr_value_str(httpd_req_t *r, const char *field, char *val, size_t val_size) Get the value string of a field from the request headers. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once httpd_resp_send() API is called all request headers are purged, so request headers need be copied into separate buffers if they are required later. If output size is greater than input, then the value is truncated, accompanied by truncation error as return value. Use httpd_req_get_hdr_value_len() to know the right buffer length - Parameters r -- [in] The request being responded to field -- [in] The field to be searched in the header val -- [out] Pointer to the buffer into which the value will be copied if the field is found val_size -- [in] Size of the user buffer "val" - - Returns ESP_OK : Field found in the request header and value string copied ESP_ERR_NOT_FOUND : Key not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated - - - size_t httpd_req_get_url_query_len(httpd_req_t *r) Get Query string length from the request URL. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid - Parameters r -- [in] The request being responded to - Returns Length : Query is found in the request URL Zero : Query not found / Null arguments / Invalid request - - esp_err_t httpd_req_get_url_query_str(httpd_req_t *r, char *buf, size_t buf_len) Get Query string from the request URL. Note Presently, the user can fetch the full URL query string, but decoding will have to be performed by the user. Request headers can be read using httpd_req_get_hdr_value_str() to know the 'Content-Type' (eg. Content-Type: application/x-www-form-urlencoded) and then the appropriate decoding algorithm needs to be applied. This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid If output size is greater than input, then the value is truncated, accompanied by truncation error as return value Prior to calling this function, one can use httpd_req_get_url_query_len() to know the query string length beforehand and hence allocate the buffer of right size (usually query string length + 1 for null termination) for storing the query string - Parameters r -- [in] The request being responded to buf -- [out] Pointer to the buffer into which the query string will be copied (if found) buf_len -- [in] Length of output buffer - - Returns ESP_OK : Query is found in the request URL and copied to buffer ESP_ERR_NOT_FOUND : Query not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer ESP_ERR_HTTPD_RESULT_TRUNC : Query string truncated - - - esp_err_t httpd_query_key_value(const char *qry, const char *key, char *val, size_t val_size) Helper function to get a URL query tag from a query string of the type param1=val1¶m2=val2. Note The components of URL query string (keys and values) are not URLdecoded. The user must check for 'Content-Type' field in the request headers and then depending upon the specified encoding (URLencoded or otherwise) apply the appropriate decoding algorithm. If actual value size is greater than val_size, then the value is truncated, accompanied by truncation error as return value. - Parameters qry -- [in] Pointer to query string key -- [in] The key to be searched in the query string val -- [out] Pointer to the buffer into which the value will be copied if the key is found val_size -- [in] Size of the user buffer "val" - - Returns ESP_OK : Key is found in the URL query string and copied to buffer ESP_ERR_NOT_FOUND : Key not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated - - Get the value string of a cookie value from the "Cookie" request headers by cookie name. - Parameters req -- [in] Pointer to the HTTP request cookie_name -- [in] The cookie name to be searched in the request val -- [out] Pointer to the buffer into which the value of cookie will be copied if the cookie is found val_size -- [inout] Pointer to size of the user buffer "val". This variable will contain cookie length if ESP_OK is returned and required buffer length incase ESP_ERR_HTTPD_RESULT_TRUNC is returned. - - Returns ESP_OK : Key is found in the cookie string and copied to buffer ESP_ERR_NOT_FOUND : Key not found ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated ESP_ERR_NO_MEM : Memory allocation failure - - bool httpd_uri_match_wildcard(const char *uri_template, const char *uri_to_match, size_t match_upto) Test if a URI matches the given wildcard template. Template may end with "?" to make the previous character optional (typically a slash), "*" for a wildcard match, and "?*" to make the previous character optional, and if present, allow anything to follow. Example: * matches everything /foo/? matches /foo and /foo/ /foo/* (sans the backslash) matches /foo/ and /foo/bar, but not /foo or /fo /foo/?* or /foo/*? (sans the backslash) matches /foo/, /foo/bar, and also /foo, but not /foox or /fo The special characters "?" and "*" anywhere else in the template will be taken literally. - Parameters uri_template -- [in] URI template (pattern) uri_to_match -- [in] URI to be matched match_upto -- [in] how many characters of the URI buffer to test (there may be trailing query string etc.) - - Returns true if a match was found - - esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, ssize_t buf_len) API to send a complete HTTP response. This API will send the data as an HTTP response to the request. This assumes that you have the entire response ready in a single buffer. If you wish to send response in incremental chunks use httpd_resp_send_chunk() instead. If no status code and content-type were set, by default this will send 200 OK status code and content type as text/html. You may call the following functions before this API to configure the response headers : httpd_resp_set_status() - for setting the HTTP status string, httpd_resp_set_type() - for setting the Content Type, httpd_resp_set_hdr() - for appending any additional field value entries in the response header Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once this API is called, the request has been responded to. No additional data can then be sent for the request. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. - Parameters r -- [in] The request being responded to buf -- [in] Buffer from where the content is to be fetched buf_len -- [in] Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen() - - Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request - - - esp_err_t httpd_resp_send_chunk(httpd_req_t *r, const char *buf, ssize_t buf_len) API to send one HTTP chunk. This API will send the data as an HTTP response to the request. This API will use chunked-encoding and send the response in the form of chunks. If you have the entire response contained in a single buffer, please use httpd_resp_send() instead. If no status code and content-type were set, by default this will send 200 OK status code and content type as text/html. You may call the following functions before this API to configure the response headers httpd_resp_set_status() - for setting the HTTP status string, httpd_resp_set_type() - for setting the Content Type, httpd_resp_set_hdr() - for appending any additional field value entries in the response header Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. When you are finished sending all your chunks, you must call this function with buf_len as 0. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. - Parameters r -- [in] The request being responded to buf -- [in] Pointer to a buffer that stores the data buf_len -- [in] Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen() - - Returns ESP_OK : On successfully sending the response packet chunk ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer - - - static inline esp_err_t httpd_resp_sendstr(httpd_req_t *r, const char *str) API to send a complete string as HTTP response. This API simply calls http_resp_send with buffer length set to string length assuming the buffer contains a null terminated string - Parameters r -- [in] The request being responded to str -- [in] String to be sent as response body - - Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request - - static inline esp_err_t httpd_resp_sendstr_chunk(httpd_req_t *r, const char *str) API to send a string as an HTTP response chunk. This API simply calls http_resp_send_chunk with buffer length set to string length assuming the buffer contains a null terminated string - Parameters r -- [in] The request being responded to str -- [in] String to be sent as response body (NULL to finish response packet) - - Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null request pointer ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request - - esp_err_t httpd_resp_set_status(httpd_req_t *r, const char *status) API to set the HTTP status code. This API sets the status of the HTTP response to the value specified. By default, the '200 OK' response is sent as the response. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. This API only sets the status to this value. The status isn't sent out until any of the send APIs is executed. Make sure that the lifetime of the status string is valid till send function is called. - Parameters r -- [in] The request being responded to status -- [in] The HTTP status code of this response - - Returns ESP_OK : On success ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer - - - esp_err_t httpd_resp_set_type(httpd_req_t *r, const char *type) API to set the HTTP content type. This API sets the 'Content Type' field of the response. The default content type is 'text/html'. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. This API only sets the content type to this value. The type isn't sent out until any of the send APIs is executed. Make sure that the lifetime of the type string is valid till send function is called. - Parameters r -- [in] The request being responded to type -- [in] The Content Type of the response - - Returns ESP_OK : On success ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer - - - esp_err_t httpd_resp_set_hdr(httpd_req_t *r, const char *field, const char *value) API to append any additional headers. This API sets any additional header fields that need to be sent in the response. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. The header isn't sent out until any of the send APIs is executed. The maximum allowed number of additional headers is limited to value of max_resp_headers in config structure. Make sure that the lifetime of the field value strings are valid till send function is called. - Parameters r -- [in] The request being responded to field -- [in] The field name of the HTTP header value -- [in] The value of this HTTP header - - Returns ESP_OK : On successfully appending new header ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_HDR : Total additional headers exceed max allowed ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer - - - esp_err_t httpd_resp_send_err(httpd_req_t *req, httpd_err_code_t error, const char *msg) For sending out error code in response to HTTP request. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. If you wish to send additional data in the body of the response, please use the lower-level functions directly. - Parameters req -- [in] Pointer to the HTTP request for which the response needs to be sent error -- [in] Error type to send msg -- [in] Error message string (pass NULL for default message) - - Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer - - - static inline esp_err_t httpd_resp_send_404(httpd_req_t *r) Helper function for HTTP 404. Send HTTP 404 message. If you wish to send additional data in the body of the response, please use the lower-level functions directly. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. - Parameters r -- [in] The request being responded to - Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer - - - static inline esp_err_t httpd_resp_send_408(httpd_req_t *r) Helper function for HTTP 408. Send HTTP 408 message. If you wish to send additional data in the body of the response, please use the lower-level functions directly. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. - Parameters r -- [in] The request being responded to - Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer - - - static inline esp_err_t httpd_resp_send_500(httpd_req_t *r) Helper function for HTTP 500. Send HTTP 500 message. If you wish to send additional data in the body of the response, please use the lower-level functions directly. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Once this API is called, all request headers are purged, so request headers need be copied into separate buffers if they are required later. - Parameters r -- [in] The request being responded to - Returns ESP_OK : On successfully sending the response packet ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_HTTPD_RESP_SEND : Error in raw send ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer - - - int httpd_send(httpd_req_t *r, const char *buf, size_t buf_len) Raw HTTP send. Call this API if you wish to construct your custom response packet. When using this, all essential header, eg. HTTP version, Status Code, Content Type and Length, Encoding, etc. will have to be constructed manually, and HTTP delimeters (CRLF) will need to be placed correctly for separating sub-sections of the HTTP response packet. If the send override function is set, this API will end up calling that function eventually to send data out. Note This API is supposed to be called only from the context of a URI handler where httpd_req_t* request pointer is valid. Unless the response has the correct HTTP structure (which the user must now ensure) it is not guaranteed that it will be recognized by the client. For most cases, you wouldn't have to call this API, but you would rather use either of : httpd_resp_send(), httpd_resp_send_chunk() - Parameters r -- [in] The request being responded to buf -- [in] Buffer from where the fully constructed packet is to be read buf_len -- [in] Length of the buffer - - Returns Bytes : Number of bytes that were sent successfully HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() - - - int httpd_socket_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags) A low level API to send data on a given socket This internally calls the default send function, or the function registered by httpd_sess_set_send_override(). Note This API is not recommended to be used in any request handler. Use this only for advanced use cases, wherein some asynchronous data is to be sent over a socket. - Parameters hd -- [in] server instance sockfd -- [in] session socket file descriptor buf -- [in] buffer with bytes to send buf_len -- [in] data size flags -- [in] flags for the send() function - - Returns Bytes : The number of bytes sent successfully HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() - - int httpd_socket_recv(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags) A low level API to receive data from a given socket This internally calls the default recv function, or the function registered by httpd_sess_set_recv_override(). Note This API is not recommended to be used in any request handler. Use this only for advanced use cases, wherein some asynchronous communication is required. - Parameters hd -- [in] server instance sockfd -- [in] session socket file descriptor buf -- [in] buffer with bytes to send buf_len -- [in] data size flags -- [in] flags for the send() function - - Returns Bytes : The number of bytes received successfully 0 : Buffer length parameter is zero / connection closed by peer HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv() - - esp_err_t httpd_register_err_handler(httpd_handle_t handle, httpd_err_code_t error, httpd_err_handler_func_t handler_fn) Function for registering HTTP error handlers. This function maps a handler function to any supported error code given by httpd_err_code_t. See prototype httpd_err_handler_func_tabove for details. - Parameters handle -- [in] HTTP server handle error -- [in] Error type handler_fn -- [in] User implemented handler function (Pass NULL to unset any previously set handler) - - Returns ESP_OK : handler registered successfully ESP_ERR_INVALID_ARG : invalid error code or server handle - - esp_err_t httpd_start(httpd_handle_t *handle, const httpd_config_t *config) Starts the web server. Create an instance of HTTP server and allocate memory/resources for it depending upon the specified configuration. Example usage: //Function for starting the webserver httpd_handle_t start_webserver(void) { // Generate default configuration httpd_config_t config = HTTPD_DEFAULT_CONFIG(); // Empty handle to http_server httpd_handle_t server = NULL; // Start the httpd server if (httpd_start(&server, &config) == ESP_OK) { // Register URI handlers httpd_register_uri_handler(server, &uri_get); httpd_register_uri_handler(server, &uri_post); } // If server failed to start, handle will be NULL return server; } - Parameters config -- [in] Configuration for new instance of the server handle -- [out] Handle to newly created instance of the server. NULL on error - - Returns ESP_OK : Instance created successfully ESP_ERR_INVALID_ARG : Null argument(s) ESP_ERR_HTTPD_ALLOC_MEM : Failed to allocate memory for instance ESP_ERR_HTTPD_TASK : Failed to launch server task - - esp_err_t httpd_stop(httpd_handle_t handle) Stops the web server. Deallocates memory/resources used by an HTTP server instance and deletes it. Once deleted the handle can no longer be used for accessing the instance. Example usage: // Function for stopping the webserver void stop_webserver(httpd_handle_t server) { // Ensure handle is non NULL if (server != NULL) { // Stop the httpd server httpd_stop(server); } } - Parameters handle -- [in] Handle to server returned by httpd_start - Returns ESP_OK : Server stopped successfully ESP_ERR_INVALID_ARG : Handle argument is Null - - esp_err_t httpd_queue_work(httpd_handle_t handle, httpd_work_fn_t work, void *arg) Queue execution of a function in HTTPD's context. This API queues a work function for asynchronous execution Note Some protocols require that the web server generate some asynchronous data and send it to the persistently opened connection. This facility is for use by such protocols. - Parameters handle -- [in] Handle to server returned by httpd_start work -- [in] Pointer to the function to be executed in the HTTPD's context arg -- [in] Pointer to the arguments that should be passed to this function - - Returns ESP_OK : On successfully queueing the work ESP_FAIL : Failure in ctrl socket ESP_ERR_INVALID_ARG : Null arguments - - void *httpd_sess_get_ctx(httpd_handle_t handle, int sockfd) Get session context from socket descriptor. Typically if a session context is created, it is available to URI handlers through the httpd_req_t structure. But, there are cases where the web server's send/receive functions may require the context (for example, for accessing keying information etc). Since the send/receive function only have the socket descriptor at their disposal, this API provides them with a way to retrieve the session context. - Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. - - Returns void* : Pointer to the context associated with this session NULL : Empty context / Invalid handle / Invalid socket fd - - void httpd_sess_set_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn) Set session context by socket descriptor. - Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. ctx -- [in] Context object to assign to the session free_fn -- [in] Function that should be called to free the context - - void *httpd_sess_get_transport_ctx(httpd_handle_t handle, int sockfd) Get session 'transport' context by socket descriptor. This context is used by the send/receive functions, for example to manage SSL context. See also httpd_sess_get_ctx() - Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. - - Returns void* : Pointer to the transport context associated with this session NULL : Empty context / Invalid handle / Invalid socket fd - - void httpd_sess_set_transport_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn) Set session 'transport' context by socket descriptor. See also httpd_sess_set_ctx() - Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor for which the context should be extracted. ctx -- [in] Transport context object to assign to the session free_fn -- [in] Function that should be called to free the transport context - - void *httpd_get_global_user_ctx(httpd_handle_t handle) Get HTTPD global user context (it was set in the server config struct) - Parameters handle -- [in] Handle to server returned by httpd_start - Returns global user context - void *httpd_get_global_transport_ctx(httpd_handle_t handle) Get HTTPD global transport context (it was set in the server config struct) - Parameters handle -- [in] Handle to server returned by httpd_start - Returns global transport context - esp_err_t httpd_sess_trigger_close(httpd_handle_t handle, int sockfd) Trigger an httpd session close externally. Note Calling this API is only required in special circumstances wherein some application requires to close an httpd client session asynchronously. - Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor of the session to be closed - - Returns ESP_OK : On successfully initiating closure ESP_FAIL : Failure to queue work ESP_ERR_NOT_FOUND : Socket fd not found ESP_ERR_INVALID_ARG : Null arguments - - esp_err_t httpd_sess_update_lru_counter(httpd_handle_t handle, int sockfd) Update LRU counter for a given socket. LRU Counters are internally associated with each session to monitor how recently a session exchanged traffic. When LRU purge is enabled, if a client is requesting for connection but maximum number of sockets/sessions is reached, then the session having the earliest LRU counter is closed automatically. Updating the LRU counter manually prevents the socket from being purged due to the Least Recently Used (LRU) logic, even though it might not have received traffic for some time. This is useful when all open sockets/session are frequently exchanging traffic but the user specifically wants one of the sessions to be kept open, irrespective of when it last exchanged a packet. Note Calling this API is only necessary if the LRU Purge Enable option is enabled. - Parameters handle -- [in] Handle to server returned by httpd_start sockfd -- [in] The socket descriptor of the session for which LRU counter is to be updated - - Returns ESP_OK : Socket found and LRU counter updated ESP_ERR_NOT_FOUND : Socket not found ESP_ERR_INVALID_ARG : Null arguments - - esp_err_t httpd_get_client_list(httpd_handle_t handle, size_t *fds, int *client_fds) Returns list of current socket descriptors of active sessions. Note Size of provided array has to be equal or greater then maximum number of opened sockets, configured upon initialization with max_open_sockets field in httpd_config_t structure. - Parameters handle -- [in] Handle to server returned by httpd_start fds -- [inout] In: Size of provided client_fds array Out: Number of valid client fds returned in client_fds, client_fds -- [out] Array of client fds - - Returns ESP_OK : Successfully retrieved session list ESP_ERR_INVALID_ARG : Wrong arguments or list is longer than provided array - Structures - struct esp_http_server_event_data Argument structure for HTTP_SERVER_EVENT_ON_DATA and HTTP_SERVER_EVENT_SENT_DATA event - struct httpd_config HTTP Server Configuration Structure. Note Use HTTPD_DEFAULT_CONFIG() to initialize the configuration to a default value and then modify only those fields that are specifically determined by the use case. Public Members - unsigned task_priority Priority of FreeRTOS task which runs the server - size_t stack_size The maximum stack size allowed for the server task - BaseType_t core_id The core the HTTP server task will run on - uint16_t server_port TCP Port number for receiving and transmitting HTTP traffic - uint16_t ctrl_port UDP Port number for asynchronously exchanging control signals between various components of the server - uint16_t max_open_sockets Max number of sockets/clients connected at any time (3 sockets are reserved for internal working of the HTTP server) - uint16_t max_uri_handlers Maximum allowed uri handlers - uint16_t max_resp_headers Maximum allowed additional headers in HTTP response - uint16_t backlog_conn Number of backlog connections - bool lru_purge_enable Purge "Least Recently Used" connection - uint16_t recv_wait_timeout Timeout for recv function (in seconds) - uint16_t send_wait_timeout Timeout for send function (in seconds) - void *global_user_ctx Global user context. This field can be used to store arbitrary user data within the server context. The value can be retrieved using the server handle, available e.g. in the httpd_req_t struct. When shutting down, the server frees up the user context by calling free() on the global_user_ctx field. If you wish to use a custom function for freeing the global user context, please specify that here. - httpd_free_ctx_fn_t global_user_ctx_free_fn Free function for global user context - void *global_transport_ctx Global transport context. Similar to global_user_ctx, but used for session encoding or encryption (e.g. to hold the SSL context). It will be freed using free(), unless global_transport_ctx_free_fn is specified. - httpd_free_ctx_fn_t global_transport_ctx_free_fn Free function for global transport context - bool enable_so_linger bool to enable/disable linger - int linger_timeout linger timeout (in seconds) - bool keep_alive_enable Enable keep-alive timeout - int keep_alive_idle Keep-alive idle time. Default is 5 (second) - int keep_alive_interval Keep-alive interval time. Default is 5 (second) - int keep_alive_count Keep-alive packet retry send count. Default is 3 counts - httpd_open_func_t open_fn Custom session opening callback. Called on a new session socket just after accept(), but before reading any data. This is an opportunity to set up e.g. SSL encryption using global_transport_ctx and the send/recv/pending session overrides. If a context needs to be maintained between these functions, store it in the session using httpd_sess_set_transport_ctx() and retrieve it later with httpd_sess_get_transport_ctx() Returning a value other than ESP_OK will immediately close the new socket. - httpd_close_func_t close_fn Custom session closing callback. Called when a session is deleted, before freeing user and transport contexts and before closing the socket. This is a place for custom de-init code common to all sockets. The server will only close the socket if no custom session closing callback is set. If a custom callback is used, close(sockfd)should be called in here for most cases. Set the user or transport context to NULL if it was freed here, so the server does not try to free it again. This function is run for all terminated sessions, including sessions where the socket was closed by the network stack - that is, the file descriptor may not be valid anymore. - httpd_uri_match_func_t uri_match_fn URI matcher function. Called when searching for a matching URI: 1) whose request handler is to be executed right after an HTTP request is successfully parsed 2) in order to prevent duplication while registering a new URI handler using httpd_register_uri_handler() Available options are: 1) NULL : Internally do basic matching using strncmp()2) httpd_uri_match_wildcard(): URI wildcard matcher Users can implement their own matching functions (See description of the httpd_uri_match_func_tfunction prototype) - unsigned task_priority - struct httpd_req HTTP Request Data Structure. Public Members - httpd_handle_t handle Handle to server instance - int method The type of HTTP request, -1 if unsupported method - const char uri[HTTPD_MAX_URI_LEN + 1] The URI of this request (1 byte extra for null termination) - size_t content_len Length of the request body - void *aux Internally used members - void *user_ctx User context pointer passed during URI registration. - void *sess_ctx Session Context Pointer A session context. Contexts are maintained across 'sessions' for a given open TCP connection. One session could have multiple request responses. The web server will ensure that the context persists across all these request and responses. By default, this is NULL. URI Handlers can set this to any meaningful value. If the underlying socket gets closed, and this pointer is non-NULL, the web server will free up the context by calling free(), unless free_ctx function is set. - httpd_free_ctx_fn_t free_ctx Pointer to free context hook Function to free session context If the web server's socket closes, it frees up the session context by calling free() on the sess_ctx member. If you wish to use a custom function for freeing the session context, please specify that here. - bool ignore_sess_ctx_changes Flag indicating if Session Context changes should be ignored By default, if you change the sess_ctx in some URI handler, the http server will internally free the earlier context (if non NULL), after the URI handler returns. If you want to manage the allocation/reallocation/freeing of sess_ctx yourself, set this flag to true, so that the server will not perform any checks on it. The context will be cleared by the server (by calling free_ctx or free()) only if the socket gets closed. - httpd_handle_t handle - struct httpd_uri Structure for URI handler. Public Members - const char *uri The URI to handle - httpd_method_t method Method supported by the URI - esp_err_t (*handler)(httpd_req_t *r) Handler to call for supported request method. This must return ESP_OK, or else the underlying socket will be closed. - void *user_ctx Pointer to user context data which will be available to handler - const char *uri Macros - HTTPD_MAX_REQ_HDR_LEN - HTTPD_MAX_URI_LEN - HTTPD_SOCK_ERR_FAIL - HTTPD_SOCK_ERR_INVALID - HTTPD_SOCK_ERR_TIMEOUT - HTTPD_200 HTTP Response 200 - HTTPD_204 HTTP Response 204 - HTTPD_207 HTTP Response 207 - HTTPD_400 HTTP Response 400 - HTTPD_404 HTTP Response 404 - HTTPD_408 HTTP Response 408 - HTTPD_500 HTTP Response 500 - HTTPD_TYPE_JSON HTTP Content type JSON - HTTPD_TYPE_TEXT HTTP Content type text/HTML - HTTPD_TYPE_OCTET HTTP Content type octext-stream - ESP_HTTPD_DEF_CTRL_PORT HTTP Server control socket port - HTTPD_DEFAULT_CONFIG() - ESP_ERR_HTTPD_BASE Starting number of HTTPD error codes - ESP_ERR_HTTPD_HANDLERS_FULL All slots for registering URI handlers have been consumed - ESP_ERR_HTTPD_HANDLER_EXISTS URI handler with same method and target URI already registered - ESP_ERR_HTTPD_INVALID_REQ Invalid request pointer - ESP_ERR_HTTPD_RESULT_TRUNC Result string truncated - ESP_ERR_HTTPD_RESP_HDR Response header field larger than supported - ESP_ERR_HTTPD_RESP_SEND Error occured while sending response packet - ESP_ERR_HTTPD_ALLOC_MEM Failed to dynamically allocate memory for resource - ESP_ERR_HTTPD_TASK Failed to launch server task/thread - HTTPD_RESP_USE_STRLEN Type Definitions - typedef int (*httpd_send_func_t)(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags) Prototype for HTTPDs low-level send function. Note User specified send function must handle errors internally, depending upon the set value of errno, and return specific HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as return value of httpd_send() function - Param hd [in] server instance - Param sockfd [in] session socket file descriptor - Param buf [in] buffer with bytes to send - Param buf_len [in] data size - Param flags [in] flags for the send() function - Return Bytes : The number of bytes sent successfully HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() - - typedef int (*httpd_recv_func_t)(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags) Prototype for HTTPDs low-level recv function. Note User specified recv function must handle errors internally, depending upon the set value of errno, and return specific HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as return value of httpd_req_recv() function - Param hd [in] server instance - Param sockfd [in] session socket file descriptor - Param buf [in] buffer with bytes to send - Param buf_len [in] data size - Param flags [in] flags for the send() function - Return Bytes : The number of bytes received successfully 0 : Buffer length parameter is zero / connection closed by peer HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv() - - typedef int (*httpd_pending_func_t)(httpd_handle_t hd, int sockfd) Prototype for HTTPDs low-level "get pending bytes" function. Note User specified pending function must handle errors internally, depending upon the set value of errno, and return specific HTTPD_SOCK_ERR_ codes, which will be handled accordingly in the server task. - Param hd [in] server instance - Param sockfd [in] session socket file descriptor - Return Bytes : The number of bytes waiting to be received HTTPD_SOCK_ERR_INVALID : Invalid arguments HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket pending() HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket pending() - - typedef esp_err_t (*httpd_err_handler_func_t)(httpd_req_t *req, httpd_err_code_t error) Function prototype for HTTP error handling. This function is executed upon HTTP errors generated during internal processing of an HTTP request. This is used to override the default behavior on error, which is to send HTTP error response and close the underlying socket. Note If implemented, the server will not automatically send out HTTP error response codes, therefore, httpd_resp_send_err() must be invoked inside this function if user wishes to generate HTTP error responses. When invoked, the validity of uri, method, content_lenand user_ctxfields of the httpd_req_t parameter is not guaranteed as the HTTP request may be partially received/parsed. The function must return ESP_OK if underlying socket needs to be kept open. Any other value will ensure that the socket is closed. The return value is ignored when error is of type HTTPD_500_INTERNAL_SERVER_ERRORand the socket closed anyway. - Param req [in] HTTP request for which the error needs to be handled - Param error [in] Error type - Return ESP_OK : error handled successful ESP_FAIL : failure indicates that the underlying socket needs to be closed - - - typedef void *httpd_handle_t HTTP Server Instance Handle. Every instance of the server will have a unique handle. - typedef enum http_method httpd_method_t HTTP Method Type wrapper over "enum http_method" available in "http_parser" library. - typedef void (*httpd_free_ctx_fn_t)(void *ctx) Prototype for freeing context data (if any) - Param ctx [in] object to free - typedef esp_err_t (*httpd_open_func_t)(httpd_handle_t hd, int sockfd) Function prototype for opening a session. Called immediately after the socket was opened to set up the send/recv functions and other parameters of the socket. - Param hd [in] server instance - Param sockfd [in] session socket file descriptor - Return ESP_OK : On success Any value other than ESP_OK will signal the server to close the socket immediately - - typedef void (*httpd_close_func_t)(httpd_handle_t hd, int sockfd) Function prototype for closing a session. Note It's possible that the socket descriptor is invalid at this point, the function is called for all terminated sessions. Ensure proper handling of return codes. - Param hd [in] server instance - Param sockfd [in] session socket file descriptor - typedef bool (*httpd_uri_match_func_t)(const char *reference_uri, const char *uri_to_match, size_t match_upto) Function prototype for URI matching. - Param reference_uri [in] URI/template with respect to which the other URI is matched - Param uri_to_match [in] URI/template being matched to the reference URI/template - Param match_upto [in] For specifying the actual length of uri_to_matchup to which the matching algorithm is to be applied (The maximum value is strlen(uri_to_match), independent of the length of reference_uri) - Return true on match - typedef struct httpd_config httpd_config_t HTTP Server Configuration Structure. Note Use HTTPD_DEFAULT_CONFIG() to initialize the configuration to a default value and then modify only those fields that are specifically determined by the use case. - typedef void (*httpd_work_fn_t)(void *arg) Prototype of the HTTPD work function Please refer to httpd_queue_work() for more details. - Param arg [in] The arguments for this work function Enumerations - enum httpd_err_code_t Error codes sent as HTTP response in case of errors encountered during processing of an HTTP request. Values: - enumerator HTTPD_500_INTERNAL_SERVER_ERROR - enumerator HTTPD_501_METHOD_NOT_IMPLEMENTED - enumerator HTTPD_505_VERSION_NOT_SUPPORTED - enumerator HTTPD_400_BAD_REQUEST - enumerator HTTPD_401_UNAUTHORIZED - enumerator HTTPD_403_FORBIDDEN - enumerator HTTPD_404_NOT_FOUND - enumerator HTTPD_405_METHOD_NOT_ALLOWED - enumerator HTTPD_408_REQ_TIMEOUT - enumerator HTTPD_411_LENGTH_REQUIRED - enumerator HTTPD_414_URI_TOO_LONG - enumerator HTTPD_431_REQ_HDR_FIELDS_TOO_LARGE - enumerator HTTPD_ERR_CODE_MAX - enumerator HTTPD_500_INTERNAL_SERVER_ERROR - enum esp_http_server_event_id_t HTTP Server events id. Values: - enumerator HTTP_SERVER_EVENT_ERROR This event occurs when there are any errors during execution - enumerator HTTP_SERVER_EVENT_START This event occurs when HTTP Server is started - enumerator HTTP_SERVER_EVENT_ON_CONNECTED Once the HTTP Server has been connected to the client, no data exchange has been performed - enumerator HTTP_SERVER_EVENT_ON_HEADER Occurs when receiving each header sent from the client - enumerator HTTP_SERVER_EVENT_HEADERS_SENT After sending all the headers to the client - enumerator HTTP_SERVER_EVENT_ON_DATA Occurs when receiving data from the client - enumerator HTTP_SERVER_EVENT_SENT_DATA Occurs when an ESP HTTP server session is finished - enumerator HTTP_SERVER_EVENT_DISCONNECTED The connection has been disconnected - enumerator HTTP_SERVER_EVENT_STOP This event occurs when HTTP Server is stopped - enumerator HTTP_SERVER_EVENT_ERROR
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/protocols/esp_http_server.html
ESP-IDF Programming Guide v5.2.1 documentation
null
HTTPS Server
null
espressif.com
2016-01-01
cc52bd4bb812f89d
null
null
HTTPS Server Overview This component is built on top of HTTP Server. The HTTPS server takes advantage of hook registration functions in the regular HTTP server to provide callback function for SSL session. All documentation for HTTP Server applies also to a server you create this way. Used APIs The following APIs of HTTP Server should not be used with HTTPS Server, as they are used internally to handle secure sessions and to maintain internal state: "send", "receive" and "pending" callback registration functions - secure socket handling "transport context" - both global and session httpd_sess_get_transport_ctx() - returns SSL used for the session httpd_get_global_transport_ctx() - returns the shared SSL context httpd_config::open_fn - used to set up secure sockets httpd_sess_get_transport_ctx() - returns SSL used for the session httpd_get_global_transport_ctx() - returns the shared SSL context httpd_config::open_fn - used to set up secure sockets httpd_sess_get_transport_ctx() - returns SSL used for the session Everything else can be used without limitations. Usage Please see the example protocols/https_server to learn how to set up a secure server. Basically, all you need is to generate a certificate, embed it into the firmware, and pass the init struct into the start function after the certificate address and lengths are correctly configured in the init struct. The server can be started with or without SSL by changing a flag in the init struct - httpd_ssl_config::transport_mode . This could be used, e.g., for testing or in trusted environments where you prefer speed over security. Performance The initial session setup can take about two seconds, or more with slower clock speed or more verbose logging. Subsequent requests through the open secure socket are much faster (down to under 100 ms). API Reference Header File This header file can be included with: #include "esp_https_server.h" This header file is a part of the API provided by the esp_https_server component. To declare that your component depends on esp_https_server , add the following to your CMakeLists.txt: REQUIRES esp_https_server or PRIV_REQUIRES esp_https_server Functions esp_err_t httpd_ssl_start(httpd_handle_t *handle, httpd_ssl_config_t *config) Create a SSL capable HTTP server (secure mode may be disabled in config) Parameters config -- [inout] - server config, must not be const. Does not have to stay valid after calling this function. handle -- [out] - storage for the server handle, must be a valid pointer config -- [inout] - server config, must not be const. Does not have to stay valid after calling this function. handle -- [out] - storage for the server handle, must be a valid pointer config -- [inout] - server config, must not be const. Does not have to stay valid after calling this function. Returns success Parameters config -- [inout] - server config, must not be const. Does not have to stay valid after calling this function. handle -- [out] - storage for the server handle, must be a valid pointer Returns success esp_err_t httpd_ssl_stop(httpd_handle_t handle) Stop the server. Blocks until the server is shut down. Parameters handle -- [in] Returns ESP_OK: Server stopped successfully ESP_ERR_INVALID_ARG: Invalid argument ESP_FAIL: Failure to shut down server ESP_OK: Server stopped successfully ESP_ERR_INVALID_ARG: Invalid argument ESP_FAIL: Failure to shut down server ESP_OK: Server stopped successfully Parameters handle -- [in] Returns ESP_OK: Server stopped successfully ESP_ERR_INVALID_ARG: Invalid argument ESP_FAIL: Failure to shut down server Structures struct esp_https_server_user_cb_arg Callback data struct, contains the ESP-TLS connection handle and the connection state at which the callback is executed. Public Members httpd_ssl_user_cb_state_t user_cb_state State of user callback httpd_ssl_user_cb_state_t user_cb_state State of user callback httpd_ssl_user_cb_state_t user_cb_state struct httpd_ssl_config HTTPS server config struct Please use HTTPD_SSL_CONFIG_DEFAULT() to initialize it. Public Members httpd_config_t httpd Underlying HTTPD server config Parameters like task stack size and priority can be adjusted here. httpd_config_t httpd Underlying HTTPD server config Parameters like task stack size and priority can be adjusted here. const uint8_t *servercert Server certificate const uint8_t *servercert Server certificate size_t servercert_len Server certificate byte length size_t servercert_len Server certificate byte length const uint8_t *cacert_pem CA certificate ((CA used to sign clients, or client cert itself) const uint8_t *cacert_pem CA certificate ((CA used to sign clients, or client cert itself) size_t cacert_len CA certificate byte length size_t cacert_len CA certificate byte length const uint8_t *prvtkey_pem Private key const uint8_t *prvtkey_pem Private key size_t prvtkey_len Private key byte length size_t prvtkey_len Private key byte length bool use_ecdsa_peripheral Use ECDSA peripheral to use private key bool use_ecdsa_peripheral Use ECDSA peripheral to use private key uint8_t ecdsa_key_efuse_blk The efuse block where ECDSA key is stored uint8_t ecdsa_key_efuse_blk The efuse block where ECDSA key is stored httpd_ssl_transport_mode_t transport_mode Transport Mode (default secure) httpd_ssl_transport_mode_t transport_mode Transport Mode (default secure) uint16_t port_secure Port used when transport mode is secure (default 443) uint16_t port_secure Port used when transport mode is secure (default 443) uint16_t port_insecure Port used when transport mode is insecure (default 80) uint16_t port_insecure Port used when transport mode is insecure (default 80) bool session_tickets Enable tls session tickets bool session_tickets Enable tls session tickets bool use_secure_element Enable secure element for server session bool use_secure_element Enable secure element for server session esp_https_server_user_cb *user_cb User callback for esp_https_server esp_https_server_user_cb *user_cb User callback for esp_https_server void *ssl_userdata user data to add to the ssl context void *ssl_userdata user data to add to the ssl context esp_tls_handshake_callback cert_select_cb Certificate selection callback to use esp_tls_handshake_callback cert_select_cb Certificate selection callback to use const char **alpn_protos Application protocols the server supports in order of prefernece. Used for negotiating during the TLS handshake, first one the client supports is selected. The data structure must live as long as the https server itself! const char **alpn_protos Application protocols the server supports in order of prefernece. Used for negotiating during the TLS handshake, first one the client supports is selected. The data structure must live as long as the https server itself! httpd_config_t httpd Macros HTTPD_SSL_CONFIG_DEFAULT() Default config struct init (http_server default config had to be copied for customization) Notes: port is set when starting the server, according to 'transport_mode' one socket uses ~ 40kB RAM with SSL, we reduce the default socket count to 4 SSL sockets are usually long-lived, closing LRU prevents pool exhaustion DOS Stack size may need adjustments depending on the user application port is set when starting the server, according to 'transport_mode' one socket uses ~ 40kB RAM with SSL, we reduce the default socket count to 4 SSL sockets are usually long-lived, closing LRU prevents pool exhaustion DOS Stack size may need adjustments depending on the user application port is set when starting the server, according to 'transport_mode' Type Definitions typedef struct esp_https_server_user_cb_arg esp_https_server_user_cb_arg_t Callback data struct, contains the ESP-TLS connection handle and the connection state at which the callback is executed. typedef void esp_https_server_user_cb(esp_https_server_user_cb_arg_t *user_cb) Callback function prototype Can be used to get connection or client information (SSL context) E.g. Client certificate, Socket FD, Connection state, etc. Param user_cb Callback data struct Param user_cb Callback data struct typedef struct httpd_ssl_config httpd_ssl_config_t Enumerations enum httpd_ssl_transport_mode_t Values: enumerator HTTPD_SSL_TRANSPORT_SECURE enumerator HTTPD_SSL_TRANSPORT_SECURE enumerator HTTPD_SSL_TRANSPORT_INSECURE enumerator HTTPD_SSL_TRANSPORT_INSECURE enumerator HTTPD_SSL_TRANSPORT_SECURE
HTTPS Server Overview This component is built on top of HTTP Server. The HTTPS server takes advantage of hook registration functions in the regular HTTP server to provide callback function for SSL session. All documentation for HTTP Server applies also to a server you create this way. Used APIs The following APIs of HTTP Server should not be used with HTTPS Server, as they are used internally to handle secure sessions and to maintain internal state: "send", "receive" and "pending" callback registration functions - secure socket handling "transport context" - both global and session httpd_sess_get_transport_ctx()- returns SSL used for the session httpd_get_global_transport_ctx()- returns the shared SSL context httpd_config::open_fn- used to set up secure sockets - Everything else can be used without limitations. Usage Please see the example protocols/https_server to learn how to set up a secure server. Basically, all you need is to generate a certificate, embed it into the firmware, and pass the init struct into the start function after the certificate address and lengths are correctly configured in the init struct. The server can be started with or without SSL by changing a flag in the init struct - httpd_ssl_config::transport_mode. This could be used, e.g., for testing or in trusted environments where you prefer speed over security. Performance The initial session setup can take about two seconds, or more with slower clock speed or more verbose logging. Subsequent requests through the open secure socket are much faster (down to under 100 ms). API Reference Header File This header file can be included with: #include "esp_https_server.h" This header file is a part of the API provided by the esp_https_servercomponent. To declare that your component depends on esp_https_server, add the following to your CMakeLists.txt: REQUIRES esp_https_server or PRIV_REQUIRES esp_https_server Functions - esp_err_t httpd_ssl_start(httpd_handle_t *handle, httpd_ssl_config_t *config) Create a SSL capable HTTP server (secure mode may be disabled in config) - Parameters config -- [inout] - server config, must not be const. Does not have to stay valid after calling this function. handle -- [out] - storage for the server handle, must be a valid pointer - - Returns success - esp_err_t httpd_ssl_stop(httpd_handle_t handle) Stop the server. Blocks until the server is shut down. - Parameters handle -- [in] - Returns ESP_OK: Server stopped successfully ESP_ERR_INVALID_ARG: Invalid argument ESP_FAIL: Failure to shut down server - Structures - struct esp_https_server_user_cb_arg Callback data struct, contains the ESP-TLS connection handle and the connection state at which the callback is executed. Public Members - httpd_ssl_user_cb_state_t user_cb_state State of user callback - httpd_ssl_user_cb_state_t user_cb_state - struct httpd_ssl_config HTTPS server config struct Please use HTTPD_SSL_CONFIG_DEFAULT() to initialize it. Public Members - httpd_config_t httpd Underlying HTTPD server config Parameters like task stack size and priority can be adjusted here. - const uint8_t *servercert Server certificate - size_t servercert_len Server certificate byte length - const uint8_t *cacert_pem CA certificate ((CA used to sign clients, or client cert itself) - size_t cacert_len CA certificate byte length - const uint8_t *prvtkey_pem Private key - size_t prvtkey_len Private key byte length - bool use_ecdsa_peripheral Use ECDSA peripheral to use private key - uint8_t ecdsa_key_efuse_blk The efuse block where ECDSA key is stored - httpd_ssl_transport_mode_t transport_mode Transport Mode (default secure) - uint16_t port_secure Port used when transport mode is secure (default 443) - uint16_t port_insecure Port used when transport mode is insecure (default 80) - bool session_tickets Enable tls session tickets - bool use_secure_element Enable secure element for server session - esp_https_server_user_cb *user_cb User callback for esp_https_server - void *ssl_userdata user data to add to the ssl context - esp_tls_handshake_callback cert_select_cb Certificate selection callback to use - const char **alpn_protos Application protocols the server supports in order of prefernece. Used for negotiating during the TLS handshake, first one the client supports is selected. The data structure must live as long as the https server itself! - httpd_config_t httpd Macros - HTTPD_SSL_CONFIG_DEFAULT() Default config struct init (http_server default config had to be copied for customization) Notes: port is set when starting the server, according to 'transport_mode' one socket uses ~ 40kB RAM with SSL, we reduce the default socket count to 4 SSL sockets are usually long-lived, closing LRU prevents pool exhaustion DOS Stack size may need adjustments depending on the user application - Type Definitions - typedef struct esp_https_server_user_cb_arg esp_https_server_user_cb_arg_t Callback data struct, contains the ESP-TLS connection handle and the connection state at which the callback is executed. - typedef void esp_https_server_user_cb(esp_https_server_user_cb_arg_t *user_cb) Callback function prototype Can be used to get connection or client information (SSL context) E.g. Client certificate, Socket FD, Connection state, etc. - Param user_cb Callback data struct - typedef struct httpd_ssl_config httpd_ssl_config_t Enumerations - enum httpd_ssl_transport_mode_t Values: - enumerator HTTPD_SSL_TRANSPORT_SECURE - enumerator HTTPD_SSL_TRANSPORT_INSECURE - enumerator HTTPD_SSL_TRANSPORT_SECURE
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/protocols/esp_https_server.html
ESP-IDF Programming Guide v5.2.1 documentation
null
ICMP Echo
null
espressif.com
2016-01-01
a4f8bdb0a61cb1f1
null
null
ICMP Echo Overview ICMP (Internet Control Message Protocol) is used for diagnostic or control purposes or generated in response to errors in IP operations. The common network util ping is implemented based on the ICMP packets with the type field value of 0, also called Echo Reply . During a ping session, the source host firstly sends out an ICMP echo request packet and wait for an ICMP echo reply with specific times. In this way, it also measures the round-trip time for the messages. After receiving a valid ICMP echo reply, the source host will generate statistics about the IP link layer (e.g., packet loss, elapsed time, etc). It is common that IoT device needs to check whether a remote server is alive or not. The device should show the warnings to users when it got offline. It can be achieved by creating a ping session and sending or parsing ICMP echo packets periodically. To make this internal procedure much easier for users, ESP-IDF provides some out-of-box APIs. Create a New Ping Session To create a ping session, you need to fill in the esp_ping_config_t configuration structure firstly, specifying target IP address, interval times, and etc. Optionally, you can also register some callback functions with the esp_ping_callbacks_t structure. Example method to create a new ping session and register callbacks: static void test_on_ping_success(esp_ping_handle_t hdl, void *args) { // optionally, get callback arguments // const char* str = (const char*) args; // printf("%s\r\n", str); // "foo" uint8_t ttl; uint16_t seqno; uint32_t elapsed_time, recv_len; ip_addr_t target_addr; esp_ping_get_profile(hdl, ESP_PING_PROF_SEQNO, &seqno, sizeof(seqno)); esp_ping_get_profile(hdl, ESP_PING_PROF_TTL, &ttl, sizeof(ttl)); esp_ping_get_profile(hdl, ESP_PING_PROF_IPADDR, &target_addr, sizeof(target_addr)); esp_ping_get_profile(hdl, ESP_PING_PROF_SIZE, &recv_len, sizeof(recv_len)); esp_ping_get_profile(hdl, ESP_PING_PROF_TIMEGAP, &elapsed_time, sizeof(elapsed_time)); printf("%d bytes from %s icmp_seq=%d ttl=%d time=%d ms\n", recv_len, inet_ntoa(target_addr.u_addr.ip4), seqno, ttl, elapsed_time); } static void test_on_ping_timeout(esp_ping_handle_t hdl, void *args) { uint16_t seqno; ip_addr_t target_addr; esp_ping_get_profile(hdl, ESP_PING_PROF_SEQNO, &seqno, sizeof(seqno)); esp_ping_get_profile(hdl, ESP_PING_PROF_IPADDR, &target_addr, sizeof(target_addr)); printf("From %s icmp_seq=%d timeout\n", inet_ntoa(target_addr.u_addr.ip4), seqno); } static void test_on_ping_end(esp_ping_handle_t hdl, void *args) { uint32_t transmitted; uint32_t received; uint32_t total_time_ms; esp_ping_get_profile(hdl, ESP_PING_PROF_REQUEST, &transmitted, sizeof(transmitted)); esp_ping_get_profile(hdl, ESP_PING_PROF_REPLY, &received, sizeof(received)); esp_ping_get_profile(hdl, ESP_PING_PROF_DURATION, &total_time_ms, sizeof(total_time_ms)); printf("%d packets transmitted, %d received, time %dms\n", transmitted, received, total_time_ms); } void initialize_ping() { /* convert URL to IP address */ ip_addr_t target_addr; struct addrinfo hint; struct addrinfo *res = NULL; memset(&hint, 0, sizeof(hint)); memset(&target_addr, 0, sizeof(target_addr)); getaddrinfo("www.espressif.com", NULL, &hint, &res); struct in_addr addr4 = ((struct sockaddr_in *) (res->ai_addr))->sin_addr; inet_addr_to_ip4addr(ip_2_ip4(&target_addr), &addr4); freeaddrinfo(res); esp_ping_config_t ping_config = ESP_PING_DEFAULT_CONFIG(); ping_config.target_addr = target_addr; // target IP address ping_config.count = ESP_PING_COUNT_INFINITE; // ping in infinite mode, esp_ping_stop can stop it /* set callback functions */ esp_ping_callbacks_t cbs; cbs.on_ping_success = test_on_ping_success; cbs.on_ping_timeout = test_on_ping_timeout; cbs.on_ping_end = test_on_ping_end; cbs.cb_args = "foo"; // arguments that feeds to all callback functions, can be NULL cbs.cb_args = eth_event_group; esp_ping_handle_t ping; esp_ping_new_session(&ping_config, &cbs, &ping); } Start and Stop Ping Session You can start and stop ping session with the handle returned by esp_ping_new_session . Note that, the ping session does not start automatically after creation. If the ping session is stopped, and restart again, the sequence number in ICMP packets will recount from zero again. Delete a Ping Session If a ping session will not be used any more, you can delete it with esp_ping_delete_session . Please make sure the ping session is in stop state (i.e., you have called esp_ping_stop before or the ping session has finished all the procedures) when you call this function. Get Runtime Statistics As the example code above, you can call esp_ping_get_profile to get different runtime statistics of ping session in the callback function. Application Example ICMP echo example: protocols/icmp_echo API Reference Header File This header file can be included with: #include "ping/ping_sock.h" This header file is a part of the API provided by the lwip component. To declare that your component depends on lwip , add the following to your CMakeLists.txt: REQUIRES lwip or PRIV_REQUIRES lwip Functions esp_err_t esp_ping_new_session(const esp_ping_config_t *config, const esp_ping_callbacks_t *cbs, esp_ping_handle_t *hdl_out) Create a ping session. Parameters config -- ping configuration cbs -- a bunch of callback functions invoked by internal ping task hdl_out -- handle of ping session config -- ping configuration cbs -- a bunch of callback functions invoked by internal ping task hdl_out -- handle of ping session config -- ping configuration Returns ESP_ERR_INVALID_ARG: invalid parameters (e.g. configuration is null, etc) ESP_ERR_NO_MEM: out of memory ESP_FAIL: other internal error (e.g. socket error) ESP_OK: create ping session successfully, user can take the ping handle to do follow-on jobs ESP_ERR_INVALID_ARG: invalid parameters (e.g. configuration is null, etc) ESP_ERR_NO_MEM: out of memory ESP_FAIL: other internal error (e.g. socket error) ESP_OK: create ping session successfully, user can take the ping handle to do follow-on jobs ESP_ERR_INVALID_ARG: invalid parameters (e.g. configuration is null, etc) Parameters config -- ping configuration cbs -- a bunch of callback functions invoked by internal ping task hdl_out -- handle of ping session Returns ESP_ERR_INVALID_ARG: invalid parameters (e.g. configuration is null, etc) ESP_ERR_NO_MEM: out of memory ESP_FAIL: other internal error (e.g. socket error) ESP_OK: create ping session successfully, user can take the ping handle to do follow-on jobs esp_err_t esp_ping_delete_session(esp_ping_handle_t hdl) Delete a ping session. Parameters hdl -- handle of ping session Returns ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_OK: delete ping session successfully ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_OK: delete ping session successfully ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) Parameters hdl -- handle of ping session Returns ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_OK: delete ping session successfully esp_err_t esp_ping_start(esp_ping_handle_t hdl) Start the ping session. Parameters hdl -- handle of ping session Returns ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_OK: start ping session successfully ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_OK: start ping session successfully ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) Parameters hdl -- handle of ping session Returns ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_OK: start ping session successfully esp_err_t esp_ping_stop(esp_ping_handle_t hdl) Stop the ping session. Parameters hdl -- handle of ping session Returns ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_OK: stop ping session successfully ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_OK: stop ping session successfully ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) Parameters hdl -- handle of ping session Returns ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_OK: stop ping session successfully esp_err_t esp_ping_get_profile(esp_ping_handle_t hdl, esp_ping_profile_t profile, void *data, uint32_t size) Get runtime profile of ping session. Parameters hdl -- handle of ping session profile -- type of profile data -- profile data size -- profile data size hdl -- handle of ping session profile -- type of profile data -- profile data size -- profile data size hdl -- handle of ping session Returns ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_ERR_INVALID_SIZE: the actual profile data size doesn't match the "size" parameter ESP_OK: get profile successfully ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_ERR_INVALID_SIZE: the actual profile data size doesn't match the "size" parameter ESP_OK: get profile successfully ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) Parameters hdl -- handle of ping session profile -- type of profile data -- profile data size -- profile data size Returns ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_ERR_INVALID_SIZE: the actual profile data size doesn't match the "size" parameter ESP_OK: get profile successfully Structures struct esp_ping_callbacks_t Type of "ping" callback functions. Public Members void *cb_args arguments for callback functions void *cb_args arguments for callback functions void (*on_ping_success)(esp_ping_handle_t hdl, void *args) Invoked by internal ping thread when received ICMP echo reply packet. void (*on_ping_success)(esp_ping_handle_t hdl, void *args) Invoked by internal ping thread when received ICMP echo reply packet. void (*on_ping_timeout)(esp_ping_handle_t hdl, void *args) Invoked by internal ping thread when receive ICMP echo reply packet timeout. void (*on_ping_timeout)(esp_ping_handle_t hdl, void *args) Invoked by internal ping thread when receive ICMP echo reply packet timeout. void (*on_ping_end)(esp_ping_handle_t hdl, void *args) Invoked by internal ping thread when a ping session is finished. void (*on_ping_end)(esp_ping_handle_t hdl, void *args) Invoked by internal ping thread when a ping session is finished. void *cb_args struct esp_ping_config_t Type of "ping" configuration. Public Members uint32_t count A "ping" session contains count procedures uint32_t count A "ping" session contains count procedures uint32_t interval_ms Milliseconds between each ping procedure uint32_t interval_ms Milliseconds between each ping procedure uint32_t timeout_ms Timeout value (in milliseconds) of each ping procedure uint32_t timeout_ms Timeout value (in milliseconds) of each ping procedure uint32_t data_size Size of the data next to ICMP packet header uint32_t data_size Size of the data next to ICMP packet header int tos Type of Service, a field specified in the IP header int tos Type of Service, a field specified in the IP header int ttl Time to Live,a field specified in the IP header int ttl Time to Live,a field specified in the IP header ip_addr_t target_addr Target IP address, either IPv4 or IPv6 ip_addr_t target_addr Target IP address, either IPv4 or IPv6 uint32_t task_stack_size Stack size of internal ping task uint32_t task_stack_size Stack size of internal ping task uint32_t task_prio Priority of internal ping task uint32_t task_prio Priority of internal ping task uint32_t interface Netif index, interface=0 means NETIF_NO_INDEX uint32_t interface Netif index, interface=0 means NETIF_NO_INDEX uint32_t count Macros ESP_PING_DEFAULT_CONFIG() Default ping configuration. ESP_PING_COUNT_INFINITE Set ping count to zero will ping target infinitely Type Definitions typedef void *esp_ping_handle_t Type of "ping" session handle. Enumerations enum esp_ping_profile_t Profile of ping session. Values: enumerator ESP_PING_PROF_SEQNO Sequence number of a ping procedure enumerator ESP_PING_PROF_SEQNO Sequence number of a ping procedure enumerator ESP_PING_PROF_TOS Type of service of a ping procedure enumerator ESP_PING_PROF_TOS Type of service of a ping procedure enumerator ESP_PING_PROF_TTL Time to live of a ping procedure enumerator ESP_PING_PROF_TTL Time to live of a ping procedure enumerator ESP_PING_PROF_REQUEST Number of request packets sent out enumerator ESP_PING_PROF_REQUEST Number of request packets sent out enumerator ESP_PING_PROF_REPLY Number of reply packets received enumerator ESP_PING_PROF_REPLY Number of reply packets received enumerator ESP_PING_PROF_IPADDR IP address of replied target enumerator ESP_PING_PROF_IPADDR IP address of replied target enumerator ESP_PING_PROF_SIZE Size of received packet enumerator ESP_PING_PROF_SIZE Size of received packet enumerator ESP_PING_PROF_TIMEGAP Elapsed time between request and reply packet enumerator ESP_PING_PROF_TIMEGAP Elapsed time between request and reply packet enumerator ESP_PING_PROF_DURATION Elapsed time of the whole ping session enumerator ESP_PING_PROF_DURATION Elapsed time of the whole ping session enumerator ESP_PING_PROF_SEQNO
ICMP Echo Overview ICMP (Internet Control Message Protocol) is used for diagnostic or control purposes or generated in response to errors in IP operations. The common network util ping is implemented based on the ICMP packets with the type field value of 0, also called Echo Reply. During a ping session, the source host firstly sends out an ICMP echo request packet and wait for an ICMP echo reply with specific times. In this way, it also measures the round-trip time for the messages. After receiving a valid ICMP echo reply, the source host will generate statistics about the IP link layer (e.g., packet loss, elapsed time, etc). It is common that IoT device needs to check whether a remote server is alive or not. The device should show the warnings to users when it got offline. It can be achieved by creating a ping session and sending or parsing ICMP echo packets periodically. To make this internal procedure much easier for users, ESP-IDF provides some out-of-box APIs. Create a New Ping Session To create a ping session, you need to fill in the esp_ping_config_t configuration structure firstly, specifying target IP address, interval times, and etc. Optionally, you can also register some callback functions with the esp_ping_callbacks_t structure. Example method to create a new ping session and register callbacks: static void test_on_ping_success(esp_ping_handle_t hdl, void *args) { // optionally, get callback arguments // const char* str = (const char*) args; // printf("%s\r\n", str); // "foo" uint8_t ttl; uint16_t seqno; uint32_t elapsed_time, recv_len; ip_addr_t target_addr; esp_ping_get_profile(hdl, ESP_PING_PROF_SEQNO, &seqno, sizeof(seqno)); esp_ping_get_profile(hdl, ESP_PING_PROF_TTL, &ttl, sizeof(ttl)); esp_ping_get_profile(hdl, ESP_PING_PROF_IPADDR, &target_addr, sizeof(target_addr)); esp_ping_get_profile(hdl, ESP_PING_PROF_SIZE, &recv_len, sizeof(recv_len)); esp_ping_get_profile(hdl, ESP_PING_PROF_TIMEGAP, &elapsed_time, sizeof(elapsed_time)); printf("%d bytes from %s icmp_seq=%d ttl=%d time=%d ms\n", recv_len, inet_ntoa(target_addr.u_addr.ip4), seqno, ttl, elapsed_time); } static void test_on_ping_timeout(esp_ping_handle_t hdl, void *args) { uint16_t seqno; ip_addr_t target_addr; esp_ping_get_profile(hdl, ESP_PING_PROF_SEQNO, &seqno, sizeof(seqno)); esp_ping_get_profile(hdl, ESP_PING_PROF_IPADDR, &target_addr, sizeof(target_addr)); printf("From %s icmp_seq=%d timeout\n", inet_ntoa(target_addr.u_addr.ip4), seqno); } static void test_on_ping_end(esp_ping_handle_t hdl, void *args) { uint32_t transmitted; uint32_t received; uint32_t total_time_ms; esp_ping_get_profile(hdl, ESP_PING_PROF_REQUEST, &transmitted, sizeof(transmitted)); esp_ping_get_profile(hdl, ESP_PING_PROF_REPLY, &received, sizeof(received)); esp_ping_get_profile(hdl, ESP_PING_PROF_DURATION, &total_time_ms, sizeof(total_time_ms)); printf("%d packets transmitted, %d received, time %dms\n", transmitted, received, total_time_ms); } void initialize_ping() { /* convert URL to IP address */ ip_addr_t target_addr; struct addrinfo hint; struct addrinfo *res = NULL; memset(&hint, 0, sizeof(hint)); memset(&target_addr, 0, sizeof(target_addr)); getaddrinfo("www.espressif.com", NULL, &hint, &res); struct in_addr addr4 = ((struct sockaddr_in *) (res->ai_addr))->sin_addr; inet_addr_to_ip4addr(ip_2_ip4(&target_addr), &addr4); freeaddrinfo(res); esp_ping_config_t ping_config = ESP_PING_DEFAULT_CONFIG(); ping_config.target_addr = target_addr; // target IP address ping_config.count = ESP_PING_COUNT_INFINITE; // ping in infinite mode, esp_ping_stop can stop it /* set callback functions */ esp_ping_callbacks_t cbs; cbs.on_ping_success = test_on_ping_success; cbs.on_ping_timeout = test_on_ping_timeout; cbs.on_ping_end = test_on_ping_end; cbs.cb_args = "foo"; // arguments that feeds to all callback functions, can be NULL cbs.cb_args = eth_event_group; esp_ping_handle_t ping; esp_ping_new_session(&ping_config, &cbs, &ping); } Start and Stop Ping Session You can start and stop ping session with the handle returned by esp_ping_new_session. Note that, the ping session does not start automatically after creation. If the ping session is stopped, and restart again, the sequence number in ICMP packets will recount from zero again. Delete a Ping Session If a ping session will not be used any more, you can delete it with esp_ping_delete_session. Please make sure the ping session is in stop state (i.e., you have called esp_ping_stop before or the ping session has finished all the procedures) when you call this function. Get Runtime Statistics As the example code above, you can call esp_ping_get_profile to get different runtime statistics of ping session in the callback function. Application Example ICMP echo example: protocols/icmp_echo API Reference Header File This header file can be included with: #include "ping/ping_sock.h" This header file is a part of the API provided by the lwipcomponent. To declare that your component depends on lwip, add the following to your CMakeLists.txt: REQUIRES lwip or PRIV_REQUIRES lwip Functions - esp_err_t esp_ping_new_session(const esp_ping_config_t *config, const esp_ping_callbacks_t *cbs, esp_ping_handle_t *hdl_out) Create a ping session. - Parameters config -- ping configuration cbs -- a bunch of callback functions invoked by internal ping task hdl_out -- handle of ping session - - Returns ESP_ERR_INVALID_ARG: invalid parameters (e.g. configuration is null, etc) ESP_ERR_NO_MEM: out of memory ESP_FAIL: other internal error (e.g. socket error) ESP_OK: create ping session successfully, user can take the ping handle to do follow-on jobs - - esp_err_t esp_ping_delete_session(esp_ping_handle_t hdl) Delete a ping session. - Parameters hdl -- handle of ping session - Returns ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_OK: delete ping session successfully - - esp_err_t esp_ping_start(esp_ping_handle_t hdl) Start the ping session. - Parameters hdl -- handle of ping session - Returns ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_OK: start ping session successfully - - esp_err_t esp_ping_stop(esp_ping_handle_t hdl) Stop the ping session. - Parameters hdl -- handle of ping session - Returns ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_OK: stop ping session successfully - - esp_err_t esp_ping_get_profile(esp_ping_handle_t hdl, esp_ping_profile_t profile, void *data, uint32_t size) Get runtime profile of ping session. - Parameters hdl -- handle of ping session profile -- type of profile data -- profile data size -- profile data size - - Returns ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc) ESP_ERR_INVALID_SIZE: the actual profile data size doesn't match the "size" parameter ESP_OK: get profile successfully - Structures - struct esp_ping_callbacks_t Type of "ping" callback functions. Public Members - void *cb_args arguments for callback functions - void (*on_ping_success)(esp_ping_handle_t hdl, void *args) Invoked by internal ping thread when received ICMP echo reply packet. - void (*on_ping_timeout)(esp_ping_handle_t hdl, void *args) Invoked by internal ping thread when receive ICMP echo reply packet timeout. - void (*on_ping_end)(esp_ping_handle_t hdl, void *args) Invoked by internal ping thread when a ping session is finished. - void *cb_args - struct esp_ping_config_t Type of "ping" configuration. Public Members - uint32_t count A "ping" session contains count procedures - uint32_t interval_ms Milliseconds between each ping procedure - uint32_t timeout_ms Timeout value (in milliseconds) of each ping procedure - uint32_t data_size Size of the data next to ICMP packet header - int tos Type of Service, a field specified in the IP header - int ttl Time to Live,a field specified in the IP header - ip_addr_t target_addr Target IP address, either IPv4 or IPv6 - uint32_t task_stack_size Stack size of internal ping task - uint32_t task_prio Priority of internal ping task - uint32_t interface Netif index, interface=0 means NETIF_NO_INDEX - uint32_t count Macros - ESP_PING_DEFAULT_CONFIG() Default ping configuration. - ESP_PING_COUNT_INFINITE Set ping count to zero will ping target infinitely Type Definitions - typedef void *esp_ping_handle_t Type of "ping" session handle. Enumerations - enum esp_ping_profile_t Profile of ping session. Values: - enumerator ESP_PING_PROF_SEQNO Sequence number of a ping procedure - enumerator ESP_PING_PROF_TOS Type of service of a ping procedure - enumerator ESP_PING_PROF_TTL Time to live of a ping procedure - enumerator ESP_PING_PROF_REQUEST Number of request packets sent out - enumerator ESP_PING_PROF_REPLY Number of reply packets received - enumerator ESP_PING_PROF_IPADDR IP address of replied target - enumerator ESP_PING_PROF_SIZE Size of received packet - enumerator ESP_PING_PROF_TIMEGAP Elapsed time between request and reply packet - enumerator ESP_PING_PROF_DURATION Elapsed time of the whole ping session - enumerator ESP_PING_PROF_SEQNO
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/protocols/icmp_echo.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Mbed TLS
null
espressif.com
2016-01-01
6e16f81f49428ad4
null
null
Mbed TLS Mbed TLS is a C library that implements cryptographic primitives, X.509 certificate manipulation and the SSL/TLS and DTLS protocols. Its small code footprint makes it suitable for embedded systems. Note ESP-IDF uses a fork of Mbed TLS which includes a few patches (related to hardware routines of certain modules like bignum (MPI) and ECC ) over vanilla Mbed TLS. Mbed TLS supports SSL 3.0 up to TLS 1.3 and DTLS 1.0 to 1.2 communication by providing the following: TCP/IP communication functions: listen, connect, accept, read/write. SSL/TLS communication functions: init, handshake, read/write. X.509 functions: CRT, CRL and key handling Random number generation Hashing Encryption/decryption Supported TLS versions include SSL 3.0, TLS 1.0, TLS 1.1, TLS 1.2, and TLS 1.3, but on the latest ESP-IDF, SSL 3.0, TLS 1.0, and TLS 1.1 have been removed from Mbed TLS. Supported DTLS versions include DTLS 1.0, DTLS 1.1, and DTLS 1.2, but on the latest ESP-IDF, DTLS 1.0 has been removed from Mbed TLS. Mbed TLS Documentation For Mbed TLS documentation please refer to the following (upstream) pointers: Mbed TLS Support in ESP-IDF Please find the information about the Mbed TLS versions presented in different branches of ESP-IDF here. Note Please refer the Mbed TLS to migrate from Mbed TLS version 2.x to version 3.0 or greater. Application Examples Examples in ESP-IDF use ESP-TLS which provides a simplified API interface for accessing the commonly used TLS functionality. Refer to the examples protocols/https_server/simple (Simple HTTPS server) and protocols/https_request (Make HTTPS requests) for more information. If the Mbed TLS API is to be used directly, refer to the example protocols/https_mbedtls. Alternatives ESP-TLS acts as an abstraction layer over the underlying SSL/TLS library and thus has an option to use Mbed TLS or wolfSSL as the underlying library. By default, only Mbed TLS is available and used in ESP-IDF whereas wolfSSL is available publicly at <https://github.com/espressif/esp-wolfSSL> with the upstream submodule pointer. Please refer to ESP-TLS: Underlying SSL/TLS Library Options docs for more information on this and comparison of Mbed TLS and wolfSSL. Important Config Options Following is a brief list of important config options accessible at Component Config -> mbedTLS . The full list of config options can be found here. CONFIG_MBEDTLS_SSL_PROTO_TLS1_2: Support for TLS 1.2 CONFIG_MBEDTLS_SSL_PROTO_TLS1_3: Support for TLS 1.3 CONFIG_MBEDTLS_CERTIFICATE_BUNDLE: Support for trusted root certificate bundle (more about this: ESP x509 Certificate Bundle) CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS: Support for TLS Session Resumption: Client session tickets CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS: Support for TLS Session Resumption: Server session tickets CONFIG_MBEDTLS_HARDWARE_SHA: Support for hardware SHA acceleration CONFIG_MBEDTLS_HARDWARE_AES: Support for hardware AES acceleration CONFIG_MBEDTLS_HARDWARE_MPI: Support for hardware MPI (bignum) acceleration Note Mbed TLS v3.0.0 and later support only TLS 1.2 and TLS 1.3 (SSL 3.0, TLS 1.0, TLS 1.1, and DTLS 1.0 are not supported). The support for TLS 1.3 is experimental and only supports the client-side. More information about this can be found out here. Performance and Memory Tweaks Reducing Heap Usage The following table shows typical memory usage with different configs when the protocols/https_request example (with Server Validation enabled) was run with Mbed TLS as the SSL/TLS library. Mbed TLS Test Related Configs Heap Usage (approx.) Default NA 42196 B Enable SSL Variable Length 42120 B Disable Keep Peer Certificate 38533 B Enable Dynamic TX/RX Buffer CONFIG_MBEDTLS_DYNAMIC_BUFFER CONFIG_MBEDTLS_DYNAMIC_FREE_CONFIG_DATA CONFIG_MBEDTLS_DYNAMIC_FREE_CA_CERT 22013 B Note These values are subject to change with change in configuration options and versions of Mbed TLS. Reducing Binary Size Under Component Config -> mbedTLS , there are multiple Mbed TLS features which are enabled by default but can be disabled if not needed to save code size. More information can be about this can be found in Minimizing Binary Size docs.
Mbed TLS Mbed TLS is a C library that implements cryptographic primitives, X.509 certificate manipulation and the SSL/TLS and DTLS protocols. Its small code footprint makes it suitable for embedded systems. Note ESP-IDF uses a fork of Mbed TLS which includes a few patches (related to hardware routines of certain modules like bignum (MPI) and ECC) over vanilla Mbed TLS. Mbed TLS supports SSL 3.0 up to TLS 1.3 and DTLS 1.0 to 1.2 communication by providing the following: TCP/IP communication functions: listen, connect, accept, read/write. SSL/TLS communication functions: init, handshake, read/write. X.509 functions: CRT, CRL and key handling Random number generation Hashing Encryption/decryption Supported TLS versions include SSL 3.0, TLS 1.0, TLS 1.1, TLS 1.2, and TLS 1.3, but on the latest ESP-IDF, SSL 3.0, TLS 1.0, and TLS 1.1 have been removed from Mbed TLS. Supported DTLS versions include DTLS 1.0, DTLS 1.1, and DTLS 1.2, but on the latest ESP-IDF, DTLS 1.0 has been removed from Mbed TLS. Mbed TLS Documentation For Mbed TLS documentation please refer to the following (upstream) pointers: Mbed TLS Support in ESP-IDF Please find the information about the Mbed TLS versions presented in different branches of ESP-IDF here. Note Please refer the Mbed TLS to migrate from Mbed TLS version 2.x to version 3.0 or greater. Application Examples Examples in ESP-IDF use ESP-TLS which provides a simplified API interface for accessing the commonly used TLS functionality. Refer to the examples protocols/https_server/simple (Simple HTTPS server) and protocols/https_request (Make HTTPS requests) for more information. If the Mbed TLS API is to be used directly, refer to the example protocols/https_mbedtls. Alternatives ESP-TLS acts as an abstraction layer over the underlying SSL/TLS library and thus has an option to use Mbed TLS or wolfSSL as the underlying library. By default, only Mbed TLS is available and used in ESP-IDF whereas wolfSSL is available publicly at <https://github.com/espressif/esp-wolfSSL> with the upstream submodule pointer. Please refer to ESP-TLS: Underlying SSL/TLS Library Options docs for more information on this and comparison of Mbed TLS and wolfSSL. Important Config Options Following is a brief list of important config options accessible at Component Config -> mbedTLS. The full list of config options can be found here. CONFIG_MBEDTLS_SSL_PROTO_TLS1_2: Support for TLS 1.2 CONFIG_MBEDTLS_SSL_PROTO_TLS1_3: Support for TLS 1.3 CONFIG_MBEDTLS_CERTIFICATE_BUNDLE: Support for trusted root certificate bundle (more about this: ESP x509 Certificate Bundle) CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS: Support for TLS Session Resumption: Client session tickets CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS: Support for TLS Session Resumption: Server session tickets CONFIG_MBEDTLS_HARDWARE_SHA: Support for hardware SHA acceleration CONFIG_MBEDTLS_HARDWARE_AES: Support for hardware AES acceleration CONFIG_MBEDTLS_HARDWARE_MPI: Support for hardware MPI (bignum) acceleration Note Mbed TLS v3.0.0 and later support only TLS 1.2 and TLS 1.3 (SSL 3.0, TLS 1.0, TLS 1.1, and DTLS 1.0 are not supported). The support for TLS 1.3 is experimental and only supports the client-side. More information about this can be found out here. Performance and Memory Tweaks Reducing Heap Usage The following table shows typical memory usage with different configs when the protocols/https_request example (with Server Validation enabled) was run with Mbed TLS as the SSL/TLS library. | Mbed TLS Test | Related Configs | Heap Usage (approx.) | Default | NA | 42196 B | Enable SSL Variable Length | 42120 B | Disable Keep Peer Certificate | 38533 B | Enable Dynamic TX/RX Buffer | CONFIG_MBEDTLS_DYNAMIC_BUFFER CONFIG_MBEDTLS_DYNAMIC_FREE_CONFIG_DATA CONFIG_MBEDTLS_DYNAMIC_FREE_CA_CERT | 22013 B Note These values are subject to change with change in configuration options and versions of Mbed TLS. Reducing Binary Size Under Component Config -> mbedTLS, there are multiple Mbed TLS features which are enabled by default but can be disabled if not needed to save code size. More information can be about this can be found in Minimizing Binary Size docs.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/protocols/mbedtls.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Bluetooth® Generic Defines
null
espressif.com
2016-01-01
758f3be2c2aa841
null
null
Bluetooth® Generic Defines API Reference Header File This header file can be included with: #include "esp_bt_defs.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Structures struct esp_bt_uuid_t UUID type. Macros ESP_BLUEDROID_STATUS_CHECK(status) ESP_BT_STATUS_BASE_FOR_HCI_ERR ESP_BT_OCTET16_LEN ESP_BT_OCTET8_LEN ESP_DEFAULT_GATT_IF Default GATT interface id. ESP_BLE_PRIM_ADV_INT_MIN Minimum advertising interval for undirected and low duty cycle directed advertising ESP_BLE_PRIM_ADV_INT_MAX Maximum advertising interval for undirected and low duty cycle directed advertising ESP_BLE_CONN_INT_MIN relate to BTM_BLE_CONN_INT_MIN in stack/btm_ble_api.h ESP_BLE_CONN_INT_MAX relate to BTM_BLE_CONN_INT_MAX in stack/btm_ble_api.h ESP_BLE_CONN_LATENCY_MAX relate to ESP_BLE_CONN_LATENCY_MAX in stack/btm_ble_api.h ESP_BLE_CONN_SUP_TOUT_MIN relate to BTM_BLE_CONN_SUP_TOUT_MIN in stack/btm_ble_api.h ESP_BLE_CONN_SUP_TOUT_MAX relate to ESP_BLE_CONN_SUP_TOUT_MAX in stack/btm_ble_api.h ESP_BLE_IS_VALID_PARAM(x, min, max) Check the param is valid or not. ESP_UUID_LEN_16 ESP_UUID_LEN_32 ESP_UUID_LEN_128 ESP_BD_ADDR_LEN Bluetooth address length. ESP_BLE_ENC_KEY_MASK Used to exchange the encryption key in the init key & response key. ESP_BLE_ID_KEY_MASK Used to exchange the IRK key in the init key & response key. ESP_BLE_CSR_KEY_MASK Used to exchange the CSRK key in the init key & response key. ESP_BLE_LINK_KEY_MASK Used to exchange the link key(this key just used in the BLE & BR/EDR coexist mode) in the init key & response key. ESP_APP_ID_MIN Minimum of the application id. ESP_APP_ID_MAX Maximum of the application id. ESP_BD_ADDR_STR ESP_BD_ADDR_HEX(addr) Type Definitions typedef uint8_t esp_bt_octet16_t[ESP_BT_OCTET16_LEN] typedef uint8_t esp_bt_octet8_t[ESP_BT_OCTET8_LEN] typedef uint8_t esp_link_key[ESP_BT_OCTET16_LEN] typedef uint8_t esp_bd_addr_t[ESP_BD_ADDR_LEN] Bluetooth device address. typedef uint8_t esp_ble_key_mask_t Enumerations enum esp_bt_status_t Status Return Value. Values: enumerator ESP_BT_STATUS_SUCCESS enumerator ESP_BT_STATUS_SUCCESS enumerator ESP_BT_STATUS_FAIL enumerator ESP_BT_STATUS_FAIL enumerator ESP_BT_STATUS_NOT_READY enumerator ESP_BT_STATUS_NOT_READY enumerator ESP_BT_STATUS_NOMEM enumerator ESP_BT_STATUS_NOMEM enumerator ESP_BT_STATUS_BUSY enumerator ESP_BT_STATUS_BUSY enumerator ESP_BT_STATUS_DONE enumerator ESP_BT_STATUS_DONE enumerator ESP_BT_STATUS_UNSUPPORTED enumerator ESP_BT_STATUS_UNSUPPORTED enumerator ESP_BT_STATUS_PARM_INVALID enumerator ESP_BT_STATUS_PARM_INVALID enumerator ESP_BT_STATUS_UNHANDLED enumerator ESP_BT_STATUS_UNHANDLED enumerator ESP_BT_STATUS_AUTH_FAILURE enumerator ESP_BT_STATUS_AUTH_FAILURE enumerator ESP_BT_STATUS_RMT_DEV_DOWN enumerator ESP_BT_STATUS_RMT_DEV_DOWN enumerator ESP_BT_STATUS_AUTH_REJECTED enumerator ESP_BT_STATUS_AUTH_REJECTED enumerator ESP_BT_STATUS_INVALID_STATIC_RAND_ADDR enumerator ESP_BT_STATUS_INVALID_STATIC_RAND_ADDR enumerator ESP_BT_STATUS_PENDING enumerator ESP_BT_STATUS_PENDING enumerator ESP_BT_STATUS_UNACCEPT_CONN_INTERVAL enumerator ESP_BT_STATUS_UNACCEPT_CONN_INTERVAL enumerator ESP_BT_STATUS_PARAM_OUT_OF_RANGE enumerator ESP_BT_STATUS_PARAM_OUT_OF_RANGE enumerator ESP_BT_STATUS_TIMEOUT enumerator ESP_BT_STATUS_TIMEOUT enumerator ESP_BT_STATUS_PEER_LE_DATA_LEN_UNSUPPORTED enumerator ESP_BT_STATUS_PEER_LE_DATA_LEN_UNSUPPORTED enumerator ESP_BT_STATUS_CONTROL_LE_DATA_LEN_UNSUPPORTED enumerator ESP_BT_STATUS_CONTROL_LE_DATA_LEN_UNSUPPORTED enumerator ESP_BT_STATUS_ERR_ILLEGAL_PARAMETER_FMT enumerator ESP_BT_STATUS_ERR_ILLEGAL_PARAMETER_FMT enumerator ESP_BT_STATUS_MEMORY_FULL enumerator ESP_BT_STATUS_MEMORY_FULL enumerator ESP_BT_STATUS_EIR_TOO_LARGE enumerator ESP_BT_STATUS_EIR_TOO_LARGE enumerator ESP_BT_STATUS_HCI_SUCCESS enumerator ESP_BT_STATUS_HCI_SUCCESS enumerator ESP_BT_STATUS_HCI_ILLEGAL_COMMAND enumerator ESP_BT_STATUS_HCI_ILLEGAL_COMMAND enumerator ESP_BT_STATUS_HCI_NO_CONNECTION enumerator ESP_BT_STATUS_HCI_NO_CONNECTION enumerator ESP_BT_STATUS_HCI_HW_FAILURE enumerator ESP_BT_STATUS_HCI_HW_FAILURE enumerator ESP_BT_STATUS_HCI_PAGE_TIMEOUT enumerator ESP_BT_STATUS_HCI_PAGE_TIMEOUT enumerator ESP_BT_STATUS_HCI_AUTH_FAILURE enumerator ESP_BT_STATUS_HCI_AUTH_FAILURE enumerator ESP_BT_STATUS_HCI_KEY_MISSING enumerator ESP_BT_STATUS_HCI_KEY_MISSING enumerator ESP_BT_STATUS_HCI_MEMORY_FULL enumerator ESP_BT_STATUS_HCI_MEMORY_FULL enumerator ESP_BT_STATUS_HCI_CONNECTION_TOUT enumerator ESP_BT_STATUS_HCI_CONNECTION_TOUT enumerator ESP_BT_STATUS_HCI_MAX_NUM_OF_CONNECTIONS enumerator ESP_BT_STATUS_HCI_MAX_NUM_OF_CONNECTIONS enumerator ESP_BT_STATUS_HCI_MAX_NUM_OF_SCOS enumerator ESP_BT_STATUS_HCI_MAX_NUM_OF_SCOS enumerator ESP_BT_STATUS_HCI_CONNECTION_EXISTS enumerator ESP_BT_STATUS_HCI_CONNECTION_EXISTS enumerator ESP_BT_STATUS_HCI_COMMAND_DISALLOWED enumerator ESP_BT_STATUS_HCI_COMMAND_DISALLOWED enumerator ESP_BT_STATUS_HCI_HOST_REJECT_RESOURCES enumerator ESP_BT_STATUS_HCI_HOST_REJECT_RESOURCES enumerator ESP_BT_STATUS_HCI_HOST_REJECT_SECURITY enumerator ESP_BT_STATUS_HCI_HOST_REJECT_SECURITY enumerator ESP_BT_STATUS_HCI_HOST_REJECT_DEVICE enumerator ESP_BT_STATUS_HCI_HOST_REJECT_DEVICE enumerator ESP_BT_STATUS_HCI_HOST_TIMEOUT enumerator ESP_BT_STATUS_HCI_HOST_TIMEOUT enumerator ESP_BT_STATUS_HCI_UNSUPPORTED_VALUE enumerator ESP_BT_STATUS_HCI_UNSUPPORTED_VALUE enumerator ESP_BT_STATUS_HCI_ILLEGAL_PARAMETER_FMT enumerator ESP_BT_STATUS_HCI_ILLEGAL_PARAMETER_FMT enumerator ESP_BT_STATUS_HCI_PEER_USER enumerator ESP_BT_STATUS_HCI_PEER_USER enumerator ESP_BT_STATUS_HCI_PEER_LOW_RESOURCES enumerator ESP_BT_STATUS_HCI_PEER_LOW_RESOURCES enumerator ESP_BT_STATUS_HCI_PEER_POWER_OFF enumerator ESP_BT_STATUS_HCI_PEER_POWER_OFF enumerator ESP_BT_STATUS_HCI_CONN_CAUSE_LOCAL_HOST enumerator ESP_BT_STATUS_HCI_CONN_CAUSE_LOCAL_HOST enumerator ESP_BT_STATUS_HCI_REPEATED_ATTEMPTS enumerator ESP_BT_STATUS_HCI_REPEATED_ATTEMPTS enumerator ESP_BT_STATUS_HCI_PAIRING_NOT_ALLOWED enumerator ESP_BT_STATUS_HCI_PAIRING_NOT_ALLOWED enumerator ESP_BT_STATUS_HCI_UNKNOWN_LMP_PDU enumerator ESP_BT_STATUS_HCI_UNKNOWN_LMP_PDU enumerator ESP_BT_STATUS_HCI_UNSUPPORTED_REM_FEATURE enumerator ESP_BT_STATUS_HCI_UNSUPPORTED_REM_FEATURE enumerator ESP_BT_STATUS_HCI_SCO_OFFSET_REJECTED enumerator ESP_BT_STATUS_HCI_SCO_OFFSET_REJECTED enumerator ESP_BT_STATUS_HCI_SCO_INTERVAL_REJECTED enumerator ESP_BT_STATUS_HCI_SCO_INTERVAL_REJECTED enumerator ESP_BT_STATUS_HCI_SCO_AIR_MODE enumerator ESP_BT_STATUS_HCI_SCO_AIR_MODE enumerator ESP_BT_STATUS_HCI_INVALID_LMP_PARAM enumerator ESP_BT_STATUS_HCI_INVALID_LMP_PARAM enumerator ESP_BT_STATUS_HCI_UNSPECIFIED enumerator ESP_BT_STATUS_HCI_UNSPECIFIED enumerator ESP_BT_STATUS_HCI_UNSUPPORTED_LMP_PARAMETERS enumerator ESP_BT_STATUS_HCI_UNSUPPORTED_LMP_PARAMETERS enumerator ESP_BT_STATUS_HCI_ROLE_CHANGE_NOT_ALLOWED enumerator ESP_BT_STATUS_HCI_ROLE_CHANGE_NOT_ALLOWED enumerator ESP_BT_STATUS_HCI_LMP_RESPONSE_TIMEOUT enumerator ESP_BT_STATUS_HCI_LMP_RESPONSE_TIMEOUT enumerator ESP_BT_STATUS_HCI_LMP_ERR_TRANS_COLLISION enumerator ESP_BT_STATUS_HCI_LMP_ERR_TRANS_COLLISION enumerator ESP_BT_STATUS_HCI_LMP_PDU_NOT_ALLOWED enumerator ESP_BT_STATUS_HCI_LMP_PDU_NOT_ALLOWED enumerator ESP_BT_STATUS_HCI_ENCRY_MODE_NOT_ACCEPTABLE enumerator ESP_BT_STATUS_HCI_ENCRY_MODE_NOT_ACCEPTABLE enumerator ESP_BT_STATUS_HCI_UNIT_KEY_USED enumerator ESP_BT_STATUS_HCI_UNIT_KEY_USED enumerator ESP_BT_STATUS_HCI_QOS_NOT_SUPPORTED enumerator ESP_BT_STATUS_HCI_QOS_NOT_SUPPORTED enumerator ESP_BT_STATUS_HCI_INSTANT_PASSED enumerator ESP_BT_STATUS_HCI_INSTANT_PASSED enumerator ESP_BT_STATUS_HCI_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED enumerator ESP_BT_STATUS_HCI_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED enumerator ESP_BT_STATUS_HCI_DIFF_TRANSACTION_COLLISION enumerator ESP_BT_STATUS_HCI_DIFF_TRANSACTION_COLLISION enumerator ESP_BT_STATUS_HCI_UNDEFINED_0x2B enumerator ESP_BT_STATUS_HCI_UNDEFINED_0x2B enumerator ESP_BT_STATUS_HCI_QOS_UNACCEPTABLE_PARAM enumerator ESP_BT_STATUS_HCI_QOS_UNACCEPTABLE_PARAM enumerator ESP_BT_STATUS_HCI_QOS_REJECTED enumerator ESP_BT_STATUS_HCI_QOS_REJECTED enumerator ESP_BT_STATUS_HCI_CHAN_CLASSIF_NOT_SUPPORTED enumerator ESP_BT_STATUS_HCI_CHAN_CLASSIF_NOT_SUPPORTED enumerator ESP_BT_STATUS_HCI_INSUFFCIENT_SECURITY enumerator ESP_BT_STATUS_HCI_INSUFFCIENT_SECURITY enumerator ESP_BT_STATUS_HCI_PARAM_OUT_OF_RANGE enumerator ESP_BT_STATUS_HCI_PARAM_OUT_OF_RANGE enumerator ESP_BT_STATUS_HCI_UNDEFINED_0x31 enumerator ESP_BT_STATUS_HCI_UNDEFINED_0x31 enumerator ESP_BT_STATUS_HCI_ROLE_SWITCH_PENDING enumerator ESP_BT_STATUS_HCI_ROLE_SWITCH_PENDING enumerator ESP_BT_STATUS_HCI_UNDEFINED_0x33 enumerator ESP_BT_STATUS_HCI_UNDEFINED_0x33 enumerator ESP_BT_STATUS_HCI_RESERVED_SLOT_VIOLATION enumerator ESP_BT_STATUS_HCI_RESERVED_SLOT_VIOLATION enumerator ESP_BT_STATUS_HCI_ROLE_SWITCH_FAILED enumerator ESP_BT_STATUS_HCI_ROLE_SWITCH_FAILED enumerator ESP_BT_STATUS_HCI_INQ_RSP_DATA_TOO_LARGE enumerator ESP_BT_STATUS_HCI_INQ_RSP_DATA_TOO_LARGE enumerator ESP_BT_STATUS_HCI_SIMPLE_PAIRING_NOT_SUPPORTED enumerator ESP_BT_STATUS_HCI_SIMPLE_PAIRING_NOT_SUPPORTED enumerator ESP_BT_STATUS_HCI_HOST_BUSY_PAIRING enumerator ESP_BT_STATUS_HCI_HOST_BUSY_PAIRING enumerator ESP_BT_STATUS_HCI_REJ_NO_SUITABLE_CHANNEL enumerator ESP_BT_STATUS_HCI_REJ_NO_SUITABLE_CHANNEL enumerator ESP_BT_STATUS_HCI_CONTROLLER_BUSY enumerator ESP_BT_STATUS_HCI_CONTROLLER_BUSY enumerator ESP_BT_STATUS_HCI_UNACCEPT_CONN_INTERVAL enumerator ESP_BT_STATUS_HCI_UNACCEPT_CONN_INTERVAL enumerator ESP_BT_STATUS_HCI_DIRECTED_ADVERTISING_TIMEOUT enumerator ESP_BT_STATUS_HCI_DIRECTED_ADVERTISING_TIMEOUT enumerator ESP_BT_STATUS_HCI_CONN_TOUT_DUE_TO_MIC_FAILURE enumerator ESP_BT_STATUS_HCI_CONN_TOUT_DUE_TO_MIC_FAILURE enumerator ESP_BT_STATUS_HCI_CONN_FAILED_ESTABLISHMENT enumerator ESP_BT_STATUS_HCI_CONN_FAILED_ESTABLISHMENT enumerator ESP_BT_STATUS_HCI_MAC_CONNECTION_FAILED enumerator ESP_BT_STATUS_HCI_MAC_CONNECTION_FAILED enumerator ESP_BT_STATUS_SUCCESS enum esp_bt_dev_type_t Bluetooth device type. Values: enumerator ESP_BT_DEVICE_TYPE_BREDR enumerator ESP_BT_DEVICE_TYPE_BREDR enumerator ESP_BT_DEVICE_TYPE_BLE enumerator ESP_BT_DEVICE_TYPE_BLE enumerator ESP_BT_DEVICE_TYPE_DUMO enumerator ESP_BT_DEVICE_TYPE_DUMO enumerator ESP_BT_DEVICE_TYPE_BREDR enum esp_ble_addr_type_t BLE device address type. Values: enumerator BLE_ADDR_TYPE_PUBLIC Public Device Address enumerator BLE_ADDR_TYPE_PUBLIC Public Device Address enumerator BLE_ADDR_TYPE_RANDOM Random Device Address. To set this address, use the function esp_ble_gap_set_rand_addr(esp_bd_addr_t rand_addr) enumerator BLE_ADDR_TYPE_RANDOM Random Device Address. To set this address, use the function esp_ble_gap_set_rand_addr(esp_bd_addr_t rand_addr) enumerator BLE_ADDR_TYPE_RPA_PUBLIC Resolvable Private Address (RPA) with public identity address enumerator BLE_ADDR_TYPE_RPA_PUBLIC Resolvable Private Address (RPA) with public identity address enumerator BLE_ADDR_TYPE_RPA_RANDOM Resolvable Private Address (RPA) with random identity address. To set this address, use the function esp_ble_gap_set_rand_addr(esp_bd_addr_t rand_addr) enumerator BLE_ADDR_TYPE_RPA_RANDOM Resolvable Private Address (RPA) with random identity address. To set this address, use the function esp_ble_gap_set_rand_addr(esp_bd_addr_t rand_addr) enumerator BLE_ADDR_TYPE_PUBLIC
Bluetooth® Generic Defines API Reference Header File This header file can be included with: #include "esp_bt_defs.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Structures - struct esp_bt_uuid_t UUID type. Macros - ESP_BLUEDROID_STATUS_CHECK(status) - ESP_BT_STATUS_BASE_FOR_HCI_ERR - ESP_BT_OCTET16_LEN - ESP_BT_OCTET8_LEN - ESP_DEFAULT_GATT_IF Default GATT interface id. - ESP_BLE_PRIM_ADV_INT_MIN Minimum advertising interval for undirected and low duty cycle directed advertising - ESP_BLE_PRIM_ADV_INT_MAX Maximum advertising interval for undirected and low duty cycle directed advertising - ESP_BLE_CONN_INT_MIN relate to BTM_BLE_CONN_INT_MIN in stack/btm_ble_api.h - ESP_BLE_CONN_INT_MAX relate to BTM_BLE_CONN_INT_MAX in stack/btm_ble_api.h - ESP_BLE_CONN_LATENCY_MAX relate to ESP_BLE_CONN_LATENCY_MAX in stack/btm_ble_api.h - ESP_BLE_CONN_SUP_TOUT_MIN relate to BTM_BLE_CONN_SUP_TOUT_MIN in stack/btm_ble_api.h - ESP_BLE_CONN_SUP_TOUT_MAX relate to ESP_BLE_CONN_SUP_TOUT_MAX in stack/btm_ble_api.h - ESP_BLE_IS_VALID_PARAM(x, min, max) Check the param is valid or not. - ESP_UUID_LEN_16 - ESP_UUID_LEN_32 - ESP_UUID_LEN_128 - ESP_BD_ADDR_LEN Bluetooth address length. - ESP_BLE_ENC_KEY_MASK Used to exchange the encryption key in the init key & response key. - ESP_BLE_ID_KEY_MASK Used to exchange the IRK key in the init key & response key. - ESP_BLE_CSR_KEY_MASK Used to exchange the CSRK key in the init key & response key. - ESP_BLE_LINK_KEY_MASK Used to exchange the link key(this key just used in the BLE & BR/EDR coexist mode) in the init key & response key. - ESP_APP_ID_MIN Minimum of the application id. - ESP_APP_ID_MAX Maximum of the application id. - ESP_BD_ADDR_STR - ESP_BD_ADDR_HEX(addr) Type Definitions - typedef uint8_t esp_bt_octet16_t[ESP_BT_OCTET16_LEN] - typedef uint8_t esp_bt_octet8_t[ESP_BT_OCTET8_LEN] - typedef uint8_t esp_link_key[ESP_BT_OCTET16_LEN] - typedef uint8_t esp_bd_addr_t[ESP_BD_ADDR_LEN] Bluetooth device address. - typedef uint8_t esp_ble_key_mask_t Enumerations - enum esp_bt_status_t Status Return Value. Values: - enumerator ESP_BT_STATUS_SUCCESS - enumerator ESP_BT_STATUS_FAIL - enumerator ESP_BT_STATUS_NOT_READY - enumerator ESP_BT_STATUS_NOMEM - enumerator ESP_BT_STATUS_BUSY - enumerator ESP_BT_STATUS_DONE - enumerator ESP_BT_STATUS_UNSUPPORTED - enumerator ESP_BT_STATUS_PARM_INVALID - enumerator ESP_BT_STATUS_UNHANDLED - enumerator ESP_BT_STATUS_AUTH_FAILURE - enumerator ESP_BT_STATUS_RMT_DEV_DOWN - enumerator ESP_BT_STATUS_AUTH_REJECTED - enumerator ESP_BT_STATUS_INVALID_STATIC_RAND_ADDR - enumerator ESP_BT_STATUS_PENDING - enumerator ESP_BT_STATUS_UNACCEPT_CONN_INTERVAL - enumerator ESP_BT_STATUS_PARAM_OUT_OF_RANGE - enumerator ESP_BT_STATUS_TIMEOUT - enumerator ESP_BT_STATUS_PEER_LE_DATA_LEN_UNSUPPORTED - enumerator ESP_BT_STATUS_CONTROL_LE_DATA_LEN_UNSUPPORTED - enumerator ESP_BT_STATUS_ERR_ILLEGAL_PARAMETER_FMT - enumerator ESP_BT_STATUS_MEMORY_FULL - enumerator ESP_BT_STATUS_EIR_TOO_LARGE - enumerator ESP_BT_STATUS_HCI_SUCCESS - enumerator ESP_BT_STATUS_HCI_ILLEGAL_COMMAND - enumerator ESP_BT_STATUS_HCI_NO_CONNECTION - enumerator ESP_BT_STATUS_HCI_HW_FAILURE - enumerator ESP_BT_STATUS_HCI_PAGE_TIMEOUT - enumerator ESP_BT_STATUS_HCI_AUTH_FAILURE - enumerator ESP_BT_STATUS_HCI_KEY_MISSING - enumerator ESP_BT_STATUS_HCI_MEMORY_FULL - enumerator ESP_BT_STATUS_HCI_CONNECTION_TOUT - enumerator ESP_BT_STATUS_HCI_MAX_NUM_OF_CONNECTIONS - enumerator ESP_BT_STATUS_HCI_MAX_NUM_OF_SCOS - enumerator ESP_BT_STATUS_HCI_CONNECTION_EXISTS - enumerator ESP_BT_STATUS_HCI_COMMAND_DISALLOWED - enumerator ESP_BT_STATUS_HCI_HOST_REJECT_RESOURCES - enumerator ESP_BT_STATUS_HCI_HOST_REJECT_SECURITY - enumerator ESP_BT_STATUS_HCI_HOST_REJECT_DEVICE - enumerator ESP_BT_STATUS_HCI_HOST_TIMEOUT - enumerator ESP_BT_STATUS_HCI_UNSUPPORTED_VALUE - enumerator ESP_BT_STATUS_HCI_ILLEGAL_PARAMETER_FMT - enumerator ESP_BT_STATUS_HCI_PEER_USER - enumerator ESP_BT_STATUS_HCI_PEER_LOW_RESOURCES - enumerator ESP_BT_STATUS_HCI_PEER_POWER_OFF - enumerator ESP_BT_STATUS_HCI_CONN_CAUSE_LOCAL_HOST - enumerator ESP_BT_STATUS_HCI_REPEATED_ATTEMPTS - enumerator ESP_BT_STATUS_HCI_PAIRING_NOT_ALLOWED - enumerator ESP_BT_STATUS_HCI_UNKNOWN_LMP_PDU - enumerator ESP_BT_STATUS_HCI_UNSUPPORTED_REM_FEATURE - enumerator ESP_BT_STATUS_HCI_SCO_OFFSET_REJECTED - enumerator ESP_BT_STATUS_HCI_SCO_INTERVAL_REJECTED - enumerator ESP_BT_STATUS_HCI_SCO_AIR_MODE - enumerator ESP_BT_STATUS_HCI_INVALID_LMP_PARAM - enumerator ESP_BT_STATUS_HCI_UNSPECIFIED - enumerator ESP_BT_STATUS_HCI_UNSUPPORTED_LMP_PARAMETERS - enumerator ESP_BT_STATUS_HCI_ROLE_CHANGE_NOT_ALLOWED - enumerator ESP_BT_STATUS_HCI_LMP_RESPONSE_TIMEOUT - enumerator ESP_BT_STATUS_HCI_LMP_ERR_TRANS_COLLISION - enumerator ESP_BT_STATUS_HCI_LMP_PDU_NOT_ALLOWED - enumerator ESP_BT_STATUS_HCI_ENCRY_MODE_NOT_ACCEPTABLE - enumerator ESP_BT_STATUS_HCI_UNIT_KEY_USED - enumerator ESP_BT_STATUS_HCI_QOS_NOT_SUPPORTED - enumerator ESP_BT_STATUS_HCI_INSTANT_PASSED - enumerator ESP_BT_STATUS_HCI_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED - enumerator ESP_BT_STATUS_HCI_DIFF_TRANSACTION_COLLISION - enumerator ESP_BT_STATUS_HCI_UNDEFINED_0x2B - enumerator ESP_BT_STATUS_HCI_QOS_UNACCEPTABLE_PARAM - enumerator ESP_BT_STATUS_HCI_QOS_REJECTED - enumerator ESP_BT_STATUS_HCI_CHAN_CLASSIF_NOT_SUPPORTED - enumerator ESP_BT_STATUS_HCI_INSUFFCIENT_SECURITY - enumerator ESP_BT_STATUS_HCI_PARAM_OUT_OF_RANGE - enumerator ESP_BT_STATUS_HCI_UNDEFINED_0x31 - enumerator ESP_BT_STATUS_HCI_ROLE_SWITCH_PENDING - enumerator ESP_BT_STATUS_HCI_UNDEFINED_0x33 - enumerator ESP_BT_STATUS_HCI_RESERVED_SLOT_VIOLATION - enumerator ESP_BT_STATUS_HCI_ROLE_SWITCH_FAILED - enumerator ESP_BT_STATUS_HCI_INQ_RSP_DATA_TOO_LARGE - enumerator ESP_BT_STATUS_HCI_SIMPLE_PAIRING_NOT_SUPPORTED - enumerator ESP_BT_STATUS_HCI_HOST_BUSY_PAIRING - enumerator ESP_BT_STATUS_HCI_REJ_NO_SUITABLE_CHANNEL - enumerator ESP_BT_STATUS_HCI_CONTROLLER_BUSY - enumerator ESP_BT_STATUS_HCI_UNACCEPT_CONN_INTERVAL - enumerator ESP_BT_STATUS_HCI_DIRECTED_ADVERTISING_TIMEOUT - enumerator ESP_BT_STATUS_HCI_CONN_TOUT_DUE_TO_MIC_FAILURE - enumerator ESP_BT_STATUS_HCI_CONN_FAILED_ESTABLISHMENT - enumerator ESP_BT_STATUS_HCI_MAC_CONNECTION_FAILED - enumerator ESP_BT_STATUS_SUCCESS - enum esp_bt_dev_type_t Bluetooth device type. Values: - enumerator ESP_BT_DEVICE_TYPE_BREDR - enumerator ESP_BT_DEVICE_TYPE_BLE - enumerator ESP_BT_DEVICE_TYPE_DUMO - enumerator ESP_BT_DEVICE_TYPE_BREDR - enum esp_ble_addr_type_t BLE device address type. Values: - enumerator BLE_ADDR_TYPE_PUBLIC Public Device Address - enumerator BLE_ADDR_TYPE_RANDOM Random Device Address. To set this address, use the function esp_ble_gap_set_rand_addr(esp_bd_addr_t rand_addr) - enumerator BLE_ADDR_TYPE_RPA_PUBLIC Resolvable Private Address (RPA) with public identity address - enumerator BLE_ADDR_TYPE_RPA_RANDOM Resolvable Private Address (RPA) with random identity address. To set this address, use the function esp_ble_gap_set_rand_addr(esp_bd_addr_t rand_addr) - enumerator BLE_ADDR_TYPE_PUBLIC
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_bt_defs.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Bluetooth® Main API
null
espressif.com
2016-01-01
9563e01dde360111
null
null
Bluetooth® Main API API Reference Header File This header file can be included with: #include "esp_bt_main.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_bluedroid_status_t esp_bluedroid_get_status(void) Get bluetooth stack status. Returns Bluetooth stack status Returns Bluetooth stack status esp_err_t esp_bluedroid_enable(void) Enable bluetooth, must after esp_bluedroid_init()/esp_bluedroid_init_with_cfg(). Returns ESP_OK : Succeed Other : Failed ESP_OK : Succeed Other : Failed ESP_OK : Succeed Returns ESP_OK : Succeed Other : Failed esp_err_t esp_bluedroid_disable(void) Disable bluetooth, must prior to esp_bluedroid_deinit(). Returns ESP_OK : Succeed Other : Failed ESP_OK : Succeed Other : Failed ESP_OK : Succeed Returns ESP_OK : Succeed Other : Failed esp_err_t esp_bluedroid_init(void) Init and alloc the resource for bluetooth, must be prior to every bluetooth stuff. Returns ESP_OK : Succeed Other : Failed ESP_OK : Succeed Other : Failed ESP_OK : Succeed Returns ESP_OK : Succeed Other : Failed esp_err_t esp_bluedroid_init_with_cfg(esp_bluedroid_config_t *cfg) Init and alloc the resource for bluetooth, must be prior to every bluetooth stuff. Parameters cfg -- Initial configuration of ESP Bluedroid stack. Returns ESP_OK : Succeed Other : Failed ESP_OK : Succeed Other : Failed ESP_OK : Succeed Parameters cfg -- Initial configuration of ESP Bluedroid stack. Returns ESP_OK : Succeed Other : Failed Structures Macros BT_BLUEDROID_INIT_CONFIG_DEFAULT() Enumerations enum esp_bluedroid_status_t Bluetooth stack status type, to indicate whether the bluetooth stack is ready. Values: enumerator ESP_BLUEDROID_STATUS_UNINITIALIZED Bluetooth not initialized enumerator ESP_BLUEDROID_STATUS_UNINITIALIZED Bluetooth not initialized enumerator ESP_BLUEDROID_STATUS_INITIALIZED Bluetooth initialized but not enabled enumerator ESP_BLUEDROID_STATUS_INITIALIZED Bluetooth initialized but not enabled enumerator ESP_BLUEDROID_STATUS_ENABLED Bluetooth initialized and enabled enumerator ESP_BLUEDROID_STATUS_ENABLED Bluetooth initialized and enabled enumerator ESP_BLUEDROID_STATUS_UNINITIALIZED
Bluetooth® Main API API Reference Header File This header file can be included with: #include "esp_bt_main.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_bluedroid_status_t esp_bluedroid_get_status(void) Get bluetooth stack status. - Returns Bluetooth stack status - esp_err_t esp_bluedroid_enable(void) Enable bluetooth, must after esp_bluedroid_init()/esp_bluedroid_init_with_cfg(). - Returns ESP_OK : Succeed Other : Failed - - esp_err_t esp_bluedroid_disable(void) Disable bluetooth, must prior to esp_bluedroid_deinit(). - Returns ESP_OK : Succeed Other : Failed - - esp_err_t esp_bluedroid_init(void) Init and alloc the resource for bluetooth, must be prior to every bluetooth stuff. - Returns ESP_OK : Succeed Other : Failed - - esp_err_t esp_bluedroid_init_with_cfg(esp_bluedroid_config_t *cfg) Init and alloc the resource for bluetooth, must be prior to every bluetooth stuff. - Parameters cfg -- Initial configuration of ESP Bluedroid stack. - Returns ESP_OK : Succeed Other : Failed - Structures Macros - BT_BLUEDROID_INIT_CONFIG_DEFAULT() Enumerations - enum esp_bluedroid_status_t Bluetooth stack status type, to indicate whether the bluetooth stack is ready. Values: - enumerator ESP_BLUEDROID_STATUS_UNINITIALIZED Bluetooth not initialized - enumerator ESP_BLUEDROID_STATUS_INITIALIZED Bluetooth initialized but not enabled - enumerator ESP_BLUEDROID_STATUS_ENABLED Bluetooth initialized and enabled - enumerator ESP_BLUEDROID_STATUS_UNINITIALIZED
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_bt_main.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Bluetooth® Device APIs
null
espressif.com
2016-01-01
b6052215eb0fd350
null
null
Bluetooth® Device APIs Overview Bluetooth device reference APIs. API Reference Header File components/bt/host/bluedroid/api/include/api/esp_bt_device.h This header file can be included with: #include "esp_bt_device.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions const uint8_t *esp_bt_dev_get_address(void) Get bluetooth device address. Must use after "esp_bluedroid_enable". Returns bluetooth device address (six bytes), or NULL if bluetooth stack is not enabled Returns bluetooth device address (six bytes), or NULL if bluetooth stack is not enabled esp_err_t esp_bt_dev_set_device_name(const char *name) Set bluetooth device name. This function should be called after esp_bluedroid_enable() completes successfully. A BR/EDR/LE device type shall have a single Bluetooth device name which shall be identical irrespective of the physical channel used to perform the name discovery procedure. Parameters name -- [in] : device name to be set Returns ESP_OK : Succeed ESP_ERR_INVALID_ARG : if name is NULL pointer or empty, or string length out of limit ESP_ERR_INVALID_STATE : if bluetooth stack is not yet enabled ESP_FAIL : others ESP_OK : Succeed ESP_ERR_INVALID_ARG : if name is NULL pointer or empty, or string length out of limit ESP_ERR_INVALID_STATE : if bluetooth stack is not yet enabled ESP_FAIL : others ESP_OK : Succeed Parameters name -- [in] : device name to be set Returns ESP_OK : Succeed ESP_ERR_INVALID_ARG : if name is NULL pointer or empty, or string length out of limit ESP_ERR_INVALID_STATE : if bluetooth stack is not yet enabled ESP_FAIL : others esp_err_t esp_bt_dev_coex_status_config(esp_bt_dev_coex_type_t type, esp_bt_dev_coex_op_t op, uint8_t status) Config bluetooth device coexis status. This function should be called after esp_bluedroid_enable() completes successfully. Parameters type -- [in] : coexist type to operate on op -- [in] : clear or set coexist status status -- [in] : coexist status to be configured type -- [in] : coexist type to operate on op -- [in] : clear or set coexist status status -- [in] : coexist status to be configured type -- [in] : coexist type to operate on Returns ESP_OK : Succeed ESP_ERR_INVALID_ARG : if name is NULL pointer or empty, or string length out of limit ESP_ERR_INVALID_STATE : if bluetooth stack is not yet enabled ESP_FAIL : others ESP_OK : Succeed ESP_ERR_INVALID_ARG : if name is NULL pointer or empty, or string length out of limit ESP_ERR_INVALID_STATE : if bluetooth stack is not yet enabled ESP_FAIL : others ESP_OK : Succeed Parameters type -- [in] : coexist type to operate on op -- [in] : clear or set coexist status status -- [in] : coexist status to be configured Returns ESP_OK : Succeed ESP_ERR_INVALID_ARG : if name is NULL pointer or empty, or string length out of limit ESP_ERR_INVALID_STATE : if bluetooth stack is not yet enabled ESP_FAIL : others esp_err_t esp_bt_config_file_path_update(const char *file_path) This function is used to update the path name of bluetooth bond keys saved in the NVS module and need to be called before esp_bluedroid_init(). Parameters file_path -- [in] the name of config file path, the length of file_path should be less than NVS_NS_NAME_MAX_SIZE Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters file_path -- [in] the name of config file path, the length of file_path should be less than NVS_NS_NAME_MAX_SIZE Returns ESP_OK: success other: failed Macros ESP_BT_DEV_COEX_BLE_ST_MESH_CONFIG ESP_BT_DEV_COEX_BLE_ST_MESH_TRAFFIC ESP_BT_DEV_COEX_BLE_ST_MESH_STANDBY ESP_BT_DEV_COEX_BT_ST_A2DP_STREAMING ESP_BT_DEV_COEX_BT_ST_A2DP_PAUSED ESP_BT_DEV_COEX_OP_CLEAR ESP_BT_DEV_COEX_OP_SET Type Definitions typedef uint8_t esp_bt_dev_coex_op_t
Bluetooth® Device APIs Overview Bluetooth device reference APIs. API Reference Header File components/bt/host/bluedroid/api/include/api/esp_bt_device.h This header file can be included with: #include "esp_bt_device.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - const uint8_t *esp_bt_dev_get_address(void) Get bluetooth device address. Must use after "esp_bluedroid_enable". - Returns bluetooth device address (six bytes), or NULL if bluetooth stack is not enabled - esp_err_t esp_bt_dev_set_device_name(const char *name) Set bluetooth device name. This function should be called after esp_bluedroid_enable() completes successfully. A BR/EDR/LE device type shall have a single Bluetooth device name which shall be identical irrespective of the physical channel used to perform the name discovery procedure. - Parameters name -- [in] : device name to be set - Returns ESP_OK : Succeed ESP_ERR_INVALID_ARG : if name is NULL pointer or empty, or string length out of limit ESP_ERR_INVALID_STATE : if bluetooth stack is not yet enabled ESP_FAIL : others - - esp_err_t esp_bt_dev_coex_status_config(esp_bt_dev_coex_type_t type, esp_bt_dev_coex_op_t op, uint8_t status) Config bluetooth device coexis status. This function should be called after esp_bluedroid_enable() completes successfully. - Parameters type -- [in] : coexist type to operate on op -- [in] : clear or set coexist status status -- [in] : coexist status to be configured - - Returns ESP_OK : Succeed ESP_ERR_INVALID_ARG : if name is NULL pointer or empty, or string length out of limit ESP_ERR_INVALID_STATE : if bluetooth stack is not yet enabled ESP_FAIL : others - - esp_err_t esp_bt_config_file_path_update(const char *file_path) This function is used to update the path name of bluetooth bond keys saved in the NVS module and need to be called before esp_bluedroid_init(). - Parameters file_path -- [in] the name of config file path, the length of file_path should be less than NVS_NS_NAME_MAX_SIZE - Returns ESP_OK: success other: failed - Macros - ESP_BT_DEV_COEX_BLE_ST_MESH_CONFIG - ESP_BT_DEV_COEX_BLE_ST_MESH_TRAFFIC - ESP_BT_DEV_COEX_BLE_ST_MESH_STANDBY - ESP_BT_DEV_COEX_BT_ST_A2DP_STREAMING - ESP_BT_DEV_COEX_BT_ST_A2DP_PAUSED - ESP_BT_DEV_COEX_OP_CLEAR - ESP_BT_DEV_COEX_OP_SET Type Definitions - typedef uint8_t esp_bt_dev_coex_op_t
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_bt_device.html
ESP-IDF Programming Guide v5.2.1 documentation
null
GAP API
Esp Err T Esp Gap Ble Set Authorization Esp Bd Addr T Bd Addr; Bool Authorize
espressif.com
2016-01-01
ce249c99a32fb941
null
null
GAP API Application Example Check the bluetooth/bluedroid/ble folder in ESP-IDF examples, which contains the following demos and their tutorials: The following shows an SMP security client demo with its tutorial. This demo initiates its security parameters and acts as a GATT client, which can send a security request to the peer device and then complete the encryption procedure. The following shows an SMP security server demo with its tutorial. This demo initiates its security parameters and acts as a GATT server, which can send a pair request to the peer device and then complete the encryption procedure. API Reference Header File components/bt/host/bluedroid/api/include/api/esp_gap_ble_api.h This header file can be included with: #include "esp_gap_ble_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_gap_register_callback(esp_gap_ble_cb_t callback) This function is called to occur gap event, such as scan result. Parameters callback -- [in] callback function Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters callback -- [in] callback function Returns ESP_OK : success other : failed esp_gap_ble_cb_t esp_ble_gap_get_callback(void) This function is called to get the current gap callback. Returns esp_gap_ble_cb_t : callback function esp_gap_ble_cb_t : callback function esp_gap_ble_cb_t : callback function Returns esp_gap_ble_cb_t : callback function esp_err_t esp_ble_gap_config_adv_data(esp_ble_adv_data_t *adv_data) This function is called to override the BTA default ADV parameters. Parameters adv_data -- [in] Pointer to User defined ADV data structure. This memory space can not be freed until callback of config_adv_data is received. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters adv_data -- [in] Pointer to User defined ADV data structure. This memory space can not be freed until callback of config_adv_data is received. Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_set_scan_params(esp_ble_scan_params_t *scan_params) This function is called to set scan parameters. Parameters scan_params -- [in] Pointer to User defined scan_params data structure. This memory space can not be freed until callback of set_scan_params Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters scan_params -- [in] Pointer to User defined scan_params data structure. This memory space can not be freed until callback of set_scan_params Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_start_scanning(uint32_t duration) This procedure keep the device scanning the peer device which advertising on the air. Parameters duration -- [in] Keeping the scanning time, the unit is second. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters duration -- [in] Keeping the scanning time, the unit is second. Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_stop_scanning(void) This function call to stop the device scanning the peer device which advertising on the air. Returns ESP_OK : success other : failed other : failed other : failed ESP_OK : success other : failed ESP_OK : success other : failed Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_start_advertising(esp_ble_adv_params_t *adv_params) This function is called to start advertising. Parameters adv_params -- [in] pointer to User defined adv_params data structure. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters adv_params -- [in] pointer to User defined adv_params data structure. Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_stop_advertising(void) This function is called to stop advertising. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_update_conn_params(esp_ble_conn_update_params_t *params) Update connection parameters, can only be used when connection is up. Parameters params -- [in] - connection update parameters Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters params -- [in] - connection update parameters Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_set_pkt_data_len(esp_bd_addr_t remote_device, uint16_t tx_data_length) This function is to set maximum LE data packet size. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_set_rand_addr(esp_bd_addr_t rand_addr) This function allows configuring either a Non-Resolvable Private Address or a Static Random Address. Parameters rand_addr -- [in] The address to be configured. Refer to the table below for possible address subtypes: | address [47:46] | Address Type | |-----------------|--------------------------| | 0b00 | Non-Resolvable Private | | | Address | |-----------------|--------------------------| | 0b11 | Static Random Address | |-----------------|--------------------------| Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters rand_addr -- [in] The address to be configured. Refer to the table below for possible address subtypes: | address [47:46] | Address Type | |-----------------|--------------------------| | 0b00 | Non-Resolvable Private | | | Address | |-----------------|--------------------------| | 0b11 | Static Random Address | |-----------------|--------------------------| Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_clear_rand_addr(void) This function clears the random address for the application. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_config_local_privacy(bool privacy_enable) Enable/disable privacy (including address resolution) on the local device. Parameters privacy_enable -- [in] - enable/disable privacy on remote device. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters privacy_enable -- [in] - enable/disable privacy on remote device. Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_config_local_icon(uint16_t icon) set local gap appearance icon Parameters icon -- [in] - External appearance value, these values are defined by the Bluetooth SIG, please refer to https://www.bluetooth.com/specifications/assigned-numbers/ Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters icon -- [in] - External appearance value, these values are defined by the Bluetooth SIG, please refer to https://www.bluetooth.com/specifications/assigned-numbers/ Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_update_whitelist(bool add_remove, esp_bd_addr_t remote_bda, esp_ble_wl_addr_type_t wl_addr_type) Add or remove device from white list. Parameters add_remove -- [in] the value is true if added the ble device to the white list, and false remove to the white list. remote_bda -- [in] the remote device address add/remove from the white list. wl_addr_type -- [in] whitelist address type add_remove -- [in] the value is true if added the ble device to the white list, and false remove to the white list. remote_bda -- [in] the remote device address add/remove from the white list. wl_addr_type -- [in] whitelist address type add_remove -- [in] the value is true if added the ble device to the white list, and false remove to the white list. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters add_remove -- [in] the value is true if added the ble device to the white list, and false remove to the white list. remote_bda -- [in] the remote device address add/remove from the white list. wl_addr_type -- [in] whitelist address type Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_clear_whitelist(void) Clear all white list. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_get_whitelist_size(uint16_t *length) Get the whitelist size in the controller. Parameters length -- [out] the white list length. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters length -- [out] the white list length. Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_set_prefer_conn_params(esp_bd_addr_t bd_addr, uint16_t min_conn_int, uint16_t max_conn_int, uint16_t slave_latency, uint16_t supervision_tout) This function is called to set the preferred connection parameters when default connection parameter is not desired before connecting. This API can only be used in the master role. Parameters bd_addr -- [in] BD address of the peripheral min_conn_int -- [in] minimum preferred connection interval max_conn_int -- [in] maximum preferred connection interval slave_latency -- [in] preferred slave latency supervision_tout -- [in] preferred supervision timeout bd_addr -- [in] BD address of the peripheral min_conn_int -- [in] minimum preferred connection interval max_conn_int -- [in] maximum preferred connection interval slave_latency -- [in] preferred slave latency supervision_tout -- [in] preferred supervision timeout bd_addr -- [in] BD address of the peripheral Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters bd_addr -- [in] BD address of the peripheral min_conn_int -- [in] minimum preferred connection interval max_conn_int -- [in] maximum preferred connection interval slave_latency -- [in] preferred slave latency supervision_tout -- [in] preferred supervision timeout Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_set_device_name(const char *name) Set device name to the local device Note: This API don't affect the advertising data. Parameters name -- [in] - device name. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters name -- [in] - device name. Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_get_device_name(void) Get device name of the local device. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_get_local_used_addr(esp_bd_addr_t local_used_addr, uint8_t *addr_type) This function is called to get local used address and address type. uint8_t *esp_bt_dev_get_address(void) get the public address. Parameters local_used_addr -- [in] - current local used ble address (six bytes) addr_type -- [in] - ble address type local_used_addr -- [in] - current local used ble address (six bytes) addr_type -- [in] - ble address type local_used_addr -- [in] - current local used ble address (six bytes) Returns - ESP_OK : success other : failed other : failed other : failed Parameters local_used_addr -- [in] - current local used ble address (six bytes) addr_type -- [in] - ble address type Returns - ESP_OK : success other : failed uint8_t *esp_ble_resolve_adv_data(uint8_t *adv_data, uint8_t type, uint8_t *length) This function is called to get ADV data for a specific type. Parameters adv_data -- [in] - pointer of ADV data which to be resolved type -- [in] - finding ADV data type length -- [out] - return the length of ADV data not including type adv_data -- [in] - pointer of ADV data which to be resolved type -- [in] - finding ADV data type length -- [out] - return the length of ADV data not including type adv_data -- [in] - pointer of ADV data which to be resolved Returns pointer of ADV data Parameters adv_data -- [in] - pointer of ADV data which to be resolved type -- [in] - finding ADV data type length -- [out] - return the length of ADV data not including type Returns pointer of ADV data esp_err_t esp_ble_gap_config_adv_data_raw(uint8_t *raw_data, uint32_t raw_data_len) This function is called to set raw advertising data. User need to fill ADV data by self. Parameters raw_data -- [in] : raw advertising data with the format: [Length 1][Data Type 1][Data 1][Length 2][Data Type 2][Data 2] ... raw_data_len -- [in] : raw advertising data length , less than 31 bytes raw_data -- [in] : raw advertising data with the format: [Length 1][Data Type 1][Data 1][Length 2][Data Type 2][Data 2] ... raw_data_len -- [in] : raw advertising data length , less than 31 bytes raw_data -- [in] : raw advertising data with the format: [Length 1][Data Type 1][Data 1][Length 2][Data Type 2][Data 2] ... Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters raw_data -- [in] : raw advertising data with the format: [Length 1][Data Type 1][Data 1][Length 2][Data Type 2][Data 2] ... raw_data_len -- [in] : raw advertising data length , less than 31 bytes Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_config_scan_rsp_data_raw(uint8_t *raw_data, uint32_t raw_data_len) This function is called to set raw scan response data. User need to fill scan response data by self. Parameters raw_data -- [in] : raw scan response data raw_data_len -- [in] : raw scan response data length , less than 31 bytes raw_data -- [in] : raw scan response data raw_data_len -- [in] : raw scan response data length , less than 31 bytes raw_data -- [in] : raw scan response data Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters raw_data -- [in] : raw scan response data raw_data_len -- [in] : raw scan response data length , less than 31 bytes Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_read_rssi(esp_bd_addr_t remote_addr) This function is called to read the RSSI of remote device. The address of link policy results are returned in the gap callback function with ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT event. Parameters remote_addr -- [in] : The remote connection device address. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters remote_addr -- [in] : The remote connection device address. Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_add_duplicate_scan_exceptional_device(esp_ble_duplicate_exceptional_info_type_t type, esp_duplicate_info_t device_info) This function is called to add a device info into the duplicate scan exceptional list. Parameters type -- [in] device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or MESH_PROXY_SRV_ADV , device_info is invalid. device_info -- [in] the device information. type -- [in] device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or MESH_PROXY_SRV_ADV , device_info is invalid. device_info -- [in] the device information. type -- [in] device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or MESH_PROXY_SRV_ADV , device_info is invalid. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters type -- [in] device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or MESH_PROXY_SRV_ADV , device_info is invalid. device_info -- [in] the device information. Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_remove_duplicate_scan_exceptional_device(esp_ble_duplicate_exceptional_info_type_t type, esp_duplicate_info_t device_info) This function is called to remove a device info from the duplicate scan exceptional list. Parameters type -- [in] device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or MESH_PROXY_SRV_ADV , device_info is invalid. device_info -- [in] the device information. type -- [in] device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or MESH_PROXY_SRV_ADV , device_info is invalid. device_info -- [in] the device information. type -- [in] device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or MESH_PROXY_SRV_ADV , device_info is invalid. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters type -- [in] device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or MESH_PROXY_SRV_ADV , device_info is invalid. device_info -- [in] the device information. Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_clean_duplicate_scan_exceptional_list(esp_duplicate_scan_exceptional_list_type_t list_type) This function is called to clean the duplicate scan exceptional list. This API will delete all device information in the duplicate scan exceptional list. Parameters list_type -- [in] duplicate scan exceptional list type, the value can be one or more of esp_duplicate_scan_exceptional_list_type_t. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters list_type -- [in] duplicate scan exceptional list type, the value can be one or more of esp_duplicate_scan_exceptional_list_type_t. Returns ESP_OK : success other : failed esp_err_t esp_ble_gap_set_security_param(esp_ble_sm_param_t param_type, void *value, uint8_t len) Set a GAP security parameter value. Overrides the default value. Secure connection is highly recommended to avoid some major vulnerabilities like 'Impersonation in the Pin Pairing Protocol' (CVE-2020-26555) and 'Authentication of the LE Legacy Pairing Protocol'. To accept only `secure connection mode`, it is necessary do as following: 1. Set bit `ESP_LE_AUTH_REQ_SC_ONLY` (`param_type` is `ESP_BLE_SM_AUTHEN_REQ_MODE`), bit `ESP_LE_AUTH_BOND` and bit `ESP_LE_AUTH_REQ_MITM` is optional as required. 2. Set to `ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_ENABLE` (`param_type` is `ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH`). Parameters param_type -- [in] : the type of the param which to be set value -- [in] : the param value len -- [in] : the length of the param value param_type -- [in] : the type of the param which to be set value -- [in] : the param value len -- [in] : the length of the param value param_type -- [in] : the type of the param which to be set Returns - ESP_OK : success other : failed other : failed other : failed Parameters param_type -- [in] : the type of the param which to be set value -- [in] : the param value len -- [in] : the length of the param value Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_security_rsp(esp_bd_addr_t bd_addr, bool accept) Grant security request access. Parameters bd_addr -- [in] : BD address of the peer accept -- [in] : accept the security request or not bd_addr -- [in] : BD address of the peer accept -- [in] : accept the security request or not bd_addr -- [in] : BD address of the peer Returns - ESP_OK : success other : failed other : failed other : failed Parameters bd_addr -- [in] : BD address of the peer accept -- [in] : accept the security request or not Returns - ESP_OK : success other : failed esp_err_t esp_ble_set_encryption(esp_bd_addr_t bd_addr, esp_ble_sec_act_t sec_act) Set a gap parameter value. Use this function to change the default GAP parameter values. Parameters bd_addr -- [in] : the address of the peer device need to encryption sec_act -- [in] : This is the security action to indicate what kind of BLE security level is required for the BLE link if the BLE is supported bd_addr -- [in] : the address of the peer device need to encryption sec_act -- [in] : This is the security action to indicate what kind of BLE security level is required for the BLE link if the BLE is supported bd_addr -- [in] : the address of the peer device need to encryption Returns - ESP_OK : success other : failed other : failed other : failed Parameters bd_addr -- [in] : the address of the peer device need to encryption sec_act -- [in] : This is the security action to indicate what kind of BLE security level is required for the BLE link if the BLE is supported Returns - ESP_OK : success other : failed esp_err_t esp_ble_passkey_reply(esp_bd_addr_t bd_addr, bool accept, uint32_t passkey) Reply the key value to the peer device in the legacy connection stage. Parameters bd_addr -- [in] : BD address of the peer accept -- [in] : passkey entry successful or declined. passkey -- [in] : passkey value, must be a 6 digit number, can be lead by 0. bd_addr -- [in] : BD address of the peer accept -- [in] : passkey entry successful or declined. passkey -- [in] : passkey value, must be a 6 digit number, can be lead by 0. bd_addr -- [in] : BD address of the peer Returns - ESP_OK : success other : failed other : failed other : failed Parameters bd_addr -- [in] : BD address of the peer accept -- [in] : passkey entry successful or declined. passkey -- [in] : passkey value, must be a 6 digit number, can be lead by 0. Returns - ESP_OK : success other : failed esp_err_t esp_ble_confirm_reply(esp_bd_addr_t bd_addr, bool accept) Reply the confirm value to the peer device in the secure connection stage. Parameters bd_addr -- [in] : BD address of the peer device accept -- [in] : numbers to compare are the same or different. bd_addr -- [in] : BD address of the peer device accept -- [in] : numbers to compare are the same or different. bd_addr -- [in] : BD address of the peer device Returns - ESP_OK : success other : failed other : failed other : failed Parameters bd_addr -- [in] : BD address of the peer device accept -- [in] : numbers to compare are the same or different. Returns - ESP_OK : success other : failed esp_err_t esp_ble_remove_bond_device(esp_bd_addr_t bd_addr) Removes a device from the security database list of peer device. It manages unpairing event while connected. Parameters bd_addr -- [in] : BD address of the peer device Returns - ESP_OK : success other : failed other : failed other : failed Parameters bd_addr -- [in] : BD address of the peer device Returns - ESP_OK : success other : failed int esp_ble_get_bond_device_num(void) Get the device number from the security database list of peer device. It will return the device bonded number immediately. Returns - >= 0 : bonded devices number. ESP_FAIL : failed ESP_FAIL : failed ESP_FAIL : failed Returns - >= 0 : bonded devices number. ESP_FAIL : failed esp_err_t esp_ble_get_bond_device_list(int *dev_num, esp_ble_bond_dev_t *dev_list) Get the device from the security database list of peer device. It will return the device bonded information immediately. Parameters dev_num -- [inout] Indicate the dev_list array(buffer) size as input. If dev_num is large enough, it means the actual number as output. Suggest that dev_num value equal to esp_ble_get_bond_device_num(). dev_list -- [out] an array(buffer) of esp_ble_bond_dev_t type. Use for storing the bonded devices address. The dev_list should be allocated by who call this API. dev_num -- [inout] Indicate the dev_list array(buffer) size as input. If dev_num is large enough, it means the actual number as output. Suggest that dev_num value equal to esp_ble_get_bond_device_num(). dev_list -- [out] an array(buffer) of esp_ble_bond_dev_t type. Use for storing the bonded devices address. The dev_list should be allocated by who call this API. dev_num -- [inout] Indicate the dev_list array(buffer) size as input. If dev_num is large enough, it means the actual number as output. Suggest that dev_num value equal to esp_ble_get_bond_device_num(). Returns - ESP_OK : success other : failed other : failed other : failed Parameters dev_num -- [inout] Indicate the dev_list array(buffer) size as input. If dev_num is large enough, it means the actual number as output. Suggest that dev_num value equal to esp_ble_get_bond_device_num(). dev_list -- [out] an array(buffer) of esp_ble_bond_dev_t type. Use for storing the bonded devices address. The dev_list should be allocated by who call this API. Returns - ESP_OK : success other : failed esp_err_t esp_ble_oob_req_reply(esp_bd_addr_t bd_addr, uint8_t *TK, uint8_t len) This function is called to provide the OOB data for SMP in response to ESP_GAP_BLE_OOB_REQ_EVT. Parameters bd_addr -- [in] BD address of the peer device. TK -- [in] Temporary Key value, the TK value shall be a 128-bit random number len -- [in] length of temporary key, should always be 128-bit bd_addr -- [in] BD address of the peer device. TK -- [in] Temporary Key value, the TK value shall be a 128-bit random number len -- [in] length of temporary key, should always be 128-bit bd_addr -- [in] BD address of the peer device. Returns - ESP_OK : success other : failed other : failed other : failed Parameters bd_addr -- [in] BD address of the peer device. TK -- [in] Temporary Key value, the TK value shall be a 128-bit random number len -- [in] length of temporary key, should always be 128-bit Returns - ESP_OK : success other : failed esp_err_t esp_ble_sc_oob_req_reply(esp_bd_addr_t bd_addr, uint8_t p_c[16], uint8_t p_r[16]) This function is called to provide the OOB data for SMP in response to ESP_GAP_BLE_SC_OOB_REQ_EVT. Parameters bd_addr -- [in] BD address of the peer device. p_c -- [in] Confirmation value, it shall be a 128-bit random number p_r -- [in] Randomizer value, it should be a 128-bit random number bd_addr -- [in] BD address of the peer device. p_c -- [in] Confirmation value, it shall be a 128-bit random number p_r -- [in] Randomizer value, it should be a 128-bit random number bd_addr -- [in] BD address of the peer device. Returns - ESP_OK : success other : failed other : failed other : failed Parameters bd_addr -- [in] BD address of the peer device. p_c -- [in] Confirmation value, it shall be a 128-bit random number p_r -- [in] Randomizer value, it should be a 128-bit random number Returns - ESP_OK : success other : failed esp_err_t esp_ble_create_sc_oob_data(void) This function is called to create the OOB data for SMP when secure connection. Returns - ESP_OK : success other : failed other : failed other : failed Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_disconnect(esp_bd_addr_t remote_device) This function is to disconnect the physical connection of the peer device gattc may have multiple virtual GATT server connections when multiple app_id registered. esp_ble_gattc_close (esp_gatt_if_t gattc_if, uint16_t conn_id) only close one virtual GATT server connection. if there exist other virtual GATT server connections, it does not disconnect the physical connection. esp_ble_gap_disconnect(esp_bd_addr_t remote_device) disconnect the physical connection directly. Parameters remote_device -- [in] : BD address of the peer device Returns - ESP_OK : success other : failed other : failed other : failed Parameters remote_device -- [in] : BD address of the peer device Returns - ESP_OK : success other : failed esp_err_t esp_ble_get_current_conn_params(esp_bd_addr_t bd_addr, esp_gap_conn_params_t *conn_params) This function is called to read the connection parameters information of the device. Parameters bd_addr -- [in] BD address of the peer device. conn_params -- [out] the connection parameters information bd_addr -- [in] BD address of the peer device. conn_params -- [out] the connection parameters information bd_addr -- [in] BD address of the peer device. Returns - ESP_OK : success other : failed other : failed other : failed Parameters bd_addr -- [in] BD address of the peer device. conn_params -- [out] the connection parameters information Returns - ESP_OK : success other : failed esp_err_t esp_gap_ble_set_channels(esp_gap_ble_channels channels) BLE set channels. Parameters channels -- [in] : The n th such field (in the range 0 to 36) contains the value for the link layer channel index n. 0 means channel n is bad. 1 means channel n is unknown. The most significant bits are reserved and shall be set to 0. At least one channel shall be marked as unknown. Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled Parameters channels -- [in] : The n th such field (in the range 0 to 36) contains the value for the link layer channel index n. 0 means channel n is bad. 1 means channel n is unknown. The most significant bits are reserved and shall be set to 0. At least one channel shall be marked as unknown. Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed This function is called to authorized a link after Authentication(MITM protection) Parameters bd_addr -- [in] BD address of the peer device. authorize -- [out] Authorized the link or not. bd_addr -- [in] BD address of the peer device. authorize -- [out] Authorized the link or not. bd_addr -- [in] BD address of the peer device. Returns - ESP_OK : success other : failed other : failed other : failed Parameters bd_addr -- [in] BD address of the peer device. authorize -- [out] Authorized the link or not. Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_read_phy(esp_bd_addr_t bd_addr) This function is used to read the current transmitter PHY and receiver PHY on the connection identified by remote address. Parameters bd_addr -- [in] : BD address of the peer device Returns - ESP_OK : success other : failed other : failed other : failed Parameters bd_addr -- [in] : BD address of the peer device Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_set_preferred_default_phy(esp_ble_gap_phy_mask_t tx_phy_mask, esp_ble_gap_phy_mask_t rx_phy_mask) This function is used to allows the Host to specify its preferred values for the transmitter PHY and receiver PHY to be used for all subsequent connections over the LE transport. Parameters tx_phy_mask -- [in] : indicates the transmitter PHYs that the Host prefers the Controller to use rx_phy_mask -- [in] : indicates the receiver PHYs that the Host prefers the Controller to use tx_phy_mask -- [in] : indicates the transmitter PHYs that the Host prefers the Controller to use rx_phy_mask -- [in] : indicates the receiver PHYs that the Host prefers the Controller to use tx_phy_mask -- [in] : indicates the transmitter PHYs that the Host prefers the Controller to use Returns - ESP_OK : success other : failed other : failed other : failed Parameters tx_phy_mask -- [in] : indicates the transmitter PHYs that the Host prefers the Controller to use rx_phy_mask -- [in] : indicates the receiver PHYs that the Host prefers the Controller to use Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_set_preferred_phy(esp_bd_addr_t bd_addr, esp_ble_gap_all_phys_t all_phys_mask, esp_ble_gap_phy_mask_t tx_phy_mask, esp_ble_gap_phy_mask_t rx_phy_mask, esp_ble_gap_prefer_phy_options_t phy_options) This function is used to set the PHY preferences for the connection identified by the remote address. The Controller might not be able to make the change (e.g. because the peer does not support the requested PHY) or may decide that the current PHY is preferable. Parameters bd_addr -- [in] : remote address all_phys_mask -- [in] : a bit field that allows the Host to specify tx_phy_mask -- [in] : a bit field that indicates the transmitter PHYs that the Host prefers the Controller to use rx_phy_mask -- [in] : a bit field that indicates the receiver PHYs that the Host prefers the Controller to use phy_options -- [in] : a bit field that allows the Host to specify options for PHYs bd_addr -- [in] : remote address all_phys_mask -- [in] : a bit field that allows the Host to specify tx_phy_mask -- [in] : a bit field that indicates the transmitter PHYs that the Host prefers the Controller to use rx_phy_mask -- [in] : a bit field that indicates the receiver PHYs that the Host prefers the Controller to use phy_options -- [in] : a bit field that allows the Host to specify options for PHYs bd_addr -- [in] : remote address Returns - ESP_OK : success other : failed other : failed other : failed Parameters bd_addr -- [in] : remote address all_phys_mask -- [in] : a bit field that allows the Host to specify tx_phy_mask -- [in] : a bit field that indicates the transmitter PHYs that the Host prefers the Controller to use rx_phy_mask -- [in] : a bit field that indicates the receiver PHYs that the Host prefers the Controller to use phy_options -- [in] : a bit field that allows the Host to specify options for PHYs Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_ext_adv_set_rand_addr(uint8_t instance, esp_bd_addr_t rand_addr) This function is used by the Host to set the random device address specified by the Random_Address parameter. Parameters instance -- [in] : Used to identify an advertising set rand_addr -- [in] : Random Device Address instance -- [in] : Used to identify an advertising set rand_addr -- [in] : Random Device Address instance -- [in] : Used to identify an advertising set Returns - ESP_OK : success other : failed other : failed other : failed Parameters instance -- [in] : Used to identify an advertising set rand_addr -- [in] : Random Device Address Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_ext_adv_set_params(uint8_t instance, const esp_ble_gap_ext_adv_params_t *params) This function is used by the Host to set the advertising parameters. Parameters instance -- [in] : identifies the advertising set whose parameters are being configured. params -- [in] : advertising parameters instance -- [in] : identifies the advertising set whose parameters are being configured. params -- [in] : advertising parameters instance -- [in] : identifies the advertising set whose parameters are being configured. Returns - ESP_OK : success other : failed other : failed other : failed Parameters instance -- [in] : identifies the advertising set whose parameters are being configured. params -- [in] : advertising parameters Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_config_ext_adv_data_raw(uint8_t instance, uint16_t length, const uint8_t *data) This function is used to set the data used in advertising PDUs that have a data field. Parameters instance -- [in] : identifies the advertising set whose data are being configured length -- [in] : data length data -- [in] : data information instance -- [in] : identifies the advertising set whose data are being configured length -- [in] : data length data -- [in] : data information instance -- [in] : identifies the advertising set whose data are being configured Returns - ESP_OK : success other : failed other : failed other : failed Parameters instance -- [in] : identifies the advertising set whose data are being configured length -- [in] : data length data -- [in] : data information Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_config_ext_scan_rsp_data_raw(uint8_t instance, uint16_t length, const uint8_t *scan_rsp_data) This function is used to provide scan response data used in scanning response PDUs. Parameters instance -- [in] : identifies the advertising set whose response data are being configured. length -- [in] : responsedata length scan_rsp_data -- [in] : response data information instance -- [in] : identifies the advertising set whose response data are being configured. length -- [in] : responsedata length scan_rsp_data -- [in] : response data information instance -- [in] : identifies the advertising set whose response data are being configured. Returns - ESP_OK : success other : failed other : failed other : failed Parameters instance -- [in] : identifies the advertising set whose response data are being configured. length -- [in] : responsedata length scan_rsp_data -- [in] : response data information Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_ext_adv_start(uint8_t num_adv, const esp_ble_gap_ext_adv_t *ext_adv) This function is used to request the Controller to enable one or more advertising sets using the advertising sets identified by the instance parameter. Parameters num_adv -- [in] : Number of advertising sets to enable or disable ext_adv -- [in] : adv parameters num_adv -- [in] : Number of advertising sets to enable or disable ext_adv -- [in] : adv parameters num_adv -- [in] : Number of advertising sets to enable or disable Returns - ESP_OK : success other : failed other : failed other : failed Parameters num_adv -- [in] : Number of advertising sets to enable or disable ext_adv -- [in] : adv parameters Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_ext_adv_stop(uint8_t num_adv, const uint8_t *ext_adv_inst) This function is used to request the Controller to disable one or more advertising sets using the advertising sets identified by the instance parameter. Parameters num_adv -- [in] : Number of advertising sets to enable or disable ext_adv_inst -- [in] : ext adv instance num_adv -- [in] : Number of advertising sets to enable or disable ext_adv_inst -- [in] : ext adv instance num_adv -- [in] : Number of advertising sets to enable or disable Returns - ESP_OK : success other : failed other : failed other : failed Parameters num_adv -- [in] : Number of advertising sets to enable or disable ext_adv_inst -- [in] : ext adv instance Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_ext_adv_set_remove(uint8_t instance) This function is used to remove an advertising set from the Controller. Parameters instance -- [in] : Used to identify an advertising set Returns - ESP_OK : success other : failed other : failed other : failed Parameters instance -- [in] : Used to identify an advertising set Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_ext_adv_set_clear(void) This function is used to remove all existing advertising sets from the Controller. Returns - ESP_OK : success other : failed other : failed other : failed Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_periodic_adv_set_params(uint8_t instance, const esp_ble_gap_periodic_adv_params_t *params) This function is used by the Host to set the parameters for periodic advertising. Parameters instance -- [in] : identifies the advertising set whose periodic advertising parameters are being configured. params -- [in] : periodic adv parameters instance -- [in] : identifies the advertising set whose periodic advertising parameters are being configured. params -- [in] : periodic adv parameters instance -- [in] : identifies the advertising set whose periodic advertising parameters are being configured. Returns - ESP_OK : success other : failed other : failed other : failed Parameters instance -- [in] : identifies the advertising set whose periodic advertising parameters are being configured. params -- [in] : periodic adv parameters Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_config_periodic_adv_data_raw(uint8_t instance, uint16_t length, const uint8_t *data) This function is used to set the data used in periodic advertising PDUs. Parameters instance -- [in] : identifies the advertising set whose periodic advertising parameters are being configured. length -- [in] : the length of periodic data data -- [in] : periodic data information instance -- [in] : identifies the advertising set whose periodic advertising parameters are being configured. length -- [in] : the length of periodic data data -- [in] : periodic data information instance -- [in] : identifies the advertising set whose periodic advertising parameters are being configured. Returns - ESP_OK : success other : failed other : failed other : failed Parameters instance -- [in] : identifies the advertising set whose periodic advertising parameters are being configured. length -- [in] : the length of periodic data data -- [in] : periodic data information Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_periodic_adv_start(uint8_t instance) This function is used to request the Controller to enable the periodic advertising for the advertising set specified. Parameters instance -- [in] : Used to identify an advertising set Returns - ESP_OK : success other : failed other : failed other : failed Parameters instance -- [in] : Used to identify an advertising set Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_periodic_adv_stop(uint8_t instance) This function is used to request the Controller to disable the periodic advertising for the advertising set specified. Parameters instance -- [in] : Used to identify an advertising set Returns - ESP_OK : success other : failed other : failed other : failed Parameters instance -- [in] : Used to identify an advertising set Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_set_ext_scan_params(const esp_ble_ext_scan_params_t *params) This function is used to set the extended scan parameters to be used on the advertising channels. Parameters params -- [in] : scan parameters Returns - ESP_OK : success other : failed other : failed other : failed Parameters params -- [in] : scan parameters Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_start_ext_scan(uint32_t duration, uint16_t period) This function is used to enable scanning. Parameters duration -- [in] Scan duration time, where Time = N * 10 ms. Range: 0x0001 to 0xFFFF. period -- [in] Time interval from when the Controller started its last Scan Duration until it begins the subsequent Scan Duration. Time = N * 1.28 sec. Range: 0x0001 to 0xFFFF. duration -- [in] Scan duration time, where Time = N * 10 ms. Range: 0x0001 to 0xFFFF. period -- [in] Time interval from when the Controller started its last Scan Duration until it begins the subsequent Scan Duration. Time = N * 1.28 sec. Range: 0x0001 to 0xFFFF. duration -- [in] Scan duration time, where Time = N * 10 ms. Range: 0x0001 to 0xFFFF. Returns - ESP_OK : success other : failed other : failed other : failed Parameters duration -- [in] Scan duration time, where Time = N * 10 ms. Range: 0x0001 to 0xFFFF. period -- [in] Time interval from when the Controller started its last Scan Duration until it begins the subsequent Scan Duration. Time = N * 1.28 sec. Range: 0x0001 to 0xFFFF. Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_stop_ext_scan(void) This function is used to disable scanning. Returns - ESP_OK : success other : failed other : failed other : failed Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_periodic_adv_create_sync(const esp_ble_gap_periodic_adv_sync_params_t *params) This function is used to synchronize with periodic advertising from an advertiser and begin receiving periodic advertising packets. Parameters params -- [in] : sync parameters Returns - ESP_OK : success other : failed other : failed other : failed Parameters params -- [in] : sync parameters Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_periodic_adv_sync_cancel(void) This function is used to cancel the LE_Periodic_Advertising_Create_Sync command while it is pending. Returns - ESP_OK : success other : failed other : failed other : failed Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_periodic_adv_sync_terminate(uint16_t sync_handle) This function is used to stop reception of the periodic advertising identified by the Sync Handle parameter. Parameters sync_handle -- [in] : identify the periodic advertiser Returns - ESP_OK : success other : failed other : failed other : failed Parameters sync_handle -- [in] : identify the periodic advertiser Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_periodic_adv_add_dev_to_list(esp_ble_addr_type_t addr_type, esp_bd_addr_t addr, uint8_t sid) This function is used to add a single device to the Periodic Advertiser list stored in the Controller. Parameters addr_type -- [in] : address type addr -- [in] : Device Address sid -- [in] : Advertising SID subfield in the ADI field used to identify the Periodic Advertising addr_type -- [in] : address type addr -- [in] : Device Address sid -- [in] : Advertising SID subfield in the ADI field used to identify the Periodic Advertising addr_type -- [in] : address type Returns - ESP_OK : success other : failed other : failed other : failed Parameters addr_type -- [in] : address type addr -- [in] : Device Address sid -- [in] : Advertising SID subfield in the ADI field used to identify the Periodic Advertising Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_periodic_adv_remove_dev_from_list(esp_ble_addr_type_t addr_type, esp_bd_addr_t addr, uint8_t sid) This function is used to remove one device from the list of Periodic Advertisers stored in the Controller. Removals from the Periodic Advertisers List take effect immediately. Parameters addr_type -- [in] : address type addr -- [in] : Device Address sid -- [in] : Advertising SID subfield in the ADI field used to identify the Periodic Advertising addr_type -- [in] : address type addr -- [in] : Device Address sid -- [in] : Advertising SID subfield in the ADI field used to identify the Periodic Advertising addr_type -- [in] : address type Returns - ESP_OK : success other : failed other : failed other : failed Parameters addr_type -- [in] : address type addr -- [in] : Device Address sid -- [in] : Advertising SID subfield in the ADI field used to identify the Periodic Advertising Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_periodic_adv_clear_dev(void) This function is used to remove all devices from the list of Periodic Advertisers in the Controller. Returns - ESP_OK : success other : failed other : failed other : failed Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_prefer_ext_connect_params_set(esp_bd_addr_t addr, esp_ble_gap_phy_mask_t phy_mask, const esp_ble_gap_conn_params_t *phy_1m_conn_params, const esp_ble_gap_conn_params_t *phy_2m_conn_params, const esp_ble_gap_conn_params_t *phy_coded_conn_params) This function is used to set aux connection parameters. Parameters addr -- [in] : device address phy_mask -- [in] : indicates the PHY(s) on which the advertising packets should be received on the primary advertising channel and the PHYs for which connection parameters have been specified. phy_1m_conn_params -- [in] : Scan connectable advertisements on the LE 1M PHY. Connection parameters for the LE 1M PHY are provided. phy_2m_conn_params -- [in] : Connection parameters for the LE 2M PHY are provided. phy_coded_conn_params -- [in] : Scan connectable advertisements on the LE Coded PHY. Connection parameters for the LE Coded PHY are provided. addr -- [in] : device address phy_mask -- [in] : indicates the PHY(s) on which the advertising packets should be received on the primary advertising channel and the PHYs for which connection parameters have been specified. phy_1m_conn_params -- [in] : Scan connectable advertisements on the LE 1M PHY. Connection parameters for the LE 1M PHY are provided. phy_2m_conn_params -- [in] : Connection parameters for the LE 2M PHY are provided. phy_coded_conn_params -- [in] : Scan connectable advertisements on the LE Coded PHY. Connection parameters for the LE Coded PHY are provided. addr -- [in] : device address Returns - ESP_OK : success other : failed other : failed other : failed Parameters addr -- [in] : device address phy_mask -- [in] : indicates the PHY(s) on which the advertising packets should be received on the primary advertising channel and the PHYs for which connection parameters have been specified. phy_1m_conn_params -- [in] : Scan connectable advertisements on the LE 1M PHY. Connection parameters for the LE 1M PHY are provided. phy_2m_conn_params -- [in] : Connection parameters for the LE 2M PHY are provided. phy_coded_conn_params -- [in] : Scan connectable advertisements on the LE Coded PHY. Connection parameters for the LE Coded PHY are provided. Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_periodic_adv_recv_enable(uint16_t sync_handle, uint8_t enable) This function is used to set periodic advertising receive enable. Parameters sync_handle -- [in] : Handle of periodic advertising sync enable -- [in] : Determines whether reporting and duplicate filtering are enabled or disabled sync_handle -- [in] : Handle of periodic advertising sync enable -- [in] : Determines whether reporting and duplicate filtering are enabled or disabled sync_handle -- [in] : Handle of periodic advertising sync Returns - ESP_OK : success other : failed other : failed other : failed Parameters sync_handle -- [in] : Handle of periodic advertising sync enable -- [in] : Determines whether reporting and duplicate filtering are enabled or disabled Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_periodic_adv_sync_trans(esp_bd_addr_t addr, uint16_t service_data, uint16_t sync_handle) This function is used to transfer periodic advertising sync. Parameters addr -- [in] : Peer device address service_data -- [in] : Service data used by Host sync_handle -- [in] : Handle of periodic advertising sync addr -- [in] : Peer device address service_data -- [in] : Service data used by Host sync_handle -- [in] : Handle of periodic advertising sync addr -- [in] : Peer device address Returns - ESP_OK : success other : failed other : failed other : failed Parameters addr -- [in] : Peer device address service_data -- [in] : Service data used by Host sync_handle -- [in] : Handle of periodic advertising sync Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_periodic_adv_set_info_trans(esp_bd_addr_t addr, uint16_t service_data, uint8_t adv_handle) This function is used to transfer periodic advertising set info. Parameters addr -- [in] : Peer device address service_data -- [in] : Service data used by Host adv_handle -- [in] : Handle of advertising set addr -- [in] : Peer device address service_data -- [in] : Service data used by Host adv_handle -- [in] : Handle of advertising set addr -- [in] : Peer device address Returns - ESP_OK : success other : failed other : failed other : failed Parameters addr -- [in] : Peer device address service_data -- [in] : Service data used by Host adv_handle -- [in] : Handle of advertising set Returns - ESP_OK : success other : failed esp_err_t esp_ble_gap_set_periodic_adv_sync_trans_params(esp_bd_addr_t addr, const esp_ble_gap_past_params_t *params) This function is used to set periodic advertising sync transfer params. Parameters addr -- [in] : Peer device address params -- [in] : Params of periodic advertising sync transfer addr -- [in] : Peer device address params -- [in] : Params of periodic advertising sync transfer addr -- [in] : Peer device address Returns - ESP_OK : success other : failed other : failed other : failed Parameters addr -- [in] : Peer device address params -- [in] : Params of periodic advertising sync transfer Returns - ESP_OK : success other : failed esp_err_t esp_ble_dtm_tx_start(const esp_ble_dtm_tx_t *tx_params) This function is used to start a test where the DUT generates reference packets at a fixed interval. Parameters tx_params -- [in] : DTM Transmitter parameters Returns - ESP_OK : success other : failed other : failed other : failed Parameters tx_params -- [in] : DTM Transmitter parameters Returns - ESP_OK : success other : failed esp_err_t esp_ble_dtm_rx_start(const esp_ble_dtm_rx_t *rx_params) This function is used to start a test where the DUT receives test reference packets at a fixed interval. Parameters rx_params -- [in] : DTM Receiver parameters Returns - ESP_OK : success other : failed other : failed other : failed Parameters rx_params -- [in] : DTM Receiver parameters Returns - ESP_OK : success other : failed esp_err_t esp_ble_dtm_enh_tx_start(const esp_ble_dtm_enh_tx_t *tx_params) This function is used to start a test where the DUT generates reference packets at a fixed interval. Parameters tx_params -- [in] : DTM Transmitter parameters Returns - ESP_OK : success other : failed other : failed other : failed Parameters tx_params -- [in] : DTM Transmitter parameters Returns - ESP_OK : success other : failed esp_err_t esp_ble_dtm_enh_rx_start(const esp_ble_dtm_enh_rx_t *rx_params) This function is used to start a test where the DUT receives test reference packets at a fixed interval. Parameters rx_params -- [in] : DTM Receiver parameters Returns - ESP_OK : success other : failed other : failed other : failed Parameters rx_params -- [in] : DTM Receiver parameters Returns - ESP_OK : success other : failed esp_err_t esp_ble_dtm_stop(void) This function is used to stop any test which is in progress. Returns - ESP_OK : success other : failed other : failed other : failed Returns - ESP_OK : success other : failed Unions union esp_ble_key_value_t #include <esp_gap_ble_api.h> union type of the security key value Public Members esp_ble_penc_keys_t penc_key received peer encryption key esp_ble_penc_keys_t penc_key received peer encryption key esp_ble_pcsrk_keys_t pcsrk_key received peer device SRK esp_ble_pcsrk_keys_t pcsrk_key received peer device SRK esp_ble_pid_keys_t pid_key peer device ID key esp_ble_pid_keys_t pid_key peer device ID key esp_ble_lenc_keys_t lenc_key local encryption reproduction keys LTK = = d1(ER,DIV,0) esp_ble_lenc_keys_t lenc_key local encryption reproduction keys LTK = = d1(ER,DIV,0) esp_ble_lcsrk_keys lcsrk_key local device CSRK = d1(ER,DIV,1) esp_ble_lcsrk_keys lcsrk_key local device CSRK = d1(ER,DIV,1) esp_ble_penc_keys_t penc_key union esp_ble_sec_t #include <esp_gap_ble_api.h> union associated with ble security Public Members esp_ble_sec_key_notif_t key_notif passkey notification esp_ble_sec_key_notif_t key_notif passkey notification esp_ble_sec_req_t ble_req BLE SMP related request esp_ble_sec_req_t ble_req BLE SMP related request esp_ble_key_t ble_key BLE SMP keys used when pairing esp_ble_key_t ble_key BLE SMP keys used when pairing esp_ble_local_id_keys_t ble_id_keys BLE IR event esp_ble_local_id_keys_t ble_id_keys BLE IR event esp_ble_local_oob_data_t oob_data BLE SMP secure connection OOB data esp_ble_local_oob_data_t oob_data BLE SMP secure connection OOB data esp_ble_auth_cmpl_t auth_cmpl Authentication complete indication. esp_ble_auth_cmpl_t auth_cmpl Authentication complete indication. esp_ble_sec_key_notif_t key_notif union esp_ble_gap_cb_param_t #include <esp_gap_ble_api.h> Gap callback parameters union. Public Members struct esp_ble_gap_cb_param_t::ble_get_dev_name_cmpl_evt_param get_dev_name_cmpl Event parameter of ESP_GAP_BLE_GET_DEV_NAME_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_get_dev_name_cmpl_evt_param get_dev_name_cmpl Event parameter of ESP_GAP_BLE_GET_DEV_NAME_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_adv_data_cmpl_evt_param adv_data_cmpl Event parameter of ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_adv_data_cmpl_evt_param adv_data_cmpl Event parameter of ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_scan_rsp_data_cmpl_evt_param scan_rsp_data_cmpl Event parameter of ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_scan_rsp_data_cmpl_evt_param scan_rsp_data_cmpl Event parameter of ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_scan_param_cmpl_evt_param scan_param_cmpl Event parameter of ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_scan_param_cmpl_evt_param scan_param_cmpl Event parameter of ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_scan_result_evt_param scan_rst Event parameter of ESP_GAP_BLE_SCAN_RESULT_EVT struct esp_ble_gap_cb_param_t::ble_scan_result_evt_param scan_rst Event parameter of ESP_GAP_BLE_SCAN_RESULT_EVT struct esp_ble_gap_cb_param_t::ble_adv_data_raw_cmpl_evt_param adv_data_raw_cmpl Event parameter of ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_adv_data_raw_cmpl_evt_param adv_data_raw_cmpl Event parameter of ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_scan_rsp_data_raw_cmpl_evt_param scan_rsp_data_raw_cmpl Event parameter of ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_scan_rsp_data_raw_cmpl_evt_param scan_rsp_data_raw_cmpl Event parameter of ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_adv_start_cmpl_evt_param adv_start_cmpl Event parameter of ESP_GAP_BLE_ADV_START_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_adv_start_cmpl_evt_param adv_start_cmpl Event parameter of ESP_GAP_BLE_ADV_START_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param scan_start_cmpl Event parameter of ESP_GAP_BLE_SCAN_START_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param scan_start_cmpl Event parameter of ESP_GAP_BLE_SCAN_START_COMPLETE_EVT esp_ble_sec_t ble_security ble gap security union type esp_ble_sec_t ble_security ble gap security union type struct esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param scan_stop_cmpl Event parameter of ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param scan_stop_cmpl Event parameter of ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_adv_stop_cmpl_evt_param adv_stop_cmpl Event parameter of ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_adv_stop_cmpl_evt_param adv_stop_cmpl Event parameter of ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_adv_clear_cmpl_evt_param adv_clear_cmpl Event parameter of ESP_GAP_BLE_ADV_CLEAR_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_adv_clear_cmpl_evt_param adv_clear_cmpl Event parameter of ESP_GAP_BLE_ADV_CLEAR_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_set_rand_cmpl_evt_param set_rand_addr_cmpl Event parameter of ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT struct esp_ble_gap_cb_param_t::ble_set_rand_cmpl_evt_param set_rand_addr_cmpl Event parameter of ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT struct esp_ble_gap_cb_param_t::ble_update_conn_params_evt_param update_conn_params Event parameter of ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT struct esp_ble_gap_cb_param_t::ble_update_conn_params_evt_param update_conn_params Event parameter of ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT struct esp_ble_gap_cb_param_t::ble_pkt_data_length_cmpl_evt_param pkt_data_length_cmpl Event parameter of ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_pkt_data_length_cmpl_evt_param pkt_data_length_cmpl Event parameter of ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_local_privacy_cmpl_evt_param local_privacy_cmpl Event parameter of ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_local_privacy_cmpl_evt_param local_privacy_cmpl Event parameter of ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_remove_bond_dev_cmpl_evt_param remove_bond_dev_cmpl Event parameter of ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_remove_bond_dev_cmpl_evt_param remove_bond_dev_cmpl Event parameter of ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_clear_bond_dev_cmpl_evt_param clear_bond_dev_cmpl Event parameter of ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_clear_bond_dev_cmpl_evt_param clear_bond_dev_cmpl Event parameter of ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_get_bond_dev_cmpl_evt_param get_bond_dev_cmpl Event parameter of ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_get_bond_dev_cmpl_evt_param get_bond_dev_cmpl Event parameter of ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_read_rssi_cmpl_evt_param read_rssi_cmpl Event parameter of ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_read_rssi_cmpl_evt_param read_rssi_cmpl Event parameter of ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_update_whitelist_cmpl_evt_param update_whitelist_cmpl Event parameter of ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_update_whitelist_cmpl_evt_param update_whitelist_cmpl Event parameter of ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_update_duplicate_exceptional_list_cmpl_evt_param update_duplicate_exceptional_list_cmpl Event parameter of ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_update_duplicate_exceptional_list_cmpl_evt_param update_duplicate_exceptional_list_cmpl Event parameter of ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_set_channels_evt_param ble_set_channels Event parameter of ESP_GAP_BLE_SET_CHANNELS_EVT struct esp_ble_gap_cb_param_t::ble_set_channels_evt_param ble_set_channels Event parameter of ESP_GAP_BLE_SET_CHANNELS_EVT struct esp_ble_gap_cb_param_t::ble_read_phy_cmpl_evt_param read_phy Event parameter of ESP_GAP_BLE_READ_PHY_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_read_phy_cmpl_evt_param read_phy Event parameter of ESP_GAP_BLE_READ_PHY_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_set_perf_def_phy_cmpl_evt_param set_perf_def_phy Event parameter of ESP_GAP_BLE_SET_PREFERRED_DEFAULT_PHY_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_set_perf_def_phy_cmpl_evt_param set_perf_def_phy Event parameter of ESP_GAP_BLE_SET_PREFERRED_DEFAULT_PHY_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_set_perf_phy_cmpl_evt_param set_perf_phy Event parameter of ESP_GAP_BLE_SET_PREFERRED_PHY_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_set_perf_phy_cmpl_evt_param set_perf_phy Event parameter of ESP_GAP_BLE_SET_PREFERRED_PHY_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_set_rand_addr_cmpl_evt_param ext_adv_set_rand_addr Event parameter of ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_set_rand_addr_cmpl_evt_param ext_adv_set_rand_addr Event parameter of ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_set_params_cmpl_evt_param ext_adv_set_params Event parameter of ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_set_params_cmpl_evt_param ext_adv_set_params Event parameter of ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_data_set_cmpl_evt_param ext_adv_data_set Event parameter of ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_data_set_cmpl_evt_param ext_adv_data_set Event parameter of ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_scan_rsp_set_cmpl_evt_param scan_rsp_set Event parameter of ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_scan_rsp_set_cmpl_evt_param scan_rsp_set Event parameter of ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_start_cmpl_evt_param ext_adv_start Event parameter of ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_start_cmpl_evt_param ext_adv_start Event parameter of ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_stop_cmpl_evt_param ext_adv_stop Event parameter of ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_stop_cmpl_evt_param ext_adv_stop Event parameter of ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_set_remove_cmpl_evt_param ext_adv_remove Event parameter of ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_set_remove_cmpl_evt_param ext_adv_remove Event parameter of ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_set_clear_cmpl_evt_param ext_adv_clear Event parameter of ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_set_clear_cmpl_evt_param ext_adv_clear Event parameter of ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_set_params_cmpl_param peroid_adv_set_params Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_set_params_cmpl_param peroid_adv_set_params Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_data_set_cmpl_param period_adv_data_set Event parameter of ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_data_set_cmpl_param period_adv_data_set Event parameter of ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_start_cmpl_param period_adv_start Event parameter of ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_start_cmpl_param period_adv_start Event parameter of ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_stop_cmpl_param period_adv_stop Event parameter of ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_stop_cmpl_param period_adv_stop Event parameter of ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_period_adv_create_sync_cmpl_param period_adv_create_sync Event parameter of ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_period_adv_create_sync_cmpl_param period_adv_create_sync Event parameter of ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_period_adv_sync_cancel_cmpl_param period_adv_sync_cancel Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_period_adv_sync_cancel_cmpl_param period_adv_sync_cancel Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_period_adv_sync_terminate_cmpl_param period_adv_sync_term Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_period_adv_sync_terminate_cmpl_param period_adv_sync_term Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_period_adv_add_dev_cmpl_param period_adv_add_dev Event parameter of ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_period_adv_add_dev_cmpl_param period_adv_add_dev Event parameter of ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_period_adv_remove_dev_cmpl_param period_adv_remove_dev Event parameter of ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_period_adv_remove_dev_cmpl_param period_adv_remove_dev Event parameter of ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_period_adv_clear_dev_cmpl_param period_adv_clear_dev Event parameter of ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_period_adv_clear_dev_cmpl_param period_adv_clear_dev Event parameter of ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_set_ext_scan_params_cmpl_param set_ext_scan_params Event parameter of ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_set_ext_scan_params_cmpl_param set_ext_scan_params Event parameter of ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_scan_start_cmpl_param ext_scan_start Event parameter of ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_scan_start_cmpl_param ext_scan_start Event parameter of ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_scan_stop_cmpl_param ext_scan_stop Event parameter of ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_scan_stop_cmpl_param ext_scan_stop Event parameter of ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_conn_params_set_cmpl_param ext_conn_params_set Event parameter of ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_conn_params_set_cmpl_param ext_conn_params_set Event parameter of ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_adv_terminate_param adv_terminate Event parameter of ESP_GAP_BLE_ADV_TERMINATED_EVT struct esp_ble_gap_cb_param_t::ble_adv_terminate_param adv_terminate Event parameter of ESP_GAP_BLE_ADV_TERMINATED_EVT struct esp_ble_gap_cb_param_t::ble_scan_req_received_param scan_req_received Event parameter of ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT struct esp_ble_gap_cb_param_t::ble_scan_req_received_param scan_req_received Event parameter of ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT struct esp_ble_gap_cb_param_t::ble_channel_sel_alg_param channel_sel_alg Event parameter of ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT struct esp_ble_gap_cb_param_t::ble_channel_sel_alg_param channel_sel_alg Event parameter of ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_lost_param periodic_adv_sync_lost Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_lost_param periodic_adv_sync_lost Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_estab_param periodic_adv_sync_estab Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_estab_param periodic_adv_sync_estab Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT struct esp_ble_gap_cb_param_t::ble_phy_update_cmpl_param phy_update Event parameter of ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_phy_update_cmpl_param phy_update Event parameter of ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_report_param ext_adv_report Event parameter of ESP_GAP_BLE_EXT_ADV_REPORT_EVT struct esp_ble_gap_cb_param_t::ble_ext_adv_report_param ext_adv_report Event parameter of ESP_GAP_BLE_EXT_ADV_REPORT_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_report_param period_adv_report Event parameter of ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_report_param period_adv_report Event parameter of ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_recv_enable_cmpl_param period_adv_recv_enable Event parameter of ESP_GAP_BLE_PERIODIC_ADV_RECV_ENABLE_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_recv_enable_cmpl_param period_adv_recv_enable Event parameter of ESP_GAP_BLE_PERIODIC_ADV_RECV_ENABLE_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_trans_cmpl_param period_adv_sync_trans Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_trans_cmpl_param period_adv_sync_trans Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_set_info_trans_cmpl_param period_adv_set_info_trans Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SET_INFO_TRANS_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_set_info_trans_cmpl_param period_adv_set_info_trans Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SET_INFO_TRANS_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_set_past_params_cmpl_param set_past_params Event parameter of ESP_GAP_BLE_SET_PAST_PARAMS_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_set_past_params_cmpl_param set_past_params Event parameter of ESP_GAP_BLE_SET_PAST_PARAMS_COMPLETE_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_trans_recv_param past_received Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_RECV_EVT struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_trans_recv_param past_received Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_RECV_EVT struct esp_ble_gap_cb_param_t::ble_dtm_state_update_evt_param dtm_state_update Event parameter of ESP_GAP_BLE_DTM_TEST_UPDATE_EVT struct esp_ble_gap_cb_param_t::ble_dtm_state_update_evt_param dtm_state_update Event parameter of ESP_GAP_BLE_DTM_TEST_UPDATE_EVT struct ble_adv_clear_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_CLEAR_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate adv clear operation success status esp_bt_status_t status Indicate adv clear operation success status esp_bt_status_t status struct ble_adv_clear_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_CLEAR_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate adv clear operation success status struct ble_adv_data_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the set advertising data operation success status esp_bt_status_t status Indicate the set advertising data operation success status esp_bt_status_t status struct ble_adv_data_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the set advertising data operation success status struct ble_adv_data_raw_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the set raw advertising data operation success status esp_bt_status_t status Indicate the set raw advertising data operation success status esp_bt_status_t status struct ble_adv_data_raw_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the set raw advertising data operation success status struct ble_adv_start_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_START_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate advertising start operation success status esp_bt_status_t status Indicate advertising start operation success status esp_bt_status_t status struct ble_adv_start_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_START_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate advertising start operation success status struct ble_adv_stop_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate adv stop operation success status esp_bt_status_t status Indicate adv stop operation success status esp_bt_status_t status struct ble_adv_stop_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate adv stop operation success status struct ble_adv_terminate_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_TERMINATED_EVT. struct ble_adv_terminate_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_TERMINATED_EVT. struct ble_channel_sel_alg_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT. struct ble_channel_sel_alg_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT. struct ble_clear_bond_dev_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the clear bond device operation success status esp_bt_status_t status Indicate the clear bond device operation success status esp_bt_status_t status struct ble_clear_bond_dev_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the clear bond device operation success status struct ble_dtm_state_update_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_DTM_TEST_UPDATE_EVT. Public Members esp_bt_status_t status Indicate DTM operation success status esp_bt_status_t status Indicate DTM operation success status esp_ble_dtm_update_evt_t update_evt DTM state change event, 0x00: DTM TX start, 0x01: DTM RX start, 0x02:DTM end esp_ble_dtm_update_evt_t update_evt DTM state change event, 0x00: DTM TX start, 0x01: DTM RX start, 0x02:DTM end uint16_t num_of_pkt number of packets received, only valid if update_evt is DTM_TEST_STOP_EVT and shall be reported as 0 for a transmitter uint16_t num_of_pkt number of packets received, only valid if update_evt is DTM_TEST_STOP_EVT and shall be reported as 0 for a transmitter esp_bt_status_t status struct ble_dtm_state_update_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_DTM_TEST_UPDATE_EVT. Public Members esp_bt_status_t status Indicate DTM operation success status esp_ble_dtm_update_evt_t update_evt DTM state change event, 0x00: DTM TX start, 0x01: DTM RX start, 0x02:DTM end uint16_t num_of_pkt number of packets received, only valid if update_evt is DTM_TEST_STOP_EVT and shall be reported as 0 for a transmitter struct ble_ext_adv_data_set_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend advertising data set status esp_bt_status_t status Indicate extend advertising data set status esp_bt_status_t status struct ble_ext_adv_data_set_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend advertising data set status struct ble_ext_adv_report_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_REPORT_EVT. Public Members esp_ble_gap_ext_adv_reprot_t params extend advertising report parameters esp_ble_gap_ext_adv_reprot_t params extend advertising report parameters esp_ble_gap_ext_adv_reprot_t params struct ble_ext_adv_report_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_REPORT_EVT. Public Members esp_ble_gap_ext_adv_reprot_t params extend advertising report parameters struct ble_ext_adv_scan_rsp_set_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend advertising scan response data set status esp_bt_status_t status Indicate extend advertising scan response data set status esp_bt_status_t status struct ble_ext_adv_scan_rsp_set_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend advertising scan response data set status struct ble_ext_adv_set_clear_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT. struct ble_ext_adv_set_clear_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT. struct ble_ext_adv_set_params_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend advertising parameters set status esp_bt_status_t status Indicate extend advertising parameters set status esp_bt_status_t status struct ble_ext_adv_set_params_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend advertising parameters set status struct ble_ext_adv_set_rand_addr_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend advertising random address set status esp_bt_status_t status Indicate extend advertising random address set status esp_bt_status_t status struct ble_ext_adv_set_rand_addr_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend advertising random address set status struct ble_ext_adv_set_remove_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT. struct ble_ext_adv_set_remove_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT. struct ble_ext_adv_start_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate advertising start operation success status esp_bt_status_t status Indicate advertising start operation success status esp_bt_status_t status struct ble_ext_adv_start_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate advertising start operation success status struct ble_ext_adv_stop_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT. struct ble_ext_adv_stop_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT. struct ble_ext_conn_params_set_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend connection parameters set status esp_bt_status_t status Indicate extend connection parameters set status esp_bt_status_t status struct ble_ext_conn_params_set_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend connection parameters set status struct ble_ext_scan_start_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend advertising start status esp_bt_status_t status Indicate extend advertising start status esp_bt_status_t status struct ble_ext_scan_start_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend advertising start status struct ble_ext_scan_stop_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend advertising stop status esp_bt_status_t status Indicate extend advertising stop status esp_bt_status_t status struct ble_ext_scan_stop_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend advertising stop status struct ble_get_bond_dev_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the get bond device operation success status esp_bt_status_t status Indicate the get bond device operation success status uint8_t dev_num Indicate the get number device in the bond list uint8_t dev_num Indicate the get number device in the bond list esp_ble_bond_dev_t *bond_dev the pointer to the bond device Structure esp_ble_bond_dev_t *bond_dev the pointer to the bond device Structure esp_bt_status_t status struct ble_get_bond_dev_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the get bond device operation success status uint8_t dev_num Indicate the get number device in the bond list esp_ble_bond_dev_t *bond_dev the pointer to the bond device Structure struct ble_get_dev_name_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_GET_DEV_NAME_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the get device name success status esp_bt_status_t status Indicate the get device name success status char *name Name of bluetooth device char *name Name of bluetooth device esp_bt_status_t status struct ble_get_dev_name_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_GET_DEV_NAME_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the get device name success status char *name Name of bluetooth device struct ble_local_privacy_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the set local privacy operation success status esp_bt_status_t status Indicate the set local privacy operation success status esp_bt_status_t status struct ble_local_privacy_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the set local privacy operation success status struct ble_period_adv_add_dev_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising device list add status esp_bt_status_t status Indicate periodic advertising device list add status esp_bt_status_t status struct ble_period_adv_add_dev_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising device list add status struct ble_period_adv_clear_dev_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising device list clean status esp_bt_status_t status Indicate periodic advertising device list clean status esp_bt_status_t status struct ble_period_adv_clear_dev_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising device list clean status struct ble_period_adv_create_sync_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising create sync status esp_bt_status_t status Indicate periodic advertising create sync status esp_bt_status_t status struct ble_period_adv_create_sync_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising create sync status struct ble_period_adv_remove_dev_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising device list remove status esp_bt_status_t status Indicate periodic advertising device list remove status esp_bt_status_t status struct ble_period_adv_remove_dev_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising device list remove status struct ble_period_adv_sync_cancel_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising sync cancel status esp_bt_status_t status Indicate periodic advertising sync cancel status esp_bt_status_t status struct ble_period_adv_sync_cancel_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising sync cancel status struct ble_period_adv_sync_terminate_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising sync terminate status esp_bt_status_t status Indicate periodic advertising sync terminate status esp_bt_status_t status struct ble_period_adv_sync_terminate_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising sync terminate status struct ble_periodic_adv_data_set_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising data set status esp_bt_status_t status Indicate periodic advertising data set status esp_bt_status_t status struct ble_periodic_adv_data_set_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising data set status struct ble_periodic_adv_recv_enable_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_RECV_ENABLE_COMPLETE_EVT. Public Members esp_bt_status_t status Set periodic advertising receive enable status esp_bt_status_t status Set periodic advertising receive enable status esp_bt_status_t status struct ble_periodic_adv_recv_enable_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_RECV_ENABLE_COMPLETE_EVT. Public Members esp_bt_status_t status Set periodic advertising receive enable status struct ble_periodic_adv_report_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT. Public Members esp_ble_gap_periodic_adv_report_t params periodic advertising report parameters esp_ble_gap_periodic_adv_report_t params periodic advertising report parameters esp_ble_gap_periodic_adv_report_t params struct ble_periodic_adv_report_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT. Public Members esp_ble_gap_periodic_adv_report_t params periodic advertising report parameters struct ble_periodic_adv_set_info_trans_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SET_INFO_TRANS_COMPLETE_EVT. Public Members esp_bt_status_t status Periodic advertising set info transfer status esp_bt_status_t status Periodic advertising set info transfer status esp_bd_addr_t bda The remote device address esp_bd_addr_t bda The remote device address esp_bt_status_t status struct ble_periodic_adv_set_info_trans_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SET_INFO_TRANS_COMPLETE_EVT. Public Members esp_bt_status_t status Periodic advertising set info transfer status esp_bd_addr_t bda The remote device address struct ble_periodic_adv_set_params_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertisingparameters set status esp_bt_status_t status Indicate periodic advertisingparameters set status esp_bt_status_t status struct ble_periodic_adv_set_params_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertisingparameters set status struct ble_periodic_adv_start_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising start status esp_bt_status_t status Indicate periodic advertising start status esp_bt_status_t status struct ble_periodic_adv_start_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising start status struct ble_periodic_adv_stop_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising stop status esp_bt_status_t status Indicate periodic advertising stop status esp_bt_status_t status struct ble_periodic_adv_stop_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate periodic advertising stop status struct ble_periodic_adv_sync_estab_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT. Public Members uint8_t status periodic advertising sync status uint8_t status periodic advertising sync status uint16_t sync_handle periodic advertising sync handle uint16_t sync_handle periodic advertising sync handle uint8_t sid periodic advertising sid uint8_t sid periodic advertising sid esp_ble_addr_type_t adv_addr_type periodic advertising address type esp_ble_addr_type_t adv_addr_type periodic advertising address type esp_bd_addr_t adv_addr periodic advertising address esp_bd_addr_t adv_addr periodic advertising address esp_ble_gap_phy_t adv_phy periodic advertising phy type esp_ble_gap_phy_t adv_phy periodic advertising phy type uint16_t period_adv_interval periodic advertising interval uint16_t period_adv_interval periodic advertising interval uint8_t adv_clk_accuracy periodic advertising clock accuracy uint8_t adv_clk_accuracy periodic advertising clock accuracy uint8_t status struct ble_periodic_adv_sync_estab_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT. Public Members uint8_t status periodic advertising sync status uint16_t sync_handle periodic advertising sync handle uint8_t sid periodic advertising sid esp_ble_addr_type_t adv_addr_type periodic advertising address type esp_bd_addr_t adv_addr periodic advertising address esp_ble_gap_phy_t adv_phy periodic advertising phy type uint16_t period_adv_interval periodic advertising interval uint8_t adv_clk_accuracy periodic advertising clock accuracy struct ble_periodic_adv_sync_lost_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT. Public Members uint16_t sync_handle sync handle uint16_t sync_handle sync handle uint16_t sync_handle struct ble_periodic_adv_sync_lost_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT. Public Members uint16_t sync_handle sync handle struct ble_periodic_adv_sync_trans_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_COMPLETE_EVT. Public Members esp_bt_status_t status Periodic advertising sync transfer status esp_bt_status_t status Periodic advertising sync transfer status esp_bd_addr_t bda The remote device address esp_bd_addr_t bda The remote device address esp_bt_status_t status struct ble_periodic_adv_sync_trans_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_COMPLETE_EVT. Public Members esp_bt_status_t status Periodic advertising sync transfer status esp_bd_addr_t bda The remote device address struct ble_periodic_adv_sync_trans_recv_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_RECV_EVT. Public Members esp_bt_status_t status Periodic advertising sync transfer received status esp_bt_status_t status Periodic advertising sync transfer received status esp_bd_addr_t bda The remote device address esp_bd_addr_t bda The remote device address uint16_t service_data The value provided by the peer device uint16_t service_data The value provided by the peer device uint16_t sync_handle Periodic advertising sync handle uint16_t sync_handle Periodic advertising sync handle uint8_t adv_sid Periodic advertising set id uint8_t adv_sid Periodic advertising set id uint8_t adv_addr_type Periodic advertiser address type uint8_t adv_addr_type Periodic advertiser address type esp_bd_addr_t adv_addr Periodic advertiser address esp_bd_addr_t adv_addr Periodic advertiser address esp_ble_gap_phy_t adv_phy Periodic advertising PHY esp_ble_gap_phy_t adv_phy Periodic advertising PHY uint16_t adv_interval Periodic advertising interval uint16_t adv_interval Periodic advertising interval uint8_t adv_clk_accuracy Periodic advertising clock accuracy uint8_t adv_clk_accuracy Periodic advertising clock accuracy esp_bt_status_t status struct ble_periodic_adv_sync_trans_recv_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_RECV_EVT. Public Members esp_bt_status_t status Periodic advertising sync transfer received status esp_bd_addr_t bda The remote device address uint16_t service_data The value provided by the peer device uint16_t sync_handle Periodic advertising sync handle uint8_t adv_sid Periodic advertising set id uint8_t adv_addr_type Periodic advertiser address type esp_bd_addr_t adv_addr Periodic advertiser address esp_ble_gap_phy_t adv_phy Periodic advertising PHY uint16_t adv_interval Periodic advertising interval uint8_t adv_clk_accuracy Periodic advertising clock accuracy struct ble_phy_update_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT. Public Members esp_bt_status_t status phy update status esp_bt_status_t status phy update status esp_bd_addr_t bda address esp_bd_addr_t bda address esp_ble_gap_phy_t tx_phy tx phy type esp_ble_gap_phy_t tx_phy tx phy type esp_ble_gap_phy_t rx_phy rx phy type esp_ble_gap_phy_t rx_phy rx phy type esp_bt_status_t status struct ble_phy_update_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT. Public Members esp_bt_status_t status phy update status esp_bd_addr_t bda address esp_ble_gap_phy_t tx_phy tx phy type esp_ble_gap_phy_t rx_phy rx phy type struct ble_pkt_data_length_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the set pkt data length operation success status esp_bt_status_t status Indicate the set pkt data length operation success status esp_ble_pkt_data_length_params_t params pkt data length value esp_ble_pkt_data_length_params_t params pkt data length value esp_bt_status_t status struct ble_pkt_data_length_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the set pkt data length operation success status esp_ble_pkt_data_length_params_t params pkt data length value struct ble_read_phy_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_READ_PHY_COMPLETE_EVT. Public Members esp_bt_status_t status read phy complete status esp_bt_status_t status read phy complete status esp_bd_addr_t bda read phy address esp_bd_addr_t bda read phy address esp_ble_gap_phy_t tx_phy tx phy type esp_ble_gap_phy_t tx_phy tx phy type esp_ble_gap_phy_t rx_phy rx phy type esp_ble_gap_phy_t rx_phy rx phy type esp_bt_status_t status struct ble_read_phy_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_READ_PHY_COMPLETE_EVT. Public Members esp_bt_status_t status read phy complete status esp_bd_addr_t bda read phy address esp_ble_gap_phy_t tx_phy tx phy type esp_ble_gap_phy_t rx_phy rx phy type struct ble_read_rssi_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the read adv tx power operation success status esp_bt_status_t status Indicate the read adv tx power operation success status int8_t rssi The ble remote device rssi value, the range is from -127 to 20, the unit is dbm, if the RSSI cannot be read, the RSSI metric shall be set to 127. int8_t rssi The ble remote device rssi value, the range is from -127 to 20, the unit is dbm, if the RSSI cannot be read, the RSSI metric shall be set to 127. esp_bd_addr_t remote_addr The remote device address esp_bd_addr_t remote_addr The remote device address esp_bt_status_t status struct ble_read_rssi_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the read adv tx power operation success status int8_t rssi The ble remote device rssi value, the range is from -127 to 20, the unit is dbm, if the RSSI cannot be read, the RSSI metric shall be set to 127. esp_bd_addr_t remote_addr The remote device address struct ble_remove_bond_dev_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the remove bond device operation success status esp_bt_status_t status Indicate the remove bond device operation success status esp_bd_addr_t bd_addr The device address which has been remove from the bond list esp_bd_addr_t bd_addr The device address which has been remove from the bond list esp_bt_status_t status struct ble_remove_bond_dev_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the remove bond device operation success status esp_bd_addr_t bd_addr The device address which has been remove from the bond list struct ble_scan_param_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the set scan param operation success status esp_bt_status_t status Indicate the set scan param operation success status esp_bt_status_t status struct ble_scan_param_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the set scan param operation success status struct ble_scan_req_received_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT. Public Members uint8_t adv_instance extend advertising handle uint8_t adv_instance extend advertising handle esp_ble_addr_type_t scan_addr_type scanner address type esp_ble_addr_type_t scan_addr_type scanner address type esp_bd_addr_t scan_addr scanner address esp_bd_addr_t scan_addr scanner address uint8_t adv_instance struct ble_scan_req_received_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT. Public Members uint8_t adv_instance extend advertising handle esp_ble_addr_type_t scan_addr_type scanner address type esp_bd_addr_t scan_addr scanner address struct ble_scan_result_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_RESULT_EVT. Public Members esp_gap_search_evt_t search_evt Search event type esp_gap_search_evt_t search_evt Search event type esp_bd_addr_t bda Bluetooth device address which has been searched esp_bd_addr_t bda Bluetooth device address which has been searched esp_bt_dev_type_t dev_type Device type esp_bt_dev_type_t dev_type Device type esp_ble_addr_type_t ble_addr_type Ble device address type esp_ble_addr_type_t ble_addr_type Ble device address type esp_ble_evt_type_t ble_evt_type Ble scan result event type esp_ble_evt_type_t ble_evt_type Ble scan result event type int rssi Searched device's RSSI int rssi Searched device's RSSI uint8_t ble_adv[ESP_BLE_ADV_DATA_LEN_MAX + ESP_BLE_SCAN_RSP_DATA_LEN_MAX] Received EIR uint8_t ble_adv[ESP_BLE_ADV_DATA_LEN_MAX + ESP_BLE_SCAN_RSP_DATA_LEN_MAX] Received EIR int flag Advertising data flag bit int flag Advertising data flag bit int num_resps Scan result number int num_resps Scan result number uint8_t adv_data_len Adv data length uint8_t adv_data_len Adv data length uint8_t scan_rsp_len Scan response length uint8_t scan_rsp_len Scan response length uint32_t num_dis The number of discard packets uint32_t num_dis The number of discard packets esp_gap_search_evt_t search_evt struct ble_scan_result_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_RESULT_EVT. Public Members esp_gap_search_evt_t search_evt Search event type esp_bd_addr_t bda Bluetooth device address which has been searched esp_bt_dev_type_t dev_type Device type esp_ble_addr_type_t ble_addr_type Ble device address type esp_ble_evt_type_t ble_evt_type Ble scan result event type int rssi Searched device's RSSI uint8_t ble_adv[ESP_BLE_ADV_DATA_LEN_MAX + ESP_BLE_SCAN_RSP_DATA_LEN_MAX] Received EIR int flag Advertising data flag bit int num_resps Scan result number uint8_t adv_data_len Adv data length uint8_t scan_rsp_len Scan response length uint32_t num_dis The number of discard packets struct ble_scan_rsp_data_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the set scan response data operation success status esp_bt_status_t status Indicate the set scan response data operation success status esp_bt_status_t status struct ble_scan_rsp_data_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the set scan response data operation success status struct ble_scan_rsp_data_raw_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the set raw advertising data operation success status esp_bt_status_t status Indicate the set raw advertising data operation success status esp_bt_status_t status struct ble_scan_rsp_data_raw_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the set raw advertising data operation success status struct ble_scan_start_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_START_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate scan start operation success status esp_bt_status_t status Indicate scan start operation success status esp_bt_status_t status struct ble_scan_start_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_START_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate scan start operation success status struct ble_scan_stop_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate scan stop operation success status esp_bt_status_t status Indicate scan stop operation success status esp_bt_status_t status struct ble_scan_stop_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate scan stop operation success status struct ble_set_channels_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_CHANNELS_EVT. Public Members esp_bt_status_t stat BLE set channel status esp_bt_status_t stat BLE set channel status esp_bt_status_t stat struct ble_set_channels_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_CHANNELS_EVT. Public Members esp_bt_status_t stat BLE set channel status struct ble_set_ext_scan_params_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend advertising parameters set status esp_bt_status_t status Indicate extend advertising parameters set status esp_bt_status_t status struct ble_set_ext_scan_params_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate extend advertising parameters set status struct ble_set_past_params_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PAST_PARAMS_COMPLETE_EVT. Public Members esp_bt_status_t status Set periodic advertising sync transfer params status esp_bt_status_t status Set periodic advertising sync transfer params status esp_bd_addr_t bda The remote device address esp_bd_addr_t bda The remote device address esp_bt_status_t status struct ble_set_past_params_cmpl_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PAST_PARAMS_COMPLETE_EVT. Public Members esp_bt_status_t status Set periodic advertising sync transfer params status esp_bd_addr_t bda The remote device address struct ble_set_perf_def_phy_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PREFERRED_DEFAULT_PHY_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate perf default phy set status esp_bt_status_t status Indicate perf default phy set status esp_bt_status_t status struct ble_set_perf_def_phy_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PREFERRED_DEFAULT_PHY_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate perf default phy set status struct ble_set_perf_phy_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PREFERRED_PHY_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate perf phy set status esp_bt_status_t status Indicate perf phy set status esp_bt_status_t status struct ble_set_perf_phy_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PREFERRED_PHY_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate perf phy set status struct ble_set_rand_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT. Public Members esp_bt_status_t status Indicate set static rand address operation success status esp_bt_status_t status Indicate set static rand address operation success status esp_bt_status_t status struct ble_set_rand_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT. Public Members esp_bt_status_t status Indicate set static rand address operation success status struct ble_update_conn_params_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT. Public Members esp_bt_status_t status Indicate update connection parameters success status esp_bt_status_t status Indicate update connection parameters success status esp_bd_addr_t bda Bluetooth device address esp_bd_addr_t bda Bluetooth device address uint16_t min_int Min connection interval uint16_t min_int Min connection interval uint16_t max_int Max connection interval uint16_t max_int Max connection interval uint16_t latency Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 uint16_t latency Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 uint16_t conn_int Current connection interval uint16_t conn_int Current connection interval uint16_t timeout Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec uint16_t timeout Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec esp_bt_status_t status struct ble_update_conn_params_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT. Public Members esp_bt_status_t status Indicate update connection parameters success status esp_bd_addr_t bda Bluetooth device address uint16_t min_int Min connection interval uint16_t max_int Max connection interval uint16_t latency Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 uint16_t conn_int Current connection interval uint16_t timeout Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec struct ble_update_duplicate_exceptional_list_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate update duplicate scan exceptional list operation success status esp_bt_status_t status Indicate update duplicate scan exceptional list operation success status uint8_t subcode Define in esp_bt_duplicate_exceptional_subcode_type_t uint8_t subcode Define in esp_bt_duplicate_exceptional_subcode_type_t uint16_t length The length of device_info uint16_t length The length of device_info esp_duplicate_info_t device_info device information, when subcode is ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_CLEAN, the value is invalid esp_duplicate_info_t device_info device information, when subcode is ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_CLEAN, the value is invalid esp_bt_status_t status struct ble_update_duplicate_exceptional_list_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate update duplicate scan exceptional list operation success status uint8_t subcode Define in esp_bt_duplicate_exceptional_subcode_type_t uint16_t length The length of device_info esp_duplicate_info_t device_info device information, when subcode is ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_CLEAN, the value is invalid struct ble_update_whitelist_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the add or remove whitelist operation success status esp_bt_status_t status Indicate the add or remove whitelist operation success status esp_ble_wl_operation_t wl_operation The value is ESP_BLE_WHITELIST_ADD if add address to whitelist operation success, ESP_BLE_WHITELIST_REMOVE if remove address from the whitelist operation success esp_ble_wl_operation_t wl_operation The value is ESP_BLE_WHITELIST_ADD if add address to whitelist operation success, ESP_BLE_WHITELIST_REMOVE if remove address from the whitelist operation success esp_bt_status_t status struct ble_update_whitelist_cmpl_evt_param #include <esp_gap_ble_api.h> ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT. Public Members esp_bt_status_t status Indicate the add or remove whitelist operation success status esp_ble_wl_operation_t wl_operation The value is ESP_BLE_WHITELIST_ADD if add address to whitelist operation success, ESP_BLE_WHITELIST_REMOVE if remove address from the whitelist operation success struct esp_ble_gap_cb_param_t::ble_get_dev_name_cmpl_evt_param get_dev_name_cmpl Structures struct esp_ble_dtm_tx_t DTM TX parameters. Public Members uint8_t tx_channel channel for sending test data, tx_channel = (Frequency -2402)/2, tx_channel range:0x00-0x27, Frequency range: 2402 MHz to 2480 MHz uint8_t tx_channel channel for sending test data, tx_channel = (Frequency -2402)/2, tx_channel range:0x00-0x27, Frequency range: 2402 MHz to 2480 MHz uint8_t len_of_data length in bytes of payload data in each packet uint8_t len_of_data length in bytes of payload data in each packet esp_ble_dtm_pkt_payload_t pkt_payload packet payload type. value range: 0x00-0x07 esp_ble_dtm_pkt_payload_t pkt_payload packet payload type. value range: 0x00-0x07 uint8_t tx_channel struct esp_ble_dtm_rx_t DTM RX parameters. Public Members uint8_t rx_channel channel for test data reception, rx_channel = (Frequency -2402)/2, tx_channel range:0x00-0x27, Frequency range: 2402 MHz to 2480 MHz uint8_t rx_channel channel for test data reception, rx_channel = (Frequency -2402)/2, tx_channel range:0x00-0x27, Frequency range: 2402 MHz to 2480 MHz uint8_t rx_channel struct esp_ble_adv_params_t Advertising parameters. Public Members uint16_t adv_int_min Minimum advertising interval for undirected and low duty cycle directed advertising. Range: 0x0020 to 0x4000 Default: N = 0x0800 (1.28 second) Time = N * 0.625 msec Time Range: 20 ms to 10.24 sec uint16_t adv_int_min Minimum advertising interval for undirected and low duty cycle directed advertising. Range: 0x0020 to 0x4000 Default: N = 0x0800 (1.28 second) Time = N * 0.625 msec Time Range: 20 ms to 10.24 sec uint16_t adv_int_max Maximum advertising interval for undirected and low duty cycle directed advertising. Range: 0x0020 to 0x4000 Default: N = 0x0800 (1.28 second) Time = N * 0.625 msec Time Range: 20 ms to 10.24 sec Advertising max interval uint16_t adv_int_max Maximum advertising interval for undirected and low duty cycle directed advertising. Range: 0x0020 to 0x4000 Default: N = 0x0800 (1.28 second) Time = N * 0.625 msec Time Range: 20 ms to 10.24 sec Advertising max interval esp_ble_adv_type_t adv_type Advertising type esp_ble_adv_type_t adv_type Advertising type esp_ble_addr_type_t own_addr_type Owner bluetooth device address type esp_ble_addr_type_t own_addr_type Owner bluetooth device address type esp_bd_addr_t peer_addr Peer device bluetooth device address esp_bd_addr_t peer_addr Peer device bluetooth device address esp_ble_addr_type_t peer_addr_type Peer device bluetooth device address type, only support public address type and random address type esp_ble_addr_type_t peer_addr_type Peer device bluetooth device address type, only support public address type and random address type esp_ble_adv_channel_t channel_map Advertising channel map esp_ble_adv_channel_t channel_map Advertising channel map esp_ble_adv_filter_t adv_filter_policy Advertising filter policy esp_ble_adv_filter_t adv_filter_policy Advertising filter policy uint16_t adv_int_min struct esp_ble_adv_data_t Advertising data content, according to "Supplement to the Bluetooth Core Specification". Public Members bool set_scan_rsp Set this advertising data as scan response or not bool set_scan_rsp Set this advertising data as scan response or not bool include_name Advertising data include device name or not bool include_name Advertising data include device name or not bool include_txpower Advertising data include TX power bool include_txpower Advertising data include TX power int min_interval Advertising data show slave preferred connection min interval. The connection interval in the following manner: connIntervalmin = Conn_Interval_Min * 1.25 ms Conn_Interval_Min range: 0x0006 to 0x0C80 Value of 0xFFFF indicates no specific minimum. Values not defined above are reserved for future use. int min_interval Advertising data show slave preferred connection min interval. The connection interval in the following manner: connIntervalmin = Conn_Interval_Min * 1.25 ms Conn_Interval_Min range: 0x0006 to 0x0C80 Value of 0xFFFF indicates no specific minimum. Values not defined above are reserved for future use. int max_interval Advertising data show slave preferred connection max interval. The connection interval in the following manner: connIntervalmax = Conn_Interval_Max * 1.25 ms Conn_Interval_Max range: 0x0006 to 0x0C80 Conn_Interval_Max shall be equal to or greater than the Conn_Interval_Min. Value of 0xFFFF indicates no specific maximum. Values not defined above are reserved for future use. int max_interval Advertising data show slave preferred connection max interval. The connection interval in the following manner: connIntervalmax = Conn_Interval_Max * 1.25 ms Conn_Interval_Max range: 0x0006 to 0x0C80 Conn_Interval_Max shall be equal to or greater than the Conn_Interval_Min. Value of 0xFFFF indicates no specific maximum. Values not defined above are reserved for future use. int appearance External appearance of device int appearance External appearance of device uint16_t manufacturer_len Manufacturer data length uint16_t manufacturer_len Manufacturer data length uint8_t *p_manufacturer_data Manufacturer data point uint8_t *p_manufacturer_data Manufacturer data point uint16_t service_data_len Service data length uint16_t service_data_len Service data length uint8_t *p_service_data Service data point uint8_t *p_service_data Service data point uint16_t service_uuid_len Service uuid length uint16_t service_uuid_len Service uuid length uint8_t *p_service_uuid Service uuid array point uint8_t *p_service_uuid Service uuid array point uint8_t flag Advertising flag of discovery mode, see BLE_ADV_DATA_FLAG detail uint8_t flag Advertising flag of discovery mode, see BLE_ADV_DATA_FLAG detail bool set_scan_rsp struct esp_ble_scan_params_t Ble scan parameters. Public Members esp_ble_scan_type_t scan_type Scan type esp_ble_scan_type_t scan_type Scan type esp_ble_addr_type_t own_addr_type Owner address type esp_ble_addr_type_t own_addr_type Owner address type esp_ble_scan_filter_t scan_filter_policy Scan filter policy esp_ble_scan_filter_t scan_filter_policy Scan filter policy uint16_t scan_interval Scan interval. This is defined as the time interval from when the Controller started its last LE scan until it begins the subsequent LE scan. Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms) Time = N * 0.625 msec Time Range: 2.5 msec to 10.24 seconds uint16_t scan_interval Scan interval. This is defined as the time interval from when the Controller started its last LE scan until it begins the subsequent LE scan. Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms) Time = N * 0.625 msec Time Range: 2.5 msec to 10.24 seconds uint16_t scan_window Scan window. The duration of the LE scan. LE_Scan_Window shall be less than or equal to LE_Scan_Interval Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms) Time = N * 0.625 msec Time Range: 2.5 msec to 10240 msec uint16_t scan_window Scan window. The duration of the LE scan. LE_Scan_Window shall be less than or equal to LE_Scan_Interval Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms) Time = N * 0.625 msec Time Range: 2.5 msec to 10240 msec esp_ble_scan_duplicate_t scan_duplicate The Scan_Duplicates parameter controls whether the Link Layer should filter out duplicate advertising reports (BLE_SCAN_DUPLICATE_ENABLE) to the Host, or if the Link Layer should generate advertising reports for each packet received esp_ble_scan_duplicate_t scan_duplicate The Scan_Duplicates parameter controls whether the Link Layer should filter out duplicate advertising reports (BLE_SCAN_DUPLICATE_ENABLE) to the Host, or if the Link Layer should generate advertising reports for each packet received esp_ble_scan_type_t scan_type struct esp_gap_conn_params_t connection parameters information Public Members uint16_t interval connection interval uint16_t interval connection interval uint16_t latency Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 uint16_t latency Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 uint16_t timeout Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec Time Range: 100 msec to 32 seconds uint16_t timeout Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec Time Range: 100 msec to 32 seconds uint16_t interval struct esp_ble_conn_update_params_t Connection update parameters. Public Members esp_bd_addr_t bda Bluetooth device address esp_bd_addr_t bda Bluetooth device address uint16_t min_int Min connection interval uint16_t min_int Min connection interval uint16_t max_int Max connection interval uint16_t max_int Max connection interval uint16_t latency Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 uint16_t latency Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 uint16_t timeout Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec Time Range: 100 msec to 32 seconds uint16_t timeout Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec Time Range: 100 msec to 32 seconds esp_bd_addr_t bda struct esp_ble_pkt_data_length_params_t BLE pkt date length keys. struct esp_ble_penc_keys_t BLE encryption keys. Public Members esp_bt_octet16_t ltk The long term key esp_bt_octet16_t ltk The long term key esp_bt_octet8_t rand The random number esp_bt_octet8_t rand The random number uint16_t ediv The ediv value uint16_t ediv The ediv value uint8_t sec_level The security level of the security link uint8_t sec_level The security level of the security link uint8_t key_size The key size(7~16) of the security link uint8_t key_size The key size(7~16) of the security link esp_bt_octet16_t ltk struct esp_ble_pcsrk_keys_t BLE CSRK keys. Public Members uint32_t counter The counter uint32_t counter The counter esp_bt_octet16_t csrk The csrk key esp_bt_octet16_t csrk The csrk key uint8_t sec_level The security level uint8_t sec_level The security level uint32_t counter struct esp_ble_pid_keys_t BLE pid keys. Public Members esp_bt_octet16_t irk The irk value esp_bt_octet16_t irk The irk value esp_ble_addr_type_t addr_type The address type esp_ble_addr_type_t addr_type The address type esp_bd_addr_t static_addr The static address esp_bd_addr_t static_addr The static address esp_bt_octet16_t irk struct esp_ble_lenc_keys_t BLE Encryption reproduction keys. Public Members esp_bt_octet16_t ltk The long term key esp_bt_octet16_t ltk The long term key uint16_t div The div value uint16_t div The div value uint8_t key_size The key size of the security link uint8_t key_size The key size of the security link uint8_t sec_level The security level of the security link uint8_t sec_level The security level of the security link esp_bt_octet16_t ltk struct esp_ble_lcsrk_keys BLE SRK keys. Public Members uint32_t counter The counter value uint32_t counter The counter value uint16_t div The div value uint16_t div The div value uint8_t sec_level The security level of the security link uint8_t sec_level The security level of the security link esp_bt_octet16_t csrk The csrk key value esp_bt_octet16_t csrk The csrk key value uint32_t counter struct esp_ble_sec_key_notif_t Structure associated with ESP_KEY_NOTIF_EVT. Public Members esp_bd_addr_t bd_addr peer address esp_bd_addr_t bd_addr peer address uint32_t passkey the numeric value for comparison. If just_works, do not show this number to UI uint32_t passkey the numeric value for comparison. If just_works, do not show this number to UI esp_bd_addr_t bd_addr struct esp_ble_sec_req_t Structure of the security request. Public Members esp_bd_addr_t bd_addr peer address esp_bd_addr_t bd_addr peer address esp_bd_addr_t bd_addr struct esp_ble_bond_key_info_t struct type of the bond key information value Public Members esp_ble_key_mask_t key_mask the key mask to indicate witch key is present esp_ble_key_mask_t key_mask the key mask to indicate witch key is present esp_ble_penc_keys_t penc_key received peer encryption key esp_ble_penc_keys_t penc_key received peer encryption key esp_ble_pcsrk_keys_t pcsrk_key received peer device SRK esp_ble_pcsrk_keys_t pcsrk_key received peer device SRK esp_ble_pid_keys_t pid_key peer device ID key esp_ble_pid_keys_t pid_key peer device ID key esp_ble_key_mask_t key_mask struct esp_ble_bond_dev_t struct type of the bond device value Public Members esp_bd_addr_t bd_addr peer address esp_bd_addr_t bd_addr peer address esp_ble_bond_key_info_t bond_key the bond key information esp_ble_bond_key_info_t bond_key the bond key information esp_bd_addr_t bd_addr struct esp_ble_key_t union type of the security key value Public Members esp_bd_addr_t bd_addr peer address esp_bd_addr_t bd_addr peer address esp_ble_key_type_t key_type key type of the security link esp_ble_key_type_t key_type key type of the security link esp_ble_key_value_t p_key_value the pointer to the key value esp_ble_key_value_t p_key_value the pointer to the key value esp_bd_addr_t bd_addr struct esp_ble_local_id_keys_t structure type of the ble local id keys value Public Members esp_bt_octet16_t ir the 16 bits of the ir value esp_bt_octet16_t ir the 16 bits of the ir value esp_bt_octet16_t irk the 16 bits of the ir key value esp_bt_octet16_t irk the 16 bits of the ir key value esp_bt_octet16_t dhk the 16 bits of the dh key value esp_bt_octet16_t dhk the 16 bits of the dh key value esp_bt_octet16_t ir struct esp_ble_local_oob_data_t structure type of the ble local oob data value Public Members esp_bt_octet16_t oob_c the 128 bits of confirmation value esp_bt_octet16_t oob_c the 128 bits of confirmation value esp_bt_octet16_t oob_r the 128 bits of randomizer value esp_bt_octet16_t oob_r the 128 bits of randomizer value esp_bt_octet16_t oob_c struct esp_ble_auth_cmpl_t Structure associated with ESP_AUTH_CMPL_EVT. Public Members esp_bd_addr_t bd_addr BD address peer device. esp_bd_addr_t bd_addr BD address peer device. bool key_present Valid link key value in key element bool key_present Valid link key value in key element esp_link_key key Link key associated with peer device. esp_link_key key Link key associated with peer device. uint8_t key_type The type of Link Key uint8_t key_type The type of Link Key bool success TRUE of authentication succeeded, FALSE if failed. bool success TRUE of authentication succeeded, FALSE if failed. uint8_t fail_reason The HCI reason/error code for when success=FALSE uint8_t fail_reason The HCI reason/error code for when success=FALSE esp_ble_addr_type_t addr_type Peer device address type esp_ble_addr_type_t addr_type Peer device address type esp_bt_dev_type_t dev_type Device type esp_bt_dev_type_t dev_type Device type esp_ble_auth_req_t auth_mode authentication mode esp_ble_auth_req_t auth_mode authentication mode esp_bd_addr_t bd_addr struct esp_ble_gap_ext_adv_params_t ext adv parameters Public Members esp_ble_ext_adv_type_mask_t type ext adv type esp_ble_ext_adv_type_mask_t type ext adv type uint32_t interval_min ext adv minimum interval uint32_t interval_min ext adv minimum interval uint32_t interval_max ext adv maximum interval uint32_t interval_max ext adv maximum interval esp_ble_adv_channel_t channel_map ext adv channel map esp_ble_adv_channel_t channel_map ext adv channel map esp_ble_addr_type_t own_addr_type ext adv own address type esp_ble_addr_type_t own_addr_type ext adv own address type esp_ble_addr_type_t peer_addr_type ext adv peer address type esp_ble_addr_type_t peer_addr_type ext adv peer address type esp_bd_addr_t peer_addr ext adv peer address esp_bd_addr_t peer_addr ext adv peer address esp_ble_adv_filter_t filter_policy ext adv filter policy esp_ble_adv_filter_t filter_policy ext adv filter policy int8_t tx_power ext adv tx power int8_t tx_power ext adv tx power esp_ble_gap_pri_phy_t primary_phy ext adv primary phy esp_ble_gap_pri_phy_t primary_phy ext adv primary phy uint8_t max_skip ext adv maximum skip uint8_t max_skip ext adv maximum skip esp_ble_gap_phy_t secondary_phy ext adv secondary phy esp_ble_gap_phy_t secondary_phy ext adv secondary phy uint8_t sid ext adv sid uint8_t sid ext adv sid bool scan_req_notif ext adv scan request event notify bool scan_req_notif ext adv scan request event notify esp_ble_ext_adv_type_mask_t type struct esp_ble_ext_scan_cfg_t ext scan config Public Members esp_ble_scan_type_t scan_type ext scan type esp_ble_scan_type_t scan_type ext scan type uint16_t scan_interval ext scan interval uint16_t scan_interval ext scan interval uint16_t scan_window ext scan window uint16_t scan_window ext scan window esp_ble_scan_type_t scan_type struct esp_ble_ext_scan_params_t ext scan parameters Public Members esp_ble_addr_type_t own_addr_type ext scan own address type esp_ble_addr_type_t own_addr_type ext scan own address type esp_ble_scan_filter_t filter_policy ext scan filter policy esp_ble_scan_filter_t filter_policy ext scan filter policy esp_ble_scan_duplicate_t scan_duplicate ext scan duplicate scan esp_ble_scan_duplicate_t scan_duplicate ext scan duplicate scan esp_ble_ext_scan_cfg_mask_t cfg_mask ext scan config mask esp_ble_ext_scan_cfg_mask_t cfg_mask ext scan config mask esp_ble_ext_scan_cfg_t uncoded_cfg ext scan uncoded config parameters esp_ble_ext_scan_cfg_t uncoded_cfg ext scan uncoded config parameters esp_ble_ext_scan_cfg_t coded_cfg ext scan coded config parameters esp_ble_ext_scan_cfg_t coded_cfg ext scan coded config parameters esp_ble_addr_type_t own_addr_type struct esp_ble_gap_conn_params_t create extend connection parameters Public Members uint16_t scan_interval init scan interval uint16_t scan_interval init scan interval uint16_t scan_window init scan window uint16_t scan_window init scan window uint16_t interval_min minimum interval uint16_t interval_min minimum interval uint16_t interval_max maximum interval uint16_t interval_max maximum interval uint16_t latency ext scan type uint16_t latency ext scan type uint16_t supervision_timeout connection supervision timeout uint16_t supervision_timeout connection supervision timeout uint16_t min_ce_len minimum ce length uint16_t min_ce_len minimum ce length uint16_t max_ce_len maximum ce length uint16_t max_ce_len maximum ce length uint16_t scan_interval struct esp_ble_gap_ext_adv_t extend adv enable parameters struct esp_ble_gap_periodic_adv_params_t periodic adv parameters struct esp_ble_gap_periodic_adv_sync_params_t periodic adv sync parameters Public Members esp_ble_gap_sync_t filter_policy Configures the filter policy for periodic advertising sync: 0: Use Advertising SID, Advertiser Address Type, and Advertiser Address parameters to determine the advertiser to listen to. 1: Use the Periodic Advertiser List to determine the advertiser to listen to. esp_ble_gap_sync_t filter_policy Configures the filter policy for periodic advertising sync: 0: Use Advertising SID, Advertiser Address Type, and Advertiser Address parameters to determine the advertiser to listen to. 1: Use the Periodic Advertiser List to determine the advertiser to listen to. uint8_t sid SID of the periodic advertising uint8_t sid SID of the periodic advertising esp_ble_addr_type_t addr_type Address type of the periodic advertising esp_ble_addr_type_t addr_type Address type of the periodic advertising esp_bd_addr_t addr Address of the periodic advertising esp_bd_addr_t addr Address of the periodic advertising uint16_t skip Maximum number of periodic advertising events that can be skipped uint16_t skip Maximum number of periodic advertising events that can be skipped uint16_t sync_timeout Synchronization timeout uint16_t sync_timeout Synchronization timeout esp_ble_gap_sync_t filter_policy struct esp_ble_gap_ext_adv_reprot_t extend adv report parameters Public Members esp_ble_gap_adv_type_t event_type extend advertising type esp_ble_gap_adv_type_t event_type extend advertising type uint8_t addr_type extend advertising address type uint8_t addr_type extend advertising address type esp_bd_addr_t addr extend advertising address esp_bd_addr_t addr extend advertising address esp_ble_gap_pri_phy_t primary_phy extend advertising primary phy esp_ble_gap_pri_phy_t primary_phy extend advertising primary phy esp_ble_gap_phy_t secondly_phy extend advertising secondary phy esp_ble_gap_phy_t secondly_phy extend advertising secondary phy uint8_t sid extend advertising sid uint8_t sid extend advertising sid uint8_t tx_power extend advertising tx power uint8_t tx_power extend advertising tx power int8_t rssi extend advertising rssi int8_t rssi extend advertising rssi uint16_t per_adv_interval periodic advertising interval uint16_t per_adv_interval periodic advertising interval uint8_t dir_addr_type direct address type uint8_t dir_addr_type direct address type esp_bd_addr_t dir_addr direct address esp_bd_addr_t dir_addr direct address esp_ble_gap_ext_adv_data_status_t data_status data type esp_ble_gap_ext_adv_data_status_t data_status data type uint8_t adv_data_len extend advertising data length uint8_t adv_data_len extend advertising data length uint8_t adv_data[251] extend advertising data uint8_t adv_data[251] extend advertising data esp_ble_gap_adv_type_t event_type struct esp_ble_gap_periodic_adv_report_t periodic adv report parameters Public Members uint16_t sync_handle periodic advertising train handle uint16_t sync_handle periodic advertising train handle uint8_t tx_power periodic advertising tx power uint8_t tx_power periodic advertising tx power int8_t rssi periodic advertising rssi int8_t rssi periodic advertising rssi esp_ble_gap_ext_adv_data_status_t data_status periodic advertising data type esp_ble_gap_ext_adv_data_status_t data_status periodic advertising data type uint8_t data_length periodic advertising data length uint8_t data_length periodic advertising data length uint8_t data[251] periodic advertising data uint8_t data[251] periodic advertising data uint16_t sync_handle struct esp_ble_gap_periodic_adv_sync_estab_t perodic adv sync establish parameters Public Members uint8_t status periodic advertising sync status uint8_t status periodic advertising sync status uint16_t sync_handle periodic advertising train handle uint16_t sync_handle periodic advertising train handle uint8_t sid periodic advertising sid uint8_t sid periodic advertising sid esp_ble_addr_type_t addr_type periodic advertising address type esp_ble_addr_type_t addr_type periodic advertising address type esp_bd_addr_t adv_addr periodic advertising address esp_bd_addr_t adv_addr periodic advertising address esp_ble_gap_phy_t adv_phy periodic advertising adv phy type esp_ble_gap_phy_t adv_phy periodic advertising adv phy type uint16_t period_adv_interval periodic advertising interval uint16_t period_adv_interval periodic advertising interval uint8_t adv_clk_accuracy periodic advertising clock accuracy uint8_t adv_clk_accuracy periodic advertising clock accuracy uint8_t status struct esp_ble_dtm_enh_tx_t DTM TX parameters. Public Members uint8_t tx_channel channel for sending test data, tx_channel = (Frequency -2402)/2, tx_channel range:0x00-0x27, Frequency range: 2402 MHz to 2480 MHz uint8_t tx_channel channel for sending test data, tx_channel = (Frequency -2402)/2, tx_channel range:0x00-0x27, Frequency range: 2402 MHz to 2480 MHz uint8_t len_of_data length in bytes of payload data in each packet uint8_t len_of_data length in bytes of payload data in each packet esp_ble_dtm_pkt_payload_t pkt_payload packet payload type. value range: 0x00-0x07 esp_ble_dtm_pkt_payload_t pkt_payload packet payload type. value range: 0x00-0x07 esp_ble_gap_phy_t phy the phy type used by the transmitter, coded phy with S=2:0x04 esp_ble_gap_phy_t phy the phy type used by the transmitter, coded phy with S=2:0x04 uint8_t tx_channel struct esp_ble_dtm_enh_rx_t DTM RX parameters. Public Members uint8_t rx_channel channel for test data reception, rx_channel = (Frequency -2402)/2, tx_channel range:0x00-0x27, Frequency range: 2402 MHz to 2480 MHz uint8_t rx_channel channel for test data reception, rx_channel = (Frequency -2402)/2, tx_channel range:0x00-0x27, Frequency range: 2402 MHz to 2480 MHz esp_ble_gap_phy_t phy the phy type used by the receiver, 1M phy: 0x01, 2M phy:0x02, coded phy:0x03 esp_ble_gap_phy_t phy the phy type used by the receiver, 1M phy: 0x01, 2M phy:0x02, coded phy:0x03 uint8_t modulation_idx modulation index, 0x00:standard modulation index, 0x01:stable modulation index uint8_t modulation_idx modulation index, 0x00:standard modulation index, 0x01:stable modulation index uint8_t rx_channel struct esp_ble_gap_past_params_t periodic adv sync transfer parameters Public Members esp_ble_gap_past_mode_t mode periodic advertising sync transfer mode esp_ble_gap_past_mode_t mode periodic advertising sync transfer mode uint16_t skip the number of periodic advertising packets that can be skipped uint16_t skip the number of periodic advertising packets that can be skipped uint16_t sync_timeout synchronization timeout for the periodic advertising train uint16_t sync_timeout synchronization timeout for the periodic advertising train uint8_t cte_type periodic advertising sync transfer CET type uint8_t cte_type periodic advertising sync transfer CET type esp_ble_gap_past_mode_t mode Macros ESP_BLE_ADV_FLAG_LIMIT_DISC BLE_ADV_DATA_FLAG data flag bit definition used for advertising data flag. ESP_BLE_ADV_FLAG_GEN_DISC ESP_BLE_ADV_FLAG_BREDR_NOT_SPT ESP_BLE_ADV_FLAG_DMT_CONTROLLER_SPT ESP_BLE_ADV_FLAG_DMT_HOST_SPT ESP_BLE_ADV_FLAG_NON_LIMIT_DISC ESP_LE_KEY_NONE relate to BTM_LE_KEY_xxx in stack/btm_api.h No encryption key ESP_LE_KEY_PENC encryption key, encryption information of peer device ESP_LE_KEY_PID identity key of the peer device ESP_LE_KEY_PCSRK peer SRK ESP_LE_KEY_PLK Link key ESP_LE_KEY_LLK peer link key ESP_LE_KEY_LENC master role security information:div ESP_LE_KEY_LID master device ID key ESP_LE_KEY_LCSRK local CSRK has been deliver to peer ESP_LE_AUTH_NO_BOND relate to BTM_LE_AUTH_xxx in stack/btm_api.h 0 no bondingv ESP_LE_AUTH_BOND 1 << 0 device in the bonding with peer ESP_LE_AUTH_REQ_MITM 1 << 2 man in the middle attack ESP_LE_AUTH_REQ_BOND_MITM 0101 banding with man in the middle attack ESP_LE_AUTH_REQ_SC_ONLY 1 << 3 secure connection ESP_LE_AUTH_REQ_SC_BOND 1001 secure connection with band ESP_LE_AUTH_REQ_SC_MITM 1100 secure conn with MITM ESP_LE_AUTH_REQ_SC_MITM_BOND 1101 SC with MITM and Bonding ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_DISABLE authentication disable ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_ENABLE authentication enable ESP_BLE_OOB_DISABLE disbale the out of bond ESP_BLE_OOB_ENABLE enable the out of bond ESP_IO_CAP_OUT relate to BTM_IO_CAP_xxx in stack/btm_api.h DisplayOnly ESP_IO_CAP_IO DisplayYesNo ESP_IO_CAP_IN KeyboardOnly ESP_IO_CAP_NONE NoInputNoOutput ESP_IO_CAP_KBDISP Keyboard display ESP_BLE_APPEARANCE_UNKNOWN relate to BTM_BLE_APPEARANCE_UNKNOWN in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_PHONE relate to BTM_BLE_APPEARANCE_GENERIC_PHONE in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_COMPUTER relate to BTM_BLE_APPEARANCE_GENERIC_COMPUTER in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_WATCH relate to BTM_BLE_APPEARANCE_GENERIC_WATCH in stack/btm_ble_api.h ESP_BLE_APPEARANCE_SPORTS_WATCH relate to BTM_BLE_APPEARANCE_SPORTS_WATCH in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_CLOCK relate to BTM_BLE_APPEARANCE_GENERIC_CLOCK in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_DISPLAY relate to BTM_BLE_APPEARANCE_GENERIC_DISPLAY in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_REMOTE relate to BTM_BLE_APPEARANCE_GENERIC_REMOTE in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_EYEGLASSES relate to BTM_BLE_APPEARANCE_GENERIC_EYEGLASSES in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_TAG relate to BTM_BLE_APPEARANCE_GENERIC_TAG in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_KEYRING relate to BTM_BLE_APPEARANCE_GENERIC_KEYRING in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_MEDIA_PLAYER relate to BTM_BLE_APPEARANCE_GENERIC_MEDIA_PLAYER in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_BARCODE_SCANNER relate to BTM_BLE_APPEARANCE_GENERIC_BARCODE_SCANNER in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_THERMOMETER relate to BTM_BLE_APPEARANCE_GENERIC_THERMOMETER in stack/btm_ble_api.h ESP_BLE_APPEARANCE_THERMOMETER_EAR relate to BTM_BLE_APPEARANCE_THERMOMETER_EAR in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_HEART_RATE relate to BTM_BLE_APPEARANCE_GENERIC_HEART_RATE in stack/btm_ble_api.h ESP_BLE_APPEARANCE_HEART_RATE_BELT relate to BTM_BLE_APPEARANCE_HEART_RATE_BELT in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_BLOOD_PRESSURE relate to BTM_BLE_APPEARANCE_GENERIC_BLOOD_PRESSURE in stack/btm_ble_api.h ESP_BLE_APPEARANCE_BLOOD_PRESSURE_ARM relate to BTM_BLE_APPEARANCE_BLOOD_PRESSURE_ARM in stack/btm_ble_api.h ESP_BLE_APPEARANCE_BLOOD_PRESSURE_WRIST relate to BTM_BLE_APPEARANCE_BLOOD_PRESSURE_WRIST in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_HID relate to BTM_BLE_APPEARANCE_GENERIC_HID in stack/btm_ble_api.h ESP_BLE_APPEARANCE_HID_KEYBOARD relate to BTM_BLE_APPEARANCE_HID_KEYBOARD in stack/btm_ble_api.h ESP_BLE_APPEARANCE_HID_MOUSE relate to BTM_BLE_APPEARANCE_HID_MOUSE in stack/btm_ble_api.h ESP_BLE_APPEARANCE_HID_JOYSTICK relate to BTM_BLE_APPEARANCE_HID_JOYSTICK in stack/btm_ble_api.h ESP_BLE_APPEARANCE_HID_GAMEPAD relate to BTM_BLE_APPEARANCE_HID_GAMEPAD in stack/btm_ble_api.h ESP_BLE_APPEARANCE_HID_DIGITIZER_TABLET relate to BTM_BLE_APPEARANCE_HID_DIGITIZER_TABLET in stack/btm_ble_api.h ESP_BLE_APPEARANCE_HID_CARD_READER relate to BTM_BLE_APPEARANCE_HID_CARD_READER in stack/btm_ble_api.h ESP_BLE_APPEARANCE_HID_DIGITAL_PEN relate to BTM_BLE_APPEARANCE_HID_DIGITAL_PEN in stack/btm_ble_api.h ESP_BLE_APPEARANCE_HID_BARCODE_SCANNER relate to BTM_BLE_APPEARANCE_HID_BARCODE_SCANNER in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_GLUCOSE relate to BTM_BLE_APPEARANCE_GENERIC_GLUCOSE in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_WALKING relate to BTM_BLE_APPEARANCE_GENERIC_WALKING in stack/btm_ble_api.h ESP_BLE_APPEARANCE_WALKING_IN_SHOE relate to BTM_BLE_APPEARANCE_WALKING_IN_SHOE in stack/btm_ble_api.h ESP_BLE_APPEARANCE_WALKING_ON_SHOE relate to BTM_BLE_APPEARANCE_WALKING_ON_SHOE in stack/btm_ble_api.h ESP_BLE_APPEARANCE_WALKING_ON_HIP relate to BTM_BLE_APPEARANCE_WALKING_ON_HIP in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_CYCLING relate to BTM_BLE_APPEARANCE_GENERIC_CYCLING in stack/btm_ble_api.h ESP_BLE_APPEARANCE_CYCLING_COMPUTER relate to BTM_BLE_APPEARANCE_CYCLING_COMPUTER in stack/btm_ble_api.h ESP_BLE_APPEARANCE_CYCLING_SPEED relate to BTM_BLE_APPEARANCE_CYCLING_SPEED in stack/btm_ble_api.h ESP_BLE_APPEARANCE_CYCLING_CADENCE relate to BTM_BLE_APPEARANCE_CYCLING_CADENCE in stack/btm_ble_api.h ESP_BLE_APPEARANCE_CYCLING_POWER relate to BTM_BLE_APPEARANCE_CYCLING_POWER in stack/btm_ble_api.h ESP_BLE_APPEARANCE_CYCLING_SPEED_CADENCE relate to BTM_BLE_APPEARANCE_CYCLING_SPEED_CADENCE in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_PULSE_OXIMETER relate to BTM_BLE_APPEARANCE_GENERIC_PULSE_OXIMETER in stack/btm_ble_api.h ESP_BLE_APPEARANCE_PULSE_OXIMETER_FINGERTIP relate to BTM_BLE_APPEARANCE_PULSE_OXIMETER_FINGERTIP in stack/btm_ble_api.h ESP_BLE_APPEARANCE_PULSE_OXIMETER_WRIST relate to BTM_BLE_APPEARANCE_PULSE_OXIMETER_WRIST in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_WEIGHT relate to BTM_BLE_APPEARANCE_GENERIC_WEIGHT in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_PERSONAL_MOBILITY_DEVICE relate to BTM_BLE_APPEARANCE_GENERIC_PERSONAL_MOBILITY_DEVICE in stack/btm_ble_api.h ESP_BLE_APPEARANCE_POWERED_WHEELCHAIR relate to BTM_BLE_APPEARANCE_POWERED_WHEELCHAIR in stack/btm_ble_api.h ESP_BLE_APPEARANCE_MOBILITY_SCOOTER relate to BTM_BLE_APPEARANCE_MOBILITY_SCOOTER in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_CONTINUOUS_GLUCOSE_MONITOR relate to BTM_BLE_APPEARANCE_GENERIC_CONTINUOUS_GLUCOSE_MONITOR in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_INSULIN_PUMP relate to BTM_BLE_APPEARANCE_GENERIC_INSULIN_PUMP in stack/btm_ble_api.h ESP_BLE_APPEARANCE_INSULIN_PUMP_DURABLE_PUMP relate to BTM_BLE_APPEARANCE_INSULIN_PUMP_DURABLE_PUMP in stack/btm_ble_api.h ESP_BLE_APPEARANCE_INSULIN_PUMP_PATCH_PUMP relate to BTM_BLE_APPEARANCE_INSULIN_PUMP_PATCH_PUMP in stack/btm_ble_api.h ESP_BLE_APPEARANCE_INSULIN_PEN relate to BTM_BLE_APPEARANCE_INSULIN_PEN in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_MEDICATION_DELIVERY relate to BTM_BLE_APPEARANCE_GENERIC_MEDICATION_DELIVERY in stack/btm_ble_api.h ESP_BLE_APPEARANCE_GENERIC_OUTDOOR_SPORTS relate to BTM_BLE_APPEARANCE_GENERIC_OUTDOOR_SPORTS in stack/btm_ble_api.h ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION in stack/btm_ble_api.h ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_AND_NAV relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_AND_NAV in stack/btm_ble_api.h ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD in stack/btm_ble_api.h ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD_AND_NAV relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD_AND_NAV in stack/btm_ble_api.h BLE_DTM_PKT_PAYLOAD_0x00 PRBS9 sequence ‘11111111100000111101...’ (in transmission order) as described in [Vol 6] Part F, Section 4.1.5 BLE_DTM_PKT_PAYLOAD_0x01 Repeated ‘11110000’ (in transmission order) sequence as described in [Vol 6] Part F, Section 4.1.5 BLE_DTM_PKT_PAYLOAD_0x02 Repeated ‘10101010’ (in transmission order) sequence as described in [Vol 6] Part F, Section 4.1.5 BLE_DTM_PKT_PAYLOAD_0x03 PRBS15 sequence as described in [Vol 6] Part F, Section 4.1.5 BLE_DTM_PKT_PAYLOAD_0x04 Repeated ‘11111111’ (in transmission order) sequence BLE_DTM_PKT_PAYLOAD_0x05 Repeated ‘00000000’ (in transmission order) sequence BLE_DTM_PKT_PAYLOAD_0x06 Repeated ‘00001111’ (in transmission order) sequence BLE_DTM_PKT_PAYLOAD_0x07 Repeated ‘01010101’ (in transmission order) sequence BLE_DTM_PKT_PAYLOAD_MAX 0x08 ~ 0xFF, Reserved for future use ESP_GAP_BLE_CHANNELS_LEN channel length ESP_GAP_BLE_ADD_WHITELIST_COMPLETE_EVT This is the old name, just for backwards compatibility. ESP_BLE_ADV_DATA_LEN_MAX Advertising data maximum length. ESP_BLE_SCAN_RSP_DATA_LEN_MAX Scan response data maximum length. BLE_BIT(n) ESP_BLE_GAP_SET_EXT_ADV_PROP_NONCONN_NONSCANNABLE_UNDIRECTED Non-Connectable and Non-Scannable Undirected advertising ESP_BLE_GAP_SET_EXT_ADV_PROP_CONNECTABLE Connectable advertising ESP_BLE_GAP_SET_EXT_ADV_PROP_SCANNABLE Scannable advertising ESP_BLE_GAP_SET_EXT_ADV_PROP_DIRECTED Directed advertising ESP_BLE_GAP_SET_EXT_ADV_PROP_HD_DIRECTED High Duty Cycle Directed Connectable advertising (<= 3.75 ms Advertising Interval) ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY Use legacy advertising PDUs ESP_BLE_GAP_SET_EXT_ADV_PROP_ANON_ADV Omit advertiser's address from all PDUs ("anonymous advertising") ESP_BLE_GAP_SET_EXT_ADV_PROP_INCLUDE_TX_PWR Include TxPower in the extended header of the advertising PDU ESP_BLE_GAP_SET_EXT_ADV_PROP_MASK Reserved for future use If extended advertising PDU types are being used (bit 4 = 0) then: The advertisement shall not be both connectable and scannable. High duty cycle directed connectable advertising (<= 3.75 ms advertising interval) shall not be used (bit 3 = 0) ADV_IND ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_IND ADV_DIRECT_IND (low duty cycle) ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_LD_DIR ADV_DIRECT_IND (high duty cycle) ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_HD_DIR ADV_SCAN_IND ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_SCAN ADV_NONCONN_IND ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_NONCONN ESP_BLE_GAP_PHY_1M Secondery Advertisement PHY is LE1M ESP_BLE_GAP_PHY_2M Secondery Advertisement PHY is LE2M ESP_BLE_GAP_PHY_CODED Secondery Advertisement PHY is LE Coded ESP_BLE_GAP_NO_PREFER_TRANSMIT_PHY No Prefer TX PHY supported by controller ESP_BLE_GAP_NO_PREFER_RECEIVE_PHY No Prefer RX PHY supported by controller ESP_BLE_GAP_PRI_PHY_1M Primary phy only support 1M and LE coded phy. Primary Phy is LE1M ESP_BLE_GAP_PRI_PHY_CODED Primary Phy is LE CODED ESP_BLE_GAP_PHY_1M_PREF_MASK The Host prefers use the LE1M transmitter or reciever PHY ESP_BLE_GAP_PHY_2M_PREF_MASK The Host prefers use the LE2M transmitter or reciever PHY ESP_BLE_GAP_PHY_CODED_PREF_MASK The Host prefers use the LE CODED transmitter or reciever PHY ESP_BLE_GAP_PHY_OPTIONS_NO_PREF The Host has no preferred coding when transmitting on the LE Coded PHY ESP_BLE_GAP_PHY_OPTIONS_PREF_S2_CODING The Host prefers that S=2 coding be used when transmitting on the LE Coded PHY ESP_BLE_GAP_PHY_OPTIONS_PREF_S8_CODING The Host prefers that S=8 coding be used when transmitting on the LE Coded PHY ESP_BLE_GAP_EXT_SCAN_CFG_UNCODE_MASK Scan Advertisements on the LE1M PHY ESP_BLE_GAP_EXT_SCAN_CFG_CODE_MASK Scan advertisements on the LE coded PHY ESP_BLE_GAP_EXT_ADV_DATA_COMPLETE Advertising data. extended advertising data compete ESP_BLE_GAP_EXT_ADV_DATA_INCOMPLETE extended advertising data incomplete ESP_BLE_GAP_EXT_ADV_DATA_TRUNCATED extended advertising data truncated mode ESP_BLE_GAP_SYNC_POLICY_BY_ADV_INFO Advertising SYNC policy. sync policy by advertising info ESP_BLE_GAP_SYNC_POLICY_BY_PERIODIC_LIST periodic advertising sync policy ESP_BLE_ADV_REPORT_EXT_ADV_IND Advertising report. advertising report with extended advertising indication type ESP_BLE_ADV_REPORT_EXT_SCAN_IND advertising report with extended scan indication type ESP_BLE_ADV_REPORT_EXT_DIRECT_ADV advertising report with extended direct advertising indication type ESP_BLE_ADV_REPORT_EXT_SCAN_RSP advertising report with extended scan response indication type Bluetooth 5.0, Vol 2, Part E, 7.7.65.13 ESP_BLE_LEGACY_ADV_TYPE_IND advertising report with legacy advertising indication type ESP_BLE_LEGACY_ADV_TYPE_DIRECT_IND advertising report with legacy direct indication type ESP_BLE_LEGACY_ADV_TYPE_SCAN_IND advertising report with legacy scan indication type ESP_BLE_LEGACY_ADV_TYPE_NONCON_IND advertising report with legacy non connectable indication type ESP_BLE_LEGACY_ADV_TYPE_SCAN_RSP_TO_ADV_IND advertising report with legacy scan response indication type ESP_BLE_LEGACY_ADV_TYPE_SCAN_RSP_TO_ADV_SCAN_IND advertising report with legacy advertising with scan response indication type EXT_ADV_TX_PWR_NO_PREFERENCE Extend advertising tx power, range: [-127, +126] dBm. host has no preference for tx power ESP_BLE_GAP_PAST_MODE_NO_SYNC_EVT Periodic advertising sync trans mode. No attempt is made to sync and no periodic adv sync transfer received event ESP_BLE_GAP_PAST_MODE_NO_REPORT_EVT An periodic adv sync transfer received event and no periodic adv report events ESP_BLE_GAP_PAST_MODE_DUP_FILTER_DISABLED Periodic adv report events will be enabled with duplicate filtering disabled ESP_BLE_GAP_PAST_MODE_DUP_FILTER_ENABLED Periodic adv report events will be enabled with duplicate filtering enabled Type Definitions typedef uint8_t esp_ble_key_type_t typedef uint8_t esp_ble_auth_req_t combination of the above bit pattern typedef uint8_t esp_ble_io_cap_t combination of the io capability typedef uint8_t esp_ble_dtm_pkt_payload_t typedef uint8_t esp_gap_ble_channels[ESP_GAP_BLE_CHANNELS_LEN] typedef uint8_t esp_duplicate_info_t[ESP_BD_ADDR_LEN] typedef uint16_t esp_ble_ext_adv_type_mask_t typedef uint8_t esp_ble_gap_phy_t typedef uint8_t esp_ble_gap_all_phys_t typedef uint8_t esp_ble_gap_pri_phy_t typedef uint8_t esp_ble_gap_phy_mask_t typedef uint16_t esp_ble_gap_prefer_phy_options_t typedef uint8_t esp_ble_ext_scan_cfg_mask_t typedef uint8_t esp_ble_gap_ext_adv_data_status_t typedef uint8_t esp_ble_gap_sync_t typedef uint8_t esp_ble_gap_adv_type_t typedef uint8_t esp_ble_gap_past_mode_t typedef void (*esp_gap_ble_cb_t)(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) GAP callback function type. Param event : Event type Param param : Point to callback parameter, currently is union type Param event : Event type Param param : Point to callback parameter, currently is union type Enumerations enum esp_gap_ble_cb_event_t GAP BLE callback event type. Values: enumerator ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT When advertising data set complete, the event comes enumerator ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT When advertising data set complete, the event comes enumerator ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT When scan response data set complete, the event comes enumerator ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT When scan response data set complete, the event comes enumerator ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT When scan parameters set complete, the event comes enumerator ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT When scan parameters set complete, the event comes enumerator ESP_GAP_BLE_SCAN_RESULT_EVT When one scan result ready, the event comes each time enumerator ESP_GAP_BLE_SCAN_RESULT_EVT When one scan result ready, the event comes each time enumerator ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT When raw advertising data set complete, the event comes enumerator ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT When raw advertising data set complete, the event comes enumerator ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT When raw scan response data set complete, the event comes enumerator ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT When raw scan response data set complete, the event comes enumerator ESP_GAP_BLE_ADV_START_COMPLETE_EVT When start advertising complete, the event comes enumerator ESP_GAP_BLE_ADV_START_COMPLETE_EVT When start advertising complete, the event comes enumerator ESP_GAP_BLE_SCAN_START_COMPLETE_EVT When start scan complete, the event comes enumerator ESP_GAP_BLE_SCAN_START_COMPLETE_EVT When start scan complete, the event comes enumerator ESP_GAP_BLE_AUTH_CMPL_EVT Authentication complete indication. enumerator ESP_GAP_BLE_AUTH_CMPL_EVT Authentication complete indication. enumerator ESP_GAP_BLE_KEY_EVT BLE key event for peer device keys enumerator ESP_GAP_BLE_KEY_EVT BLE key event for peer device keys enumerator ESP_GAP_BLE_SEC_REQ_EVT BLE security request enumerator ESP_GAP_BLE_SEC_REQ_EVT BLE security request enumerator ESP_GAP_BLE_PASSKEY_NOTIF_EVT passkey notification event enumerator ESP_GAP_BLE_PASSKEY_NOTIF_EVT passkey notification event enumerator ESP_GAP_BLE_PASSKEY_REQ_EVT passkey request event enumerator ESP_GAP_BLE_PASSKEY_REQ_EVT passkey request event enumerator ESP_GAP_BLE_OOB_REQ_EVT OOB request event enumerator ESP_GAP_BLE_OOB_REQ_EVT OOB request event enumerator ESP_GAP_BLE_LOCAL_IR_EVT BLE local IR (identity Root 128-bit random static value used to generate Long Term Key) event enumerator ESP_GAP_BLE_LOCAL_IR_EVT BLE local IR (identity Root 128-bit random static value used to generate Long Term Key) event enumerator ESP_GAP_BLE_LOCAL_ER_EVT BLE local ER (Encryption Root vakue used to genrate identity resolving key) event enumerator ESP_GAP_BLE_LOCAL_ER_EVT BLE local ER (Encryption Root vakue used to genrate identity resolving key) event enumerator ESP_GAP_BLE_NC_REQ_EVT Numeric Comparison request event enumerator ESP_GAP_BLE_NC_REQ_EVT Numeric Comparison request event enumerator ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT When stop adv complete, the event comes enumerator ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT When stop adv complete, the event comes enumerator ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT When stop scan complete, the event comes enumerator ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT When stop scan complete, the event comes enumerator ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT When set the static rand address complete, the event comes enumerator ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT When set the static rand address complete, the event comes enumerator ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT When update connection parameters complete, the event comes enumerator ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT When update connection parameters complete, the event comes enumerator ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT When set pkt length complete, the event comes enumerator ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT When set pkt length complete, the event comes enumerator ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT When Enable/disable privacy on the local device complete, the event comes enumerator ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT When Enable/disable privacy on the local device complete, the event comes enumerator ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT When remove the bond device complete, the event comes enumerator ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT When remove the bond device complete, the event comes enumerator ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT When clear the bond device clear complete, the event comes enumerator ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT When clear the bond device clear complete, the event comes enumerator ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT When get the bond device list complete, the event comes enumerator ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT When get the bond device list complete, the event comes enumerator ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT When read the rssi complete, the event comes enumerator ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT When read the rssi complete, the event comes enumerator ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT When add or remove whitelist complete, the event comes enumerator ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT When add or remove whitelist complete, the event comes enumerator ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT When update duplicate exceptional list complete, the event comes enumerator ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT When update duplicate exceptional list complete, the event comes enumerator ESP_GAP_BLE_SET_CHANNELS_EVT When setting BLE channels complete, the event comes enumerator ESP_GAP_BLE_SET_CHANNELS_EVT When setting BLE channels complete, the event comes enumerator ESP_GAP_BLE_READ_PHY_COMPLETE_EVT when reading phy complete, this event comes enumerator ESP_GAP_BLE_READ_PHY_COMPLETE_EVT when reading phy complete, this event comes enumerator ESP_GAP_BLE_SET_PREFERRED_DEFAULT_PHY_COMPLETE_EVT when preferred default phy complete, this event comes enumerator ESP_GAP_BLE_SET_PREFERRED_DEFAULT_PHY_COMPLETE_EVT when preferred default phy complete, this event comes enumerator ESP_GAP_BLE_SET_PREFERRED_PHY_COMPLETE_EVT when preferred phy complete , this event comes enumerator ESP_GAP_BLE_SET_PREFERRED_PHY_COMPLETE_EVT when preferred phy complete , this event comes enumerator ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT when extended set random address complete, the event comes enumerator ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT when extended set random address complete, the event comes enumerator ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT when extended advertising parameter complete, the event comes enumerator ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT when extended advertising parameter complete, the event comes enumerator ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT when extended advertising data complete, the event comes enumerator ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT when extended advertising data complete, the event comes enumerator ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT when extended scan response data complete, the event comes enumerator ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT when extended scan response data complete, the event comes enumerator ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT when extended advertising start complete, the event comes enumerator ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT when extended advertising start complete, the event comes enumerator ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT when extended advertising stop complete, the event comes enumerator ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT when extended advertising stop complete, the event comes enumerator ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT when extended advertising set remove complete, the event comes enumerator ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT when extended advertising set remove complete, the event comes enumerator ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT when extended advertising set clear complete, the event comes enumerator ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT when extended advertising set clear complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT when periodic advertising parameter complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT when periodic advertising parameter complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT when periodic advertising data complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT when periodic advertising data complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT when periodic advertising start complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT when periodic advertising start complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT when periodic advertising stop complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT when periodic advertising stop complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT when periodic advertising create sync complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT when periodic advertising create sync complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT when extended advertising sync cancel complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT when extended advertising sync cancel complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT when extended advertising sync terminate complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT when extended advertising sync terminate complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT when extended advertising add device complete , the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT when extended advertising add device complete , the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT when extended advertising remove device complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT when extended advertising remove device complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT when extended advertising clear device, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT when extended advertising clear device, the event comes enumerator ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT when extended scan parameter complete, the event comes enumerator ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT when extended scan parameter complete, the event comes enumerator ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT when extended scan start complete, the event comes enumerator ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT when extended scan start complete, the event comes enumerator ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT when extended scan stop complete, the event comes enumerator ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT when extended scan stop complete, the event comes enumerator ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT when extended prefer connection parameter set complete, the event comes enumerator ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT when extended prefer connection parameter set complete, the event comes enumerator ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT when ble phy update complete, the event comes enumerator ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT when ble phy update complete, the event comes enumerator ESP_GAP_BLE_EXT_ADV_REPORT_EVT when extended advertising report complete, the event comes enumerator ESP_GAP_BLE_EXT_ADV_REPORT_EVT when extended advertising report complete, the event comes enumerator ESP_GAP_BLE_SCAN_TIMEOUT_EVT when scan timeout complete, the event comes enumerator ESP_GAP_BLE_SCAN_TIMEOUT_EVT when scan timeout complete, the event comes enumerator ESP_GAP_BLE_ADV_TERMINATED_EVT when advertising terminate data complete, the event comes enumerator ESP_GAP_BLE_ADV_TERMINATED_EVT when advertising terminate data complete, the event comes enumerator ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT when scan req received complete, the event comes enumerator ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT when scan req received complete, the event comes enumerator ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT when channel select algorithm complete, the event comes enumerator ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT when channel select algorithm complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT when periodic report advertising complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT when periodic report advertising complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT when periodic advertising sync lost complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT when periodic advertising sync lost complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT when periodic advertising sync establish complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT when periodic advertising sync establish complete, the event comes enumerator ESP_GAP_BLE_SC_OOB_REQ_EVT Secure Connection OOB request event enumerator ESP_GAP_BLE_SC_OOB_REQ_EVT Secure Connection OOB request event enumerator ESP_GAP_BLE_SC_CR_LOC_OOB_EVT Secure Connection create OOB data complete event enumerator ESP_GAP_BLE_SC_CR_LOC_OOB_EVT Secure Connection create OOB data complete event enumerator ESP_GAP_BLE_GET_DEV_NAME_COMPLETE_EVT When getting BT device name complete, the event comes enumerator ESP_GAP_BLE_GET_DEV_NAME_COMPLETE_EVT When getting BT device name complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_RECV_ENABLE_COMPLETE_EVT when set periodic advertising receive enable complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_RECV_ENABLE_COMPLETE_EVT when set periodic advertising receive enable complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_COMPLETE_EVT when periodic advertising sync transfer complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_COMPLETE_EVT when periodic advertising sync transfer complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SET_INFO_TRANS_COMPLETE_EVT when periodic advertising set info transfer complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SET_INFO_TRANS_COMPLETE_EVT when periodic advertising set info transfer complete, the event comes enumerator ESP_GAP_BLE_SET_PAST_PARAMS_COMPLETE_EVT when set periodic advertising sync transfer params complete, the event comes enumerator ESP_GAP_BLE_SET_PAST_PARAMS_COMPLETE_EVT when set periodic advertising sync transfer params complete, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_RECV_EVT when periodic advertising sync transfer received, the event comes enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_RECV_EVT when periodic advertising sync transfer received, the event comes enumerator ESP_GAP_BLE_DTM_TEST_UPDATE_EVT when direct test mode state changes, the event comes enumerator ESP_GAP_BLE_DTM_TEST_UPDATE_EVT when direct test mode state changes, the event comes enumerator ESP_GAP_BLE_ADV_CLEAR_COMPLETE_EVT When clear advertising complete, the event comes enumerator ESP_GAP_BLE_ADV_CLEAR_COMPLETE_EVT When clear advertising complete, the event comes enumerator ESP_GAP_BLE_EVT_MAX when maximum advertising event complete, the event comes enumerator ESP_GAP_BLE_EVT_MAX when maximum advertising event complete, the event comes enumerator ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT enum esp_ble_adv_data_type The type of advertising data(not adv_type) Values: enumerator ESP_BLE_AD_TYPE_FLAG enumerator ESP_BLE_AD_TYPE_FLAG enumerator ESP_BLE_AD_TYPE_16SRV_PART enumerator ESP_BLE_AD_TYPE_16SRV_PART enumerator ESP_BLE_AD_TYPE_16SRV_CMPL enumerator ESP_BLE_AD_TYPE_16SRV_CMPL enumerator ESP_BLE_AD_TYPE_32SRV_PART enumerator ESP_BLE_AD_TYPE_32SRV_PART enumerator ESP_BLE_AD_TYPE_32SRV_CMPL enumerator ESP_BLE_AD_TYPE_32SRV_CMPL enumerator ESP_BLE_AD_TYPE_128SRV_PART enumerator ESP_BLE_AD_TYPE_128SRV_PART enumerator ESP_BLE_AD_TYPE_128SRV_CMPL enumerator ESP_BLE_AD_TYPE_128SRV_CMPL enumerator ESP_BLE_AD_TYPE_NAME_SHORT enumerator ESP_BLE_AD_TYPE_NAME_SHORT enumerator ESP_BLE_AD_TYPE_NAME_CMPL enumerator ESP_BLE_AD_TYPE_NAME_CMPL enumerator ESP_BLE_AD_TYPE_TX_PWR enumerator ESP_BLE_AD_TYPE_TX_PWR enumerator ESP_BLE_AD_TYPE_DEV_CLASS enumerator ESP_BLE_AD_TYPE_DEV_CLASS enumerator ESP_BLE_AD_TYPE_SM_TK enumerator ESP_BLE_AD_TYPE_SM_TK enumerator ESP_BLE_AD_TYPE_SM_OOB_FLAG enumerator ESP_BLE_AD_TYPE_SM_OOB_FLAG enumerator ESP_BLE_AD_TYPE_INT_RANGE enumerator ESP_BLE_AD_TYPE_INT_RANGE enumerator ESP_BLE_AD_TYPE_SOL_SRV_UUID enumerator ESP_BLE_AD_TYPE_SOL_SRV_UUID enumerator ESP_BLE_AD_TYPE_128SOL_SRV_UUID enumerator ESP_BLE_AD_TYPE_128SOL_SRV_UUID enumerator ESP_BLE_AD_TYPE_SERVICE_DATA enumerator ESP_BLE_AD_TYPE_SERVICE_DATA enumerator ESP_BLE_AD_TYPE_PUBLIC_TARGET enumerator ESP_BLE_AD_TYPE_PUBLIC_TARGET enumerator ESP_BLE_AD_TYPE_RANDOM_TARGET enumerator ESP_BLE_AD_TYPE_RANDOM_TARGET enumerator ESP_BLE_AD_TYPE_APPEARANCE enumerator ESP_BLE_AD_TYPE_APPEARANCE enumerator ESP_BLE_AD_TYPE_ADV_INT enumerator ESP_BLE_AD_TYPE_ADV_INT enumerator ESP_BLE_AD_TYPE_LE_DEV_ADDR enumerator ESP_BLE_AD_TYPE_LE_DEV_ADDR enumerator ESP_BLE_AD_TYPE_LE_ROLE enumerator ESP_BLE_AD_TYPE_LE_ROLE enumerator ESP_BLE_AD_TYPE_SPAIR_C256 enumerator ESP_BLE_AD_TYPE_SPAIR_C256 enumerator ESP_BLE_AD_TYPE_SPAIR_R256 enumerator ESP_BLE_AD_TYPE_SPAIR_R256 enumerator ESP_BLE_AD_TYPE_32SOL_SRV_UUID enumerator ESP_BLE_AD_TYPE_32SOL_SRV_UUID enumerator ESP_BLE_AD_TYPE_32SERVICE_DATA enumerator ESP_BLE_AD_TYPE_32SERVICE_DATA enumerator ESP_BLE_AD_TYPE_128SERVICE_DATA enumerator ESP_BLE_AD_TYPE_128SERVICE_DATA enumerator ESP_BLE_AD_TYPE_LE_SECURE_CONFIRM enumerator ESP_BLE_AD_TYPE_LE_SECURE_CONFIRM enumerator ESP_BLE_AD_TYPE_LE_SECURE_RANDOM enumerator ESP_BLE_AD_TYPE_LE_SECURE_RANDOM enumerator ESP_BLE_AD_TYPE_URI enumerator ESP_BLE_AD_TYPE_URI enumerator ESP_BLE_AD_TYPE_INDOOR_POSITION enumerator ESP_BLE_AD_TYPE_INDOOR_POSITION enumerator ESP_BLE_AD_TYPE_TRANS_DISC_DATA enumerator ESP_BLE_AD_TYPE_TRANS_DISC_DATA enumerator ESP_BLE_AD_TYPE_LE_SUPPORT_FEATURE enumerator ESP_BLE_AD_TYPE_LE_SUPPORT_FEATURE enumerator ESP_BLE_AD_TYPE_CHAN_MAP_UPDATE enumerator ESP_BLE_AD_TYPE_CHAN_MAP_UPDATE enumerator ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE enumerator ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE enumerator ESP_BLE_AD_TYPE_FLAG enum esp_ble_adv_type_t Advertising mode. Values: enumerator ADV_TYPE_IND enumerator ADV_TYPE_IND enumerator ADV_TYPE_DIRECT_IND_HIGH enumerator ADV_TYPE_DIRECT_IND_HIGH enumerator ADV_TYPE_SCAN_IND enumerator ADV_TYPE_SCAN_IND enumerator ADV_TYPE_NONCONN_IND enumerator ADV_TYPE_NONCONN_IND enumerator ADV_TYPE_DIRECT_IND_LOW enumerator ADV_TYPE_DIRECT_IND_LOW enumerator ADV_TYPE_IND enum esp_ble_adv_channel_t Advertising channel mask. Values: enumerator ADV_CHNL_37 enumerator ADV_CHNL_37 enumerator ADV_CHNL_38 enumerator ADV_CHNL_38 enumerator ADV_CHNL_39 enumerator ADV_CHNL_39 enumerator ADV_CHNL_ALL enumerator ADV_CHNL_ALL enumerator ADV_CHNL_37 enum esp_ble_adv_filter_t Values: enumerator ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY Allow both scan and connection requests from anyone. enumerator ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY Allow both scan and connection requests from anyone. enumerator ADV_FILTER_ALLOW_SCAN_WLST_CON_ANY Allow both scan req from White List devices only and connection req from anyone. enumerator ADV_FILTER_ALLOW_SCAN_WLST_CON_ANY Allow both scan req from White List devices only and connection req from anyone. enumerator ADV_FILTER_ALLOW_SCAN_ANY_CON_WLST Allow both scan req from anyone and connection req from White List devices only. enumerator ADV_FILTER_ALLOW_SCAN_ANY_CON_WLST Allow both scan req from anyone and connection req from White List devices only. enumerator ADV_FILTER_ALLOW_SCAN_WLST_CON_WLST Allow scan and connection requests from White List devices only. enumerator ADV_FILTER_ALLOW_SCAN_WLST_CON_WLST Allow scan and connection requests from White List devices only. enumerator ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY enum esp_ble_sec_act_t Values: enumerator ESP_BLE_SEC_ENCRYPT relate to BTA_DM_BLE_SEC_ENCRYPT in bta/bta_api.h. If the device has already bonded, the stack will used Long Term Key (LTK) to encrypt with the remote device directly. Else if the device hasn't bonded, the stack will used the default authentication request used the esp_ble_gap_set_security_param function set by the user. enumerator ESP_BLE_SEC_ENCRYPT relate to BTA_DM_BLE_SEC_ENCRYPT in bta/bta_api.h. If the device has already bonded, the stack will used Long Term Key (LTK) to encrypt with the remote device directly. Else if the device hasn't bonded, the stack will used the default authentication request used the esp_ble_gap_set_security_param function set by the user. enumerator ESP_BLE_SEC_ENCRYPT_NO_MITM relate to BTA_DM_BLE_SEC_ENCRYPT_NO_MITM in bta/bta_api.h. If the device has been already bonded, the stack will check the LTK (Long Term Key) Whether the authentication request has been met, and if met, use the LTK to encrypt with the remote device directly, else re-pair with the remote device. Else if the device hasn't been bonded, the stack will use NO MITM authentication request in the current link instead of using the authreq in the esp_ble_gap_set_security_param function set by the user. enumerator ESP_BLE_SEC_ENCRYPT_NO_MITM relate to BTA_DM_BLE_SEC_ENCRYPT_NO_MITM in bta/bta_api.h. If the device has been already bonded, the stack will check the LTK (Long Term Key) Whether the authentication request has been met, and if met, use the LTK to encrypt with the remote device directly, else re-pair with the remote device. Else if the device hasn't been bonded, the stack will use NO MITM authentication request in the current link instead of using the authreq in the esp_ble_gap_set_security_param function set by the user. enumerator ESP_BLE_SEC_ENCRYPT_MITM relate to BTA_DM_BLE_SEC_ENCRYPT_MITM in bta/bta_api.h. If the device has been already bonded, the stack will check the LTK (Long Term Key) whether the authentication request has been met, and if met, use the LTK to encrypt with the remote device directly, else re-pair with the remote device. Else if the device hasn't been bonded, the stack will use MITM authentication request in the current link instead of using the authreq in the esp_ble_gap_set_security_param function set by the user. enumerator ESP_BLE_SEC_ENCRYPT_MITM relate to BTA_DM_BLE_SEC_ENCRYPT_MITM in bta/bta_api.h. If the device has been already bonded, the stack will check the LTK (Long Term Key) whether the authentication request has been met, and if met, use the LTK to encrypt with the remote device directly, else re-pair with the remote device. Else if the device hasn't been bonded, the stack will use MITM authentication request in the current link instead of using the authreq in the esp_ble_gap_set_security_param function set by the user. enumerator ESP_BLE_SEC_ENCRYPT enum esp_ble_sm_param_t Values: enumerator ESP_BLE_SM_PASSKEY Authentication requirements of local device enumerator ESP_BLE_SM_PASSKEY Authentication requirements of local device enumerator ESP_BLE_SM_AUTHEN_REQ_MODE The IO capability of local device enumerator ESP_BLE_SM_AUTHEN_REQ_MODE The IO capability of local device enumerator ESP_BLE_SM_IOCAP_MODE Initiator Key Distribution/Generation enumerator ESP_BLE_SM_IOCAP_MODE Initiator Key Distribution/Generation enumerator ESP_BLE_SM_SET_INIT_KEY Responder Key Distribution/Generation enumerator ESP_BLE_SM_SET_INIT_KEY Responder Key Distribution/Generation enumerator ESP_BLE_SM_SET_RSP_KEY Maximum Encryption key size to support enumerator ESP_BLE_SM_SET_RSP_KEY Maximum Encryption key size to support enumerator ESP_BLE_SM_MAX_KEY_SIZE Minimum Encryption key size requirement from Peer enumerator ESP_BLE_SM_MAX_KEY_SIZE Minimum Encryption key size requirement from Peer enumerator ESP_BLE_SM_MIN_KEY_SIZE Set static Passkey enumerator ESP_BLE_SM_MIN_KEY_SIZE Set static Passkey enumerator ESP_BLE_SM_SET_STATIC_PASSKEY Reset static Passkey enumerator ESP_BLE_SM_SET_STATIC_PASSKEY Reset static Passkey enumerator ESP_BLE_SM_CLEAR_STATIC_PASSKEY Accept only specified SMP Authentication requirement enumerator ESP_BLE_SM_CLEAR_STATIC_PASSKEY Accept only specified SMP Authentication requirement enumerator ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH Enable/Disable OOB support enumerator ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH Enable/Disable OOB support enumerator ESP_BLE_SM_OOB_SUPPORT Appl encryption key size enumerator ESP_BLE_SM_OOB_SUPPORT Appl encryption key size enumerator ESP_BLE_APP_ENC_KEY_SIZE authentication max param enumerator ESP_BLE_APP_ENC_KEY_SIZE authentication max param enumerator ESP_BLE_SM_MAX_PARAM enumerator ESP_BLE_SM_MAX_PARAM enumerator ESP_BLE_SM_PASSKEY enum esp_ble_dtm_update_evt_t Values: enumerator DTM_TX_START_EVT DTM TX start event. enumerator DTM_TX_START_EVT DTM TX start event. enumerator DTM_RX_START_EVT DTM RX start event. enumerator DTM_RX_START_EVT DTM RX start event. enumerator DTM_TEST_STOP_EVT DTM test end event. enumerator DTM_TEST_STOP_EVT DTM test end event. enumerator DTM_TX_START_EVT enum esp_ble_scan_type_t Ble scan type. Values: enumerator BLE_SCAN_TYPE_PASSIVE Passive scan enumerator BLE_SCAN_TYPE_PASSIVE Passive scan enumerator BLE_SCAN_TYPE_ACTIVE Active scan enumerator BLE_SCAN_TYPE_ACTIVE Active scan enumerator BLE_SCAN_TYPE_PASSIVE enum esp_ble_scan_filter_t Ble scan filter type. Values: enumerator BLE_SCAN_FILTER_ALLOW_ALL Accept all : advertisement packets except directed advertising packets not addressed to this device (default). advertisement packets except directed advertising packets not addressed to this device (default). advertisement packets except directed advertising packets not addressed to this device (default). enumerator BLE_SCAN_FILTER_ALLOW_ALL Accept all : advertisement packets except directed advertising packets not addressed to this device (default). enumerator BLE_SCAN_FILTER_ALLOW_ONLY_WLST Accept only : advertisement packets from devices where the advertiser’s address is in the White list. Directed advertising packets which are not addressed for this device shall be ignored. advertisement packets from devices where the advertiser’s address is in the White list. Directed advertising packets which are not addressed for this device shall be ignored. advertisement packets from devices where the advertiser’s address is in the White list. enumerator BLE_SCAN_FILTER_ALLOW_ONLY_WLST Accept only : advertisement packets from devices where the advertiser’s address is in the White list. Directed advertising packets which are not addressed for this device shall be ignored. enumerator BLE_SCAN_FILTER_ALLOW_UND_RPA_DIR Accept all : undirected advertisement packets, and directed advertising packets where the initiator address is a resolvable private address, and directed advertising packets addressed to this device. undirected advertisement packets, and directed advertising packets where the initiator address is a resolvable private address, and directed advertising packets addressed to this device. undirected advertisement packets, and enumerator BLE_SCAN_FILTER_ALLOW_UND_RPA_DIR Accept all : undirected advertisement packets, and directed advertising packets where the initiator address is a resolvable private address, and directed advertising packets addressed to this device. enumerator BLE_SCAN_FILTER_ALLOW_WLIST_RPA_DIR Accept all : advertisement packets from devices where the advertiser’s address is in the White list, and directed advertising packets where the initiator address is a resolvable private address, and directed advertising packets addressed to this device. advertisement packets from devices where the advertiser’s address is in the White list, and directed advertising packets where the initiator address is a resolvable private address, and directed advertising packets addressed to this device. advertisement packets from devices where the advertiser’s address is in the White list, and enumerator BLE_SCAN_FILTER_ALLOW_WLIST_RPA_DIR Accept all : advertisement packets from devices where the advertiser’s address is in the White list, and directed advertising packets where the initiator address is a resolvable private address, and directed advertising packets addressed to this device. enumerator BLE_SCAN_FILTER_ALLOW_ALL enum esp_ble_scan_duplicate_t Ble scan duplicate type. Values: enumerator BLE_SCAN_DUPLICATE_DISABLE the Link Layer should generate advertising reports to the host for each packet received enumerator BLE_SCAN_DUPLICATE_DISABLE the Link Layer should generate advertising reports to the host for each packet received enumerator BLE_SCAN_DUPLICATE_ENABLE the Link Layer should filter out duplicate advertising reports to the Host enumerator BLE_SCAN_DUPLICATE_ENABLE the Link Layer should filter out duplicate advertising reports to the Host enumerator BLE_SCAN_DUPLICATE_ENABLE_RESET Duplicate filtering enabled, reset for each scan period, only supported in BLE 5.0. enumerator BLE_SCAN_DUPLICATE_ENABLE_RESET Duplicate filtering enabled, reset for each scan period, only supported in BLE 5.0. enumerator BLE_SCAN_DUPLICATE_MAX Reserved for future use. enumerator BLE_SCAN_DUPLICATE_MAX Reserved for future use. enumerator BLE_SCAN_DUPLICATE_DISABLE enum esp_gap_search_evt_t Sub Event of ESP_GAP_BLE_SCAN_RESULT_EVT. Values: enumerator ESP_GAP_SEARCH_INQ_RES_EVT Inquiry result for a peer device. enumerator ESP_GAP_SEARCH_INQ_RES_EVT Inquiry result for a peer device. enumerator ESP_GAP_SEARCH_INQ_CMPL_EVT Inquiry complete. enumerator ESP_GAP_SEARCH_INQ_CMPL_EVT Inquiry complete. enumerator ESP_GAP_SEARCH_DISC_RES_EVT Discovery result for a peer device. enumerator ESP_GAP_SEARCH_DISC_RES_EVT Discovery result for a peer device. enumerator ESP_GAP_SEARCH_DISC_BLE_RES_EVT Discovery result for BLE GATT based service on a peer device. enumerator ESP_GAP_SEARCH_DISC_BLE_RES_EVT Discovery result for BLE GATT based service on a peer device. enumerator ESP_GAP_SEARCH_DISC_CMPL_EVT Discovery complete. enumerator ESP_GAP_SEARCH_DISC_CMPL_EVT Discovery complete. enumerator ESP_GAP_SEARCH_DI_DISC_CMPL_EVT Discovery complete. enumerator ESP_GAP_SEARCH_DI_DISC_CMPL_EVT Discovery complete. enumerator ESP_GAP_SEARCH_SEARCH_CANCEL_CMPL_EVT Search cancelled enumerator ESP_GAP_SEARCH_SEARCH_CANCEL_CMPL_EVT Search cancelled enumerator ESP_GAP_SEARCH_INQ_DISCARD_NUM_EVT The number of pkt discarded by flow control enumerator ESP_GAP_SEARCH_INQ_DISCARD_NUM_EVT The number of pkt discarded by flow control enumerator ESP_GAP_SEARCH_INQ_RES_EVT enum esp_ble_evt_type_t Ble scan result event type, to indicate the result is scan response or advertising data or other. Values: enumerator ESP_BLE_EVT_CONN_ADV Connectable undirected advertising (ADV_IND) enumerator ESP_BLE_EVT_CONN_ADV Connectable undirected advertising (ADV_IND) enumerator ESP_BLE_EVT_CONN_DIR_ADV Connectable directed advertising (ADV_DIRECT_IND) enumerator ESP_BLE_EVT_CONN_DIR_ADV Connectable directed advertising (ADV_DIRECT_IND) enumerator ESP_BLE_EVT_DISC_ADV Scannable undirected advertising (ADV_SCAN_IND) enumerator ESP_BLE_EVT_DISC_ADV Scannable undirected advertising (ADV_SCAN_IND) enumerator ESP_BLE_EVT_NON_CONN_ADV Non connectable undirected advertising (ADV_NONCONN_IND) enumerator ESP_BLE_EVT_NON_CONN_ADV Non connectable undirected advertising (ADV_NONCONN_IND) enumerator ESP_BLE_EVT_SCAN_RSP Scan Response (SCAN_RSP) enumerator ESP_BLE_EVT_SCAN_RSP Scan Response (SCAN_RSP) enumerator ESP_BLE_EVT_CONN_ADV enum esp_ble_wl_operation_t Values: enumerator ESP_BLE_WHITELIST_REMOVE remove mac from whitelist enumerator ESP_BLE_WHITELIST_REMOVE remove mac from whitelist enumerator ESP_BLE_WHITELIST_ADD add address to whitelist enumerator ESP_BLE_WHITELIST_ADD add address to whitelist enumerator ESP_BLE_WHITELIST_CLEAR clear all device in whitelist enumerator ESP_BLE_WHITELIST_CLEAR clear all device in whitelist enumerator ESP_BLE_WHITELIST_REMOVE enum esp_bt_duplicate_exceptional_subcode_type_t Values: enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_ADD Add device info into duplicate scan exceptional list enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_ADD Add device info into duplicate scan exceptional list enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_REMOVE Remove device info from duplicate scan exceptional list enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_REMOVE Remove device info from duplicate scan exceptional list enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_CLEAN Clean duplicate scan exceptional list enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_CLEAN Clean duplicate scan exceptional list enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_ADD enum esp_ble_duplicate_exceptional_info_type_t Values: enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_ADV_ADDR BLE advertising address , device info will be added into ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ADDR_LIST enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_ADV_ADDR BLE advertising address , device info will be added into ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ADDR_LIST enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_LINK_ID BLE mesh link ID, it is for BLE mesh, device info will be added into ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_LINK_ID_LIST enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_LINK_ID BLE mesh link ID, it is for BLE mesh, device info will be added into ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_LINK_ID_LIST enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_BEACON_TYPE BLE mesh beacon AD type, the format is | Len | 0x2B | Beacon Type | Beacon Data | enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_BEACON_TYPE BLE mesh beacon AD type, the format is | Len | 0x2B | Beacon Type | Beacon Data | enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROV_SRV_ADV BLE mesh provisioning service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x1827 | .... |` enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROV_SRV_ADV BLE mesh provisioning service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x1827 | .... |` enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROXY_SRV_ADV BLE mesh adv with proxy service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x1828 | .... |` enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROXY_SRV_ADV BLE mesh adv with proxy service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x1828 | .... |` enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROXY_SOLIC_ADV BLE mesh adv with proxy service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x1859 | .... |` enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROXY_SOLIC_ADV BLE mesh adv with proxy service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x1859 | .... |` enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_URI_ADV BLE mesh URI adv, the format is ...| Len | 0x24 | data |... enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_URI_ADV BLE mesh URI adv, the format is ...| Len | 0x24 | data |... enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_ADV_ADDR enum esp_duplicate_scan_exceptional_list_type_t Values: enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ADDR_LIST duplicate scan exceptional addr list enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ADDR_LIST duplicate scan exceptional addr list enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_LINK_ID_LIST duplicate scan exceptional mesh link ID list enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_LINK_ID_LIST duplicate scan exceptional mesh link ID list enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_BEACON_TYPE_LIST duplicate scan exceptional mesh beacon type list enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_BEACON_TYPE_LIST duplicate scan exceptional mesh beacon type list enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROV_SRV_ADV_LIST duplicate scan exceptional mesh adv with provisioning service uuid enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROV_SRV_ADV_LIST duplicate scan exceptional mesh adv with provisioning service uuid enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROXY_SRV_ADV_LIST duplicate scan exceptional mesh adv with proxy service uuid enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROXY_SRV_ADV_LIST duplicate scan exceptional mesh adv with proxy service uuid enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROXY_SOLIC_ADV_LIST duplicate scan exceptional mesh adv with proxy solicitation PDU uuid enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROXY_SOLIC_ADV_LIST duplicate scan exceptional mesh adv with proxy solicitation PDU uuid enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_URI_ADV_LIST duplicate scan exceptional URI list enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_URI_ADV_LIST duplicate scan exceptional URI list enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ALL_LIST duplicate scan exceptional all list enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ALL_LIST duplicate scan exceptional all list enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ADDR_LIST
GAP API Application Example Check the bluetooth/bluedroid/ble folder in ESP-IDF examples, which contains the following demos and their tutorials: The following shows an SMP security client demo with its tutorial. This demo initiates its security parameters and acts as a GATT client, which can send a security request to the peer device and then complete the encryption procedure. The following shows an SMP security server demo with its tutorial. This demo initiates its security parameters and acts as a GATT server, which can send a pair request to the peer device and then complete the encryption procedure. API Reference Header File components/bt/host/bluedroid/api/include/api/esp_gap_ble_api.h This header file can be included with: #include "esp_gap_ble_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_gap_register_callback(esp_gap_ble_cb_t callback) This function is called to occur gap event, such as scan result. - Parameters callback -- [in] callback function - Returns ESP_OK : success other : failed - - esp_gap_ble_cb_t esp_ble_gap_get_callback(void) This function is called to get the current gap callback. - Returns esp_gap_ble_cb_t : callback function - - esp_err_t esp_ble_gap_config_adv_data(esp_ble_adv_data_t *adv_data) This function is called to override the BTA default ADV parameters. - Parameters adv_data -- [in] Pointer to User defined ADV data structure. This memory space can not be freed until callback of config_adv_data is received. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_set_scan_params(esp_ble_scan_params_t *scan_params) This function is called to set scan parameters. - Parameters scan_params -- [in] Pointer to User defined scan_params data structure. This memory space can not be freed until callback of set_scan_params - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_start_scanning(uint32_t duration) This procedure keep the device scanning the peer device which advertising on the air. - Parameters duration -- [in] Keeping the scanning time, the unit is second. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_stop_scanning(void) This function call to stop the device scanning the peer device which advertising on the air. - Returns ESP_OK : success other : failed - - - esp_err_t esp_ble_gap_start_advertising(esp_ble_adv_params_t *adv_params) This function is called to start advertising. - Parameters adv_params -- [in] pointer to User defined adv_params data structure. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_stop_advertising(void) This function is called to stop advertising. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_update_conn_params(esp_ble_conn_update_params_t *params) Update connection parameters, can only be used when connection is up. - Parameters params -- [in] - connection update parameters - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_set_pkt_data_len(esp_bd_addr_t remote_device, uint16_t tx_data_length) This function is to set maximum LE data packet size. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_set_rand_addr(esp_bd_addr_t rand_addr) This function allows configuring either a Non-Resolvable Private Address or a Static Random Address. - Parameters rand_addr -- [in] The address to be configured. Refer to the table below for possible address subtypes: | address [47:46] | Address Type | |-----------------|--------------------------| | 0b00 | Non-Resolvable Private | | | Address | |-----------------|--------------------------| | 0b11 | Static Random Address | |-----------------|--------------------------| - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_clear_rand_addr(void) This function clears the random address for the application. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_config_local_privacy(bool privacy_enable) Enable/disable privacy (including address resolution) on the local device. - Parameters privacy_enable -- [in] - enable/disable privacy on remote device. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_config_local_icon(uint16_t icon) set local gap appearance icon - Parameters icon -- [in] - External appearance value, these values are defined by the Bluetooth SIG, please refer to https://www.bluetooth.com/specifications/assigned-numbers/ - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_update_whitelist(bool add_remove, esp_bd_addr_t remote_bda, esp_ble_wl_addr_type_t wl_addr_type) Add or remove device from white list. - Parameters add_remove -- [in] the value is true if added the ble device to the white list, and false remove to the white list. remote_bda -- [in] the remote device address add/remove from the white list. wl_addr_type -- [in] whitelist address type - - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_clear_whitelist(void) Clear all white list. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_get_whitelist_size(uint16_t *length) Get the whitelist size in the controller. - Parameters length -- [out] the white list length. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_set_prefer_conn_params(esp_bd_addr_t bd_addr, uint16_t min_conn_int, uint16_t max_conn_int, uint16_t slave_latency, uint16_t supervision_tout) This function is called to set the preferred connection parameters when default connection parameter is not desired before connecting. This API can only be used in the master role. - Parameters bd_addr -- [in] BD address of the peripheral min_conn_int -- [in] minimum preferred connection interval max_conn_int -- [in] maximum preferred connection interval slave_latency -- [in] preferred slave latency supervision_tout -- [in] preferred supervision timeout - - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_set_device_name(const char *name) Set device name to the local device Note: This API don't affect the advertising data. - Parameters name -- [in] - device name. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_get_device_name(void) Get device name of the local device. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_get_local_used_addr(esp_bd_addr_t local_used_addr, uint8_t *addr_type) This function is called to get local used address and address type. uint8_t *esp_bt_dev_get_address(void) get the public address. - Parameters local_used_addr -- [in] - current local used ble address (six bytes) addr_type -- [in] - ble address type - - Returns - ESP_OK : success other : failed - - uint8_t *esp_ble_resolve_adv_data(uint8_t *adv_data, uint8_t type, uint8_t *length) This function is called to get ADV data for a specific type. - Parameters adv_data -- [in] - pointer of ADV data which to be resolved type -- [in] - finding ADV data type length -- [out] - return the length of ADV data not including type - - Returns pointer of ADV data - esp_err_t esp_ble_gap_config_adv_data_raw(uint8_t *raw_data, uint32_t raw_data_len) This function is called to set raw advertising data. User need to fill ADV data by self. - Parameters raw_data -- [in] : raw advertising data with the format: [Length 1][Data Type 1][Data 1][Length 2][Data Type 2][Data 2] ... raw_data_len -- [in] : raw advertising data length , less than 31 bytes - - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_config_scan_rsp_data_raw(uint8_t *raw_data, uint32_t raw_data_len) This function is called to set raw scan response data. User need to fill scan response data by self. - Parameters raw_data -- [in] : raw scan response data raw_data_len -- [in] : raw scan response data length , less than 31 bytes - - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_read_rssi(esp_bd_addr_t remote_addr) This function is called to read the RSSI of remote device. The address of link policy results are returned in the gap callback function with ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT event. - Parameters remote_addr -- [in] : The remote connection device address. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_add_duplicate_scan_exceptional_device(esp_ble_duplicate_exceptional_info_type_t type, esp_duplicate_info_t device_info) This function is called to add a device info into the duplicate scan exceptional list. - Parameters type -- [in] device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or MESH_PROXY_SRV_ADV , device_info is invalid. device_info -- [in] the device information. - - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_remove_duplicate_scan_exceptional_device(esp_ble_duplicate_exceptional_info_type_t type, esp_duplicate_info_t device_info) This function is called to remove a device info from the duplicate scan exceptional list. - Parameters type -- [in] device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or MESH_PROXY_SRV_ADV , device_info is invalid. device_info -- [in] the device information. - - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_clean_duplicate_scan_exceptional_list(esp_duplicate_scan_exceptional_list_type_t list_type) This function is called to clean the duplicate scan exceptional list. This API will delete all device information in the duplicate scan exceptional list. - Parameters list_type -- [in] duplicate scan exceptional list type, the value can be one or more of esp_duplicate_scan_exceptional_list_type_t. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gap_set_security_param(esp_ble_sm_param_t param_type, void *value, uint8_t len) Set a GAP security parameter value. Overrides the default value. Secure connection is highly recommended to avoid some major vulnerabilities like 'Impersonation in the Pin Pairing Protocol' (CVE-2020-26555) and 'Authentication of the LE Legacy Pairing Protocol'. To accept only `secure connection mode`, it is necessary do as following: 1. Set bit `ESP_LE_AUTH_REQ_SC_ONLY` (`param_type` is `ESP_BLE_SM_AUTHEN_REQ_MODE`), bit `ESP_LE_AUTH_BOND` and bit `ESP_LE_AUTH_REQ_MITM` is optional as required. 2. Set to `ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_ENABLE` (`param_type` is `ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH`). - Parameters param_type -- [in] : the type of the param which to be set value -- [in] : the param value len -- [in] : the length of the param value - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_security_rsp(esp_bd_addr_t bd_addr, bool accept) Grant security request access. - Parameters bd_addr -- [in] : BD address of the peer accept -- [in] : accept the security request or not - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_set_encryption(esp_bd_addr_t bd_addr, esp_ble_sec_act_t sec_act) Set a gap parameter value. Use this function to change the default GAP parameter values. - Parameters bd_addr -- [in] : the address of the peer device need to encryption sec_act -- [in] : This is the security action to indicate what kind of BLE security level is required for the BLE link if the BLE is supported - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_passkey_reply(esp_bd_addr_t bd_addr, bool accept, uint32_t passkey) Reply the key value to the peer device in the legacy connection stage. - Parameters bd_addr -- [in] : BD address of the peer accept -- [in] : passkey entry successful or declined. passkey -- [in] : passkey value, must be a 6 digit number, can be lead by 0. - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_confirm_reply(esp_bd_addr_t bd_addr, bool accept) Reply the confirm value to the peer device in the secure connection stage. - Parameters bd_addr -- [in] : BD address of the peer device accept -- [in] : numbers to compare are the same or different. - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_remove_bond_device(esp_bd_addr_t bd_addr) Removes a device from the security database list of peer device. It manages unpairing event while connected. - Parameters bd_addr -- [in] : BD address of the peer device - Returns - ESP_OK : success other : failed - - int esp_ble_get_bond_device_num(void) Get the device number from the security database list of peer device. It will return the device bonded number immediately. - Returns - >= 0 : bonded devices number. ESP_FAIL : failed - - esp_err_t esp_ble_get_bond_device_list(int *dev_num, esp_ble_bond_dev_t *dev_list) Get the device from the security database list of peer device. It will return the device bonded information immediately. - Parameters dev_num -- [inout] Indicate the dev_list array(buffer) size as input. If dev_num is large enough, it means the actual number as output. Suggest that dev_num value equal to esp_ble_get_bond_device_num(). dev_list -- [out] an array(buffer) of esp_ble_bond_dev_ttype. Use for storing the bonded devices address. The dev_list should be allocated by who call this API. - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_oob_req_reply(esp_bd_addr_t bd_addr, uint8_t *TK, uint8_t len) This function is called to provide the OOB data for SMP in response to ESP_GAP_BLE_OOB_REQ_EVT. - Parameters bd_addr -- [in] BD address of the peer device. TK -- [in] Temporary Key value, the TK value shall be a 128-bit random number len -- [in] length of temporary key, should always be 128-bit - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_sc_oob_req_reply(esp_bd_addr_t bd_addr, uint8_t p_c[16], uint8_t p_r[16]) This function is called to provide the OOB data for SMP in response to ESP_GAP_BLE_SC_OOB_REQ_EVT. - Parameters bd_addr -- [in] BD address of the peer device. p_c -- [in] Confirmation value, it shall be a 128-bit random number p_r -- [in] Randomizer value, it should be a 128-bit random number - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_create_sc_oob_data(void) This function is called to create the OOB data for SMP when secure connection. - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_disconnect(esp_bd_addr_t remote_device) This function is to disconnect the physical connection of the peer device gattc may have multiple virtual GATT server connections when multiple app_id registered. esp_ble_gattc_close (esp_gatt_if_t gattc_if, uint16_t conn_id) only close one virtual GATT server connection. if there exist other virtual GATT server connections, it does not disconnect the physical connection. esp_ble_gap_disconnect(esp_bd_addr_t remote_device) disconnect the physical connection directly. - Parameters remote_device -- [in] : BD address of the peer device - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_get_current_conn_params(esp_bd_addr_t bd_addr, esp_gap_conn_params_t *conn_params) This function is called to read the connection parameters information of the device. - Parameters bd_addr -- [in] BD address of the peer device. conn_params -- [out] the connection parameters information - - Returns - ESP_OK : success other : failed - - esp_err_t esp_gap_ble_set_channels(esp_gap_ble_channels channels) BLE set channels. - Parameters channels -- [in] : The n th such field (in the range 0 to 36) contains the value for the link layer channel index n. 0 means channel n is bad. 1 means channel n is unknown. The most significant bits are reserved and shall be set to 0. At least one channel shall be marked as unknown. - Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed - This function is called to authorized a link after Authentication(MITM protection) - Parameters bd_addr -- [in] BD address of the peer device. authorize -- [out] Authorized the link or not. - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_read_phy(esp_bd_addr_t bd_addr) This function is used to read the current transmitter PHY and receiver PHY on the connection identified by remote address. - Parameters bd_addr -- [in] : BD address of the peer device - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_set_preferred_default_phy(esp_ble_gap_phy_mask_t tx_phy_mask, esp_ble_gap_phy_mask_t rx_phy_mask) This function is used to allows the Host to specify its preferred values for the transmitter PHY and receiver PHY to be used for all subsequent connections over the LE transport. - Parameters tx_phy_mask -- [in] : indicates the transmitter PHYs that the Host prefers the Controller to use rx_phy_mask -- [in] : indicates the receiver PHYs that the Host prefers the Controller to use - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_set_preferred_phy(esp_bd_addr_t bd_addr, esp_ble_gap_all_phys_t all_phys_mask, esp_ble_gap_phy_mask_t tx_phy_mask, esp_ble_gap_phy_mask_t rx_phy_mask, esp_ble_gap_prefer_phy_options_t phy_options) This function is used to set the PHY preferences for the connection identified by the remote address. The Controller might not be able to make the change (e.g. because the peer does not support the requested PHY) or may decide that the current PHY is preferable. - Parameters bd_addr -- [in] : remote address all_phys_mask -- [in] : a bit field that allows the Host to specify tx_phy_mask -- [in] : a bit field that indicates the transmitter PHYs that the Host prefers the Controller to use rx_phy_mask -- [in] : a bit field that indicates the receiver PHYs that the Host prefers the Controller to use phy_options -- [in] : a bit field that allows the Host to specify options for PHYs - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_ext_adv_set_rand_addr(uint8_t instance, esp_bd_addr_t rand_addr) This function is used by the Host to set the random device address specified by the Random_Address parameter. - Parameters instance -- [in] : Used to identify an advertising set rand_addr -- [in] : Random Device Address - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_ext_adv_set_params(uint8_t instance, const esp_ble_gap_ext_adv_params_t *params) This function is used by the Host to set the advertising parameters. - Parameters instance -- [in] : identifies the advertising set whose parameters are being configured. params -- [in] : advertising parameters - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_config_ext_adv_data_raw(uint8_t instance, uint16_t length, const uint8_t *data) This function is used to set the data used in advertising PDUs that have a data field. - Parameters instance -- [in] : identifies the advertising set whose data are being configured length -- [in] : data length data -- [in] : data information - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_config_ext_scan_rsp_data_raw(uint8_t instance, uint16_t length, const uint8_t *scan_rsp_data) This function is used to provide scan response data used in scanning response PDUs. - Parameters instance -- [in] : identifies the advertising set whose response data are being configured. length -- [in] : responsedata length scan_rsp_data -- [in] : response data information - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_ext_adv_start(uint8_t num_adv, const esp_ble_gap_ext_adv_t *ext_adv) This function is used to request the Controller to enable one or more advertising sets using the advertising sets identified by the instance parameter. - Parameters num_adv -- [in] : Number of advertising sets to enable or disable ext_adv -- [in] : adv parameters - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_ext_adv_stop(uint8_t num_adv, const uint8_t *ext_adv_inst) This function is used to request the Controller to disable one or more advertising sets using the advertising sets identified by the instance parameter. - Parameters num_adv -- [in] : Number of advertising sets to enable or disable ext_adv_inst -- [in] : ext adv instance - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_ext_adv_set_remove(uint8_t instance) This function is used to remove an advertising set from the Controller. - Parameters instance -- [in] : Used to identify an advertising set - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_ext_adv_set_clear(void) This function is used to remove all existing advertising sets from the Controller. - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_periodic_adv_set_params(uint8_t instance, const esp_ble_gap_periodic_adv_params_t *params) This function is used by the Host to set the parameters for periodic advertising. - Parameters instance -- [in] : identifies the advertising set whose periodic advertising parameters are being configured. params -- [in] : periodic adv parameters - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_config_periodic_adv_data_raw(uint8_t instance, uint16_t length, const uint8_t *data) This function is used to set the data used in periodic advertising PDUs. - Parameters instance -- [in] : identifies the advertising set whose periodic advertising parameters are being configured. length -- [in] : the length of periodic data data -- [in] : periodic data information - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_periodic_adv_start(uint8_t instance) This function is used to request the Controller to enable the periodic advertising for the advertising set specified. - Parameters instance -- [in] : Used to identify an advertising set - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_periodic_adv_stop(uint8_t instance) This function is used to request the Controller to disable the periodic advertising for the advertising set specified. - Parameters instance -- [in] : Used to identify an advertising set - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_set_ext_scan_params(const esp_ble_ext_scan_params_t *params) This function is used to set the extended scan parameters to be used on the advertising channels. - Parameters params -- [in] : scan parameters - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_start_ext_scan(uint32_t duration, uint16_t period) This function is used to enable scanning. - Parameters duration -- [in] Scan duration time, where Time = N * 10 ms. Range: 0x0001 to 0xFFFF. period -- [in] Time interval from when the Controller started its last Scan Duration until it begins the subsequent Scan Duration. Time = N * 1.28 sec. Range: 0x0001 to 0xFFFF. - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_stop_ext_scan(void) This function is used to disable scanning. - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_periodic_adv_create_sync(const esp_ble_gap_periodic_adv_sync_params_t *params) This function is used to synchronize with periodic advertising from an advertiser and begin receiving periodic advertising packets. - Parameters params -- [in] : sync parameters - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_periodic_adv_sync_cancel(void) This function is used to cancel the LE_Periodic_Advertising_Create_Sync command while it is pending. - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_periodic_adv_sync_terminate(uint16_t sync_handle) This function is used to stop reception of the periodic advertising identified by the Sync Handle parameter. - Parameters sync_handle -- [in] : identify the periodic advertiser - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_periodic_adv_add_dev_to_list(esp_ble_addr_type_t addr_type, esp_bd_addr_t addr, uint8_t sid) This function is used to add a single device to the Periodic Advertiser list stored in the Controller. - Parameters addr_type -- [in] : address type addr -- [in] : Device Address sid -- [in] : Advertising SID subfield in the ADI field used to identify the Periodic Advertising - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_periodic_adv_remove_dev_from_list(esp_ble_addr_type_t addr_type, esp_bd_addr_t addr, uint8_t sid) This function is used to remove one device from the list of Periodic Advertisers stored in the Controller. Removals from the Periodic Advertisers List take effect immediately. - Parameters addr_type -- [in] : address type addr -- [in] : Device Address sid -- [in] : Advertising SID subfield in the ADI field used to identify the Periodic Advertising - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_periodic_adv_clear_dev(void) This function is used to remove all devices from the list of Periodic Advertisers in the Controller. - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_prefer_ext_connect_params_set(esp_bd_addr_t addr, esp_ble_gap_phy_mask_t phy_mask, const esp_ble_gap_conn_params_t *phy_1m_conn_params, const esp_ble_gap_conn_params_t *phy_2m_conn_params, const esp_ble_gap_conn_params_t *phy_coded_conn_params) This function is used to set aux connection parameters. - Parameters addr -- [in] : device address phy_mask -- [in] : indicates the PHY(s) on which the advertising packets should be received on the primary advertising channel and the PHYs for which connection parameters have been specified. phy_1m_conn_params -- [in] : Scan connectable advertisements on the LE 1M PHY. Connection parameters for the LE 1M PHY are provided. phy_2m_conn_params -- [in] : Connection parameters for the LE 2M PHY are provided. phy_coded_conn_params -- [in] : Scan connectable advertisements on the LE Coded PHY. Connection parameters for the LE Coded PHY are provided. - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_periodic_adv_recv_enable(uint16_t sync_handle, uint8_t enable) This function is used to set periodic advertising receive enable. - Parameters sync_handle -- [in] : Handle of periodic advertising sync enable -- [in] : Determines whether reporting and duplicate filtering are enabled or disabled - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_periodic_adv_sync_trans(esp_bd_addr_t addr, uint16_t service_data, uint16_t sync_handle) This function is used to transfer periodic advertising sync. - Parameters addr -- [in] : Peer device address service_data -- [in] : Service data used by Host sync_handle -- [in] : Handle of periodic advertising sync - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_periodic_adv_set_info_trans(esp_bd_addr_t addr, uint16_t service_data, uint8_t adv_handle) This function is used to transfer periodic advertising set info. - Parameters addr -- [in] : Peer device address service_data -- [in] : Service data used by Host adv_handle -- [in] : Handle of advertising set - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_gap_set_periodic_adv_sync_trans_params(esp_bd_addr_t addr, const esp_ble_gap_past_params_t *params) This function is used to set periodic advertising sync transfer params. - Parameters addr -- [in] : Peer device address params -- [in] : Params of periodic advertising sync transfer - - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_dtm_tx_start(const esp_ble_dtm_tx_t *tx_params) This function is used to start a test where the DUT generates reference packets at a fixed interval. - Parameters tx_params -- [in] : DTM Transmitter parameters - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_dtm_rx_start(const esp_ble_dtm_rx_t *rx_params) This function is used to start a test where the DUT receives test reference packets at a fixed interval. - Parameters rx_params -- [in] : DTM Receiver parameters - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_dtm_enh_tx_start(const esp_ble_dtm_enh_tx_t *tx_params) This function is used to start a test where the DUT generates reference packets at a fixed interval. - Parameters tx_params -- [in] : DTM Transmitter parameters - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_dtm_enh_rx_start(const esp_ble_dtm_enh_rx_t *rx_params) This function is used to start a test where the DUT receives test reference packets at a fixed interval. - Parameters rx_params -- [in] : DTM Receiver parameters - Returns - ESP_OK : success other : failed - - esp_err_t esp_ble_dtm_stop(void) This function is used to stop any test which is in progress. - Returns - ESP_OK : success other : failed - Unions - union esp_ble_key_value_t - #include <esp_gap_ble_api.h> union type of the security key value Public Members - esp_ble_penc_keys_t penc_key received peer encryption key - esp_ble_pcsrk_keys_t pcsrk_key received peer device SRK - esp_ble_pid_keys_t pid_key peer device ID key - esp_ble_lenc_keys_t lenc_key local encryption reproduction keys LTK = = d1(ER,DIV,0) - esp_ble_lcsrk_keys lcsrk_key local device CSRK = d1(ER,DIV,1) - esp_ble_penc_keys_t penc_key - union esp_ble_sec_t - #include <esp_gap_ble_api.h> union associated with ble security Public Members - esp_ble_sec_key_notif_t key_notif passkey notification - esp_ble_sec_req_t ble_req BLE SMP related request - esp_ble_key_t ble_key BLE SMP keys used when pairing - esp_ble_local_id_keys_t ble_id_keys BLE IR event - esp_ble_local_oob_data_t oob_data BLE SMP secure connection OOB data - esp_ble_auth_cmpl_t auth_cmpl Authentication complete indication. - esp_ble_sec_key_notif_t key_notif - union esp_ble_gap_cb_param_t - #include <esp_gap_ble_api.h> Gap callback parameters union. Public Members - struct esp_ble_gap_cb_param_t::ble_get_dev_name_cmpl_evt_param get_dev_name_cmpl Event parameter of ESP_GAP_BLE_GET_DEV_NAME_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_adv_data_cmpl_evt_param adv_data_cmpl Event parameter of ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_scan_rsp_data_cmpl_evt_param scan_rsp_data_cmpl Event parameter of ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_scan_param_cmpl_evt_param scan_param_cmpl Event parameter of ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_scan_result_evt_param scan_rst Event parameter of ESP_GAP_BLE_SCAN_RESULT_EVT - struct esp_ble_gap_cb_param_t::ble_adv_data_raw_cmpl_evt_param adv_data_raw_cmpl Event parameter of ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_scan_rsp_data_raw_cmpl_evt_param scan_rsp_data_raw_cmpl Event parameter of ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_adv_start_cmpl_evt_param adv_start_cmpl Event parameter of ESP_GAP_BLE_ADV_START_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param scan_start_cmpl Event parameter of ESP_GAP_BLE_SCAN_START_COMPLETE_EVT - esp_ble_sec_t ble_security ble gap security union type - struct esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param scan_stop_cmpl Event parameter of ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_adv_stop_cmpl_evt_param adv_stop_cmpl Event parameter of ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_adv_clear_cmpl_evt_param adv_clear_cmpl Event parameter of ESP_GAP_BLE_ADV_CLEAR_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_set_rand_cmpl_evt_param set_rand_addr_cmpl Event parameter of ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT - struct esp_ble_gap_cb_param_t::ble_update_conn_params_evt_param update_conn_params Event parameter of ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT - struct esp_ble_gap_cb_param_t::ble_pkt_data_length_cmpl_evt_param pkt_data_length_cmpl Event parameter of ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_local_privacy_cmpl_evt_param local_privacy_cmpl Event parameter of ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_remove_bond_dev_cmpl_evt_param remove_bond_dev_cmpl Event parameter of ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_clear_bond_dev_cmpl_evt_param clear_bond_dev_cmpl Event parameter of ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_get_bond_dev_cmpl_evt_param get_bond_dev_cmpl Event parameter of ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_read_rssi_cmpl_evt_param read_rssi_cmpl Event parameter of ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_update_whitelist_cmpl_evt_param update_whitelist_cmpl Event parameter of ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_update_duplicate_exceptional_list_cmpl_evt_param update_duplicate_exceptional_list_cmpl Event parameter of ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_set_channels_evt_param ble_set_channels Event parameter of ESP_GAP_BLE_SET_CHANNELS_EVT - struct esp_ble_gap_cb_param_t::ble_read_phy_cmpl_evt_param read_phy Event parameter of ESP_GAP_BLE_READ_PHY_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_set_perf_def_phy_cmpl_evt_param set_perf_def_phy Event parameter of ESP_GAP_BLE_SET_PREFERRED_DEFAULT_PHY_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_set_perf_phy_cmpl_evt_param set_perf_phy Event parameter of ESP_GAP_BLE_SET_PREFERRED_PHY_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_ext_adv_set_rand_addr_cmpl_evt_param ext_adv_set_rand_addr Event parameter of ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_ext_adv_set_params_cmpl_evt_param ext_adv_set_params Event parameter of ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_ext_adv_data_set_cmpl_evt_param ext_adv_data_set Event parameter of ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_ext_adv_scan_rsp_set_cmpl_evt_param scan_rsp_set Event parameter of ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_ext_adv_start_cmpl_evt_param ext_adv_start Event parameter of ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_ext_adv_stop_cmpl_evt_param ext_adv_stop Event parameter of ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_ext_adv_set_remove_cmpl_evt_param ext_adv_remove Event parameter of ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_ext_adv_set_clear_cmpl_evt_param ext_adv_clear Event parameter of ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_periodic_adv_set_params_cmpl_param peroid_adv_set_params Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_periodic_adv_data_set_cmpl_param period_adv_data_set Event parameter of ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_periodic_adv_start_cmpl_param period_adv_start Event parameter of ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_periodic_adv_stop_cmpl_param period_adv_stop Event parameter of ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_period_adv_create_sync_cmpl_param period_adv_create_sync Event parameter of ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_period_adv_sync_cancel_cmpl_param period_adv_sync_cancel Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_period_adv_sync_terminate_cmpl_param period_adv_sync_term Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_period_adv_add_dev_cmpl_param period_adv_add_dev Event parameter of ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_period_adv_remove_dev_cmpl_param period_adv_remove_dev Event parameter of ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_period_adv_clear_dev_cmpl_param period_adv_clear_dev Event parameter of ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_set_ext_scan_params_cmpl_param set_ext_scan_params Event parameter of ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_ext_scan_start_cmpl_param ext_scan_start Event parameter of ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_ext_scan_stop_cmpl_param ext_scan_stop Event parameter of ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_ext_conn_params_set_cmpl_param ext_conn_params_set Event parameter of ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_adv_terminate_param adv_terminate Event parameter of ESP_GAP_BLE_ADV_TERMINATED_EVT - struct esp_ble_gap_cb_param_t::ble_scan_req_received_param scan_req_received Event parameter of ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT - struct esp_ble_gap_cb_param_t::ble_channel_sel_alg_param channel_sel_alg Event parameter of ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT - struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_lost_param periodic_adv_sync_lost Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT - struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_estab_param periodic_adv_sync_estab Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT - struct esp_ble_gap_cb_param_t::ble_phy_update_cmpl_param phy_update Event parameter of ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_ext_adv_report_param ext_adv_report Event parameter of ESP_GAP_BLE_EXT_ADV_REPORT_EVT - struct esp_ble_gap_cb_param_t::ble_periodic_adv_report_param period_adv_report Event parameter of ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT - struct esp_ble_gap_cb_param_t::ble_periodic_adv_recv_enable_cmpl_param period_adv_recv_enable Event parameter of ESP_GAP_BLE_PERIODIC_ADV_RECV_ENABLE_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_trans_cmpl_param period_adv_sync_trans Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_periodic_adv_set_info_trans_cmpl_param period_adv_set_info_trans Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SET_INFO_TRANS_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_set_past_params_cmpl_param set_past_params Event parameter of ESP_GAP_BLE_SET_PAST_PARAMS_COMPLETE_EVT - struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_trans_recv_param past_received Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_RECV_EVT - struct esp_ble_gap_cb_param_t::ble_dtm_state_update_evt_param dtm_state_update Event parameter of ESP_GAP_BLE_DTM_TEST_UPDATE_EVT - struct ble_adv_clear_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_CLEAR_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate adv clear operation success status - esp_bt_status_t status - struct ble_adv_data_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate the set advertising data operation success status - esp_bt_status_t status - struct ble_adv_data_raw_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate the set raw advertising data operation success status - esp_bt_status_t status - struct ble_adv_start_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_START_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate advertising start operation success status - esp_bt_status_t status - struct ble_adv_stop_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate adv stop operation success status - esp_bt_status_t status - struct ble_adv_terminate_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_TERMINATED_EVT. - struct ble_channel_sel_alg_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT. - struct ble_clear_bond_dev_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate the clear bond device operation success status - esp_bt_status_t status - struct ble_dtm_state_update_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_DTM_TEST_UPDATE_EVT. Public Members - esp_bt_status_t status Indicate DTM operation success status - esp_ble_dtm_update_evt_t update_evt DTM state change event, 0x00: DTM TX start, 0x01: DTM RX start, 0x02:DTM end - uint16_t num_of_pkt number of packets received, only valid if update_evt is DTM_TEST_STOP_EVT and shall be reported as 0 for a transmitter - esp_bt_status_t status - struct ble_ext_adv_data_set_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate extend advertising data set status - esp_bt_status_t status - struct ble_ext_adv_report_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_REPORT_EVT. Public Members - esp_ble_gap_ext_adv_reprot_t params extend advertising report parameters - esp_ble_gap_ext_adv_reprot_t params - struct ble_ext_adv_scan_rsp_set_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate extend advertising scan response data set status - esp_bt_status_t status - struct ble_ext_adv_set_clear_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT. - struct ble_ext_adv_set_params_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate extend advertising parameters set status - esp_bt_status_t status - struct ble_ext_adv_set_rand_addr_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate extend advertising random address set status - esp_bt_status_t status - struct ble_ext_adv_set_remove_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT. - struct ble_ext_adv_start_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate advertising start operation success status - esp_bt_status_t status - struct ble_ext_adv_stop_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT. - struct ble_ext_conn_params_set_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate extend connection parameters set status - esp_bt_status_t status - struct ble_ext_scan_start_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate extend advertising start status - esp_bt_status_t status - struct ble_ext_scan_stop_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate extend advertising stop status - esp_bt_status_t status - struct ble_get_bond_dev_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate the get bond device operation success status - uint8_t dev_num Indicate the get number device in the bond list - esp_ble_bond_dev_t *bond_dev the pointer to the bond device Structure - esp_bt_status_t status - struct ble_get_dev_name_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_GET_DEV_NAME_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate the get device name success status - char *name Name of bluetooth device - esp_bt_status_t status - struct ble_local_privacy_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate the set local privacy operation success status - esp_bt_status_t status - struct ble_period_adv_add_dev_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate periodic advertising device list add status - esp_bt_status_t status - struct ble_period_adv_clear_dev_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate periodic advertising device list clean status - esp_bt_status_t status - struct ble_period_adv_create_sync_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate periodic advertising create sync status - esp_bt_status_t status - struct ble_period_adv_remove_dev_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate periodic advertising device list remove status - esp_bt_status_t status - struct ble_period_adv_sync_cancel_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate periodic advertising sync cancel status - esp_bt_status_t status - struct ble_period_adv_sync_terminate_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate periodic advertising sync terminate status - esp_bt_status_t status - struct ble_periodic_adv_data_set_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate periodic advertising data set status - esp_bt_status_t status - struct ble_periodic_adv_recv_enable_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_RECV_ENABLE_COMPLETE_EVT. Public Members - esp_bt_status_t status Set periodic advertising receive enable status - esp_bt_status_t status - struct ble_periodic_adv_report_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT. Public Members - esp_ble_gap_periodic_adv_report_t params periodic advertising report parameters - esp_ble_gap_periodic_adv_report_t params - struct ble_periodic_adv_set_info_trans_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SET_INFO_TRANS_COMPLETE_EVT. Public Members - esp_bt_status_t status Periodic advertising set info transfer status - esp_bd_addr_t bda The remote device address - esp_bt_status_t status - struct ble_periodic_adv_set_params_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate periodic advertisingparameters set status - esp_bt_status_t status - struct ble_periodic_adv_start_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate periodic advertising start status - esp_bt_status_t status - struct ble_periodic_adv_stop_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate periodic advertising stop status - esp_bt_status_t status - struct ble_periodic_adv_sync_estab_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT. Public Members - uint8_t status periodic advertising sync status - uint16_t sync_handle periodic advertising sync handle - uint8_t sid periodic advertising sid - esp_ble_addr_type_t adv_addr_type periodic advertising address type - esp_bd_addr_t adv_addr periodic advertising address - esp_ble_gap_phy_t adv_phy periodic advertising phy type - uint16_t period_adv_interval periodic advertising interval - uint8_t adv_clk_accuracy periodic advertising clock accuracy - uint8_t status - struct ble_periodic_adv_sync_lost_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT. Public Members - uint16_t sync_handle sync handle - uint16_t sync_handle - struct ble_periodic_adv_sync_trans_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_COMPLETE_EVT. Public Members - esp_bt_status_t status Periodic advertising sync transfer status - esp_bd_addr_t bda The remote device address - esp_bt_status_t status - struct ble_periodic_adv_sync_trans_recv_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_RECV_EVT. Public Members - esp_bt_status_t status Periodic advertising sync transfer received status - esp_bd_addr_t bda The remote device address - uint16_t service_data The value provided by the peer device - uint16_t sync_handle Periodic advertising sync handle - uint8_t adv_sid Periodic advertising set id - uint8_t adv_addr_type Periodic advertiser address type - esp_bd_addr_t adv_addr Periodic advertiser address - esp_ble_gap_phy_t adv_phy Periodic advertising PHY - uint16_t adv_interval Periodic advertising interval - uint8_t adv_clk_accuracy Periodic advertising clock accuracy - esp_bt_status_t status - struct ble_phy_update_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT. Public Members - esp_bt_status_t status phy update status - esp_bd_addr_t bda address - esp_ble_gap_phy_t tx_phy tx phy type - esp_ble_gap_phy_t rx_phy rx phy type - esp_bt_status_t status - struct ble_pkt_data_length_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate the set pkt data length operation success status - esp_ble_pkt_data_length_params_t params pkt data length value - esp_bt_status_t status - struct ble_read_phy_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_READ_PHY_COMPLETE_EVT. Public Members - esp_bt_status_t status read phy complete status - esp_bd_addr_t bda read phy address - esp_ble_gap_phy_t tx_phy tx phy type - esp_ble_gap_phy_t rx_phy rx phy type - esp_bt_status_t status - struct ble_read_rssi_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate the read adv tx power operation success status - int8_t rssi The ble remote device rssi value, the range is from -127 to 20, the unit is dbm, if the RSSI cannot be read, the RSSI metric shall be set to 127. - esp_bd_addr_t remote_addr The remote device address - esp_bt_status_t status - struct ble_remove_bond_dev_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate the remove bond device operation success status - esp_bd_addr_t bd_addr The device address which has been remove from the bond list - esp_bt_status_t status - struct ble_scan_param_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate the set scan param operation success status - esp_bt_status_t status - struct ble_scan_req_received_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT. Public Members - uint8_t adv_instance extend advertising handle - esp_ble_addr_type_t scan_addr_type scanner address type - esp_bd_addr_t scan_addr scanner address - uint8_t adv_instance - struct ble_scan_result_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_RESULT_EVT. Public Members - esp_gap_search_evt_t search_evt Search event type - esp_bd_addr_t bda Bluetooth device address which has been searched - esp_bt_dev_type_t dev_type Device type - esp_ble_addr_type_t ble_addr_type Ble device address type - esp_ble_evt_type_t ble_evt_type Ble scan result event type - int rssi Searched device's RSSI - uint8_t ble_adv[ESP_BLE_ADV_DATA_LEN_MAX + ESP_BLE_SCAN_RSP_DATA_LEN_MAX] Received EIR - int flag Advertising data flag bit - int num_resps Scan result number - uint8_t adv_data_len Adv data length - uint8_t scan_rsp_len Scan response length - uint32_t num_dis The number of discard packets - esp_gap_search_evt_t search_evt - struct ble_scan_rsp_data_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate the set scan response data operation success status - esp_bt_status_t status - struct ble_scan_rsp_data_raw_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate the set raw advertising data operation success status - esp_bt_status_t status - struct ble_scan_start_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_START_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate scan start operation success status - esp_bt_status_t status - struct ble_scan_stop_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate scan stop operation success status - esp_bt_status_t status - struct ble_set_channels_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_CHANNELS_EVT. Public Members - esp_bt_status_t stat BLE set channel status - esp_bt_status_t stat - struct ble_set_ext_scan_params_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate extend advertising parameters set status - esp_bt_status_t status - struct ble_set_past_params_cmpl_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PAST_PARAMS_COMPLETE_EVT. Public Members - esp_bt_status_t status Set periodic advertising sync transfer params status - esp_bd_addr_t bda The remote device address - esp_bt_status_t status - struct ble_set_perf_def_phy_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PREFERRED_DEFAULT_PHY_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate perf default phy set status - esp_bt_status_t status - struct ble_set_perf_phy_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PREFERRED_PHY_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate perf phy set status - esp_bt_status_t status - struct ble_set_rand_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT. Public Members - esp_bt_status_t status Indicate set static rand address operation success status - esp_bt_status_t status - struct ble_update_conn_params_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT. Public Members - esp_bt_status_t status Indicate update connection parameters success status - esp_bd_addr_t bda Bluetooth device address - uint16_t min_int Min connection interval - uint16_t max_int Max connection interval - uint16_t latency Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 - uint16_t conn_int Current connection interval - uint16_t timeout Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec - esp_bt_status_t status - struct ble_update_duplicate_exceptional_list_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate update duplicate scan exceptional list operation success status - uint8_t subcode Define in esp_bt_duplicate_exceptional_subcode_type_t - uint16_t length The length of device_info - esp_duplicate_info_t device_info device information, when subcode is ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_CLEAN, the value is invalid - esp_bt_status_t status - struct ble_update_whitelist_cmpl_evt_param - #include <esp_gap_ble_api.h> ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT. Public Members - esp_bt_status_t status Indicate the add or remove whitelist operation success status - esp_ble_wl_operation_t wl_operation The value is ESP_BLE_WHITELIST_ADD if add address to whitelist operation success, ESP_BLE_WHITELIST_REMOVE if remove address from the whitelist operation success - esp_bt_status_t status - struct esp_ble_gap_cb_param_t::ble_get_dev_name_cmpl_evt_param get_dev_name_cmpl Structures - struct esp_ble_dtm_tx_t DTM TX parameters. Public Members - uint8_t tx_channel channel for sending test data, tx_channel = (Frequency -2402)/2, tx_channel range:0x00-0x27, Frequency range: 2402 MHz to 2480 MHz - uint8_t len_of_data length in bytes of payload data in each packet - esp_ble_dtm_pkt_payload_t pkt_payload packet payload type. value range: 0x00-0x07 - uint8_t tx_channel - struct esp_ble_dtm_rx_t DTM RX parameters. Public Members - uint8_t rx_channel channel for test data reception, rx_channel = (Frequency -2402)/2, tx_channel range:0x00-0x27, Frequency range: 2402 MHz to 2480 MHz - uint8_t rx_channel - struct esp_ble_adv_params_t Advertising parameters. Public Members - uint16_t adv_int_min Minimum advertising interval for undirected and low duty cycle directed advertising. Range: 0x0020 to 0x4000 Default: N = 0x0800 (1.28 second) Time = N * 0.625 msec Time Range: 20 ms to 10.24 sec - uint16_t adv_int_max Maximum advertising interval for undirected and low duty cycle directed advertising. Range: 0x0020 to 0x4000 Default: N = 0x0800 (1.28 second) Time = N * 0.625 msec Time Range: 20 ms to 10.24 sec Advertising max interval - esp_ble_adv_type_t adv_type Advertising type - esp_ble_addr_type_t own_addr_type Owner bluetooth device address type - esp_bd_addr_t peer_addr Peer device bluetooth device address - esp_ble_addr_type_t peer_addr_type Peer device bluetooth device address type, only support public address type and random address type - esp_ble_adv_channel_t channel_map Advertising channel map - esp_ble_adv_filter_t adv_filter_policy Advertising filter policy - uint16_t adv_int_min - struct esp_ble_adv_data_t Advertising data content, according to "Supplement to the Bluetooth Core Specification". Public Members - bool set_scan_rsp Set this advertising data as scan response or not - bool include_name Advertising data include device name or not - bool include_txpower Advertising data include TX power - int min_interval Advertising data show slave preferred connection min interval. The connection interval in the following manner: connIntervalmin = Conn_Interval_Min * 1.25 ms Conn_Interval_Min range: 0x0006 to 0x0C80 Value of 0xFFFF indicates no specific minimum. Values not defined above are reserved for future use. - int max_interval Advertising data show slave preferred connection max interval. The connection interval in the following manner: connIntervalmax = Conn_Interval_Max * 1.25 ms Conn_Interval_Max range: 0x0006 to 0x0C80 Conn_Interval_Max shall be equal to or greater than the Conn_Interval_Min. Value of 0xFFFF indicates no specific maximum. Values not defined above are reserved for future use. - int appearance External appearance of device - uint16_t manufacturer_len Manufacturer data length - uint8_t *p_manufacturer_data Manufacturer data point - uint16_t service_data_len Service data length - uint8_t *p_service_data Service data point - uint16_t service_uuid_len Service uuid length - uint8_t *p_service_uuid Service uuid array point - uint8_t flag Advertising flag of discovery mode, see BLE_ADV_DATA_FLAG detail - bool set_scan_rsp - struct esp_ble_scan_params_t Ble scan parameters. Public Members - esp_ble_scan_type_t scan_type Scan type - esp_ble_addr_type_t own_addr_type Owner address type - esp_ble_scan_filter_t scan_filter_policy Scan filter policy - uint16_t scan_interval Scan interval. This is defined as the time interval from when the Controller started its last LE scan until it begins the subsequent LE scan. Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms) Time = N * 0.625 msec Time Range: 2.5 msec to 10.24 seconds - uint16_t scan_window Scan window. The duration of the LE scan. LE_Scan_Window shall be less than or equal to LE_Scan_Interval Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms) Time = N * 0.625 msec Time Range: 2.5 msec to 10240 msec - esp_ble_scan_duplicate_t scan_duplicate The Scan_Duplicates parameter controls whether the Link Layer should filter out duplicate advertising reports (BLE_SCAN_DUPLICATE_ENABLE) to the Host, or if the Link Layer should generate advertising reports for each packet received - esp_ble_scan_type_t scan_type - struct esp_gap_conn_params_t connection parameters information Public Members - uint16_t interval connection interval - uint16_t latency Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 - uint16_t timeout Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec Time Range: 100 msec to 32 seconds - uint16_t interval - struct esp_ble_conn_update_params_t Connection update parameters. Public Members - esp_bd_addr_t bda Bluetooth device address - uint16_t min_int Min connection interval - uint16_t max_int Max connection interval - uint16_t latency Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 - uint16_t timeout Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec Time Range: 100 msec to 32 seconds - esp_bd_addr_t bda - struct esp_ble_pkt_data_length_params_t BLE pkt date length keys. - struct esp_ble_penc_keys_t BLE encryption keys. Public Members - esp_bt_octet16_t ltk The long term key - esp_bt_octet8_t rand The random number - uint16_t ediv The ediv value - uint8_t sec_level The security level of the security link - uint8_t key_size The key size(7~16) of the security link - esp_bt_octet16_t ltk - struct esp_ble_pcsrk_keys_t BLE CSRK keys. Public Members - uint32_t counter The counter - esp_bt_octet16_t csrk The csrk key - uint8_t sec_level The security level - uint32_t counter - struct esp_ble_pid_keys_t BLE pid keys. Public Members - esp_bt_octet16_t irk The irk value - esp_ble_addr_type_t addr_type The address type - esp_bd_addr_t static_addr The static address - esp_bt_octet16_t irk - struct esp_ble_lenc_keys_t BLE Encryption reproduction keys. Public Members - esp_bt_octet16_t ltk The long term key - uint16_t div The div value - uint8_t key_size The key size of the security link - uint8_t sec_level The security level of the security link - esp_bt_octet16_t ltk - struct esp_ble_lcsrk_keys BLE SRK keys. Public Members - uint32_t counter The counter value - uint16_t div The div value - uint8_t sec_level The security level of the security link - esp_bt_octet16_t csrk The csrk key value - uint32_t counter - struct esp_ble_sec_key_notif_t Structure associated with ESP_KEY_NOTIF_EVT. Public Members - esp_bd_addr_t bd_addr peer address - uint32_t passkey the numeric value for comparison. If just_works, do not show this number to UI - esp_bd_addr_t bd_addr - struct esp_ble_sec_req_t Structure of the security request. Public Members - esp_bd_addr_t bd_addr peer address - esp_bd_addr_t bd_addr - struct esp_ble_bond_key_info_t struct type of the bond key information value Public Members - esp_ble_key_mask_t key_mask the key mask to indicate witch key is present - esp_ble_penc_keys_t penc_key received peer encryption key - esp_ble_pcsrk_keys_t pcsrk_key received peer device SRK - esp_ble_pid_keys_t pid_key peer device ID key - esp_ble_key_mask_t key_mask - struct esp_ble_bond_dev_t struct type of the bond device value Public Members - esp_bd_addr_t bd_addr peer address - esp_ble_bond_key_info_t bond_key the bond key information - esp_bd_addr_t bd_addr - struct esp_ble_key_t union type of the security key value Public Members - esp_bd_addr_t bd_addr peer address - esp_ble_key_type_t key_type key type of the security link - esp_ble_key_value_t p_key_value the pointer to the key value - esp_bd_addr_t bd_addr - struct esp_ble_local_id_keys_t structure type of the ble local id keys value Public Members - esp_bt_octet16_t ir the 16 bits of the ir value - esp_bt_octet16_t irk the 16 bits of the ir key value - esp_bt_octet16_t dhk the 16 bits of the dh key value - esp_bt_octet16_t ir - struct esp_ble_local_oob_data_t structure type of the ble local oob data value Public Members - esp_bt_octet16_t oob_c the 128 bits of confirmation value - esp_bt_octet16_t oob_r the 128 bits of randomizer value - esp_bt_octet16_t oob_c - struct esp_ble_auth_cmpl_t Structure associated with ESP_AUTH_CMPL_EVT. Public Members - esp_bd_addr_t bd_addr BD address peer device. - bool key_present Valid link key value in key element - esp_link_key key Link key associated with peer device. - uint8_t key_type The type of Link Key - bool success TRUE of authentication succeeded, FALSE if failed. - uint8_t fail_reason The HCI reason/error code for when success=FALSE - esp_ble_addr_type_t addr_type Peer device address type - esp_bt_dev_type_t dev_type Device type - esp_ble_auth_req_t auth_mode authentication mode - esp_bd_addr_t bd_addr - struct esp_ble_gap_ext_adv_params_t ext adv parameters Public Members - esp_ble_ext_adv_type_mask_t type ext adv type - uint32_t interval_min ext adv minimum interval - uint32_t interval_max ext adv maximum interval - esp_ble_adv_channel_t channel_map ext adv channel map - esp_ble_addr_type_t own_addr_type ext adv own address type - esp_ble_addr_type_t peer_addr_type ext adv peer address type - esp_bd_addr_t peer_addr ext adv peer address - esp_ble_adv_filter_t filter_policy ext adv filter policy - int8_t tx_power ext adv tx power - esp_ble_gap_pri_phy_t primary_phy ext adv primary phy - uint8_t max_skip ext adv maximum skip - esp_ble_gap_phy_t secondary_phy ext adv secondary phy - uint8_t sid ext adv sid - bool scan_req_notif ext adv scan request event notify - esp_ble_ext_adv_type_mask_t type - struct esp_ble_ext_scan_cfg_t ext scan config Public Members - esp_ble_scan_type_t scan_type ext scan type - uint16_t scan_interval ext scan interval - uint16_t scan_window ext scan window - esp_ble_scan_type_t scan_type - struct esp_ble_ext_scan_params_t ext scan parameters Public Members - esp_ble_addr_type_t own_addr_type ext scan own address type - esp_ble_scan_filter_t filter_policy ext scan filter policy - esp_ble_scan_duplicate_t scan_duplicate ext scan duplicate scan - esp_ble_ext_scan_cfg_mask_t cfg_mask ext scan config mask - esp_ble_ext_scan_cfg_t uncoded_cfg ext scan uncoded config parameters - esp_ble_ext_scan_cfg_t coded_cfg ext scan coded config parameters - esp_ble_addr_type_t own_addr_type - struct esp_ble_gap_conn_params_t create extend connection parameters Public Members - uint16_t scan_interval init scan interval - uint16_t scan_window init scan window - uint16_t interval_min minimum interval - uint16_t interval_max maximum interval - uint16_t latency ext scan type - uint16_t supervision_timeout connection supervision timeout - uint16_t min_ce_len minimum ce length - uint16_t max_ce_len maximum ce length - uint16_t scan_interval - struct esp_ble_gap_ext_adv_t extend adv enable parameters - struct esp_ble_gap_periodic_adv_params_t periodic adv parameters - struct esp_ble_gap_periodic_adv_sync_params_t periodic adv sync parameters Public Members - esp_ble_gap_sync_t filter_policy Configures the filter policy for periodic advertising sync: 0: Use Advertising SID, Advertiser Address Type, and Advertiser Address parameters to determine the advertiser to listen to. 1: Use the Periodic Advertiser List to determine the advertiser to listen to. - uint8_t sid SID of the periodic advertising - esp_ble_addr_type_t addr_type Address type of the periodic advertising - esp_bd_addr_t addr Address of the periodic advertising - uint16_t skip Maximum number of periodic advertising events that can be skipped - uint16_t sync_timeout Synchronization timeout - esp_ble_gap_sync_t filter_policy - struct esp_ble_gap_ext_adv_reprot_t extend adv report parameters Public Members - esp_ble_gap_adv_type_t event_type extend advertising type - uint8_t addr_type extend advertising address type - esp_bd_addr_t addr extend advertising address - esp_ble_gap_pri_phy_t primary_phy extend advertising primary phy - esp_ble_gap_phy_t secondly_phy extend advertising secondary phy - uint8_t sid extend advertising sid - uint8_t tx_power extend advertising tx power - int8_t rssi extend advertising rssi - uint16_t per_adv_interval periodic advertising interval - uint8_t dir_addr_type direct address type - esp_bd_addr_t dir_addr direct address - esp_ble_gap_ext_adv_data_status_t data_status data type - uint8_t adv_data_len extend advertising data length - uint8_t adv_data[251] extend advertising data - esp_ble_gap_adv_type_t event_type - struct esp_ble_gap_periodic_adv_report_t periodic adv report parameters Public Members - uint16_t sync_handle periodic advertising train handle - uint8_t tx_power periodic advertising tx power - int8_t rssi periodic advertising rssi - esp_ble_gap_ext_adv_data_status_t data_status periodic advertising data type - uint8_t data_length periodic advertising data length - uint8_t data[251] periodic advertising data - uint16_t sync_handle - struct esp_ble_gap_periodic_adv_sync_estab_t perodic adv sync establish parameters Public Members - uint8_t status periodic advertising sync status - uint16_t sync_handle periodic advertising train handle - uint8_t sid periodic advertising sid - esp_ble_addr_type_t addr_type periodic advertising address type - esp_bd_addr_t adv_addr periodic advertising address - esp_ble_gap_phy_t adv_phy periodic advertising adv phy type - uint16_t period_adv_interval periodic advertising interval - uint8_t adv_clk_accuracy periodic advertising clock accuracy - uint8_t status - struct esp_ble_dtm_enh_tx_t DTM TX parameters. Public Members - uint8_t tx_channel channel for sending test data, tx_channel = (Frequency -2402)/2, tx_channel range:0x00-0x27, Frequency range: 2402 MHz to 2480 MHz - uint8_t len_of_data length in bytes of payload data in each packet - esp_ble_dtm_pkt_payload_t pkt_payload packet payload type. value range: 0x00-0x07 - esp_ble_gap_phy_t phy the phy type used by the transmitter, coded phy with S=2:0x04 - uint8_t tx_channel - struct esp_ble_dtm_enh_rx_t DTM RX parameters. Public Members - uint8_t rx_channel channel for test data reception, rx_channel = (Frequency -2402)/2, tx_channel range:0x00-0x27, Frequency range: 2402 MHz to 2480 MHz - esp_ble_gap_phy_t phy the phy type used by the receiver, 1M phy: 0x01, 2M phy:0x02, coded phy:0x03 - uint8_t modulation_idx modulation index, 0x00:standard modulation index, 0x01:stable modulation index - uint8_t rx_channel - struct esp_ble_gap_past_params_t periodic adv sync transfer parameters Public Members - esp_ble_gap_past_mode_t mode periodic advertising sync transfer mode - uint16_t skip the number of periodic advertising packets that can be skipped - uint16_t sync_timeout synchronization timeout for the periodic advertising train - uint8_t cte_type periodic advertising sync transfer CET type - esp_ble_gap_past_mode_t mode Macros - ESP_BLE_ADV_FLAG_LIMIT_DISC BLE_ADV_DATA_FLAG data flag bit definition used for advertising data flag. - ESP_BLE_ADV_FLAG_GEN_DISC - ESP_BLE_ADV_FLAG_BREDR_NOT_SPT - ESP_BLE_ADV_FLAG_DMT_CONTROLLER_SPT - ESP_BLE_ADV_FLAG_DMT_HOST_SPT - ESP_BLE_ADV_FLAG_NON_LIMIT_DISC - ESP_LE_KEY_NONE relate to BTM_LE_KEY_xxx in stack/btm_api.h No encryption key - ESP_LE_KEY_PENC encryption key, encryption information of peer device - ESP_LE_KEY_PID identity key of the peer device - ESP_LE_KEY_PCSRK peer SRK - ESP_LE_KEY_PLK Link key - ESP_LE_KEY_LLK peer link key - ESP_LE_KEY_LENC master role security information:div - ESP_LE_KEY_LID master device ID key - ESP_LE_KEY_LCSRK local CSRK has been deliver to peer - ESP_LE_AUTH_NO_BOND relate to BTM_LE_AUTH_xxx in stack/btm_api.h 0 no bondingv - ESP_LE_AUTH_BOND 1 << 0 device in the bonding with peer - ESP_LE_AUTH_REQ_MITM 1 << 2 man in the middle attack - ESP_LE_AUTH_REQ_BOND_MITM 0101 banding with man in the middle attack - ESP_LE_AUTH_REQ_SC_ONLY 1 << 3 secure connection - ESP_LE_AUTH_REQ_SC_BOND 1001 secure connection with band - ESP_LE_AUTH_REQ_SC_MITM 1100 secure conn with MITM - ESP_LE_AUTH_REQ_SC_MITM_BOND 1101 SC with MITM and Bonding - ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_DISABLE authentication disable - ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_ENABLE authentication enable - ESP_BLE_OOB_DISABLE disbale the out of bond - ESP_BLE_OOB_ENABLE enable the out of bond - ESP_IO_CAP_OUT relate to BTM_IO_CAP_xxx in stack/btm_api.h DisplayOnly - ESP_IO_CAP_IO DisplayYesNo - ESP_IO_CAP_IN KeyboardOnly - ESP_IO_CAP_NONE NoInputNoOutput - ESP_IO_CAP_KBDISP Keyboard display - ESP_BLE_APPEARANCE_UNKNOWN relate to BTM_BLE_APPEARANCE_UNKNOWN in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_PHONE relate to BTM_BLE_APPEARANCE_GENERIC_PHONE in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_COMPUTER relate to BTM_BLE_APPEARANCE_GENERIC_COMPUTER in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_WATCH relate to BTM_BLE_APPEARANCE_GENERIC_WATCH in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_SPORTS_WATCH relate to BTM_BLE_APPEARANCE_SPORTS_WATCH in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_CLOCK relate to BTM_BLE_APPEARANCE_GENERIC_CLOCK in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_DISPLAY relate to BTM_BLE_APPEARANCE_GENERIC_DISPLAY in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_REMOTE relate to BTM_BLE_APPEARANCE_GENERIC_REMOTE in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_EYEGLASSES relate to BTM_BLE_APPEARANCE_GENERIC_EYEGLASSES in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_TAG relate to BTM_BLE_APPEARANCE_GENERIC_TAG in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_KEYRING relate to BTM_BLE_APPEARANCE_GENERIC_KEYRING in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_MEDIA_PLAYER relate to BTM_BLE_APPEARANCE_GENERIC_MEDIA_PLAYER in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_BARCODE_SCANNER relate to BTM_BLE_APPEARANCE_GENERIC_BARCODE_SCANNER in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_THERMOMETER relate to BTM_BLE_APPEARANCE_GENERIC_THERMOMETER in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_THERMOMETER_EAR relate to BTM_BLE_APPEARANCE_THERMOMETER_EAR in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_HEART_RATE relate to BTM_BLE_APPEARANCE_GENERIC_HEART_RATE in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_HEART_RATE_BELT relate to BTM_BLE_APPEARANCE_HEART_RATE_BELT in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_BLOOD_PRESSURE relate to BTM_BLE_APPEARANCE_GENERIC_BLOOD_PRESSURE in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_BLOOD_PRESSURE_ARM relate to BTM_BLE_APPEARANCE_BLOOD_PRESSURE_ARM in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_BLOOD_PRESSURE_WRIST relate to BTM_BLE_APPEARANCE_BLOOD_PRESSURE_WRIST in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_HID relate to BTM_BLE_APPEARANCE_GENERIC_HID in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_HID_KEYBOARD relate to BTM_BLE_APPEARANCE_HID_KEYBOARD in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_HID_MOUSE relate to BTM_BLE_APPEARANCE_HID_MOUSE in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_HID_JOYSTICK relate to BTM_BLE_APPEARANCE_HID_JOYSTICK in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_HID_GAMEPAD relate to BTM_BLE_APPEARANCE_HID_GAMEPAD in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_HID_DIGITIZER_TABLET relate to BTM_BLE_APPEARANCE_HID_DIGITIZER_TABLET in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_HID_CARD_READER relate to BTM_BLE_APPEARANCE_HID_CARD_READER in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_HID_DIGITAL_PEN relate to BTM_BLE_APPEARANCE_HID_DIGITAL_PEN in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_HID_BARCODE_SCANNER relate to BTM_BLE_APPEARANCE_HID_BARCODE_SCANNER in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_GLUCOSE relate to BTM_BLE_APPEARANCE_GENERIC_GLUCOSE in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_WALKING relate to BTM_BLE_APPEARANCE_GENERIC_WALKING in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_WALKING_IN_SHOE relate to BTM_BLE_APPEARANCE_WALKING_IN_SHOE in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_WALKING_ON_SHOE relate to BTM_BLE_APPEARANCE_WALKING_ON_SHOE in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_WALKING_ON_HIP relate to BTM_BLE_APPEARANCE_WALKING_ON_HIP in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_CYCLING relate to BTM_BLE_APPEARANCE_GENERIC_CYCLING in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_CYCLING_COMPUTER relate to BTM_BLE_APPEARANCE_CYCLING_COMPUTER in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_CYCLING_SPEED relate to BTM_BLE_APPEARANCE_CYCLING_SPEED in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_CYCLING_CADENCE relate to BTM_BLE_APPEARANCE_CYCLING_CADENCE in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_CYCLING_POWER relate to BTM_BLE_APPEARANCE_CYCLING_POWER in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_CYCLING_SPEED_CADENCE relate to BTM_BLE_APPEARANCE_CYCLING_SPEED_CADENCE in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_PULSE_OXIMETER relate to BTM_BLE_APPEARANCE_GENERIC_PULSE_OXIMETER in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_PULSE_OXIMETER_FINGERTIP relate to BTM_BLE_APPEARANCE_PULSE_OXIMETER_FINGERTIP in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_PULSE_OXIMETER_WRIST relate to BTM_BLE_APPEARANCE_PULSE_OXIMETER_WRIST in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_WEIGHT relate to BTM_BLE_APPEARANCE_GENERIC_WEIGHT in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_PERSONAL_MOBILITY_DEVICE relate to BTM_BLE_APPEARANCE_GENERIC_PERSONAL_MOBILITY_DEVICE in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_POWERED_WHEELCHAIR relate to BTM_BLE_APPEARANCE_POWERED_WHEELCHAIR in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_MOBILITY_SCOOTER relate to BTM_BLE_APPEARANCE_MOBILITY_SCOOTER in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_CONTINUOUS_GLUCOSE_MONITOR relate to BTM_BLE_APPEARANCE_GENERIC_CONTINUOUS_GLUCOSE_MONITOR in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_INSULIN_PUMP relate to BTM_BLE_APPEARANCE_GENERIC_INSULIN_PUMP in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_INSULIN_PUMP_DURABLE_PUMP relate to BTM_BLE_APPEARANCE_INSULIN_PUMP_DURABLE_PUMP in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_INSULIN_PUMP_PATCH_PUMP relate to BTM_BLE_APPEARANCE_INSULIN_PUMP_PATCH_PUMP in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_INSULIN_PEN relate to BTM_BLE_APPEARANCE_INSULIN_PEN in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_MEDICATION_DELIVERY relate to BTM_BLE_APPEARANCE_GENERIC_MEDICATION_DELIVERY in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_GENERIC_OUTDOOR_SPORTS relate to BTM_BLE_APPEARANCE_GENERIC_OUTDOOR_SPORTS in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_AND_NAV relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_AND_NAV in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD in stack/btm_ble_api.h - ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD_AND_NAV relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD_AND_NAV in stack/btm_ble_api.h - BLE_DTM_PKT_PAYLOAD_0x00 PRBS9 sequence ‘11111111100000111101...’ (in transmission order) as described in [Vol 6] Part F, Section 4.1.5 - BLE_DTM_PKT_PAYLOAD_0x01 Repeated ‘11110000’ (in transmission order) sequence as described in [Vol 6] Part F, Section 4.1.5 - BLE_DTM_PKT_PAYLOAD_0x02 Repeated ‘10101010’ (in transmission order) sequence as described in [Vol 6] Part F, Section 4.1.5 - BLE_DTM_PKT_PAYLOAD_0x03 PRBS15 sequence as described in [Vol 6] Part F, Section 4.1.5 - BLE_DTM_PKT_PAYLOAD_0x04 Repeated ‘11111111’ (in transmission order) sequence - BLE_DTM_PKT_PAYLOAD_0x05 Repeated ‘00000000’ (in transmission order) sequence - BLE_DTM_PKT_PAYLOAD_0x06 Repeated ‘00001111’ (in transmission order) sequence - BLE_DTM_PKT_PAYLOAD_0x07 Repeated ‘01010101’ (in transmission order) sequence - BLE_DTM_PKT_PAYLOAD_MAX 0x08 ~ 0xFF, Reserved for future use - ESP_GAP_BLE_CHANNELS_LEN channel length - ESP_GAP_BLE_ADD_WHITELIST_COMPLETE_EVT This is the old name, just for backwards compatibility. - ESP_BLE_ADV_DATA_LEN_MAX Advertising data maximum length. - ESP_BLE_SCAN_RSP_DATA_LEN_MAX Scan response data maximum length. - BLE_BIT(n) - ESP_BLE_GAP_SET_EXT_ADV_PROP_NONCONN_NONSCANNABLE_UNDIRECTED Non-Connectable and Non-Scannable Undirected advertising - ESP_BLE_GAP_SET_EXT_ADV_PROP_CONNECTABLE Connectable advertising - ESP_BLE_GAP_SET_EXT_ADV_PROP_SCANNABLE Scannable advertising - ESP_BLE_GAP_SET_EXT_ADV_PROP_DIRECTED Directed advertising - ESP_BLE_GAP_SET_EXT_ADV_PROP_HD_DIRECTED High Duty Cycle Directed Connectable advertising (<= 3.75 ms Advertising Interval) - ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY Use legacy advertising PDUs - ESP_BLE_GAP_SET_EXT_ADV_PROP_ANON_ADV Omit advertiser's address from all PDUs ("anonymous advertising") - ESP_BLE_GAP_SET_EXT_ADV_PROP_INCLUDE_TX_PWR Include TxPower in the extended header of the advertising PDU - ESP_BLE_GAP_SET_EXT_ADV_PROP_MASK Reserved for future use If extended advertising PDU types are being used (bit 4 = 0) then: The advertisement shall not be both connectable and scannable. High duty cycle directed connectable advertising (<= 3.75 ms advertising interval) shall not be used (bit 3 = 0) ADV_IND - ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_IND ADV_DIRECT_IND (low duty cycle) - ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_LD_DIR ADV_DIRECT_IND (high duty cycle) - ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_HD_DIR ADV_SCAN_IND - ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_SCAN ADV_NONCONN_IND - ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_NONCONN - ESP_BLE_GAP_PHY_1M Secondery Advertisement PHY is LE1M - ESP_BLE_GAP_PHY_2M Secondery Advertisement PHY is LE2M - ESP_BLE_GAP_PHY_CODED Secondery Advertisement PHY is LE Coded - ESP_BLE_GAP_NO_PREFER_TRANSMIT_PHY No Prefer TX PHY supported by controller - ESP_BLE_GAP_NO_PREFER_RECEIVE_PHY No Prefer RX PHY supported by controller - ESP_BLE_GAP_PRI_PHY_1M Primary phy only support 1M and LE coded phy. Primary Phy is LE1M - ESP_BLE_GAP_PRI_PHY_CODED Primary Phy is LE CODED - ESP_BLE_GAP_PHY_1M_PREF_MASK The Host prefers use the LE1M transmitter or reciever PHY - ESP_BLE_GAP_PHY_2M_PREF_MASK The Host prefers use the LE2M transmitter or reciever PHY - ESP_BLE_GAP_PHY_CODED_PREF_MASK The Host prefers use the LE CODED transmitter or reciever PHY - ESP_BLE_GAP_PHY_OPTIONS_NO_PREF The Host has no preferred coding when transmitting on the LE Coded PHY - ESP_BLE_GAP_PHY_OPTIONS_PREF_S2_CODING The Host prefers that S=2 coding be used when transmitting on the LE Coded PHY - ESP_BLE_GAP_PHY_OPTIONS_PREF_S8_CODING The Host prefers that S=8 coding be used when transmitting on the LE Coded PHY - ESP_BLE_GAP_EXT_SCAN_CFG_UNCODE_MASK Scan Advertisements on the LE1M PHY - ESP_BLE_GAP_EXT_SCAN_CFG_CODE_MASK Scan advertisements on the LE coded PHY - ESP_BLE_GAP_EXT_ADV_DATA_COMPLETE Advertising data. extended advertising data compete - ESP_BLE_GAP_EXT_ADV_DATA_INCOMPLETE extended advertising data incomplete - ESP_BLE_GAP_EXT_ADV_DATA_TRUNCATED extended advertising data truncated mode - ESP_BLE_GAP_SYNC_POLICY_BY_ADV_INFO Advertising SYNC policy. sync policy by advertising info - ESP_BLE_GAP_SYNC_POLICY_BY_PERIODIC_LIST periodic advertising sync policy - ESP_BLE_ADV_REPORT_EXT_ADV_IND Advertising report. advertising report with extended advertising indication type - ESP_BLE_ADV_REPORT_EXT_SCAN_IND advertising report with extended scan indication type - ESP_BLE_ADV_REPORT_EXT_DIRECT_ADV advertising report with extended direct advertising indication type - ESP_BLE_ADV_REPORT_EXT_SCAN_RSP advertising report with extended scan response indication type Bluetooth 5.0, Vol 2, Part E, 7.7.65.13 - ESP_BLE_LEGACY_ADV_TYPE_IND advertising report with legacy advertising indication type - ESP_BLE_LEGACY_ADV_TYPE_DIRECT_IND advertising report with legacy direct indication type - ESP_BLE_LEGACY_ADV_TYPE_SCAN_IND advertising report with legacy scan indication type - ESP_BLE_LEGACY_ADV_TYPE_NONCON_IND advertising report with legacy non connectable indication type - ESP_BLE_LEGACY_ADV_TYPE_SCAN_RSP_TO_ADV_IND advertising report with legacy scan response indication type - ESP_BLE_LEGACY_ADV_TYPE_SCAN_RSP_TO_ADV_SCAN_IND advertising report with legacy advertising with scan response indication type - EXT_ADV_TX_PWR_NO_PREFERENCE Extend advertising tx power, range: [-127, +126] dBm. host has no preference for tx power - ESP_BLE_GAP_PAST_MODE_NO_SYNC_EVT Periodic advertising sync trans mode. No attempt is made to sync and no periodic adv sync transfer received event - ESP_BLE_GAP_PAST_MODE_NO_REPORT_EVT An periodic adv sync transfer received event and no periodic adv report events - ESP_BLE_GAP_PAST_MODE_DUP_FILTER_DISABLED Periodic adv report events will be enabled with duplicate filtering disabled - ESP_BLE_GAP_PAST_MODE_DUP_FILTER_ENABLED Periodic adv report events will be enabled with duplicate filtering enabled Type Definitions - typedef uint8_t esp_ble_key_type_t - typedef uint8_t esp_ble_auth_req_t combination of the above bit pattern - typedef uint8_t esp_ble_io_cap_t combination of the io capability - typedef uint8_t esp_ble_dtm_pkt_payload_t - typedef uint8_t esp_gap_ble_channels[ESP_GAP_BLE_CHANNELS_LEN] - typedef uint8_t esp_duplicate_info_t[ESP_BD_ADDR_LEN] - typedef uint16_t esp_ble_ext_adv_type_mask_t - typedef uint8_t esp_ble_gap_phy_t - typedef uint8_t esp_ble_gap_all_phys_t - typedef uint8_t esp_ble_gap_pri_phy_t - typedef uint8_t esp_ble_gap_phy_mask_t - typedef uint16_t esp_ble_gap_prefer_phy_options_t - typedef uint8_t esp_ble_ext_scan_cfg_mask_t - typedef uint8_t esp_ble_gap_ext_adv_data_status_t - typedef uint8_t esp_ble_gap_sync_t - typedef uint8_t esp_ble_gap_adv_type_t - typedef uint8_t esp_ble_gap_past_mode_t - typedef void (*esp_gap_ble_cb_t)(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) GAP callback function type. - Param event : Event type - Param param : Point to callback parameter, currently is union type Enumerations - enum esp_gap_ble_cb_event_t GAP BLE callback event type. Values: - enumerator ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT When advertising data set complete, the event comes - enumerator ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT When scan response data set complete, the event comes - enumerator ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT When scan parameters set complete, the event comes - enumerator ESP_GAP_BLE_SCAN_RESULT_EVT When one scan result ready, the event comes each time - enumerator ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT When raw advertising data set complete, the event comes - enumerator ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT When raw scan response data set complete, the event comes - enumerator ESP_GAP_BLE_ADV_START_COMPLETE_EVT When start advertising complete, the event comes - enumerator ESP_GAP_BLE_SCAN_START_COMPLETE_EVT When start scan complete, the event comes - enumerator ESP_GAP_BLE_AUTH_CMPL_EVT Authentication complete indication. - enumerator ESP_GAP_BLE_KEY_EVT BLE key event for peer device keys - enumerator ESP_GAP_BLE_SEC_REQ_EVT BLE security request - enumerator ESP_GAP_BLE_PASSKEY_NOTIF_EVT passkey notification event - enumerator ESP_GAP_BLE_PASSKEY_REQ_EVT passkey request event - enumerator ESP_GAP_BLE_OOB_REQ_EVT OOB request event - enumerator ESP_GAP_BLE_LOCAL_IR_EVT BLE local IR (identity Root 128-bit random static value used to generate Long Term Key) event - enumerator ESP_GAP_BLE_LOCAL_ER_EVT BLE local ER (Encryption Root vakue used to genrate identity resolving key) event - enumerator ESP_GAP_BLE_NC_REQ_EVT Numeric Comparison request event - enumerator ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT When stop adv complete, the event comes - enumerator ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT When stop scan complete, the event comes - enumerator ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT When set the static rand address complete, the event comes - enumerator ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT When update connection parameters complete, the event comes - enumerator ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT When set pkt length complete, the event comes - enumerator ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT When Enable/disable privacy on the local device complete, the event comes - enumerator ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT When remove the bond device complete, the event comes - enumerator ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT When clear the bond device clear complete, the event comes - enumerator ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT When get the bond device list complete, the event comes - enumerator ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT When read the rssi complete, the event comes - enumerator ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT When add or remove whitelist complete, the event comes - enumerator ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT When update duplicate exceptional list complete, the event comes - enumerator ESP_GAP_BLE_SET_CHANNELS_EVT When setting BLE channels complete, the event comes - enumerator ESP_GAP_BLE_READ_PHY_COMPLETE_EVT when reading phy complete, this event comes - enumerator ESP_GAP_BLE_SET_PREFERRED_DEFAULT_PHY_COMPLETE_EVT when preferred default phy complete, this event comes - enumerator ESP_GAP_BLE_SET_PREFERRED_PHY_COMPLETE_EVT when preferred phy complete , this event comes - enumerator ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT when extended set random address complete, the event comes - enumerator ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT when extended advertising parameter complete, the event comes - enumerator ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT when extended advertising data complete, the event comes - enumerator ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT when extended scan response data complete, the event comes - enumerator ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT when extended advertising start complete, the event comes - enumerator ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT when extended advertising stop complete, the event comes - enumerator ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT when extended advertising set remove complete, the event comes - enumerator ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT when extended advertising set clear complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT when periodic advertising parameter complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT when periodic advertising data complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT when periodic advertising start complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT when periodic advertising stop complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT when periodic advertising create sync complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT when extended advertising sync cancel complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT when extended advertising sync terminate complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT when extended advertising add device complete , the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT when extended advertising remove device complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT when extended advertising clear device, the event comes - enumerator ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT when extended scan parameter complete, the event comes - enumerator ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT when extended scan start complete, the event comes - enumerator ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT when extended scan stop complete, the event comes - enumerator ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT when extended prefer connection parameter set complete, the event comes - enumerator ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT when ble phy update complete, the event comes - enumerator ESP_GAP_BLE_EXT_ADV_REPORT_EVT when extended advertising report complete, the event comes - enumerator ESP_GAP_BLE_SCAN_TIMEOUT_EVT when scan timeout complete, the event comes - enumerator ESP_GAP_BLE_ADV_TERMINATED_EVT when advertising terminate data complete, the event comes - enumerator ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT when scan req received complete, the event comes - enumerator ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT when channel select algorithm complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT when periodic report advertising complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT when periodic advertising sync lost complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT when periodic advertising sync establish complete, the event comes - enumerator ESP_GAP_BLE_SC_OOB_REQ_EVT Secure Connection OOB request event - enumerator ESP_GAP_BLE_SC_CR_LOC_OOB_EVT Secure Connection create OOB data complete event - enumerator ESP_GAP_BLE_GET_DEV_NAME_COMPLETE_EVT When getting BT device name complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_RECV_ENABLE_COMPLETE_EVT when set periodic advertising receive enable complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_COMPLETE_EVT when periodic advertising sync transfer complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_SET_INFO_TRANS_COMPLETE_EVT when periodic advertising set info transfer complete, the event comes - enumerator ESP_GAP_BLE_SET_PAST_PARAMS_COMPLETE_EVT when set periodic advertising sync transfer params complete, the event comes - enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_RECV_EVT when periodic advertising sync transfer received, the event comes - enumerator ESP_GAP_BLE_DTM_TEST_UPDATE_EVT when direct test mode state changes, the event comes - enumerator ESP_GAP_BLE_ADV_CLEAR_COMPLETE_EVT When clear advertising complete, the event comes - enumerator ESP_GAP_BLE_EVT_MAX when maximum advertising event complete, the event comes - enumerator ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT - enum esp_ble_adv_data_type The type of advertising data(not adv_type) Values: - enumerator ESP_BLE_AD_TYPE_FLAG - enumerator ESP_BLE_AD_TYPE_16SRV_PART - enumerator ESP_BLE_AD_TYPE_16SRV_CMPL - enumerator ESP_BLE_AD_TYPE_32SRV_PART - enumerator ESP_BLE_AD_TYPE_32SRV_CMPL - enumerator ESP_BLE_AD_TYPE_128SRV_PART - enumerator ESP_BLE_AD_TYPE_128SRV_CMPL - enumerator ESP_BLE_AD_TYPE_NAME_SHORT - enumerator ESP_BLE_AD_TYPE_NAME_CMPL - enumerator ESP_BLE_AD_TYPE_TX_PWR - enumerator ESP_BLE_AD_TYPE_DEV_CLASS - enumerator ESP_BLE_AD_TYPE_SM_TK - enumerator ESP_BLE_AD_TYPE_SM_OOB_FLAG - enumerator ESP_BLE_AD_TYPE_INT_RANGE - enumerator ESP_BLE_AD_TYPE_SOL_SRV_UUID - enumerator ESP_BLE_AD_TYPE_128SOL_SRV_UUID - enumerator ESP_BLE_AD_TYPE_SERVICE_DATA - enumerator ESP_BLE_AD_TYPE_PUBLIC_TARGET - enumerator ESP_BLE_AD_TYPE_RANDOM_TARGET - enumerator ESP_BLE_AD_TYPE_APPEARANCE - enumerator ESP_BLE_AD_TYPE_ADV_INT - enumerator ESP_BLE_AD_TYPE_LE_DEV_ADDR - enumerator ESP_BLE_AD_TYPE_LE_ROLE - enumerator ESP_BLE_AD_TYPE_SPAIR_C256 - enumerator ESP_BLE_AD_TYPE_SPAIR_R256 - enumerator ESP_BLE_AD_TYPE_32SOL_SRV_UUID - enumerator ESP_BLE_AD_TYPE_32SERVICE_DATA - enumerator ESP_BLE_AD_TYPE_128SERVICE_DATA - enumerator ESP_BLE_AD_TYPE_LE_SECURE_CONFIRM - enumerator ESP_BLE_AD_TYPE_LE_SECURE_RANDOM - enumerator ESP_BLE_AD_TYPE_URI - enumerator ESP_BLE_AD_TYPE_INDOOR_POSITION - enumerator ESP_BLE_AD_TYPE_TRANS_DISC_DATA - enumerator ESP_BLE_AD_TYPE_LE_SUPPORT_FEATURE - enumerator ESP_BLE_AD_TYPE_CHAN_MAP_UPDATE - enumerator ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE - enumerator ESP_BLE_AD_TYPE_FLAG - enum esp_ble_adv_type_t Advertising mode. Values: - enumerator ADV_TYPE_IND - enumerator ADV_TYPE_DIRECT_IND_HIGH - enumerator ADV_TYPE_SCAN_IND - enumerator ADV_TYPE_NONCONN_IND - enumerator ADV_TYPE_DIRECT_IND_LOW - enumerator ADV_TYPE_IND - enum esp_ble_adv_channel_t Advertising channel mask. Values: - enumerator ADV_CHNL_37 - enumerator ADV_CHNL_38 - enumerator ADV_CHNL_39 - enumerator ADV_CHNL_ALL - enumerator ADV_CHNL_37 - enum esp_ble_adv_filter_t Values: - enumerator ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY Allow both scan and connection requests from anyone. - enumerator ADV_FILTER_ALLOW_SCAN_WLST_CON_ANY Allow both scan req from White List devices only and connection req from anyone. - enumerator ADV_FILTER_ALLOW_SCAN_ANY_CON_WLST Allow both scan req from anyone and connection req from White List devices only. - enumerator ADV_FILTER_ALLOW_SCAN_WLST_CON_WLST Allow scan and connection requests from White List devices only. - enumerator ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY - enum esp_ble_sec_act_t Values: - enumerator ESP_BLE_SEC_ENCRYPT relate to BTA_DM_BLE_SEC_ENCRYPT in bta/bta_api.h. If the device has already bonded, the stack will used Long Term Key (LTK) to encrypt with the remote device directly. Else if the device hasn't bonded, the stack will used the default authentication request used the esp_ble_gap_set_security_param function set by the user. - enumerator ESP_BLE_SEC_ENCRYPT_NO_MITM relate to BTA_DM_BLE_SEC_ENCRYPT_NO_MITM in bta/bta_api.h. If the device has been already bonded, the stack will check the LTK (Long Term Key) Whether the authentication request has been met, and if met, use the LTK to encrypt with the remote device directly, else re-pair with the remote device. Else if the device hasn't been bonded, the stack will use NO MITM authentication request in the current link instead of using the authreq in the esp_ble_gap_set_security_param function set by the user. - enumerator ESP_BLE_SEC_ENCRYPT_MITM relate to BTA_DM_BLE_SEC_ENCRYPT_MITM in bta/bta_api.h. If the device has been already bonded, the stack will check the LTK (Long Term Key) whether the authentication request has been met, and if met, use the LTK to encrypt with the remote device directly, else re-pair with the remote device. Else if the device hasn't been bonded, the stack will use MITM authentication request in the current link instead of using the authreq in the esp_ble_gap_set_security_param function set by the user. - enumerator ESP_BLE_SEC_ENCRYPT - enum esp_ble_sm_param_t Values: - enumerator ESP_BLE_SM_PASSKEY Authentication requirements of local device - enumerator ESP_BLE_SM_AUTHEN_REQ_MODE The IO capability of local device - enumerator ESP_BLE_SM_IOCAP_MODE Initiator Key Distribution/Generation - enumerator ESP_BLE_SM_SET_INIT_KEY Responder Key Distribution/Generation - enumerator ESP_BLE_SM_SET_RSP_KEY Maximum Encryption key size to support - enumerator ESP_BLE_SM_MAX_KEY_SIZE Minimum Encryption key size requirement from Peer - enumerator ESP_BLE_SM_MIN_KEY_SIZE Set static Passkey - enumerator ESP_BLE_SM_SET_STATIC_PASSKEY Reset static Passkey - enumerator ESP_BLE_SM_CLEAR_STATIC_PASSKEY Accept only specified SMP Authentication requirement - enumerator ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH Enable/Disable OOB support - enumerator ESP_BLE_SM_OOB_SUPPORT Appl encryption key size - enumerator ESP_BLE_APP_ENC_KEY_SIZE authentication max param - enumerator ESP_BLE_SM_MAX_PARAM - enumerator ESP_BLE_SM_PASSKEY - enum esp_ble_dtm_update_evt_t Values: - enumerator DTM_TX_START_EVT DTM TX start event. - enumerator DTM_RX_START_EVT DTM RX start event. - enumerator DTM_TEST_STOP_EVT DTM test end event. - enumerator DTM_TX_START_EVT - enum esp_ble_scan_type_t Ble scan type. Values: - enumerator BLE_SCAN_TYPE_PASSIVE Passive scan - enumerator BLE_SCAN_TYPE_ACTIVE Active scan - enumerator BLE_SCAN_TYPE_PASSIVE - enum esp_ble_scan_filter_t Ble scan filter type. Values: - enumerator BLE_SCAN_FILTER_ALLOW_ALL Accept all : advertisement packets except directed advertising packets not addressed to this device (default). - - enumerator BLE_SCAN_FILTER_ALLOW_ONLY_WLST Accept only : advertisement packets from devices where the advertiser’s address is in the White list. Directed advertising packets which are not addressed for this device shall be ignored. - - enumerator BLE_SCAN_FILTER_ALLOW_UND_RPA_DIR Accept all : undirected advertisement packets, and directed advertising packets where the initiator address is a resolvable private address, and directed advertising packets addressed to this device. - - enumerator BLE_SCAN_FILTER_ALLOW_WLIST_RPA_DIR Accept all : advertisement packets from devices where the advertiser’s address is in the White list, and directed advertising packets where the initiator address is a resolvable private address, and directed advertising packets addressed to this device. - - enumerator BLE_SCAN_FILTER_ALLOW_ALL - enum esp_ble_scan_duplicate_t Ble scan duplicate type. Values: - enumerator BLE_SCAN_DUPLICATE_DISABLE the Link Layer should generate advertising reports to the host for each packet received - enumerator BLE_SCAN_DUPLICATE_ENABLE the Link Layer should filter out duplicate advertising reports to the Host - enumerator BLE_SCAN_DUPLICATE_ENABLE_RESET Duplicate filtering enabled, reset for each scan period, only supported in BLE 5.0. - enumerator BLE_SCAN_DUPLICATE_MAX Reserved for future use. - enumerator BLE_SCAN_DUPLICATE_DISABLE - enum esp_gap_search_evt_t Sub Event of ESP_GAP_BLE_SCAN_RESULT_EVT. Values: - enumerator ESP_GAP_SEARCH_INQ_RES_EVT Inquiry result for a peer device. - enumerator ESP_GAP_SEARCH_INQ_CMPL_EVT Inquiry complete. - enumerator ESP_GAP_SEARCH_DISC_RES_EVT Discovery result for a peer device. - enumerator ESP_GAP_SEARCH_DISC_BLE_RES_EVT Discovery result for BLE GATT based service on a peer device. - enumerator ESP_GAP_SEARCH_DISC_CMPL_EVT Discovery complete. - enumerator ESP_GAP_SEARCH_DI_DISC_CMPL_EVT Discovery complete. - enumerator ESP_GAP_SEARCH_SEARCH_CANCEL_CMPL_EVT Search cancelled - enumerator ESP_GAP_SEARCH_INQ_DISCARD_NUM_EVT The number of pkt discarded by flow control - enumerator ESP_GAP_SEARCH_INQ_RES_EVT - enum esp_ble_evt_type_t Ble scan result event type, to indicate the result is scan response or advertising data or other. Values: - enumerator ESP_BLE_EVT_CONN_ADV Connectable undirected advertising (ADV_IND) - enumerator ESP_BLE_EVT_CONN_DIR_ADV Connectable directed advertising (ADV_DIRECT_IND) - enumerator ESP_BLE_EVT_DISC_ADV Scannable undirected advertising (ADV_SCAN_IND) - enumerator ESP_BLE_EVT_NON_CONN_ADV Non connectable undirected advertising (ADV_NONCONN_IND) - enumerator ESP_BLE_EVT_SCAN_RSP Scan Response (SCAN_RSP) - enumerator ESP_BLE_EVT_CONN_ADV - enum esp_ble_wl_operation_t Values: - enumerator ESP_BLE_WHITELIST_REMOVE remove mac from whitelist - enumerator ESP_BLE_WHITELIST_ADD add address to whitelist - enumerator ESP_BLE_WHITELIST_CLEAR clear all device in whitelist - enumerator ESP_BLE_WHITELIST_REMOVE - enum esp_bt_duplicate_exceptional_subcode_type_t Values: - enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_ADD Add device info into duplicate scan exceptional list - enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_REMOVE Remove device info from duplicate scan exceptional list - enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_CLEAN Clean duplicate scan exceptional list - enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_ADD - enum esp_ble_duplicate_exceptional_info_type_t Values: - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_ADV_ADDR BLE advertising address , device info will be added into ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ADDR_LIST - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_LINK_ID BLE mesh link ID, it is for BLE mesh, device info will be added into ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_LINK_ID_LIST - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_BEACON_TYPE BLE mesh beacon AD type, the format is | Len | 0x2B | Beacon Type | Beacon Data | - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROV_SRV_ADV BLE mesh provisioning service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x1827 | .... |` - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROXY_SRV_ADV BLE mesh adv with proxy service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x1828 | .... |` - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROXY_SOLIC_ADV BLE mesh adv with proxy service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x1859 | .... |` - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_URI_ADV BLE mesh URI adv, the format is ...| Len | 0x24 | data |... - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_ADV_ADDR - enum esp_duplicate_scan_exceptional_list_type_t Values: - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ADDR_LIST duplicate scan exceptional addr list - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_LINK_ID_LIST duplicate scan exceptional mesh link ID list - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_BEACON_TYPE_LIST duplicate scan exceptional mesh beacon type list - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROV_SRV_ADV_LIST duplicate scan exceptional mesh adv with provisioning service uuid - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROXY_SRV_ADV_LIST duplicate scan exceptional mesh adv with proxy service uuid - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROXY_SOLIC_ADV_LIST duplicate scan exceptional mesh adv with proxy solicitation PDU uuid - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_URI_ADV_LIST duplicate scan exceptional URI list - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ALL_LIST duplicate scan exceptional all list - enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ADDR_LIST
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_gap_ble.html
ESP-IDF Programming Guide v5.2.1 documentation
null
GATT Defines
null
espressif.com
2016-01-01
758f3be2c2aa841
null
null
GATT Defines API Reference Header File components/bt/host/bluedroid/api/include/api/esp_gatt_defs.h This header file can be included with: #include "esp_gatt_defs.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Unions union esp_gatt_rsp_t #include <esp_gatt_defs.h> GATT remote read request response type. Public Members esp_gatt_value_t attr_value Gatt attribute structure esp_gatt_value_t attr_value Gatt attribute structure uint16_t handle Gatt attribute handle uint16_t handle Gatt attribute handle esp_gatt_value_t attr_value Structures struct esp_gatt_id_t Gatt id, include uuid and instance id. Public Members esp_bt_uuid_t uuid UUID esp_bt_uuid_t uuid UUID uint8_t inst_id Instance id uint8_t inst_id Instance id esp_bt_uuid_t uuid struct esp_gatt_srvc_id_t Gatt service id, include id (uuid and instance id) and primary flag. Public Members esp_gatt_id_t id Gatt id, include uuid and instance esp_gatt_id_t id Gatt id, include uuid and instance bool is_primary This service is primary or not bool is_primary This service is primary or not esp_gatt_id_t id struct esp_attr_desc_t Attribute description (used to create database) struct esp_attr_control_t attribute auto response flag Public Members uint8_t auto_rsp if auto_rsp set to ESP_GATT_RSP_BY_APP, means the response of Write/Read operation will by replied by application. if auto_rsp set to ESP_GATT_AUTO_RSP, means the response of Write/Read operation will be replied by GATT stack automatically. uint8_t auto_rsp if auto_rsp set to ESP_GATT_RSP_BY_APP, means the response of Write/Read operation will by replied by application. if auto_rsp set to ESP_GATT_AUTO_RSP, means the response of Write/Read operation will be replied by GATT stack automatically. uint8_t auto_rsp struct esp_gatts_attr_db_t attribute type added to the gatt server database Public Members esp_attr_control_t attr_control The attribute control type esp_attr_control_t attr_control The attribute control type esp_attr_desc_t att_desc The attribute type esp_attr_desc_t att_desc The attribute type esp_attr_control_t attr_control struct esp_attr_value_t set the attribute value type struct esp_gatts_incl_svc_desc_t Gatt include service entry element. struct esp_gatts_incl128_svc_desc_t Gatt include 128 bit service entry element. struct esp_gatt_value_t Gatt attribute value. struct esp_gatt_conn_params_t Connection parameters information. Public Members uint16_t interval connection interval uint16_t interval connection interval uint16_t latency Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 uint16_t latency Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 uint16_t timeout Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec Time Range: 100 msec to 32 seconds uint16_t timeout Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec Time Range: 100 msec to 32 seconds uint16_t interval struct esp_gattc_multi_t read multiple attribute struct esp_gattc_db_elem_t data base attribute element Public Members esp_gatt_db_attr_type_t type The attribute type esp_gatt_db_attr_type_t type The attribute type uint16_t attribute_handle The attribute handle, it's valid for all of the type uint16_t attribute_handle The attribute handle, it's valid for all of the type uint16_t start_handle The service start handle, it's valid only when the type = ESP_GATT_DB_PRIMARY_SERVICE or ESP_GATT_DB_SECONDARY_SERVICE uint16_t start_handle The service start handle, it's valid only when the type = ESP_GATT_DB_PRIMARY_SERVICE or ESP_GATT_DB_SECONDARY_SERVICE uint16_t end_handle The service end handle, it's valid only when the type = ESP_GATT_DB_PRIMARY_SERVICE or ESP_GATT_DB_SECONDARY_SERVICE uint16_t end_handle The service end handle, it's valid only when the type = ESP_GATT_DB_PRIMARY_SERVICE or ESP_GATT_DB_SECONDARY_SERVICE esp_gatt_char_prop_t properties The characteristic properties, it's valid only when the type = ESP_GATT_DB_CHARACTERISTIC esp_gatt_char_prop_t properties The characteristic properties, it's valid only when the type = ESP_GATT_DB_CHARACTERISTIC esp_bt_uuid_t uuid The attribute uuid, it's valid for all of the type esp_bt_uuid_t uuid The attribute uuid, it's valid for all of the type esp_gatt_db_attr_type_t type struct esp_gattc_service_elem_t service element Public Members bool is_primary The service flag, true if the service is primary service, else is secondary service bool is_primary The service flag, true if the service is primary service, else is secondary service uint16_t start_handle The start handle of the service uint16_t start_handle The start handle of the service uint16_t end_handle The end handle of the service uint16_t end_handle The end handle of the service esp_bt_uuid_t uuid The uuid of the service esp_bt_uuid_t uuid The uuid of the service bool is_primary struct esp_gattc_char_elem_t characteristic element Public Members uint16_t char_handle The characteristic handle uint16_t char_handle The characteristic handle esp_gatt_char_prop_t properties The characteristic properties esp_gatt_char_prop_t properties The characteristic properties esp_bt_uuid_t uuid The characteristic uuid esp_bt_uuid_t uuid The characteristic uuid uint16_t char_handle struct esp_gattc_descr_elem_t descriptor element Public Members uint16_t handle The characteristic descriptor handle uint16_t handle The characteristic descriptor handle esp_bt_uuid_t uuid The characteristic descriptor uuid esp_bt_uuid_t uuid The characteristic descriptor uuid uint16_t handle struct esp_gattc_incl_svc_elem_t include service element Public Members uint16_t handle The include service current attribute handle uint16_t handle The include service current attribute handle uint16_t incl_srvc_s_handle The start handle of the service which has been included uint16_t incl_srvc_s_handle The start handle of the service which has been included uint16_t incl_srvc_e_handle The end handle of the service which has been included uint16_t incl_srvc_e_handle The end handle of the service which has been included esp_bt_uuid_t uuid The include service uuid esp_bt_uuid_t uuid The include service uuid uint16_t handle Macros ESP_GATT_UUID_IMMEDIATE_ALERT_SVC All "ESP_GATT_UUID_xxx" is attribute types ESP_GATT_UUID_LINK_LOSS_SVC ESP_GATT_UUID_TX_POWER_SVC ESP_GATT_UUID_CURRENT_TIME_SVC ESP_GATT_UUID_REF_TIME_UPDATE_SVC ESP_GATT_UUID_NEXT_DST_CHANGE_SVC ESP_GATT_UUID_GLUCOSE_SVC ESP_GATT_UUID_HEALTH_THERMOM_SVC ESP_GATT_UUID_DEVICE_INFO_SVC ESP_GATT_UUID_HEART_RATE_SVC ESP_GATT_UUID_PHONE_ALERT_STATUS_SVC ESP_GATT_UUID_BATTERY_SERVICE_SVC ESP_GATT_UUID_BLOOD_PRESSURE_SVC ESP_GATT_UUID_ALERT_NTF_SVC ESP_GATT_UUID_HID_SVC ESP_GATT_UUID_SCAN_PARAMETERS_SVC ESP_GATT_UUID_RUNNING_SPEED_CADENCE_SVC ESP_GATT_UUID_Automation_IO_SVC ESP_GATT_UUID_CYCLING_SPEED_CADENCE_SVC ESP_GATT_UUID_CYCLING_POWER_SVC ESP_GATT_UUID_LOCATION_AND_NAVIGATION_SVC ESP_GATT_UUID_ENVIRONMENTAL_SENSING_SVC ESP_GATT_UUID_BODY_COMPOSITION ESP_GATT_UUID_USER_DATA_SVC ESP_GATT_UUID_WEIGHT_SCALE_SVC ESP_GATT_UUID_BOND_MANAGEMENT_SVC ESP_GATT_UUID_CONT_GLUCOSE_MONITOR_SVC ESP_GATT_UUID_PRI_SERVICE ESP_GATT_UUID_SEC_SERVICE ESP_GATT_UUID_INCLUDE_SERVICE ESP_GATT_UUID_CHAR_DECLARE ESP_GATT_UUID_CHAR_EXT_PROP ESP_GATT_UUID_CHAR_DESCRIPTION ESP_GATT_UUID_CHAR_CLIENT_CONFIG ESP_GATT_UUID_CHAR_SRVR_CONFIG ESP_GATT_UUID_CHAR_PRESENT_FORMAT ESP_GATT_UUID_CHAR_AGG_FORMAT ESP_GATT_UUID_CHAR_VALID_RANGE ESP_GATT_UUID_EXT_RPT_REF_DESCR ESP_GATT_UUID_RPT_REF_DESCR ESP_GATT_UUID_NUM_DIGITALS_DESCR ESP_GATT_UUID_VALUE_TRIGGER_DESCR ESP_GATT_UUID_ENV_SENSING_CONFIG_DESCR ESP_GATT_UUID_ENV_SENSING_MEASUREMENT_DESCR ESP_GATT_UUID_ENV_SENSING_TRIGGER_DESCR ESP_GATT_UUID_TIME_TRIGGER_DESCR ESP_GATT_UUID_GAP_DEVICE_NAME ESP_GATT_UUID_GAP_ICON ESP_GATT_UUID_GAP_PREF_CONN_PARAM ESP_GATT_UUID_GAP_CENTRAL_ADDR_RESOL ESP_GATT_UUID_GATT_SRV_CHGD ESP_GATT_UUID_ALERT_LEVEL ESP_GATT_UUID_TX_POWER_LEVEL ESP_GATT_UUID_CURRENT_TIME ESP_GATT_UUID_LOCAL_TIME_INFO ESP_GATT_UUID_REF_TIME_INFO ESP_GATT_UUID_NW_STATUS ESP_GATT_UUID_NW_TRIGGER ESP_GATT_UUID_ALERT_STATUS ESP_GATT_UUID_RINGER_CP ESP_GATT_UUID_RINGER_SETTING ESP_GATT_UUID_GM_MEASUREMENT ESP_GATT_UUID_GM_CONTEXT ESP_GATT_UUID_GM_CONTROL_POINT ESP_GATT_UUID_GM_FEATURE ESP_GATT_UUID_SYSTEM_ID ESP_GATT_UUID_MODEL_NUMBER_STR ESP_GATT_UUID_SERIAL_NUMBER_STR ESP_GATT_UUID_FW_VERSION_STR ESP_GATT_UUID_HW_VERSION_STR ESP_GATT_UUID_SW_VERSION_STR ESP_GATT_UUID_MANU_NAME ESP_GATT_UUID_IEEE_DATA ESP_GATT_UUID_PNP_ID ESP_GATT_UUID_HID_INFORMATION ESP_GATT_UUID_HID_REPORT_MAP ESP_GATT_UUID_HID_CONTROL_POINT ESP_GATT_UUID_HID_REPORT ESP_GATT_UUID_HID_PROTO_MODE ESP_GATT_UUID_HID_BT_KB_INPUT ESP_GATT_UUID_HID_BT_KB_OUTPUT ESP_GATT_UUID_HID_BT_MOUSE_INPUT ESP_GATT_HEART_RATE_MEAS Heart Rate Measurement. ESP_GATT_BODY_SENSOR_LOCATION Body Sensor Location. ESP_GATT_HEART_RATE_CNTL_POINT Heart Rate Control Point. ESP_GATT_UUID_BATTERY_LEVEL ESP_GATT_UUID_SC_CONTROL_POINT ESP_GATT_UUID_SENSOR_LOCATION ESP_GATT_UUID_RSC_MEASUREMENT ESP_GATT_UUID_RSC_FEATURE ESP_GATT_UUID_CSC_MEASUREMENT ESP_GATT_UUID_CSC_FEATURE ESP_GATT_UUID_SCAN_INT_WINDOW ESP_GATT_UUID_SCAN_REFRESH ESP_GATT_ILLEGAL_UUID GATT INVALID UUID. ESP_GATT_ILLEGAL_HANDLE GATT INVALID HANDLE. ESP_GATT_ATTR_HANDLE_MAX GATT attribute max handle. ESP_GATT_MAX_READ_MULTI_HANDLES ESP_GATT_PERM_READ Attribute permissions. ESP_GATT_PERM_READ_ENCRYPTED ESP_GATT_PERM_READ_ENC_MITM ESP_GATT_PERM_WRITE ESP_GATT_PERM_WRITE_ENCRYPTED ESP_GATT_PERM_WRITE_ENC_MITM ESP_GATT_PERM_WRITE_SIGNED ESP_GATT_PERM_WRITE_SIGNED_MITM ESP_GATT_PERM_READ_AUTHORIZATION ESP_GATT_PERM_WRITE_AUTHORIZATION ESP_GATT_PERM_ENCRYPT_KEY_SIZE(keysize) ESP_GATT_CHAR_PROP_BIT_BROADCAST ESP_GATT_CHAR_PROP_BIT_READ ESP_GATT_CHAR_PROP_BIT_WRITE_NR ESP_GATT_CHAR_PROP_BIT_WRITE ESP_GATT_CHAR_PROP_BIT_NOTIFY ESP_GATT_CHAR_PROP_BIT_INDICATE ESP_GATT_CHAR_PROP_BIT_AUTH ESP_GATT_CHAR_PROP_BIT_EXT_PROP ESP_GATT_MAX_ATTR_LEN GATT maximum attribute length. ESP_GATT_RSP_BY_APP ESP_GATT_AUTO_RSP ESP_GATT_IF_NONE If callback report gattc_if/gatts_if as this macro, means this event is not correspond to any app Type Definitions typedef uint16_t esp_gatt_perm_t typedef uint8_t esp_gatt_char_prop_t typedef uint8_t esp_gatt_if_t Gatt interface type, different application on GATT client use different gatt_if Enumerations enum esp_gatt_prep_write_type Attribute write data type from the client. Values: enumerator ESP_GATT_PREP_WRITE_CANCEL Prepare write cancel enumerator ESP_GATT_PREP_WRITE_CANCEL Prepare write cancel enumerator ESP_GATT_PREP_WRITE_EXEC Prepare write execute enumerator ESP_GATT_PREP_WRITE_EXEC Prepare write execute enumerator ESP_GATT_PREP_WRITE_CANCEL enum esp_gatt_status_t GATT success code and error codes. Values: enumerator ESP_GATT_OK enumerator ESP_GATT_OK enumerator ESP_GATT_INVALID_HANDLE enumerator ESP_GATT_INVALID_HANDLE enumerator ESP_GATT_READ_NOT_PERMIT enumerator ESP_GATT_READ_NOT_PERMIT enumerator ESP_GATT_WRITE_NOT_PERMIT enumerator ESP_GATT_WRITE_NOT_PERMIT enumerator ESP_GATT_INVALID_PDU enumerator ESP_GATT_INVALID_PDU enumerator ESP_GATT_INSUF_AUTHENTICATION enumerator ESP_GATT_INSUF_AUTHENTICATION enumerator ESP_GATT_REQ_NOT_SUPPORTED enumerator ESP_GATT_REQ_NOT_SUPPORTED enumerator ESP_GATT_INVALID_OFFSET enumerator ESP_GATT_INVALID_OFFSET enumerator ESP_GATT_INSUF_AUTHORIZATION enumerator ESP_GATT_INSUF_AUTHORIZATION enumerator ESP_GATT_PREPARE_Q_FULL enumerator ESP_GATT_PREPARE_Q_FULL enumerator ESP_GATT_NOT_FOUND enumerator ESP_GATT_NOT_FOUND enumerator ESP_GATT_NOT_LONG enumerator ESP_GATT_NOT_LONG enumerator ESP_GATT_INSUF_KEY_SIZE enumerator ESP_GATT_INSUF_KEY_SIZE enumerator ESP_GATT_INVALID_ATTR_LEN enumerator ESP_GATT_INVALID_ATTR_LEN enumerator ESP_GATT_ERR_UNLIKELY enumerator ESP_GATT_ERR_UNLIKELY enumerator ESP_GATT_INSUF_ENCRYPTION enumerator ESP_GATT_INSUF_ENCRYPTION enumerator ESP_GATT_UNSUPPORT_GRP_TYPE enumerator ESP_GATT_UNSUPPORT_GRP_TYPE enumerator ESP_GATT_INSUF_RESOURCE enumerator ESP_GATT_INSUF_RESOURCE enumerator ESP_GATT_NO_RESOURCES enumerator ESP_GATT_NO_RESOURCES enumerator ESP_GATT_INTERNAL_ERROR enumerator ESP_GATT_INTERNAL_ERROR enumerator ESP_GATT_WRONG_STATE enumerator ESP_GATT_WRONG_STATE enumerator ESP_GATT_DB_FULL enumerator ESP_GATT_DB_FULL enumerator ESP_GATT_BUSY enumerator ESP_GATT_BUSY enumerator ESP_GATT_ERROR enumerator ESP_GATT_ERROR enumerator ESP_GATT_CMD_STARTED enumerator ESP_GATT_CMD_STARTED enumerator ESP_GATT_ILLEGAL_PARAMETER enumerator ESP_GATT_ILLEGAL_PARAMETER enumerator ESP_GATT_PENDING enumerator ESP_GATT_PENDING enumerator ESP_GATT_AUTH_FAIL enumerator ESP_GATT_AUTH_FAIL enumerator ESP_GATT_MORE enumerator ESP_GATT_MORE enumerator ESP_GATT_INVALID_CFG enumerator ESP_GATT_INVALID_CFG enumerator ESP_GATT_SERVICE_STARTED enumerator ESP_GATT_SERVICE_STARTED enumerator ESP_GATT_ENCRYPTED_MITM enumerator ESP_GATT_ENCRYPTED_MITM enumerator ESP_GATT_ENCRYPTED_NO_MITM enumerator ESP_GATT_ENCRYPTED_NO_MITM enumerator ESP_GATT_NOT_ENCRYPTED enumerator ESP_GATT_NOT_ENCRYPTED enumerator ESP_GATT_CONGESTED enumerator ESP_GATT_CONGESTED enumerator ESP_GATT_DUP_REG enumerator ESP_GATT_DUP_REG enumerator ESP_GATT_ALREADY_OPEN enumerator ESP_GATT_ALREADY_OPEN enumerator ESP_GATT_CANCEL enumerator ESP_GATT_CANCEL enumerator ESP_GATT_STACK_RSP enumerator ESP_GATT_STACK_RSP enumerator ESP_GATT_APP_RSP enumerator ESP_GATT_APP_RSP enumerator ESP_GATT_UNKNOWN_ERROR enumerator ESP_GATT_UNKNOWN_ERROR enumerator ESP_GATT_CCC_CFG_ERR enumerator ESP_GATT_CCC_CFG_ERR enumerator ESP_GATT_PRC_IN_PROGRESS enumerator ESP_GATT_PRC_IN_PROGRESS enumerator ESP_GATT_OUT_OF_RANGE enumerator ESP_GATT_OUT_OF_RANGE enumerator ESP_GATT_OK enum esp_gatt_conn_reason_t Gatt Connection reason enum. Values: enumerator ESP_GATT_CONN_UNKNOWN Gatt connection unknown enumerator ESP_GATT_CONN_UNKNOWN Gatt connection unknown enumerator ESP_GATT_CONN_L2C_FAILURE General L2cap failure enumerator ESP_GATT_CONN_L2C_FAILURE General L2cap failure enumerator ESP_GATT_CONN_TIMEOUT Connection timeout enumerator ESP_GATT_CONN_TIMEOUT Connection timeout enumerator ESP_GATT_CONN_TERMINATE_PEER_USER Connection terminate by peer user enumerator ESP_GATT_CONN_TERMINATE_PEER_USER Connection terminate by peer user enumerator ESP_GATT_CONN_TERMINATE_LOCAL_HOST Connection terminated by local host enumerator ESP_GATT_CONN_TERMINATE_LOCAL_HOST Connection terminated by local host enumerator ESP_GATT_CONN_FAIL_ESTABLISH Connection fail to establish enumerator ESP_GATT_CONN_FAIL_ESTABLISH Connection fail to establish enumerator ESP_GATT_CONN_LMP_TIMEOUT Connection fail for LMP response tout enumerator ESP_GATT_CONN_LMP_TIMEOUT Connection fail for LMP response tout enumerator ESP_GATT_CONN_CONN_CANCEL L2CAP connection cancelled enumerator ESP_GATT_CONN_CONN_CANCEL L2CAP connection cancelled enumerator ESP_GATT_CONN_NONE No connection to cancel enumerator ESP_GATT_CONN_NONE No connection to cancel enumerator ESP_GATT_CONN_UNKNOWN enum esp_gatt_auth_req_t Gatt authentication request type. Values: enumerator ESP_GATT_AUTH_REQ_NONE enumerator ESP_GATT_AUTH_REQ_NONE enumerator ESP_GATT_AUTH_REQ_NO_MITM enumerator ESP_GATT_AUTH_REQ_NO_MITM enumerator ESP_GATT_AUTH_REQ_MITM enumerator ESP_GATT_AUTH_REQ_MITM enumerator ESP_GATT_AUTH_REQ_SIGNED_NO_MITM enumerator ESP_GATT_AUTH_REQ_SIGNED_NO_MITM enumerator ESP_GATT_AUTH_REQ_SIGNED_MITM enumerator ESP_GATT_AUTH_REQ_SIGNED_MITM enumerator ESP_GATT_AUTH_REQ_NONE enum esp_service_source_t Values: enumerator ESP_GATT_SERVICE_FROM_REMOTE_DEVICE enumerator ESP_GATT_SERVICE_FROM_REMOTE_DEVICE enumerator ESP_GATT_SERVICE_FROM_NVS_FLASH enumerator ESP_GATT_SERVICE_FROM_NVS_FLASH enumerator ESP_GATT_SERVICE_FROM_UNKNOWN enumerator ESP_GATT_SERVICE_FROM_UNKNOWN enumerator ESP_GATT_SERVICE_FROM_REMOTE_DEVICE enum esp_gatt_write_type_t Gatt write type. Values: enumerator ESP_GATT_WRITE_TYPE_NO_RSP Gatt write attribute need no response enumerator ESP_GATT_WRITE_TYPE_NO_RSP Gatt write attribute need no response enumerator ESP_GATT_WRITE_TYPE_RSP Gatt write attribute need remote response enumerator ESP_GATT_WRITE_TYPE_RSP Gatt write attribute need remote response enumerator ESP_GATT_WRITE_TYPE_NO_RSP enum esp_gatt_db_attr_type_t the type of attribute element Values: enumerator ESP_GATT_DB_PRIMARY_SERVICE Gattc primary service attribute type in the cache enumerator ESP_GATT_DB_PRIMARY_SERVICE Gattc primary service attribute type in the cache enumerator ESP_GATT_DB_SECONDARY_SERVICE Gattc secondary service attribute type in the cache enumerator ESP_GATT_DB_SECONDARY_SERVICE Gattc secondary service attribute type in the cache enumerator ESP_GATT_DB_CHARACTERISTIC Gattc characteristic attribute type in the cache enumerator ESP_GATT_DB_CHARACTERISTIC Gattc characteristic attribute type in the cache enumerator ESP_GATT_DB_DESCRIPTOR Gattc characteristic descriptor attribute type in the cache enumerator ESP_GATT_DB_DESCRIPTOR Gattc characteristic descriptor attribute type in the cache enumerator ESP_GATT_DB_INCLUDED_SERVICE Gattc include service attribute type in the cache enumerator ESP_GATT_DB_INCLUDED_SERVICE Gattc include service attribute type in the cache enumerator ESP_GATT_DB_ALL Gattc all the attribute (primary service & secondary service & include service & char & descriptor) type in the cache enumerator ESP_GATT_DB_ALL Gattc all the attribute (primary service & secondary service & include service & char & descriptor) type in the cache enumerator ESP_GATT_DB_PRIMARY_SERVICE
GATT Defines API Reference Header File components/bt/host/bluedroid/api/include/api/esp_gatt_defs.h This header file can be included with: #include "esp_gatt_defs.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Unions - union esp_gatt_rsp_t - #include <esp_gatt_defs.h> GATT remote read request response type. Public Members - esp_gatt_value_t attr_value Gatt attribute structure - uint16_t handle Gatt attribute handle - esp_gatt_value_t attr_value Structures - struct esp_gatt_id_t Gatt id, include uuid and instance id. Public Members - esp_bt_uuid_t uuid UUID - uint8_t inst_id Instance id - esp_bt_uuid_t uuid - struct esp_gatt_srvc_id_t Gatt service id, include id (uuid and instance id) and primary flag. Public Members - esp_gatt_id_t id Gatt id, include uuid and instance - bool is_primary This service is primary or not - esp_gatt_id_t id - struct esp_attr_desc_t Attribute description (used to create database) - struct esp_attr_control_t attribute auto response flag Public Members - uint8_t auto_rsp if auto_rsp set to ESP_GATT_RSP_BY_APP, means the response of Write/Read operation will by replied by application. if auto_rsp set to ESP_GATT_AUTO_RSP, means the response of Write/Read operation will be replied by GATT stack automatically. - uint8_t auto_rsp - struct esp_gatts_attr_db_t attribute type added to the gatt server database Public Members - esp_attr_control_t attr_control The attribute control type - esp_attr_desc_t att_desc The attribute type - esp_attr_control_t attr_control - struct esp_attr_value_t set the attribute value type - struct esp_gatts_incl_svc_desc_t Gatt include service entry element. - struct esp_gatts_incl128_svc_desc_t Gatt include 128 bit service entry element. - struct esp_gatt_value_t Gatt attribute value. - struct esp_gatt_conn_params_t Connection parameters information. Public Members - uint16_t interval connection interval - uint16_t latency Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 - uint16_t timeout Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec Time Range: 100 msec to 32 seconds - uint16_t interval - struct esp_gattc_multi_t read multiple attribute - struct esp_gattc_db_elem_t data base attribute element Public Members - esp_gatt_db_attr_type_t type The attribute type - uint16_t attribute_handle The attribute handle, it's valid for all of the type - uint16_t start_handle The service start handle, it's valid only when the type = ESP_GATT_DB_PRIMARY_SERVICE or ESP_GATT_DB_SECONDARY_SERVICE - uint16_t end_handle The service end handle, it's valid only when the type = ESP_GATT_DB_PRIMARY_SERVICE or ESP_GATT_DB_SECONDARY_SERVICE - esp_gatt_char_prop_t properties The characteristic properties, it's valid only when the type = ESP_GATT_DB_CHARACTERISTIC - esp_bt_uuid_t uuid The attribute uuid, it's valid for all of the type - esp_gatt_db_attr_type_t type - struct esp_gattc_service_elem_t service element Public Members - bool is_primary The service flag, true if the service is primary service, else is secondary service - uint16_t start_handle The start handle of the service - uint16_t end_handle The end handle of the service - esp_bt_uuid_t uuid The uuid of the service - bool is_primary - struct esp_gattc_char_elem_t characteristic element Public Members - uint16_t char_handle The characteristic handle - esp_gatt_char_prop_t properties The characteristic properties - esp_bt_uuid_t uuid The characteristic uuid - uint16_t char_handle - struct esp_gattc_descr_elem_t descriptor element Public Members - uint16_t handle The characteristic descriptor handle - esp_bt_uuid_t uuid The characteristic descriptor uuid - uint16_t handle - struct esp_gattc_incl_svc_elem_t include service element Public Members - uint16_t handle The include service current attribute handle - uint16_t incl_srvc_s_handle The start handle of the service which has been included - uint16_t incl_srvc_e_handle The end handle of the service which has been included - esp_bt_uuid_t uuid The include service uuid - uint16_t handle Macros - ESP_GATT_UUID_IMMEDIATE_ALERT_SVC All "ESP_GATT_UUID_xxx" is attribute types - ESP_GATT_UUID_LINK_LOSS_SVC - ESP_GATT_UUID_TX_POWER_SVC - ESP_GATT_UUID_CURRENT_TIME_SVC - ESP_GATT_UUID_REF_TIME_UPDATE_SVC - ESP_GATT_UUID_NEXT_DST_CHANGE_SVC - ESP_GATT_UUID_GLUCOSE_SVC - ESP_GATT_UUID_HEALTH_THERMOM_SVC - ESP_GATT_UUID_DEVICE_INFO_SVC - ESP_GATT_UUID_HEART_RATE_SVC - ESP_GATT_UUID_PHONE_ALERT_STATUS_SVC - ESP_GATT_UUID_BATTERY_SERVICE_SVC - ESP_GATT_UUID_BLOOD_PRESSURE_SVC - ESP_GATT_UUID_ALERT_NTF_SVC - ESP_GATT_UUID_HID_SVC - ESP_GATT_UUID_SCAN_PARAMETERS_SVC - ESP_GATT_UUID_RUNNING_SPEED_CADENCE_SVC - ESP_GATT_UUID_Automation_IO_SVC - ESP_GATT_UUID_CYCLING_SPEED_CADENCE_SVC - ESP_GATT_UUID_CYCLING_POWER_SVC - ESP_GATT_UUID_LOCATION_AND_NAVIGATION_SVC - ESP_GATT_UUID_ENVIRONMENTAL_SENSING_SVC - ESP_GATT_UUID_BODY_COMPOSITION - ESP_GATT_UUID_USER_DATA_SVC - ESP_GATT_UUID_WEIGHT_SCALE_SVC - ESP_GATT_UUID_BOND_MANAGEMENT_SVC - ESP_GATT_UUID_CONT_GLUCOSE_MONITOR_SVC - ESP_GATT_UUID_PRI_SERVICE - ESP_GATT_UUID_SEC_SERVICE - ESP_GATT_UUID_INCLUDE_SERVICE - ESP_GATT_UUID_CHAR_DECLARE - ESP_GATT_UUID_CHAR_EXT_PROP - ESP_GATT_UUID_CHAR_DESCRIPTION - ESP_GATT_UUID_CHAR_CLIENT_CONFIG - ESP_GATT_UUID_CHAR_SRVR_CONFIG - ESP_GATT_UUID_CHAR_PRESENT_FORMAT - ESP_GATT_UUID_CHAR_AGG_FORMAT - ESP_GATT_UUID_CHAR_VALID_RANGE - ESP_GATT_UUID_EXT_RPT_REF_DESCR - ESP_GATT_UUID_RPT_REF_DESCR - ESP_GATT_UUID_NUM_DIGITALS_DESCR - ESP_GATT_UUID_VALUE_TRIGGER_DESCR - ESP_GATT_UUID_ENV_SENSING_CONFIG_DESCR - ESP_GATT_UUID_ENV_SENSING_MEASUREMENT_DESCR - ESP_GATT_UUID_ENV_SENSING_TRIGGER_DESCR - ESP_GATT_UUID_TIME_TRIGGER_DESCR - ESP_GATT_UUID_GAP_DEVICE_NAME - ESP_GATT_UUID_GAP_ICON - ESP_GATT_UUID_GAP_PREF_CONN_PARAM - ESP_GATT_UUID_GAP_CENTRAL_ADDR_RESOL - ESP_GATT_UUID_GATT_SRV_CHGD - ESP_GATT_UUID_ALERT_LEVEL - ESP_GATT_UUID_TX_POWER_LEVEL - ESP_GATT_UUID_CURRENT_TIME - ESP_GATT_UUID_LOCAL_TIME_INFO - ESP_GATT_UUID_REF_TIME_INFO - ESP_GATT_UUID_NW_STATUS - ESP_GATT_UUID_NW_TRIGGER - ESP_GATT_UUID_ALERT_STATUS - ESP_GATT_UUID_RINGER_CP - ESP_GATT_UUID_RINGER_SETTING - ESP_GATT_UUID_GM_MEASUREMENT - ESP_GATT_UUID_GM_CONTEXT - ESP_GATT_UUID_GM_CONTROL_POINT - ESP_GATT_UUID_GM_FEATURE - ESP_GATT_UUID_SYSTEM_ID - ESP_GATT_UUID_MODEL_NUMBER_STR - ESP_GATT_UUID_SERIAL_NUMBER_STR - ESP_GATT_UUID_FW_VERSION_STR - ESP_GATT_UUID_HW_VERSION_STR - ESP_GATT_UUID_SW_VERSION_STR - ESP_GATT_UUID_MANU_NAME - ESP_GATT_UUID_IEEE_DATA - ESP_GATT_UUID_PNP_ID - ESP_GATT_UUID_HID_INFORMATION - ESP_GATT_UUID_HID_REPORT_MAP - ESP_GATT_UUID_HID_CONTROL_POINT - ESP_GATT_UUID_HID_REPORT - ESP_GATT_UUID_HID_PROTO_MODE - ESP_GATT_UUID_HID_BT_KB_INPUT - ESP_GATT_UUID_HID_BT_KB_OUTPUT - ESP_GATT_UUID_HID_BT_MOUSE_INPUT - ESP_GATT_HEART_RATE_MEAS Heart Rate Measurement. - ESP_GATT_BODY_SENSOR_LOCATION Body Sensor Location. - ESP_GATT_HEART_RATE_CNTL_POINT Heart Rate Control Point. - ESP_GATT_UUID_BATTERY_LEVEL - ESP_GATT_UUID_SC_CONTROL_POINT - ESP_GATT_UUID_SENSOR_LOCATION - ESP_GATT_UUID_RSC_MEASUREMENT - ESP_GATT_UUID_RSC_FEATURE - ESP_GATT_UUID_CSC_MEASUREMENT - ESP_GATT_UUID_CSC_FEATURE - ESP_GATT_UUID_SCAN_INT_WINDOW - ESP_GATT_UUID_SCAN_REFRESH - ESP_GATT_ILLEGAL_UUID GATT INVALID UUID. - ESP_GATT_ILLEGAL_HANDLE GATT INVALID HANDLE. - ESP_GATT_ATTR_HANDLE_MAX GATT attribute max handle. - ESP_GATT_MAX_READ_MULTI_HANDLES - ESP_GATT_PERM_READ Attribute permissions. - ESP_GATT_PERM_READ_ENCRYPTED - ESP_GATT_PERM_READ_ENC_MITM - ESP_GATT_PERM_WRITE - ESP_GATT_PERM_WRITE_ENCRYPTED - ESP_GATT_PERM_WRITE_ENC_MITM - ESP_GATT_PERM_WRITE_SIGNED - ESP_GATT_PERM_WRITE_SIGNED_MITM - ESP_GATT_PERM_READ_AUTHORIZATION - ESP_GATT_PERM_WRITE_AUTHORIZATION - ESP_GATT_PERM_ENCRYPT_KEY_SIZE(keysize) - ESP_GATT_CHAR_PROP_BIT_BROADCAST - ESP_GATT_CHAR_PROP_BIT_READ - ESP_GATT_CHAR_PROP_BIT_WRITE_NR - ESP_GATT_CHAR_PROP_BIT_WRITE - ESP_GATT_CHAR_PROP_BIT_NOTIFY - ESP_GATT_CHAR_PROP_BIT_INDICATE - ESP_GATT_CHAR_PROP_BIT_AUTH - ESP_GATT_CHAR_PROP_BIT_EXT_PROP - ESP_GATT_MAX_ATTR_LEN GATT maximum attribute length. - ESP_GATT_RSP_BY_APP - ESP_GATT_AUTO_RSP - ESP_GATT_IF_NONE If callback report gattc_if/gatts_if as this macro, means this event is not correspond to any app Type Definitions - typedef uint16_t esp_gatt_perm_t - typedef uint8_t esp_gatt_char_prop_t - typedef uint8_t esp_gatt_if_t Gatt interface type, different application on GATT client use different gatt_if Enumerations - enum esp_gatt_prep_write_type Attribute write data type from the client. Values: - enumerator ESP_GATT_PREP_WRITE_CANCEL Prepare write cancel - enumerator ESP_GATT_PREP_WRITE_EXEC Prepare write execute - enumerator ESP_GATT_PREP_WRITE_CANCEL - enum esp_gatt_status_t GATT success code and error codes. Values: - enumerator ESP_GATT_OK - enumerator ESP_GATT_INVALID_HANDLE - enumerator ESP_GATT_READ_NOT_PERMIT - enumerator ESP_GATT_WRITE_NOT_PERMIT - enumerator ESP_GATT_INVALID_PDU - enumerator ESP_GATT_INSUF_AUTHENTICATION - enumerator ESP_GATT_REQ_NOT_SUPPORTED - enumerator ESP_GATT_INVALID_OFFSET - enumerator ESP_GATT_INSUF_AUTHORIZATION - enumerator ESP_GATT_PREPARE_Q_FULL - enumerator ESP_GATT_NOT_FOUND - enumerator ESP_GATT_NOT_LONG - enumerator ESP_GATT_INSUF_KEY_SIZE - enumerator ESP_GATT_INVALID_ATTR_LEN - enumerator ESP_GATT_ERR_UNLIKELY - enumerator ESP_GATT_INSUF_ENCRYPTION - enumerator ESP_GATT_UNSUPPORT_GRP_TYPE - enumerator ESP_GATT_INSUF_RESOURCE - enumerator ESP_GATT_NO_RESOURCES - enumerator ESP_GATT_INTERNAL_ERROR - enumerator ESP_GATT_WRONG_STATE - enumerator ESP_GATT_DB_FULL - enumerator ESP_GATT_BUSY - enumerator ESP_GATT_ERROR - enumerator ESP_GATT_CMD_STARTED - enumerator ESP_GATT_ILLEGAL_PARAMETER - enumerator ESP_GATT_PENDING - enumerator ESP_GATT_AUTH_FAIL - enumerator ESP_GATT_MORE - enumerator ESP_GATT_INVALID_CFG - enumerator ESP_GATT_SERVICE_STARTED - enumerator ESP_GATT_ENCRYPTED_MITM - enumerator ESP_GATT_ENCRYPTED_NO_MITM - enumerator ESP_GATT_NOT_ENCRYPTED - enumerator ESP_GATT_CONGESTED - enumerator ESP_GATT_DUP_REG - enumerator ESP_GATT_ALREADY_OPEN - enumerator ESP_GATT_CANCEL - enumerator ESP_GATT_STACK_RSP - enumerator ESP_GATT_APP_RSP - enumerator ESP_GATT_UNKNOWN_ERROR - enumerator ESP_GATT_CCC_CFG_ERR - enumerator ESP_GATT_PRC_IN_PROGRESS - enumerator ESP_GATT_OUT_OF_RANGE - enumerator ESP_GATT_OK - enum esp_gatt_conn_reason_t Gatt Connection reason enum. Values: - enumerator ESP_GATT_CONN_UNKNOWN Gatt connection unknown - enumerator ESP_GATT_CONN_L2C_FAILURE General L2cap failure - enumerator ESP_GATT_CONN_TIMEOUT Connection timeout - enumerator ESP_GATT_CONN_TERMINATE_PEER_USER Connection terminate by peer user - enumerator ESP_GATT_CONN_TERMINATE_LOCAL_HOST Connection terminated by local host - enumerator ESP_GATT_CONN_FAIL_ESTABLISH Connection fail to establish - enumerator ESP_GATT_CONN_LMP_TIMEOUT Connection fail for LMP response tout - enumerator ESP_GATT_CONN_CONN_CANCEL L2CAP connection cancelled - enumerator ESP_GATT_CONN_NONE No connection to cancel - enumerator ESP_GATT_CONN_UNKNOWN - enum esp_gatt_auth_req_t Gatt authentication request type. Values: - enumerator ESP_GATT_AUTH_REQ_NONE - enumerator ESP_GATT_AUTH_REQ_NO_MITM - enumerator ESP_GATT_AUTH_REQ_MITM - enumerator ESP_GATT_AUTH_REQ_SIGNED_NO_MITM - enumerator ESP_GATT_AUTH_REQ_SIGNED_MITM - enumerator ESP_GATT_AUTH_REQ_NONE - enum esp_service_source_t Values: - enumerator ESP_GATT_SERVICE_FROM_REMOTE_DEVICE - enumerator ESP_GATT_SERVICE_FROM_NVS_FLASH - enumerator ESP_GATT_SERVICE_FROM_UNKNOWN - enumerator ESP_GATT_SERVICE_FROM_REMOTE_DEVICE - enum esp_gatt_write_type_t Gatt write type. Values: - enumerator ESP_GATT_WRITE_TYPE_NO_RSP Gatt write attribute need no response - enumerator ESP_GATT_WRITE_TYPE_RSP Gatt write attribute need remote response - enumerator ESP_GATT_WRITE_TYPE_NO_RSP - enum esp_gatt_db_attr_type_t the type of attribute element Values: - enumerator ESP_GATT_DB_PRIMARY_SERVICE Gattc primary service attribute type in the cache - enumerator ESP_GATT_DB_SECONDARY_SERVICE Gattc secondary service attribute type in the cache - enumerator ESP_GATT_DB_CHARACTERISTIC Gattc characteristic attribute type in the cache - enumerator ESP_GATT_DB_DESCRIPTOR Gattc characteristic descriptor attribute type in the cache - enumerator ESP_GATT_DB_INCLUDED_SERVICE Gattc include service attribute type in the cache - enumerator ESP_GATT_DB_ALL Gattc all the attribute (primary service & secondary service & include service & char & descriptor) type in the cache - enumerator ESP_GATT_DB_PRIMARY_SERVICE
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_gatt_defs.html
ESP-IDF Programming Guide v5.2.1 documentation
null
GATT Server API
null
espressif.com
2016-01-01
def83c57aa07b905
null
null
GATT Server API Application Examples Check bluetooth/bluedroid/ble folder in ESP-IDF examples, which contains the following demos and their tutorials: This is a GATT server demo and its tutorial. This demo creates a GATT service with an attribute table, which releases the user from the operation of adding attributes one by one. This is the recommended method of adding attributes (officially recommended). This is a GATT server demo and its tutorial. This demo creates a GATT service by adding attributes one by one as defined by Bluedroid. The recommended method of adding attributes is presented in the example below. This is a demo similar to Bluetooth® Low Energy (Bluetooth LE) SPP. In this demo, GATT server can receive data from UART and then send the data to the peer device automatically. API Reference Header File components/bt/host/bluedroid/api/include/api/esp_gatts_api.h This header file can be included with: #include "esp_gatts_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_gatts_register_callback(esp_gatts_cb_t callback) This function is called to register application callbacks with BTA GATTS module. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Returns ESP_OK : success other : failed esp_gatts_cb_t esp_ble_gatts_get_callback(void) This function is called to get the current application callbacks with BTA GATTS module. Returns esp_gatts_cb_t : current callback esp_gatts_cb_t : current callback esp_gatts_cb_t : current callback Returns esp_gatts_cb_t : current callback esp_err_t esp_ble_gatts_app_register(uint16_t app_id) This function is called to register application identifier. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Returns ESP_OK : success other : failed esp_err_t esp_ble_gatts_app_unregister(esp_gatt_if_t gatts_if) unregister with GATT Server. Parameters gatts_if -- [in] GATT server access interface Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters gatts_if -- [in] GATT server access interface Returns ESP_OK : success other : failed esp_err_t esp_ble_gatts_create_service(esp_gatt_if_t gatts_if, esp_gatt_srvc_id_t *service_id, uint16_t num_handle) Create a service. When service creation is done, a callback event ESP_GATTS_CREATE_EVT is called to report status and service ID to the profile. The service ID obtained in the callback function needs to be used when adding included service and characteristics/descriptors into the service. Parameters gatts_if -- [in] GATT server access interface service_id -- [in] service ID. num_handle -- [in] number of handle requested for this service. gatts_if -- [in] GATT server access interface service_id -- [in] service ID. num_handle -- [in] number of handle requested for this service. gatts_if -- [in] GATT server access interface Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters gatts_if -- [in] GATT server access interface service_id -- [in] service ID. num_handle -- [in] number of handle requested for this service. Returns ESP_OK : success other : failed esp_err_t esp_ble_gatts_create_attr_tab(const esp_gatts_attr_db_t *gatts_attr_db, esp_gatt_if_t gatts_if, uint16_t max_nb_attr, uint8_t srvc_inst_id) Create a service attribute tab. Parameters gatts_attr_db -- [in] the pointer to the service attr tab gatts_if -- [in] GATT server access interface max_nb_attr -- [in] the number of attribute to be added to the service database. srvc_inst_id -- [in] the instance id of the service gatts_attr_db -- [in] the pointer to the service attr tab gatts_if -- [in] GATT server access interface max_nb_attr -- [in] the number of attribute to be added to the service database. srvc_inst_id -- [in] the instance id of the service gatts_attr_db -- [in] the pointer to the service attr tab Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters gatts_attr_db -- [in] the pointer to the service attr tab gatts_if -- [in] GATT server access interface max_nb_attr -- [in] the number of attribute to be added to the service database. srvc_inst_id -- [in] the instance id of the service Returns ESP_OK : success other : failed esp_err_t esp_ble_gatts_add_included_service(uint16_t service_handle, uint16_t included_service_handle) This function is called to add an included service. This function have to be called between 'esp_ble_gatts_create_service' and 'esp_ble_gatts_add_char'. After included service is included, a callback event ESP_GATTS_ADD_INCL_SRVC_EVT is reported the included service ID. Parameters service_handle -- [in] service handle to which this included service is to be added. included_service_handle -- [in] the service ID to be included. service_handle -- [in] service handle to which this included service is to be added. included_service_handle -- [in] the service ID to be included. service_handle -- [in] service handle to which this included service is to be added. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters service_handle -- [in] service handle to which this included service is to be added. included_service_handle -- [in] the service ID to be included. Returns ESP_OK : success other : failed esp_err_t esp_ble_gatts_add_char(uint16_t service_handle, esp_bt_uuid_t *char_uuid, esp_gatt_perm_t perm, esp_gatt_char_prop_t property, esp_attr_value_t *char_val, esp_attr_control_t *control) This function is called to add a characteristic into a service. Parameters service_handle -- [in] service handle to which this included service is to be added. char_uuid -- [in] : Characteristic UUID. perm -- [in] : Characteristic value declaration attribute permission. property -- [in] : Characteristic Properties char_val -- [in] : Characteristic value control -- [in] : attribute response control byte service_handle -- [in] service handle to which this included service is to be added. char_uuid -- [in] : Characteristic UUID. perm -- [in] : Characteristic value declaration attribute permission. property -- [in] : Characteristic Properties char_val -- [in] : Characteristic value control -- [in] : attribute response control byte service_handle -- [in] service handle to which this included service is to be added. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters service_handle -- [in] service handle to which this included service is to be added. char_uuid -- [in] : Characteristic UUID. perm -- [in] : Characteristic value declaration attribute permission. property -- [in] : Characteristic Properties char_val -- [in] : Characteristic value control -- [in] : attribute response control byte Returns ESP_OK : success other : failed esp_err_t esp_ble_gatts_add_char_descr(uint16_t service_handle, esp_bt_uuid_t *descr_uuid, esp_gatt_perm_t perm, esp_attr_value_t *char_descr_val, esp_attr_control_t *control) This function is called to add characteristic descriptor. When it's done, a callback event ESP_GATTS_ADD_DESCR_EVT is called to report the status and an ID number for this descriptor. Parameters service_handle -- [in] service handle to which this characteristic descriptor is to be added. perm -- [in] descriptor access permission. descr_uuid -- [in] descriptor UUID. char_descr_val -- [in] : Characteristic descriptor value control -- [in] : attribute response control byte service_handle -- [in] service handle to which this characteristic descriptor is to be added. perm -- [in] descriptor access permission. descr_uuid -- [in] descriptor UUID. char_descr_val -- [in] : Characteristic descriptor value control -- [in] : attribute response control byte service_handle -- [in] service handle to which this characteristic descriptor is to be added. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters service_handle -- [in] service handle to which this characteristic descriptor is to be added. perm -- [in] descriptor access permission. descr_uuid -- [in] descriptor UUID. char_descr_val -- [in] : Characteristic descriptor value control -- [in] : attribute response control byte Returns ESP_OK : success other : failed esp_err_t esp_ble_gatts_delete_service(uint16_t service_handle) This function is called to delete a service. When this is done, a callback event ESP_GATTS_DELETE_EVT is report with the status. Parameters service_handle -- [in] service_handle to be deleted. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters service_handle -- [in] service_handle to be deleted. Returns ESP_OK : success other : failed esp_err_t esp_ble_gatts_start_service(uint16_t service_handle) This function is called to start a service. Parameters service_handle -- [in] the service handle to be started. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters service_handle -- [in] the service handle to be started. Returns ESP_OK : success other : failed esp_err_t esp_ble_gatts_stop_service(uint16_t service_handle) This function is called to stop a service. Parameters service_handle -- [in] - service to be topped. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters service_handle -- [in] - service to be topped. Returns ESP_OK : success other : failed esp_err_t esp_ble_gatts_send_indicate(esp_gatt_if_t gatts_if, uint16_t conn_id, uint16_t attr_handle, uint16_t value_len, uint8_t *value, bool need_confirm) Send indicate or notify to GATT client. Set param need_confirm as false will send notification, otherwise indication. Note: the size of indicate or notify data need less than MTU size,see "esp_ble_gattc_send_mtu_req". Parameters gatts_if -- [in] GATT server access interface conn_id -- [in] - connection id to indicate. attr_handle -- [in] - attribute handle to indicate. value_len -- [in] - indicate value length. value -- [in] value to indicate. need_confirm -- [in] - Whether a confirmation is required. false sends a GATT notification, true sends a GATT indication. gatts_if -- [in] GATT server access interface conn_id -- [in] - connection id to indicate. attr_handle -- [in] - attribute handle to indicate. value_len -- [in] - indicate value length. value -- [in] value to indicate. need_confirm -- [in] - Whether a confirmation is required. false sends a GATT notification, true sends a GATT indication. gatts_if -- [in] GATT server access interface Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters gatts_if -- [in] GATT server access interface conn_id -- [in] - connection id to indicate. attr_handle -- [in] - attribute handle to indicate. value_len -- [in] - indicate value length. value -- [in] value to indicate. need_confirm -- [in] - Whether a confirmation is required. false sends a GATT notification, true sends a GATT indication. Returns ESP_OK : success other : failed esp_err_t esp_ble_gatts_send_response(esp_gatt_if_t gatts_if, uint16_t conn_id, uint32_t trans_id, esp_gatt_status_t status, esp_gatt_rsp_t *rsp) This function is called to send a response to a request. Parameters gatts_if -- [in] GATT server access interface conn_id -- [in] - connection identifier. trans_id -- [in] - transfer id status -- [in] - response status rsp -- [in] - response data. gatts_if -- [in] GATT server access interface conn_id -- [in] - connection identifier. trans_id -- [in] - transfer id status -- [in] - response status rsp -- [in] - response data. gatts_if -- [in] GATT server access interface Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters gatts_if -- [in] GATT server access interface conn_id -- [in] - connection identifier. trans_id -- [in] - transfer id status -- [in] - response status rsp -- [in] - response data. Returns ESP_OK : success other : failed esp_err_t esp_ble_gatts_set_attr_value(uint16_t attr_handle, uint16_t length, const uint8_t *value) This function is called to set the attribute value by the application. Parameters attr_handle -- [in] the attribute handle which to be set length -- [in] the value length value -- [in] the pointer to the attribute value attr_handle -- [in] the attribute handle which to be set length -- [in] the value length value -- [in] the pointer to the attribute value attr_handle -- [in] the attribute handle which to be set Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters attr_handle -- [in] the attribute handle which to be set length -- [in] the value length value -- [in] the pointer to the attribute value Returns ESP_OK : success other : failed esp_gatt_status_t esp_ble_gatts_get_attr_value(uint16_t attr_handle, uint16_t *length, const uint8_t **value) Retrieve attribute value. Parameters attr_handle -- [in] Attribute handle. length -- [out] pointer to the attribute value length value -- [out] Pointer to attribute value payload, the value cannot be modified by user attr_handle -- [in] Attribute handle. length -- [out] pointer to the attribute value length value -- [out] Pointer to attribute value payload, the value cannot be modified by user attr_handle -- [in] Attribute handle. Returns ESP_GATT_OK : success other : failed ESP_GATT_OK : success other : failed ESP_GATT_OK : success Parameters attr_handle -- [in] Attribute handle. length -- [out] pointer to the attribute value length value -- [out] Pointer to attribute value payload, the value cannot be modified by user Returns ESP_GATT_OK : success other : failed esp_err_t esp_ble_gatts_open(esp_gatt_if_t gatts_if, esp_bd_addr_t remote_bda, bool is_direct) Open a direct open connection or add a background auto connection. Parameters gatts_if -- [in] GATT server access interface remote_bda -- [in] remote device bluetooth device address. is_direct -- [in] direct connection or background auto connection gatts_if -- [in] GATT server access interface remote_bda -- [in] remote device bluetooth device address. is_direct -- [in] direct connection or background auto connection gatts_if -- [in] GATT server access interface Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters gatts_if -- [in] GATT server access interface remote_bda -- [in] remote device bluetooth device address. is_direct -- [in] direct connection or background auto connection Returns ESP_OK : success other : failed esp_err_t esp_ble_gatts_close(esp_gatt_if_t gatts_if, uint16_t conn_id) Close a connection a remote device. Parameters gatts_if -- [in] GATT server access interface conn_id -- [in] connection ID to be closed. gatts_if -- [in] GATT server access interface conn_id -- [in] connection ID to be closed. gatts_if -- [in] GATT server access interface Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters gatts_if -- [in] GATT server access interface conn_id -- [in] connection ID to be closed. Returns ESP_OK : success other : failed esp_err_t esp_ble_gatts_send_service_change_indication(esp_gatt_if_t gatts_if, esp_bd_addr_t remote_bda) Send service change indication. Parameters gatts_if -- [in] GATT server access interface remote_bda -- [in] remote device bluetooth device address. If remote_bda is NULL then it will send service change indication to all the connected devices and if not then to a specific device gatts_if -- [in] GATT server access interface remote_bda -- [in] remote device bluetooth device address. If remote_bda is NULL then it will send service change indication to all the connected devices and if not then to a specific device gatts_if -- [in] GATT server access interface Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Parameters gatts_if -- [in] GATT server access interface remote_bda -- [in] remote device bluetooth device address. If remote_bda is NULL then it will send service change indication to all the connected devices and if not then to a specific device Returns ESP_OK : success other : failed Unions union esp_ble_gatts_cb_param_t #include <esp_gatts_api.h> Gatt server callback parameters union. Public Members struct esp_ble_gatts_cb_param_t::gatts_reg_evt_param reg Gatt server callback param of ESP_GATTS_REG_EVT struct esp_ble_gatts_cb_param_t::gatts_reg_evt_param reg Gatt server callback param of ESP_GATTS_REG_EVT struct esp_ble_gatts_cb_param_t::gatts_read_evt_param read Gatt server callback param of ESP_GATTS_READ_EVT struct esp_ble_gatts_cb_param_t::gatts_read_evt_param read Gatt server callback param of ESP_GATTS_READ_EVT struct esp_ble_gatts_cb_param_t::gatts_write_evt_param write Gatt server callback param of ESP_GATTS_WRITE_EVT struct esp_ble_gatts_cb_param_t::gatts_write_evt_param write Gatt server callback param of ESP_GATTS_WRITE_EVT struct esp_ble_gatts_cb_param_t::gatts_exec_write_evt_param exec_write Gatt server callback param of ESP_GATTS_EXEC_WRITE_EVT struct esp_ble_gatts_cb_param_t::gatts_exec_write_evt_param exec_write Gatt server callback param of ESP_GATTS_EXEC_WRITE_EVT struct esp_ble_gatts_cb_param_t::gatts_mtu_evt_param mtu Gatt server callback param of ESP_GATTS_MTU_EVT struct esp_ble_gatts_cb_param_t::gatts_mtu_evt_param mtu Gatt server callback param of ESP_GATTS_MTU_EVT struct esp_ble_gatts_cb_param_t::gatts_conf_evt_param conf Gatt server callback param of ESP_GATTS_CONF_EVT (confirm) struct esp_ble_gatts_cb_param_t::gatts_conf_evt_param conf Gatt server callback param of ESP_GATTS_CONF_EVT (confirm) struct esp_ble_gatts_cb_param_t::gatts_create_evt_param create Gatt server callback param of ESP_GATTS_CREATE_EVT struct esp_ble_gatts_cb_param_t::gatts_create_evt_param create Gatt server callback param of ESP_GATTS_CREATE_EVT struct esp_ble_gatts_cb_param_t::gatts_add_incl_srvc_evt_param add_incl_srvc Gatt server callback param of ESP_GATTS_ADD_INCL_SRVC_EVT struct esp_ble_gatts_cb_param_t::gatts_add_incl_srvc_evt_param add_incl_srvc Gatt server callback param of ESP_GATTS_ADD_INCL_SRVC_EVT struct esp_ble_gatts_cb_param_t::gatts_add_char_evt_param add_char Gatt server callback param of ESP_GATTS_ADD_CHAR_EVT struct esp_ble_gatts_cb_param_t::gatts_add_char_evt_param add_char Gatt server callback param of ESP_GATTS_ADD_CHAR_EVT struct esp_ble_gatts_cb_param_t::gatts_add_char_descr_evt_param add_char_descr Gatt server callback param of ESP_GATTS_ADD_CHAR_DESCR_EVT struct esp_ble_gatts_cb_param_t::gatts_add_char_descr_evt_param add_char_descr Gatt server callback param of ESP_GATTS_ADD_CHAR_DESCR_EVT struct esp_ble_gatts_cb_param_t::gatts_delete_evt_param del Gatt server callback param of ESP_GATTS_DELETE_EVT struct esp_ble_gatts_cb_param_t::gatts_delete_evt_param del Gatt server callback param of ESP_GATTS_DELETE_EVT struct esp_ble_gatts_cb_param_t::gatts_start_evt_param start Gatt server callback param of ESP_GATTS_START_EVT struct esp_ble_gatts_cb_param_t::gatts_start_evt_param start Gatt server callback param of ESP_GATTS_START_EVT struct esp_ble_gatts_cb_param_t::gatts_stop_evt_param stop Gatt server callback param of ESP_GATTS_STOP_EVT struct esp_ble_gatts_cb_param_t::gatts_stop_evt_param stop Gatt server callback param of ESP_GATTS_STOP_EVT struct esp_ble_gatts_cb_param_t::gatts_connect_evt_param connect Gatt server callback param of ESP_GATTS_CONNECT_EVT struct esp_ble_gatts_cb_param_t::gatts_connect_evt_param connect Gatt server callback param of ESP_GATTS_CONNECT_EVT struct esp_ble_gatts_cb_param_t::gatts_disconnect_evt_param disconnect Gatt server callback param of ESP_GATTS_DISCONNECT_EVT struct esp_ble_gatts_cb_param_t::gatts_disconnect_evt_param disconnect Gatt server callback param of ESP_GATTS_DISCONNECT_EVT struct esp_ble_gatts_cb_param_t::gatts_open_evt_param open Gatt server callback param of ESP_GATTS_OPEN_EVT struct esp_ble_gatts_cb_param_t::gatts_open_evt_param open Gatt server callback param of ESP_GATTS_OPEN_EVT struct esp_ble_gatts_cb_param_t::gatts_cancel_open_evt_param cancel_open Gatt server callback param of ESP_GATTS_CANCEL_OPEN_EVT struct esp_ble_gatts_cb_param_t::gatts_cancel_open_evt_param cancel_open Gatt server callback param of ESP_GATTS_CANCEL_OPEN_EVT struct esp_ble_gatts_cb_param_t::gatts_close_evt_param close Gatt server callback param of ESP_GATTS_CLOSE_EVT struct esp_ble_gatts_cb_param_t::gatts_close_evt_param close Gatt server callback param of ESP_GATTS_CLOSE_EVT struct esp_ble_gatts_cb_param_t::gatts_congest_evt_param congest Gatt server callback param of ESP_GATTS_CONGEST_EVT struct esp_ble_gatts_cb_param_t::gatts_congest_evt_param congest Gatt server callback param of ESP_GATTS_CONGEST_EVT struct esp_ble_gatts_cb_param_t::gatts_rsp_evt_param rsp Gatt server callback param of ESP_GATTS_RESPONSE_EVT struct esp_ble_gatts_cb_param_t::gatts_rsp_evt_param rsp Gatt server callback param of ESP_GATTS_RESPONSE_EVT struct esp_ble_gatts_cb_param_t::gatts_add_attr_tab_evt_param add_attr_tab Gatt server callback param of ESP_GATTS_CREAT_ATTR_TAB_EVT struct esp_ble_gatts_cb_param_t::gatts_add_attr_tab_evt_param add_attr_tab Gatt server callback param of ESP_GATTS_CREAT_ATTR_TAB_EVT struct esp_ble_gatts_cb_param_t::gatts_set_attr_val_evt_param set_attr_val Gatt server callback param of ESP_GATTS_SET_ATTR_VAL_EVT struct esp_ble_gatts_cb_param_t::gatts_set_attr_val_evt_param set_attr_val Gatt server callback param of ESP_GATTS_SET_ATTR_VAL_EVT struct esp_ble_gatts_cb_param_t::gatts_send_service_change_evt_param service_change Gatt server callback param of ESP_GATTS_SEND_SERVICE_CHANGE_EVT struct esp_ble_gatts_cb_param_t::gatts_send_service_change_evt_param service_change Gatt server callback param of ESP_GATTS_SEND_SERVICE_CHANGE_EVT struct gatts_add_attr_tab_evt_param #include <esp_gatts_api.h> ESP_GATTS_CREAT_ATTR_TAB_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status esp_bt_uuid_t svc_uuid Service uuid type esp_bt_uuid_t svc_uuid Service uuid type uint8_t svc_inst_id Service id uint8_t svc_inst_id Service id uint16_t num_handle The number of the attribute handle to be added to the gatts database uint16_t num_handle The number of the attribute handle to be added to the gatts database uint16_t *handles The number to the handles uint16_t *handles The number to the handles esp_gatt_status_t status struct gatts_add_attr_tab_evt_param #include <esp_gatts_api.h> ESP_GATTS_CREAT_ATTR_TAB_EVT. Public Members esp_gatt_status_t status Operation status esp_bt_uuid_t svc_uuid Service uuid type uint8_t svc_inst_id Service id uint16_t num_handle The number of the attribute handle to be added to the gatts database uint16_t *handles The number to the handles struct gatts_add_char_descr_evt_param #include <esp_gatts_api.h> ESP_GATTS_ADD_CHAR_DESCR_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t attr_handle Descriptor attribute handle uint16_t attr_handle Descriptor attribute handle uint16_t service_handle Service attribute handle uint16_t service_handle Service attribute handle esp_bt_uuid_t descr_uuid Characteristic descriptor uuid esp_bt_uuid_t descr_uuid Characteristic descriptor uuid esp_gatt_status_t status struct gatts_add_char_descr_evt_param #include <esp_gatts_api.h> ESP_GATTS_ADD_CHAR_DESCR_EVT. Public Members esp_gatt_status_t status Operation status uint16_t attr_handle Descriptor attribute handle uint16_t service_handle Service attribute handle esp_bt_uuid_t descr_uuid Characteristic descriptor uuid struct gatts_add_char_evt_param #include <esp_gatts_api.h> ESP_GATTS_ADD_CHAR_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t attr_handle Characteristic attribute handle uint16_t attr_handle Characteristic attribute handle uint16_t service_handle Service attribute handle uint16_t service_handle Service attribute handle esp_bt_uuid_t char_uuid Characteristic uuid esp_bt_uuid_t char_uuid Characteristic uuid esp_gatt_status_t status struct gatts_add_char_evt_param #include <esp_gatts_api.h> ESP_GATTS_ADD_CHAR_EVT. Public Members esp_gatt_status_t status Operation status uint16_t attr_handle Characteristic attribute handle uint16_t service_handle Service attribute handle esp_bt_uuid_t char_uuid Characteristic uuid struct gatts_add_incl_srvc_evt_param #include <esp_gatts_api.h> ESP_GATTS_ADD_INCL_SRVC_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t attr_handle Included service attribute handle uint16_t attr_handle Included service attribute handle uint16_t service_handle Service attribute handle uint16_t service_handle Service attribute handle esp_gatt_status_t status struct gatts_add_incl_srvc_evt_param #include <esp_gatts_api.h> ESP_GATTS_ADD_INCL_SRVC_EVT. Public Members esp_gatt_status_t status Operation status uint16_t attr_handle Included service attribute handle uint16_t service_handle Service attribute handle struct gatts_cancel_open_evt_param #include <esp_gatts_api.h> ESP_GATTS_CANCEL_OPEN_EVT. struct gatts_cancel_open_evt_param #include <esp_gatts_api.h> ESP_GATTS_CANCEL_OPEN_EVT. struct gatts_close_evt_param #include <esp_gatts_api.h> ESP_GATTS_CLOSE_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t conn_id Connection id uint16_t conn_id Connection id esp_gatt_status_t status struct gatts_close_evt_param #include <esp_gatts_api.h> ESP_GATTS_CLOSE_EVT. Public Members esp_gatt_status_t status Operation status uint16_t conn_id Connection id struct gatts_conf_evt_param #include <esp_gatts_api.h> ESP_GATTS_CONF_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t conn_id Connection id uint16_t conn_id Connection id uint16_t handle attribute handle uint16_t handle attribute handle uint16_t len The indication or notification value length, len is valid when send notification or indication failed uint16_t len The indication or notification value length, len is valid when send notification or indication failed uint8_t *value The indication or notification value , value is valid when send notification or indication failed uint8_t *value The indication or notification value , value is valid when send notification or indication failed esp_gatt_status_t status struct gatts_conf_evt_param #include <esp_gatts_api.h> ESP_GATTS_CONF_EVT. Public Members esp_gatt_status_t status Operation status uint16_t conn_id Connection id uint16_t handle attribute handle uint16_t len The indication or notification value length, len is valid when send notification or indication failed uint8_t *value The indication or notification value , value is valid when send notification or indication failed struct gatts_congest_evt_param #include <esp_gatts_api.h> ESP_GATTS_LISTEN_EVT. ESP_GATTS_CONGEST_EVT struct gatts_congest_evt_param #include <esp_gatts_api.h> ESP_GATTS_LISTEN_EVT. ESP_GATTS_CONGEST_EVT struct gatts_connect_evt_param #include <esp_gatts_api.h> ESP_GATTS_CONNECT_EVT. Public Members uint16_t conn_id Connection id uint16_t conn_id Connection id uint8_t link_role Link role : master role = 0 ; slave role = 1 uint8_t link_role Link role : master role = 0 ; slave role = 1 esp_bd_addr_t remote_bda Remote bluetooth device address esp_bd_addr_t remote_bda Remote bluetooth device address esp_gatt_conn_params_t conn_params current Connection parameters esp_gatt_conn_params_t conn_params current Connection parameters esp_ble_addr_type_t ble_addr_type Remote BLE device address type esp_ble_addr_type_t ble_addr_type Remote BLE device address type uint16_t conn_handle HCI connection handle uint16_t conn_handle HCI connection handle uint16_t conn_id struct gatts_connect_evt_param #include <esp_gatts_api.h> ESP_GATTS_CONNECT_EVT. Public Members uint16_t conn_id Connection id uint8_t link_role Link role : master role = 0 ; slave role = 1 esp_bd_addr_t remote_bda Remote bluetooth device address esp_gatt_conn_params_t conn_params current Connection parameters esp_ble_addr_type_t ble_addr_type Remote BLE device address type uint16_t conn_handle HCI connection handle struct gatts_create_evt_param #include <esp_gatts_api.h> ESP_GATTS_UNREG_EVT. ESP_GATTS_CREATE_EVT Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t service_handle Service attribute handle uint16_t service_handle Service attribute handle esp_gatt_srvc_id_t service_id Service id, include service uuid and other information esp_gatt_srvc_id_t service_id Service id, include service uuid and other information esp_gatt_status_t status struct gatts_create_evt_param #include <esp_gatts_api.h> ESP_GATTS_UNREG_EVT. ESP_GATTS_CREATE_EVT Public Members esp_gatt_status_t status Operation status uint16_t service_handle Service attribute handle esp_gatt_srvc_id_t service_id Service id, include service uuid and other information struct gatts_delete_evt_param #include <esp_gatts_api.h> ESP_GATTS_DELETE_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t service_handle Service attribute handle uint16_t service_handle Service attribute handle esp_gatt_status_t status struct gatts_delete_evt_param #include <esp_gatts_api.h> ESP_GATTS_DELETE_EVT. Public Members esp_gatt_status_t status Operation status uint16_t service_handle Service attribute handle struct gatts_disconnect_evt_param #include <esp_gatts_api.h> ESP_GATTS_DISCONNECT_EVT. Public Members uint16_t conn_id Connection id uint16_t conn_id Connection id esp_bd_addr_t remote_bda Remote bluetooth device address esp_bd_addr_t remote_bda Remote bluetooth device address esp_gatt_conn_reason_t reason Indicate the reason of disconnection esp_gatt_conn_reason_t reason Indicate the reason of disconnection uint16_t conn_id struct gatts_disconnect_evt_param #include <esp_gatts_api.h> ESP_GATTS_DISCONNECT_EVT. Public Members uint16_t conn_id Connection id esp_bd_addr_t remote_bda Remote bluetooth device address esp_gatt_conn_reason_t reason Indicate the reason of disconnection struct gatts_exec_write_evt_param #include <esp_gatts_api.h> ESP_GATTS_EXEC_WRITE_EVT. Public Members uint16_t conn_id Connection id uint16_t conn_id Connection id uint32_t trans_id Transfer id uint32_t trans_id Transfer id esp_bd_addr_t bda The bluetooth device address which been written esp_bd_addr_t bda The bluetooth device address which been written uint8_t exec_write_flag Execute write flag uint8_t exec_write_flag Execute write flag uint16_t conn_id struct gatts_exec_write_evt_param #include <esp_gatts_api.h> ESP_GATTS_EXEC_WRITE_EVT. Public Members uint16_t conn_id Connection id uint32_t trans_id Transfer id esp_bd_addr_t bda The bluetooth device address which been written uint8_t exec_write_flag Execute write flag struct gatts_mtu_evt_param #include <esp_gatts_api.h> ESP_GATTS_MTU_EVT. struct gatts_mtu_evt_param #include <esp_gatts_api.h> ESP_GATTS_MTU_EVT. struct gatts_open_evt_param #include <esp_gatts_api.h> ESP_GATTS_OPEN_EVT. struct gatts_open_evt_param #include <esp_gatts_api.h> ESP_GATTS_OPEN_EVT. struct gatts_read_evt_param #include <esp_gatts_api.h> ESP_GATTS_READ_EVT. Public Members uint16_t conn_id Connection id uint16_t conn_id Connection id uint32_t trans_id Transfer id uint32_t trans_id Transfer id esp_bd_addr_t bda The bluetooth device address which been read esp_bd_addr_t bda The bluetooth device address which been read uint16_t handle The attribute handle uint16_t handle The attribute handle uint16_t offset Offset of the value, if the value is too long uint16_t offset Offset of the value, if the value is too long bool is_long The value is too long or not bool is_long The value is too long or not bool need_rsp The read operation need to do response bool need_rsp The read operation need to do response uint16_t conn_id struct gatts_read_evt_param #include <esp_gatts_api.h> ESP_GATTS_READ_EVT. Public Members uint16_t conn_id Connection id uint32_t trans_id Transfer id esp_bd_addr_t bda The bluetooth device address which been read uint16_t handle The attribute handle uint16_t offset Offset of the value, if the value is too long bool is_long The value is too long or not bool need_rsp The read operation need to do response struct gatts_reg_evt_param #include <esp_gatts_api.h> ESP_GATTS_REG_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t app_id Application id which input in register API uint16_t app_id Application id which input in register API esp_gatt_status_t status struct gatts_reg_evt_param #include <esp_gatts_api.h> ESP_GATTS_REG_EVT. Public Members esp_gatt_status_t status Operation status uint16_t app_id Application id which input in register API struct gatts_rsp_evt_param #include <esp_gatts_api.h> ESP_GATTS_RESPONSE_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t handle Attribute handle which send response uint16_t handle Attribute handle which send response esp_gatt_status_t status struct gatts_rsp_evt_param #include <esp_gatts_api.h> ESP_GATTS_RESPONSE_EVT. Public Members esp_gatt_status_t status Operation status uint16_t handle Attribute handle which send response struct gatts_send_service_change_evt_param #include <esp_gatts_api.h> ESP_GATTS_SEND_SERVICE_CHANGE_EVT. struct gatts_send_service_change_evt_param #include <esp_gatts_api.h> ESP_GATTS_SEND_SERVICE_CHANGE_EVT. struct gatts_set_attr_val_evt_param #include <esp_gatts_api.h> ESP_GATTS_SET_ATTR_VAL_EVT. Public Members uint16_t srvc_handle The service handle uint16_t srvc_handle The service handle uint16_t attr_handle The attribute handle uint16_t attr_handle The attribute handle esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t srvc_handle struct gatts_set_attr_val_evt_param #include <esp_gatts_api.h> ESP_GATTS_SET_ATTR_VAL_EVT. Public Members uint16_t srvc_handle The service handle uint16_t attr_handle The attribute handle esp_gatt_status_t status Operation status struct gatts_start_evt_param #include <esp_gatts_api.h> ESP_GATTS_START_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t service_handle Service attribute handle uint16_t service_handle Service attribute handle esp_gatt_status_t status struct gatts_start_evt_param #include <esp_gatts_api.h> ESP_GATTS_START_EVT. Public Members esp_gatt_status_t status Operation status uint16_t service_handle Service attribute handle struct gatts_stop_evt_param #include <esp_gatts_api.h> ESP_GATTS_STOP_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t service_handle Service attribute handle uint16_t service_handle Service attribute handle esp_gatt_status_t status struct gatts_stop_evt_param #include <esp_gatts_api.h> ESP_GATTS_STOP_EVT. Public Members esp_gatt_status_t status Operation status uint16_t service_handle Service attribute handle struct gatts_write_evt_param #include <esp_gatts_api.h> ESP_GATTS_WRITE_EVT. Public Members uint16_t conn_id Connection id uint16_t conn_id Connection id uint32_t trans_id Transfer id uint32_t trans_id Transfer id esp_bd_addr_t bda The bluetooth device address which been written esp_bd_addr_t bda The bluetooth device address which been written uint16_t handle The attribute handle uint16_t handle The attribute handle uint16_t offset Offset of the value, if the value is too long uint16_t offset Offset of the value, if the value is too long bool need_rsp The write operation need to do response bool need_rsp The write operation need to do response bool is_prep This write operation is prepare write bool is_prep This write operation is prepare write uint16_t len The write attribute value length uint16_t len The write attribute value length uint8_t *value The write attribute value uint8_t *value The write attribute value uint16_t conn_id struct gatts_write_evt_param #include <esp_gatts_api.h> ESP_GATTS_WRITE_EVT. Public Members uint16_t conn_id Connection id uint32_t trans_id Transfer id esp_bd_addr_t bda The bluetooth device address which been written uint16_t handle The attribute handle uint16_t offset Offset of the value, if the value is too long bool need_rsp The write operation need to do response bool is_prep This write operation is prepare write uint16_t len The write attribute value length uint8_t *value The write attribute value struct esp_ble_gatts_cb_param_t::gatts_reg_evt_param reg Macros ESP_GATT_PREP_WRITE_CANCEL Prepare write flag to indicate cancel prepare write ESP_GATT_PREP_WRITE_EXEC Prepare write flag to indicate execute prepare write Type Definitions typedef void (*esp_gatts_cb_t)(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) GATT Server callback function type. Param event : Event type Param gatts_if : GATT server access interface, normally different gatts_if correspond to different profile Param param : Point to callback parameter, currently is union type Param event : Event type Param gatts_if : GATT server access interface, normally different gatts_if correspond to different profile Param param : Point to callback parameter, currently is union type Enumerations enum esp_gatts_cb_event_t GATT Server callback function events. Values: enumerator ESP_GATTS_REG_EVT When register application id, the event comes enumerator ESP_GATTS_REG_EVT When register application id, the event comes enumerator ESP_GATTS_READ_EVT When gatt client request read operation, the event comes enumerator ESP_GATTS_READ_EVT When gatt client request read operation, the event comes enumerator ESP_GATTS_WRITE_EVT When gatt client request write operation, the event comes enumerator ESP_GATTS_WRITE_EVT When gatt client request write operation, the event comes enumerator ESP_GATTS_EXEC_WRITE_EVT When gatt client request execute write, the event comes enumerator ESP_GATTS_EXEC_WRITE_EVT When gatt client request execute write, the event comes enumerator ESP_GATTS_MTU_EVT When set mtu complete, the event comes enumerator ESP_GATTS_MTU_EVT When set mtu complete, the event comes enumerator ESP_GATTS_CONF_EVT When receive confirm, the event comes enumerator ESP_GATTS_CONF_EVT When receive confirm, the event comes enumerator ESP_GATTS_UNREG_EVT When unregister application id, the event comes enumerator ESP_GATTS_UNREG_EVT When unregister application id, the event comes enumerator ESP_GATTS_CREATE_EVT When create service complete, the event comes enumerator ESP_GATTS_CREATE_EVT When create service complete, the event comes enumerator ESP_GATTS_ADD_INCL_SRVC_EVT When add included service complete, the event comes enumerator ESP_GATTS_ADD_INCL_SRVC_EVT When add included service complete, the event comes enumerator ESP_GATTS_ADD_CHAR_EVT When add characteristic complete, the event comes enumerator ESP_GATTS_ADD_CHAR_EVT When add characteristic complete, the event comes enumerator ESP_GATTS_ADD_CHAR_DESCR_EVT When add descriptor complete, the event comes enumerator ESP_GATTS_ADD_CHAR_DESCR_EVT When add descriptor complete, the event comes enumerator ESP_GATTS_DELETE_EVT When delete service complete, the event comes enumerator ESP_GATTS_DELETE_EVT When delete service complete, the event comes enumerator ESP_GATTS_START_EVT When start service complete, the event comes enumerator ESP_GATTS_START_EVT When start service complete, the event comes enumerator ESP_GATTS_STOP_EVT When stop service complete, the event comes enumerator ESP_GATTS_STOP_EVT When stop service complete, the event comes enumerator ESP_GATTS_CONNECT_EVT When gatt client connect, the event comes enumerator ESP_GATTS_CONNECT_EVT When gatt client connect, the event comes enumerator ESP_GATTS_DISCONNECT_EVT When gatt client disconnect, the event comes enumerator ESP_GATTS_DISCONNECT_EVT When gatt client disconnect, the event comes enumerator ESP_GATTS_OPEN_EVT When connect to peer, the event comes enumerator ESP_GATTS_OPEN_EVT When connect to peer, the event comes enumerator ESP_GATTS_CANCEL_OPEN_EVT When disconnect from peer, the event comes enumerator ESP_GATTS_CANCEL_OPEN_EVT When disconnect from peer, the event comes enumerator ESP_GATTS_CLOSE_EVT When gatt server close, the event comes enumerator ESP_GATTS_CLOSE_EVT When gatt server close, the event comes enumerator ESP_GATTS_LISTEN_EVT When gatt listen to be connected the event comes enumerator ESP_GATTS_LISTEN_EVT When gatt listen to be connected the event comes enumerator ESP_GATTS_CONGEST_EVT When congest happen, the event comes enumerator ESP_GATTS_CONGEST_EVT When congest happen, the event comes enumerator ESP_GATTS_RESPONSE_EVT When gatt send response complete, the event comes enumerator ESP_GATTS_RESPONSE_EVT When gatt send response complete, the event comes enumerator ESP_GATTS_CREAT_ATTR_TAB_EVT When gatt create table complete, the event comes enumerator ESP_GATTS_CREAT_ATTR_TAB_EVT When gatt create table complete, the event comes enumerator ESP_GATTS_SET_ATTR_VAL_EVT When gatt set attr value complete, the event comes enumerator ESP_GATTS_SET_ATTR_VAL_EVT When gatt set attr value complete, the event comes enumerator ESP_GATTS_SEND_SERVICE_CHANGE_EVT When gatt send service change indication complete, the event comes enumerator ESP_GATTS_SEND_SERVICE_CHANGE_EVT When gatt send service change indication complete, the event comes enumerator ESP_GATTS_REG_EVT
GATT Server API Application Examples Check bluetooth/bluedroid/ble folder in ESP-IDF examples, which contains the following demos and their tutorials: This is a GATT server demo and its tutorial. This demo creates a GATT service with an attribute table, which releases the user from the operation of adding attributes one by one. This is the recommended method of adding attributes (officially recommended). This is a GATT server demo and its tutorial. This demo creates a GATT service by adding attributes one by one as defined by Bluedroid. The recommended method of adding attributes is presented in the example below. This is a demo similar to Bluetooth® Low Energy (Bluetooth LE) SPP. In this demo, GATT server can receive data from UART and then send the data to the peer device automatically. API Reference Header File components/bt/host/bluedroid/api/include/api/esp_gatts_api.h This header file can be included with: #include "esp_gatts_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_gatts_register_callback(esp_gatts_cb_t callback) This function is called to register application callbacks with BTA GATTS module. - Returns ESP_OK : success other : failed - - esp_gatts_cb_t esp_ble_gatts_get_callback(void) This function is called to get the current application callbacks with BTA GATTS module. - Returns esp_gatts_cb_t : current callback - - esp_err_t esp_ble_gatts_app_register(uint16_t app_id) This function is called to register application identifier. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gatts_app_unregister(esp_gatt_if_t gatts_if) unregister with GATT Server. - Parameters gatts_if -- [in] GATT server access interface - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gatts_create_service(esp_gatt_if_t gatts_if, esp_gatt_srvc_id_t *service_id, uint16_t num_handle) Create a service. When service creation is done, a callback event ESP_GATTS_CREATE_EVT is called to report status and service ID to the profile. The service ID obtained in the callback function needs to be used when adding included service and characteristics/descriptors into the service. - Parameters gatts_if -- [in] GATT server access interface service_id -- [in] service ID. num_handle -- [in] number of handle requested for this service. - - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gatts_create_attr_tab(const esp_gatts_attr_db_t *gatts_attr_db, esp_gatt_if_t gatts_if, uint16_t max_nb_attr, uint8_t srvc_inst_id) Create a service attribute tab. - Parameters gatts_attr_db -- [in] the pointer to the service attr tab gatts_if -- [in] GATT server access interface max_nb_attr -- [in] the number of attribute to be added to the service database. srvc_inst_id -- [in] the instance id of the service - - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gatts_add_included_service(uint16_t service_handle, uint16_t included_service_handle) This function is called to add an included service. This function have to be called between 'esp_ble_gatts_create_service' and 'esp_ble_gatts_add_char'. After included service is included, a callback event ESP_GATTS_ADD_INCL_SRVC_EVT is reported the included service ID. - Parameters service_handle -- [in] service handle to which this included service is to be added. included_service_handle -- [in] the service ID to be included. - - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gatts_add_char(uint16_t service_handle, esp_bt_uuid_t *char_uuid, esp_gatt_perm_t perm, esp_gatt_char_prop_t property, esp_attr_value_t *char_val, esp_attr_control_t *control) This function is called to add a characteristic into a service. - Parameters service_handle -- [in] service handle to which this included service is to be added. char_uuid -- [in] : Characteristic UUID. perm -- [in] : Characteristic value declaration attribute permission. property -- [in] : Characteristic Properties char_val -- [in] : Characteristic value control -- [in] : attribute response control byte - - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gatts_add_char_descr(uint16_t service_handle, esp_bt_uuid_t *descr_uuid, esp_gatt_perm_t perm, esp_attr_value_t *char_descr_val, esp_attr_control_t *control) This function is called to add characteristic descriptor. When it's done, a callback event ESP_GATTS_ADD_DESCR_EVT is called to report the status and an ID number for this descriptor. - Parameters service_handle -- [in] service handle to which this characteristic descriptor is to be added. perm -- [in] descriptor access permission. descr_uuid -- [in] descriptor UUID. char_descr_val -- [in] : Characteristic descriptor value control -- [in] : attribute response control byte - - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gatts_delete_service(uint16_t service_handle) This function is called to delete a service. When this is done, a callback event ESP_GATTS_DELETE_EVT is report with the status. - Parameters service_handle -- [in] service_handle to be deleted. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gatts_start_service(uint16_t service_handle) This function is called to start a service. - Parameters service_handle -- [in] the service handle to be started. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gatts_stop_service(uint16_t service_handle) This function is called to stop a service. - Parameters service_handle -- [in] - service to be topped. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gatts_send_indicate(esp_gatt_if_t gatts_if, uint16_t conn_id, uint16_t attr_handle, uint16_t value_len, uint8_t *value, bool need_confirm) Send indicate or notify to GATT client. Set param need_confirm as false will send notification, otherwise indication. Note: the size of indicate or notify data need less than MTU size,see "esp_ble_gattc_send_mtu_req". - Parameters gatts_if -- [in] GATT server access interface conn_id -- [in] - connection id to indicate. attr_handle -- [in] - attribute handle to indicate. value_len -- [in] - indicate value length. value -- [in] value to indicate. need_confirm -- [in] - Whether a confirmation is required. false sends a GATT notification, true sends a GATT indication. - - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gatts_send_response(esp_gatt_if_t gatts_if, uint16_t conn_id, uint32_t trans_id, esp_gatt_status_t status, esp_gatt_rsp_t *rsp) This function is called to send a response to a request. - Parameters gatts_if -- [in] GATT server access interface conn_id -- [in] - connection identifier. trans_id -- [in] - transfer id status -- [in] - response status rsp -- [in] - response data. - - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gatts_set_attr_value(uint16_t attr_handle, uint16_t length, const uint8_t *value) This function is called to set the attribute value by the application. - Parameters attr_handle -- [in] the attribute handle which to be set length -- [in] the value length value -- [in] the pointer to the attribute value - - Returns ESP_OK : success other : failed - - esp_gatt_status_t esp_ble_gatts_get_attr_value(uint16_t attr_handle, uint16_t *length, const uint8_t **value) Retrieve attribute value. - Parameters attr_handle -- [in] Attribute handle. length -- [out] pointer to the attribute value length value -- [out] Pointer to attribute value payload, the value cannot be modified by user - - Returns ESP_GATT_OK : success other : failed - - esp_err_t esp_ble_gatts_open(esp_gatt_if_t gatts_if, esp_bd_addr_t remote_bda, bool is_direct) Open a direct open connection or add a background auto connection. - Parameters gatts_if -- [in] GATT server access interface remote_bda -- [in] remote device bluetooth device address. is_direct -- [in] direct connection or background auto connection - - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gatts_close(esp_gatt_if_t gatts_if, uint16_t conn_id) Close a connection a remote device. - Parameters gatts_if -- [in] GATT server access interface conn_id -- [in] connection ID to be closed. - - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_gatts_send_service_change_indication(esp_gatt_if_t gatts_if, esp_bd_addr_t remote_bda) Send service change indication. - Parameters gatts_if -- [in] GATT server access interface remote_bda -- [in] remote device bluetooth device address. If remote_bda is NULL then it will send service change indication to all the connected devices and if not then to a specific device - - Returns ESP_OK : success other : failed - Unions - union esp_ble_gatts_cb_param_t - #include <esp_gatts_api.h> Gatt server callback parameters union. Public Members - struct esp_ble_gatts_cb_param_t::gatts_reg_evt_param reg Gatt server callback param of ESP_GATTS_REG_EVT - struct esp_ble_gatts_cb_param_t::gatts_read_evt_param read Gatt server callback param of ESP_GATTS_READ_EVT - struct esp_ble_gatts_cb_param_t::gatts_write_evt_param write Gatt server callback param of ESP_GATTS_WRITE_EVT - struct esp_ble_gatts_cb_param_t::gatts_exec_write_evt_param exec_write Gatt server callback param of ESP_GATTS_EXEC_WRITE_EVT - struct esp_ble_gatts_cb_param_t::gatts_mtu_evt_param mtu Gatt server callback param of ESP_GATTS_MTU_EVT - struct esp_ble_gatts_cb_param_t::gatts_conf_evt_param conf Gatt server callback param of ESP_GATTS_CONF_EVT (confirm) - struct esp_ble_gatts_cb_param_t::gatts_create_evt_param create Gatt server callback param of ESP_GATTS_CREATE_EVT - struct esp_ble_gatts_cb_param_t::gatts_add_incl_srvc_evt_param add_incl_srvc Gatt server callback param of ESP_GATTS_ADD_INCL_SRVC_EVT - struct esp_ble_gatts_cb_param_t::gatts_add_char_evt_param add_char Gatt server callback param of ESP_GATTS_ADD_CHAR_EVT - struct esp_ble_gatts_cb_param_t::gatts_add_char_descr_evt_param add_char_descr Gatt server callback param of ESP_GATTS_ADD_CHAR_DESCR_EVT - struct esp_ble_gatts_cb_param_t::gatts_delete_evt_param del Gatt server callback param of ESP_GATTS_DELETE_EVT - struct esp_ble_gatts_cb_param_t::gatts_start_evt_param start Gatt server callback param of ESP_GATTS_START_EVT - struct esp_ble_gatts_cb_param_t::gatts_stop_evt_param stop Gatt server callback param of ESP_GATTS_STOP_EVT - struct esp_ble_gatts_cb_param_t::gatts_connect_evt_param connect Gatt server callback param of ESP_GATTS_CONNECT_EVT - struct esp_ble_gatts_cb_param_t::gatts_disconnect_evt_param disconnect Gatt server callback param of ESP_GATTS_DISCONNECT_EVT - struct esp_ble_gatts_cb_param_t::gatts_open_evt_param open Gatt server callback param of ESP_GATTS_OPEN_EVT - struct esp_ble_gatts_cb_param_t::gatts_cancel_open_evt_param cancel_open Gatt server callback param of ESP_GATTS_CANCEL_OPEN_EVT - struct esp_ble_gatts_cb_param_t::gatts_close_evt_param close Gatt server callback param of ESP_GATTS_CLOSE_EVT - struct esp_ble_gatts_cb_param_t::gatts_congest_evt_param congest Gatt server callback param of ESP_GATTS_CONGEST_EVT - struct esp_ble_gatts_cb_param_t::gatts_rsp_evt_param rsp Gatt server callback param of ESP_GATTS_RESPONSE_EVT - struct esp_ble_gatts_cb_param_t::gatts_add_attr_tab_evt_param add_attr_tab Gatt server callback param of ESP_GATTS_CREAT_ATTR_TAB_EVT - struct esp_ble_gatts_cb_param_t::gatts_set_attr_val_evt_param set_attr_val Gatt server callback param of ESP_GATTS_SET_ATTR_VAL_EVT - struct esp_ble_gatts_cb_param_t::gatts_send_service_change_evt_param service_change Gatt server callback param of ESP_GATTS_SEND_SERVICE_CHANGE_EVT - struct gatts_add_attr_tab_evt_param - #include <esp_gatts_api.h> ESP_GATTS_CREAT_ATTR_TAB_EVT. Public Members - esp_gatt_status_t status Operation status - esp_bt_uuid_t svc_uuid Service uuid type - uint8_t svc_inst_id Service id - uint16_t num_handle The number of the attribute handle to be added to the gatts database - uint16_t *handles The number to the handles - esp_gatt_status_t status - struct gatts_add_char_descr_evt_param - #include <esp_gatts_api.h> ESP_GATTS_ADD_CHAR_DESCR_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t attr_handle Descriptor attribute handle - uint16_t service_handle Service attribute handle - esp_bt_uuid_t descr_uuid Characteristic descriptor uuid - esp_gatt_status_t status - struct gatts_add_char_evt_param - #include <esp_gatts_api.h> ESP_GATTS_ADD_CHAR_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t attr_handle Characteristic attribute handle - uint16_t service_handle Service attribute handle - esp_bt_uuid_t char_uuid Characteristic uuid - esp_gatt_status_t status - struct gatts_add_incl_srvc_evt_param - #include <esp_gatts_api.h> ESP_GATTS_ADD_INCL_SRVC_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t attr_handle Included service attribute handle - uint16_t service_handle Service attribute handle - esp_gatt_status_t status - struct gatts_cancel_open_evt_param - #include <esp_gatts_api.h> ESP_GATTS_CANCEL_OPEN_EVT. - struct gatts_close_evt_param - #include <esp_gatts_api.h> ESP_GATTS_CLOSE_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t conn_id Connection id - esp_gatt_status_t status - struct gatts_conf_evt_param - #include <esp_gatts_api.h> ESP_GATTS_CONF_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t conn_id Connection id - uint16_t handle attribute handle - uint16_t len The indication or notification value length, len is valid when send notification or indication failed - uint8_t *value The indication or notification value , value is valid when send notification or indication failed - esp_gatt_status_t status - struct gatts_congest_evt_param - #include <esp_gatts_api.h> ESP_GATTS_LISTEN_EVT. ESP_GATTS_CONGEST_EVT - struct gatts_connect_evt_param - #include <esp_gatts_api.h> ESP_GATTS_CONNECT_EVT. Public Members - uint16_t conn_id Connection id - uint8_t link_role Link role : master role = 0 ; slave role = 1 - esp_bd_addr_t remote_bda Remote bluetooth device address - esp_gatt_conn_params_t conn_params current Connection parameters - esp_ble_addr_type_t ble_addr_type Remote BLE device address type - uint16_t conn_handle HCI connection handle - uint16_t conn_id - struct gatts_create_evt_param - #include <esp_gatts_api.h> ESP_GATTS_UNREG_EVT. ESP_GATTS_CREATE_EVT Public Members - esp_gatt_status_t status Operation status - uint16_t service_handle Service attribute handle - esp_gatt_srvc_id_t service_id Service id, include service uuid and other information - esp_gatt_status_t status - struct gatts_delete_evt_param - #include <esp_gatts_api.h> ESP_GATTS_DELETE_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t service_handle Service attribute handle - esp_gatt_status_t status - struct gatts_disconnect_evt_param - #include <esp_gatts_api.h> ESP_GATTS_DISCONNECT_EVT. Public Members - uint16_t conn_id Connection id - esp_bd_addr_t remote_bda Remote bluetooth device address - esp_gatt_conn_reason_t reason Indicate the reason of disconnection - uint16_t conn_id - struct gatts_exec_write_evt_param - #include <esp_gatts_api.h> ESP_GATTS_EXEC_WRITE_EVT. Public Members - uint16_t conn_id Connection id - uint32_t trans_id Transfer id - esp_bd_addr_t bda The bluetooth device address which been written - uint8_t exec_write_flag Execute write flag - uint16_t conn_id - struct gatts_mtu_evt_param - #include <esp_gatts_api.h> ESP_GATTS_MTU_EVT. - struct gatts_open_evt_param - #include <esp_gatts_api.h> ESP_GATTS_OPEN_EVT. - struct gatts_read_evt_param - #include <esp_gatts_api.h> ESP_GATTS_READ_EVT. Public Members - uint16_t conn_id Connection id - uint32_t trans_id Transfer id - esp_bd_addr_t bda The bluetooth device address which been read - uint16_t handle The attribute handle - uint16_t offset Offset of the value, if the value is too long - bool is_long The value is too long or not - bool need_rsp The read operation need to do response - uint16_t conn_id - struct gatts_reg_evt_param - #include <esp_gatts_api.h> ESP_GATTS_REG_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t app_id Application id which input in register API - esp_gatt_status_t status - struct gatts_rsp_evt_param - #include <esp_gatts_api.h> ESP_GATTS_RESPONSE_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t handle Attribute handle which send response - esp_gatt_status_t status - struct gatts_send_service_change_evt_param - #include <esp_gatts_api.h> ESP_GATTS_SEND_SERVICE_CHANGE_EVT. - struct gatts_set_attr_val_evt_param - #include <esp_gatts_api.h> ESP_GATTS_SET_ATTR_VAL_EVT. Public Members - uint16_t srvc_handle The service handle - uint16_t attr_handle The attribute handle - esp_gatt_status_t status Operation status - uint16_t srvc_handle - struct gatts_start_evt_param - #include <esp_gatts_api.h> ESP_GATTS_START_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t service_handle Service attribute handle - esp_gatt_status_t status - struct gatts_stop_evt_param - #include <esp_gatts_api.h> ESP_GATTS_STOP_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t service_handle Service attribute handle - esp_gatt_status_t status - struct gatts_write_evt_param - #include <esp_gatts_api.h> ESP_GATTS_WRITE_EVT. Public Members - uint16_t conn_id Connection id - uint32_t trans_id Transfer id - esp_bd_addr_t bda The bluetooth device address which been written - uint16_t handle The attribute handle - uint16_t offset Offset of the value, if the value is too long - bool need_rsp The write operation need to do response - bool is_prep This write operation is prepare write - uint16_t len The write attribute value length - uint8_t *value The write attribute value - uint16_t conn_id - struct esp_ble_gatts_cb_param_t::gatts_reg_evt_param reg Macros - ESP_GATT_PREP_WRITE_CANCEL Prepare write flag to indicate cancel prepare write - ESP_GATT_PREP_WRITE_EXEC Prepare write flag to indicate execute prepare write Type Definitions - typedef void (*esp_gatts_cb_t)(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) GATT Server callback function type. - Param event : Event type - Param gatts_if : GATT server access interface, normally different gatts_if correspond to different profile - Param param : Point to callback parameter, currently is union type Enumerations - enum esp_gatts_cb_event_t GATT Server callback function events. Values: - enumerator ESP_GATTS_REG_EVT When register application id, the event comes - enumerator ESP_GATTS_READ_EVT When gatt client request read operation, the event comes - enumerator ESP_GATTS_WRITE_EVT When gatt client request write operation, the event comes - enumerator ESP_GATTS_EXEC_WRITE_EVT When gatt client request execute write, the event comes - enumerator ESP_GATTS_MTU_EVT When set mtu complete, the event comes - enumerator ESP_GATTS_CONF_EVT When receive confirm, the event comes - enumerator ESP_GATTS_UNREG_EVT When unregister application id, the event comes - enumerator ESP_GATTS_CREATE_EVT When create service complete, the event comes - enumerator ESP_GATTS_ADD_INCL_SRVC_EVT When add included service complete, the event comes - enumerator ESP_GATTS_ADD_CHAR_EVT When add characteristic complete, the event comes - enumerator ESP_GATTS_ADD_CHAR_DESCR_EVT When add descriptor complete, the event comes - enumerator ESP_GATTS_DELETE_EVT When delete service complete, the event comes - enumerator ESP_GATTS_START_EVT When start service complete, the event comes - enumerator ESP_GATTS_STOP_EVT When stop service complete, the event comes - enumerator ESP_GATTS_CONNECT_EVT When gatt client connect, the event comes - enumerator ESP_GATTS_DISCONNECT_EVT When gatt client disconnect, the event comes - enumerator ESP_GATTS_OPEN_EVT When connect to peer, the event comes - enumerator ESP_GATTS_CANCEL_OPEN_EVT When disconnect from peer, the event comes - enumerator ESP_GATTS_CLOSE_EVT When gatt server close, the event comes - enumerator ESP_GATTS_LISTEN_EVT When gatt listen to be connected the event comes - enumerator ESP_GATTS_CONGEST_EVT When congest happen, the event comes - enumerator ESP_GATTS_RESPONSE_EVT When gatt send response complete, the event comes - enumerator ESP_GATTS_CREAT_ATTR_TAB_EVT When gatt create table complete, the event comes - enumerator ESP_GATTS_SET_ATTR_VAL_EVT When gatt set attr value complete, the event comes - enumerator ESP_GATTS_SEND_SERVICE_CHANGE_EVT When gatt send service change indication complete, the event comes - enumerator ESP_GATTS_REG_EVT
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_gatts.html
ESP-IDF Programming Guide v5.2.1 documentation
null
GATT Client API
null
espressif.com
2016-01-01
c638ec563a0f9b41
null
null
GATT Client API Application Example Check bluetooth/bluedroid/ble folder in ESP-IDF examples, which contains the following demos and their tutorials: This is a GATT client demo and its tutorial. This demo can scan for devices, connect to the GATT server and discover its services. This is a multiple connection demo and its tutorial. This demo can connect to multiple GATT server devices and discover their services. This is a demo similar to Bluetooth® Low Energy (Bluetooth LE) SPP. This demo, which acts as a GATT client, can receive data from UART and then send the data to the peer device automatically. API Reference Header File components/bt/host/bluedroid/api/include/api/esp_gattc_api.h This header file can be included with: #include "esp_gattc_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_gattc_register_callback(esp_gattc_cb_t callback) This function is called to register application callbacks with GATTC module. Parameters callback -- [in] : pointer to the application callback function. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters callback -- [in] : pointer to the application callback function. Returns ESP_OK: success other: failed esp_gattc_cb_t esp_ble_gattc_get_callback(void) This function is called to get the current application callbacks with BTA GATTC module. Returns esp_gattC_cb_t : current callback esp_gattC_cb_t : current callback esp_gattC_cb_t : current callback Returns esp_gattC_cb_t : current callback esp_err_t esp_ble_gattc_app_register(uint16_t app_id) This function is called to register application callbacks with GATTC module. Parameters app_id -- [in] : Application Identify (UUID), for different application Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters app_id -- [in] : Application Identify (UUID), for different application Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_app_unregister(esp_gatt_if_t gattc_if) This function is called to unregister an application from GATTC module. Parameters gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_open(esp_gatt_if_t gattc_if, esp_bd_addr_t remote_bda, esp_ble_addr_type_t remote_addr_type, bool is_direct) Open a direct connection or add a background auto connection. Parameters gattc_if -- [in] Gatt client access interface. remote_bda -- [in] remote device bluetooth device address. remote_addr_type -- [in] remote device bluetooth device the address type. is_direct -- [in] direct connection or background auto connection(by now, background auto connection is not supported). gattc_if -- [in] Gatt client access interface. remote_bda -- [in] remote device bluetooth device address. remote_addr_type -- [in] remote device bluetooth device the address type. is_direct -- [in] direct connection or background auto connection(by now, background auto connection is not supported). gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. remote_bda -- [in] remote device bluetooth device address. remote_addr_type -- [in] remote device bluetooth device the address type. is_direct -- [in] direct connection or background auto connection(by now, background auto connection is not supported). Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_aux_open(esp_gatt_if_t gattc_if, esp_bd_addr_t remote_bda, esp_ble_addr_type_t remote_addr_type, bool is_direct) esp_err_t esp_ble_gattc_close(esp_gatt_if_t gattc_if, uint16_t conn_id) Close the virtual connection to the GATT server. gattc may have multiple virtual GATT server connections when multiple app_id registered, this API only close one virtual GATT server connection. if there exist other virtual GATT server connections, it does not disconnect the physical connection. if you want to disconnect the physical connection directly, you can use esp_ble_gap_disconnect(esp_bd_addr_t remote_device). Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID to be closed. gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID to be closed. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID to be closed. Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_send_mtu_req(esp_gatt_if_t gattc_if, uint16_t conn_id) Configure the MTU size in the GATT channel. This can be done only once per connection. Before using, use esp_ble_gatt_set_local_mtu() to configure the local MTU size. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID. gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID. Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_search_service(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_bt_uuid_t *filter_uuid) This function is called to get service from local cache. This function report service search result by a callback event, and followed by a service search complete event. Note: 128-bit base UUID will automatically be converted to a 16-bit UUID in the search results. Other types of UUID remain unchanged. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID. filter_uuid -- [in] a UUID of the service application is interested in. If Null, discover for all services. gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID. filter_uuid -- [in] a UUID of the service application is interested in. If Null, discover for all services. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID. filter_uuid -- [in] a UUID of the service application is interested in. If Null, discover for all services. Returns ESP_OK: success other: failed esp_gatt_status_t esp_ble_gattc_get_service(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_bt_uuid_t *svc_uuid, esp_gattc_service_elem_t *result, uint16_t *count, uint16_t offset) Find all the service with the given service uuid in the gattc cache, if the svc_uuid is NULL, find all the service. Note: It just get service from local cache, won't get from remote devices. If want to get it from remote device, need to used the esp_ble_gattc_cache_refresh, then call esp_ble_gattc_get_service again. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. svc_uuid -- [in] the pointer to the service uuid. result -- [out] The pointer to the service which has been found in the gattc cache. count -- [inout] input the number of service want to find, it will output the number of service has been found in the gattc cache with the given service uuid. offset -- [in] Offset of the service position to get. gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. svc_uuid -- [in] the pointer to the service uuid. result -- [out] The pointer to the service which has been found in the gattc cache. count -- [inout] input the number of service want to find, it will output the number of service has been found in the gattc cache with the given service uuid. offset -- [in] Offset of the service position to get. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. svc_uuid -- [in] the pointer to the service uuid. result -- [out] The pointer to the service which has been found in the gattc cache. count -- [inout] input the number of service want to find, it will output the number of service has been found in the gattc cache with the given service uuid. offset -- [in] Offset of the service position to get. Returns ESP_OK: success other: failed esp_gatt_status_t esp_ble_gattc_get_all_char(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, esp_gattc_char_elem_t *result, uint16_t *count, uint16_t offset) Find all the characteristic with the given service in the gattc cache Note: It just get characteristic from local cache, won't get from remote devices. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle. end_handle -- [in] the attribute end handle result -- [out] The pointer to the characteristic in the service. count -- [inout] input the number of characteristic want to find, it will output the number of characteristic has been found in the gattc cache with the given service. offset -- [in] Offset of the characteristic position to get. gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle. end_handle -- [in] the attribute end handle result -- [out] The pointer to the characteristic in the service. count -- [inout] input the number of characteristic want to find, it will output the number of characteristic has been found in the gattc cache with the given service. offset -- [in] Offset of the characteristic position to get. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle. end_handle -- [in] the attribute end handle result -- [out] The pointer to the characteristic in the service. count -- [inout] input the number of characteristic want to find, it will output the number of characteristic has been found in the gattc cache with the given service. offset -- [in] Offset of the characteristic position to get. Returns ESP_OK: success other: failed esp_gatt_status_t esp_ble_gattc_get_all_descr(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t char_handle, esp_gattc_descr_elem_t *result, uint16_t *count, uint16_t offset) Find all the descriptor with the given characteristic in the gattc cache Note: It just get descriptor from local cache, won't get from remote devices. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. char_handle -- [in] the given characteristic handle result -- [out] The pointer to the descriptor in the characteristic. count -- [inout] input the number of descriptor want to find, it will output the number of descriptor has been found in the gattc cache with the given characteristic. offset -- [in] Offset of the descriptor position to get. gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. char_handle -- [in] the given characteristic handle result -- [out] The pointer to the descriptor in the characteristic. count -- [inout] input the number of descriptor want to find, it will output the number of descriptor has been found in the gattc cache with the given characteristic. offset -- [in] Offset of the descriptor position to get. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. char_handle -- [in] the given characteristic handle result -- [out] The pointer to the descriptor in the characteristic. count -- [inout] input the number of descriptor want to find, it will output the number of descriptor has been found in the gattc cache with the given characteristic. offset -- [in] Offset of the descriptor position to get. Returns ESP_OK: success other: failed esp_gatt_status_t esp_ble_gattc_get_char_by_uuid(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, esp_bt_uuid_t char_uuid, esp_gattc_char_elem_t *result, uint16_t *count) Find the characteristic with the given characteristic uuid in the gattc cache Note: It just get characteristic from local cache, won't get from remote devices. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle char_uuid -- [in] the characteristic uuid result -- [out] The pointer to the characteristic in the service. count -- [inout] input the number of characteristic want to find, it will output the number of characteristic has been found in the gattc cache with the given service. gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle char_uuid -- [in] the characteristic uuid result -- [out] The pointer to the characteristic in the service. count -- [inout] input the number of characteristic want to find, it will output the number of characteristic has been found in the gattc cache with the given service. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle char_uuid -- [in] the characteristic uuid result -- [out] The pointer to the characteristic in the service. count -- [inout] input the number of characteristic want to find, it will output the number of characteristic has been found in the gattc cache with the given service. Returns ESP_OK: success other: failed esp_gatt_status_t esp_ble_gattc_get_descr_by_uuid(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, esp_bt_uuid_t char_uuid, esp_bt_uuid_t descr_uuid, esp_gattc_descr_elem_t *result, uint16_t *count) Find the descriptor with the given characteristic uuid in the gattc cache Note: It just get descriptor from local cache, won't get from remote devices. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle char_uuid -- [in] the characteristic uuid. descr_uuid -- [in] the descriptor uuid. result -- [out] The pointer to the descriptor in the given characteristic. count -- [inout] input the number of descriptor want to find, it will output the number of descriptor has been found in the gattc cache with the given characteristic. gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle char_uuid -- [in] the characteristic uuid. descr_uuid -- [in] the descriptor uuid. result -- [out] The pointer to the descriptor in the given characteristic. count -- [inout] input the number of descriptor want to find, it will output the number of descriptor has been found in the gattc cache with the given characteristic. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle char_uuid -- [in] the characteristic uuid. descr_uuid -- [in] the descriptor uuid. result -- [out] The pointer to the descriptor in the given characteristic. count -- [inout] input the number of descriptor want to find, it will output the number of descriptor has been found in the gattc cache with the given characteristic. Returns ESP_OK: success other: failed esp_gatt_status_t esp_ble_gattc_get_descr_by_char_handle(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t char_handle, esp_bt_uuid_t descr_uuid, esp_gattc_descr_elem_t *result, uint16_t *count) Find the descriptor with the given characteristic handle in the gattc cache Note: It just get descriptor from local cache, won't get from remote devices. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. char_handle -- [in] the characteristic handle. descr_uuid -- [in] the descriptor uuid. result -- [out] The pointer to the descriptor in the given characteristic. count -- [inout] input the number of descriptor want to find, it will output the number of descriptor has been found in the gattc cache with the given characteristic. gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. char_handle -- [in] the characteristic handle. descr_uuid -- [in] the descriptor uuid. result -- [out] The pointer to the descriptor in the given characteristic. count -- [inout] input the number of descriptor want to find, it will output the number of descriptor has been found in the gattc cache with the given characteristic. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. char_handle -- [in] the characteristic handle. descr_uuid -- [in] the descriptor uuid. result -- [out] The pointer to the descriptor in the given characteristic. count -- [inout] input the number of descriptor want to find, it will output the number of descriptor has been found in the gattc cache with the given characteristic. Returns ESP_OK: success other: failed esp_gatt_status_t esp_ble_gattc_get_include_service(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, esp_bt_uuid_t *incl_uuid, esp_gattc_incl_svc_elem_t *result, uint16_t *count) Find the include service with the given service handle in the gattc cache Note: It just get include service from local cache, won't get from remote devices. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle incl_uuid -- [in] the include service uuid result -- [out] The pointer to the include service in the given service. count -- [inout] input the number of include service want to find, it will output the number of include service has been found in the gattc cache with the given service. gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle incl_uuid -- [in] the include service uuid result -- [out] The pointer to the include service in the given service. count -- [inout] input the number of include service want to find, it will output the number of include service has been found in the gattc cache with the given service. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle incl_uuid -- [in] the include service uuid result -- [out] The pointer to the include service in the given service. count -- [inout] input the number of include service want to find, it will output the number of include service has been found in the gattc cache with the given service. Returns ESP_OK: success other: failed esp_gatt_status_t esp_ble_gattc_get_attr_count(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_gatt_db_attr_type_t type, uint16_t start_handle, uint16_t end_handle, uint16_t char_handle, uint16_t *count) Find the attribute count with the given service or characteristic in the gattc cache. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. type -- [in] the attribute type. start_handle -- [in] the attribute start handle, if the type is ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore end_handle -- [in] the attribute end handle, if the type is ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore char_handle -- [in] the characteristic handle, this parameter valid when the type is ESP_GATT_DB_DESCRIPTOR. If the type isn't ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore. count -- [out] output the number of attribute has been found in the gattc cache with the given attribute type. gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. type -- [in] the attribute type. start_handle -- [in] the attribute start handle, if the type is ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore end_handle -- [in] the attribute end handle, if the type is ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore char_handle -- [in] the characteristic handle, this parameter valid when the type is ESP_GATT_DB_DESCRIPTOR. If the type isn't ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore. count -- [out] output the number of attribute has been found in the gattc cache with the given attribute type. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. type -- [in] the attribute type. start_handle -- [in] the attribute start handle, if the type is ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore end_handle -- [in] the attribute end handle, if the type is ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore char_handle -- [in] the characteristic handle, this parameter valid when the type is ESP_GATT_DB_DESCRIPTOR. If the type isn't ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore. count -- [out] output the number of attribute has been found in the gattc cache with the given attribute type. Returns ESP_OK: success other: failed esp_gatt_status_t esp_ble_gattc_get_db(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, esp_gattc_db_elem_t *db, uint16_t *count) This function is called to get the GATT database. Note: It just get attribute data base from local cache, won't get from remote devices. Parameters gattc_if -- [in] Gatt client access interface. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle conn_id -- [in] connection ID which identify the server. db -- [in] output parameter which will contain the GATT database copy. Caller is responsible for freeing it. count -- [in] number of elements in database. gattc_if -- [in] Gatt client access interface. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle conn_id -- [in] connection ID which identify the server. db -- [in] output parameter which will contain the GATT database copy. Caller is responsible for freeing it. count -- [in] number of elements in database. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle conn_id -- [in] connection ID which identify the server. db -- [in] output parameter which will contain the GATT database copy. Caller is responsible for freeing it. count -- [in] number of elements in database. Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_read_char(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle, esp_gatt_auth_req_t auth_req) This function is called to read a service's characteristics of the given characteristic handle. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteritic handle to read. auth_req -- [in] : authenticate request type gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteritic handle to read. auth_req -- [in] : authenticate request type gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteritic handle to read. auth_req -- [in] : authenticate request type Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_read_by_type(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, esp_bt_uuid_t *uuid, esp_gatt_auth_req_t auth_req) This function is called to read a service's characteristics of the given characteristic UUID. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. start_handle -- [in] : the attribute start handle. end_handle -- [in] : the attribute end handle uuid -- [in] : The UUID of attribute which will be read. auth_req -- [in] : authenticate request type gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. start_handle -- [in] : the attribute start handle. end_handle -- [in] : the attribute end handle uuid -- [in] : The UUID of attribute which will be read. auth_req -- [in] : authenticate request type gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. start_handle -- [in] : the attribute start handle. end_handle -- [in] : the attribute end handle uuid -- [in] : The UUID of attribute which will be read. auth_req -- [in] : authenticate request type Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_read_multiple(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_gattc_multi_t *read_multi, esp_gatt_auth_req_t auth_req) This function is called to read multiple characteristic or characteristic descriptors. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. read_multi -- [in] : pointer to the read multiple parameter. auth_req -- [in] : authenticate request type gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. read_multi -- [in] : pointer to the read multiple parameter. auth_req -- [in] : authenticate request type gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. read_multi -- [in] : pointer to the read multiple parameter. auth_req -- [in] : authenticate request type Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_read_multiple_variable(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_gattc_multi_t *read_multi, esp_gatt_auth_req_t auth_req) This function is called to read multiple variable length characteristic or characteristic descriptors. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. read_multi -- [in] : pointer to the read multiple parameter. auth_req -- [in] : authenticate request type gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. read_multi -- [in] : pointer to the read multiple parameter. auth_req -- [in] : authenticate request type gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. read_multi -- [in] : pointer to the read multiple parameter. auth_req -- [in] : authenticate request type Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_read_char_descr(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle, esp_gatt_auth_req_t auth_req) This function is called to read a characteristics descriptor. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : descriptor handle to read. auth_req -- [in] : authenticate request type gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : descriptor handle to read. auth_req -- [in] : authenticate request type gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : descriptor handle to read. auth_req -- [in] : authenticate request type Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_write_char(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle, uint16_t value_len, uint8_t *value, esp_gatt_write_type_t write_type, esp_gatt_auth_req_t auth_req) This function is called to write characteristic value. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteristic handle to write. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. write_type -- [in] : the type of attribute write operation. auth_req -- [in] : authentication request. gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteristic handle to write. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. write_type -- [in] : the type of attribute write operation. auth_req -- [in] : authentication request. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteristic handle to write. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. write_type -- [in] : the type of attribute write operation. auth_req -- [in] : authentication request. Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_write_char_descr(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle, uint16_t value_len, uint8_t *value, esp_gatt_write_type_t write_type, esp_gatt_auth_req_t auth_req) This function is called to write characteristic descriptor value. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID handle -- [in] : descriptor handle to write. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. write_type -- [in] : the type of attribute write operation. auth_req -- [in] : authentication request. gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID handle -- [in] : descriptor handle to write. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. write_type -- [in] : the type of attribute write operation. auth_req -- [in] : authentication request. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID handle -- [in] : descriptor handle to write. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. write_type -- [in] : the type of attribute write operation. auth_req -- [in] : authentication request. Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_prepare_write(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle, uint16_t offset, uint16_t value_len, uint8_t *value, esp_gatt_auth_req_t auth_req) This function is called to prepare write a characteristic value. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteristic handle to prepare write. offset -- [in] : offset of the write value. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. auth_req -- [in] : authentication request. gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteristic handle to prepare write. offset -- [in] : offset of the write value. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. auth_req -- [in] : authentication request. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteristic handle to prepare write. offset -- [in] : offset of the write value. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. auth_req -- [in] : authentication request. Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_prepare_write_char_descr(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle, uint16_t offset, uint16_t value_len, uint8_t *value, esp_gatt_auth_req_t auth_req) This function is called to prepare write a characteristic descriptor value. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteristic descriptor handle to prepare write. offset -- [in] : offset of the write value. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. auth_req -- [in] : authentication request. gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteristic descriptor handle to prepare write. offset -- [in] : offset of the write value. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. auth_req -- [in] : authentication request. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteristic descriptor handle to prepare write. offset -- [in] : offset of the write value. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. auth_req -- [in] : authentication request. Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_execute_write(esp_gatt_if_t gattc_if, uint16_t conn_id, bool is_execute) This function is called to execute write a prepare write sequence. Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. is_execute -- [in] : execute or cancel. gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. is_execute -- [in] : execute or cancel. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. is_execute -- [in] : execute or cancel. Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_register_for_notify(esp_gatt_if_t gattc_if, esp_bd_addr_t server_bda, uint16_t handle) This function is called to register for notification of a service. Parameters gattc_if -- [in] Gatt client access interface. server_bda -- [in] : target GATT server. handle -- [in] : GATT characteristic handle. gattc_if -- [in] Gatt client access interface. server_bda -- [in] : target GATT server. handle -- [in] : GATT characteristic handle. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: registration succeeds other: failed ESP_OK: registration succeeds other: failed ESP_OK: registration succeeds Parameters gattc_if -- [in] Gatt client access interface. server_bda -- [in] : target GATT server. handle -- [in] : GATT characteristic handle. Returns ESP_OK: registration succeeds other: failed esp_err_t esp_ble_gattc_unregister_for_notify(esp_gatt_if_t gattc_if, esp_bd_addr_t server_bda, uint16_t handle) This function is called to de-register for notification of a service. Parameters gattc_if -- [in] Gatt client access interface. server_bda -- [in] : target GATT server. handle -- [in] : GATT characteristic handle. gattc_if -- [in] Gatt client access interface. server_bda -- [in] : target GATT server. handle -- [in] : GATT characteristic handle. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: unregister succeeds other: failed ESP_OK: unregister succeeds other: failed ESP_OK: unregister succeeds Parameters gattc_if -- [in] Gatt client access interface. server_bda -- [in] : target GATT server. handle -- [in] : GATT characteristic handle. Returns ESP_OK: unregister succeeds other: failed esp_err_t esp_ble_gattc_cache_refresh(esp_bd_addr_t remote_bda) Refresh the server cache store in the gattc stack of the remote device. If the device is connected, this API will restart the discovery of service information of the remote device. Parameters remote_bda -- [in] remote device BD address. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters remote_bda -- [in] remote device BD address. Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_cache_assoc(esp_gatt_if_t gattc_if, esp_bd_addr_t src_addr, esp_bd_addr_t assoc_addr, bool is_assoc) Add or delete the associated address with the source address. Note: The role of this API is mainly when the client side has stored a server-side database, when it needs to connect another device, but the device's attribute database is the same as the server database stored on the client-side, calling this API can use the database that the device has stored used as the peer server database to reduce the attribute database search and discovery process and speed up the connection time. The associated address mains that device want to used the database has stored in the local cache. The source address mains that device want to share the database to the associated address device. Parameters gattc_if -- [in] Gatt client access interface. src_addr -- [in] the source address which provide the attribute table. assoc_addr -- [in] the associated device address which went to share the attribute table with the source address. is_assoc -- [in] true add the associated device address, false remove the associated device address. gattc_if -- [in] Gatt client access interface. src_addr -- [in] the source address which provide the attribute table. assoc_addr -- [in] the associated device address which went to share the attribute table with the source address. is_assoc -- [in] true add the associated device address, false remove the associated device address. gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. src_addr -- [in] the source address which provide the attribute table. assoc_addr -- [in] the associated device address which went to share the attribute table with the source address. is_assoc -- [in] true add the associated device address, false remove the associated device address. Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_cache_get_addr_list(esp_gatt_if_t gattc_if) Get the address list which has store the attribute table in the gattc cache. There will callback ESP_GATTC_GET_ADDR_LIST_EVT event when get address list complete. Parameters gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters gattc_if -- [in] Gatt client access interface. Returns ESP_OK: success other: failed esp_err_t esp_ble_gattc_cache_clean(esp_bd_addr_t remote_bda) Clean the service cache of this device in the gattc stack,. Parameters remote_bda -- [in] remote device BD address. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters remote_bda -- [in] remote device BD address. Returns ESP_OK: success other: failed Unions union esp_ble_gattc_cb_param_t #include <esp_gattc_api.h> Gatt client callback parameters union. Public Members struct esp_ble_gattc_cb_param_t::gattc_reg_evt_param reg Gatt client callback param of ESP_GATTC_REG_EVT struct esp_ble_gattc_cb_param_t::gattc_reg_evt_param reg Gatt client callback param of ESP_GATTC_REG_EVT struct esp_ble_gattc_cb_param_t::gattc_open_evt_param open Gatt client callback param of ESP_GATTC_OPEN_EVT struct esp_ble_gattc_cb_param_t::gattc_open_evt_param open Gatt client callback param of ESP_GATTC_OPEN_EVT struct esp_ble_gattc_cb_param_t::gattc_close_evt_param close Gatt client callback param of ESP_GATTC_CLOSE_EVT struct esp_ble_gattc_cb_param_t::gattc_close_evt_param close Gatt client callback param of ESP_GATTC_CLOSE_EVT struct esp_ble_gattc_cb_param_t::gattc_cfg_mtu_evt_param cfg_mtu Gatt client callback param of ESP_GATTC_CFG_MTU_EVT struct esp_ble_gattc_cb_param_t::gattc_cfg_mtu_evt_param cfg_mtu Gatt client callback param of ESP_GATTC_CFG_MTU_EVT struct esp_ble_gattc_cb_param_t::gattc_search_cmpl_evt_param search_cmpl Gatt client callback param of ESP_GATTC_SEARCH_CMPL_EVT struct esp_ble_gattc_cb_param_t::gattc_search_cmpl_evt_param search_cmpl Gatt client callback param of ESP_GATTC_SEARCH_CMPL_EVT struct esp_ble_gattc_cb_param_t::gattc_search_res_evt_param search_res Gatt client callback param of ESP_GATTC_SEARCH_RES_EVT struct esp_ble_gattc_cb_param_t::gattc_search_res_evt_param search_res Gatt client callback param of ESP_GATTC_SEARCH_RES_EVT struct esp_ble_gattc_cb_param_t::gattc_read_char_evt_param read Gatt client callback param of ESP_GATTC_READ_CHAR_EVT struct esp_ble_gattc_cb_param_t::gattc_read_char_evt_param read Gatt client callback param of ESP_GATTC_READ_CHAR_EVT struct esp_ble_gattc_cb_param_t::gattc_write_evt_param write Gatt client callback param of ESP_GATTC_WRITE_DESCR_EVT struct esp_ble_gattc_cb_param_t::gattc_write_evt_param write Gatt client callback param of ESP_GATTC_WRITE_DESCR_EVT struct esp_ble_gattc_cb_param_t::gattc_exec_cmpl_evt_param exec_cmpl Gatt client callback param of ESP_GATTC_EXEC_EVT struct esp_ble_gattc_cb_param_t::gattc_exec_cmpl_evt_param exec_cmpl Gatt client callback param of ESP_GATTC_EXEC_EVT struct esp_ble_gattc_cb_param_t::gattc_notify_evt_param notify Gatt client callback param of ESP_GATTC_NOTIFY_EVT struct esp_ble_gattc_cb_param_t::gattc_notify_evt_param notify Gatt client callback param of ESP_GATTC_NOTIFY_EVT struct esp_ble_gattc_cb_param_t::gattc_srvc_chg_evt_param srvc_chg Gatt client callback param of ESP_GATTC_SRVC_CHG_EVT struct esp_ble_gattc_cb_param_t::gattc_srvc_chg_evt_param srvc_chg Gatt client callback param of ESP_GATTC_SRVC_CHG_EVT struct esp_ble_gattc_cb_param_t::gattc_congest_evt_param congest Gatt client callback param of ESP_GATTC_CONGEST_EVT struct esp_ble_gattc_cb_param_t::gattc_congest_evt_param congest Gatt client callback param of ESP_GATTC_CONGEST_EVT struct esp_ble_gattc_cb_param_t::gattc_reg_for_notify_evt_param reg_for_notify Gatt client callback param of ESP_GATTC_REG_FOR_NOTIFY_EVT struct esp_ble_gattc_cb_param_t::gattc_reg_for_notify_evt_param reg_for_notify Gatt client callback param of ESP_GATTC_REG_FOR_NOTIFY_EVT struct esp_ble_gattc_cb_param_t::gattc_unreg_for_notify_evt_param unreg_for_notify Gatt client callback param of ESP_GATTC_UNREG_FOR_NOTIFY_EVT struct esp_ble_gattc_cb_param_t::gattc_unreg_for_notify_evt_param unreg_for_notify Gatt client callback param of ESP_GATTC_UNREG_FOR_NOTIFY_EVT struct esp_ble_gattc_cb_param_t::gattc_connect_evt_param connect Gatt client callback param of ESP_GATTC_CONNECT_EVT struct esp_ble_gattc_cb_param_t::gattc_connect_evt_param connect Gatt client callback param of ESP_GATTC_CONNECT_EVT struct esp_ble_gattc_cb_param_t::gattc_disconnect_evt_param disconnect Gatt client callback param of ESP_GATTC_DISCONNECT_EVT struct esp_ble_gattc_cb_param_t::gattc_disconnect_evt_param disconnect Gatt client callback param of ESP_GATTC_DISCONNECT_EVT struct esp_ble_gattc_cb_param_t::gattc_set_assoc_addr_cmp_evt_param set_assoc_cmp Gatt client callback param of ESP_GATTC_SET_ASSOC_EVT struct esp_ble_gattc_cb_param_t::gattc_set_assoc_addr_cmp_evt_param set_assoc_cmp Gatt client callback param of ESP_GATTC_SET_ASSOC_EVT struct esp_ble_gattc_cb_param_t::gattc_get_addr_list_evt_param get_addr_list Gatt client callback param of ESP_GATTC_GET_ADDR_LIST_EVT struct esp_ble_gattc_cb_param_t::gattc_get_addr_list_evt_param get_addr_list Gatt client callback param of ESP_GATTC_GET_ADDR_LIST_EVT struct esp_ble_gattc_cb_param_t::gattc_queue_full_evt_param queue_full Gatt client callback param of ESP_GATTC_QUEUE_FULL_EVT struct esp_ble_gattc_cb_param_t::gattc_queue_full_evt_param queue_full Gatt client callback param of ESP_GATTC_QUEUE_FULL_EVT struct esp_ble_gattc_cb_param_t::gattc_dis_srvc_cmpl_evt_param dis_srvc_cmpl Gatt client callback param of ESP_GATTC_DIS_SRVC_CMPL_EVT struct esp_ble_gattc_cb_param_t::gattc_dis_srvc_cmpl_evt_param dis_srvc_cmpl Gatt client callback param of ESP_GATTC_DIS_SRVC_CMPL_EVT struct gattc_cfg_mtu_evt_param #include <esp_gattc_api.h> ESP_GATTC_CFG_MTU_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t conn_id Connection id uint16_t conn_id Connection id uint16_t mtu MTU size uint16_t mtu MTU size esp_gatt_status_t status struct gattc_cfg_mtu_evt_param #include <esp_gattc_api.h> ESP_GATTC_CFG_MTU_EVT. Public Members esp_gatt_status_t status Operation status uint16_t conn_id Connection id uint16_t mtu MTU size struct gattc_close_evt_param #include <esp_gattc_api.h> ESP_GATTC_CLOSE_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t conn_id Connection id uint16_t conn_id Connection id esp_bd_addr_t remote_bda Remote bluetooth device address esp_bd_addr_t remote_bda Remote bluetooth device address esp_gatt_conn_reason_t reason The reason of gatt connection close esp_gatt_conn_reason_t reason The reason of gatt connection close esp_gatt_status_t status struct gattc_close_evt_param #include <esp_gattc_api.h> ESP_GATTC_CLOSE_EVT. Public Members esp_gatt_status_t status Operation status uint16_t conn_id Connection id esp_bd_addr_t remote_bda Remote bluetooth device address esp_gatt_conn_reason_t reason The reason of gatt connection close struct gattc_congest_evt_param #include <esp_gattc_api.h> ESP_GATTC_CONGEST_EVT. struct gattc_congest_evt_param #include <esp_gattc_api.h> ESP_GATTC_CONGEST_EVT. struct gattc_connect_evt_param #include <esp_gattc_api.h> ESP_GATTC_CONNECT_EVT. Public Members uint16_t conn_id Connection id uint16_t conn_id Connection id uint8_t link_role Link role : master role = 0 ; slave role = 1 uint8_t link_role Link role : master role = 0 ; slave role = 1 esp_bd_addr_t remote_bda Remote bluetooth device address esp_bd_addr_t remote_bda Remote bluetooth device address esp_gatt_conn_params_t conn_params current connection parameters esp_gatt_conn_params_t conn_params current connection parameters esp_ble_addr_type_t ble_addr_type Remote BLE device address type esp_ble_addr_type_t ble_addr_type Remote BLE device address type uint16_t conn_handle HCI connection handle uint16_t conn_handle HCI connection handle uint16_t conn_id struct gattc_connect_evt_param #include <esp_gattc_api.h> ESP_GATTC_CONNECT_EVT. Public Members uint16_t conn_id Connection id uint8_t link_role Link role : master role = 0 ; slave role = 1 esp_bd_addr_t remote_bda Remote bluetooth device address esp_gatt_conn_params_t conn_params current connection parameters esp_ble_addr_type_t ble_addr_type Remote BLE device address type uint16_t conn_handle HCI connection handle struct gattc_dis_srvc_cmpl_evt_param #include <esp_gattc_api.h> ESP_GATTC_DIS_SRVC_CMPL_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t conn_id Connection id uint16_t conn_id Connection id esp_gatt_status_t status struct gattc_dis_srvc_cmpl_evt_param #include <esp_gattc_api.h> ESP_GATTC_DIS_SRVC_CMPL_EVT. Public Members esp_gatt_status_t status Operation status uint16_t conn_id Connection id struct gattc_disconnect_evt_param #include <esp_gattc_api.h> ESP_GATTC_DISCONNECT_EVT. Public Members esp_gatt_conn_reason_t reason disconnection reason esp_gatt_conn_reason_t reason disconnection reason uint16_t conn_id Connection id uint16_t conn_id Connection id esp_bd_addr_t remote_bda Remote bluetooth device address esp_bd_addr_t remote_bda Remote bluetooth device address esp_gatt_conn_reason_t reason struct gattc_disconnect_evt_param #include <esp_gattc_api.h> ESP_GATTC_DISCONNECT_EVT. Public Members esp_gatt_conn_reason_t reason disconnection reason uint16_t conn_id Connection id esp_bd_addr_t remote_bda Remote bluetooth device address struct gattc_exec_cmpl_evt_param #include <esp_gattc_api.h> ESP_GATTC_EXEC_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t conn_id Connection id uint16_t conn_id Connection id esp_gatt_status_t status struct gattc_exec_cmpl_evt_param #include <esp_gattc_api.h> ESP_GATTC_EXEC_EVT. Public Members esp_gatt_status_t status Operation status uint16_t conn_id Connection id struct gattc_get_addr_list_evt_param #include <esp_gattc_api.h> ESP_GATTC_GET_ADDR_LIST_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint8_t num_addr The number of address in the gattc cache address list uint8_t num_addr The number of address in the gattc cache address list esp_bd_addr_t *addr_list The pointer to the address list which has been get from the gattc cache esp_bd_addr_t *addr_list The pointer to the address list which has been get from the gattc cache esp_gatt_status_t status struct gattc_get_addr_list_evt_param #include <esp_gattc_api.h> ESP_GATTC_GET_ADDR_LIST_EVT. Public Members esp_gatt_status_t status Operation status uint8_t num_addr The number of address in the gattc cache address list esp_bd_addr_t *addr_list The pointer to the address list which has been get from the gattc cache struct gattc_notify_evt_param #include <esp_gattc_api.h> ESP_GATTC_NOTIFY_EVT. struct gattc_notify_evt_param #include <esp_gattc_api.h> ESP_GATTC_NOTIFY_EVT. struct gattc_open_evt_param #include <esp_gattc_api.h> ESP_GATTC_OPEN_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t conn_id Connection id uint16_t conn_id Connection id esp_bd_addr_t remote_bda Remote bluetooth device address esp_bd_addr_t remote_bda Remote bluetooth device address uint16_t mtu MTU size uint16_t mtu MTU size esp_gatt_status_t status struct gattc_open_evt_param #include <esp_gattc_api.h> ESP_GATTC_OPEN_EVT. Public Members esp_gatt_status_t status Operation status uint16_t conn_id Connection id esp_bd_addr_t remote_bda Remote bluetooth device address uint16_t mtu MTU size struct gattc_queue_full_evt_param #include <esp_gattc_api.h> ESP_GATTC_QUEUE_FULL_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t conn_id Connection id uint16_t conn_id Connection id bool is_full The gattc command queue is full or not bool is_full The gattc command queue is full or not esp_gatt_status_t status struct gattc_queue_full_evt_param #include <esp_gattc_api.h> ESP_GATTC_QUEUE_FULL_EVT. Public Members esp_gatt_status_t status Operation status uint16_t conn_id Connection id bool is_full The gattc command queue is full or not struct gattc_read_char_evt_param #include <esp_gattc_api.h> ESP_GATTC_READ_CHAR_EVT, ESP_GATTC_READ_DESCR_EVT, ESP_GATTC_READ_MULTIPLE_EVT, ESP_GATTC_READ_MULTI_VAR_EVT. struct gattc_read_char_evt_param #include <esp_gattc_api.h> ESP_GATTC_READ_CHAR_EVT, ESP_GATTC_READ_DESCR_EVT, ESP_GATTC_READ_MULTIPLE_EVT, ESP_GATTC_READ_MULTI_VAR_EVT. struct gattc_reg_evt_param #include <esp_gattc_api.h> ESP_GATTC_REG_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t app_id Application id which input in register API uint16_t app_id Application id which input in register API esp_gatt_status_t status struct gattc_reg_evt_param #include <esp_gattc_api.h> ESP_GATTC_REG_EVT. Public Members esp_gatt_status_t status Operation status uint16_t app_id Application id which input in register API struct gattc_reg_for_notify_evt_param #include <esp_gattc_api.h> ESP_GATTC_REG_FOR_NOTIFY_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t handle The characteristic or descriptor handle uint16_t handle The characteristic or descriptor handle esp_gatt_status_t status struct gattc_reg_for_notify_evt_param #include <esp_gattc_api.h> ESP_GATTC_REG_FOR_NOTIFY_EVT. Public Members esp_gatt_status_t status Operation status uint16_t handle The characteristic or descriptor handle struct gattc_search_cmpl_evt_param #include <esp_gattc_api.h> ESP_GATTC_SEARCH_CMPL_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t conn_id Connection id uint16_t conn_id Connection id esp_service_source_t searched_service_source The source of the service information esp_service_source_t searched_service_source The source of the service information esp_gatt_status_t status struct gattc_search_cmpl_evt_param #include <esp_gattc_api.h> ESP_GATTC_SEARCH_CMPL_EVT. Public Members esp_gatt_status_t status Operation status uint16_t conn_id Connection id esp_service_source_t searched_service_source The source of the service information struct gattc_search_res_evt_param #include <esp_gattc_api.h> ESP_GATTC_SEARCH_RES_EVT. struct gattc_search_res_evt_param #include <esp_gattc_api.h> ESP_GATTC_SEARCH_RES_EVT. struct gattc_set_assoc_addr_cmp_evt_param #include <esp_gattc_api.h> ESP_GATTC_SET_ASSOC_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status esp_gatt_status_t status struct gattc_set_assoc_addr_cmp_evt_param #include <esp_gattc_api.h> ESP_GATTC_SET_ASSOC_EVT. Public Members esp_gatt_status_t status Operation status struct gattc_srvc_chg_evt_param #include <esp_gattc_api.h> ESP_GATTC_SRVC_CHG_EVT. Public Members esp_bd_addr_t remote_bda Remote bluetooth device address esp_bd_addr_t remote_bda Remote bluetooth device address esp_bd_addr_t remote_bda struct gattc_srvc_chg_evt_param #include <esp_gattc_api.h> ESP_GATTC_SRVC_CHG_EVT. Public Members esp_bd_addr_t remote_bda Remote bluetooth device address struct gattc_unreg_for_notify_evt_param #include <esp_gattc_api.h> ESP_GATTC_UNREG_FOR_NOTIFY_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t handle The characteristic or descriptor handle uint16_t handle The characteristic or descriptor handle esp_gatt_status_t status struct gattc_unreg_for_notify_evt_param #include <esp_gattc_api.h> ESP_GATTC_UNREG_FOR_NOTIFY_EVT. Public Members esp_gatt_status_t status Operation status uint16_t handle The characteristic or descriptor handle struct gattc_write_evt_param #include <esp_gattc_api.h> ESP_GATTC_WRITE_CHAR_EVT, ESP_GATTC_PREP_WRITE_EVT, ESP_GATTC_WRITE_DESCR_EVT. Public Members esp_gatt_status_t status Operation status esp_gatt_status_t status Operation status uint16_t conn_id Connection id uint16_t conn_id Connection id uint16_t handle The Characteristic or descriptor handle uint16_t handle The Characteristic or descriptor handle uint16_t offset The prepare write offset, this value is valid only when prepare write uint16_t offset The prepare write offset, this value is valid only when prepare write esp_gatt_status_t status struct gattc_write_evt_param #include <esp_gattc_api.h> ESP_GATTC_WRITE_CHAR_EVT, ESP_GATTC_PREP_WRITE_EVT, ESP_GATTC_WRITE_DESCR_EVT. Public Members esp_gatt_status_t status Operation status uint16_t conn_id Connection id uint16_t handle The Characteristic or descriptor handle uint16_t offset The prepare write offset, this value is valid only when prepare write struct esp_ble_gattc_cb_param_t::gattc_reg_evt_param reg Type Definitions typedef void (*esp_gattc_cb_t)(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) GATT Client callback function type. Param event : Event type Param gattc_if : GATT client access interface, normally different gattc_if correspond to different profile Param param : Point to callback parameter, currently is union type Param event : Event type Param gattc_if : GATT client access interface, normally different gattc_if correspond to different profile Param param : Point to callback parameter, currently is union type Enumerations enum esp_gattc_cb_event_t GATT Client callback function events. Values: enumerator ESP_GATTC_REG_EVT When GATT client is registered, the event comes enumerator ESP_GATTC_REG_EVT When GATT client is registered, the event comes enumerator ESP_GATTC_UNREG_EVT When GATT client is unregistered, the event comes enumerator ESP_GATTC_UNREG_EVT When GATT client is unregistered, the event comes enumerator ESP_GATTC_OPEN_EVT When GATT virtual connection is set up, the event comes enumerator ESP_GATTC_OPEN_EVT When GATT virtual connection is set up, the event comes enumerator ESP_GATTC_READ_CHAR_EVT When GATT characteristic is read, the event comes enumerator ESP_GATTC_READ_CHAR_EVT When GATT characteristic is read, the event comes enumerator ESP_GATTC_WRITE_CHAR_EVT When GATT characteristic write operation completes, the event comes enumerator ESP_GATTC_WRITE_CHAR_EVT When GATT characteristic write operation completes, the event comes enumerator ESP_GATTC_CLOSE_EVT When GATT virtual connection is closed, the event comes enumerator ESP_GATTC_CLOSE_EVT When GATT virtual connection is closed, the event comes enumerator ESP_GATTC_SEARCH_CMPL_EVT When GATT service discovery is completed, the event comes enumerator ESP_GATTC_SEARCH_CMPL_EVT When GATT service discovery is completed, the event comes enumerator ESP_GATTC_SEARCH_RES_EVT When GATT service discovery result is got, the event comes enumerator ESP_GATTC_SEARCH_RES_EVT When GATT service discovery result is got, the event comes enumerator ESP_GATTC_READ_DESCR_EVT When GATT characteristic descriptor read completes, the event comes enumerator ESP_GATTC_READ_DESCR_EVT When GATT characteristic descriptor read completes, the event comes enumerator ESP_GATTC_WRITE_DESCR_EVT When GATT characteristic descriptor write completes, the event comes enumerator ESP_GATTC_WRITE_DESCR_EVT When GATT characteristic descriptor write completes, the event comes enumerator ESP_GATTC_NOTIFY_EVT When GATT notification or indication arrives, the event comes enumerator ESP_GATTC_NOTIFY_EVT When GATT notification or indication arrives, the event comes enumerator ESP_GATTC_PREP_WRITE_EVT When GATT prepare-write operation completes, the event comes enumerator ESP_GATTC_PREP_WRITE_EVT When GATT prepare-write operation completes, the event comes enumerator ESP_GATTC_EXEC_EVT When write execution completes, the event comes enumerator ESP_GATTC_EXEC_EVT When write execution completes, the event comes enumerator ESP_GATTC_ACL_EVT When ACL connection is up, the event comes enumerator ESP_GATTC_ACL_EVT When ACL connection is up, the event comes enumerator ESP_GATTC_CANCEL_OPEN_EVT When GATT client ongoing connection is cancelled, the event comes enumerator ESP_GATTC_CANCEL_OPEN_EVT When GATT client ongoing connection is cancelled, the event comes enumerator ESP_GATTC_SRVC_CHG_EVT When "service changed" occurs, the event comes enumerator ESP_GATTC_SRVC_CHG_EVT When "service changed" occurs, the event comes enumerator ESP_GATTC_ENC_CMPL_CB_EVT When encryption procedure completes, the event comes enumerator ESP_GATTC_ENC_CMPL_CB_EVT When encryption procedure completes, the event comes enumerator ESP_GATTC_CFG_MTU_EVT When configuration of MTU completes, the event comes enumerator ESP_GATTC_CFG_MTU_EVT When configuration of MTU completes, the event comes enumerator ESP_GATTC_ADV_DATA_EVT When advertising of data, the event comes enumerator ESP_GATTC_ADV_DATA_EVT When advertising of data, the event comes enumerator ESP_GATTC_MULT_ADV_ENB_EVT When multi-advertising is enabled, the event comes enumerator ESP_GATTC_MULT_ADV_ENB_EVT When multi-advertising is enabled, the event comes enumerator ESP_GATTC_MULT_ADV_UPD_EVT When multi-advertising parameters are updated, the event comes enumerator ESP_GATTC_MULT_ADV_UPD_EVT When multi-advertising parameters are updated, the event comes enumerator ESP_GATTC_MULT_ADV_DATA_EVT When multi-advertising data arrives, the event comes enumerator ESP_GATTC_MULT_ADV_DATA_EVT When multi-advertising data arrives, the event comes enumerator ESP_GATTC_MULT_ADV_DIS_EVT When multi-advertising is disabled, the event comes enumerator ESP_GATTC_MULT_ADV_DIS_EVT When multi-advertising is disabled, the event comes enumerator ESP_GATTC_CONGEST_EVT When GATT connection congestion comes, the event comes enumerator ESP_GATTC_CONGEST_EVT When GATT connection congestion comes, the event comes enumerator ESP_GATTC_BTH_SCAN_ENB_EVT When batch scan is enabled, the event comes enumerator ESP_GATTC_BTH_SCAN_ENB_EVT When batch scan is enabled, the event comes enumerator ESP_GATTC_BTH_SCAN_CFG_EVT When batch scan storage is configured, the event comes enumerator ESP_GATTC_BTH_SCAN_CFG_EVT When batch scan storage is configured, the event comes enumerator ESP_GATTC_BTH_SCAN_RD_EVT When Batch scan read event is reported, the event comes enumerator ESP_GATTC_BTH_SCAN_RD_EVT When Batch scan read event is reported, the event comes enumerator ESP_GATTC_BTH_SCAN_THR_EVT When Batch scan threshold is set, the event comes enumerator ESP_GATTC_BTH_SCAN_THR_EVT When Batch scan threshold is set, the event comes enumerator ESP_GATTC_BTH_SCAN_PARAM_EVT When Batch scan parameters are set, the event comes enumerator ESP_GATTC_BTH_SCAN_PARAM_EVT When Batch scan parameters are set, the event comes enumerator ESP_GATTC_BTH_SCAN_DIS_EVT When Batch scan is disabled, the event comes enumerator ESP_GATTC_BTH_SCAN_DIS_EVT When Batch scan is disabled, the event comes enumerator ESP_GATTC_SCAN_FLT_CFG_EVT When Scan filter configuration completes, the event comes enumerator ESP_GATTC_SCAN_FLT_CFG_EVT When Scan filter configuration completes, the event comes enumerator ESP_GATTC_SCAN_FLT_PARAM_EVT When Scan filter parameters are set, the event comes enumerator ESP_GATTC_SCAN_FLT_PARAM_EVT When Scan filter parameters are set, the event comes enumerator ESP_GATTC_SCAN_FLT_STATUS_EVT When Scan filter status is reported, the event comes enumerator ESP_GATTC_SCAN_FLT_STATUS_EVT When Scan filter status is reported, the event comes enumerator ESP_GATTC_ADV_VSC_EVT When advertising vendor spec content event is reported, the event comes enumerator ESP_GATTC_ADV_VSC_EVT When advertising vendor spec content event is reported, the event comes enumerator ESP_GATTC_REG_FOR_NOTIFY_EVT When register for notification of a service completes, the event comes enumerator ESP_GATTC_REG_FOR_NOTIFY_EVT When register for notification of a service completes, the event comes enumerator ESP_GATTC_UNREG_FOR_NOTIFY_EVT When unregister for notification of a service completes, the event comes enumerator ESP_GATTC_UNREG_FOR_NOTIFY_EVT When unregister for notification of a service completes, the event comes enumerator ESP_GATTC_CONNECT_EVT When the ble physical connection is set up, the event comes enumerator ESP_GATTC_CONNECT_EVT When the ble physical connection is set up, the event comes enumerator ESP_GATTC_DISCONNECT_EVT When the ble physical connection disconnected, the event comes enumerator ESP_GATTC_DISCONNECT_EVT When the ble physical connection disconnected, the event comes enumerator ESP_GATTC_READ_MULTIPLE_EVT When the ble characteristic or descriptor multiple complete, the event comes enumerator ESP_GATTC_READ_MULTIPLE_EVT When the ble characteristic or descriptor multiple complete, the event comes enumerator ESP_GATTC_QUEUE_FULL_EVT When the gattc command queue full, the event comes enumerator ESP_GATTC_QUEUE_FULL_EVT When the gattc command queue full, the event comes enumerator ESP_GATTC_SET_ASSOC_EVT When the ble gattc set the associated address complete, the event comes enumerator ESP_GATTC_SET_ASSOC_EVT When the ble gattc set the associated address complete, the event comes enumerator ESP_GATTC_GET_ADDR_LIST_EVT When the ble get gattc address list in cache finish, the event comes enumerator ESP_GATTC_GET_ADDR_LIST_EVT When the ble get gattc address list in cache finish, the event comes enumerator ESP_GATTC_DIS_SRVC_CMPL_EVT When the ble discover service complete, the event comes enumerator ESP_GATTC_DIS_SRVC_CMPL_EVT When the ble discover service complete, the event comes enumerator ESP_GATTC_READ_MULTI_VAR_EVT When read multiple variable characteristic complete, the event comes enumerator ESP_GATTC_READ_MULTI_VAR_EVT When read multiple variable characteristic complete, the event comes enumerator ESP_GATTC_REG_EVT
GATT Client API Application Example Check bluetooth/bluedroid/ble folder in ESP-IDF examples, which contains the following demos and their tutorials: This is a GATT client demo and its tutorial. This demo can scan for devices, connect to the GATT server and discover its services. This is a multiple connection demo and its tutorial. This demo can connect to multiple GATT server devices and discover their services. This is a demo similar to Bluetooth® Low Energy (Bluetooth LE) SPP. This demo, which acts as a GATT client, can receive data from UART and then send the data to the peer device automatically. API Reference Header File components/bt/host/bluedroid/api/include/api/esp_gattc_api.h This header file can be included with: #include "esp_gattc_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_gattc_register_callback(esp_gattc_cb_t callback) This function is called to register application callbacks with GATTC module. - Parameters callback -- [in] : pointer to the application callback function. - Returns ESP_OK: success other: failed - - esp_gattc_cb_t esp_ble_gattc_get_callback(void) This function is called to get the current application callbacks with BTA GATTC module. - Returns esp_gattC_cb_t : current callback - - esp_err_t esp_ble_gattc_app_register(uint16_t app_id) This function is called to register application callbacks with GATTC module. - Parameters app_id -- [in] : Application Identify (UUID), for different application - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_app_unregister(esp_gatt_if_t gattc_if) This function is called to unregister an application from GATTC module. - Parameters gattc_if -- [in] Gatt client access interface. - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_open(esp_gatt_if_t gattc_if, esp_bd_addr_t remote_bda, esp_ble_addr_type_t remote_addr_type, bool is_direct) Open a direct connection or add a background auto connection. - Parameters gattc_if -- [in] Gatt client access interface. remote_bda -- [in] remote device bluetooth device address. remote_addr_type -- [in] remote device bluetooth device the address type. is_direct -- [in] direct connection or background auto connection(by now, background auto connection is not supported). - - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_aux_open(esp_gatt_if_t gattc_if, esp_bd_addr_t remote_bda, esp_ble_addr_type_t remote_addr_type, bool is_direct) - esp_err_t esp_ble_gattc_close(esp_gatt_if_t gattc_if, uint16_t conn_id) Close the virtual connection to the GATT server. gattc may have multiple virtual GATT server connections when multiple app_id registered, this API only close one virtual GATT server connection. if there exist other virtual GATT server connections, it does not disconnect the physical connection. if you want to disconnect the physical connection directly, you can use esp_ble_gap_disconnect(esp_bd_addr_t remote_device). - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID to be closed. - - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_send_mtu_req(esp_gatt_if_t gattc_if, uint16_t conn_id) Configure the MTU size in the GATT channel. This can be done only once per connection. Before using, use esp_ble_gatt_set_local_mtu() to configure the local MTU size. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID. - - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_search_service(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_bt_uuid_t *filter_uuid) This function is called to get service from local cache. This function report service search result by a callback event, and followed by a service search complete event. Note: 128-bit base UUID will automatically be converted to a 16-bit UUID in the search results. Other types of UUID remain unchanged. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID. filter_uuid -- [in] a UUID of the service application is interested in. If Null, discover for all services. - - Returns ESP_OK: success other: failed - - esp_gatt_status_t esp_ble_gattc_get_service(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_bt_uuid_t *svc_uuid, esp_gattc_service_elem_t *result, uint16_t *count, uint16_t offset) Find all the service with the given service uuid in the gattc cache, if the svc_uuid is NULL, find all the service. Note: It just get service from local cache, won't get from remote devices. If want to get it from remote device, need to used the esp_ble_gattc_cache_refresh, then call esp_ble_gattc_get_service again. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. svc_uuid -- [in] the pointer to the service uuid. result -- [out] The pointer to the service which has been found in the gattc cache. count -- [inout] input the number of service want to find, it will output the number of service has been found in the gattc cache with the given service uuid. offset -- [in] Offset of the service position to get. - - Returns ESP_OK: success other: failed - - esp_gatt_status_t esp_ble_gattc_get_all_char(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, esp_gattc_char_elem_t *result, uint16_t *count, uint16_t offset) Find all the characteristic with the given service in the gattc cache Note: It just get characteristic from local cache, won't get from remote devices. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle. end_handle -- [in] the attribute end handle result -- [out] The pointer to the characteristic in the service. count -- [inout] input the number of characteristic want to find, it will output the number of characteristic has been found in the gattc cache with the given service. offset -- [in] Offset of the characteristic position to get. - - Returns ESP_OK: success other: failed - - esp_gatt_status_t esp_ble_gattc_get_all_descr(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t char_handle, esp_gattc_descr_elem_t *result, uint16_t *count, uint16_t offset) Find all the descriptor with the given characteristic in the gattc cache Note: It just get descriptor from local cache, won't get from remote devices. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. char_handle -- [in] the given characteristic handle result -- [out] The pointer to the descriptor in the characteristic. count -- [inout] input the number of descriptor want to find, it will output the number of descriptor has been found in the gattc cache with the given characteristic. offset -- [in] Offset of the descriptor position to get. - - Returns ESP_OK: success other: failed - - esp_gatt_status_t esp_ble_gattc_get_char_by_uuid(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, esp_bt_uuid_t char_uuid, esp_gattc_char_elem_t *result, uint16_t *count) Find the characteristic with the given characteristic uuid in the gattc cache Note: It just get characteristic from local cache, won't get from remote devices. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle char_uuid -- [in] the characteristic uuid result -- [out] The pointer to the characteristic in the service. count -- [inout] input the number of characteristic want to find, it will output the number of characteristic has been found in the gattc cache with the given service. - - Returns ESP_OK: success other: failed - - esp_gatt_status_t esp_ble_gattc_get_descr_by_uuid(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, esp_bt_uuid_t char_uuid, esp_bt_uuid_t descr_uuid, esp_gattc_descr_elem_t *result, uint16_t *count) Find the descriptor with the given characteristic uuid in the gattc cache Note: It just get descriptor from local cache, won't get from remote devices. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle char_uuid -- [in] the characteristic uuid. descr_uuid -- [in] the descriptor uuid. result -- [out] The pointer to the descriptor in the given characteristic. count -- [inout] input the number of descriptor want to find, it will output the number of descriptor has been found in the gattc cache with the given characteristic. - - Returns ESP_OK: success other: failed - - esp_gatt_status_t esp_ble_gattc_get_descr_by_char_handle(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t char_handle, esp_bt_uuid_t descr_uuid, esp_gattc_descr_elem_t *result, uint16_t *count) Find the descriptor with the given characteristic handle in the gattc cache Note: It just get descriptor from local cache, won't get from remote devices. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. char_handle -- [in] the characteristic handle. descr_uuid -- [in] the descriptor uuid. result -- [out] The pointer to the descriptor in the given characteristic. count -- [inout] input the number of descriptor want to find, it will output the number of descriptor has been found in the gattc cache with the given characteristic. - - Returns ESP_OK: success other: failed - - esp_gatt_status_t esp_ble_gattc_get_include_service(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, esp_bt_uuid_t *incl_uuid, esp_gattc_incl_svc_elem_t *result, uint16_t *count) Find the include service with the given service handle in the gattc cache Note: It just get include service from local cache, won't get from remote devices. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle incl_uuid -- [in] the include service uuid result -- [out] The pointer to the include service in the given service. count -- [inout] input the number of include service want to find, it will output the number of include service has been found in the gattc cache with the given service. - - Returns ESP_OK: success other: failed - - esp_gatt_status_t esp_ble_gattc_get_attr_count(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_gatt_db_attr_type_t type, uint16_t start_handle, uint16_t end_handle, uint16_t char_handle, uint16_t *count) Find the attribute count with the given service or characteristic in the gattc cache. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] connection ID which identify the server. type -- [in] the attribute type. start_handle -- [in] the attribute start handle, if the type is ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore end_handle -- [in] the attribute end handle, if the type is ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore char_handle -- [in] the characteristic handle, this parameter valid when the type is ESP_GATT_DB_DESCRIPTOR. If the type isn't ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore. count -- [out] output the number of attribute has been found in the gattc cache with the given attribute type. - - Returns ESP_OK: success other: failed - - esp_gatt_status_t esp_ble_gattc_get_db(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, esp_gattc_db_elem_t *db, uint16_t *count) This function is called to get the GATT database. Note: It just get attribute data base from local cache, won't get from remote devices. - Parameters gattc_if -- [in] Gatt client access interface. start_handle -- [in] the attribute start handle end_handle -- [in] the attribute end handle conn_id -- [in] connection ID which identify the server. db -- [in] output parameter which will contain the GATT database copy. Caller is responsible for freeing it. count -- [in] number of elements in database. - - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_read_char(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle, esp_gatt_auth_req_t auth_req) This function is called to read a service's characteristics of the given characteristic handle. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteritic handle to read. auth_req -- [in] : authenticate request type - - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_read_by_type(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, esp_bt_uuid_t *uuid, esp_gatt_auth_req_t auth_req) This function is called to read a service's characteristics of the given characteristic UUID. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. start_handle -- [in] : the attribute start handle. end_handle -- [in] : the attribute end handle uuid -- [in] : The UUID of attribute which will be read. auth_req -- [in] : authenticate request type - - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_read_multiple(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_gattc_multi_t *read_multi, esp_gatt_auth_req_t auth_req) This function is called to read multiple characteristic or characteristic descriptors. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. read_multi -- [in] : pointer to the read multiple parameter. auth_req -- [in] : authenticate request type - - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_read_multiple_variable(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_gattc_multi_t *read_multi, esp_gatt_auth_req_t auth_req) This function is called to read multiple variable length characteristic or characteristic descriptors. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. read_multi -- [in] : pointer to the read multiple parameter. auth_req -- [in] : authenticate request type - - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_read_char_descr(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle, esp_gatt_auth_req_t auth_req) This function is called to read a characteristics descriptor. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : descriptor handle to read. auth_req -- [in] : authenticate request type - - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_write_char(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle, uint16_t value_len, uint8_t *value, esp_gatt_write_type_t write_type, esp_gatt_auth_req_t auth_req) This function is called to write characteristic value. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteristic handle to write. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. write_type -- [in] : the type of attribute write operation. auth_req -- [in] : authentication request. - - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_write_char_descr(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle, uint16_t value_len, uint8_t *value, esp_gatt_write_type_t write_type, esp_gatt_auth_req_t auth_req) This function is called to write characteristic descriptor value. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID handle -- [in] : descriptor handle to write. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. write_type -- [in] : the type of attribute write operation. auth_req -- [in] : authentication request. - - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_prepare_write(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle, uint16_t offset, uint16_t value_len, uint8_t *value, esp_gatt_auth_req_t auth_req) This function is called to prepare write a characteristic value. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteristic handle to prepare write. offset -- [in] : offset of the write value. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. auth_req -- [in] : authentication request. - - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_prepare_write_char_descr(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle, uint16_t offset, uint16_t value_len, uint8_t *value, esp_gatt_auth_req_t auth_req) This function is called to prepare write a characteristic descriptor value. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. handle -- [in] : characteristic descriptor handle to prepare write. offset -- [in] : offset of the write value. value_len -- [in] length of the value to be written. value -- [in] : the value to be written. auth_req -- [in] : authentication request. - - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_execute_write(esp_gatt_if_t gattc_if, uint16_t conn_id, bool is_execute) This function is called to execute write a prepare write sequence. - Parameters gattc_if -- [in] Gatt client access interface. conn_id -- [in] : connection ID. is_execute -- [in] : execute or cancel. - - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_register_for_notify(esp_gatt_if_t gattc_if, esp_bd_addr_t server_bda, uint16_t handle) This function is called to register for notification of a service. - Parameters gattc_if -- [in] Gatt client access interface. server_bda -- [in] : target GATT server. handle -- [in] : GATT characteristic handle. - - Returns ESP_OK: registration succeeds other: failed - - esp_err_t esp_ble_gattc_unregister_for_notify(esp_gatt_if_t gattc_if, esp_bd_addr_t server_bda, uint16_t handle) This function is called to de-register for notification of a service. - Parameters gattc_if -- [in] Gatt client access interface. server_bda -- [in] : target GATT server. handle -- [in] : GATT characteristic handle. - - Returns ESP_OK: unregister succeeds other: failed - - esp_err_t esp_ble_gattc_cache_refresh(esp_bd_addr_t remote_bda) Refresh the server cache store in the gattc stack of the remote device. If the device is connected, this API will restart the discovery of service information of the remote device. - Parameters remote_bda -- [in] remote device BD address. - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_cache_assoc(esp_gatt_if_t gattc_if, esp_bd_addr_t src_addr, esp_bd_addr_t assoc_addr, bool is_assoc) Add or delete the associated address with the source address. Note: The role of this API is mainly when the client side has stored a server-side database, when it needs to connect another device, but the device's attribute database is the same as the server database stored on the client-side, calling this API can use the database that the device has stored used as the peer server database to reduce the attribute database search and discovery process and speed up the connection time. The associated address mains that device want to used the database has stored in the local cache. The source address mains that device want to share the database to the associated address device. - Parameters gattc_if -- [in] Gatt client access interface. src_addr -- [in] the source address which provide the attribute table. assoc_addr -- [in] the associated device address which went to share the attribute table with the source address. is_assoc -- [in] true add the associated device address, false remove the associated device address. - - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_cache_get_addr_list(esp_gatt_if_t gattc_if) Get the address list which has store the attribute table in the gattc cache. There will callback ESP_GATTC_GET_ADDR_LIST_EVT event when get address list complete. - Parameters gattc_if -- [in] Gatt client access interface. - Returns ESP_OK: success other: failed - - esp_err_t esp_ble_gattc_cache_clean(esp_bd_addr_t remote_bda) Clean the service cache of this device in the gattc stack,. - Parameters remote_bda -- [in] remote device BD address. - Returns ESP_OK: success other: failed - Unions - union esp_ble_gattc_cb_param_t - #include <esp_gattc_api.h> Gatt client callback parameters union. Public Members - struct esp_ble_gattc_cb_param_t::gattc_reg_evt_param reg Gatt client callback param of ESP_GATTC_REG_EVT - struct esp_ble_gattc_cb_param_t::gattc_open_evt_param open Gatt client callback param of ESP_GATTC_OPEN_EVT - struct esp_ble_gattc_cb_param_t::gattc_close_evt_param close Gatt client callback param of ESP_GATTC_CLOSE_EVT - struct esp_ble_gattc_cb_param_t::gattc_cfg_mtu_evt_param cfg_mtu Gatt client callback param of ESP_GATTC_CFG_MTU_EVT - struct esp_ble_gattc_cb_param_t::gattc_search_cmpl_evt_param search_cmpl Gatt client callback param of ESP_GATTC_SEARCH_CMPL_EVT - struct esp_ble_gattc_cb_param_t::gattc_search_res_evt_param search_res Gatt client callback param of ESP_GATTC_SEARCH_RES_EVT - struct esp_ble_gattc_cb_param_t::gattc_read_char_evt_param read Gatt client callback param of ESP_GATTC_READ_CHAR_EVT - struct esp_ble_gattc_cb_param_t::gattc_write_evt_param write Gatt client callback param of ESP_GATTC_WRITE_DESCR_EVT - struct esp_ble_gattc_cb_param_t::gattc_exec_cmpl_evt_param exec_cmpl Gatt client callback param of ESP_GATTC_EXEC_EVT - struct esp_ble_gattc_cb_param_t::gattc_notify_evt_param notify Gatt client callback param of ESP_GATTC_NOTIFY_EVT - struct esp_ble_gattc_cb_param_t::gattc_srvc_chg_evt_param srvc_chg Gatt client callback param of ESP_GATTC_SRVC_CHG_EVT - struct esp_ble_gattc_cb_param_t::gattc_congest_evt_param congest Gatt client callback param of ESP_GATTC_CONGEST_EVT - struct esp_ble_gattc_cb_param_t::gattc_reg_for_notify_evt_param reg_for_notify Gatt client callback param of ESP_GATTC_REG_FOR_NOTIFY_EVT - struct esp_ble_gattc_cb_param_t::gattc_unreg_for_notify_evt_param unreg_for_notify Gatt client callback param of ESP_GATTC_UNREG_FOR_NOTIFY_EVT - struct esp_ble_gattc_cb_param_t::gattc_connect_evt_param connect Gatt client callback param of ESP_GATTC_CONNECT_EVT - struct esp_ble_gattc_cb_param_t::gattc_disconnect_evt_param disconnect Gatt client callback param of ESP_GATTC_DISCONNECT_EVT - struct esp_ble_gattc_cb_param_t::gattc_set_assoc_addr_cmp_evt_param set_assoc_cmp Gatt client callback param of ESP_GATTC_SET_ASSOC_EVT - struct esp_ble_gattc_cb_param_t::gattc_get_addr_list_evt_param get_addr_list Gatt client callback param of ESP_GATTC_GET_ADDR_LIST_EVT - struct esp_ble_gattc_cb_param_t::gattc_queue_full_evt_param queue_full Gatt client callback param of ESP_GATTC_QUEUE_FULL_EVT - struct esp_ble_gattc_cb_param_t::gattc_dis_srvc_cmpl_evt_param dis_srvc_cmpl Gatt client callback param of ESP_GATTC_DIS_SRVC_CMPL_EVT - struct gattc_cfg_mtu_evt_param - #include <esp_gattc_api.h> ESP_GATTC_CFG_MTU_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t conn_id Connection id - uint16_t mtu MTU size - esp_gatt_status_t status - struct gattc_close_evt_param - #include <esp_gattc_api.h> ESP_GATTC_CLOSE_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t conn_id Connection id - esp_bd_addr_t remote_bda Remote bluetooth device address - esp_gatt_conn_reason_t reason The reason of gatt connection close - esp_gatt_status_t status - struct gattc_congest_evt_param - #include <esp_gattc_api.h> ESP_GATTC_CONGEST_EVT. - struct gattc_connect_evt_param - #include <esp_gattc_api.h> ESP_GATTC_CONNECT_EVT. Public Members - uint16_t conn_id Connection id - uint8_t link_role Link role : master role = 0 ; slave role = 1 - esp_bd_addr_t remote_bda Remote bluetooth device address - esp_gatt_conn_params_t conn_params current connection parameters - esp_ble_addr_type_t ble_addr_type Remote BLE device address type - uint16_t conn_handle HCI connection handle - uint16_t conn_id - struct gattc_dis_srvc_cmpl_evt_param - #include <esp_gattc_api.h> ESP_GATTC_DIS_SRVC_CMPL_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t conn_id Connection id - esp_gatt_status_t status - struct gattc_disconnect_evt_param - #include <esp_gattc_api.h> ESP_GATTC_DISCONNECT_EVT. Public Members - esp_gatt_conn_reason_t reason disconnection reason - uint16_t conn_id Connection id - esp_bd_addr_t remote_bda Remote bluetooth device address - esp_gatt_conn_reason_t reason - struct gattc_exec_cmpl_evt_param - #include <esp_gattc_api.h> ESP_GATTC_EXEC_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t conn_id Connection id - esp_gatt_status_t status - struct gattc_get_addr_list_evt_param - #include <esp_gattc_api.h> ESP_GATTC_GET_ADDR_LIST_EVT. Public Members - esp_gatt_status_t status Operation status - uint8_t num_addr The number of address in the gattc cache address list - esp_bd_addr_t *addr_list The pointer to the address list which has been get from the gattc cache - esp_gatt_status_t status - struct gattc_notify_evt_param - #include <esp_gattc_api.h> ESP_GATTC_NOTIFY_EVT. - struct gattc_open_evt_param - #include <esp_gattc_api.h> ESP_GATTC_OPEN_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t conn_id Connection id - esp_bd_addr_t remote_bda Remote bluetooth device address - uint16_t mtu MTU size - esp_gatt_status_t status - struct gattc_queue_full_evt_param - #include <esp_gattc_api.h> ESP_GATTC_QUEUE_FULL_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t conn_id Connection id - bool is_full The gattc command queue is full or not - esp_gatt_status_t status - struct gattc_read_char_evt_param - #include <esp_gattc_api.h> ESP_GATTC_READ_CHAR_EVT, ESP_GATTC_READ_DESCR_EVT, ESP_GATTC_READ_MULTIPLE_EVT, ESP_GATTC_READ_MULTI_VAR_EVT. - struct gattc_reg_evt_param - #include <esp_gattc_api.h> ESP_GATTC_REG_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t app_id Application id which input in register API - esp_gatt_status_t status - struct gattc_reg_for_notify_evt_param - #include <esp_gattc_api.h> ESP_GATTC_REG_FOR_NOTIFY_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t handle The characteristic or descriptor handle - esp_gatt_status_t status - struct gattc_search_cmpl_evt_param - #include <esp_gattc_api.h> ESP_GATTC_SEARCH_CMPL_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t conn_id Connection id - esp_service_source_t searched_service_source The source of the service information - esp_gatt_status_t status - struct gattc_search_res_evt_param - #include <esp_gattc_api.h> ESP_GATTC_SEARCH_RES_EVT. - struct gattc_set_assoc_addr_cmp_evt_param - #include <esp_gattc_api.h> ESP_GATTC_SET_ASSOC_EVT. Public Members - esp_gatt_status_t status Operation status - esp_gatt_status_t status - struct gattc_srvc_chg_evt_param - #include <esp_gattc_api.h> ESP_GATTC_SRVC_CHG_EVT. Public Members - esp_bd_addr_t remote_bda Remote bluetooth device address - esp_bd_addr_t remote_bda - struct gattc_unreg_for_notify_evt_param - #include <esp_gattc_api.h> ESP_GATTC_UNREG_FOR_NOTIFY_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t handle The characteristic or descriptor handle - esp_gatt_status_t status - struct gattc_write_evt_param - #include <esp_gattc_api.h> ESP_GATTC_WRITE_CHAR_EVT, ESP_GATTC_PREP_WRITE_EVT, ESP_GATTC_WRITE_DESCR_EVT. Public Members - esp_gatt_status_t status Operation status - uint16_t conn_id Connection id - uint16_t handle The Characteristic or descriptor handle - uint16_t offset The prepare write offset, this value is valid only when prepare write - esp_gatt_status_t status - struct esp_ble_gattc_cb_param_t::gattc_reg_evt_param reg Type Definitions - typedef void (*esp_gattc_cb_t)(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) GATT Client callback function type. - Param event : Event type - Param gattc_if : GATT client access interface, normally different gattc_if correspond to different profile - Param param : Point to callback parameter, currently is union type Enumerations - enum esp_gattc_cb_event_t GATT Client callback function events. Values: - enumerator ESP_GATTC_REG_EVT When GATT client is registered, the event comes - enumerator ESP_GATTC_UNREG_EVT When GATT client is unregistered, the event comes - enumerator ESP_GATTC_OPEN_EVT When GATT virtual connection is set up, the event comes - enumerator ESP_GATTC_READ_CHAR_EVT When GATT characteristic is read, the event comes - enumerator ESP_GATTC_WRITE_CHAR_EVT When GATT characteristic write operation completes, the event comes - enumerator ESP_GATTC_CLOSE_EVT When GATT virtual connection is closed, the event comes - enumerator ESP_GATTC_SEARCH_CMPL_EVT When GATT service discovery is completed, the event comes - enumerator ESP_GATTC_SEARCH_RES_EVT When GATT service discovery result is got, the event comes - enumerator ESP_GATTC_READ_DESCR_EVT When GATT characteristic descriptor read completes, the event comes - enumerator ESP_GATTC_WRITE_DESCR_EVT When GATT characteristic descriptor write completes, the event comes - enumerator ESP_GATTC_NOTIFY_EVT When GATT notification or indication arrives, the event comes - enumerator ESP_GATTC_PREP_WRITE_EVT When GATT prepare-write operation completes, the event comes - enumerator ESP_GATTC_EXEC_EVT When write execution completes, the event comes - enumerator ESP_GATTC_ACL_EVT When ACL connection is up, the event comes - enumerator ESP_GATTC_CANCEL_OPEN_EVT When GATT client ongoing connection is cancelled, the event comes - enumerator ESP_GATTC_SRVC_CHG_EVT When "service changed" occurs, the event comes - enumerator ESP_GATTC_ENC_CMPL_CB_EVT When encryption procedure completes, the event comes - enumerator ESP_GATTC_CFG_MTU_EVT When configuration of MTU completes, the event comes - enumerator ESP_GATTC_ADV_DATA_EVT When advertising of data, the event comes - enumerator ESP_GATTC_MULT_ADV_ENB_EVT When multi-advertising is enabled, the event comes - enumerator ESP_GATTC_MULT_ADV_UPD_EVT When multi-advertising parameters are updated, the event comes - enumerator ESP_GATTC_MULT_ADV_DATA_EVT When multi-advertising data arrives, the event comes - enumerator ESP_GATTC_MULT_ADV_DIS_EVT When multi-advertising is disabled, the event comes - enumerator ESP_GATTC_CONGEST_EVT When GATT connection congestion comes, the event comes - enumerator ESP_GATTC_BTH_SCAN_ENB_EVT When batch scan is enabled, the event comes - enumerator ESP_GATTC_BTH_SCAN_CFG_EVT When batch scan storage is configured, the event comes - enumerator ESP_GATTC_BTH_SCAN_RD_EVT When Batch scan read event is reported, the event comes - enumerator ESP_GATTC_BTH_SCAN_THR_EVT When Batch scan threshold is set, the event comes - enumerator ESP_GATTC_BTH_SCAN_PARAM_EVT When Batch scan parameters are set, the event comes - enumerator ESP_GATTC_BTH_SCAN_DIS_EVT When Batch scan is disabled, the event comes - enumerator ESP_GATTC_SCAN_FLT_CFG_EVT When Scan filter configuration completes, the event comes - enumerator ESP_GATTC_SCAN_FLT_PARAM_EVT When Scan filter parameters are set, the event comes - enumerator ESP_GATTC_SCAN_FLT_STATUS_EVT When Scan filter status is reported, the event comes - enumerator ESP_GATTC_ADV_VSC_EVT When advertising vendor spec content event is reported, the event comes - enumerator ESP_GATTC_REG_FOR_NOTIFY_EVT When register for notification of a service completes, the event comes - enumerator ESP_GATTC_UNREG_FOR_NOTIFY_EVT When unregister for notification of a service completes, the event comes - enumerator ESP_GATTC_CONNECT_EVT When the ble physical connection is set up, the event comes - enumerator ESP_GATTC_DISCONNECT_EVT When the ble physical connection disconnected, the event comes - enumerator ESP_GATTC_READ_MULTIPLE_EVT When the ble characteristic or descriptor multiple complete, the event comes - enumerator ESP_GATTC_QUEUE_FULL_EVT When the gattc command queue full, the event comes - enumerator ESP_GATTC_SET_ASSOC_EVT When the ble gattc set the associated address complete, the event comes - enumerator ESP_GATTC_GET_ADDR_LIST_EVT When the ble get gattc address list in cache finish, the event comes - enumerator ESP_GATTC_DIS_SRVC_CMPL_EVT When the ble discover service complete, the event comes - enumerator ESP_GATTC_READ_MULTI_VAR_EVT When read multiple variable characteristic complete, the event comes - enumerator ESP_GATTC_REG_EVT
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_gattc.html
ESP-IDF Programming Guide v5.2.1 documentation
null
BluFi API
null
espressif.com
2016-01-01
4eb8a65da20ba941
null
null
BluFi API Overview BluFi is a profile based GATT to config ESP32 Wi-Fi to connect/disconnect AP or setup a softap and etc. Use should concern these things: The event sent from profile. Then you need to do something as the event indicate. Security reference. You can write your own Security functions such as symmetrical encryption/decryption and checksum functions. Even you can define the "Key Exchange/Negotiation" procedure. Application Example Check bluetooth folder in ESP-IDF examples, which contains the following application: This is the BluFi demo. This demo can set ESP32's Wi-Fi to softap/station/softap&station mode and config Wi-Fi connections - bluetooth/blufi API Reference Header File This header file can be included with: #include "esp_blufi_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_blufi_register_callbacks(esp_blufi_callbacks_t *callbacks) This function is called to receive blufi callback event. Parameters callbacks -- [in] callback functions Returns ESP_OK - success, other - failed Parameters callbacks -- [in] callback functions Returns ESP_OK - success, other - failed esp_err_t esp_blufi_profile_init(void) This function is called to initialize blufi_profile. Returns ESP_OK - success, other - failed Returns ESP_OK - success, other - failed esp_err_t esp_blufi_profile_deinit(void) This function is called to de-initialize blufi_profile. Returns ESP_OK - success, other - failed Returns ESP_OK - success, other - failed esp_err_t esp_blufi_send_wifi_conn_report(wifi_mode_t opmode, esp_blufi_sta_conn_state_t sta_conn_state, uint8_t softap_conn_num, esp_blufi_extra_info_t *extra_info) This function is called to send wifi connection report. Parameters opmode -- : wifi opmode sta_conn_state -- : station is already in connection or not softap_conn_num -- : softap connection number extra_info -- : extra information, such as sta_ssid, softap_ssid and etc. opmode -- : wifi opmode sta_conn_state -- : station is already in connection or not softap_conn_num -- : softap connection number extra_info -- : extra information, such as sta_ssid, softap_ssid and etc. opmode -- : wifi opmode Returns ESP_OK - success, other - failed Parameters opmode -- : wifi opmode sta_conn_state -- : station is already in connection or not softap_conn_num -- : softap connection number extra_info -- : extra information, such as sta_ssid, softap_ssid and etc. Returns ESP_OK - success, other - failed esp_err_t esp_blufi_send_wifi_list(uint16_t apCount, esp_blufi_ap_record_t *list) This function is called to send wifi list. Parameters apCount -- : wifi list count list -- : wifi list apCount -- : wifi list count list -- : wifi list apCount -- : wifi list count Returns ESP_OK - success, other - failed Parameters apCount -- : wifi list count list -- : wifi list Returns ESP_OK - success, other - failed uint16_t esp_blufi_get_version(void) Get BLUFI profile version. Returns Most 8bit significant is Great version, Least 8bit is Sub version Returns Most 8bit significant is Great version, Least 8bit is Sub version esp_err_t esp_blufi_send_error_info(esp_blufi_error_state_t state) This function is called to send blufi error information. Parameters state -- : error state Returns ESP_OK - success, other - failed Parameters state -- : error state Returns ESP_OK - success, other - failed Unions union esp_blufi_cb_param_t #include <esp_blufi_api.h> BLUFI callback parameters union. Public Members struct esp_blufi_cb_param_t::blufi_init_finish_evt_param init_finish Blufi callback param of ESP_BLUFI_EVENT_INIT_FINISH struct esp_blufi_cb_param_t::blufi_init_finish_evt_param init_finish Blufi callback param of ESP_BLUFI_EVENT_INIT_FINISH struct esp_blufi_cb_param_t::blufi_deinit_finish_evt_param deinit_finish Blufi callback param of ESP_BLUFI_EVENT_DEINIT_FINISH struct esp_blufi_cb_param_t::blufi_deinit_finish_evt_param deinit_finish Blufi callback param of ESP_BLUFI_EVENT_DEINIT_FINISH struct esp_blufi_cb_param_t::blufi_set_wifi_mode_evt_param wifi_mode Blufi callback param of ESP_BLUFI_EVENT_INIT_FINISH struct esp_blufi_cb_param_t::blufi_set_wifi_mode_evt_param wifi_mode Blufi callback param of ESP_BLUFI_EVENT_INIT_FINISH struct esp_blufi_cb_param_t::blufi_connect_evt_param connect Blufi callback param of ESP_BLUFI_EVENT_CONNECT struct esp_blufi_cb_param_t::blufi_connect_evt_param connect Blufi callback param of ESP_BLUFI_EVENT_CONNECT struct esp_blufi_cb_param_t::blufi_disconnect_evt_param disconnect Blufi callback param of ESP_BLUFI_EVENT_DISCONNECT struct esp_blufi_cb_param_t::blufi_disconnect_evt_param disconnect Blufi callback param of ESP_BLUFI_EVENT_DISCONNECT struct esp_blufi_cb_param_t::blufi_recv_sta_bssid_evt_param sta_bssid Blufi callback param of ESP_BLUFI_EVENT_RECV_STA_BSSID struct esp_blufi_cb_param_t::blufi_recv_sta_bssid_evt_param sta_bssid Blufi callback param of ESP_BLUFI_EVENT_RECV_STA_BSSID struct esp_blufi_cb_param_t::blufi_recv_sta_ssid_evt_param sta_ssid Blufi callback param of ESP_BLUFI_EVENT_RECV_STA_SSID struct esp_blufi_cb_param_t::blufi_recv_sta_ssid_evt_param sta_ssid Blufi callback param of ESP_BLUFI_EVENT_RECV_STA_SSID struct esp_blufi_cb_param_t::blufi_recv_sta_passwd_evt_param sta_passwd Blufi callback param of ESP_BLUFI_EVENT_RECV_STA_PASSWD struct esp_blufi_cb_param_t::blufi_recv_sta_passwd_evt_param sta_passwd Blufi callback param of ESP_BLUFI_EVENT_RECV_STA_PASSWD struct esp_blufi_cb_param_t::blufi_recv_softap_ssid_evt_param softap_ssid Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_SSID struct esp_blufi_cb_param_t::blufi_recv_softap_ssid_evt_param softap_ssid Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_SSID struct esp_blufi_cb_param_t::blufi_recv_softap_passwd_evt_param softap_passwd Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD struct esp_blufi_cb_param_t::blufi_recv_softap_passwd_evt_param softap_passwd Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD struct esp_blufi_cb_param_t::blufi_recv_softap_max_conn_num_evt_param softap_max_conn_num Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM struct esp_blufi_cb_param_t::blufi_recv_softap_max_conn_num_evt_param softap_max_conn_num Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM struct esp_blufi_cb_param_t::blufi_recv_softap_auth_mode_evt_param softap_auth_mode Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE struct esp_blufi_cb_param_t::blufi_recv_softap_auth_mode_evt_param softap_auth_mode Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE struct esp_blufi_cb_param_t::blufi_recv_softap_channel_evt_param softap_channel Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL struct esp_blufi_cb_param_t::blufi_recv_softap_channel_evt_param softap_channel Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL struct esp_blufi_cb_param_t::blufi_recv_username_evt_param username Blufi callback param of ESP_BLUFI_EVENT_RECV_USERNAME struct esp_blufi_cb_param_t::blufi_recv_username_evt_param username Blufi callback param of ESP_BLUFI_EVENT_RECV_USERNAME struct esp_blufi_cb_param_t::blufi_recv_ca_evt_param ca Blufi callback param of ESP_BLUFI_EVENT_RECV_CA_CERT struct esp_blufi_cb_param_t::blufi_recv_ca_evt_param ca Blufi callback param of ESP_BLUFI_EVENT_RECV_CA_CERT struct esp_blufi_cb_param_t::blufi_recv_client_cert_evt_param client_cert Blufi callback param of ESP_BLUFI_EVENT_RECV_CLIENT_CERT struct esp_blufi_cb_param_t::blufi_recv_client_cert_evt_param client_cert Blufi callback param of ESP_BLUFI_EVENT_RECV_CLIENT_CERT struct esp_blufi_cb_param_t::blufi_recv_server_cert_evt_param server_cert Blufi callback param of ESP_BLUFI_EVENT_RECV_SERVER_CERT struct esp_blufi_cb_param_t::blufi_recv_server_cert_evt_param server_cert Blufi callback param of ESP_BLUFI_EVENT_RECV_SERVER_CERT struct esp_blufi_cb_param_t::blufi_recv_client_pkey_evt_param client_pkey Blufi callback param of ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY struct esp_blufi_cb_param_t::blufi_recv_client_pkey_evt_param client_pkey Blufi callback param of ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY struct esp_blufi_cb_param_t::blufi_recv_server_pkey_evt_param server_pkey Blufi callback param of ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY struct esp_blufi_cb_param_t::blufi_recv_server_pkey_evt_param server_pkey Blufi callback param of ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY struct esp_blufi_cb_param_t::blufi_get_error_evt_param report_error Blufi callback param of ESP_BLUFI_EVENT_REPORT_ERROR struct esp_blufi_cb_param_t::blufi_get_error_evt_param report_error Blufi callback param of ESP_BLUFI_EVENT_REPORT_ERROR struct esp_blufi_cb_param_t::blufi_recv_custom_data_evt_param custom_data Blufi callback param of ESP_BLUFI_EVENT_RECV_CUSTOM_DATA struct esp_blufi_cb_param_t::blufi_recv_custom_data_evt_param custom_data Blufi callback param of ESP_BLUFI_EVENT_RECV_CUSTOM_DATA struct blufi_connect_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_CONNECT. Public Members esp_blufi_bd_addr_t remote_bda Blufi Remote bluetooth device address esp_blufi_bd_addr_t remote_bda Blufi Remote bluetooth device address uint8_t server_if server interface uint8_t server_if server interface uint16_t conn_id Connection id uint16_t conn_id Connection id esp_blufi_bd_addr_t remote_bda struct blufi_connect_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_CONNECT. Public Members esp_blufi_bd_addr_t remote_bda Blufi Remote bluetooth device address uint8_t server_if server interface uint16_t conn_id Connection id struct blufi_deinit_finish_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_DEINIT_FINISH. Public Members esp_blufi_deinit_state_t state De-initial status esp_blufi_deinit_state_t state De-initial status esp_blufi_deinit_state_t state struct blufi_deinit_finish_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_DEINIT_FINISH. Public Members esp_blufi_deinit_state_t state De-initial status struct blufi_disconnect_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_DISCONNECT. Public Members esp_blufi_bd_addr_t remote_bda Blufi Remote bluetooth device address esp_blufi_bd_addr_t remote_bda Blufi Remote bluetooth device address esp_blufi_bd_addr_t remote_bda struct blufi_disconnect_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_DISCONNECT. Public Members esp_blufi_bd_addr_t remote_bda Blufi Remote bluetooth device address struct blufi_get_error_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_REPORT_ERROR. Public Members esp_blufi_error_state_t state Blufi error state esp_blufi_error_state_t state Blufi error state esp_blufi_error_state_t state struct blufi_get_error_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_REPORT_ERROR. Public Members esp_blufi_error_state_t state Blufi error state struct blufi_init_finish_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_INIT_FINISH. Public Members esp_blufi_init_state_t state Initial status esp_blufi_init_state_t state Initial status esp_blufi_init_state_t state struct blufi_init_finish_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_INIT_FINISH. Public Members esp_blufi_init_state_t state Initial status struct blufi_recv_ca_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CA_CERT. struct blufi_recv_ca_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CA_CERT. struct blufi_recv_client_cert_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CLIENT_CERT struct blufi_recv_client_cert_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CLIENT_CERT struct blufi_recv_client_pkey_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY struct blufi_recv_client_pkey_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY struct blufi_recv_custom_data_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CUSTOM_DATA. struct blufi_recv_custom_data_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CUSTOM_DATA. struct blufi_recv_server_cert_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SERVER_CERT struct blufi_recv_server_cert_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SERVER_CERT struct blufi_recv_server_pkey_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY struct blufi_recv_server_pkey_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY struct blufi_recv_softap_auth_mode_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE. Public Members wifi_auth_mode_t auth_mode Authentication mode wifi_auth_mode_t auth_mode Authentication mode wifi_auth_mode_t auth_mode struct blufi_recv_softap_auth_mode_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE. Public Members wifi_auth_mode_t auth_mode Authentication mode struct blufi_recv_softap_channel_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL. Public Members uint8_t channel Authentication mode uint8_t channel Authentication mode uint8_t channel struct blufi_recv_softap_channel_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL. Public Members uint8_t channel Authentication mode struct blufi_recv_softap_max_conn_num_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM. Public Members int max_conn_num SSID int max_conn_num SSID int max_conn_num struct blufi_recv_softap_max_conn_num_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM. Public Members int max_conn_num SSID struct blufi_recv_softap_passwd_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD. struct blufi_recv_softap_passwd_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD. struct blufi_recv_softap_ssid_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_SSID. struct blufi_recv_softap_ssid_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_SSID. struct blufi_recv_sta_bssid_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_STA_BSSID. Public Members uint8_t bssid[6] BSSID uint8_t bssid[6] BSSID uint8_t bssid[6] struct blufi_recv_sta_bssid_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_STA_BSSID. Public Members uint8_t bssid[6] BSSID struct blufi_recv_sta_passwd_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_STA_PASSWD. struct blufi_recv_sta_passwd_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_STA_PASSWD. struct blufi_recv_sta_ssid_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_STA_SSID. struct blufi_recv_sta_ssid_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_STA_SSID. struct blufi_recv_username_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_USERNAME. struct blufi_recv_username_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_USERNAME. struct blufi_set_wifi_mode_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_SET_WIFI_MODE. Public Members wifi_mode_t op_mode Wifi operation mode wifi_mode_t op_mode Wifi operation mode wifi_mode_t op_mode struct blufi_set_wifi_mode_evt_param #include <esp_blufi_api.h> ESP_BLUFI_EVENT_SET_WIFI_MODE. Public Members wifi_mode_t op_mode Wifi operation mode struct esp_blufi_cb_param_t::blufi_init_finish_evt_param init_finish Structures struct esp_blufi_extra_info_t BLUFI extra information structure. Public Members uint8_t sta_bssid[6] BSSID of station interface uint8_t sta_bssid[6] BSSID of station interface bool sta_bssid_set is BSSID of station interface set bool sta_bssid_set is BSSID of station interface set uint8_t *sta_ssid SSID of station interface uint8_t *sta_ssid SSID of station interface int sta_ssid_len length of SSID of station interface int sta_ssid_len length of SSID of station interface uint8_t *sta_passwd password of station interface uint8_t *sta_passwd password of station interface int sta_passwd_len length of password of station interface int sta_passwd_len length of password of station interface uint8_t *softap_ssid SSID of softap interface uint8_t *softap_ssid SSID of softap interface int softap_ssid_len length of SSID of softap interface int softap_ssid_len length of SSID of softap interface uint8_t *softap_passwd password of station interface uint8_t *softap_passwd password of station interface int softap_passwd_len length of password of station interface int softap_passwd_len length of password of station interface uint8_t softap_authmode authentication mode of softap interface uint8_t softap_authmode authentication mode of softap interface bool softap_authmode_set is authentication mode of softap interface set bool softap_authmode_set is authentication mode of softap interface set uint8_t softap_max_conn_num max connection number of softap interface uint8_t softap_max_conn_num max connection number of softap interface bool softap_max_conn_num_set is max connection number of softap interface set bool softap_max_conn_num_set is max connection number of softap interface set uint8_t softap_channel channel of softap interface uint8_t softap_channel channel of softap interface bool softap_channel_set is channel of softap interface set bool softap_channel_set is channel of softap interface set uint8_t sta_max_conn_retry max retry of sta establish connection uint8_t sta_max_conn_retry max retry of sta establish connection bool sta_max_conn_retry_set is max retry of sta establish connection set bool sta_max_conn_retry_set is max retry of sta establish connection set uint8_t sta_conn_end_reason reason of sta connection end uint8_t sta_conn_end_reason reason of sta connection end bool sta_conn_end_reason_set is reason of sta connection end set bool sta_conn_end_reason_set is reason of sta connection end set int8_t sta_conn_rssi rssi of sta connection int8_t sta_conn_rssi rssi of sta connection bool sta_conn_rssi_set is rssi of sta connection set bool sta_conn_rssi_set is rssi of sta connection set uint8_t sta_bssid[6] struct esp_blufi_ap_record_t Description of an WiFi AP. struct esp_blufi_callbacks_t BLUFI callback functions type. Public Members esp_blufi_event_cb_t event_cb BLUFI event callback esp_blufi_event_cb_t event_cb BLUFI event callback esp_blufi_negotiate_data_handler_t negotiate_data_handler BLUFI negotiate data function for negotiate share key esp_blufi_negotiate_data_handler_t negotiate_data_handler BLUFI negotiate data function for negotiate share key esp_blufi_encrypt_func_t encrypt_func BLUFI encrypt data function with share key generated by negotiate_data_handler esp_blufi_encrypt_func_t encrypt_func BLUFI encrypt data function with share key generated by negotiate_data_handler esp_blufi_decrypt_func_t decrypt_func BLUFI decrypt data function with share key generated by negotiate_data_handler esp_blufi_decrypt_func_t decrypt_func BLUFI decrypt data function with share key generated by negotiate_data_handler esp_blufi_checksum_func_t checksum_func BLUFI check sum function (FCS) esp_blufi_checksum_func_t checksum_func BLUFI check sum function (FCS) esp_blufi_event_cb_t event_cb Macros ESP_BLUFI_BD_ADDR_LEN Bluetooth address length. Type Definitions typedef uint8_t esp_blufi_bd_addr_t[ESP_BLUFI_BD_ADDR_LEN] Bluetooth device address. typedef void (*esp_blufi_event_cb_t)(esp_blufi_cb_event_t event, esp_blufi_cb_param_t *param) BLUFI event callback function type. Param event : Event type Param param : Point to callback parameter, currently is union type Param event : Event type Param param : Point to callback parameter, currently is union type typedef void (*esp_blufi_negotiate_data_handler_t)(uint8_t *data, int len, uint8_t **output_data, int *output_len, bool *need_free) BLUFI negotiate data handler. Param data : data from phone Param len : length of data from phone Param output_data : data want to send to phone Param output_len : length of data want to send to phone Param need_free : output reporting if memory needs to be freed or not * Param data : data from phone Param len : length of data from phone Param output_data : data want to send to phone Param output_len : length of data want to send to phone Param need_free : output reporting if memory needs to be freed or not * typedef int (*esp_blufi_encrypt_func_t)(uint8_t iv8, uint8_t *crypt_data, int crypt_len) BLUFI encrypt the data after negotiate a share key. Param iv8 : initial vector(8bit), normally, blufi core will input packet sequence number Param crypt_data : plain text and encrypted data, the encrypt function must support autochthonous encrypt Param crypt_len : length of plain text Return Nonnegative number is encrypted length, if error, return negative number; Param iv8 : initial vector(8bit), normally, blufi core will input packet sequence number Param crypt_data : plain text and encrypted data, the encrypt function must support autochthonous encrypt Param crypt_len : length of plain text Return Nonnegative number is encrypted length, if error, return negative number; typedef int (*esp_blufi_decrypt_func_t)(uint8_t iv8, uint8_t *crypt_data, int crypt_len) BLUFI decrypt the data after negotiate a share key. Param iv8 : initial vector(8bit), normally, blufi core will input packet sequence number Param crypt_data : encrypted data and plain text, the encrypt function must support autochthonous decrypt Param crypt_len : length of encrypted text Return Nonnegative number is decrypted length, if error, return negative number; Param iv8 : initial vector(8bit), normally, blufi core will input packet sequence number Param crypt_data : encrypted data and plain text, the encrypt function must support autochthonous decrypt Param crypt_len : length of encrypted text Return Nonnegative number is decrypted length, if error, return negative number; typedef uint16_t (*esp_blufi_checksum_func_t)(uint8_t iv8, uint8_t *data, int len) BLUFI checksum. Param iv8 : initial vector(8bit), normally, blufi core will input packet sequence number Param data : data need to checksum Param len : length of data Param iv8 : initial vector(8bit), normally, blufi core will input packet sequence number Param data : data need to checksum Param len : length of data Enumerations enum esp_blufi_cb_event_t Values: enumerator ESP_BLUFI_EVENT_INIT_FINISH enumerator ESP_BLUFI_EVENT_INIT_FINISH enumerator ESP_BLUFI_EVENT_DEINIT_FINISH enumerator ESP_BLUFI_EVENT_DEINIT_FINISH enumerator ESP_BLUFI_EVENT_SET_WIFI_OPMODE enumerator ESP_BLUFI_EVENT_SET_WIFI_OPMODE enumerator ESP_BLUFI_EVENT_BLE_CONNECT enumerator ESP_BLUFI_EVENT_BLE_CONNECT enumerator ESP_BLUFI_EVENT_BLE_DISCONNECT enumerator ESP_BLUFI_EVENT_BLE_DISCONNECT enumerator ESP_BLUFI_EVENT_REQ_CONNECT_TO_AP enumerator ESP_BLUFI_EVENT_REQ_CONNECT_TO_AP enumerator ESP_BLUFI_EVENT_REQ_DISCONNECT_FROM_AP enumerator ESP_BLUFI_EVENT_REQ_DISCONNECT_FROM_AP enumerator ESP_BLUFI_EVENT_GET_WIFI_STATUS enumerator ESP_BLUFI_EVENT_GET_WIFI_STATUS enumerator ESP_BLUFI_EVENT_DEAUTHENTICATE_STA enumerator ESP_BLUFI_EVENT_DEAUTHENTICATE_STA enumerator ESP_BLUFI_EVENT_RECV_STA_BSSID enumerator ESP_BLUFI_EVENT_RECV_STA_BSSID enumerator ESP_BLUFI_EVENT_RECV_STA_SSID enumerator ESP_BLUFI_EVENT_RECV_STA_SSID enumerator ESP_BLUFI_EVENT_RECV_STA_PASSWD enumerator ESP_BLUFI_EVENT_RECV_STA_PASSWD enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_SSID enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_SSID enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL enumerator ESP_BLUFI_EVENT_RECV_USERNAME enumerator ESP_BLUFI_EVENT_RECV_USERNAME enumerator ESP_BLUFI_EVENT_RECV_CA_CERT enumerator ESP_BLUFI_EVENT_RECV_CA_CERT enumerator ESP_BLUFI_EVENT_RECV_CLIENT_CERT enumerator ESP_BLUFI_EVENT_RECV_CLIENT_CERT enumerator ESP_BLUFI_EVENT_RECV_SERVER_CERT enumerator ESP_BLUFI_EVENT_RECV_SERVER_CERT enumerator ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY enumerator ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY enumerator ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY enumerator ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY enumerator ESP_BLUFI_EVENT_RECV_SLAVE_DISCONNECT_BLE enumerator ESP_BLUFI_EVENT_RECV_SLAVE_DISCONNECT_BLE enumerator ESP_BLUFI_EVENT_GET_WIFI_LIST enumerator ESP_BLUFI_EVENT_GET_WIFI_LIST enumerator ESP_BLUFI_EVENT_REPORT_ERROR enumerator ESP_BLUFI_EVENT_REPORT_ERROR enumerator ESP_BLUFI_EVENT_RECV_CUSTOM_DATA enumerator ESP_BLUFI_EVENT_RECV_CUSTOM_DATA enumerator ESP_BLUFI_EVENT_INIT_FINISH enum esp_blufi_sta_conn_state_t BLUFI config status. Values: enumerator ESP_BLUFI_STA_CONN_SUCCESS enumerator ESP_BLUFI_STA_CONN_SUCCESS enumerator ESP_BLUFI_STA_CONN_FAIL enumerator ESP_BLUFI_STA_CONN_FAIL enumerator ESP_BLUFI_STA_CONNECTING enumerator ESP_BLUFI_STA_CONNECTING enumerator ESP_BLUFI_STA_NO_IP enumerator ESP_BLUFI_STA_NO_IP enumerator ESP_BLUFI_STA_CONN_SUCCESS enum esp_blufi_init_state_t BLUFI init status. Values: enumerator ESP_BLUFI_INIT_OK enumerator ESP_BLUFI_INIT_OK enumerator ESP_BLUFI_INIT_FAILED enumerator ESP_BLUFI_INIT_FAILED enumerator ESP_BLUFI_INIT_OK enum esp_blufi_deinit_state_t BLUFI deinit status. Values: enumerator ESP_BLUFI_DEINIT_OK enumerator ESP_BLUFI_DEINIT_OK enumerator ESP_BLUFI_DEINIT_FAILED enumerator ESP_BLUFI_DEINIT_FAILED enumerator ESP_BLUFI_DEINIT_OK enum esp_blufi_error_state_t Values: enumerator ESP_BLUFI_SEQUENCE_ERROR enumerator ESP_BLUFI_SEQUENCE_ERROR enumerator ESP_BLUFI_CHECKSUM_ERROR enumerator ESP_BLUFI_CHECKSUM_ERROR enumerator ESP_BLUFI_DECRYPT_ERROR enumerator ESP_BLUFI_DECRYPT_ERROR enumerator ESP_BLUFI_ENCRYPT_ERROR enumerator ESP_BLUFI_ENCRYPT_ERROR enumerator ESP_BLUFI_INIT_SECURITY_ERROR enumerator ESP_BLUFI_INIT_SECURITY_ERROR enumerator ESP_BLUFI_DH_MALLOC_ERROR enumerator ESP_BLUFI_DH_MALLOC_ERROR enumerator ESP_BLUFI_DH_PARAM_ERROR enumerator ESP_BLUFI_DH_PARAM_ERROR enumerator ESP_BLUFI_READ_PARAM_ERROR enumerator ESP_BLUFI_READ_PARAM_ERROR enumerator ESP_BLUFI_MAKE_PUBLIC_ERROR enumerator ESP_BLUFI_MAKE_PUBLIC_ERROR enumerator ESP_BLUFI_DATA_FORMAT_ERROR enumerator ESP_BLUFI_DATA_FORMAT_ERROR enumerator ESP_BLUFI_CALC_MD5_ERROR enumerator ESP_BLUFI_CALC_MD5_ERROR enumerator ESP_BLUFI_WIFI_SCAN_FAIL enumerator ESP_BLUFI_WIFI_SCAN_FAIL enumerator ESP_BLUFI_MSG_STATE_ERROR enumerator ESP_BLUFI_MSG_STATE_ERROR enumerator ESP_BLUFI_SEQUENCE_ERROR
BluFi API Overview BluFi is a profile based GATT to config ESP32 Wi-Fi to connect/disconnect AP or setup a softap and etc. Use should concern these things: The event sent from profile. Then you need to do something as the event indicate. Security reference. You can write your own Security functions such as symmetrical encryption/decryption and checksum functions. Even you can define the "Key Exchange/Negotiation" procedure. Application Example Check bluetooth folder in ESP-IDF examples, which contains the following application: This is the BluFi demo. This demo can set ESP32's Wi-Fi to softap/station/softap&station mode and config Wi-Fi connections - bluetooth/blufi API Reference Header File This header file can be included with: #include "esp_blufi_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_blufi_register_callbacks(esp_blufi_callbacks_t *callbacks) This function is called to receive blufi callback event. - Parameters callbacks -- [in] callback functions - Returns ESP_OK - success, other - failed - esp_err_t esp_blufi_profile_init(void) This function is called to initialize blufi_profile. - Returns ESP_OK - success, other - failed - esp_err_t esp_blufi_profile_deinit(void) This function is called to de-initialize blufi_profile. - Returns ESP_OK - success, other - failed - esp_err_t esp_blufi_send_wifi_conn_report(wifi_mode_t opmode, esp_blufi_sta_conn_state_t sta_conn_state, uint8_t softap_conn_num, esp_blufi_extra_info_t *extra_info) This function is called to send wifi connection report. - Parameters opmode -- : wifi opmode sta_conn_state -- : station is already in connection or not softap_conn_num -- : softap connection number extra_info -- : extra information, such as sta_ssid, softap_ssid and etc. - - Returns ESP_OK - success, other - failed - esp_err_t esp_blufi_send_wifi_list(uint16_t apCount, esp_blufi_ap_record_t *list) This function is called to send wifi list. - Parameters apCount -- : wifi list count list -- : wifi list - - Returns ESP_OK - success, other - failed - uint16_t esp_blufi_get_version(void) Get BLUFI profile version. - Returns Most 8bit significant is Great version, Least 8bit is Sub version - esp_err_t esp_blufi_send_error_info(esp_blufi_error_state_t state) This function is called to send blufi error information. - Parameters state -- : error state - Returns ESP_OK - success, other - failed Unions - union esp_blufi_cb_param_t - #include <esp_blufi_api.h> BLUFI callback parameters union. Public Members - struct esp_blufi_cb_param_t::blufi_init_finish_evt_param init_finish Blufi callback param of ESP_BLUFI_EVENT_INIT_FINISH - struct esp_blufi_cb_param_t::blufi_deinit_finish_evt_param deinit_finish Blufi callback param of ESP_BLUFI_EVENT_DEINIT_FINISH - struct esp_blufi_cb_param_t::blufi_set_wifi_mode_evt_param wifi_mode Blufi callback param of ESP_BLUFI_EVENT_INIT_FINISH - struct esp_blufi_cb_param_t::blufi_connect_evt_param connect Blufi callback param of ESP_BLUFI_EVENT_CONNECT - struct esp_blufi_cb_param_t::blufi_disconnect_evt_param disconnect Blufi callback param of ESP_BLUFI_EVENT_DISCONNECT - struct esp_blufi_cb_param_t::blufi_recv_sta_bssid_evt_param sta_bssid Blufi callback param of ESP_BLUFI_EVENT_RECV_STA_BSSID - struct esp_blufi_cb_param_t::blufi_recv_sta_ssid_evt_param sta_ssid Blufi callback param of ESP_BLUFI_EVENT_RECV_STA_SSID - struct esp_blufi_cb_param_t::blufi_recv_sta_passwd_evt_param sta_passwd Blufi callback param of ESP_BLUFI_EVENT_RECV_STA_PASSWD - struct esp_blufi_cb_param_t::blufi_recv_softap_ssid_evt_param softap_ssid Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_SSID - struct esp_blufi_cb_param_t::blufi_recv_softap_passwd_evt_param softap_passwd Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD - struct esp_blufi_cb_param_t::blufi_recv_softap_max_conn_num_evt_param softap_max_conn_num Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM - struct esp_blufi_cb_param_t::blufi_recv_softap_auth_mode_evt_param softap_auth_mode Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE - struct esp_blufi_cb_param_t::blufi_recv_softap_channel_evt_param softap_channel Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL - struct esp_blufi_cb_param_t::blufi_recv_username_evt_param username Blufi callback param of ESP_BLUFI_EVENT_RECV_USERNAME - struct esp_blufi_cb_param_t::blufi_recv_ca_evt_param ca Blufi callback param of ESP_BLUFI_EVENT_RECV_CA_CERT - struct esp_blufi_cb_param_t::blufi_recv_client_cert_evt_param client_cert Blufi callback param of ESP_BLUFI_EVENT_RECV_CLIENT_CERT - struct esp_blufi_cb_param_t::blufi_recv_server_cert_evt_param server_cert Blufi callback param of ESP_BLUFI_EVENT_RECV_SERVER_CERT - struct esp_blufi_cb_param_t::blufi_recv_client_pkey_evt_param client_pkey Blufi callback param of ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY - struct esp_blufi_cb_param_t::blufi_recv_server_pkey_evt_param server_pkey Blufi callback param of ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY - struct esp_blufi_cb_param_t::blufi_get_error_evt_param report_error Blufi callback param of ESP_BLUFI_EVENT_REPORT_ERROR - struct esp_blufi_cb_param_t::blufi_recv_custom_data_evt_param custom_data Blufi callback param of ESP_BLUFI_EVENT_RECV_CUSTOM_DATA - struct blufi_connect_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_CONNECT. Public Members - esp_blufi_bd_addr_t remote_bda Blufi Remote bluetooth device address - uint8_t server_if server interface - uint16_t conn_id Connection id - esp_blufi_bd_addr_t remote_bda - struct blufi_deinit_finish_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_DEINIT_FINISH. Public Members - esp_blufi_deinit_state_t state De-initial status - esp_blufi_deinit_state_t state - struct blufi_disconnect_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_DISCONNECT. Public Members - esp_blufi_bd_addr_t remote_bda Blufi Remote bluetooth device address - esp_blufi_bd_addr_t remote_bda - struct blufi_get_error_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_REPORT_ERROR. Public Members - esp_blufi_error_state_t state Blufi error state - esp_blufi_error_state_t state - struct blufi_init_finish_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_INIT_FINISH. Public Members - esp_blufi_init_state_t state Initial status - esp_blufi_init_state_t state - struct blufi_recv_ca_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CA_CERT. - struct blufi_recv_client_cert_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CLIENT_CERT - struct blufi_recv_client_pkey_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY - struct blufi_recv_custom_data_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CUSTOM_DATA. - struct blufi_recv_server_cert_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SERVER_CERT - struct blufi_recv_server_pkey_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY - struct blufi_recv_softap_auth_mode_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE. Public Members - wifi_auth_mode_t auth_mode Authentication mode - wifi_auth_mode_t auth_mode - struct blufi_recv_softap_channel_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL. Public Members - uint8_t channel Authentication mode - uint8_t channel - struct blufi_recv_softap_max_conn_num_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM. Public Members - int max_conn_num SSID - int max_conn_num - struct blufi_recv_softap_passwd_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD. - struct blufi_recv_softap_ssid_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_SSID. - struct blufi_recv_sta_bssid_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_STA_BSSID. Public Members - uint8_t bssid[6] BSSID - uint8_t bssid[6] - struct blufi_recv_sta_passwd_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_STA_PASSWD. - struct blufi_recv_sta_ssid_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_STA_SSID. - struct blufi_recv_username_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_USERNAME. - struct blufi_set_wifi_mode_evt_param - #include <esp_blufi_api.h> ESP_BLUFI_EVENT_SET_WIFI_MODE. Public Members - wifi_mode_t op_mode Wifi operation mode - wifi_mode_t op_mode - struct esp_blufi_cb_param_t::blufi_init_finish_evt_param init_finish Structures - struct esp_blufi_extra_info_t BLUFI extra information structure. Public Members - uint8_t sta_bssid[6] BSSID of station interface - bool sta_bssid_set is BSSID of station interface set - uint8_t *sta_ssid SSID of station interface - int sta_ssid_len length of SSID of station interface - uint8_t *sta_passwd password of station interface - int sta_passwd_len length of password of station interface - uint8_t *softap_ssid SSID of softap interface - int softap_ssid_len length of SSID of softap interface - uint8_t *softap_passwd password of station interface - int softap_passwd_len length of password of station interface - uint8_t softap_authmode authentication mode of softap interface - bool softap_authmode_set is authentication mode of softap interface set - uint8_t softap_max_conn_num max connection number of softap interface - bool softap_max_conn_num_set is max connection number of softap interface set - uint8_t softap_channel channel of softap interface - bool softap_channel_set is channel of softap interface set - uint8_t sta_max_conn_retry max retry of sta establish connection - bool sta_max_conn_retry_set is max retry of sta establish connection set - uint8_t sta_conn_end_reason reason of sta connection end - bool sta_conn_end_reason_set is reason of sta connection end set - int8_t sta_conn_rssi rssi of sta connection - bool sta_conn_rssi_set is rssi of sta connection set - uint8_t sta_bssid[6] - struct esp_blufi_ap_record_t Description of an WiFi AP. - struct esp_blufi_callbacks_t BLUFI callback functions type. Public Members - esp_blufi_event_cb_t event_cb BLUFI event callback - esp_blufi_negotiate_data_handler_t negotiate_data_handler BLUFI negotiate data function for negotiate share key - esp_blufi_encrypt_func_t encrypt_func BLUFI encrypt data function with share key generated by negotiate_data_handler - esp_blufi_decrypt_func_t decrypt_func BLUFI decrypt data function with share key generated by negotiate_data_handler - esp_blufi_checksum_func_t checksum_func BLUFI check sum function (FCS) - esp_blufi_event_cb_t event_cb Macros - ESP_BLUFI_BD_ADDR_LEN Bluetooth address length. Type Definitions - typedef uint8_t esp_blufi_bd_addr_t[ESP_BLUFI_BD_ADDR_LEN] Bluetooth device address. - typedef void (*esp_blufi_event_cb_t)(esp_blufi_cb_event_t event, esp_blufi_cb_param_t *param) BLUFI event callback function type. - Param event : Event type - Param param : Point to callback parameter, currently is union type - typedef void (*esp_blufi_negotiate_data_handler_t)(uint8_t *data, int len, uint8_t **output_data, int *output_len, bool *need_free) BLUFI negotiate data handler. - Param data : data from phone - Param len : length of data from phone - Param output_data : data want to send to phone - Param output_len : length of data want to send to phone - Param need_free : output reporting if memory needs to be freed or not * - typedef int (*esp_blufi_encrypt_func_t)(uint8_t iv8, uint8_t *crypt_data, int crypt_len) BLUFI encrypt the data after negotiate a share key. - Param iv8 : initial vector(8bit), normally, blufi core will input packet sequence number - Param crypt_data : plain text and encrypted data, the encrypt function must support autochthonous encrypt - Param crypt_len : length of plain text - Return Nonnegative number is encrypted length, if error, return negative number; - typedef int (*esp_blufi_decrypt_func_t)(uint8_t iv8, uint8_t *crypt_data, int crypt_len) BLUFI decrypt the data after negotiate a share key. - Param iv8 : initial vector(8bit), normally, blufi core will input packet sequence number - Param crypt_data : encrypted data and plain text, the encrypt function must support autochthonous decrypt - Param crypt_len : length of encrypted text - Return Nonnegative number is decrypted length, if error, return negative number; - typedef uint16_t (*esp_blufi_checksum_func_t)(uint8_t iv8, uint8_t *data, int len) BLUFI checksum. - Param iv8 : initial vector(8bit), normally, blufi core will input packet sequence number - Param data : data need to checksum - Param len : length of data Enumerations - enum esp_blufi_cb_event_t Values: - enumerator ESP_BLUFI_EVENT_INIT_FINISH - enumerator ESP_BLUFI_EVENT_DEINIT_FINISH - enumerator ESP_BLUFI_EVENT_SET_WIFI_OPMODE - enumerator ESP_BLUFI_EVENT_BLE_CONNECT - enumerator ESP_BLUFI_EVENT_BLE_DISCONNECT - enumerator ESP_BLUFI_EVENT_REQ_CONNECT_TO_AP - enumerator ESP_BLUFI_EVENT_REQ_DISCONNECT_FROM_AP - enumerator ESP_BLUFI_EVENT_GET_WIFI_STATUS - enumerator ESP_BLUFI_EVENT_DEAUTHENTICATE_STA - enumerator ESP_BLUFI_EVENT_RECV_STA_BSSID - enumerator ESP_BLUFI_EVENT_RECV_STA_SSID - enumerator ESP_BLUFI_EVENT_RECV_STA_PASSWD - enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_SSID - enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD - enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM - enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE - enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL - enumerator ESP_BLUFI_EVENT_RECV_USERNAME - enumerator ESP_BLUFI_EVENT_RECV_CA_CERT - enumerator ESP_BLUFI_EVENT_RECV_CLIENT_CERT - enumerator ESP_BLUFI_EVENT_RECV_SERVER_CERT - enumerator ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY - enumerator ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY - enumerator ESP_BLUFI_EVENT_RECV_SLAVE_DISCONNECT_BLE - enumerator ESP_BLUFI_EVENT_GET_WIFI_LIST - enumerator ESP_BLUFI_EVENT_REPORT_ERROR - enumerator ESP_BLUFI_EVENT_RECV_CUSTOM_DATA - enumerator ESP_BLUFI_EVENT_INIT_FINISH - enum esp_blufi_sta_conn_state_t BLUFI config status. Values: - enumerator ESP_BLUFI_STA_CONN_SUCCESS - enumerator ESP_BLUFI_STA_CONN_FAIL - enumerator ESP_BLUFI_STA_CONNECTING - enumerator ESP_BLUFI_STA_NO_IP - enumerator ESP_BLUFI_STA_CONN_SUCCESS - enum esp_blufi_init_state_t BLUFI init status. Values: - enumerator ESP_BLUFI_INIT_OK - enumerator ESP_BLUFI_INIT_FAILED - enumerator ESP_BLUFI_INIT_OK - enum esp_blufi_deinit_state_t BLUFI deinit status. Values: - enumerator ESP_BLUFI_DEINIT_OK - enumerator ESP_BLUFI_DEINIT_FAILED - enumerator ESP_BLUFI_DEINIT_OK - enum esp_blufi_error_state_t Values: - enumerator ESP_BLUFI_SEQUENCE_ERROR - enumerator ESP_BLUFI_CHECKSUM_ERROR - enumerator ESP_BLUFI_DECRYPT_ERROR - enumerator ESP_BLUFI_ENCRYPT_ERROR - enumerator ESP_BLUFI_INIT_SECURITY_ERROR - enumerator ESP_BLUFI_DH_MALLOC_ERROR - enumerator ESP_BLUFI_DH_PARAM_ERROR - enumerator ESP_BLUFI_READ_PARAM_ERROR - enumerator ESP_BLUFI_MAKE_PUBLIC_ERROR - enumerator ESP_BLUFI_DATA_FORMAT_ERROR - enumerator ESP_BLUFI_CALC_MD5_ERROR - enumerator ESP_BLUFI_WIFI_SCAN_FAIL - enumerator ESP_BLUFI_MSG_STATE_ERROR - enumerator ESP_BLUFI_SEQUENCE_ERROR
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_blufi.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Classic Bluetooth® GAP API
null
espressif.com
2016-01-01
2668e01dea239b40
null
null
Classic Bluetooth® GAP API API Reference Header File components/bt/host/bluedroid/api/include/api/esp_gap_bt_api.h This header file can be included with: #include "esp_gap_bt_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions static inline uint32_t esp_bt_gap_get_cod_srvc(uint32_t cod) get major service field of COD Parameters cod -- [in] Class of Device Returns major service bits Parameters cod -- [in] Class of Device Returns major service bits static inline uint32_t esp_bt_gap_get_cod_major_dev(uint32_t cod) get major device field of COD Parameters cod -- [in] Class of Device Returns major device bits Parameters cod -- [in] Class of Device Returns major device bits static inline uint32_t esp_bt_gap_get_cod_minor_dev(uint32_t cod) get minor service field of COD Parameters cod -- [in] Class of Device Returns minor service bits Parameters cod -- [in] Class of Device Returns minor service bits static inline uint32_t esp_bt_gap_get_cod_format_type(uint32_t cod) get format type of COD Parameters cod -- [in] Class of Device Returns format type Parameters cod -- [in] Class of Device Returns format type static inline bool esp_bt_gap_is_valid_cod(uint32_t cod) decide the integrity of COD Parameters cod -- [in] Class of Device Returns true if cod is valid false otherise true if cod is valid false otherise true if cod is valid Parameters cod -- [in] Class of Device Returns true if cod is valid false otherise esp_err_t esp_bt_gap_register_callback(esp_bt_gap_cb_t callback) register callback function. This function should be called after esp_bluedroid_enable() completes successfully Returns ESP_OK : Succeed ESP_FAIL: others ESP_OK : Succeed ESP_FAIL: others ESP_OK : Succeed Returns ESP_OK : Succeed ESP_FAIL: others esp_err_t esp_bt_gap_set_scan_mode(esp_bt_connection_mode_t c_mode, esp_bt_discovery_mode_t d_mode) Set discoverability and connectability mode for legacy bluetooth. This function should be called after esp_bluedroid_enable() completes successfully. Parameters c_mode -- [in] : one of the enums of esp_bt_connection_mode_t d_mode -- [in] : one of the enums of esp_bt_discovery_mode_t c_mode -- [in] : one of the enums of esp_bt_connection_mode_t d_mode -- [in] : one of the enums of esp_bt_discovery_mode_t c_mode -- [in] : one of the enums of esp_bt_connection_mode_t Returns ESP_OK : Succeed ESP_ERR_INVALID_ARG: if argument invalid ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK : Succeed ESP_ERR_INVALID_ARG: if argument invalid ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK : Succeed Parameters c_mode -- [in] : one of the enums of esp_bt_connection_mode_t d_mode -- [in] : one of the enums of esp_bt_discovery_mode_t Returns ESP_OK : Succeed ESP_ERR_INVALID_ARG: if argument invalid ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_bt_gap_start_discovery(esp_bt_inq_mode_t mode, uint8_t inq_len, uint8_t num_rsps) This function starts Inquiry and Name Discovery. This function should be called after esp_bluedroid_enable() completes successfully. When Inquiry is halted and cached results do not contain device name, then Name Discovery will connect to the peer target to get the device name. esp_bt_gap_cb_t will be called with ESP_BT_GAP_DISC_STATE_CHANGED_EVT when Inquiry is started or Name Discovery is completed. esp_bt_gap_cb_t will be called with ESP_BT_GAP_DISC_RES_EVT each time the two types of discovery results are got. Parameters mode -- [in] - Inquiry mode inq_len -- [in] - Inquiry duration in 1.28 sec units, ranging from 0x01 to 0x30. This parameter only specifies the total duration of the Inquiry process, when this time expires, Inquiry will be halted. when this time expires, Inquiry will be halted. when this time expires, Inquiry will be halted. num_rsps -- [in] - Number of responses that can be received before the Inquiry is halted, value 0 indicates an unlimited number of responses. mode -- [in] - Inquiry mode inq_len -- [in] - Inquiry duration in 1.28 sec units, ranging from 0x01 to 0x30. This parameter only specifies the total duration of the Inquiry process, when this time expires, Inquiry will be halted. num_rsps -- [in] - Number of responses that can be received before the Inquiry is halted, value 0 indicates an unlimited number of responses. mode -- [in] - Inquiry mode Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if invalid parameters are provided ESP_FAIL: others ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if invalid parameters are provided ESP_FAIL: others ESP_OK : Succeed Parameters mode -- [in] - Inquiry mode inq_len -- [in] - Inquiry duration in 1.28 sec units, ranging from 0x01 to 0x30. This parameter only specifies the total duration of the Inquiry process, when this time expires, Inquiry will be halted. num_rsps -- [in] - Number of responses that can be received before the Inquiry is halted, value 0 indicates an unlimited number of responses. Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if invalid parameters are provided ESP_FAIL: others esp_err_t esp_bt_gap_cancel_discovery(void) Cancel Inquiry and Name Discovery. This function should be called after esp_bluedroid_enable() completes successfully. esp_bt_gap_cb_t will be called with ESP_BT_GAP_DISC_STATE_CHANGED_EVT if Inquiry or Name Discovery is cancelled by calling this function. Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK : Succeed Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_bt_gap_get_remote_services(esp_bd_addr_t remote_bda) Start SDP to get remote services. This function should be called after esp_bluedroid_enable() completes successfully. esp_bt_gap_cb_t will be called with ESP_BT_GAP_RMT_SRVCS_EVT after service discovery ends. Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK : Succeed Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_bt_gap_get_remote_service_record(esp_bd_addr_t remote_bda, esp_bt_uuid_t *uuid) Start SDP to look up the service matching uuid on the remote device. This function should be called after esp_bluedroid_enable() completes successfully. esp_bt_gap_cb_t will be called with ESP_BT_GAP_RMT_SRVC_REC_EVT after service discovery ends Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK : Succeed Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others uint8_t *esp_bt_gap_resolve_eir_data(uint8_t *eir, esp_bt_eir_type_t type, uint8_t *length) This function is called to get EIR data for a specific type. Parameters eir -- [in] - pointer of raw eir data to be resolved type -- [in] - specific EIR data type length -- [out] - return the length of EIR data excluding fields of length and data type eir -- [in] - pointer of raw eir data to be resolved type -- [in] - specific EIR data type length -- [out] - return the length of EIR data excluding fields of length and data type eir -- [in] - pointer of raw eir data to be resolved Returns pointer of starting position of eir data excluding eir data type, NULL if not found Parameters eir -- [in] - pointer of raw eir data to be resolved type -- [in] - specific EIR data type length -- [out] - return the length of EIR data excluding fields of length and data type Returns pointer of starting position of eir data excluding eir data type, NULL if not found esp_err_t esp_bt_gap_config_eir_data(esp_bt_eir_data_t *eir_data) This function is called to config EIR data. esp_bt_gap_cb_t will be called with ESP_BT_GAP_CONFIG_EIR_DATA_EVT after config EIR ends. Parameters eir_data -- [in] - pointer of EIR data content Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if param is invalid ESP_FAIL: others ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if param is invalid ESP_FAIL: others ESP_OK : Succeed Parameters eir_data -- [in] - pointer of EIR data content Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if param is invalid ESP_FAIL: others esp_err_t esp_bt_gap_set_cod(esp_bt_cod_t cod, esp_bt_cod_mode_t mode) This function is called to set class of device. The structure esp_bt_gap_cb_t will be called with ESP_BT_GAP_SET_COD_EVT after set COD ends. This function should be called after Bluetooth profiles are initialized, otherwise the user configured class of device can be overwritten. Some profiles have special restrictions on class of device, and changes may make these profiles unable to work. Parameters cod -- [in] - class of device mode -- [in] - setting mode cod -- [in] - class of device mode -- [in] - setting mode cod -- [in] - class of device Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if param is invalid ESP_FAIL: others ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if param is invalid ESP_FAIL: others ESP_OK : Succeed Parameters cod -- [in] - class of device mode -- [in] - setting mode Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if param is invalid ESP_FAIL: others esp_err_t esp_bt_gap_get_cod(esp_bt_cod_t *cod) This function is called to get class of device. Parameters cod -- [out] - class of device Returns ESP_OK : Succeed ESP_FAIL: others ESP_OK : Succeed ESP_FAIL: others ESP_OK : Succeed Parameters cod -- [out] - class of device Returns ESP_OK : Succeed ESP_FAIL: others esp_err_t esp_bt_gap_read_rssi_delta(esp_bd_addr_t remote_addr) This function is called to read RSSI delta by address after connected. The RSSI value returned by ESP_BT_GAP_READ_RSSI_DELTA_EVT. Parameters remote_addr -- [in] - remote device address, corresponding to a certain connection handle Returns ESP_OK : Succeed ESP_FAIL: others ESP_OK : Succeed ESP_FAIL: others ESP_OK : Succeed Parameters remote_addr -- [in] - remote device address, corresponding to a certain connection handle Returns ESP_OK : Succeed ESP_FAIL: others esp_err_t esp_bt_gap_remove_bond_device(esp_bd_addr_t bd_addr) Removes a device from the security database list of peer device. Parameters bd_addr -- [in] : BD address of the peer device Returns - ESP_OK : success ESP_FAIL : failed ESP_FAIL : failed ESP_FAIL : failed Parameters bd_addr -- [in] : BD address of the peer device Returns - ESP_OK : success ESP_FAIL : failed int esp_bt_gap_get_bond_device_num(void) Get the device number from the security database list of peer device. It will return the device bonded number immediately. Returns - >= 0 : bonded devices number ESP_FAIL : failed ESP_FAIL : failed ESP_FAIL : failed Returns - >= 0 : bonded devices number ESP_FAIL : failed esp_err_t esp_bt_gap_get_bond_device_list(int *dev_num, esp_bd_addr_t *dev_list) Get the device from the security database list of peer device. It will return the device bonded information immediately. Parameters dev_num -- [inout] Indicate the dev_list array(buffer) size as input. If dev_num is large enough, it means the actual number as output. Suggest that dev_num value equal to esp_ble_get_bond_device_num(). dev_list -- [out] an array(buffer) of esp_bd_addr_t type. Use for storing the bonded devices address. The dev_list should be allocated by who call this API. dev_num -- [inout] Indicate the dev_list array(buffer) size as input. If dev_num is large enough, it means the actual number as output. Suggest that dev_num value equal to esp_ble_get_bond_device_num(). dev_list -- [out] an array(buffer) of esp_bd_addr_t type. Use for storing the bonded devices address. The dev_list should be allocated by who call this API. dev_num -- [inout] Indicate the dev_list array(buffer) size as input. If dev_num is large enough, it means the actual number as output. Suggest that dev_num value equal to esp_ble_get_bond_device_num(). Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK : Succeed Parameters dev_num -- [inout] Indicate the dev_list array(buffer) size as input. If dev_num is large enough, it means the actual number as output. Suggest that dev_num value equal to esp_ble_get_bond_device_num(). dev_list -- [out] an array(buffer) of esp_bd_addr_t type. Use for storing the bonded devices address. The dev_list should be allocated by who call this API. Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_bt_gap_set_pin(esp_bt_pin_type_t pin_type, uint8_t pin_code_len, esp_bt_pin_code_t pin_code) Set pin type and default pin code for legacy pairing. Parameters pin_type -- [in] Use variable or fixed pin. If pin_type is ESP_BT_PIN_TYPE_VARIABLE, pin_code and pin_code_len will be ignored, and ESP_BT_GAP_PIN_REQ_EVT will come when control requests for pin code. Else, will use fixed pin code and not callback to users. pin_code_len -- [in] Length of pin_code pin_code -- [in] Pin_code pin_type -- [in] Use variable or fixed pin. If pin_type is ESP_BT_PIN_TYPE_VARIABLE, pin_code and pin_code_len will be ignored, and ESP_BT_GAP_PIN_REQ_EVT will come when control requests for pin code. Else, will use fixed pin code and not callback to users. pin_code_len -- [in] Length of pin_code pin_code -- [in] Pin_code pin_type -- [in] Use variable or fixed pin. If pin_type is ESP_BT_PIN_TYPE_VARIABLE, pin_code and pin_code_len will be ignored, and ESP_BT_GAP_PIN_REQ_EVT will come when control requests for pin code. Else, will use fixed pin code and not callback to users. Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled Parameters pin_type -- [in] Use variable or fixed pin. If pin_type is ESP_BT_PIN_TYPE_VARIABLE, pin_code and pin_code_len will be ignored, and ESP_BT_GAP_PIN_REQ_EVT will come when control requests for pin code. Else, will use fixed pin code and not callback to users. pin_code_len -- [in] Length of pin_code pin_code -- [in] Pin_code Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed esp_err_t esp_bt_gap_pin_reply(esp_bd_addr_t bd_addr, bool accept, uint8_t pin_code_len, esp_bt_pin_code_t pin_code) Reply the pin_code to the peer device for legacy pairing when ESP_BT_GAP_PIN_REQ_EVT is coming. Parameters bd_addr -- [in] BD address of the peer accept -- [in] Pin_code reply successful or declined. pin_code_len -- [in] Length of pin_code pin_code -- [in] Pin_code bd_addr -- [in] BD address of the peer accept -- [in] Pin_code reply successful or declined. pin_code_len -- [in] Length of pin_code pin_code -- [in] Pin_code bd_addr -- [in] BD address of the peer Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled Parameters bd_addr -- [in] BD address of the peer accept -- [in] Pin_code reply successful or declined. pin_code_len -- [in] Length of pin_code pin_code -- [in] Pin_code Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed esp_err_t esp_bt_gap_set_security_param(esp_bt_sp_param_t param_type, void *value, uint8_t len) Set a GAP security parameter value. Overrides the default value. Parameters param_type -- [in] : the type of the param which is to be set value -- [in] : the param value len -- [in] : the length of the param value param_type -- [in] : the type of the param which is to be set value -- [in] : the param value len -- [in] : the length of the param value param_type -- [in] : the type of the param which is to be set Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled Parameters param_type -- [in] : the type of the param which is to be set value -- [in] : the param value len -- [in] : the length of the param value Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed esp_err_t esp_bt_gap_ssp_passkey_reply(esp_bd_addr_t bd_addr, bool accept, uint32_t passkey) Reply the key value to the peer device in the legacy connection stage. Parameters bd_addr -- [in] : BD address of the peer accept -- [in] : passkey entry successful or declined. passkey -- [in] : passkey value, must be a 6 digit number, can be lead by 0. bd_addr -- [in] : BD address of the peer accept -- [in] : passkey entry successful or declined. passkey -- [in] : passkey value, must be a 6 digit number, can be lead by 0. bd_addr -- [in] : BD address of the peer Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled Parameters bd_addr -- [in] : BD address of the peer accept -- [in] : passkey entry successful or declined. passkey -- [in] : passkey value, must be a 6 digit number, can be lead by 0. Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed esp_err_t esp_bt_gap_ssp_confirm_reply(esp_bd_addr_t bd_addr, bool accept) Reply the confirm value to the peer device in the legacy connection stage. Parameters bd_addr -- [in] : BD address of the peer device accept -- [in] : numbers to compare are the same or different bd_addr -- [in] : BD address of the peer device accept -- [in] : numbers to compare are the same or different bd_addr -- [in] : BD address of the peer device Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled Parameters bd_addr -- [in] : BD address of the peer device accept -- [in] : numbers to compare are the same or different Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed esp_err_t esp_bt_gap_set_afh_channels(esp_bt_gap_afh_channels channels) Set the AFH channels. Parameters channels -- [in] : The n th such field (in the range 0 to 78) contains the value for channel n : 0 means channel n is bad. 1 means channel n is unknown. The most significant bit is reserved and shall be set to 0. At least 20 channels shall be marked as unknown. Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled Parameters channels -- [in] : The n th such field (in the range 0 to 78) contains the value for channel n : 0 means channel n is bad. 1 means channel n is unknown. The most significant bit is reserved and shall be set to 0. At least 20 channels shall be marked as unknown. Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed esp_err_t esp_bt_gap_read_remote_name(esp_bd_addr_t remote_bda) Read the remote device name. Parameters remote_bda -- [in] The remote device's address Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled Parameters remote_bda -- [in] The remote device's address Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed esp_err_t esp_bt_gap_set_qos(esp_bd_addr_t remote_bda, uint32_t t_poll) Config Quality of service. Parameters remote_bda -- [in] The remote device's address t_poll -- [in] Poll interval, the maximum time between transmissions which from the master to a particular slave on the ACL logical transport. unit is 0.625ms remote_bda -- [in] The remote device's address t_poll -- [in] Poll interval, the maximum time between transmissions which from the master to a particular slave on the ACL logical transport. unit is 0.625ms remote_bda -- [in] The remote device's address Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled Parameters remote_bda -- [in] The remote device's address t_poll -- [in] Poll interval, the maximum time between transmissions which from the master to a particular slave on the ACL logical transport. unit is 0.625ms Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed esp_err_t esp_bt_gap_set_page_timeout(uint16_t page_to) Set the page timeout esp_bt_gap_cb_t will be called with ESP_BT_GAP_SET_PAGE_TO_EVT after set page timeout ends. The value to be set will not be effective util the next page procedure, it's suggested to set the page timeout before initiating a connection. Parameters page_to -- [in] Page timeout, the maximum time the master will wait for a Base-band page response from the remote device at a locally initiated connection attempt. The valid range is 0x0016 ~ 0xffff, the default value is 0x2000, unit is 0.625ms. Returns - ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other: failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other: failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled Parameters page_to -- [in] Page timeout, the maximum time the master will wait for a Base-band page response from the remote device at a locally initiated connection attempt. The valid range is 0x0016 ~ 0xffff, the default value is 0x2000, unit is 0.625ms. Returns - ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other: failed esp_err_t esp_bt_gap_get_page_timeout(void) Get the page timeout esp_bt_gap_cb_t will be called with ESP_BT_GAP_GET_PAGE_TO_EVT after get page timeout ends. Returns - ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other: failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other: failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled Returns - ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other: failed esp_err_t esp_bt_gap_set_acl_pkt_types(esp_bd_addr_t remote_bda, esp_bt_acl_pkt_type_t pkt_types) Set ACL packet types An ESP_BT_GAP_SET_ACL_PPKT_TYPES_EVT event will reported to the APP layer. Returns - ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other: failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other: failed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled Returns - ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other: failed Unions union esp_bt_gap_cb_param_t #include <esp_gap_bt_api.h> GAP state callback parameters. Public Members struct esp_bt_gap_cb_param_t::disc_res_param disc_res discovery result parameter struct struct esp_bt_gap_cb_param_t::disc_res_param disc_res discovery result parameter struct struct esp_bt_gap_cb_param_t::disc_state_changed_param disc_st_chg discovery state changed parameter struct struct esp_bt_gap_cb_param_t::disc_state_changed_param disc_st_chg discovery state changed parameter struct struct esp_bt_gap_cb_param_t::rmt_srvcs_param rmt_srvcs services of remote device parameter struct struct esp_bt_gap_cb_param_t::rmt_srvcs_param rmt_srvcs services of remote device parameter struct struct esp_bt_gap_cb_param_t::rmt_srvc_rec_param rmt_srvc_rec specific service record from remote device parameter struct struct esp_bt_gap_cb_param_t::rmt_srvc_rec_param rmt_srvc_rec specific service record from remote device parameter struct struct esp_bt_gap_cb_param_t::read_rssi_delta_param read_rssi_delta read rssi parameter struct struct esp_bt_gap_cb_param_t::read_rssi_delta_param read_rssi_delta read rssi parameter struct struct esp_bt_gap_cb_param_t::config_eir_data_param config_eir_data config EIR data struct esp_bt_gap_cb_param_t::config_eir_data_param config_eir_data config EIR data struct esp_bt_gap_cb_param_t::auth_cmpl_param auth_cmpl authentication complete parameter struct struct esp_bt_gap_cb_param_t::auth_cmpl_param auth_cmpl authentication complete parameter struct struct esp_bt_gap_cb_param_t::enc_chg_param enc_chg encryption change parameter struct struct esp_bt_gap_cb_param_t::enc_chg_param enc_chg encryption change parameter struct struct esp_bt_gap_cb_param_t::pin_req_param pin_req pin request parameter struct struct esp_bt_gap_cb_param_t::pin_req_param pin_req pin request parameter struct struct esp_bt_gap_cb_param_t::cfm_req_param cfm_req confirm request parameter struct struct esp_bt_gap_cb_param_t::cfm_req_param cfm_req confirm request parameter struct struct esp_bt_gap_cb_param_t::key_notif_param key_notif passkey notif parameter struct struct esp_bt_gap_cb_param_t::key_notif_param key_notif passkey notif parameter struct struct esp_bt_gap_cb_param_t::key_req_param key_req passkey request parameter struct struct esp_bt_gap_cb_param_t::key_req_param key_req passkey request parameter struct struct esp_bt_gap_cb_param_t::set_afh_channels_param set_afh_channels set AFH channel parameter struct struct esp_bt_gap_cb_param_t::set_afh_channels_param set_afh_channels set AFH channel parameter struct struct esp_bt_gap_cb_param_t::read_rmt_name_param read_rmt_name read Remote Name parameter struct struct esp_bt_gap_cb_param_t::read_rmt_name_param read_rmt_name read Remote Name parameter struct struct esp_bt_gap_cb_param_t::mode_chg_param mode_chg mode change event parameter struct struct esp_bt_gap_cb_param_t::mode_chg_param mode_chg mode change event parameter struct struct esp_bt_gap_cb_param_t::bt_remove_bond_dev_cmpl_evt_param remove_bond_dev_cmpl Event parameter of ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT struct esp_bt_gap_cb_param_t::bt_remove_bond_dev_cmpl_evt_param remove_bond_dev_cmpl Event parameter of ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT struct esp_bt_gap_cb_param_t::qos_cmpl_param qos_cmpl QoS complete parameter struct struct esp_bt_gap_cb_param_t::qos_cmpl_param qos_cmpl QoS complete parameter struct struct esp_bt_gap_cb_param_t::page_to_set_param set_page_timeout set page timeout parameter struct struct esp_bt_gap_cb_param_t::page_to_set_param set_page_timeout set page timeout parameter struct struct esp_bt_gap_cb_param_t::page_to_get_param get_page_timeout get page timeout parameter struct struct esp_bt_gap_cb_param_t::page_to_get_param get_page_timeout get page timeout parameter struct struct esp_bt_gap_cb_param_t::set_acl_pkt_types_param set_acl_pkt_types set ACL packet types parameter struct struct esp_bt_gap_cb_param_t::set_acl_pkt_types_param set_acl_pkt_types set ACL packet types parameter struct struct esp_bt_gap_cb_param_t::acl_conn_cmpl_stat_param acl_conn_cmpl_stat ACL connection complete status parameter struct struct esp_bt_gap_cb_param_t::acl_conn_cmpl_stat_param acl_conn_cmpl_stat ACL connection complete status parameter struct struct esp_bt_gap_cb_param_t::acl_disconn_cmpl_stat_param acl_disconn_cmpl_stat ACL disconnection complete status parameter struct struct esp_bt_gap_cb_param_t::acl_disconn_cmpl_stat_param acl_disconn_cmpl_stat ACL disconnection complete status parameter struct struct acl_conn_cmpl_stat_param #include <esp_gap_bt_api.h> ESP_BT_GAP_ACL_CONN_CMPL_STAT_EVT. Public Members esp_bt_status_t stat ACL connection status esp_bt_status_t stat ACL connection status uint16_t handle ACL connection handle uint16_t handle ACL connection handle esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address esp_bt_status_t stat struct acl_conn_cmpl_stat_param #include <esp_gap_bt_api.h> ESP_BT_GAP_ACL_CONN_CMPL_STAT_EVT. Public Members esp_bt_status_t stat ACL connection status uint16_t handle ACL connection handle esp_bd_addr_t bda remote bluetooth device address struct acl_disconn_cmpl_stat_param #include <esp_gap_bt_api.h> ESP_BT_GAP_ACL_DISCONN_CMPL_STAT_EVT. Public Members esp_bt_status_t reason ACL disconnection reason esp_bt_status_t reason ACL disconnection reason uint16_t handle ACL connection handle uint16_t handle ACL connection handle esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address esp_bt_status_t reason struct acl_disconn_cmpl_stat_param #include <esp_gap_bt_api.h> ESP_BT_GAP_ACL_DISCONN_CMPL_STAT_EVT. Public Members esp_bt_status_t reason ACL disconnection reason uint16_t handle ACL connection handle esp_bd_addr_t bda remote bluetooth device address struct auth_cmpl_param #include <esp_gap_bt_api.h> ESP_BT_GAP_AUTH_CMPL_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address esp_bt_status_t stat authentication complete status esp_bt_status_t stat authentication complete status esp_bt_link_key_type_t lk_type type of link key generated esp_bt_link_key_type_t lk_type type of link key generated uint8_t device_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1] device name uint8_t device_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1] device name esp_bd_addr_t bda struct auth_cmpl_param #include <esp_gap_bt_api.h> ESP_BT_GAP_AUTH_CMPL_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bt_status_t stat authentication complete status esp_bt_link_key_type_t lk_type type of link key generated uint8_t device_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1] device name struct bt_remove_bond_dev_cmpl_evt_param #include <esp_gap_bt_api.h> ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address esp_bt_status_t status Indicate the remove bond device operation success status esp_bt_status_t status Indicate the remove bond device operation success status esp_bd_addr_t bda struct bt_remove_bond_dev_cmpl_evt_param #include <esp_gap_bt_api.h> ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bt_status_t status Indicate the remove bond device operation success status struct cfm_req_param #include <esp_gap_bt_api.h> ESP_BT_GAP_CFM_REQ_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address uint32_t num_val the numeric value for comparison. uint32_t num_val the numeric value for comparison. esp_bd_addr_t bda struct cfm_req_param #include <esp_gap_bt_api.h> ESP_BT_GAP_CFM_REQ_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address uint32_t num_val the numeric value for comparison. struct config_eir_data_param #include <esp_gap_bt_api.h> ESP_BT_GAP_CONFIG_EIR_DATA_EVT *. Public Members esp_bt_status_t stat config EIR status: ESP_BT_STATUS_SUCCESS: config success ESP_BT_STATUS_EIR_TOO_LARGE: the EIR data is more than 240B. The EIR may not contain the whole data. others: failed esp_bt_status_t stat config EIR status: ESP_BT_STATUS_SUCCESS: config success ESP_BT_STATUS_EIR_TOO_LARGE: the EIR data is more than 240B. The EIR may not contain the whole data. others: failed uint8_t eir_type_num the number of EIR types in EIR type uint8_t eir_type_num the number of EIR types in EIR type esp_bt_eir_type_t eir_type[ESP_BT_EIR_TYPE_MAX_NUM] EIR types in EIR type esp_bt_eir_type_t eir_type[ESP_BT_EIR_TYPE_MAX_NUM] EIR types in EIR type esp_bt_status_t stat struct config_eir_data_param #include <esp_gap_bt_api.h> ESP_BT_GAP_CONFIG_EIR_DATA_EVT *. Public Members esp_bt_status_t stat config EIR status: ESP_BT_STATUS_SUCCESS: config success ESP_BT_STATUS_EIR_TOO_LARGE: the EIR data is more than 240B. The EIR may not contain the whole data. others: failed uint8_t eir_type_num the number of EIR types in EIR type esp_bt_eir_type_t eir_type[ESP_BT_EIR_TYPE_MAX_NUM] EIR types in EIR type struct disc_res_param #include <esp_gap_bt_api.h> ESP_BT_GAP_DISC_RES_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address int num_prop number of properties got int num_prop number of properties got esp_bt_gap_dev_prop_t *prop properties discovered from the new device esp_bt_gap_dev_prop_t *prop properties discovered from the new device esp_bd_addr_t bda struct disc_res_param #include <esp_gap_bt_api.h> ESP_BT_GAP_DISC_RES_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address int num_prop number of properties got esp_bt_gap_dev_prop_t *prop properties discovered from the new device struct disc_state_changed_param #include <esp_gap_bt_api.h> ESP_BT_GAP_DISC_STATE_CHANGED_EVT. Public Members esp_bt_gap_discovery_state_t state discovery state esp_bt_gap_discovery_state_t state discovery state esp_bt_gap_discovery_state_t state struct disc_state_changed_param #include <esp_gap_bt_api.h> ESP_BT_GAP_DISC_STATE_CHANGED_EVT. Public Members esp_bt_gap_discovery_state_t state discovery state struct enc_chg_param #include <esp_gap_bt_api.h> ESP_BT_GAP_ENC_CHG_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address esp_bt_enc_mode_t enc_mode encryption mode esp_bt_enc_mode_t enc_mode encryption mode esp_bd_addr_t bda struct enc_chg_param #include <esp_gap_bt_api.h> ESP_BT_GAP_ENC_CHG_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bt_enc_mode_t enc_mode encryption mode struct key_notif_param #include <esp_gap_bt_api.h> ESP_BT_GAP_KEY_NOTIF_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address uint32_t passkey the numeric value for passkey entry. uint32_t passkey the numeric value for passkey entry. esp_bd_addr_t bda struct key_notif_param #include <esp_gap_bt_api.h> ESP_BT_GAP_KEY_NOTIF_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address uint32_t passkey the numeric value for passkey entry. struct key_req_param #include <esp_gap_bt_api.h> ESP_BT_GAP_KEY_REQ_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda struct key_req_param #include <esp_gap_bt_api.h> ESP_BT_GAP_KEY_REQ_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address struct mode_chg_param #include <esp_gap_bt_api.h> ESP_BT_GAP_MODE_CHG_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address esp_bt_pm_mode_t mode PM mode esp_bt_pm_mode_t mode PM mode esp_bd_addr_t bda struct mode_chg_param #include <esp_gap_bt_api.h> ESP_BT_GAP_MODE_CHG_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bt_pm_mode_t mode PM mode struct page_to_get_param #include <esp_gap_bt_api.h> ESP_BT_GAP_GET_PAGE_TO_EVT. Public Members esp_bt_status_t stat get page timeout status esp_bt_status_t stat get page timeout status uint16_t page_to page_timeout value to be set, unit is 0.625ms. uint16_t page_to page_timeout value to be set, unit is 0.625ms. esp_bt_status_t stat struct page_to_get_param #include <esp_gap_bt_api.h> ESP_BT_GAP_GET_PAGE_TO_EVT. Public Members esp_bt_status_t stat get page timeout status uint16_t page_to page_timeout value to be set, unit is 0.625ms. struct page_to_set_param #include <esp_gap_bt_api.h> ESP_BT_GAP_SET_PAGE_TO_EVT. Public Members esp_bt_status_t stat set page timeout status esp_bt_status_t stat set page timeout status esp_bt_status_t stat struct page_to_set_param #include <esp_gap_bt_api.h> ESP_BT_GAP_SET_PAGE_TO_EVT. Public Members esp_bt_status_t stat set page timeout status struct pin_req_param #include <esp_gap_bt_api.h> ESP_BT_GAP_PIN_REQ_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address bool min_16_digit TRUE if the pin returned must be at least 16 digits bool min_16_digit TRUE if the pin returned must be at least 16 digits esp_bd_addr_t bda struct pin_req_param #include <esp_gap_bt_api.h> ESP_BT_GAP_PIN_REQ_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address bool min_16_digit TRUE if the pin returned must be at least 16 digits struct qos_cmpl_param #include <esp_gap_bt_api.h> ESP_BT_GAP_QOS_CMPL_EVT. Public Members esp_bt_status_t stat QoS status esp_bt_status_t stat QoS status esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address uint32_t t_poll poll interval, the maximum time between transmissions which from the master to a particular slave on the ACL logical transport. unit is 0.625ms. uint32_t t_poll poll interval, the maximum time between transmissions which from the master to a particular slave on the ACL logical transport. unit is 0.625ms. esp_bt_status_t stat struct qos_cmpl_param #include <esp_gap_bt_api.h> ESP_BT_GAP_QOS_CMPL_EVT. Public Members esp_bt_status_t stat QoS status esp_bd_addr_t bda remote bluetooth device address uint32_t t_poll poll interval, the maximum time between transmissions which from the master to a particular slave on the ACL logical transport. unit is 0.625ms. struct read_rmt_name_param #include <esp_gap_bt_api.h> ESP_BT_GAP_READ_REMOTE_NAME_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address esp_bt_status_t stat read Remote Name status esp_bt_status_t stat read Remote Name status uint8_t rmt_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1] Remote device name uint8_t rmt_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1] Remote device name esp_bd_addr_t bda struct read_rmt_name_param #include <esp_gap_bt_api.h> ESP_BT_GAP_READ_REMOTE_NAME_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bt_status_t stat read Remote Name status uint8_t rmt_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1] Remote device name struct read_rssi_delta_param #include <esp_gap_bt_api.h> ESP_BT_GAP_READ_RSSI_DELTA_EVT *. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address esp_bt_status_t stat read rssi status esp_bt_status_t stat read rssi status int8_t rssi_delta rssi delta value range -128 ~127, The value zero indicates that the RSSI is inside the Golden Receive Power Range, the Golden Receive Power Range is from ESP_BT_GAP_RSSI_LOW_THRLD to ESP_BT_GAP_RSSI_HIGH_THRLD int8_t rssi_delta rssi delta value range -128 ~127, The value zero indicates that the RSSI is inside the Golden Receive Power Range, the Golden Receive Power Range is from ESP_BT_GAP_RSSI_LOW_THRLD to ESP_BT_GAP_RSSI_HIGH_THRLD esp_bd_addr_t bda struct read_rssi_delta_param #include <esp_gap_bt_api.h> ESP_BT_GAP_READ_RSSI_DELTA_EVT *. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bt_status_t stat read rssi status int8_t rssi_delta rssi delta value range -128 ~127, The value zero indicates that the RSSI is inside the Golden Receive Power Range, the Golden Receive Power Range is from ESP_BT_GAP_RSSI_LOW_THRLD to ESP_BT_GAP_RSSI_HIGH_THRLD struct rmt_srvc_rec_param #include <esp_gap_bt_api.h> ESP_BT_GAP_RMT_SRVC_REC_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address esp_bt_status_t stat service search status esp_bt_status_t stat service search status esp_bd_addr_t bda struct rmt_srvc_rec_param #include <esp_gap_bt_api.h> ESP_BT_GAP_RMT_SRVC_REC_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bt_status_t stat service search status struct rmt_srvcs_param #include <esp_gap_bt_api.h> ESP_BT_GAP_RMT_SRVCS_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address esp_bt_status_t stat service search status esp_bt_status_t stat service search status int num_uuids number of UUID in uuid_list int num_uuids number of UUID in uuid_list esp_bt_uuid_t *uuid_list list of service UUIDs of remote device esp_bt_uuid_t *uuid_list list of service UUIDs of remote device esp_bd_addr_t bda struct rmt_srvcs_param #include <esp_gap_bt_api.h> ESP_BT_GAP_RMT_SRVCS_EVT. Public Members esp_bd_addr_t bda remote bluetooth device address esp_bt_status_t stat service search status int num_uuids number of UUID in uuid_list esp_bt_uuid_t *uuid_list list of service UUIDs of remote device struct set_acl_pkt_types_param #include <esp_gap_bt_api.h> ESP_BT_GAP_ACL_PKT_TYPE_CHANGED_EVT. Public Members esp_bt_status_t status set ACL packet types status esp_bt_status_t status set ACL packet types status esp_bd_addr_t bda remote bluetooth device address esp_bd_addr_t bda remote bluetooth device address uint16_t pkt_types packet types successfully set uint16_t pkt_types packet types successfully set esp_bt_status_t status struct set_acl_pkt_types_param #include <esp_gap_bt_api.h> ESP_BT_GAP_ACL_PKT_TYPE_CHANGED_EVT. Public Members esp_bt_status_t status set ACL packet types status esp_bd_addr_t bda remote bluetooth device address uint16_t pkt_types packet types successfully set struct set_afh_channels_param #include <esp_gap_bt_api.h> ESP_BT_GAP_SET_AFH_CHANNELS_EVT. Public Members esp_bt_status_t stat set AFH channel status esp_bt_status_t stat set AFH channel status esp_bt_status_t stat struct set_afh_channels_param #include <esp_gap_bt_api.h> ESP_BT_GAP_SET_AFH_CHANNELS_EVT. Public Members esp_bt_status_t stat set AFH channel status struct esp_bt_gap_cb_param_t::disc_res_param disc_res Structures struct esp_bt_cod_t Class of device. struct esp_bt_gap_dev_prop_t Bluetooth Device Property Descriptor. Public Members esp_bt_gap_dev_prop_type_t type Device property type esp_bt_gap_dev_prop_type_t type Device property type int len Device property value length int len Device property value length void *val Device property value void *val Device property value esp_bt_gap_dev_prop_type_t type struct esp_bt_eir_data_t EIR data content, according to "Supplement to the Bluetooth Core Specification". Public Members bool fec_required FEC is required or not, true by default bool fec_required FEC is required or not, true by default bool include_txpower EIR data include TX power, false by default bool include_txpower EIR data include TX power, false by default bool include_uuid EIR data include UUID, false by default bool include_uuid EIR data include UUID, false by default bool include_name EIR data include device name, true by default bool include_name EIR data include device name, true by default uint8_t flag EIR flags, see ESP_BT_EIR_FLAG for details, EIR will not include flag if it is 0, 0 by default uint8_t flag EIR flags, see ESP_BT_EIR_FLAG for details, EIR will not include flag if it is 0, 0 by default uint16_t manufacturer_len Manufacturer data length, 0 by default uint16_t manufacturer_len Manufacturer data length, 0 by default uint8_t *p_manufacturer_data Manufacturer data point uint8_t *p_manufacturer_data Manufacturer data point uint16_t url_len URL length, 0 by default uint16_t url_len URL length, 0 by default uint8_t *p_url URL point uint8_t *p_url URL point bool fec_required Macros ESP_BT_GAP_RSSI_HIGH_THRLD RSSI threshold. High RSSI threshold ESP_BT_GAP_RSSI_LOW_THRLD Low RSSI threshold ESP_BT_GAP_AFH_CHANNELS_LEN ESP_BT_GAP_MAX_BDNAME_LEN Maximum bytes of Bluetooth device name. ESP_BT_GAP_EIR_DATA_LEN Maximum size of EIR Significant part. ESP_BT_EIR_TYPE_FLAGS Extended Inquiry Response data type. Flag with information such as BR/EDR and LE support ESP_BT_EIR_TYPE_INCMPL_16BITS_UUID Incomplete list of 16-bit service UUIDs ESP_BT_EIR_TYPE_CMPL_16BITS_UUID Complete list of 16-bit service UUIDs ESP_BT_EIR_TYPE_INCMPL_32BITS_UUID Incomplete list of 32-bit service UUIDs ESP_BT_EIR_TYPE_CMPL_32BITS_UUID Complete list of 32-bit service UUIDs ESP_BT_EIR_TYPE_INCMPL_128BITS_UUID Incomplete list of 128-bit service UUIDs ESP_BT_EIR_TYPE_CMPL_128BITS_UUID Complete list of 128-bit service UUIDs ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME Shortened Local Name ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME Complete Local Name ESP_BT_EIR_TYPE_TX_POWER_LEVEL Tx power level, value is 1 octet ranging from -127 to 127, unit is dBm ESP_BT_EIR_TYPE_URL Uniform resource identifier ESP_BT_EIR_TYPE_MANU_SPECIFIC Manufacturer specific data ESP_BT_EIR_TYPE_MAX_NUM MAX number of EIR type ESP_BT_ACL_PKT_TYPES_MASK_DM1 ESP_BT_ACL_PKT_TYPES_MASK_DH1 ESP_BT_ACL_PKT_TYPES_MASK_DM3 ESP_BT_ACL_PKT_TYPES_MASK_DH3 ESP_BT_ACL_PKT_TYPES_MASK_DM5 ESP_BT_ACL_PKT_TYPES_MASK_DH5 ESP_BT_ACL_PKT_TYPES_MASK_NO_2_DH1 ESP_BT_ACL_PKT_TYPES_MASK_NO_3_DH1 ESP_BT_ACL_PKT_TYPES_MASK_NO_2_DH3 ESP_BT_ACL_PKT_TYPES_MASK_NO_3_DH3 ESP_BT_ACL_PKT_TYPES_MASK_NO_2_DH5 ESP_BT_ACL_PKT_TYPES_MASK_NO_3_DH5 ESP_BT_ACL_DM1_ONLY ESP_BT_ACL_DH1_ONLY ESP_BT_ACL_DM3_ONLY ESP_BT_ACL_DH3_ONLY ESP_BT_ACL_DM5_ONLY ESP_BT_ACL_DH5_ONLY ESP_BT_ACL_2_DH1_ONLY ESP_BT_ACL_3_DH1_ONLY ESP_BT_ACL_2_DH3_ONLY ESP_BT_ACL_3_DH3_ONLY ESP_BT_ACL_2_DH5_ONLY ESP_BT_ACL_3_DH5_ONLY ESP_BT_EIR_FLAG_LIMIT_DISC ESP_BT_EIR_FLAG_GEN_DISC ESP_BT_EIR_FLAG_BREDR_NOT_SPT ESP_BT_EIR_FLAG_DMT_CONTROLLER_SPT ESP_BT_EIR_FLAG_DMT_HOST_SPT ESP_BT_EIR_MAX_LEN ESP_BT_PIN_CODE_LEN Max pin code length ESP_BT_IO_CAP_OUT ESP_BT_IO_CAP_IO ESP_BT_IO_CAP_IN ESP_BT_IO_CAP_NONE ESP_BT_PM_MD_ACTIVE Active mode ESP_BT_PM_MD_HOLD Hold mode ESP_BT_PM_MD_SNIFF Sniff mode ESP_BT_PM_MD_PARK Park state ESP_BT_COD_SRVC_BIT_MASK Bits of major service class field. Major service bit mask ESP_BT_COD_SRVC_BIT_OFFSET Major service bit offset ESP_BT_COD_MAJOR_DEV_BIT_MASK Bits of major device class field. Major device bit mask ESP_BT_COD_MAJOR_DEV_BIT_OFFSET Major device bit offset ESP_BT_COD_MINOR_DEV_BIT_MASK Bits of minor device class field. Minor device bit mask ESP_BT_COD_MINOR_DEV_BIT_OFFSET Minor device bit offset ESP_BT_COD_FORMAT_TYPE_BIT_MASK Bits of format type. Format type bit mask ESP_BT_COD_FORMAT_TYPE_BIT_OFFSET Format type bit offset ESP_BT_COD_FORMAT_TYPE_1 Class of device format type 1. ESP_BT_LINK_KEY_COMB Type of link key. Combination Key ESP_BT_LINK_KEY_DBG_COMB Debug Combination Key ESP_BT_LINK_KEY_UNAUTHED_COMB_P192 Unauthenticated Combination Key generated from P-192 ESP_BT_LINK_KEY_AUTHED_COMB_P192 Authenticated Combination Key generated from P-192 ESP_BT_LINK_KEY_CHG_COMB Changed Combination Key ESP_BT_LINK_KEY_UNAUTHED_COMB_P256 Unauthenticated Combination Key generated from P-256 ESP_BT_LINK_KEY_AUTHED_COMB_P256 Authenticated Combination Key generated from P-256 ESP_BT_ENC_MODE_OFF Type of encryption. Link Level Encryption is OFF ESP_BT_ENC_MODE_E0 Link Level Encryption is ON with E0 ESP_BT_ENC_MODE_AES Link Level Encryption is ON with AES-CCM ESP_BT_GAP_MIN_INQ_LEN Minimum and Maximum inquiry length Minimum inquiry duration, unit is 1.28s ESP_BT_GAP_MAX_INQ_LEN Maximum inquiry duration, unit is 1.28s ESP_BT_GAP_TPOLL_MIN Minimum, Default and Maximum poll interval Minimum poll interval, unit is 625 microseconds ESP_BT_GAP_TPOLL_DFT Default poll interval, unit is 625 microseconds ESP_BT_GAP_TPOLL_MAX Maximum poll interval, unit is 625 microseconds Type Definitions typedef uint8_t esp_bt_gap_afh_channels[ESP_BT_GAP_AFH_CHANNELS_LEN] typedef uint8_t esp_bt_eir_type_t typedef uint16_t esp_bt_acl_pkt_type_t typedef uint8_t esp_bt_pin_code_t[ESP_BT_PIN_CODE_LEN] Pin Code (upto 128 bits) MSB is 0 typedef uint8_t esp_bt_io_cap_t Combination of the IO Capability typedef uint8_t esp_bt_pm_mode_t typedef uint8_t esp_bt_link_key_type_t typedef uint8_t esp_bt_enc_mode_t typedef void (*esp_bt_gap_cb_t)(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param) bluetooth GAP callback function type Param event : Event type Param param : Pointer to callback parameter Param event : Event type Param param : Pointer to callback parameter Enumerations enum esp_bt_cod_mode_t class of device settings Values: enumerator ESP_BT_SET_COD_MAJOR_MINOR overwrite major, minor class enumerator ESP_BT_SET_COD_MAJOR_MINOR overwrite major, minor class enumerator ESP_BT_SET_COD_SERVICE_CLASS set the bits in the input, the current bit will remain enumerator ESP_BT_SET_COD_SERVICE_CLASS set the bits in the input, the current bit will remain enumerator ESP_BT_CLR_COD_SERVICE_CLASS clear the bits in the input, others will remain enumerator ESP_BT_CLR_COD_SERVICE_CLASS clear the bits in the input, others will remain enumerator ESP_BT_SET_COD_ALL overwrite major, minor, set the bits in service class enumerator ESP_BT_SET_COD_ALL overwrite major, minor, set the bits in service class enumerator ESP_BT_INIT_COD overwrite major, minor, and service class enumerator ESP_BT_INIT_COD overwrite major, minor, and service class enumerator ESP_BT_SET_COD_MAJOR_MINOR enum esp_bt_connection_mode_t Discoverability and Connectability mode. Values: enumerator ESP_BT_NON_CONNECTABLE Non-connectable enumerator ESP_BT_NON_CONNECTABLE Non-connectable enumerator ESP_BT_CONNECTABLE Connectable enumerator ESP_BT_CONNECTABLE Connectable enumerator ESP_BT_NON_CONNECTABLE enum esp_bt_discovery_mode_t Values: enumerator ESP_BT_NON_DISCOVERABLE Non-discoverable enumerator ESP_BT_NON_DISCOVERABLE Non-discoverable enumerator ESP_BT_LIMITED_DISCOVERABLE Limited Discoverable enumerator ESP_BT_LIMITED_DISCOVERABLE Limited Discoverable enumerator ESP_BT_GENERAL_DISCOVERABLE General Discoverable enumerator ESP_BT_GENERAL_DISCOVERABLE General Discoverable enumerator ESP_BT_NON_DISCOVERABLE enum esp_bt_gap_dev_prop_type_t Bluetooth Device Property type. Values: enumerator ESP_BT_GAP_DEV_PROP_BDNAME Bluetooth device name, value type is int8_t [] enumerator ESP_BT_GAP_DEV_PROP_BDNAME Bluetooth device name, value type is int8_t [] enumerator ESP_BT_GAP_DEV_PROP_COD Class of Device, value type is uint32_t enumerator ESP_BT_GAP_DEV_PROP_COD Class of Device, value type is uint32_t enumerator ESP_BT_GAP_DEV_PROP_RSSI Received Signal strength Indication, value type is int8_t, ranging from -128 to 127 enumerator ESP_BT_GAP_DEV_PROP_RSSI Received Signal strength Indication, value type is int8_t, ranging from -128 to 127 enumerator ESP_BT_GAP_DEV_PROP_EIR Extended Inquiry Response, value type is uint8_t [] enumerator ESP_BT_GAP_DEV_PROP_EIR Extended Inquiry Response, value type is uint8_t [] enumerator ESP_BT_GAP_DEV_PROP_BDNAME enum esp_bt_cod_srvc_t Major service class field of Class of Device, mutiple bits can be set. Values: enumerator ESP_BT_COD_SRVC_NONE None indicates an invalid value enumerator ESP_BT_COD_SRVC_NONE None indicates an invalid value enumerator ESP_BT_COD_SRVC_LMTD_DISCOVER Limited Discoverable Mode enumerator ESP_BT_COD_SRVC_LMTD_DISCOVER Limited Discoverable Mode enumerator ESP_BT_COD_SRVC_POSITIONING Positioning (Location identification) enumerator ESP_BT_COD_SRVC_POSITIONING Positioning (Location identification) enumerator ESP_BT_COD_SRVC_NETWORKING Networking, e.g. LAN, Ad hoc enumerator ESP_BT_COD_SRVC_NETWORKING Networking, e.g. LAN, Ad hoc enumerator ESP_BT_COD_SRVC_RENDERING Rendering, e.g. Printing, Speakers enumerator ESP_BT_COD_SRVC_RENDERING Rendering, e.g. Printing, Speakers enumerator ESP_BT_COD_SRVC_CAPTURING Capturing, e.g. Scanner, Microphone enumerator ESP_BT_COD_SRVC_CAPTURING Capturing, e.g. Scanner, Microphone enumerator ESP_BT_COD_SRVC_OBJ_TRANSFER Object Transfer, e.g. v-Inbox, v-Folder enumerator ESP_BT_COD_SRVC_OBJ_TRANSFER Object Transfer, e.g. v-Inbox, v-Folder enumerator ESP_BT_COD_SRVC_AUDIO Audio, e.g. Speaker, Microphone, Headset service enumerator ESP_BT_COD_SRVC_AUDIO Audio, e.g. Speaker, Microphone, Headset service enumerator ESP_BT_COD_SRVC_TELEPHONY Telephony, e.g. Cordless telephony, Modem, Headset service enumerator ESP_BT_COD_SRVC_TELEPHONY Telephony, e.g. Cordless telephony, Modem, Headset service enumerator ESP_BT_COD_SRVC_INFORMATION Information, e.g., WEB-server, WAP-server enumerator ESP_BT_COD_SRVC_INFORMATION Information, e.g., WEB-server, WAP-server enumerator ESP_BT_COD_SRVC_NONE enum esp_bt_pin_type_t Values: enumerator ESP_BT_PIN_TYPE_VARIABLE Refer to BTM_PIN_TYPE_VARIABLE enumerator ESP_BT_PIN_TYPE_VARIABLE Refer to BTM_PIN_TYPE_VARIABLE enumerator ESP_BT_PIN_TYPE_FIXED Refer to BTM_PIN_TYPE_FIXED enumerator ESP_BT_PIN_TYPE_FIXED Refer to BTM_PIN_TYPE_FIXED enumerator ESP_BT_PIN_TYPE_VARIABLE enum esp_bt_cod_major_dev_t Major device class field of Class of Device. Values: enumerator ESP_BT_COD_MAJOR_DEV_MISC Miscellaneous enumerator ESP_BT_COD_MAJOR_DEV_MISC Miscellaneous enumerator ESP_BT_COD_MAJOR_DEV_COMPUTER Computer enumerator ESP_BT_COD_MAJOR_DEV_COMPUTER Computer enumerator ESP_BT_COD_MAJOR_DEV_PHONE Phone(cellular, cordless, pay phone, modem enumerator ESP_BT_COD_MAJOR_DEV_PHONE Phone(cellular, cordless, pay phone, modem enumerator ESP_BT_COD_MAJOR_DEV_LAN_NAP LAN, Network Access Point enumerator ESP_BT_COD_MAJOR_DEV_LAN_NAP LAN, Network Access Point enumerator ESP_BT_COD_MAJOR_DEV_AV Audio/Video(headset, speaker, stereo, video display, VCR enumerator ESP_BT_COD_MAJOR_DEV_AV Audio/Video(headset, speaker, stereo, video display, VCR enumerator ESP_BT_COD_MAJOR_DEV_PERIPHERAL Peripheral(mouse, joystick, keyboard) enumerator ESP_BT_COD_MAJOR_DEV_PERIPHERAL Peripheral(mouse, joystick, keyboard) enumerator ESP_BT_COD_MAJOR_DEV_IMAGING Imaging(printer, scanner, camera, display enumerator ESP_BT_COD_MAJOR_DEV_IMAGING Imaging(printer, scanner, camera, display enumerator ESP_BT_COD_MAJOR_DEV_WEARABLE Wearable enumerator ESP_BT_COD_MAJOR_DEV_WEARABLE Wearable enumerator ESP_BT_COD_MAJOR_DEV_TOY Toy enumerator ESP_BT_COD_MAJOR_DEV_TOY Toy enumerator ESP_BT_COD_MAJOR_DEV_HEALTH Health enumerator ESP_BT_COD_MAJOR_DEV_HEALTH Health enumerator ESP_BT_COD_MAJOR_DEV_UNCATEGORIZED Uncategorized: device not specified enumerator ESP_BT_COD_MAJOR_DEV_UNCATEGORIZED Uncategorized: device not specified enumerator ESP_BT_COD_MAJOR_DEV_MISC enum esp_bt_gap_discovery_state_t Bluetooth Device Discovery state Values: enumerator ESP_BT_GAP_DISCOVERY_STOPPED Device discovery stopped enumerator ESP_BT_GAP_DISCOVERY_STOPPED Device discovery stopped enumerator ESP_BT_GAP_DISCOVERY_STARTED Device discovery started enumerator ESP_BT_GAP_DISCOVERY_STARTED Device discovery started enumerator ESP_BT_GAP_DISCOVERY_STOPPED enum esp_bt_gap_cb_event_t BT GAP callback events. Values: enumerator ESP_BT_GAP_DISC_RES_EVT Device discovery result event enumerator ESP_BT_GAP_DISC_RES_EVT Device discovery result event enumerator ESP_BT_GAP_DISC_STATE_CHANGED_EVT Discovery state changed event enumerator ESP_BT_GAP_DISC_STATE_CHANGED_EVT Discovery state changed event enumerator ESP_BT_GAP_RMT_SRVCS_EVT Get remote services event enumerator ESP_BT_GAP_RMT_SRVCS_EVT Get remote services event enumerator ESP_BT_GAP_RMT_SRVC_REC_EVT Get remote service record event enumerator ESP_BT_GAP_RMT_SRVC_REC_EVT Get remote service record event enumerator ESP_BT_GAP_AUTH_CMPL_EVT Authentication complete event enumerator ESP_BT_GAP_AUTH_CMPL_EVT Authentication complete event enumerator ESP_BT_GAP_PIN_REQ_EVT Legacy Pairing Pin code request enumerator ESP_BT_GAP_PIN_REQ_EVT Legacy Pairing Pin code request enumerator ESP_BT_GAP_CFM_REQ_EVT Security Simple Pairing User Confirmation request. enumerator ESP_BT_GAP_CFM_REQ_EVT Security Simple Pairing User Confirmation request. enumerator ESP_BT_GAP_KEY_NOTIF_EVT Security Simple Pairing Passkey Notification enumerator ESP_BT_GAP_KEY_NOTIF_EVT Security Simple Pairing Passkey Notification enumerator ESP_BT_GAP_KEY_REQ_EVT Security Simple Pairing Passkey request enumerator ESP_BT_GAP_KEY_REQ_EVT Security Simple Pairing Passkey request enumerator ESP_BT_GAP_READ_RSSI_DELTA_EVT Read rssi event enumerator ESP_BT_GAP_READ_RSSI_DELTA_EVT Read rssi event enumerator ESP_BT_GAP_CONFIG_EIR_DATA_EVT Config EIR data event enumerator ESP_BT_GAP_CONFIG_EIR_DATA_EVT Config EIR data event enumerator ESP_BT_GAP_SET_AFH_CHANNELS_EVT Set AFH channels event enumerator ESP_BT_GAP_SET_AFH_CHANNELS_EVT Set AFH channels event enumerator ESP_BT_GAP_READ_REMOTE_NAME_EVT Read Remote Name event enumerator ESP_BT_GAP_READ_REMOTE_NAME_EVT Read Remote Name event enumerator ESP_BT_GAP_MODE_CHG_EVT enumerator ESP_BT_GAP_MODE_CHG_EVT enumerator ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT remove bond device complete event enumerator ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT remove bond device complete event enumerator ESP_BT_GAP_QOS_CMPL_EVT QOS complete event enumerator ESP_BT_GAP_QOS_CMPL_EVT QOS complete event enumerator ESP_BT_GAP_ACL_CONN_CMPL_STAT_EVT ACL connection complete status event enumerator ESP_BT_GAP_ACL_CONN_CMPL_STAT_EVT ACL connection complete status event enumerator ESP_BT_GAP_ACL_DISCONN_CMPL_STAT_EVT ACL disconnection complete status event enumerator ESP_BT_GAP_ACL_DISCONN_CMPL_STAT_EVT ACL disconnection complete status event enumerator ESP_BT_GAP_SET_PAGE_TO_EVT Set page timeout event enumerator ESP_BT_GAP_SET_PAGE_TO_EVT Set page timeout event enumerator ESP_BT_GAP_GET_PAGE_TO_EVT Get page timeout event enumerator ESP_BT_GAP_GET_PAGE_TO_EVT Get page timeout event enumerator ESP_BT_GAP_ACL_PKT_TYPE_CHANGED_EVT Set ACL packet types event enumerator ESP_BT_GAP_ACL_PKT_TYPE_CHANGED_EVT Set ACL packet types event enumerator ESP_BT_GAP_ENC_CHG_EVT Encryption change event enumerator ESP_BT_GAP_ENC_CHG_EVT Encryption change event enumerator ESP_BT_GAP_EVT_MAX enumerator ESP_BT_GAP_EVT_MAX enumerator ESP_BT_GAP_DISC_RES_EVT
Classic Bluetooth® GAP API API Reference Header File components/bt/host/bluedroid/api/include/api/esp_gap_bt_api.h This header file can be included with: #include "esp_gap_bt_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - static inline uint32_t esp_bt_gap_get_cod_srvc(uint32_t cod) get major service field of COD - Parameters cod -- [in] Class of Device - Returns major service bits - static inline uint32_t esp_bt_gap_get_cod_major_dev(uint32_t cod) get major device field of COD - Parameters cod -- [in] Class of Device - Returns major device bits - static inline uint32_t esp_bt_gap_get_cod_minor_dev(uint32_t cod) get minor service field of COD - Parameters cod -- [in] Class of Device - Returns minor service bits - static inline uint32_t esp_bt_gap_get_cod_format_type(uint32_t cod) get format type of COD - Parameters cod -- [in] Class of Device - Returns format type - static inline bool esp_bt_gap_is_valid_cod(uint32_t cod) decide the integrity of COD - Parameters cod -- [in] Class of Device - Returns true if cod is valid false otherise - - esp_err_t esp_bt_gap_register_callback(esp_bt_gap_cb_t callback) register callback function. This function should be called after esp_bluedroid_enable() completes successfully - Returns ESP_OK : Succeed ESP_FAIL: others - - esp_err_t esp_bt_gap_set_scan_mode(esp_bt_connection_mode_t c_mode, esp_bt_discovery_mode_t d_mode) Set discoverability and connectability mode for legacy bluetooth. This function should be called after esp_bluedroid_enable() completes successfully. - Parameters c_mode -- [in] : one of the enums of esp_bt_connection_mode_t d_mode -- [in] : one of the enums of esp_bt_discovery_mode_t - - Returns ESP_OK : Succeed ESP_ERR_INVALID_ARG: if argument invalid ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_bt_gap_start_discovery(esp_bt_inq_mode_t mode, uint8_t inq_len, uint8_t num_rsps) This function starts Inquiry and Name Discovery. This function should be called after esp_bluedroid_enable() completes successfully. When Inquiry is halted and cached results do not contain device name, then Name Discovery will connect to the peer target to get the device name. esp_bt_gap_cb_t will be called with ESP_BT_GAP_DISC_STATE_CHANGED_EVT when Inquiry is started or Name Discovery is completed. esp_bt_gap_cb_t will be called with ESP_BT_GAP_DISC_RES_EVT each time the two types of discovery results are got. - Parameters mode -- [in] - Inquiry mode inq_len -- [in] - Inquiry duration in 1.28 sec units, ranging from 0x01 to 0x30. This parameter only specifies the total duration of the Inquiry process, when this time expires, Inquiry will be halted. - num_rsps -- [in] - Number of responses that can be received before the Inquiry is halted, value 0 indicates an unlimited number of responses. - - Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if invalid parameters are provided ESP_FAIL: others - - esp_err_t esp_bt_gap_cancel_discovery(void) Cancel Inquiry and Name Discovery. This function should be called after esp_bluedroid_enable() completes successfully. esp_bt_gap_cb_t will be called with ESP_BT_GAP_DISC_STATE_CHANGED_EVT if Inquiry or Name Discovery is cancelled by calling this function. - Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_bt_gap_get_remote_services(esp_bd_addr_t remote_bda) Start SDP to get remote services. This function should be called after esp_bluedroid_enable() completes successfully. esp_bt_gap_cb_t will be called with ESP_BT_GAP_RMT_SRVCS_EVT after service discovery ends. - Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_bt_gap_get_remote_service_record(esp_bd_addr_t remote_bda, esp_bt_uuid_t *uuid) Start SDP to look up the service matching uuid on the remote device. This function should be called after esp_bluedroid_enable() completes successfully. esp_bt_gap_cb_t will be called with ESP_BT_GAP_RMT_SRVC_REC_EVT after service discovery ends - Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - uint8_t *esp_bt_gap_resolve_eir_data(uint8_t *eir, esp_bt_eir_type_t type, uint8_t *length) This function is called to get EIR data for a specific type. - Parameters eir -- [in] - pointer of raw eir data to be resolved type -- [in] - specific EIR data type length -- [out] - return the length of EIR data excluding fields of length and data type - - Returns pointer of starting position of eir data excluding eir data type, NULL if not found - esp_err_t esp_bt_gap_config_eir_data(esp_bt_eir_data_t *eir_data) This function is called to config EIR data. esp_bt_gap_cb_t will be called with ESP_BT_GAP_CONFIG_EIR_DATA_EVT after config EIR ends. - Parameters eir_data -- [in] - pointer of EIR data content - Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if param is invalid ESP_FAIL: others - - esp_err_t esp_bt_gap_set_cod(esp_bt_cod_t cod, esp_bt_cod_mode_t mode) This function is called to set class of device. The structure esp_bt_gap_cb_t will be called with ESP_BT_GAP_SET_COD_EVT after set COD ends. This function should be called after Bluetooth profiles are initialized, otherwise the user configured class of device can be overwritten. Some profiles have special restrictions on class of device, and changes may make these profiles unable to work. - Parameters cod -- [in] - class of device mode -- [in] - setting mode - - Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if param is invalid ESP_FAIL: others - - esp_err_t esp_bt_gap_get_cod(esp_bt_cod_t *cod) This function is called to get class of device. - Parameters cod -- [out] - class of device - Returns ESP_OK : Succeed ESP_FAIL: others - - esp_err_t esp_bt_gap_read_rssi_delta(esp_bd_addr_t remote_addr) This function is called to read RSSI delta by address after connected. The RSSI value returned by ESP_BT_GAP_READ_RSSI_DELTA_EVT. - Parameters remote_addr -- [in] - remote device address, corresponding to a certain connection handle - Returns ESP_OK : Succeed ESP_FAIL: others - - esp_err_t esp_bt_gap_remove_bond_device(esp_bd_addr_t bd_addr) Removes a device from the security database list of peer device. - Parameters bd_addr -- [in] : BD address of the peer device - Returns - ESP_OK : success ESP_FAIL : failed - - int esp_bt_gap_get_bond_device_num(void) Get the device number from the security database list of peer device. It will return the device bonded number immediately. - Returns - >= 0 : bonded devices number ESP_FAIL : failed - - esp_err_t esp_bt_gap_get_bond_device_list(int *dev_num, esp_bd_addr_t *dev_list) Get the device from the security database list of peer device. It will return the device bonded information immediately. - Parameters dev_num -- [inout] Indicate the dev_list array(buffer) size as input. If dev_num is large enough, it means the actual number as output. Suggest that dev_num value equal to esp_ble_get_bond_device_num(). dev_list -- [out] an array(buffer) of esp_bd_addr_ttype. Use for storing the bonded devices address. The dev_list should be allocated by who call this API. - - Returns ESP_OK : Succeed ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_bt_gap_set_pin(esp_bt_pin_type_t pin_type, uint8_t pin_code_len, esp_bt_pin_code_t pin_code) Set pin type and default pin code for legacy pairing. - Parameters pin_type -- [in] Use variable or fixed pin. If pin_type is ESP_BT_PIN_TYPE_VARIABLE, pin_code and pin_code_len will be ignored, and ESP_BT_GAP_PIN_REQ_EVT will come when control requests for pin code. Else, will use fixed pin code and not callback to users. pin_code_len -- [in] Length of pin_code pin_code -- [in] Pin_code - - Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed - - esp_err_t esp_bt_gap_pin_reply(esp_bd_addr_t bd_addr, bool accept, uint8_t pin_code_len, esp_bt_pin_code_t pin_code) Reply the pin_code to the peer device for legacy pairing when ESP_BT_GAP_PIN_REQ_EVT is coming. - Parameters bd_addr -- [in] BD address of the peer accept -- [in] Pin_code reply successful or declined. pin_code_len -- [in] Length of pin_code pin_code -- [in] Pin_code - - Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed - - esp_err_t esp_bt_gap_set_security_param(esp_bt_sp_param_t param_type, void *value, uint8_t len) Set a GAP security parameter value. Overrides the default value. - Parameters param_type -- [in] : the type of the param which is to be set value -- [in] : the param value len -- [in] : the length of the param value - - Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed - - esp_err_t esp_bt_gap_ssp_passkey_reply(esp_bd_addr_t bd_addr, bool accept, uint32_t passkey) Reply the key value to the peer device in the legacy connection stage. - Parameters bd_addr -- [in] : BD address of the peer accept -- [in] : passkey entry successful or declined. passkey -- [in] : passkey value, must be a 6 digit number, can be lead by 0. - - Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed - - esp_err_t esp_bt_gap_ssp_confirm_reply(esp_bd_addr_t bd_addr, bool accept) Reply the confirm value to the peer device in the legacy connection stage. - Parameters bd_addr -- [in] : BD address of the peer device accept -- [in] : numbers to compare are the same or different - - Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed - - esp_err_t esp_bt_gap_set_afh_channels(esp_bt_gap_afh_channels channels) Set the AFH channels. - Parameters channels -- [in] : The n th such field (in the range 0 to 78) contains the value for channel n : 0 means channel n is bad. 1 means channel n is unknown. The most significant bit is reserved and shall be set to 0. At least 20 channels shall be marked as unknown. - Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed - - esp_err_t esp_bt_gap_read_remote_name(esp_bd_addr_t remote_bda) Read the remote device name. - Parameters remote_bda -- [in] The remote device's address - Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed - - esp_err_t esp_bt_gap_set_qos(esp_bd_addr_t remote_bda, uint32_t t_poll) Config Quality of service. - Parameters remote_bda -- [in] The remote device's address t_poll -- [in] Poll interval, the maximum time between transmissions which from the master to a particular slave on the ACL logical transport. unit is 0.625ms - - Returns - ESP_OK : success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other : failed - - esp_err_t esp_bt_gap_set_page_timeout(uint16_t page_to) Set the page timeout esp_bt_gap_cb_t will be called with ESP_BT_GAP_SET_PAGE_TO_EVT after set page timeout ends. The value to be set will not be effective util the next page procedure, it's suggested to set the page timeout before initiating a connection. - Parameters page_to -- [in] Page timeout, the maximum time the master will wait for a Base-band page response from the remote device at a locally initiated connection attempt. The valid range is 0x0016 ~ 0xffff, the default value is 0x2000, unit is 0.625ms. - Returns - ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other: failed - - esp_err_t esp_bt_gap_get_page_timeout(void) Get the page timeout esp_bt_gap_cb_t will be called with ESP_BT_GAP_GET_PAGE_TO_EVT after get page timeout ends. - Returns - ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other: failed - - esp_err_t esp_bt_gap_set_acl_pkt_types(esp_bd_addr_t remote_bda, esp_bt_acl_pkt_type_t pkt_types) Set ACL packet types An ESP_BT_GAP_SET_ACL_PPKT_TYPES_EVT event will reported to the APP layer. - Returns - ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled other: failed - Unions - union esp_bt_gap_cb_param_t - #include <esp_gap_bt_api.h> GAP state callback parameters. Public Members - struct esp_bt_gap_cb_param_t::disc_res_param disc_res discovery result parameter struct - struct esp_bt_gap_cb_param_t::disc_state_changed_param disc_st_chg discovery state changed parameter struct - struct esp_bt_gap_cb_param_t::rmt_srvcs_param rmt_srvcs services of remote device parameter struct - struct esp_bt_gap_cb_param_t::rmt_srvc_rec_param rmt_srvc_rec specific service record from remote device parameter struct - struct esp_bt_gap_cb_param_t::read_rssi_delta_param read_rssi_delta read rssi parameter struct - struct esp_bt_gap_cb_param_t::config_eir_data_param config_eir_data config EIR data - struct esp_bt_gap_cb_param_t::auth_cmpl_param auth_cmpl authentication complete parameter struct - struct esp_bt_gap_cb_param_t::enc_chg_param enc_chg encryption change parameter struct - struct esp_bt_gap_cb_param_t::pin_req_param pin_req pin request parameter struct - struct esp_bt_gap_cb_param_t::cfm_req_param cfm_req confirm request parameter struct - struct esp_bt_gap_cb_param_t::key_notif_param key_notif passkey notif parameter struct - struct esp_bt_gap_cb_param_t::key_req_param key_req passkey request parameter struct - struct esp_bt_gap_cb_param_t::set_afh_channels_param set_afh_channels set AFH channel parameter struct - struct esp_bt_gap_cb_param_t::read_rmt_name_param read_rmt_name read Remote Name parameter struct - struct esp_bt_gap_cb_param_t::mode_chg_param mode_chg mode change event parameter struct - struct esp_bt_gap_cb_param_t::bt_remove_bond_dev_cmpl_evt_param remove_bond_dev_cmpl Event parameter of ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT - struct esp_bt_gap_cb_param_t::qos_cmpl_param qos_cmpl QoS complete parameter struct - struct esp_bt_gap_cb_param_t::page_to_set_param set_page_timeout set page timeout parameter struct - struct esp_bt_gap_cb_param_t::page_to_get_param get_page_timeout get page timeout parameter struct - struct esp_bt_gap_cb_param_t::set_acl_pkt_types_param set_acl_pkt_types set ACL packet types parameter struct - struct esp_bt_gap_cb_param_t::acl_conn_cmpl_stat_param acl_conn_cmpl_stat ACL connection complete status parameter struct - struct esp_bt_gap_cb_param_t::acl_disconn_cmpl_stat_param acl_disconn_cmpl_stat ACL disconnection complete status parameter struct - struct acl_conn_cmpl_stat_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_ACL_CONN_CMPL_STAT_EVT. Public Members - esp_bt_status_t stat ACL connection status - uint16_t handle ACL connection handle - esp_bd_addr_t bda remote bluetooth device address - esp_bt_status_t stat - struct acl_disconn_cmpl_stat_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_ACL_DISCONN_CMPL_STAT_EVT. Public Members - esp_bt_status_t reason ACL disconnection reason - uint16_t handle ACL connection handle - esp_bd_addr_t bda remote bluetooth device address - esp_bt_status_t reason - struct auth_cmpl_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_AUTH_CMPL_EVT. Public Members - esp_bd_addr_t bda remote bluetooth device address - esp_bt_status_t stat authentication complete status - esp_bt_link_key_type_t lk_type type of link key generated - uint8_t device_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1] device name - esp_bd_addr_t bda - struct bt_remove_bond_dev_cmpl_evt_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT. Public Members - esp_bd_addr_t bda remote bluetooth device address - esp_bt_status_t status Indicate the remove bond device operation success status - esp_bd_addr_t bda - struct cfm_req_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_CFM_REQ_EVT. Public Members - esp_bd_addr_t bda remote bluetooth device address - uint32_t num_val the numeric value for comparison. - esp_bd_addr_t bda - struct config_eir_data_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_CONFIG_EIR_DATA_EVT *. Public Members - esp_bt_status_t stat config EIR status: ESP_BT_STATUS_SUCCESS: config success ESP_BT_STATUS_EIR_TOO_LARGE: the EIR data is more than 240B. The EIR may not contain the whole data. others: failed - uint8_t eir_type_num the number of EIR types in EIR type - esp_bt_eir_type_t eir_type[ESP_BT_EIR_TYPE_MAX_NUM] EIR types in EIR type - esp_bt_status_t stat - struct disc_res_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_DISC_RES_EVT. Public Members - esp_bd_addr_t bda remote bluetooth device address - int num_prop number of properties got - esp_bt_gap_dev_prop_t *prop properties discovered from the new device - esp_bd_addr_t bda - struct disc_state_changed_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_DISC_STATE_CHANGED_EVT. Public Members - esp_bt_gap_discovery_state_t state discovery state - esp_bt_gap_discovery_state_t state - struct enc_chg_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_ENC_CHG_EVT. Public Members - esp_bd_addr_t bda remote bluetooth device address - esp_bt_enc_mode_t enc_mode encryption mode - esp_bd_addr_t bda - struct key_notif_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_KEY_NOTIF_EVT. Public Members - esp_bd_addr_t bda remote bluetooth device address - uint32_t passkey the numeric value for passkey entry. - esp_bd_addr_t bda - struct key_req_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_KEY_REQ_EVT. Public Members - esp_bd_addr_t bda remote bluetooth device address - esp_bd_addr_t bda - struct mode_chg_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_MODE_CHG_EVT. Public Members - esp_bd_addr_t bda remote bluetooth device address - esp_bt_pm_mode_t mode PM mode - esp_bd_addr_t bda - struct page_to_get_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_GET_PAGE_TO_EVT. Public Members - esp_bt_status_t stat get page timeout status - uint16_t page_to page_timeout value to be set, unit is 0.625ms. - esp_bt_status_t stat - struct page_to_set_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_SET_PAGE_TO_EVT. Public Members - esp_bt_status_t stat set page timeout status - esp_bt_status_t stat - struct pin_req_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_PIN_REQ_EVT. Public Members - esp_bd_addr_t bda remote bluetooth device address - bool min_16_digit TRUE if the pin returned must be at least 16 digits - esp_bd_addr_t bda - struct qos_cmpl_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_QOS_CMPL_EVT. Public Members - esp_bt_status_t stat QoS status - esp_bd_addr_t bda remote bluetooth device address - uint32_t t_poll poll interval, the maximum time between transmissions which from the master to a particular slave on the ACL logical transport. unit is 0.625ms. - esp_bt_status_t stat - struct read_rmt_name_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_READ_REMOTE_NAME_EVT. Public Members - esp_bd_addr_t bda remote bluetooth device address - esp_bt_status_t stat read Remote Name status - uint8_t rmt_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1] Remote device name - esp_bd_addr_t bda - struct read_rssi_delta_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_READ_RSSI_DELTA_EVT *. Public Members - esp_bd_addr_t bda remote bluetooth device address - esp_bt_status_t stat read rssi status - int8_t rssi_delta rssi delta value range -128 ~127, The value zero indicates that the RSSI is inside the Golden Receive Power Range, the Golden Receive Power Range is from ESP_BT_GAP_RSSI_LOW_THRLD to ESP_BT_GAP_RSSI_HIGH_THRLD - esp_bd_addr_t bda - struct rmt_srvc_rec_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_RMT_SRVC_REC_EVT. Public Members - esp_bd_addr_t bda remote bluetooth device address - esp_bt_status_t stat service search status - esp_bd_addr_t bda - struct rmt_srvcs_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_RMT_SRVCS_EVT. Public Members - esp_bd_addr_t bda remote bluetooth device address - esp_bt_status_t stat service search status - int num_uuids number of UUID in uuid_list - esp_bt_uuid_t *uuid_list list of service UUIDs of remote device - esp_bd_addr_t bda - struct set_acl_pkt_types_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_ACL_PKT_TYPE_CHANGED_EVT. Public Members - esp_bt_status_t status set ACL packet types status - esp_bd_addr_t bda remote bluetooth device address - uint16_t pkt_types packet types successfully set - esp_bt_status_t status - struct set_afh_channels_param - #include <esp_gap_bt_api.h> ESP_BT_GAP_SET_AFH_CHANNELS_EVT. Public Members - esp_bt_status_t stat set AFH channel status - esp_bt_status_t stat - struct esp_bt_gap_cb_param_t::disc_res_param disc_res Structures - struct esp_bt_cod_t Class of device. - struct esp_bt_gap_dev_prop_t Bluetooth Device Property Descriptor. Public Members - esp_bt_gap_dev_prop_type_t type Device property type - int len Device property value length - void *val Device property value - esp_bt_gap_dev_prop_type_t type - struct esp_bt_eir_data_t EIR data content, according to "Supplement to the Bluetooth Core Specification". Public Members - bool fec_required FEC is required or not, true by default - bool include_txpower EIR data include TX power, false by default - bool include_uuid EIR data include UUID, false by default - bool include_name EIR data include device name, true by default - uint8_t flag EIR flags, see ESP_BT_EIR_FLAG for details, EIR will not include flag if it is 0, 0 by default - uint16_t manufacturer_len Manufacturer data length, 0 by default - uint8_t *p_manufacturer_data Manufacturer data point - uint16_t url_len URL length, 0 by default - uint8_t *p_url URL point - bool fec_required Macros - ESP_BT_GAP_RSSI_HIGH_THRLD RSSI threshold. High RSSI threshold - ESP_BT_GAP_RSSI_LOW_THRLD Low RSSI threshold - ESP_BT_GAP_AFH_CHANNELS_LEN - ESP_BT_GAP_MAX_BDNAME_LEN Maximum bytes of Bluetooth device name. - ESP_BT_GAP_EIR_DATA_LEN Maximum size of EIR Significant part. - ESP_BT_EIR_TYPE_FLAGS Extended Inquiry Response data type. Flag with information such as BR/EDR and LE support - ESP_BT_EIR_TYPE_INCMPL_16BITS_UUID Incomplete list of 16-bit service UUIDs - ESP_BT_EIR_TYPE_CMPL_16BITS_UUID Complete list of 16-bit service UUIDs - ESP_BT_EIR_TYPE_INCMPL_32BITS_UUID Incomplete list of 32-bit service UUIDs - ESP_BT_EIR_TYPE_CMPL_32BITS_UUID Complete list of 32-bit service UUIDs - ESP_BT_EIR_TYPE_INCMPL_128BITS_UUID Incomplete list of 128-bit service UUIDs - ESP_BT_EIR_TYPE_CMPL_128BITS_UUID Complete list of 128-bit service UUIDs - ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME Shortened Local Name - ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME Complete Local Name - ESP_BT_EIR_TYPE_TX_POWER_LEVEL Tx power level, value is 1 octet ranging from -127 to 127, unit is dBm - ESP_BT_EIR_TYPE_URL Uniform resource identifier - ESP_BT_EIR_TYPE_MANU_SPECIFIC Manufacturer specific data - ESP_BT_EIR_TYPE_MAX_NUM MAX number of EIR type - ESP_BT_ACL_PKT_TYPES_MASK_DM1 - ESP_BT_ACL_PKT_TYPES_MASK_DH1 - ESP_BT_ACL_PKT_TYPES_MASK_DM3 - ESP_BT_ACL_PKT_TYPES_MASK_DH3 - ESP_BT_ACL_PKT_TYPES_MASK_DM5 - ESP_BT_ACL_PKT_TYPES_MASK_DH5 - ESP_BT_ACL_PKT_TYPES_MASK_NO_2_DH1 - ESP_BT_ACL_PKT_TYPES_MASK_NO_3_DH1 - ESP_BT_ACL_PKT_TYPES_MASK_NO_2_DH3 - ESP_BT_ACL_PKT_TYPES_MASK_NO_3_DH3 - ESP_BT_ACL_PKT_TYPES_MASK_NO_2_DH5 - ESP_BT_ACL_PKT_TYPES_MASK_NO_3_DH5 - ESP_BT_ACL_DM1_ONLY - ESP_BT_ACL_DH1_ONLY - ESP_BT_ACL_DM3_ONLY - ESP_BT_ACL_DH3_ONLY - ESP_BT_ACL_DM5_ONLY - ESP_BT_ACL_DH5_ONLY - ESP_BT_ACL_2_DH1_ONLY - ESP_BT_ACL_3_DH1_ONLY - ESP_BT_ACL_2_DH3_ONLY - ESP_BT_ACL_3_DH3_ONLY - ESP_BT_ACL_2_DH5_ONLY - ESP_BT_ACL_3_DH5_ONLY - ESP_BT_EIR_FLAG_LIMIT_DISC - ESP_BT_EIR_FLAG_GEN_DISC - ESP_BT_EIR_FLAG_BREDR_NOT_SPT - ESP_BT_EIR_FLAG_DMT_CONTROLLER_SPT - ESP_BT_EIR_FLAG_DMT_HOST_SPT - ESP_BT_EIR_MAX_LEN - ESP_BT_PIN_CODE_LEN Max pin code length - ESP_BT_IO_CAP_OUT - ESP_BT_IO_CAP_IO - ESP_BT_IO_CAP_IN - ESP_BT_IO_CAP_NONE - ESP_BT_PM_MD_ACTIVE Active mode - ESP_BT_PM_MD_HOLD Hold mode - ESP_BT_PM_MD_SNIFF Sniff mode - ESP_BT_PM_MD_PARK Park state - ESP_BT_COD_SRVC_BIT_MASK Bits of major service class field. Major service bit mask - ESP_BT_COD_SRVC_BIT_OFFSET Major service bit offset - ESP_BT_COD_MAJOR_DEV_BIT_MASK Bits of major device class field. Major device bit mask - ESP_BT_COD_MAJOR_DEV_BIT_OFFSET Major device bit offset - ESP_BT_COD_MINOR_DEV_BIT_MASK Bits of minor device class field. Minor device bit mask - ESP_BT_COD_MINOR_DEV_BIT_OFFSET Minor device bit offset - ESP_BT_COD_FORMAT_TYPE_BIT_MASK Bits of format type. Format type bit mask - ESP_BT_COD_FORMAT_TYPE_BIT_OFFSET Format type bit offset - ESP_BT_COD_FORMAT_TYPE_1 Class of device format type 1. - ESP_BT_LINK_KEY_COMB Type of link key. Combination Key - ESP_BT_LINK_KEY_DBG_COMB Debug Combination Key - ESP_BT_LINK_KEY_UNAUTHED_COMB_P192 Unauthenticated Combination Key generated from P-192 - ESP_BT_LINK_KEY_AUTHED_COMB_P192 Authenticated Combination Key generated from P-192 - ESP_BT_LINK_KEY_CHG_COMB Changed Combination Key - ESP_BT_LINK_KEY_UNAUTHED_COMB_P256 Unauthenticated Combination Key generated from P-256 - ESP_BT_LINK_KEY_AUTHED_COMB_P256 Authenticated Combination Key generated from P-256 - ESP_BT_ENC_MODE_OFF Type of encryption. Link Level Encryption is OFF - ESP_BT_ENC_MODE_E0 Link Level Encryption is ON with E0 - ESP_BT_ENC_MODE_AES Link Level Encryption is ON with AES-CCM - ESP_BT_GAP_MIN_INQ_LEN Minimum and Maximum inquiry length Minimum inquiry duration, unit is 1.28s - ESP_BT_GAP_MAX_INQ_LEN Maximum inquiry duration, unit is 1.28s - ESP_BT_GAP_TPOLL_MIN Minimum, Default and Maximum poll interval Minimum poll interval, unit is 625 microseconds - ESP_BT_GAP_TPOLL_DFT Default poll interval, unit is 625 microseconds - ESP_BT_GAP_TPOLL_MAX Maximum poll interval, unit is 625 microseconds Type Definitions - typedef uint8_t esp_bt_gap_afh_channels[ESP_BT_GAP_AFH_CHANNELS_LEN] - typedef uint8_t esp_bt_eir_type_t - typedef uint16_t esp_bt_acl_pkt_type_t - typedef uint8_t esp_bt_pin_code_t[ESP_BT_PIN_CODE_LEN] Pin Code (upto 128 bits) MSB is 0 - typedef uint8_t esp_bt_io_cap_t Combination of the IO Capability - typedef uint8_t esp_bt_pm_mode_t - typedef uint8_t esp_bt_link_key_type_t - typedef uint8_t esp_bt_enc_mode_t - typedef void (*esp_bt_gap_cb_t)(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param) bluetooth GAP callback function type - Param event : Event type - Param param : Pointer to callback parameter Enumerations - enum esp_bt_cod_mode_t class of device settings Values: - enumerator ESP_BT_SET_COD_MAJOR_MINOR overwrite major, minor class - enumerator ESP_BT_SET_COD_SERVICE_CLASS set the bits in the input, the current bit will remain - enumerator ESP_BT_CLR_COD_SERVICE_CLASS clear the bits in the input, others will remain - enumerator ESP_BT_SET_COD_ALL overwrite major, minor, set the bits in service class - enumerator ESP_BT_INIT_COD overwrite major, minor, and service class - enumerator ESP_BT_SET_COD_MAJOR_MINOR - enum esp_bt_connection_mode_t Discoverability and Connectability mode. Values: - enumerator ESP_BT_NON_CONNECTABLE Non-connectable - enumerator ESP_BT_CONNECTABLE Connectable - enumerator ESP_BT_NON_CONNECTABLE - enum esp_bt_discovery_mode_t Values: - enumerator ESP_BT_NON_DISCOVERABLE Non-discoverable - enumerator ESP_BT_LIMITED_DISCOVERABLE Limited Discoverable - enumerator ESP_BT_GENERAL_DISCOVERABLE General Discoverable - enumerator ESP_BT_NON_DISCOVERABLE - enum esp_bt_gap_dev_prop_type_t Bluetooth Device Property type. Values: - enumerator ESP_BT_GAP_DEV_PROP_BDNAME Bluetooth device name, value type is int8_t [] - enumerator ESP_BT_GAP_DEV_PROP_COD Class of Device, value type is uint32_t - enumerator ESP_BT_GAP_DEV_PROP_RSSI Received Signal strength Indication, value type is int8_t, ranging from -128 to 127 - enumerator ESP_BT_GAP_DEV_PROP_EIR Extended Inquiry Response, value type is uint8_t [] - enumerator ESP_BT_GAP_DEV_PROP_BDNAME - enum esp_bt_cod_srvc_t Major service class field of Class of Device, mutiple bits can be set. Values: - enumerator ESP_BT_COD_SRVC_NONE None indicates an invalid value - enumerator ESP_BT_COD_SRVC_LMTD_DISCOVER Limited Discoverable Mode - enumerator ESP_BT_COD_SRVC_POSITIONING Positioning (Location identification) - enumerator ESP_BT_COD_SRVC_NETWORKING Networking, e.g. LAN, Ad hoc - enumerator ESP_BT_COD_SRVC_RENDERING Rendering, e.g. Printing, Speakers - enumerator ESP_BT_COD_SRVC_CAPTURING Capturing, e.g. Scanner, Microphone - enumerator ESP_BT_COD_SRVC_OBJ_TRANSFER Object Transfer, e.g. v-Inbox, v-Folder - enumerator ESP_BT_COD_SRVC_AUDIO Audio, e.g. Speaker, Microphone, Headset service - enumerator ESP_BT_COD_SRVC_TELEPHONY Telephony, e.g. Cordless telephony, Modem, Headset service - enumerator ESP_BT_COD_SRVC_INFORMATION Information, e.g., WEB-server, WAP-server - enumerator ESP_BT_COD_SRVC_NONE - enum esp_bt_pin_type_t Values: - enumerator ESP_BT_PIN_TYPE_VARIABLE Refer to BTM_PIN_TYPE_VARIABLE - enumerator ESP_BT_PIN_TYPE_FIXED Refer to BTM_PIN_TYPE_FIXED - enumerator ESP_BT_PIN_TYPE_VARIABLE - enum esp_bt_cod_major_dev_t Major device class field of Class of Device. Values: - enumerator ESP_BT_COD_MAJOR_DEV_MISC Miscellaneous - enumerator ESP_BT_COD_MAJOR_DEV_COMPUTER Computer - enumerator ESP_BT_COD_MAJOR_DEV_PHONE Phone(cellular, cordless, pay phone, modem - enumerator ESP_BT_COD_MAJOR_DEV_LAN_NAP LAN, Network Access Point - enumerator ESP_BT_COD_MAJOR_DEV_AV Audio/Video(headset, speaker, stereo, video display, VCR - enumerator ESP_BT_COD_MAJOR_DEV_PERIPHERAL Peripheral(mouse, joystick, keyboard) - enumerator ESP_BT_COD_MAJOR_DEV_IMAGING Imaging(printer, scanner, camera, display - enumerator ESP_BT_COD_MAJOR_DEV_WEARABLE Wearable - enumerator ESP_BT_COD_MAJOR_DEV_TOY Toy - enumerator ESP_BT_COD_MAJOR_DEV_HEALTH Health - enumerator ESP_BT_COD_MAJOR_DEV_UNCATEGORIZED Uncategorized: device not specified - enumerator ESP_BT_COD_MAJOR_DEV_MISC - enum esp_bt_gap_discovery_state_t Bluetooth Device Discovery state Values: - enumerator ESP_BT_GAP_DISCOVERY_STOPPED Device discovery stopped - enumerator ESP_BT_GAP_DISCOVERY_STARTED Device discovery started - enumerator ESP_BT_GAP_DISCOVERY_STOPPED - enum esp_bt_gap_cb_event_t BT GAP callback events. Values: - enumerator ESP_BT_GAP_DISC_RES_EVT Device discovery result event - enumerator ESP_BT_GAP_DISC_STATE_CHANGED_EVT Discovery state changed event - enumerator ESP_BT_GAP_RMT_SRVCS_EVT Get remote services event - enumerator ESP_BT_GAP_RMT_SRVC_REC_EVT Get remote service record event - enumerator ESP_BT_GAP_AUTH_CMPL_EVT Authentication complete event - enumerator ESP_BT_GAP_PIN_REQ_EVT Legacy Pairing Pin code request - enumerator ESP_BT_GAP_CFM_REQ_EVT Security Simple Pairing User Confirmation request. - enumerator ESP_BT_GAP_KEY_NOTIF_EVT Security Simple Pairing Passkey Notification - enumerator ESP_BT_GAP_KEY_REQ_EVT Security Simple Pairing Passkey request - enumerator ESP_BT_GAP_READ_RSSI_DELTA_EVT Read rssi event - enumerator ESP_BT_GAP_CONFIG_EIR_DATA_EVT Config EIR data event - enumerator ESP_BT_GAP_SET_AFH_CHANNELS_EVT Set AFH channels event - enumerator ESP_BT_GAP_READ_REMOTE_NAME_EVT Read Remote Name event - enumerator ESP_BT_GAP_MODE_CHG_EVT - enumerator ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT remove bond device complete event - enumerator ESP_BT_GAP_QOS_CMPL_EVT QOS complete event - enumerator ESP_BT_GAP_ACL_CONN_CMPL_STAT_EVT ACL connection complete status event - enumerator ESP_BT_GAP_ACL_DISCONN_CMPL_STAT_EVT ACL disconnection complete status event - enumerator ESP_BT_GAP_SET_PAGE_TO_EVT Set page timeout event - enumerator ESP_BT_GAP_GET_PAGE_TO_EVT Get page timeout event - enumerator ESP_BT_GAP_ACL_PKT_TYPE_CHANGED_EVT Set ACL packet types event - enumerator ESP_BT_GAP_ENC_CHG_EVT Encryption change event - enumerator ESP_BT_GAP_EVT_MAX - enumerator ESP_BT_GAP_DISC_RES_EVT
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_gap_bt.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Bluetooth® A2DP API
null
espressif.com
2016-01-01
2450341eee239b51
null
null
Bluetooth® A2DP API Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the following application: This is a A2DP sink client demo. This demo can be discovered and connected by A2DP source device and receive the audio stream from remote device - bluetooth/bluedroid/classic_bt/a2dp_sink API Reference Header File This header file can be included with: #include "esp_a2dp_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_a2d_register_callback(esp_a2d_cb_t callback) Register application callback function to A2DP module. This function should be called only after esp_bluedroid_enable() completes successfully, used by both A2DP source and sink. Parameters callback -- [in] A2DP event callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer ESP_OK: success Parameters callback -- [in] A2DP event callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer esp_err_t esp_a2d_sink_register_data_callback(esp_a2d_sink_data_cb_t callback) Register A2DP sink data output function; For now the output is PCM data stream decoded from SBC format. This function should be called only after esp_bluedroid_enable() completes successfully, used only by A2DP sink. The callback is invoked in the context of A2DP sink task whose stack size is configurable through menuconfig. Parameters callback -- [in] A2DP sink data callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer ESP_OK: success Parameters callback -- [in] A2DP sink data callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer esp_err_t esp_a2d_sink_init(void) Initialize the bluetooth A2DP sink module. This function should be called after esp_bluedroid_enable() completes successfully, and ESP_A2D_PROF_STATE_EVT with ESP_A2D_INIT_SUCCESS will reported to the APP layer. Note: A2DP can work independently. If you want to use AVRC together, you should initiate AVRC first. This function should be called after esp_bluedroid_enable() completes successfully. Returns ESP_OK: if the initialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the initialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the initialization request is sent successfully Returns ESP_OK: if the initialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_a2d_sink_deinit(void) De-initialize for A2DP sink module. This function should be called only after esp_bluedroid_enable() completes successfully, and ESP_A2D_PROF_STATE_EVT with ESP_A2D_DEINIT_SUCCESS will reported to APP layer. Returns ESP_OK: if the deinitialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the deinitialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the deinitialization request is sent successfully Returns ESP_OK: if the deinitialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_a2d_sink_connect(esp_bd_addr_t remote_bda) Connect to remote bluetooth A2DP source device. This API must be called after esp_a2d_sink_init() and before esp_a2d_sink_deinit(). Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: connect request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: connect request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: connect request is sent to lower layer successfully Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: connect request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_a2d_sink_disconnect(esp_bd_addr_t remote_bda) Disconnect from the remote A2DP source device. This API must be called after esp_a2d_sink_init() and before esp_a2d_sink_deinit(). Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: disconnect request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: disconnect request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: disconnect request is sent to lower layer successfully Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: disconnect request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_a2d_sink_set_delay_value(uint16_t delay_value) Set delay reporting value. The delay value of sink is caused by buffering (including protocol stack and application layer), decoding and rendering. The default delay value is 120ms, if the set value is less than 120ms, the setting will fail. This API must be called after esp_a2d_sink_init() and before esp_a2d_sink_deinit(). Parameters delay_value -- [in] reporting value is in 1/10 millisecond Returns ESP_OK: delay value is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: delay value is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: delay value is sent to lower layer successfully Parameters delay_value -- [in] reporting value is in 1/10 millisecond Returns ESP_OK: delay value is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_a2d_sink_get_delay_value(void) Get delay reporting value. This API must be called after esp_a2d_sink_init() and before esp_a2d_sink_deinit(). Returns ESP_OK: if the request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the request is sent successfully Returns ESP_OK: if the request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_a2d_media_ctrl(esp_a2d_media_ctrl_t ctrl) Media control commands. This API can be used for both A2DP sink and source and must be called after esp_a2d_sink_init() and before esp_a2d_sink_deinit(). Parameters ctrl -- [in] control commands for A2DP data channel Returns ESP_OK: control command is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: control command is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: control command is sent to lower layer successfully Parameters ctrl -- [in] control commands for A2DP data channel Returns ESP_OK: control command is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_a2d_source_init(void) Initialize the bluetooth A2DP source module. A2DP can work independently. If you want to use AVRC together, you should initiate AVRC first. This function should be called after esp_bluedroid_enable() completes successfully, and ESP_A2D_PROF_STATE_EVT with ESP_A2D_INIT_SUCCESS will reported to the APP layer. Note: A2DP can work independently. If you want to use AVRC together, you should initiate AVRC first. Returns ESP_OK: if the initialization request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the initialization request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the initialization request is sent to lower layer successfully Returns ESP_OK: if the initialization request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_a2d_source_deinit(void) De-initialize for A2DP source module. This function should be called only after esp_bluedroid_enable() completes successfully, and ESP_A2D_PROF_STATE_EVT with ESP_A2D_DEINIT_SUCCESS will reported to APP layer. Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_a2d_source_register_data_callback(esp_a2d_source_data_cb_t callback) Register A2DP source data input function. For now, the input shoule be PCM data stream. This function should be called only after esp_bluedroid_enable() completes successfully. The callback is invoked in the context of A2DP source task whose stack size is configurable through menuconfig. Parameters callback -- [in] A2DP source data callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer ESP_OK: success Parameters callback -- [in] A2DP source data callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer esp_err_t esp_a2d_source_connect(esp_bd_addr_t remote_bda) Connect to remote A2DP sink device. This API must be called after esp_a2d_source_init() and before esp_a2d_source_deinit(). Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: connect request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: connect request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: connect request is sent to lower layer successfully Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: connect request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_a2d_source_disconnect(esp_bd_addr_t remote_bda) Disconnect from the remote A2DP sink device. This API must be called after esp_a2d_source_init() and before esp_a2d_source_deinit(). Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: disconnect request is sent to lower layer Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others Unions union esp_a2d_cb_param_t #include <esp_a2dp_api.h> A2DP state callback parameters. Public Members struct esp_a2d_cb_param_t::a2d_conn_stat_param conn_stat A2DP connection status struct esp_a2d_cb_param_t::a2d_conn_stat_param conn_stat A2DP connection status struct esp_a2d_cb_param_t::a2d_audio_stat_param audio_stat audio stream playing state struct esp_a2d_cb_param_t::a2d_audio_stat_param audio_stat audio stream playing state struct esp_a2d_cb_param_t::a2d_audio_cfg_param audio_cfg media codec configuration information struct esp_a2d_cb_param_t::a2d_audio_cfg_param audio_cfg media codec configuration information struct esp_a2d_cb_param_t::media_ctrl_stat_param media_ctrl_stat status in acknowledgement to media control commands struct esp_a2d_cb_param_t::media_ctrl_stat_param media_ctrl_stat status in acknowledgement to media control commands struct esp_a2d_cb_param_t::a2d_prof_stat_param a2d_prof_stat status to indicate a2d prof init or deinit struct esp_a2d_cb_param_t::a2d_prof_stat_param a2d_prof_stat status to indicate a2d prof init or deinit struct esp_a2d_cb_param_t::a2d_psc_cfg_param a2d_psc_cfg_stat status to indicate protocol service capabilities configured struct esp_a2d_cb_param_t::a2d_psc_cfg_param a2d_psc_cfg_stat status to indicate protocol service capabilities configured struct esp_a2d_cb_param_t::a2d_set_stat_param a2d_set_delay_value_stat A2DP sink set delay report value status struct esp_a2d_cb_param_t::a2d_set_stat_param a2d_set_delay_value_stat A2DP sink set delay report value status struct esp_a2d_cb_param_t::a2d_get_stat_param a2d_get_delay_value_stat A2DP sink get delay report value status struct esp_a2d_cb_param_t::a2d_get_stat_param a2d_get_delay_value_stat A2DP sink get delay report value status struct esp_a2d_cb_param_t::a2d_report_delay_stat_param a2d_report_delay_value_stat A2DP source received sink report value status struct esp_a2d_cb_param_t::a2d_report_delay_stat_param a2d_report_delay_value_stat A2DP source received sink report value status struct a2d_audio_cfg_param #include <esp_a2dp_api.h> ESP_A2D_AUDIO_CFG_EVT. Public Members esp_bd_addr_t remote_bda remote bluetooth device address esp_bd_addr_t remote_bda remote bluetooth device address esp_a2d_mcc_t mcc A2DP media codec capability information esp_a2d_mcc_t mcc A2DP media codec capability information esp_bd_addr_t remote_bda struct a2d_audio_cfg_param #include <esp_a2dp_api.h> ESP_A2D_AUDIO_CFG_EVT. Public Members esp_bd_addr_t remote_bda remote bluetooth device address esp_a2d_mcc_t mcc A2DP media codec capability information struct a2d_audio_stat_param #include <esp_a2dp_api.h> ESP_A2D_AUDIO_STATE_EVT. Public Members esp_a2d_audio_state_t state one of the values from esp_a2d_audio_state_t esp_a2d_audio_state_t state one of the values from esp_a2d_audio_state_t esp_bd_addr_t remote_bda remote bluetooth device address esp_bd_addr_t remote_bda remote bluetooth device address esp_a2d_audio_state_t state struct a2d_audio_stat_param #include <esp_a2dp_api.h> ESP_A2D_AUDIO_STATE_EVT. Public Members esp_a2d_audio_state_t state one of the values from esp_a2d_audio_state_t esp_bd_addr_t remote_bda remote bluetooth device address struct a2d_conn_stat_param #include <esp_a2dp_api.h> ESP_A2D_CONNECTION_STATE_EVT. Public Members esp_a2d_connection_state_t state one of values from esp_a2d_connection_state_t esp_a2d_connection_state_t state one of values from esp_a2d_connection_state_t esp_bd_addr_t remote_bda remote bluetooth device address esp_bd_addr_t remote_bda remote bluetooth device address esp_a2d_disc_rsn_t disc_rsn reason of disconnection for "DISCONNECTED" esp_a2d_disc_rsn_t disc_rsn reason of disconnection for "DISCONNECTED" esp_a2d_connection_state_t state struct a2d_conn_stat_param #include <esp_a2dp_api.h> ESP_A2D_CONNECTION_STATE_EVT. Public Members esp_a2d_connection_state_t state one of values from esp_a2d_connection_state_t esp_bd_addr_t remote_bda remote bluetooth device address esp_a2d_disc_rsn_t disc_rsn reason of disconnection for "DISCONNECTED" struct a2d_get_stat_param #include <esp_a2dp_api.h> ESP_A2D_SNK_GET_DELAY_VALUE_EVT. Public Members uint16_t delay_value delay report value uint16_t delay_value delay report value uint16_t delay_value struct a2d_get_stat_param #include <esp_a2dp_api.h> ESP_A2D_SNK_GET_DELAY_VALUE_EVT. Public Members uint16_t delay_value delay report value struct a2d_prof_stat_param #include <esp_a2dp_api.h> ESP_A2D_PROF_STATE_EVT. Public Members esp_a2d_init_state_t init_state a2dp profile state param esp_a2d_init_state_t init_state a2dp profile state param esp_a2d_init_state_t init_state struct a2d_prof_stat_param #include <esp_a2dp_api.h> ESP_A2D_PROF_STATE_EVT. Public Members esp_a2d_init_state_t init_state a2dp profile state param struct a2d_psc_cfg_param #include <esp_a2dp_api.h> ESP_A2D_SNK_PSC_CFG_EVT. Public Members esp_a2d_psc_t psc_mask protocol service capabilities configured esp_a2d_psc_t psc_mask protocol service capabilities configured esp_a2d_psc_t psc_mask struct a2d_psc_cfg_param #include <esp_a2dp_api.h> ESP_A2D_SNK_PSC_CFG_EVT. Public Members esp_a2d_psc_t psc_mask protocol service capabilities configured struct a2d_report_delay_stat_param #include <esp_a2dp_api.h> ESP_A2D_REPORT_SNK_DELAY_VALUE_EVT. Public Members uint16_t delay_value delay report value uint16_t delay_value delay report value uint16_t delay_value struct a2d_report_delay_stat_param #include <esp_a2dp_api.h> ESP_A2D_REPORT_SNK_DELAY_VALUE_EVT. Public Members uint16_t delay_value delay report value struct a2d_set_stat_param #include <esp_a2dp_api.h> ESP_A2D_SNK_SET_DELAY_VALUE_EVT. Public Members esp_a2d_set_delay_value_state_t set_state a2dp profile state param esp_a2d_set_delay_value_state_t set_state a2dp profile state param uint16_t delay_value delay report value uint16_t delay_value delay report value esp_a2d_set_delay_value_state_t set_state struct a2d_set_stat_param #include <esp_a2dp_api.h> ESP_A2D_SNK_SET_DELAY_VALUE_EVT. Public Members esp_a2d_set_delay_value_state_t set_state a2dp profile state param uint16_t delay_value delay report value struct media_ctrl_stat_param #include <esp_a2dp_api.h> ESP_A2D_MEDIA_CTRL_ACK_EVT. Public Members esp_a2d_media_ctrl_t cmd media control commands to acknowledge esp_a2d_media_ctrl_t cmd media control commands to acknowledge esp_a2d_media_ctrl_ack_t status acknowledgement to media control commands esp_a2d_media_ctrl_ack_t status acknowledgement to media control commands esp_a2d_media_ctrl_t cmd struct media_ctrl_stat_param #include <esp_a2dp_api.h> ESP_A2D_MEDIA_CTRL_ACK_EVT. Public Members esp_a2d_media_ctrl_t cmd media control commands to acknowledge esp_a2d_media_ctrl_ack_t status acknowledgement to media control commands struct esp_a2d_cb_param_t::a2d_conn_stat_param conn_stat Structures struct esp_a2d_mcc_t A2DP media codec capabilities union. Public Members esp_a2d_mct_t type A2DP media codec type esp_a2d_mct_t type A2DP media codec type uint8_t sbc[ESP_A2D_CIE_LEN_SBC] SBC codec capabilities uint8_t sbc[ESP_A2D_CIE_LEN_SBC] SBC codec capabilities uint8_t m12[ESP_A2D_CIE_LEN_M12] MPEG-1,2 audio codec capabilities uint8_t m12[ESP_A2D_CIE_LEN_M12] MPEG-1,2 audio codec capabilities uint8_t m24[ESP_A2D_CIE_LEN_M24] MPEG-2, 4 AAC audio codec capabilities uint8_t m24[ESP_A2D_CIE_LEN_M24] MPEG-2, 4 AAC audio codec capabilities uint8_t atrac[ESP_A2D_CIE_LEN_ATRAC] ATRAC family codec capabilities uint8_t atrac[ESP_A2D_CIE_LEN_ATRAC] ATRAC family codec capabilities union esp_a2d_mcc_t::[anonymous] cie A2DP codec information element union esp_a2d_mcc_t::[anonymous] cie A2DP codec information element esp_a2d_mct_t type Macros ESP_A2D_MCT_SBC Media codec types supported by A2DP. SBC ESP_A2D_MCT_M12 MPEG-1, 2 Audio ESP_A2D_MCT_M24 MPEG-2, 4 AAC ESP_A2D_MCT_ATRAC ATRAC family ESP_A2D_MCT_NON_A2DP NON-A2DP ESP_A2D_PSC_DELAY_RPT Protocol service capabilities. This value is a mask. Delay Report ESP_A2D_CIE_LEN_SBC ESP_A2D_CIE_LEN_M12 ESP_A2D_CIE_LEN_M24 ESP_A2D_CIE_LEN_ATRAC Type Definitions typedef uint8_t esp_a2d_mct_t typedef uint16_t esp_a2d_psc_t typedef void (*esp_a2d_cb_t)(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param) A2DP profile callback function type. Param event : Event type Param param : Pointer to callback parameter Param event : Event type Param param : Pointer to callback parameter typedef void (*esp_a2d_sink_data_cb_t)(const uint8_t *buf, uint32_t len) A2DP sink data callback function. Param buf [in] : pointer to the data received from A2DP source device and is PCM format decoded from SBC decoder; buf references to a static memory block and can be overwritten by upcoming data Param len [in] : size(in bytes) in buf Param buf [in] : pointer to the data received from A2DP source device and is PCM format decoded from SBC decoder; buf references to a static memory block and can be overwritten by upcoming data Param len [in] : size(in bytes) in buf typedef int32_t (*esp_a2d_source_data_cb_t)(uint8_t *buf, int32_t len) A2DP source data read callback function. Param buf [in] : buffer to be filled with PCM data stream from higher layer Param len [in] : size(in bytes) of data block to be copied to buf. -1 is an indication to user that data buffer shall be flushed Return size of bytes read successfully, if the argument len is -1, this value is ignored. Param buf [in] : buffer to be filled with PCM data stream from higher layer Param len [in] : size(in bytes) of data block to be copied to buf. -1 is an indication to user that data buffer shall be flushed Return size of bytes read successfully, if the argument len is -1, this value is ignored. Enumerations enum esp_a2d_connection_state_t Bluetooth A2DP connection states. Values: enumerator ESP_A2D_CONNECTION_STATE_DISCONNECTED connection released enumerator ESP_A2D_CONNECTION_STATE_DISCONNECTED connection released enumerator ESP_A2D_CONNECTION_STATE_CONNECTING connecting remote device enumerator ESP_A2D_CONNECTION_STATE_CONNECTING connecting remote device enumerator ESP_A2D_CONNECTION_STATE_CONNECTED connection established enumerator ESP_A2D_CONNECTION_STATE_CONNECTED connection established enumerator ESP_A2D_CONNECTION_STATE_DISCONNECTING disconnecting remote device enumerator ESP_A2D_CONNECTION_STATE_DISCONNECTING disconnecting remote device enumerator ESP_A2D_CONNECTION_STATE_DISCONNECTED enum esp_a2d_disc_rsn_t Bluetooth A2DP disconnection reason. Values: enumerator ESP_A2D_DISC_RSN_NORMAL Finished disconnection that is initiated by local or remote device enumerator ESP_A2D_DISC_RSN_NORMAL Finished disconnection that is initiated by local or remote device enumerator ESP_A2D_DISC_RSN_ABNORMAL Abnormal disconnection caused by signal loss enumerator ESP_A2D_DISC_RSN_ABNORMAL Abnormal disconnection caused by signal loss enumerator ESP_A2D_DISC_RSN_NORMAL enum esp_a2d_audio_state_t Bluetooth A2DP datapath states. Values: enumerator ESP_A2D_AUDIO_STATE_SUSPEND audio stream datapath suspended by remote device enumerator ESP_A2D_AUDIO_STATE_SUSPEND audio stream datapath suspended by remote device enumerator ESP_A2D_AUDIO_STATE_STARTED audio stream datapath started enumerator ESP_A2D_AUDIO_STATE_STARTED audio stream datapath started enumerator ESP_A2D_AUDIO_STATE_STOPPED Note Deprecated enumerator ESP_A2D_AUDIO_STATE_STOPPED Note Deprecated enumerator ESP_A2D_AUDIO_STATE_REMOTE_SUSPEND Note Deprecated enumerator ESP_A2D_AUDIO_STATE_REMOTE_SUSPEND Note Deprecated enumerator ESP_A2D_AUDIO_STATE_SUSPEND enum esp_a2d_media_ctrl_ack_t A2DP media control command acknowledgement code. Values: enumerator ESP_A2D_MEDIA_CTRL_ACK_SUCCESS media control command is acknowledged with success enumerator ESP_A2D_MEDIA_CTRL_ACK_SUCCESS media control command is acknowledged with success enumerator ESP_A2D_MEDIA_CTRL_ACK_FAILURE media control command is acknowledged with failure enumerator ESP_A2D_MEDIA_CTRL_ACK_FAILURE media control command is acknowledged with failure enumerator ESP_A2D_MEDIA_CTRL_ACK_BUSY media control command is rejected, as previous command is not yet acknowledged enumerator ESP_A2D_MEDIA_CTRL_ACK_BUSY media control command is rejected, as previous command is not yet acknowledged enumerator ESP_A2D_MEDIA_CTRL_ACK_SUCCESS enum esp_a2d_media_ctrl_t A2DP media control commands. Values: enumerator ESP_A2D_MEDIA_CTRL_NONE Not for application use, use inside stack only. enumerator ESP_A2D_MEDIA_CTRL_NONE Not for application use, use inside stack only. enumerator ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY check whether AVDTP is connected, only used in A2DP source enumerator ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY check whether AVDTP is connected, only used in A2DP source enumerator ESP_A2D_MEDIA_CTRL_START command to set up media transmission channel enumerator ESP_A2D_MEDIA_CTRL_START command to set up media transmission channel enumerator ESP_A2D_MEDIA_CTRL_SUSPEND command to suspend media transmission enumerator ESP_A2D_MEDIA_CTRL_SUSPEND command to suspend media transmission enumerator ESP_A2D_MEDIA_CTRL_STOP Note Deprecated, Please use ESP_A2D_MEDIA_CTRL_SUSPEND enumerator ESP_A2D_MEDIA_CTRL_STOP Note Deprecated, Please use ESP_A2D_MEDIA_CTRL_SUSPEND enumerator ESP_A2D_MEDIA_CTRL_NONE enum esp_a2d_init_state_t Bluetooth A2DP Initiation states. Values: enumerator ESP_A2D_DEINIT_SUCCESS A2DP profile deinit successful event enumerator ESP_A2D_DEINIT_SUCCESS A2DP profile deinit successful event enumerator ESP_A2D_INIT_SUCCESS A2DP profile deinit successful event enumerator ESP_A2D_INIT_SUCCESS A2DP profile deinit successful event enumerator ESP_A2D_DEINIT_SUCCESS enum esp_a2d_set_delay_value_state_t Bluetooth A2DP set delay report value states. Values: enumerator ESP_A2D_SET_SUCCESS A2DP profile set delay report value successful enumerator ESP_A2D_SET_SUCCESS A2DP profile set delay report value successful enumerator ESP_A2D_SET_INVALID_PARAMS A2DP profile set delay report value is invalid parameter enumerator ESP_A2D_SET_INVALID_PARAMS A2DP profile set delay report value is invalid parameter enumerator ESP_A2D_SET_SUCCESS enum esp_a2d_cb_event_t A2DP callback events. Values: enumerator ESP_A2D_CONNECTION_STATE_EVT connection state changed event enumerator ESP_A2D_CONNECTION_STATE_EVT connection state changed event enumerator ESP_A2D_AUDIO_STATE_EVT audio stream transmission state changed event enumerator ESP_A2D_AUDIO_STATE_EVT audio stream transmission state changed event enumerator ESP_A2D_AUDIO_CFG_EVT audio codec is configured, only used for A2DP SINK enumerator ESP_A2D_AUDIO_CFG_EVT audio codec is configured, only used for A2DP SINK enumerator ESP_A2D_MEDIA_CTRL_ACK_EVT acknowledge event in response to media control commands enumerator ESP_A2D_MEDIA_CTRL_ACK_EVT acknowledge event in response to media control commands enumerator ESP_A2D_PROF_STATE_EVT indicate a2dp init&deinit complete enumerator ESP_A2D_PROF_STATE_EVT indicate a2dp init&deinit complete enumerator ESP_A2D_SNK_PSC_CFG_EVT protocol service capabilities configured,only used for A2DP SINK enumerator ESP_A2D_SNK_PSC_CFG_EVT protocol service capabilities configured,only used for A2DP SINK enumerator ESP_A2D_SNK_SET_DELAY_VALUE_EVT indicate a2dp sink set delay report value complete, only used for A2DP SINK enumerator ESP_A2D_SNK_SET_DELAY_VALUE_EVT indicate a2dp sink set delay report value complete, only used for A2DP SINK enumerator ESP_A2D_SNK_GET_DELAY_VALUE_EVT indicate a2dp sink get delay report value complete, only used for A2DP SINK enumerator ESP_A2D_SNK_GET_DELAY_VALUE_EVT indicate a2dp sink get delay report value complete, only used for A2DP SINK enumerator ESP_A2D_REPORT_SNK_DELAY_VALUE_EVT report delay value, only used for A2DP SRC enumerator ESP_A2D_REPORT_SNK_DELAY_VALUE_EVT report delay value, only used for A2DP SRC enumerator ESP_A2D_CONNECTION_STATE_EVT
Bluetooth® A2DP API Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the following application: This is a A2DP sink client demo. This demo can be discovered and connected by A2DP source device and receive the audio stream from remote device - bluetooth/bluedroid/classic_bt/a2dp_sink API Reference Header File This header file can be included with: #include "esp_a2dp_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_a2d_register_callback(esp_a2d_cb_t callback) Register application callback function to A2DP module. This function should be called only after esp_bluedroid_enable() completes successfully, used by both A2DP source and sink. - Parameters callback -- [in] A2DP event callback function - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer - - esp_err_t esp_a2d_sink_register_data_callback(esp_a2d_sink_data_cb_t callback) Register A2DP sink data output function; For now the output is PCM data stream decoded from SBC format. This function should be called only after esp_bluedroid_enable() completes successfully, used only by A2DP sink. The callback is invoked in the context of A2DP sink task whose stack size is configurable through menuconfig. - Parameters callback -- [in] A2DP sink data callback function - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer - - esp_err_t esp_a2d_sink_init(void) Initialize the bluetooth A2DP sink module. This function should be called after esp_bluedroid_enable() completes successfully, and ESP_A2D_PROF_STATE_EVT with ESP_A2D_INIT_SUCCESS will reported to the APP layer. Note: A2DP can work independently. If you want to use AVRC together, you should initiate AVRC first. This function should be called after esp_bluedroid_enable() completes successfully. - Returns ESP_OK: if the initialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_a2d_sink_deinit(void) De-initialize for A2DP sink module. This function should be called only after esp_bluedroid_enable() completes successfully, and ESP_A2D_PROF_STATE_EVT with ESP_A2D_DEINIT_SUCCESS will reported to APP layer. - Returns ESP_OK: if the deinitialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_a2d_sink_connect(esp_bd_addr_t remote_bda) Connect to remote bluetooth A2DP source device. This API must be called after esp_a2d_sink_init() and before esp_a2d_sink_deinit(). - Parameters remote_bda -- [in] remote bluetooth device address - Returns ESP_OK: connect request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_a2d_sink_disconnect(esp_bd_addr_t remote_bda) Disconnect from the remote A2DP source device. This API must be called after esp_a2d_sink_init() and before esp_a2d_sink_deinit(). - Parameters remote_bda -- [in] remote bluetooth device address - Returns ESP_OK: disconnect request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_a2d_sink_set_delay_value(uint16_t delay_value) Set delay reporting value. The delay value of sink is caused by buffering (including protocol stack and application layer), decoding and rendering. The default delay value is 120ms, if the set value is less than 120ms, the setting will fail. This API must be called after esp_a2d_sink_init() and before esp_a2d_sink_deinit(). - Parameters delay_value -- [in] reporting value is in 1/10 millisecond - Returns ESP_OK: delay value is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_a2d_sink_get_delay_value(void) Get delay reporting value. This API must be called after esp_a2d_sink_init() and before esp_a2d_sink_deinit(). - Returns ESP_OK: if the request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_a2d_media_ctrl(esp_a2d_media_ctrl_t ctrl) Media control commands. This API can be used for both A2DP sink and source and must be called after esp_a2d_sink_init() and before esp_a2d_sink_deinit(). - Parameters ctrl -- [in] control commands for A2DP data channel - Returns ESP_OK: control command is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_a2d_source_init(void) Initialize the bluetooth A2DP source module. A2DP can work independently. If you want to use AVRC together, you should initiate AVRC first. This function should be called after esp_bluedroid_enable() completes successfully, and ESP_A2D_PROF_STATE_EVT with ESP_A2D_INIT_SUCCESS will reported to the APP layer. Note: A2DP can work independently. If you want to use AVRC together, you should initiate AVRC first. - Returns ESP_OK: if the initialization request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_a2d_source_deinit(void) De-initialize for A2DP source module. This function should be called only after esp_bluedroid_enable() completes successfully, and ESP_A2D_PROF_STATE_EVT with ESP_A2D_DEINIT_SUCCESS will reported to APP layer. - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_a2d_source_register_data_callback(esp_a2d_source_data_cb_t callback) Register A2DP source data input function. For now, the input shoule be PCM data stream. This function should be called only after esp_bluedroid_enable() completes successfully. The callback is invoked in the context of A2DP source task whose stack size is configurable through menuconfig. - Parameters callback -- [in] A2DP source data callback function - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer - - esp_err_t esp_a2d_source_connect(esp_bd_addr_t remote_bda) Connect to remote A2DP sink device. This API must be called after esp_a2d_source_init() and before esp_a2d_source_deinit(). - Parameters remote_bda -- [in] remote bluetooth device address - Returns ESP_OK: connect request is sent to lower layer successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_a2d_source_disconnect(esp_bd_addr_t remote_bda) Disconnect from the remote A2DP sink device. This API must be called after esp_a2d_source_init() and before esp_a2d_source_deinit(). - Parameters remote_bda -- [in] remote bluetooth device address - Returns ESP_OK: disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - Unions - union esp_a2d_cb_param_t - #include <esp_a2dp_api.h> A2DP state callback parameters. Public Members - struct esp_a2d_cb_param_t::a2d_conn_stat_param conn_stat A2DP connection status - struct esp_a2d_cb_param_t::a2d_audio_stat_param audio_stat audio stream playing state - struct esp_a2d_cb_param_t::a2d_audio_cfg_param audio_cfg media codec configuration information - struct esp_a2d_cb_param_t::media_ctrl_stat_param media_ctrl_stat status in acknowledgement to media control commands - struct esp_a2d_cb_param_t::a2d_prof_stat_param a2d_prof_stat status to indicate a2d prof init or deinit - struct esp_a2d_cb_param_t::a2d_psc_cfg_param a2d_psc_cfg_stat status to indicate protocol service capabilities configured - struct esp_a2d_cb_param_t::a2d_set_stat_param a2d_set_delay_value_stat A2DP sink set delay report value status - struct esp_a2d_cb_param_t::a2d_get_stat_param a2d_get_delay_value_stat A2DP sink get delay report value status - struct esp_a2d_cb_param_t::a2d_report_delay_stat_param a2d_report_delay_value_stat A2DP source received sink report value status - struct a2d_audio_cfg_param - #include <esp_a2dp_api.h> ESP_A2D_AUDIO_CFG_EVT. Public Members - esp_bd_addr_t remote_bda remote bluetooth device address - esp_a2d_mcc_t mcc A2DP media codec capability information - esp_bd_addr_t remote_bda - struct a2d_audio_stat_param - #include <esp_a2dp_api.h> ESP_A2D_AUDIO_STATE_EVT. Public Members - esp_a2d_audio_state_t state one of the values from esp_a2d_audio_state_t - esp_bd_addr_t remote_bda remote bluetooth device address - esp_a2d_audio_state_t state - struct a2d_conn_stat_param - #include <esp_a2dp_api.h> ESP_A2D_CONNECTION_STATE_EVT. Public Members - esp_a2d_connection_state_t state one of values from esp_a2d_connection_state_t - esp_bd_addr_t remote_bda remote bluetooth device address - esp_a2d_disc_rsn_t disc_rsn reason of disconnection for "DISCONNECTED" - esp_a2d_connection_state_t state - struct a2d_get_stat_param - #include <esp_a2dp_api.h> ESP_A2D_SNK_GET_DELAY_VALUE_EVT. Public Members - uint16_t delay_value delay report value - uint16_t delay_value - struct a2d_prof_stat_param - #include <esp_a2dp_api.h> ESP_A2D_PROF_STATE_EVT. Public Members - esp_a2d_init_state_t init_state a2dp profile state param - esp_a2d_init_state_t init_state - struct a2d_psc_cfg_param - #include <esp_a2dp_api.h> ESP_A2D_SNK_PSC_CFG_EVT. Public Members - esp_a2d_psc_t psc_mask protocol service capabilities configured - esp_a2d_psc_t psc_mask - struct a2d_report_delay_stat_param - #include <esp_a2dp_api.h> ESP_A2D_REPORT_SNK_DELAY_VALUE_EVT. Public Members - uint16_t delay_value delay report value - uint16_t delay_value - struct a2d_set_stat_param - #include <esp_a2dp_api.h> ESP_A2D_SNK_SET_DELAY_VALUE_EVT. Public Members - esp_a2d_set_delay_value_state_t set_state a2dp profile state param - uint16_t delay_value delay report value - esp_a2d_set_delay_value_state_t set_state - struct media_ctrl_stat_param - #include <esp_a2dp_api.h> ESP_A2D_MEDIA_CTRL_ACK_EVT. Public Members - esp_a2d_media_ctrl_t cmd media control commands to acknowledge - esp_a2d_media_ctrl_ack_t status acknowledgement to media control commands - esp_a2d_media_ctrl_t cmd - struct esp_a2d_cb_param_t::a2d_conn_stat_param conn_stat Structures - struct esp_a2d_mcc_t A2DP media codec capabilities union. Public Members - esp_a2d_mct_t type A2DP media codec type - uint8_t sbc[ESP_A2D_CIE_LEN_SBC] SBC codec capabilities - uint8_t m12[ESP_A2D_CIE_LEN_M12] MPEG-1,2 audio codec capabilities - uint8_t m24[ESP_A2D_CIE_LEN_M24] MPEG-2, 4 AAC audio codec capabilities - uint8_t atrac[ESP_A2D_CIE_LEN_ATRAC] ATRAC family codec capabilities - union esp_a2d_mcc_t::[anonymous] cie A2DP codec information element - esp_a2d_mct_t type Macros - ESP_A2D_MCT_SBC Media codec types supported by A2DP. SBC - ESP_A2D_MCT_M12 MPEG-1, 2 Audio - ESP_A2D_MCT_M24 MPEG-2, 4 AAC - ESP_A2D_MCT_ATRAC ATRAC family - ESP_A2D_MCT_NON_A2DP NON-A2DP - ESP_A2D_PSC_DELAY_RPT Protocol service capabilities. This value is a mask. Delay Report - ESP_A2D_CIE_LEN_SBC - ESP_A2D_CIE_LEN_M12 - ESP_A2D_CIE_LEN_M24 - ESP_A2D_CIE_LEN_ATRAC Type Definitions - typedef uint8_t esp_a2d_mct_t - typedef uint16_t esp_a2d_psc_t - typedef void (*esp_a2d_cb_t)(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param) A2DP profile callback function type. - Param event : Event type - Param param : Pointer to callback parameter - typedef void (*esp_a2d_sink_data_cb_t)(const uint8_t *buf, uint32_t len) A2DP sink data callback function. - Param buf [in] : pointer to the data received from A2DP source device and is PCM format decoded from SBC decoder; buf references to a static memory block and can be overwritten by upcoming data - Param len [in] : size(in bytes) in buf - typedef int32_t (*esp_a2d_source_data_cb_t)(uint8_t *buf, int32_t len) A2DP source data read callback function. - Param buf [in] : buffer to be filled with PCM data stream from higher layer - Param len [in] : size(in bytes) of data block to be copied to buf. -1 is an indication to user that data buffer shall be flushed - Return size of bytes read successfully, if the argument len is -1, this value is ignored. Enumerations - enum esp_a2d_connection_state_t Bluetooth A2DP connection states. Values: - enumerator ESP_A2D_CONNECTION_STATE_DISCONNECTED connection released - enumerator ESP_A2D_CONNECTION_STATE_CONNECTING connecting remote device - enumerator ESP_A2D_CONNECTION_STATE_CONNECTED connection established - enumerator ESP_A2D_CONNECTION_STATE_DISCONNECTING disconnecting remote device - enumerator ESP_A2D_CONNECTION_STATE_DISCONNECTED - enum esp_a2d_disc_rsn_t Bluetooth A2DP disconnection reason. Values: - enumerator ESP_A2D_DISC_RSN_NORMAL Finished disconnection that is initiated by local or remote device - enumerator ESP_A2D_DISC_RSN_ABNORMAL Abnormal disconnection caused by signal loss - enumerator ESP_A2D_DISC_RSN_NORMAL - enum esp_a2d_audio_state_t Bluetooth A2DP datapath states. Values: - enumerator ESP_A2D_AUDIO_STATE_SUSPEND audio stream datapath suspended by remote device - enumerator ESP_A2D_AUDIO_STATE_STARTED audio stream datapath started - enumerator ESP_A2D_AUDIO_STATE_STOPPED Note Deprecated - enumerator ESP_A2D_AUDIO_STATE_REMOTE_SUSPEND Note Deprecated - enumerator ESP_A2D_AUDIO_STATE_SUSPEND - enum esp_a2d_media_ctrl_ack_t A2DP media control command acknowledgement code. Values: - enumerator ESP_A2D_MEDIA_CTRL_ACK_SUCCESS media control command is acknowledged with success - enumerator ESP_A2D_MEDIA_CTRL_ACK_FAILURE media control command is acknowledged with failure - enumerator ESP_A2D_MEDIA_CTRL_ACK_BUSY media control command is rejected, as previous command is not yet acknowledged - enumerator ESP_A2D_MEDIA_CTRL_ACK_SUCCESS - enum esp_a2d_media_ctrl_t A2DP media control commands. Values: - enumerator ESP_A2D_MEDIA_CTRL_NONE Not for application use, use inside stack only. - enumerator ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY check whether AVDTP is connected, only used in A2DP source - enumerator ESP_A2D_MEDIA_CTRL_START command to set up media transmission channel - enumerator ESP_A2D_MEDIA_CTRL_SUSPEND command to suspend media transmission - enumerator ESP_A2D_MEDIA_CTRL_STOP Note Deprecated, Please use ESP_A2D_MEDIA_CTRL_SUSPEND - enumerator ESP_A2D_MEDIA_CTRL_NONE - enum esp_a2d_init_state_t Bluetooth A2DP Initiation states. Values: - enumerator ESP_A2D_DEINIT_SUCCESS A2DP profile deinit successful event - enumerator ESP_A2D_INIT_SUCCESS A2DP profile deinit successful event - enumerator ESP_A2D_DEINIT_SUCCESS - enum esp_a2d_set_delay_value_state_t Bluetooth A2DP set delay report value states. Values: - enumerator ESP_A2D_SET_SUCCESS A2DP profile set delay report value successful - enumerator ESP_A2D_SET_INVALID_PARAMS A2DP profile set delay report value is invalid parameter - enumerator ESP_A2D_SET_SUCCESS - enum esp_a2d_cb_event_t A2DP callback events. Values: - enumerator ESP_A2D_CONNECTION_STATE_EVT connection state changed event - enumerator ESP_A2D_AUDIO_STATE_EVT audio stream transmission state changed event - enumerator ESP_A2D_AUDIO_CFG_EVT audio codec is configured, only used for A2DP SINK - enumerator ESP_A2D_MEDIA_CTRL_ACK_EVT acknowledge event in response to media control commands - enumerator ESP_A2D_PROF_STATE_EVT indicate a2dp init&deinit complete - enumerator ESP_A2D_SNK_PSC_CFG_EVT protocol service capabilities configured,only used for A2DP SINK - enumerator ESP_A2D_SNK_SET_DELAY_VALUE_EVT indicate a2dp sink set delay report value complete, only used for A2DP SINK - enumerator ESP_A2D_SNK_GET_DELAY_VALUE_EVT indicate a2dp sink get delay report value complete, only used for A2DP SINK - enumerator ESP_A2D_REPORT_SNK_DELAY_VALUE_EVT report delay value, only used for A2DP SRC - enumerator ESP_A2D_CONNECTION_STATE_EVT
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_a2dp.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Bluetooth® AVRCP APIs
null
espressif.com
2016-01-01
758f7be2c2bb801
null
null
Bluetooth® AVRCP APIs Overview Bluetooth AVRCP reference APIs. API Reference Header File This header file can be included with: #include "esp_avrc_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_avrc_ct_register_callback(esp_avrc_ct_cb_t callback) Register application callbacks to AVRCP module. This function should be called after esp_bluedroid_enable() completes successfully. Parameters callback -- [in] AVRCP controller callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success Parameters callback -- [in] AVRCP controller callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_avrc_ct_init(void) Initialize the bluetooth AVRCP controller module, This function should be called after esp_bluedroid_enable() completes successfully. Note: AVRC cannot work independently, AVRC should be used along with A2DP and AVRC should be initialized before A2DP. Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_avrc_ct_deinit(void) De-initialize AVRCP controller module. This function should be called after after esp_bluedroid_enable() completes successfully. Note: AVRC cannot work independently, AVRC should be used along with A2DP and AVRC should be deinitialized before A2DP. Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_avrc_ct_send_set_player_value_cmd(uint8_t tl, uint8_t attr_id, uint8_t value_id) Send player application settings command to AVRCP target. This function should be called after ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established. Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values attr_id -- [in] : player application setting attribute IDs from one of esp_avrc_ps_attr_ids_t value_id -- [in] : attribute value defined for the specific player application setting attribute tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values attr_id -- [in] : player application setting attribute IDs from one of esp_avrc_ps_attr_ids_t value_id -- [in] : attribute value defined for the specific player application setting attribute tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values attr_id -- [in] : player application setting attribute IDs from one of esp_avrc_ps_attr_ids_t value_id -- [in] : attribute value defined for the specific player application setting attribute Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_avrc_ct_send_get_rn_capabilities_cmd(uint8_t tl) Send GetCapabilities PDU to AVRCP target to retrieve remote device's supported notification event_ids. This function should be called after ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established. Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_avrc_ct_send_register_notification_cmd(uint8_t tl, uint8_t event_id, uint32_t event_parameter) Send register notification command to AVRCP target. This function should be called after ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established. Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values. event_id -- [in] : id of events, e.g. ESP_AVRC_RN_PLAY_STATUS_CHANGE, ESP_AVRC_RN_TRACK_CHANGE, etc. event_parameter -- [in] : playback interval for ESP_AVRC_RN_PLAY_POS_CHANGED; For other events , value of this parameter is ignored. tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values. event_id -- [in] : id of events, e.g. ESP_AVRC_RN_PLAY_STATUS_CHANGE, ESP_AVRC_RN_TRACK_CHANGE, etc. event_parameter -- [in] : playback interval for ESP_AVRC_RN_PLAY_POS_CHANGED; For other events , value of this parameter is ignored. tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values. Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_NOT_SUPPORTED: if the event_id is not supported in current implementation ESP_FAIL: others ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_NOT_SUPPORTED: if the event_id is not supported in current implementation ESP_FAIL: others ESP_OK: success Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values. event_id -- [in] : id of events, e.g. ESP_AVRC_RN_PLAY_STATUS_CHANGE, ESP_AVRC_RN_TRACK_CHANGE, etc. event_parameter -- [in] : playback interval for ESP_AVRC_RN_PLAY_POS_CHANGED; For other events , value of this parameter is ignored. Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_NOT_SUPPORTED: if the event_id is not supported in current implementation ESP_FAIL: others esp_err_t esp_avrc_ct_send_set_absolute_volume_cmd(uint8_t tl, uint8_t volume) Send set absolute volume command to AVRCP target. This function should be called after ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established. Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values volume -- [in] : volume, 0 to 0x7f, means 0% to 100% tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values volume -- [in] : volume, 0 to 0x7f, means 0% to 100% tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_NOT_SUPPORTED: if the event_id is not supported in current implementation ESP_FAIL: others ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_NOT_SUPPORTED: if the event_id is not supported in current implementation ESP_FAIL: others ESP_OK: success Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values volume -- [in] : volume, 0 to 0x7f, means 0% to 100% Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_NOT_SUPPORTED: if the event_id is not supported in current implementation ESP_FAIL: others esp_err_t esp_avrc_ct_send_metadata_cmd(uint8_t tl, uint8_t attr_mask) Send metadata command to AVRCP target. This function should be called after ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established. Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values. attr_mask -- [in] : mask of attributes, e.g. ESP_AVRC_MD_ATTR_ID_TITLE | ESP_AVRC_MD_ATTR_ID_ARTIST. tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values. attr_mask -- [in] : mask of attributes, e.g. ESP_AVRC_MD_ATTR_ID_TITLE | ESP_AVRC_MD_ATTR_ID_ARTIST. tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values. Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values. attr_mask -- [in] : mask of attributes, e.g. ESP_AVRC_MD_ATTR_ID_TITLE | ESP_AVRC_MD_ATTR_ID_ARTIST. Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_avrc_ct_send_passthrough_cmd(uint8_t tl, uint8_t key_code, uint8_t key_state) Send passthrough command to AVRCP target. This function should be called after ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established. Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values. key_code -- [in] : passthrough command code, e.g. ESP_AVRC_PT_CMD_PLAY, ESP_AVRC_PT_CMD_STOP, etc. key_state -- [in] : passthrough command key state, ESP_AVRC_PT_CMD_STATE_PRESSED or ESP_AVRC_PT_CMD_STATE_RELEASED tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values. key_code -- [in] : passthrough command code, e.g. ESP_AVRC_PT_CMD_PLAY, ESP_AVRC_PT_CMD_STOP, etc. key_state -- [in] : passthrough command key state, ESP_AVRC_PT_CMD_STATE_PRESSED or ESP_AVRC_PT_CMD_STATE_RELEASED tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values. Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values. key_code -- [in] : passthrough command code, e.g. ESP_AVRC_PT_CMD_PLAY, ESP_AVRC_PT_CMD_STOP, etc. key_state -- [in] : passthrough command key state, ESP_AVRC_PT_CMD_STATE_PRESSED or ESP_AVRC_PT_CMD_STATE_RELEASED Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_avrc_tg_register_callback(esp_avrc_tg_cb_t callback) Register application callbacks to AVRCP target module. This function should be called after esp_bluedroid_enable() completes successfully. Parameters callback -- [in] AVRCP target callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success Parameters callback -- [in] AVRCP target callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_avrc_tg_init(void) Initialize the bluetooth AVRCP target module, This function should be called after esp_bluedroid_enable() completes successfully. Note: AVRC cannot work independently, AVRC should be used along with A2DP and AVRC should be initialized before A2DP. Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_avrc_tg_deinit(void) De-initialize AVRCP target module. This function should be called after after esp_bluedroid_enable() completes successfully. Note: AVRC cannot work independently, AVRC should be used along with A2DP and AVRC should be deinitialized before A2DP. Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_avrc_tg_get_psth_cmd_filter(esp_avrc_psth_filter_t filter, esp_avrc_psth_bit_mask_t *cmd_set) Get the current filter of remote passthrough commands on AVRC target. Filter is given by filter type and bit mask for the passthrough commands. This function should be called after esp_avrc_tg_init(). For filter type ESP_AVRC_PSTH_FILTER_ALLOWED_CMD, the retrieved command set is constant and it covers all of the passthrough commands that can possibly be supported. For filter type ESP_AVRC_PSTH_FILTER_SUPPORT_COMMANDS, the retrieved command set covers the passthrough commands selected to be supported according to current configuration. The configuration can be changed using esp_avrc_tg_set_psth_cmd_filter(). Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not initialized ESP_ERR_INVALID_ARG: if filter type is invalid or cmd_set is NULL ESP_FAIL: otherwise ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not initialized ESP_ERR_INVALID_ARG: if filter type is invalid or cmd_set is NULL ESP_FAIL: otherwise ESP_OK: success Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not initialized ESP_ERR_INVALID_ARG: if filter type is invalid or cmd_set is NULL ESP_FAIL: otherwise esp_err_t esp_avrc_tg_set_psth_cmd_filter(esp_avrc_psth_filter_t filter, const esp_avrc_psth_bit_mask_t *cmd_set) Set the filter of remote passthrough commands on AVRC target. Filter is given by filter type and bit mask for the passthrough commands. This function should be called after esp_avrc_tg_init(). If filter type is ESP_AVRC_PSTH_FILTER_SUPPORT_CMD, the passthrough commands which are set "1" as given in cmd_set will generate ESP_AVRC_CT_PASSTHROUGH_RSP_EVT callback event and are auto-accepted in the protocol stack, other commands are replied with response type "NOT IMPLEMENTED" (8). The set of supported commands should be a subset of allowed command set. The allowed command set can be retrieved using esp_avrc_tg_get_psth_cmd_filter() with filter type "ESP_AVRC_PSTH_FILTER_ALLOWED_CMD". Filter type "ESP_AVRC_PSTH_FILTER_ALLOWED_CMD" does not apply to this function. Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled ESP_ERR_INVALID_ARG: if filter type is invalid or cmd_set is NULL ESP_ERR_NOT_SUPPORTED:: if filter type is ESP_AVRC_PSTH_FILTER_ALLOWED_CMD, or cmd_set includes commands that are not allowed ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled ESP_ERR_INVALID_ARG: if filter type is invalid or cmd_set is NULL ESP_ERR_NOT_SUPPORTED:: if filter type is ESP_AVRC_PSTH_FILTER_ALLOWED_CMD, or cmd_set includes commands that are not allowed ESP_OK: success Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled ESP_ERR_INVALID_ARG: if filter type is invalid or cmd_set is NULL ESP_ERR_NOT_SUPPORTED:: if filter type is ESP_AVRC_PSTH_FILTER_ALLOWED_CMD, or cmd_set includes commands that are not allowed bool esp_avrc_psth_bit_mask_operation(esp_avrc_bit_mask_op_t op, esp_avrc_psth_bit_mask_t *psth, esp_avrc_pt_cmd_t cmd) Operate on the type esp_avrc_psth_bit_mask_t with regard to a specific PASSTHROUGH command. Parameters op -- [in] operation requested on the bit mask field psth -- [in] pointer to passthrough command bit mask structure cmd -- [in] passthrough command code op -- [in] operation requested on the bit mask field psth -- [in] pointer to passthrough command bit mask structure cmd -- [in] passthrough command code op -- [in] operation requested on the bit mask field Returns For operation ESP_AVRC_BIT_MASK_OP_SET or ESP_AVRC_BIT_MASK_OP_CLEAR, return true for a successful operation, otherwise return false. For operation ESP_AVRC_BIT_MASK_OP_TEST, return true if the corresponding bit is set, otherwise false. Parameters op -- [in] operation requested on the bit mask field psth -- [in] pointer to passthrough command bit mask structure cmd -- [in] passthrough command code Returns For operation ESP_AVRC_BIT_MASK_OP_SET or ESP_AVRC_BIT_MASK_OP_CLEAR, return true for a successful operation, otherwise return false. For operation ESP_AVRC_BIT_MASK_OP_TEST, return true if the corresponding bit is set, otherwise false. esp_err_t esp_avrc_tg_get_rn_evt_cap(esp_avrc_rn_evt_cap_t cap, esp_avrc_rn_evt_cap_mask_t *evt_set) Get the requested event notification capabilies on local AVRC target. The capability is returned in a bit mask representation in evt_set. This function should be called after esp_avrc_tg_init(). For capability type "ESP_AVRC_RN_CAP_ALLOWED_EVT, the retrieved event set is constant and it covers all of the notifcation events that can possibly be supported with current implementation. For capability type ESP_AVRC_RN_CAP_SUPPORTED_EVT, the event set covers the notification events selected to be supported under current configuration, The configuration can be changed using esp_avrc_tg_set_rn_evt_cap(). Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not initialized ESP_ERR_INVALID_ARG: if cap is invalid or evt_set is NULL ESP_FAIL: otherwise ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not initialized ESP_ERR_INVALID_ARG: if cap is invalid or evt_set is NULL ESP_FAIL: otherwise ESP_OK: success Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not initialized ESP_ERR_INVALID_ARG: if cap is invalid or evt_set is NULL ESP_FAIL: otherwise esp_err_t esp_avrc_tg_set_rn_evt_cap(const esp_avrc_rn_evt_cap_mask_t *evt_set) Set the event notification capabilities on local AVRCP target. The capability is given in a bit mask representation in evt_set and must be a subset of allowed event IDs with current implementation. This function should be called after esp_avrc_tg_init(). Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled ESP_ERR_INVALID_ARG: if evt_set is NULL ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled ESP_ERR_INVALID_ARG: if evt_set is NULL ESP_OK: success Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled ESP_ERR_INVALID_ARG: if evt_set is NULL bool esp_avrc_rn_evt_bit_mask_operation(esp_avrc_bit_mask_op_t op, esp_avrc_rn_evt_cap_mask_t *events, esp_avrc_rn_event_ids_t event_id) Operate on the type esp_avrc_rn_evt_cap_mask_t with regard to a specific event. For operation ESP_AVRC_BIT_MASK_OP_TEST, return true if the corresponding bit is set, otherwise false. Parameters op -- [in] operation requested on the bit mask field events -- [in] pointer to event notification capability bit mask structure event_id -- [in] notification event code op -- [in] operation requested on the bit mask field events -- [in] pointer to event notification capability bit mask structure event_id -- [in] notification event code op -- [in] operation requested on the bit mask field Returns For operation ESP_AVRC_BIT_MASK_OP_SET or ESP_AVRC_BIT_MASK_OP_CLEAR, return true for a successful operation, otherwise return false. Parameters op -- [in] operation requested on the bit mask field events -- [in] pointer to event notification capability bit mask structure event_id -- [in] notification event code Returns For operation ESP_AVRC_BIT_MASK_OP_SET or ESP_AVRC_BIT_MASK_OP_CLEAR, return true for a successful operation, otherwise return false. esp_err_t esp_avrc_tg_send_rn_rsp(esp_avrc_rn_event_ids_t event_id, esp_avrc_rn_rsp_t rsp, esp_avrc_rn_param_t *param) Send RegisterNotification Response to remote AVRCP controller. Local event notification capability can be set using esp_avrc_tg_set_rn_evt_cap(), in a bit mask representation in evt_set. This function should be called after esp_avrc_tg_init(). Parameters event_id -- [in] notification event ID that remote AVRCP CT registers rsp -- [in] notification response code param -- [in] parameters included in the specific notification event_id -- [in] notification event ID that remote AVRCP CT registers rsp -- [in] notification response code param -- [in] parameters included in the specific notification event_id -- [in] notification event ID that remote AVRCP CT registers Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not initialized ESP_ERR_INVALID_ARG: if evt_set is NULL ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not initialized ESP_ERR_INVALID_ARG: if evt_set is NULL ESP_OK: success Parameters event_id -- [in] notification event ID that remote AVRCP CT registers rsp -- [in] notification response code param -- [in] parameters included in the specific notification Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not initialized ESP_ERR_INVALID_ARG: if evt_set is NULL Unions union esp_avrc_rn_param_t #include <esp_avrc_api.h> AVRCP notification parameters. Public Members uint8_t volume response data for ESP_AVRC_RN_VOLUME_CHANGE, ranges 0..127 uint8_t volume response data for ESP_AVRC_RN_VOLUME_CHANGE, ranges 0..127 esp_avrc_playback_stat_t playback response data for ESP_AVRC_RN_PLAY_STATUS_CHANGE esp_avrc_playback_stat_t playback response data for ESP_AVRC_RN_PLAY_STATUS_CHANGE uint8_t elm_id[8] response data for ESP_AVRC_RN_TRACK_CHANGE uint8_t elm_id[8] response data for ESP_AVRC_RN_TRACK_CHANGE uint32_t play_pos response data for ESP_AVRC_RN_PLAY_POS_CHANGED, in millisecond uint32_t play_pos response data for ESP_AVRC_RN_PLAY_POS_CHANGED, in millisecond esp_avrc_batt_stat_t batt response data for ESP_AVRC_RN_BATTERY_STATUS_CHANGE esp_avrc_batt_stat_t batt response data for ESP_AVRC_RN_BATTERY_STATUS_CHANGE uint8_t volume union esp_avrc_ct_cb_param_t #include <esp_avrc_api.h> AVRC controller callback parameters. Public Members struct esp_avrc_ct_cb_param_t::avrc_ct_conn_stat_param conn_stat AVRC connection status struct esp_avrc_ct_cb_param_t::avrc_ct_conn_stat_param conn_stat AVRC connection status struct esp_avrc_ct_cb_param_t::avrc_ct_psth_rsp_param psth_rsp passthrough command response struct esp_avrc_ct_cb_param_t::avrc_ct_psth_rsp_param psth_rsp passthrough command response struct esp_avrc_ct_cb_param_t::avrc_ct_meta_rsp_param meta_rsp metadata attributes response struct esp_avrc_ct_cb_param_t::avrc_ct_meta_rsp_param meta_rsp metadata attributes response struct esp_avrc_ct_cb_param_t::avrc_ct_change_notify_param change_ntf notifications struct esp_avrc_ct_cb_param_t::avrc_ct_change_notify_param change_ntf notifications struct esp_avrc_ct_cb_param_t::avrc_ct_rmt_feats_param rmt_feats AVRC features discovered from remote SDP server struct esp_avrc_ct_cb_param_t::avrc_ct_rmt_feats_param rmt_feats AVRC features discovered from remote SDP server struct esp_avrc_ct_cb_param_t::avrc_ct_get_rn_caps_rsp_param get_rn_caps_rsp get supported event capabilities response from AVRCP target struct esp_avrc_ct_cb_param_t::avrc_ct_get_rn_caps_rsp_param get_rn_caps_rsp get supported event capabilities response from AVRCP target struct esp_avrc_ct_cb_param_t::avrc_ct_set_volume_rsp_param set_volume_rsp set absolute volume response event struct esp_avrc_ct_cb_param_t::avrc_ct_set_volume_rsp_param set_volume_rsp set absolute volume response event struct avrc_ct_change_notify_param #include <esp_avrc_api.h> ESP_AVRC_CT_CHANGE_NOTIFY_EVT. Public Members uint8_t event_id id of AVRC event notification uint8_t event_id id of AVRC event notification esp_avrc_rn_param_t event_parameter event notification parameter esp_avrc_rn_param_t event_parameter event notification parameter uint8_t event_id struct avrc_ct_change_notify_param #include <esp_avrc_api.h> ESP_AVRC_CT_CHANGE_NOTIFY_EVT. Public Members uint8_t event_id id of AVRC event notification esp_avrc_rn_param_t event_parameter event notification parameter struct avrc_ct_conn_stat_param #include <esp_avrc_api.h> ESP_AVRC_CT_CONNECTION_STATE_EVT. Public Members bool connected whether AVRC connection is set up bool connected whether AVRC connection is set up esp_bd_addr_t remote_bda remote bluetooth device address esp_bd_addr_t remote_bda remote bluetooth device address bool connected struct avrc_ct_conn_stat_param #include <esp_avrc_api.h> ESP_AVRC_CT_CONNECTION_STATE_EVT. Public Members bool connected whether AVRC connection is set up esp_bd_addr_t remote_bda remote bluetooth device address struct avrc_ct_get_rn_caps_rsp_param #include <esp_avrc_api.h> ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT. Public Members uint8_t cap_count number of items provided in event or company_id according to cap_id used uint8_t cap_count number of items provided in event or company_id according to cap_id used esp_avrc_rn_evt_cap_mask_t evt_set supported event_ids represented in bit-mask esp_avrc_rn_evt_cap_mask_t evt_set supported event_ids represented in bit-mask uint8_t cap_count struct avrc_ct_get_rn_caps_rsp_param #include <esp_avrc_api.h> ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT. Public Members uint8_t cap_count number of items provided in event or company_id according to cap_id used esp_avrc_rn_evt_cap_mask_t evt_set supported event_ids represented in bit-mask struct avrc_ct_meta_rsp_param #include <esp_avrc_api.h> ESP_AVRC_CT_METADATA_RSP_EVT. struct avrc_ct_meta_rsp_param #include <esp_avrc_api.h> ESP_AVRC_CT_METADATA_RSP_EVT. struct avrc_ct_psth_rsp_param #include <esp_avrc_api.h> ESP_AVRC_CT_PASSTHROUGH_RSP_EVT. Public Members uint8_t tl transaction label, 0 to 15 uint8_t tl transaction label, 0 to 15 uint8_t key_code passthrough command code uint8_t key_code passthrough command code uint8_t key_state 0 for PRESSED, 1 for RELEASED uint8_t key_state 0 for PRESSED, 1 for RELEASED esp_avrc_rsp_t rsp_code response code esp_avrc_rsp_t rsp_code response code uint8_t tl struct avrc_ct_psth_rsp_param #include <esp_avrc_api.h> ESP_AVRC_CT_PASSTHROUGH_RSP_EVT. Public Members uint8_t tl transaction label, 0 to 15 uint8_t key_code passthrough command code uint8_t key_state 0 for PRESSED, 1 for RELEASED esp_avrc_rsp_t rsp_code response code struct avrc_ct_rmt_feats_param #include <esp_avrc_api.h> ESP_AVRC_CT_REMOTE_FEATURES_EVT. Public Members uint32_t feat_mask AVRC feature mask of remote device uint32_t feat_mask AVRC feature mask of remote device uint16_t tg_feat_flag feature flag of remote device as TG uint16_t tg_feat_flag feature flag of remote device as TG esp_bd_addr_t remote_bda remote bluetooth device address esp_bd_addr_t remote_bda remote bluetooth device address uint32_t feat_mask struct avrc_ct_rmt_feats_param #include <esp_avrc_api.h> ESP_AVRC_CT_REMOTE_FEATURES_EVT. Public Members uint32_t feat_mask AVRC feature mask of remote device uint16_t tg_feat_flag feature flag of remote device as TG esp_bd_addr_t remote_bda remote bluetooth device address struct esp_avrc_ct_cb_param_t::avrc_ct_conn_stat_param conn_stat union esp_avrc_tg_cb_param_t #include <esp_avrc_api.h> AVRC target callback parameters. Public Members struct esp_avrc_tg_cb_param_t::avrc_tg_conn_stat_param conn_stat AVRC connection status struct esp_avrc_tg_cb_param_t::avrc_tg_conn_stat_param conn_stat AVRC connection status struct esp_avrc_tg_cb_param_t::avrc_tg_rmt_feats_param rmt_feats AVRC features discovered through SDP struct esp_avrc_tg_cb_param_t::avrc_tg_rmt_feats_param rmt_feats AVRC features discovered through SDP struct esp_avrc_tg_cb_param_t::avrc_tg_psth_cmd_param psth_cmd passthrough command struct esp_avrc_tg_cb_param_t::avrc_tg_psth_cmd_param psth_cmd passthrough command struct esp_avrc_tg_cb_param_t::avrc_tg_set_abs_vol_param set_abs_vol set absolute volume command targeted on audio sink struct esp_avrc_tg_cb_param_t::avrc_tg_set_abs_vol_param set_abs_vol set absolute volume command targeted on audio sink struct esp_avrc_tg_cb_param_t::avrc_tg_reg_ntf_param reg_ntf register notification struct esp_avrc_tg_cb_param_t::avrc_tg_reg_ntf_param reg_ntf register notification struct esp_avrc_tg_cb_param_t::avrc_tg_set_app_value_param set_app_value set player application value struct esp_avrc_tg_cb_param_t::avrc_tg_set_app_value_param set_app_value set player application value struct avrc_tg_conn_stat_param #include <esp_avrc_api.h> ESP_AVRC_TG_CONNECTION_STATE_EVT. Public Members bool connected whether AVRC connection is set up bool connected whether AVRC connection is set up esp_bd_addr_t remote_bda remote bluetooth device address esp_bd_addr_t remote_bda remote bluetooth device address bool connected struct avrc_tg_conn_stat_param #include <esp_avrc_api.h> ESP_AVRC_TG_CONNECTION_STATE_EVT. Public Members bool connected whether AVRC connection is set up esp_bd_addr_t remote_bda remote bluetooth device address struct avrc_tg_psth_cmd_param #include <esp_avrc_api.h> ESP_AVRC_TG_PASSTHROUGH_CMD_EVT. struct avrc_tg_psth_cmd_param #include <esp_avrc_api.h> ESP_AVRC_TG_PASSTHROUGH_CMD_EVT. struct avrc_tg_reg_ntf_param #include <esp_avrc_api.h> ESP_AVRC_TG_REGISTER_NOTIFICATION_EVT. struct avrc_tg_reg_ntf_param #include <esp_avrc_api.h> ESP_AVRC_TG_REGISTER_NOTIFICATION_EVT. struct avrc_tg_rmt_feats_param #include <esp_avrc_api.h> ESP_AVRC_TG_REMOTE_FEATURES_EVT. Public Members uint32_t feat_mask AVRC feature mask of remote device uint32_t feat_mask AVRC feature mask of remote device uint16_t ct_feat_flag feature flag of remote device as CT uint16_t ct_feat_flag feature flag of remote device as CT esp_bd_addr_t remote_bda remote bluetooth device address esp_bd_addr_t remote_bda remote bluetooth device address uint32_t feat_mask struct avrc_tg_rmt_feats_param #include <esp_avrc_api.h> ESP_AVRC_TG_REMOTE_FEATURES_EVT. Public Members uint32_t feat_mask AVRC feature mask of remote device uint16_t ct_feat_flag feature flag of remote device as CT esp_bd_addr_t remote_bda remote bluetooth device address struct avrc_tg_set_abs_vol_param #include <esp_avrc_api.h> ESP_AVRC_TG_SET_ABSOLUTE_VOLUME_CMD_EVT. Public Members uint8_t volume volume ranges from 0 to 127 uint8_t volume volume ranges from 0 to 127 uint8_t volume struct avrc_tg_set_abs_vol_param #include <esp_avrc_api.h> ESP_AVRC_TG_SET_ABSOLUTE_VOLUME_CMD_EVT. Public Members uint8_t volume volume ranges from 0 to 127 struct avrc_tg_set_app_value_param #include <esp_avrc_api.h> ESP_AVRC_TG_SET_PLAYER_APP_VALUE_EVT. Public Members uint8_t num_val attribute num uint8_t num_val attribute num esp_avrc_set_app_value_param_t *p_vals point to the id and value of player application attribute esp_avrc_set_app_value_param_t *p_vals point to the id and value of player application attribute uint8_t num_val struct avrc_tg_set_app_value_param #include <esp_avrc_api.h> ESP_AVRC_TG_SET_PLAYER_APP_VALUE_EVT. Public Members uint8_t num_val attribute num esp_avrc_set_app_value_param_t *p_vals point to the id and value of player application attribute struct esp_avrc_tg_cb_param_t::avrc_tg_conn_stat_param conn_stat Structures struct esp_avrc_psth_bit_mask_t AVRC passthrough command bit mask. Public Members uint16_t bits[8] bit mask representation of PASSTHROUGH commands uint16_t bits[8] bit mask representation of PASSTHROUGH commands uint16_t bits[8] struct esp_avrc_rn_evt_cap_mask_t AVRC target notification event capability bit mask. Public Members uint16_t bits bit mask representation of PASSTHROUGH commands uint16_t bits bit mask representation of PASSTHROUGH commands uint16_t bits struct esp_avrc_set_app_value_param_t AVRCP set app value parameters. Macros ESP_AVRC_TRANS_LABEL_MAX max transaction label Type Definitions typedef void (*esp_avrc_ct_cb_t)(esp_avrc_ct_cb_event_t event, esp_avrc_ct_cb_param_t *param) AVRCP controller callback function type. Param event : Event type Param param : Pointer to callback parameter union Param event : Event type Param param : Pointer to callback parameter union typedef void (*esp_avrc_tg_cb_t)(esp_avrc_tg_cb_event_t event, esp_avrc_tg_cb_param_t *param) AVRCP target callback function type. Param event : Event type Param param : Pointer to callback parameter union Param event : Event type Param param : Pointer to callback parameter union Enumerations enum esp_avrc_features_t AVRC feature bit mask. Values: enumerator ESP_AVRC_FEAT_RCTG remote control target enumerator ESP_AVRC_FEAT_RCTG remote control target enumerator ESP_AVRC_FEAT_RCCT remote control controller enumerator ESP_AVRC_FEAT_RCCT remote control controller enumerator ESP_AVRC_FEAT_VENDOR remote control vendor dependent commands enumerator ESP_AVRC_FEAT_VENDOR remote control vendor dependent commands enumerator ESP_AVRC_FEAT_BROWSE use browsing channel enumerator ESP_AVRC_FEAT_BROWSE use browsing channel enumerator ESP_AVRC_FEAT_META_DATA remote control metadata transfer command/response enumerator ESP_AVRC_FEAT_META_DATA remote control metadata transfer command/response enumerator ESP_AVRC_FEAT_ADV_CTRL remote control advanced control command/response enumerator ESP_AVRC_FEAT_ADV_CTRL remote control advanced control command/response enumerator ESP_AVRC_FEAT_RCTG enum esp_avrc_feature_flag_t AVRC supported features flag retrieved in SDP record. Values: enumerator ESP_AVRC_FEAT_FLAG_CAT1 category 1 enumerator ESP_AVRC_FEAT_FLAG_CAT1 category 1 enumerator ESP_AVRC_FEAT_FLAG_CAT2 category 2 enumerator ESP_AVRC_FEAT_FLAG_CAT2 category 2 enumerator ESP_AVRC_FEAT_FLAG_CAT3 category 3 enumerator ESP_AVRC_FEAT_FLAG_CAT3 category 3 enumerator ESP_AVRC_FEAT_FLAG_CAT4 category 4 enumerator ESP_AVRC_FEAT_FLAG_CAT4 category 4 enumerator ESP_AVRC_FEAT_FLAG_BROWSING browsing enumerator ESP_AVRC_FEAT_FLAG_BROWSING browsing enumerator ESP_AVRC_FEAT_FLAG_COVER_ART_GET_IMAGE_PROP Cover Art GetImageProperties enumerator ESP_AVRC_FEAT_FLAG_COVER_ART_GET_IMAGE_PROP Cover Art GetImageProperties enumerator ESP_AVRC_FEAT_FLAG_COVER_ART_GET_IMAGE Cover Art GetImage enumerator ESP_AVRC_FEAT_FLAG_COVER_ART_GET_IMAGE Cover Art GetImage enumerator ESP_AVRC_FEAT_FLAG_COVER_ART_GET_LINKED_THUMBNAIL Cover Art GetLinkedThumbnail enumerator ESP_AVRC_FEAT_FLAG_COVER_ART_GET_LINKED_THUMBNAIL Cover Art GetLinkedThumbnail enumerator ESP_AVRC_FEAT_FLAG_CAT1 enum esp_avrc_pt_cmd_t AVRC passthrough command code. Values: enumerator ESP_AVRC_PT_CMD_SELECT select enumerator ESP_AVRC_PT_CMD_SELECT select enumerator ESP_AVRC_PT_CMD_UP up enumerator ESP_AVRC_PT_CMD_UP up enumerator ESP_AVRC_PT_CMD_DOWN down enumerator ESP_AVRC_PT_CMD_DOWN down enumerator ESP_AVRC_PT_CMD_LEFT left enumerator ESP_AVRC_PT_CMD_LEFT left enumerator ESP_AVRC_PT_CMD_RIGHT right enumerator ESP_AVRC_PT_CMD_RIGHT right enumerator ESP_AVRC_PT_CMD_RIGHT_UP right-up enumerator ESP_AVRC_PT_CMD_RIGHT_UP right-up enumerator ESP_AVRC_PT_CMD_RIGHT_DOWN right-down enumerator ESP_AVRC_PT_CMD_RIGHT_DOWN right-down enumerator ESP_AVRC_PT_CMD_LEFT_UP left-up enumerator ESP_AVRC_PT_CMD_LEFT_UP left-up enumerator ESP_AVRC_PT_CMD_LEFT_DOWN left-down enumerator ESP_AVRC_PT_CMD_LEFT_DOWN left-down enumerator ESP_AVRC_PT_CMD_ROOT_MENU root menu enumerator ESP_AVRC_PT_CMD_ROOT_MENU root menu enumerator ESP_AVRC_PT_CMD_SETUP_MENU setup menu enumerator ESP_AVRC_PT_CMD_SETUP_MENU setup menu enumerator ESP_AVRC_PT_CMD_CONT_MENU contents menu enumerator ESP_AVRC_PT_CMD_CONT_MENU contents menu enumerator ESP_AVRC_PT_CMD_FAV_MENU favorite menu enumerator ESP_AVRC_PT_CMD_FAV_MENU favorite menu enumerator ESP_AVRC_PT_CMD_EXIT exit enumerator ESP_AVRC_PT_CMD_EXIT exit enumerator ESP_AVRC_PT_CMD_0 0 enumerator ESP_AVRC_PT_CMD_0 0 enumerator ESP_AVRC_PT_CMD_1 1 enumerator ESP_AVRC_PT_CMD_1 1 enumerator ESP_AVRC_PT_CMD_2 2 enumerator ESP_AVRC_PT_CMD_2 2 enumerator ESP_AVRC_PT_CMD_3 3 enumerator ESP_AVRC_PT_CMD_3 3 enumerator ESP_AVRC_PT_CMD_4 4 enumerator ESP_AVRC_PT_CMD_4 4 enumerator ESP_AVRC_PT_CMD_5 5 enumerator ESP_AVRC_PT_CMD_5 5 enumerator ESP_AVRC_PT_CMD_6 6 enumerator ESP_AVRC_PT_CMD_6 6 enumerator ESP_AVRC_PT_CMD_7 7 enumerator ESP_AVRC_PT_CMD_7 7 enumerator ESP_AVRC_PT_CMD_8 8 enumerator ESP_AVRC_PT_CMD_8 8 enumerator ESP_AVRC_PT_CMD_9 9 enumerator ESP_AVRC_PT_CMD_9 9 enumerator ESP_AVRC_PT_CMD_DOT dot enumerator ESP_AVRC_PT_CMD_DOT dot enumerator ESP_AVRC_PT_CMD_ENTER enter enumerator ESP_AVRC_PT_CMD_ENTER enter enumerator ESP_AVRC_PT_CMD_CLEAR clear enumerator ESP_AVRC_PT_CMD_CLEAR clear enumerator ESP_AVRC_PT_CMD_CHAN_UP channel up enumerator ESP_AVRC_PT_CMD_CHAN_UP channel up enumerator ESP_AVRC_PT_CMD_CHAN_DOWN channel down enumerator ESP_AVRC_PT_CMD_CHAN_DOWN channel down enumerator ESP_AVRC_PT_CMD_PREV_CHAN previous channel enumerator ESP_AVRC_PT_CMD_PREV_CHAN previous channel enumerator ESP_AVRC_PT_CMD_SOUND_SEL sound select enumerator ESP_AVRC_PT_CMD_SOUND_SEL sound select enumerator ESP_AVRC_PT_CMD_INPUT_SEL input select enumerator ESP_AVRC_PT_CMD_INPUT_SEL input select enumerator ESP_AVRC_PT_CMD_DISP_INFO display information enumerator ESP_AVRC_PT_CMD_DISP_INFO display information enumerator ESP_AVRC_PT_CMD_HELP help enumerator ESP_AVRC_PT_CMD_HELP help enumerator ESP_AVRC_PT_CMD_PAGE_UP page up enumerator ESP_AVRC_PT_CMD_PAGE_UP page up enumerator ESP_AVRC_PT_CMD_PAGE_DOWN page down enumerator ESP_AVRC_PT_CMD_PAGE_DOWN page down enumerator ESP_AVRC_PT_CMD_POWER power enumerator ESP_AVRC_PT_CMD_POWER power enumerator ESP_AVRC_PT_CMD_VOL_UP volume up enumerator ESP_AVRC_PT_CMD_VOL_UP volume up enumerator ESP_AVRC_PT_CMD_VOL_DOWN volume down enumerator ESP_AVRC_PT_CMD_VOL_DOWN volume down enumerator ESP_AVRC_PT_CMD_MUTE mute enumerator ESP_AVRC_PT_CMD_MUTE mute enumerator ESP_AVRC_PT_CMD_PLAY play enumerator ESP_AVRC_PT_CMD_PLAY play enumerator ESP_AVRC_PT_CMD_STOP stop enumerator ESP_AVRC_PT_CMD_STOP stop enumerator ESP_AVRC_PT_CMD_PAUSE pause enumerator ESP_AVRC_PT_CMD_PAUSE pause enumerator ESP_AVRC_PT_CMD_RECORD record enumerator ESP_AVRC_PT_CMD_RECORD record enumerator ESP_AVRC_PT_CMD_REWIND rewind enumerator ESP_AVRC_PT_CMD_REWIND rewind enumerator ESP_AVRC_PT_CMD_FAST_FORWARD fast forward enumerator ESP_AVRC_PT_CMD_FAST_FORWARD fast forward enumerator ESP_AVRC_PT_CMD_EJECT eject enumerator ESP_AVRC_PT_CMD_EJECT eject enumerator ESP_AVRC_PT_CMD_FORWARD forward enumerator ESP_AVRC_PT_CMD_FORWARD forward enumerator ESP_AVRC_PT_CMD_BACKWARD backward enumerator ESP_AVRC_PT_CMD_BACKWARD backward enumerator ESP_AVRC_PT_CMD_ANGLE angle enumerator ESP_AVRC_PT_CMD_ANGLE angle enumerator ESP_AVRC_PT_CMD_SUBPICT subpicture enumerator ESP_AVRC_PT_CMD_SUBPICT subpicture enumerator ESP_AVRC_PT_CMD_F1 F1 enumerator ESP_AVRC_PT_CMD_F1 F1 enumerator ESP_AVRC_PT_CMD_F2 F2 enumerator ESP_AVRC_PT_CMD_F2 F2 enumerator ESP_AVRC_PT_CMD_F3 F3 enumerator ESP_AVRC_PT_CMD_F3 F3 enumerator ESP_AVRC_PT_CMD_F4 F4 enumerator ESP_AVRC_PT_CMD_F4 F4 enumerator ESP_AVRC_PT_CMD_F5 F5 enumerator ESP_AVRC_PT_CMD_F5 F5 enumerator ESP_AVRC_PT_CMD_VENDOR vendor unique enumerator ESP_AVRC_PT_CMD_VENDOR vendor unique enumerator ESP_AVRC_PT_CMD_SELECT enum esp_avrc_psth_filter_t AVRC passthrough command filter. Values: enumerator ESP_AVRC_PSTH_FILTER_ALLOWED_CMD all of the PASSTHROUGH commands that can possibly be used, immutable enumerator ESP_AVRC_PSTH_FILTER_ALLOWED_CMD all of the PASSTHROUGH commands that can possibly be used, immutable enumerator ESP_AVRC_PSTH_FILTER_SUPPORTED_CMD PASSTHROUGH commands selectively supported according to the current configuration enumerator ESP_AVRC_PSTH_FILTER_SUPPORTED_CMD PASSTHROUGH commands selectively supported according to the current configuration enumerator ESP_AVRC_PSTH_FILTER_SUPPORT_MAX enumerator ESP_AVRC_PSTH_FILTER_SUPPORT_MAX enumerator ESP_AVRC_PSTH_FILTER_ALLOWED_CMD enum esp_avrc_bit_mask_op_t Values: enumerator ESP_AVRC_BIT_MASK_OP_TEST operation code to test a specific bit enumerator ESP_AVRC_BIT_MASK_OP_TEST operation code to test a specific bit enumerator ESP_AVRC_BIT_MASK_OP_SET operation code to set a specific bit enumerator ESP_AVRC_BIT_MASK_OP_SET operation code to set a specific bit enumerator ESP_AVRC_BIT_MASK_OP_CLEAR operation code to clear a specific bit enumerator ESP_AVRC_BIT_MASK_OP_CLEAR operation code to clear a specific bit enumerator ESP_AVRC_BIT_MASK_OP_TEST enum esp_avrc_pt_cmd_state_t AVRC passthrough command state. Values: enumerator ESP_AVRC_PT_CMD_STATE_PRESSED key pressed enumerator ESP_AVRC_PT_CMD_STATE_PRESSED key pressed enumerator ESP_AVRC_PT_CMD_STATE_RELEASED key released enumerator ESP_AVRC_PT_CMD_STATE_RELEASED key released enumerator ESP_AVRC_PT_CMD_STATE_PRESSED enum esp_avrc_ct_cb_event_t AVRC Controller callback events. Values: enumerator ESP_AVRC_CT_CONNECTION_STATE_EVT connection state changed event enumerator ESP_AVRC_CT_CONNECTION_STATE_EVT connection state changed event enumerator ESP_AVRC_CT_PASSTHROUGH_RSP_EVT passthrough response event enumerator ESP_AVRC_CT_PASSTHROUGH_RSP_EVT passthrough response event enumerator ESP_AVRC_CT_METADATA_RSP_EVT metadata response event enumerator ESP_AVRC_CT_METADATA_RSP_EVT metadata response event enumerator ESP_AVRC_CT_PLAY_STATUS_RSP_EVT play status response event enumerator ESP_AVRC_CT_PLAY_STATUS_RSP_EVT play status response event enumerator ESP_AVRC_CT_CHANGE_NOTIFY_EVT notification event enumerator ESP_AVRC_CT_CHANGE_NOTIFY_EVT notification event enumerator ESP_AVRC_CT_REMOTE_FEATURES_EVT feature of remote device indication event enumerator ESP_AVRC_CT_REMOTE_FEATURES_EVT feature of remote device indication event enumerator ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT supported notification events capability of peer device enumerator ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT supported notification events capability of peer device enumerator ESP_AVRC_CT_SET_ABSOLUTE_VOLUME_RSP_EVT set absolute volume response event enumerator ESP_AVRC_CT_SET_ABSOLUTE_VOLUME_RSP_EVT set absolute volume response event enumerator ESP_AVRC_CT_CONNECTION_STATE_EVT enum esp_avrc_tg_cb_event_t AVRC Target callback events. Values: enumerator ESP_AVRC_TG_CONNECTION_STATE_EVT connection state changed event enumerator ESP_AVRC_TG_CONNECTION_STATE_EVT connection state changed event enumerator ESP_AVRC_TG_REMOTE_FEATURES_EVT feature of remote device indication event enumerator ESP_AVRC_TG_REMOTE_FEATURES_EVT feature of remote device indication event enumerator ESP_AVRC_TG_PASSTHROUGH_CMD_EVT passthrough command event enumerator ESP_AVRC_TG_PASSTHROUGH_CMD_EVT passthrough command event enumerator ESP_AVRC_TG_SET_ABSOLUTE_VOLUME_CMD_EVT set absolute volume command from remote device enumerator ESP_AVRC_TG_SET_ABSOLUTE_VOLUME_CMD_EVT set absolute volume command from remote device enumerator ESP_AVRC_TG_REGISTER_NOTIFICATION_EVT register notification event enumerator ESP_AVRC_TG_REGISTER_NOTIFICATION_EVT register notification event enumerator ESP_AVRC_TG_SET_PLAYER_APP_VALUE_EVT set application attribute value, attribute refer to esp_avrc_ps_attr_ids_t enumerator ESP_AVRC_TG_SET_PLAYER_APP_VALUE_EVT set application attribute value, attribute refer to esp_avrc_ps_attr_ids_t enumerator ESP_AVRC_TG_CONNECTION_STATE_EVT enum esp_avrc_md_attr_mask_t AVRC metadata attribute mask. Values: enumerator ESP_AVRC_MD_ATTR_TITLE title of the playing track enumerator ESP_AVRC_MD_ATTR_TITLE title of the playing track enumerator ESP_AVRC_MD_ATTR_ARTIST track artist enumerator ESP_AVRC_MD_ATTR_ARTIST track artist enumerator ESP_AVRC_MD_ATTR_ALBUM album name enumerator ESP_AVRC_MD_ATTR_ALBUM album name enumerator ESP_AVRC_MD_ATTR_TRACK_NUM track position on the album enumerator ESP_AVRC_MD_ATTR_TRACK_NUM track position on the album enumerator ESP_AVRC_MD_ATTR_NUM_TRACKS number of tracks on the album enumerator ESP_AVRC_MD_ATTR_NUM_TRACKS number of tracks on the album enumerator ESP_AVRC_MD_ATTR_GENRE track genre enumerator ESP_AVRC_MD_ATTR_GENRE track genre enumerator ESP_AVRC_MD_ATTR_PLAYING_TIME total album playing time in miliseconds enumerator ESP_AVRC_MD_ATTR_PLAYING_TIME total album playing time in miliseconds enumerator ESP_AVRC_MD_ATTR_TITLE enum esp_avrc_rn_event_ids_t AVRC event notification ids. Values: enumerator ESP_AVRC_RN_PLAY_STATUS_CHANGE track status change, eg. from playing to paused enumerator ESP_AVRC_RN_PLAY_STATUS_CHANGE track status change, eg. from playing to paused enumerator ESP_AVRC_RN_TRACK_CHANGE new track is loaded enumerator ESP_AVRC_RN_TRACK_CHANGE new track is loaded enumerator ESP_AVRC_RN_TRACK_REACHED_END current track reached end enumerator ESP_AVRC_RN_TRACK_REACHED_END current track reached end enumerator ESP_AVRC_RN_TRACK_REACHED_START current track reached start position enumerator ESP_AVRC_RN_TRACK_REACHED_START current track reached start position enumerator ESP_AVRC_RN_PLAY_POS_CHANGED track playing position changed enumerator ESP_AVRC_RN_PLAY_POS_CHANGED track playing position changed enumerator ESP_AVRC_RN_BATTERY_STATUS_CHANGE battery status changed enumerator ESP_AVRC_RN_BATTERY_STATUS_CHANGE battery status changed enumerator ESP_AVRC_RN_SYSTEM_STATUS_CHANGE system status changed enumerator ESP_AVRC_RN_SYSTEM_STATUS_CHANGE system status changed enumerator ESP_AVRC_RN_APP_SETTING_CHANGE application settings changed enumerator ESP_AVRC_RN_APP_SETTING_CHANGE application settings changed enumerator ESP_AVRC_RN_NOW_PLAYING_CHANGE now playing content changed enumerator ESP_AVRC_RN_NOW_PLAYING_CHANGE now playing content changed enumerator ESP_AVRC_RN_AVAILABLE_PLAYERS_CHANGE available players changed enumerator ESP_AVRC_RN_AVAILABLE_PLAYERS_CHANGE available players changed enumerator ESP_AVRC_RN_ADDRESSED_PLAYER_CHANGE the addressed player changed enumerator ESP_AVRC_RN_ADDRESSED_PLAYER_CHANGE the addressed player changed enumerator ESP_AVRC_RN_UIDS_CHANGE UIDs changed enumerator ESP_AVRC_RN_UIDS_CHANGE UIDs changed enumerator ESP_AVRC_RN_VOLUME_CHANGE volume changed locally on TG enumerator ESP_AVRC_RN_VOLUME_CHANGE volume changed locally on TG enumerator ESP_AVRC_RN_MAX_EVT enumerator ESP_AVRC_RN_MAX_EVT enumerator ESP_AVRC_RN_PLAY_STATUS_CHANGE enum esp_avrc_rn_evt_cap_t AVRC target notification event notification capability. Values: enumerator ESP_AVRC_RN_CAP_ALLOWED_EVT all of the notification events that can possibly be supported, immutable enumerator ESP_AVRC_RN_CAP_ALLOWED_EVT all of the notification events that can possibly be supported, immutable enumerator ESP_AVRC_RN_CAP_SUPPORTED_EVT notification events selectively supported according to the current configuration enumerator ESP_AVRC_RN_CAP_SUPPORTED_EVT notification events selectively supported according to the current configuration enumerator ESP_AVRC_RN_CAP_MAX enumerator ESP_AVRC_RN_CAP_MAX enumerator ESP_AVRC_RN_CAP_ALLOWED_EVT enum esp_avrc_rn_rsp_t AVRC notification response type. Values: enumerator ESP_AVRC_RN_RSP_INTERIM initial response to RegisterNotification, should be sent T_mtp(1000ms) from receiving the command enumerator ESP_AVRC_RN_RSP_INTERIM initial response to RegisterNotification, should be sent T_mtp(1000ms) from receiving the command enumerator ESP_AVRC_RN_RSP_CHANGED final response to RegisterNotification command enumerator ESP_AVRC_RN_RSP_CHANGED final response to RegisterNotification command enumerator ESP_AVRC_RN_RSP_INTERIM enum esp_avrc_ps_attr_ids_t AVRC player setting ids. Values: enumerator ESP_AVRC_PS_EQUALIZER equalizer, on or off enumerator ESP_AVRC_PS_EQUALIZER equalizer, on or off enumerator ESP_AVRC_PS_REPEAT_MODE repeat mode enumerator ESP_AVRC_PS_REPEAT_MODE repeat mode enumerator ESP_AVRC_PS_SHUFFLE_MODE shuffle mode enumerator ESP_AVRC_PS_SHUFFLE_MODE shuffle mode enumerator ESP_AVRC_PS_SCAN_MODE scan mode on or off enumerator ESP_AVRC_PS_SCAN_MODE scan mode on or off enumerator ESP_AVRC_PS_MAX_ATTR enumerator ESP_AVRC_PS_MAX_ATTR enumerator ESP_AVRC_PS_EQUALIZER enum esp_avrc_ps_eq_value_ids_t AVRC equalizer modes. Values: enumerator ESP_AVRC_PS_EQUALIZER_OFF equalizer OFF enumerator ESP_AVRC_PS_EQUALIZER_OFF equalizer OFF enumerator ESP_AVRC_PS_EQUALIZER_ON equalizer ON enumerator ESP_AVRC_PS_EQUALIZER_ON equalizer ON enumerator ESP_AVRC_PS_EQUALIZER_OFF enum esp_avrc_ps_rpt_value_ids_t AVRC repeat modes. Values: enumerator ESP_AVRC_PS_REPEAT_OFF repeat mode off enumerator ESP_AVRC_PS_REPEAT_OFF repeat mode off enumerator ESP_AVRC_PS_REPEAT_SINGLE single track repeat enumerator ESP_AVRC_PS_REPEAT_SINGLE single track repeat enumerator ESP_AVRC_PS_REPEAT_GROUP group repeat enumerator ESP_AVRC_PS_REPEAT_GROUP group repeat enumerator ESP_AVRC_PS_REPEAT_OFF enum esp_avrc_ps_shf_value_ids_t AVRC shuffle modes. Values: enumerator ESP_AVRC_PS_SHUFFLE_OFF enumerator ESP_AVRC_PS_SHUFFLE_OFF enumerator ESP_AVRC_PS_SHUFFLE_ALL enumerator ESP_AVRC_PS_SHUFFLE_ALL enumerator ESP_AVRC_PS_SHUFFLE_GROUP enumerator ESP_AVRC_PS_SHUFFLE_GROUP enumerator ESP_AVRC_PS_SHUFFLE_OFF enum esp_avrc_ps_scn_value_ids_t AVRC scan modes. Values: enumerator ESP_AVRC_PS_SCAN_OFF scan off enumerator ESP_AVRC_PS_SCAN_OFF scan off enumerator ESP_AVRC_PS_SCAN_ALL all tracks scan enumerator ESP_AVRC_PS_SCAN_ALL all tracks scan enumerator ESP_AVRC_PS_SCAN_GROUP group scan enumerator ESP_AVRC_PS_SCAN_GROUP group scan enumerator ESP_AVRC_PS_SCAN_OFF enum esp_avrc_rsp_t AVCTP response codes. Values: enumerator ESP_AVRC_RSP_NOT_IMPL not implemented enumerator ESP_AVRC_RSP_NOT_IMPL not implemented enumerator ESP_AVRC_RSP_ACCEPT accept enumerator ESP_AVRC_RSP_ACCEPT accept enumerator ESP_AVRC_RSP_REJECT reject enumerator ESP_AVRC_RSP_REJECT reject enumerator ESP_AVRC_RSP_IN_TRANS in transition enumerator ESP_AVRC_RSP_IN_TRANS in transition enumerator ESP_AVRC_RSP_IMPL_STBL implemented/stable enumerator ESP_AVRC_RSP_IMPL_STBL implemented/stable enumerator ESP_AVRC_RSP_CHANGED changed enumerator ESP_AVRC_RSP_CHANGED changed enumerator ESP_AVRC_RSP_INTERIM interim enumerator ESP_AVRC_RSP_INTERIM interim enumerator ESP_AVRC_RSP_NOT_IMPL enum esp_avrc_batt_stat_t AVRCP battery status. Values: enumerator ESP_AVRC_BATT_NORMAL normal state enumerator ESP_AVRC_BATT_NORMAL normal state enumerator ESP_AVRC_BATT_WARNING unable to operate soon enumerator ESP_AVRC_BATT_WARNING unable to operate soon enumerator ESP_AVRC_BATT_CRITICAL cannot operate any more enumerator ESP_AVRC_BATT_CRITICAL cannot operate any more enumerator ESP_AVRC_BATT_EXTERNAL plugged to external power supply enumerator ESP_AVRC_BATT_EXTERNAL plugged to external power supply enumerator ESP_AVRC_BATT_FULL_CHARGE when completely charged from external power supply enumerator ESP_AVRC_BATT_FULL_CHARGE when completely charged from external power supply enumerator ESP_AVRC_BATT_NORMAL enum esp_avrc_playback_stat_t AVRCP current status of playback. Values: enumerator ESP_AVRC_PLAYBACK_STOPPED stopped enumerator ESP_AVRC_PLAYBACK_STOPPED stopped enumerator ESP_AVRC_PLAYBACK_PLAYING playing enumerator ESP_AVRC_PLAYBACK_PLAYING playing enumerator ESP_AVRC_PLAYBACK_PAUSED paused enumerator ESP_AVRC_PLAYBACK_PAUSED paused enumerator ESP_AVRC_PLAYBACK_FWD_SEEK forward seek enumerator ESP_AVRC_PLAYBACK_FWD_SEEK forward seek enumerator ESP_AVRC_PLAYBACK_REV_SEEK reverse seek enumerator ESP_AVRC_PLAYBACK_REV_SEEK reverse seek enumerator ESP_AVRC_PLAYBACK_ERROR error enumerator ESP_AVRC_PLAYBACK_ERROR error enumerator ESP_AVRC_PLAYBACK_STOPPED
Bluetooth® AVRCP APIs Overview Bluetooth AVRCP reference APIs. API Reference Header File This header file can be included with: #include "esp_avrc_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_avrc_ct_register_callback(esp_avrc_ct_cb_t callback) Register application callbacks to AVRCP module. This function should be called after esp_bluedroid_enable() completes successfully. - Parameters callback -- [in] AVRCP controller callback function - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_avrc_ct_init(void) Initialize the bluetooth AVRCP controller module, This function should be called after esp_bluedroid_enable() completes successfully. Note: AVRC cannot work independently, AVRC should be used along with A2DP and AVRC should be initialized before A2DP. - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_avrc_ct_deinit(void) De-initialize AVRCP controller module. This function should be called after after esp_bluedroid_enable() completes successfully. Note: AVRC cannot work independently, AVRC should be used along with A2DP and AVRC should be deinitialized before A2DP. - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_avrc_ct_send_set_player_value_cmd(uint8_t tl, uint8_t attr_id, uint8_t value_id) Send player application settings command to AVRCP target. This function should be called after ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established. - Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values attr_id -- [in] : player application setting attribute IDs from one of esp_avrc_ps_attr_ids_t value_id -- [in] : attribute value defined for the specific player application setting attribute - - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_avrc_ct_send_get_rn_capabilities_cmd(uint8_t tl) Send GetCapabilities PDU to AVRCP target to retrieve remote device's supported notification event_ids. This function should be called after ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established. - Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_avrc_ct_send_register_notification_cmd(uint8_t tl, uint8_t event_id, uint32_t event_parameter) Send register notification command to AVRCP target. This function should be called after ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established. - Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values. event_id -- [in] : id of events, e.g. ESP_AVRC_RN_PLAY_STATUS_CHANGE, ESP_AVRC_RN_TRACK_CHANGE, etc. event_parameter -- [in] : playback interval for ESP_AVRC_RN_PLAY_POS_CHANGED; For other events , value of this parameter is ignored. - - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_NOT_SUPPORTED: if the event_id is not supported in current implementation ESP_FAIL: others - - esp_err_t esp_avrc_ct_send_set_absolute_volume_cmd(uint8_t tl, uint8_t volume) Send set absolute volume command to AVRCP target. This function should be called after ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established. - Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values volume -- [in] : volume, 0 to 0x7f, means 0% to 100% - - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_NOT_SUPPORTED: if the event_id is not supported in current implementation ESP_FAIL: others - - esp_err_t esp_avrc_ct_send_metadata_cmd(uint8_t tl, uint8_t attr_mask) Send metadata command to AVRCP target. This function should be called after ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established. - Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values. attr_mask -- [in] : mask of attributes, e.g. ESP_AVRC_MD_ATTR_ID_TITLE | ESP_AVRC_MD_ATTR_ID_ARTIST. - - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_avrc_ct_send_passthrough_cmd(uint8_t tl, uint8_t key_code, uint8_t key_state) Send passthrough command to AVRCP target. This function should be called after ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established. - Parameters tl -- [in] : transaction label, 0 to 15, consecutive commands should use different values. key_code -- [in] : passthrough command code, e.g. ESP_AVRC_PT_CMD_PLAY, ESP_AVRC_PT_CMD_STOP, etc. key_state -- [in] : passthrough command key state, ESP_AVRC_PT_CMD_STATE_PRESSED or ESP_AVRC_PT_CMD_STATE_RELEASED - - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_avrc_tg_register_callback(esp_avrc_tg_cb_t callback) Register application callbacks to AVRCP target module. This function should be called after esp_bluedroid_enable() completes successfully. - Parameters callback -- [in] AVRCP target callback function - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_avrc_tg_init(void) Initialize the bluetooth AVRCP target module, This function should be called after esp_bluedroid_enable() completes successfully. Note: AVRC cannot work independently, AVRC should be used along with A2DP and AVRC should be initialized before A2DP. - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_avrc_tg_deinit(void) De-initialize AVRCP target module. This function should be called after after esp_bluedroid_enable() completes successfully. Note: AVRC cannot work independently, AVRC should be used along with A2DP and AVRC should be deinitialized before A2DP. - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_avrc_tg_get_psth_cmd_filter(esp_avrc_psth_filter_t filter, esp_avrc_psth_bit_mask_t *cmd_set) Get the current filter of remote passthrough commands on AVRC target. Filter is given by filter type and bit mask for the passthrough commands. This function should be called after esp_avrc_tg_init(). For filter type ESP_AVRC_PSTH_FILTER_ALLOWED_CMD, the retrieved command set is constant and it covers all of the passthrough commands that can possibly be supported. For filter type ESP_AVRC_PSTH_FILTER_SUPPORT_COMMANDS, the retrieved command set covers the passthrough commands selected to be supported according to current configuration. The configuration can be changed using esp_avrc_tg_set_psth_cmd_filter(). - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not initialized ESP_ERR_INVALID_ARG: if filter type is invalid or cmd_set is NULL ESP_FAIL: otherwise - - esp_err_t esp_avrc_tg_set_psth_cmd_filter(esp_avrc_psth_filter_t filter, const esp_avrc_psth_bit_mask_t *cmd_set) Set the filter of remote passthrough commands on AVRC target. Filter is given by filter type and bit mask for the passthrough commands. This function should be called after esp_avrc_tg_init(). If filter type is ESP_AVRC_PSTH_FILTER_SUPPORT_CMD, the passthrough commands which are set "1" as given in cmd_set will generate ESP_AVRC_CT_PASSTHROUGH_RSP_EVT callback event and are auto-accepted in the protocol stack, other commands are replied with response type "NOT IMPLEMENTED" (8). The set of supported commands should be a subset of allowed command set. The allowed command set can be retrieved using esp_avrc_tg_get_psth_cmd_filter() with filter type "ESP_AVRC_PSTH_FILTER_ALLOWED_CMD". Filter type "ESP_AVRC_PSTH_FILTER_ALLOWED_CMD" does not apply to this function. - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled ESP_ERR_INVALID_ARG: if filter type is invalid or cmd_set is NULL ESP_ERR_NOT_SUPPORTED:: if filter type is ESP_AVRC_PSTH_FILTER_ALLOWED_CMD, or cmd_set includes commands that are not allowed - - bool esp_avrc_psth_bit_mask_operation(esp_avrc_bit_mask_op_t op, esp_avrc_psth_bit_mask_t *psth, esp_avrc_pt_cmd_t cmd) Operate on the type esp_avrc_psth_bit_mask_t with regard to a specific PASSTHROUGH command. - Parameters op -- [in] operation requested on the bit mask field psth -- [in] pointer to passthrough command bit mask structure cmd -- [in] passthrough command code - - Returns For operation ESP_AVRC_BIT_MASK_OP_SET or ESP_AVRC_BIT_MASK_OP_CLEAR, return true for a successful operation, otherwise return false. For operation ESP_AVRC_BIT_MASK_OP_TEST, return true if the corresponding bit is set, otherwise false. - esp_err_t esp_avrc_tg_get_rn_evt_cap(esp_avrc_rn_evt_cap_t cap, esp_avrc_rn_evt_cap_mask_t *evt_set) Get the requested event notification capabilies on local AVRC target. The capability is returned in a bit mask representation in evt_set. This function should be called after esp_avrc_tg_init(). For capability type "ESP_AVRC_RN_CAP_ALLOWED_EVT, the retrieved event set is constant and it covers all of the notifcation events that can possibly be supported with current implementation. For capability type ESP_AVRC_RN_CAP_SUPPORTED_EVT, the event set covers the notification events selected to be supported under current configuration, The configuration can be changed using esp_avrc_tg_set_rn_evt_cap(). - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not initialized ESP_ERR_INVALID_ARG: if cap is invalid or evt_set is NULL ESP_FAIL: otherwise - - esp_err_t esp_avrc_tg_set_rn_evt_cap(const esp_avrc_rn_evt_cap_mask_t *evt_set) Set the event notification capabilities on local AVRCP target. The capability is given in a bit mask representation in evt_set and must be a subset of allowed event IDs with current implementation. This function should be called after esp_avrc_tg_init(). - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled ESP_ERR_INVALID_ARG: if evt_set is NULL - - bool esp_avrc_rn_evt_bit_mask_operation(esp_avrc_bit_mask_op_t op, esp_avrc_rn_evt_cap_mask_t *events, esp_avrc_rn_event_ids_t event_id) Operate on the type esp_avrc_rn_evt_cap_mask_t with regard to a specific event. For operation ESP_AVRC_BIT_MASK_OP_TEST, return true if the corresponding bit is set, otherwise false. - Parameters op -- [in] operation requested on the bit mask field events -- [in] pointer to event notification capability bit mask structure event_id -- [in] notification event code - - Returns For operation ESP_AVRC_BIT_MASK_OP_SET or ESP_AVRC_BIT_MASK_OP_CLEAR, return true for a successful operation, otherwise return false. - esp_err_t esp_avrc_tg_send_rn_rsp(esp_avrc_rn_event_ids_t event_id, esp_avrc_rn_rsp_t rsp, esp_avrc_rn_param_t *param) Send RegisterNotification Response to remote AVRCP controller. Local event notification capability can be set using esp_avrc_tg_set_rn_evt_cap(), in a bit mask representation in evt_set. This function should be called after esp_avrc_tg_init(). - Parameters event_id -- [in] notification event ID that remote AVRCP CT registers rsp -- [in] notification response code param -- [in] parameters included in the specific notification - - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not initialized ESP_ERR_INVALID_ARG: if evt_set is NULL - Unions - union esp_avrc_rn_param_t - #include <esp_avrc_api.h> AVRCP notification parameters. Public Members - uint8_t volume response data for ESP_AVRC_RN_VOLUME_CHANGE, ranges 0..127 - esp_avrc_playback_stat_t playback response data for ESP_AVRC_RN_PLAY_STATUS_CHANGE - uint8_t elm_id[8] response data for ESP_AVRC_RN_TRACK_CHANGE - uint32_t play_pos response data for ESP_AVRC_RN_PLAY_POS_CHANGED, in millisecond - esp_avrc_batt_stat_t batt response data for ESP_AVRC_RN_BATTERY_STATUS_CHANGE - uint8_t volume - union esp_avrc_ct_cb_param_t - #include <esp_avrc_api.h> AVRC controller callback parameters. Public Members - struct esp_avrc_ct_cb_param_t::avrc_ct_conn_stat_param conn_stat AVRC connection status - struct esp_avrc_ct_cb_param_t::avrc_ct_psth_rsp_param psth_rsp passthrough command response - struct esp_avrc_ct_cb_param_t::avrc_ct_meta_rsp_param meta_rsp metadata attributes response - struct esp_avrc_ct_cb_param_t::avrc_ct_change_notify_param change_ntf notifications - struct esp_avrc_ct_cb_param_t::avrc_ct_rmt_feats_param rmt_feats AVRC features discovered from remote SDP server - struct esp_avrc_ct_cb_param_t::avrc_ct_get_rn_caps_rsp_param get_rn_caps_rsp get supported event capabilities response from AVRCP target - struct esp_avrc_ct_cb_param_t::avrc_ct_set_volume_rsp_param set_volume_rsp set absolute volume response event - struct avrc_ct_change_notify_param - #include <esp_avrc_api.h> ESP_AVRC_CT_CHANGE_NOTIFY_EVT. Public Members - uint8_t event_id id of AVRC event notification - esp_avrc_rn_param_t event_parameter event notification parameter - uint8_t event_id - struct avrc_ct_conn_stat_param - #include <esp_avrc_api.h> ESP_AVRC_CT_CONNECTION_STATE_EVT. Public Members - bool connected whether AVRC connection is set up - esp_bd_addr_t remote_bda remote bluetooth device address - bool connected - struct avrc_ct_get_rn_caps_rsp_param - #include <esp_avrc_api.h> ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT. Public Members - uint8_t cap_count number of items provided in event or company_id according to cap_id used - esp_avrc_rn_evt_cap_mask_t evt_set supported event_ids represented in bit-mask - uint8_t cap_count - struct avrc_ct_meta_rsp_param - #include <esp_avrc_api.h> ESP_AVRC_CT_METADATA_RSP_EVT. - struct avrc_ct_psth_rsp_param - #include <esp_avrc_api.h> ESP_AVRC_CT_PASSTHROUGH_RSP_EVT. Public Members - uint8_t tl transaction label, 0 to 15 - uint8_t key_code passthrough command code - uint8_t key_state 0 for PRESSED, 1 for RELEASED - esp_avrc_rsp_t rsp_code response code - uint8_t tl - struct avrc_ct_rmt_feats_param - #include <esp_avrc_api.h> ESP_AVRC_CT_REMOTE_FEATURES_EVT. Public Members - uint32_t feat_mask AVRC feature mask of remote device - uint16_t tg_feat_flag feature flag of remote device as TG - esp_bd_addr_t remote_bda remote bluetooth device address - uint32_t feat_mask - struct esp_avrc_ct_cb_param_t::avrc_ct_conn_stat_param conn_stat - union esp_avrc_tg_cb_param_t - #include <esp_avrc_api.h> AVRC target callback parameters. Public Members - struct esp_avrc_tg_cb_param_t::avrc_tg_conn_stat_param conn_stat AVRC connection status - struct esp_avrc_tg_cb_param_t::avrc_tg_rmt_feats_param rmt_feats AVRC features discovered through SDP - struct esp_avrc_tg_cb_param_t::avrc_tg_psth_cmd_param psth_cmd passthrough command - struct esp_avrc_tg_cb_param_t::avrc_tg_set_abs_vol_param set_abs_vol set absolute volume command targeted on audio sink - struct esp_avrc_tg_cb_param_t::avrc_tg_reg_ntf_param reg_ntf register notification - struct esp_avrc_tg_cb_param_t::avrc_tg_set_app_value_param set_app_value set player application value - struct avrc_tg_conn_stat_param - #include <esp_avrc_api.h> ESP_AVRC_TG_CONNECTION_STATE_EVT. Public Members - bool connected whether AVRC connection is set up - esp_bd_addr_t remote_bda remote bluetooth device address - bool connected - struct avrc_tg_psth_cmd_param - #include <esp_avrc_api.h> ESP_AVRC_TG_PASSTHROUGH_CMD_EVT. - struct avrc_tg_reg_ntf_param - #include <esp_avrc_api.h> ESP_AVRC_TG_REGISTER_NOTIFICATION_EVT. - struct avrc_tg_rmt_feats_param - #include <esp_avrc_api.h> ESP_AVRC_TG_REMOTE_FEATURES_EVT. Public Members - uint32_t feat_mask AVRC feature mask of remote device - uint16_t ct_feat_flag feature flag of remote device as CT - esp_bd_addr_t remote_bda remote bluetooth device address - uint32_t feat_mask - struct avrc_tg_set_abs_vol_param - #include <esp_avrc_api.h> ESP_AVRC_TG_SET_ABSOLUTE_VOLUME_CMD_EVT. Public Members - uint8_t volume volume ranges from 0 to 127 - uint8_t volume - struct avrc_tg_set_app_value_param - #include <esp_avrc_api.h> ESP_AVRC_TG_SET_PLAYER_APP_VALUE_EVT. Public Members - uint8_t num_val attribute num - esp_avrc_set_app_value_param_t *p_vals point to the id and value of player application attribute - uint8_t num_val - struct esp_avrc_tg_cb_param_t::avrc_tg_conn_stat_param conn_stat Structures - struct esp_avrc_psth_bit_mask_t AVRC passthrough command bit mask. Public Members - uint16_t bits[8] bit mask representation of PASSTHROUGH commands - uint16_t bits[8] - struct esp_avrc_rn_evt_cap_mask_t AVRC target notification event capability bit mask. Public Members - uint16_t bits bit mask representation of PASSTHROUGH commands - uint16_t bits - struct esp_avrc_set_app_value_param_t AVRCP set app value parameters. Macros - ESP_AVRC_TRANS_LABEL_MAX max transaction label Type Definitions - typedef void (*esp_avrc_ct_cb_t)(esp_avrc_ct_cb_event_t event, esp_avrc_ct_cb_param_t *param) AVRCP controller callback function type. - Param event : Event type - Param param : Pointer to callback parameter union - typedef void (*esp_avrc_tg_cb_t)(esp_avrc_tg_cb_event_t event, esp_avrc_tg_cb_param_t *param) AVRCP target callback function type. - Param event : Event type - Param param : Pointer to callback parameter union Enumerations - enum esp_avrc_features_t AVRC feature bit mask. Values: - enumerator ESP_AVRC_FEAT_RCTG remote control target - enumerator ESP_AVRC_FEAT_RCCT remote control controller - enumerator ESP_AVRC_FEAT_VENDOR remote control vendor dependent commands - enumerator ESP_AVRC_FEAT_BROWSE use browsing channel - enumerator ESP_AVRC_FEAT_META_DATA remote control metadata transfer command/response - enumerator ESP_AVRC_FEAT_ADV_CTRL remote control advanced control command/response - enumerator ESP_AVRC_FEAT_RCTG - enum esp_avrc_feature_flag_t AVRC supported features flag retrieved in SDP record. Values: - enumerator ESP_AVRC_FEAT_FLAG_CAT1 category 1 - enumerator ESP_AVRC_FEAT_FLAG_CAT2 category 2 - enumerator ESP_AVRC_FEAT_FLAG_CAT3 category 3 - enumerator ESP_AVRC_FEAT_FLAG_CAT4 category 4 - enumerator ESP_AVRC_FEAT_FLAG_BROWSING browsing - enumerator ESP_AVRC_FEAT_FLAG_COVER_ART_GET_IMAGE_PROP Cover Art GetImageProperties - enumerator ESP_AVRC_FEAT_FLAG_COVER_ART_GET_IMAGE Cover Art GetImage - enumerator ESP_AVRC_FEAT_FLAG_COVER_ART_GET_LINKED_THUMBNAIL Cover Art GetLinkedThumbnail - enumerator ESP_AVRC_FEAT_FLAG_CAT1 - enum esp_avrc_pt_cmd_t AVRC passthrough command code. Values: - enumerator ESP_AVRC_PT_CMD_SELECT select - enumerator ESP_AVRC_PT_CMD_UP up - enumerator ESP_AVRC_PT_CMD_DOWN down - enumerator ESP_AVRC_PT_CMD_LEFT left - enumerator ESP_AVRC_PT_CMD_RIGHT right - enumerator ESP_AVRC_PT_CMD_RIGHT_UP right-up - enumerator ESP_AVRC_PT_CMD_RIGHT_DOWN right-down - enumerator ESP_AVRC_PT_CMD_LEFT_UP left-up - enumerator ESP_AVRC_PT_CMD_LEFT_DOWN left-down - enumerator ESP_AVRC_PT_CMD_ROOT_MENU root menu - enumerator ESP_AVRC_PT_CMD_SETUP_MENU setup menu - enumerator ESP_AVRC_PT_CMD_CONT_MENU contents menu - enumerator ESP_AVRC_PT_CMD_FAV_MENU favorite menu - enumerator ESP_AVRC_PT_CMD_EXIT exit - enumerator ESP_AVRC_PT_CMD_0 0 - enumerator ESP_AVRC_PT_CMD_1 1 - enumerator ESP_AVRC_PT_CMD_2 2 - enumerator ESP_AVRC_PT_CMD_3 3 - enumerator ESP_AVRC_PT_CMD_4 4 - enumerator ESP_AVRC_PT_CMD_5 5 - enumerator ESP_AVRC_PT_CMD_6 6 - enumerator ESP_AVRC_PT_CMD_7 7 - enumerator ESP_AVRC_PT_CMD_8 8 - enumerator ESP_AVRC_PT_CMD_9 9 - enumerator ESP_AVRC_PT_CMD_DOT dot - enumerator ESP_AVRC_PT_CMD_ENTER enter - enumerator ESP_AVRC_PT_CMD_CLEAR clear - enumerator ESP_AVRC_PT_CMD_CHAN_UP channel up - enumerator ESP_AVRC_PT_CMD_CHAN_DOWN channel down - enumerator ESP_AVRC_PT_CMD_PREV_CHAN previous channel - enumerator ESP_AVRC_PT_CMD_SOUND_SEL sound select - enumerator ESP_AVRC_PT_CMD_INPUT_SEL input select - enumerator ESP_AVRC_PT_CMD_DISP_INFO display information - enumerator ESP_AVRC_PT_CMD_HELP help - enumerator ESP_AVRC_PT_CMD_PAGE_UP page up - enumerator ESP_AVRC_PT_CMD_PAGE_DOWN page down - enumerator ESP_AVRC_PT_CMD_POWER power - enumerator ESP_AVRC_PT_CMD_VOL_UP volume up - enumerator ESP_AVRC_PT_CMD_VOL_DOWN volume down - enumerator ESP_AVRC_PT_CMD_MUTE mute - enumerator ESP_AVRC_PT_CMD_PLAY play - enumerator ESP_AVRC_PT_CMD_STOP stop - enumerator ESP_AVRC_PT_CMD_PAUSE pause - enumerator ESP_AVRC_PT_CMD_RECORD record - enumerator ESP_AVRC_PT_CMD_REWIND rewind - enumerator ESP_AVRC_PT_CMD_FAST_FORWARD fast forward - enumerator ESP_AVRC_PT_CMD_EJECT eject - enumerator ESP_AVRC_PT_CMD_FORWARD forward - enumerator ESP_AVRC_PT_CMD_BACKWARD backward - enumerator ESP_AVRC_PT_CMD_ANGLE angle - enumerator ESP_AVRC_PT_CMD_SUBPICT subpicture - enumerator ESP_AVRC_PT_CMD_F1 F1 - enumerator ESP_AVRC_PT_CMD_F2 F2 - enumerator ESP_AVRC_PT_CMD_F3 F3 - enumerator ESP_AVRC_PT_CMD_F4 F4 - enumerator ESP_AVRC_PT_CMD_F5 F5 - enumerator ESP_AVRC_PT_CMD_VENDOR vendor unique - enumerator ESP_AVRC_PT_CMD_SELECT - enum esp_avrc_psth_filter_t AVRC passthrough command filter. Values: - enumerator ESP_AVRC_PSTH_FILTER_ALLOWED_CMD all of the PASSTHROUGH commands that can possibly be used, immutable - enumerator ESP_AVRC_PSTH_FILTER_SUPPORTED_CMD PASSTHROUGH commands selectively supported according to the current configuration - enumerator ESP_AVRC_PSTH_FILTER_SUPPORT_MAX - enumerator ESP_AVRC_PSTH_FILTER_ALLOWED_CMD - enum esp_avrc_bit_mask_op_t Values: - enumerator ESP_AVRC_BIT_MASK_OP_TEST operation code to test a specific bit - enumerator ESP_AVRC_BIT_MASK_OP_SET operation code to set a specific bit - enumerator ESP_AVRC_BIT_MASK_OP_CLEAR operation code to clear a specific bit - enumerator ESP_AVRC_BIT_MASK_OP_TEST - enum esp_avrc_pt_cmd_state_t AVRC passthrough command state. Values: - enumerator ESP_AVRC_PT_CMD_STATE_PRESSED key pressed - enumerator ESP_AVRC_PT_CMD_STATE_RELEASED key released - enumerator ESP_AVRC_PT_CMD_STATE_PRESSED - enum esp_avrc_ct_cb_event_t AVRC Controller callback events. Values: - enumerator ESP_AVRC_CT_CONNECTION_STATE_EVT connection state changed event - enumerator ESP_AVRC_CT_PASSTHROUGH_RSP_EVT passthrough response event - enumerator ESP_AVRC_CT_METADATA_RSP_EVT metadata response event - enumerator ESP_AVRC_CT_PLAY_STATUS_RSP_EVT play status response event - enumerator ESP_AVRC_CT_CHANGE_NOTIFY_EVT notification event - enumerator ESP_AVRC_CT_REMOTE_FEATURES_EVT feature of remote device indication event - enumerator ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT supported notification events capability of peer device - enumerator ESP_AVRC_CT_SET_ABSOLUTE_VOLUME_RSP_EVT set absolute volume response event - enumerator ESP_AVRC_CT_CONNECTION_STATE_EVT - enum esp_avrc_tg_cb_event_t AVRC Target callback events. Values: - enumerator ESP_AVRC_TG_CONNECTION_STATE_EVT connection state changed event - enumerator ESP_AVRC_TG_REMOTE_FEATURES_EVT feature of remote device indication event - enumerator ESP_AVRC_TG_PASSTHROUGH_CMD_EVT passthrough command event - enumerator ESP_AVRC_TG_SET_ABSOLUTE_VOLUME_CMD_EVT set absolute volume command from remote device - enumerator ESP_AVRC_TG_REGISTER_NOTIFICATION_EVT register notification event - enumerator ESP_AVRC_TG_SET_PLAYER_APP_VALUE_EVT set application attribute value, attribute refer to esp_avrc_ps_attr_ids_t - enumerator ESP_AVRC_TG_CONNECTION_STATE_EVT - enum esp_avrc_md_attr_mask_t AVRC metadata attribute mask. Values: - enumerator ESP_AVRC_MD_ATTR_TITLE title of the playing track - enumerator ESP_AVRC_MD_ATTR_ARTIST track artist - enumerator ESP_AVRC_MD_ATTR_ALBUM album name - enumerator ESP_AVRC_MD_ATTR_TRACK_NUM track position on the album - enumerator ESP_AVRC_MD_ATTR_NUM_TRACKS number of tracks on the album - enumerator ESP_AVRC_MD_ATTR_GENRE track genre - enumerator ESP_AVRC_MD_ATTR_PLAYING_TIME total album playing time in miliseconds - enumerator ESP_AVRC_MD_ATTR_TITLE - enum esp_avrc_rn_event_ids_t AVRC event notification ids. Values: - enumerator ESP_AVRC_RN_PLAY_STATUS_CHANGE track status change, eg. from playing to paused - enumerator ESP_AVRC_RN_TRACK_CHANGE new track is loaded - enumerator ESP_AVRC_RN_TRACK_REACHED_END current track reached end - enumerator ESP_AVRC_RN_TRACK_REACHED_START current track reached start position - enumerator ESP_AVRC_RN_PLAY_POS_CHANGED track playing position changed - enumerator ESP_AVRC_RN_BATTERY_STATUS_CHANGE battery status changed - enumerator ESP_AVRC_RN_SYSTEM_STATUS_CHANGE system status changed - enumerator ESP_AVRC_RN_APP_SETTING_CHANGE application settings changed - enumerator ESP_AVRC_RN_NOW_PLAYING_CHANGE now playing content changed - enumerator ESP_AVRC_RN_AVAILABLE_PLAYERS_CHANGE available players changed - enumerator ESP_AVRC_RN_ADDRESSED_PLAYER_CHANGE the addressed player changed - enumerator ESP_AVRC_RN_UIDS_CHANGE UIDs changed - enumerator ESP_AVRC_RN_VOLUME_CHANGE volume changed locally on TG - enumerator ESP_AVRC_RN_MAX_EVT - enumerator ESP_AVRC_RN_PLAY_STATUS_CHANGE - enum esp_avrc_rn_evt_cap_t AVRC target notification event notification capability. Values: - enumerator ESP_AVRC_RN_CAP_ALLOWED_EVT all of the notification events that can possibly be supported, immutable - enumerator ESP_AVRC_RN_CAP_SUPPORTED_EVT notification events selectively supported according to the current configuration - enumerator ESP_AVRC_RN_CAP_MAX - enumerator ESP_AVRC_RN_CAP_ALLOWED_EVT - enum esp_avrc_rn_rsp_t AVRC notification response type. Values: - enumerator ESP_AVRC_RN_RSP_INTERIM initial response to RegisterNotification, should be sent T_mtp(1000ms) from receiving the command - enumerator ESP_AVRC_RN_RSP_CHANGED final response to RegisterNotification command - enumerator ESP_AVRC_RN_RSP_INTERIM - enum esp_avrc_ps_attr_ids_t AVRC player setting ids. Values: - enumerator ESP_AVRC_PS_EQUALIZER equalizer, on or off - enumerator ESP_AVRC_PS_REPEAT_MODE repeat mode - enumerator ESP_AVRC_PS_SHUFFLE_MODE shuffle mode - enumerator ESP_AVRC_PS_SCAN_MODE scan mode on or off - enumerator ESP_AVRC_PS_MAX_ATTR - enumerator ESP_AVRC_PS_EQUALIZER - enum esp_avrc_ps_eq_value_ids_t AVRC equalizer modes. Values: - enumerator ESP_AVRC_PS_EQUALIZER_OFF equalizer OFF - enumerator ESP_AVRC_PS_EQUALIZER_ON equalizer ON - enumerator ESP_AVRC_PS_EQUALIZER_OFF - enum esp_avrc_ps_rpt_value_ids_t AVRC repeat modes. Values: - enumerator ESP_AVRC_PS_REPEAT_OFF repeat mode off - enumerator ESP_AVRC_PS_REPEAT_SINGLE single track repeat - enumerator ESP_AVRC_PS_REPEAT_GROUP group repeat - enumerator ESP_AVRC_PS_REPEAT_OFF - enum esp_avrc_ps_shf_value_ids_t AVRC shuffle modes. Values: - enumerator ESP_AVRC_PS_SHUFFLE_OFF - enumerator ESP_AVRC_PS_SHUFFLE_ALL - enumerator ESP_AVRC_PS_SHUFFLE_GROUP - enumerator ESP_AVRC_PS_SHUFFLE_OFF - enum esp_avrc_ps_scn_value_ids_t AVRC scan modes. Values: - enumerator ESP_AVRC_PS_SCAN_OFF scan off - enumerator ESP_AVRC_PS_SCAN_ALL all tracks scan - enumerator ESP_AVRC_PS_SCAN_GROUP group scan - enumerator ESP_AVRC_PS_SCAN_OFF - enum esp_avrc_rsp_t AVCTP response codes. Values: - enumerator ESP_AVRC_RSP_NOT_IMPL not implemented - enumerator ESP_AVRC_RSP_ACCEPT accept - enumerator ESP_AVRC_RSP_REJECT reject - enumerator ESP_AVRC_RSP_IN_TRANS in transition - enumerator ESP_AVRC_RSP_IMPL_STBL implemented/stable - enumerator ESP_AVRC_RSP_CHANGED changed - enumerator ESP_AVRC_RSP_INTERIM interim - enumerator ESP_AVRC_RSP_NOT_IMPL - enum esp_avrc_batt_stat_t AVRCP battery status. Values: - enumerator ESP_AVRC_BATT_NORMAL normal state - enumerator ESP_AVRC_BATT_WARNING unable to operate soon - enumerator ESP_AVRC_BATT_CRITICAL cannot operate any more - enumerator ESP_AVRC_BATT_EXTERNAL plugged to external power supply - enumerator ESP_AVRC_BATT_FULL_CHARGE when completely charged from external power supply - enumerator ESP_AVRC_BATT_NORMAL - enum esp_avrc_playback_stat_t AVRCP current status of playback. Values: - enumerator ESP_AVRC_PLAYBACK_STOPPED stopped - enumerator ESP_AVRC_PLAYBACK_PLAYING playing - enumerator ESP_AVRC_PLAYBACK_PAUSED paused - enumerator ESP_AVRC_PLAYBACK_FWD_SEEK forward seek - enumerator ESP_AVRC_PLAYBACK_REV_SEEK reverse seek - enumerator ESP_AVRC_PLAYBACK_ERROR error - enumerator ESP_AVRC_PLAYBACK_STOPPED
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_avrc.html
ESP-IDF Programming Guide v5.2.1 documentation
null
SPP API
null
espressif.com
2016-01-01
d678aed2aa239b0b
null
null
SPP API Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the following application: This is a SPP demo. This demo can discover the service, connect, send and recive SPP data bluetooth/bluedroid/classic_bt/bt_spp_acceptor, bluetooth/bluedroid/classic_bt/bt_spp_initiator API Reference Header File This header file can be included with: #include "esp_spp_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_spp_register_callback(esp_spp_cb_t callback) This function is called to init callbacks with SPP module. Parameters callback -- [in] pointer to the init callback function. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters callback -- [in] pointer to the init callback function. Returns ESP_OK: success other: failed esp_err_t esp_spp_init(esp_spp_mode_t mode) This function is called to init SPP module. When the operation is completed, the callback function will be called with ESP_SPP_INIT_EVT. This function should be called after esp_bluedroid_enable() completes successfully. Parameters mode -- [in] Choose the mode of SPP, ESP_SPP_MODE_CB or ESP_SPP_MODE_VFS. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters mode -- [in] Choose the mode of SPP, ESP_SPP_MODE_CB or ESP_SPP_MODE_VFS. Returns ESP_OK: success other: failed esp_err_t esp_spp_enhanced_init(const esp_spp_cfg_t *cfg) This function is called to init SPP module. When the operation is completed, the callback function will be called with ESP_SPP_INIT_EVT. This function should be called after esp_bluedroid_enable() completes successfully. Note The member variable enable_l2cap_etrm in esp_spp_cfg_t can affect all L2CAP channel configurations of the upper layer RFCOMM protocol. Parameters cfg -- [in] SPP configuration. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters cfg -- [in] SPP configuration. Returns ESP_OK: success other: failed esp_err_t esp_spp_deinit(void) This function is called to uninit SPP module. The operation will close all active SPP connection first, then the callback function will be called with ESP_SPP_CLOSE_EVT, and the number of ESP_SPP_CLOSE_EVT is equal to the number of connection. When the operation is completed, the callback function will be called with ESP_SPP_UNINIT_EVT. This function should be called after esp_spp_init()/esp_spp_enhanced_init() completes successfully. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Returns ESP_OK: success other: failed esp_err_t esp_spp_start_discovery(esp_bd_addr_t bd_addr) This function is called to performs service discovery for the services provided by the given peer device. When the operation is completed, the callback function will be called with ESP_SPP_DISCOVERY_COMP_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit(). Parameters bd_addr -- [in] Remote device bluetooth device address. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters bd_addr -- [in] Remote device bluetooth device address. Returns ESP_OK: success other: failed esp_err_t esp_spp_connect(esp_spp_sec_t sec_mask, esp_spp_role_t role, uint8_t remote_scn, esp_bd_addr_t peer_bd_addr) This function makes an SPP connection to a remote BD Address. When the connection is initiated or failed to initiate, the callback is called with ESP_SPP_CL_INIT_EVT. When the connection is established or failed, the callback is called with ESP_SPP_OPEN_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit(). Parameters sec_mask -- [in] Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE, ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only. role -- [in] Master or slave. remote_scn -- [in] Remote device bluetooth device SCN. peer_bd_addr -- [in] Remote device bluetooth device address. sec_mask -- [in] Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE, ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only. role -- [in] Master or slave. remote_scn -- [in] Remote device bluetooth device SCN. peer_bd_addr -- [in] Remote device bluetooth device address. sec_mask -- [in] Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE, ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters sec_mask -- [in] Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE, ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only. role -- [in] Master or slave. remote_scn -- [in] Remote device bluetooth device SCN. peer_bd_addr -- [in] Remote device bluetooth device address. Returns ESP_OK: success other: failed esp_err_t esp_spp_disconnect(uint32_t handle) This function closes an SPP connection. When the operation is completed, the callback function will be called with ESP_SPP_CLOSE_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit(). Parameters handle -- [in] The connection handle. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters handle -- [in] The connection handle. Returns ESP_OK: success other: failed esp_err_t esp_spp_start_srv(esp_spp_sec_t sec_mask, esp_spp_role_t role, uint8_t local_scn, const char *name) This function create a SPP server and starts listening for an SPP connection request from a remote Bluetooth device. When the server is started successfully, the callback is called with ESP_SPP_START_EVT. When the connection is established, the callback is called with ESP_SPP_SRV_OPEN_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit(). Parameters sec_mask -- [in] Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE, ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only. role -- [in] Master or slave. local_scn -- [in] The specific channel you want to get. If channel is 0, means get any channel. name -- [in] Server's name. sec_mask -- [in] Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE, ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only. role -- [in] Master or slave. local_scn -- [in] The specific channel you want to get. If channel is 0, means get any channel. name -- [in] Server's name. sec_mask -- [in] Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE, ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters sec_mask -- [in] Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE, ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only. role -- [in] Master or slave. local_scn -- [in] The specific channel you want to get. If channel is 0, means get any channel. name -- [in] Server's name. Returns ESP_OK: success other: failed esp_err_t esp_spp_stop_srv(void) This function stops all SPP servers. The operation will close all active SPP connection first, then the callback function will be called with ESP_SPP_CLOSE_EVT, and the number of ESP_SPP_CLOSE_EVT is equal to the number of connection. When the operation is completed, the callback is called with ESP_SPP_SRV_STOP_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit(). Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Returns ESP_OK: success other: failed esp_err_t esp_spp_stop_srv_scn(uint8_t scn) This function stops a specific SPP server. The operation will close all active SPP connection first on the specific SPP server, then the callback function will be called with ESP_SPP_CLOSE_EVT, and the number of ESP_SPP_CLOSE_EVT is equal to the number of connection. When the operation is completed, the callback is called with ESP_SPP_SRV_STOP_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit(). Parameters scn -- [in] Server channel number. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters scn -- [in] Server channel number. Returns ESP_OK: success other: failed esp_err_t esp_spp_write(uint32_t handle, int len, uint8_t *p_data) This function is used to write data, only for ESP_SPP_MODE_CB. When this function need to be called repeatedly, it is strongly recommended to call this function again after the previous event ESP_SPP_WRITE_EVT is received and the parameter 'cong' is equal to false. If the previous event ESP_SPP_WRITE_EVT with parameter 'cong' is equal to true, the function can only be called again when the event ESP_SPP_CONG_EVT with parameter 'cong' equal to false is received. This function must be called after an connection between initiator and acceptor has been established. Parameters handle -- [in] The connection handle. len -- [in] The length of the data written. p_data -- [in] The data written. handle -- [in] The connection handle. len -- [in] The length of the data written. p_data -- [in] The data written. handle -- [in] The connection handle. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters handle -- [in] The connection handle. len -- [in] The length of the data written. p_data -- [in] The data written. Returns ESP_OK: success other: failed esp_err_t esp_spp_vfs_register(void) This function is used to register VFS. For now, SPP only supports write, read and close. When the operation is completed, the callback function will be called with ESP_SPP_VFS_REGISTER_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit(). Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Returns ESP_OK: success other: failed esp_err_t esp_spp_vfs_unregister(void) This function is used to unregister VFS. When the operation is completed, the callback function will be called with ESP_SPP_VFS_UNREGISTER_EVT. This function must be called after esp_spp_vfs_register() successful and before esp_spp_deinit(). Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Returns ESP_OK: success other: failed Unions union esp_spp_cb_param_t #include <esp_spp_api.h> SPP callback parameters union. Public Members struct esp_spp_cb_param_t::spp_init_evt_param init SPP callback param of SPP_INIT_EVT struct esp_spp_cb_param_t::spp_init_evt_param init SPP callback param of SPP_INIT_EVT struct esp_spp_cb_param_t::spp_uninit_evt_param uninit SPP callback param of SPP_UNINIT_EVT struct esp_spp_cb_param_t::spp_uninit_evt_param uninit SPP callback param of SPP_UNINIT_EVT struct esp_spp_cb_param_t::spp_discovery_comp_evt_param disc_comp SPP callback param of SPP_DISCOVERY_COMP_EVT struct esp_spp_cb_param_t::spp_discovery_comp_evt_param disc_comp SPP callback param of SPP_DISCOVERY_COMP_EVT struct esp_spp_cb_param_t::spp_open_evt_param open SPP callback param of ESP_SPP_OPEN_EVT struct esp_spp_cb_param_t::spp_open_evt_param open SPP callback param of ESP_SPP_OPEN_EVT struct esp_spp_cb_param_t::spp_srv_open_evt_param srv_open SPP callback param of ESP_SPP_SRV_OPEN_EVT struct esp_spp_cb_param_t::spp_srv_open_evt_param srv_open SPP callback param of ESP_SPP_SRV_OPEN_EVT struct esp_spp_cb_param_t::spp_close_evt_param close SPP callback param of ESP_SPP_CLOSE_EVT struct esp_spp_cb_param_t::spp_close_evt_param close SPP callback param of ESP_SPP_CLOSE_EVT struct esp_spp_cb_param_t::spp_start_evt_param start SPP callback param of ESP_SPP_START_EVT struct esp_spp_cb_param_t::spp_start_evt_param start SPP callback param of ESP_SPP_START_EVT struct esp_spp_cb_param_t::spp_srv_stop_evt_param srv_stop SPP callback param of ESP_SPP_SRV_STOP_EVT struct esp_spp_cb_param_t::spp_srv_stop_evt_param srv_stop SPP callback param of ESP_SPP_SRV_STOP_EVT struct esp_spp_cb_param_t::spp_cl_init_evt_param cl_init SPP callback param of ESP_SPP_CL_INIT_EVT struct esp_spp_cb_param_t::spp_cl_init_evt_param cl_init SPP callback param of ESP_SPP_CL_INIT_EVT struct esp_spp_cb_param_t::spp_write_evt_param write SPP callback param of ESP_SPP_WRITE_EVT struct esp_spp_cb_param_t::spp_write_evt_param write SPP callback param of ESP_SPP_WRITE_EVT struct esp_spp_cb_param_t::spp_data_ind_evt_param data_ind SPP callback param of ESP_SPP_DATA_IND_EVT struct esp_spp_cb_param_t::spp_data_ind_evt_param data_ind SPP callback param of ESP_SPP_DATA_IND_EVT struct esp_spp_cb_param_t::spp_cong_evt_param cong SPP callback param of ESP_SPP_CONG_EVT struct esp_spp_cb_param_t::spp_cong_evt_param cong SPP callback param of ESP_SPP_CONG_EVT struct esp_spp_cb_param_t::spp_vfs_register_evt_param vfs_register SPP callback param of ESP_SPP_VFS_REGISTER_EVT struct esp_spp_cb_param_t::spp_vfs_register_evt_param vfs_register SPP callback param of ESP_SPP_VFS_REGISTER_EVT struct esp_spp_cb_param_t::spp_vfs_unregister_evt_param vfs_unregister SPP callback param of ESP_SPP_VFS_UNREGISTER_EVT struct esp_spp_cb_param_t::spp_vfs_unregister_evt_param vfs_unregister SPP callback param of ESP_SPP_VFS_UNREGISTER_EVT struct spp_cl_init_evt_param #include <esp_spp_api.h> ESP_SPP_CL_INIT_EVT. Public Members esp_spp_status_t status status esp_spp_status_t status status uint32_t handle The connection handle uint32_t handle The connection handle uint8_t sec_id security ID used by this server uint8_t sec_id security ID used by this server bool use_co TRUE to use co_rfc_data bool use_co TRUE to use co_rfc_data esp_spp_status_t status struct spp_cl_init_evt_param #include <esp_spp_api.h> ESP_SPP_CL_INIT_EVT. Public Members esp_spp_status_t status status uint32_t handle The connection handle uint8_t sec_id security ID used by this server bool use_co TRUE to use co_rfc_data struct spp_close_evt_param #include <esp_spp_api.h> ESP_SPP_CLOSE_EVT. Public Members esp_spp_status_t status status esp_spp_status_t status status uint32_t port_status PORT status uint32_t port_status PORT status uint32_t handle The connection handle uint32_t handle The connection handle bool async FALSE, if local initiates disconnect bool async FALSE, if local initiates disconnect esp_spp_status_t status struct spp_close_evt_param #include <esp_spp_api.h> ESP_SPP_CLOSE_EVT. Public Members esp_spp_status_t status status uint32_t port_status PORT status uint32_t handle The connection handle bool async FALSE, if local initiates disconnect struct spp_cong_evt_param #include <esp_spp_api.h> ESP_SPP_CONG_EVT. Public Members esp_spp_status_t status status esp_spp_status_t status status uint32_t handle The connection handle uint32_t handle The connection handle bool cong TRUE, congested. FALSE, uncongested bool cong TRUE, congested. FALSE, uncongested esp_spp_status_t status struct spp_cong_evt_param #include <esp_spp_api.h> ESP_SPP_CONG_EVT. Public Members esp_spp_status_t status status uint32_t handle The connection handle bool cong TRUE, congested. FALSE, uncongested struct spp_data_ind_evt_param #include <esp_spp_api.h> ESP_SPP_DATA_IND_EVT. Public Members esp_spp_status_t status status esp_spp_status_t status status uint32_t handle The connection handle uint32_t handle The connection handle uint16_t len The length of data uint16_t len The length of data uint8_t *data The data received uint8_t *data The data received esp_spp_status_t status struct spp_data_ind_evt_param #include <esp_spp_api.h> ESP_SPP_DATA_IND_EVT. Public Members esp_spp_status_t status status uint32_t handle The connection handle uint16_t len The length of data uint8_t *data The data received struct spp_discovery_comp_evt_param #include <esp_spp_api.h> SPP_DISCOVERY_COMP_EVT. Public Members esp_spp_status_t status status esp_spp_status_t status status uint8_t scn_num The num of scn_num uint8_t scn_num The num of scn_num uint8_t scn[ESP_SPP_MAX_SCN] channel # uint8_t scn[ESP_SPP_MAX_SCN] channel # const char *service_name[ESP_SPP_MAX_SCN] service_name const char *service_name[ESP_SPP_MAX_SCN] service_name esp_spp_status_t status struct spp_discovery_comp_evt_param #include <esp_spp_api.h> SPP_DISCOVERY_COMP_EVT. Public Members esp_spp_status_t status status uint8_t scn_num The num of scn_num uint8_t scn[ESP_SPP_MAX_SCN] channel # const char *service_name[ESP_SPP_MAX_SCN] service_name struct spp_init_evt_param #include <esp_spp_api.h> SPP_INIT_EVT. struct spp_init_evt_param #include <esp_spp_api.h> SPP_INIT_EVT. struct spp_open_evt_param #include <esp_spp_api.h> ESP_SPP_OPEN_EVT. Public Members esp_spp_status_t status status esp_spp_status_t status status uint32_t handle The connection handle uint32_t handle The connection handle int fd The file descriptor only for ESP_SPP_MODE_VFS int fd The file descriptor only for ESP_SPP_MODE_VFS esp_bd_addr_t rem_bda The peer address esp_bd_addr_t rem_bda The peer address esp_spp_status_t status struct spp_open_evt_param #include <esp_spp_api.h> ESP_SPP_OPEN_EVT. Public Members esp_spp_status_t status status uint32_t handle The connection handle int fd The file descriptor only for ESP_SPP_MODE_VFS esp_bd_addr_t rem_bda The peer address struct spp_srv_open_evt_param #include <esp_spp_api.h> ESP_SPP_SRV_OPEN_EVT. Public Members esp_spp_status_t status status esp_spp_status_t status status uint32_t handle The connection handle uint32_t handle The connection handle uint32_t new_listen_handle The new listen handle uint32_t new_listen_handle The new listen handle int fd The file descriptor only for ESP_SPP_MODE_VFS int fd The file descriptor only for ESP_SPP_MODE_VFS esp_bd_addr_t rem_bda The peer address esp_bd_addr_t rem_bda The peer address esp_spp_status_t status struct spp_srv_open_evt_param #include <esp_spp_api.h> ESP_SPP_SRV_OPEN_EVT. Public Members esp_spp_status_t status status uint32_t handle The connection handle uint32_t new_listen_handle The new listen handle int fd The file descriptor only for ESP_SPP_MODE_VFS esp_bd_addr_t rem_bda The peer address struct spp_srv_stop_evt_param #include <esp_spp_api.h> ESP_SPP_SRV_STOP_EVT. Public Members esp_spp_status_t status status esp_spp_status_t status status uint8_t scn Server channel number uint8_t scn Server channel number esp_spp_status_t status struct spp_srv_stop_evt_param #include <esp_spp_api.h> ESP_SPP_SRV_STOP_EVT. Public Members esp_spp_status_t status status uint8_t scn Server channel number struct spp_start_evt_param #include <esp_spp_api.h> ESP_SPP_START_EVT. struct spp_start_evt_param #include <esp_spp_api.h> ESP_SPP_START_EVT. struct spp_uninit_evt_param #include <esp_spp_api.h> SPP_UNINIT_EVT. struct spp_uninit_evt_param #include <esp_spp_api.h> SPP_UNINIT_EVT. struct spp_vfs_register_evt_param #include <esp_spp_api.h> ESP_SPP_VFS_REGISTER_EVT. struct spp_vfs_register_evt_param #include <esp_spp_api.h> ESP_SPP_VFS_REGISTER_EVT. struct spp_vfs_unregister_evt_param #include <esp_spp_api.h> ESP_SPP_VFS_UNREGISTER_EVT. struct spp_vfs_unregister_evt_param #include <esp_spp_api.h> ESP_SPP_VFS_UNREGISTER_EVT. struct esp_spp_cb_param_t::spp_init_evt_param init Structures struct esp_spp_cfg_t SPP configuration parameters. Public Members esp_spp_mode_t mode Choose the mode of SPP, ESP_SPP_MODE_CB or ESP_SPP_MODE_VFS. esp_spp_mode_t mode Choose the mode of SPP, ESP_SPP_MODE_CB or ESP_SPP_MODE_VFS. bool enable_l2cap_ertm Enable/disable Logical Link Control and Adaptation Layer Protocol enhanced retransmission mode. bool enable_l2cap_ertm Enable/disable Logical Link Control and Adaptation Layer Protocol enhanced retransmission mode. uint16_t tx_buffer_size Tx buffer size for a new SPP channel. A smaller setting can save memory, but may incur a decrease in throughput. Only for ESP_SPP_MODE_VFS mode. uint16_t tx_buffer_size Tx buffer size for a new SPP channel. A smaller setting can save memory, but may incur a decrease in throughput. Only for ESP_SPP_MODE_VFS mode. esp_spp_mode_t mode Macros ESP_SPP_MAX_MTU SPP max MTU ESP_SPP_MAX_SCN SPP max SCN ESP_SPP_MIN_TX_BUFFER_SIZE SPP min tx buffer ESP_SPP_MAX_TX_BUFFER_SIZE SPP max tx buffer size BT_SPP_DEFAULT_CONFIG() SPP default configuration. ESP_SPP_SEC_NONE No security. relate to BTA_SEC_NONE in bta/bta_api.h ESP_SPP_SEC_AUTHORIZE Authorization required (only needed for out going connection ) relate to BTA_SEC_AUTHORIZE in bta/bta_api.h ESP_SPP_SEC_AUTHENTICATE Authentication required. relate to BTA_SEC_AUTHENTICATE in bta/bta_api.h ESP_SPP_SEC_ENCRYPT Encryption required. relate to BTA_SEC_ENCRYPT in bta/bta_api.h ESP_SPP_SEC_MODE4_LEVEL4 Mode 4 level 4 service, i.e. incoming/outgoing MITM and P-256 encryption relate to BTA_SEC_MODE4_LEVEL4 in bta/bta_api.h ESP_SPP_SEC_MITM Man-In-The_Middle protection relate to BTA_SEC_MITM in bta/bta_api.h ESP_SPP_SEC_IN_16_DIGITS Min 16 digit for pin code relate to BTA_SEC_IN_16_DIGITS in bta/bta_api.h Type Definitions typedef uint16_t esp_spp_sec_t typedef void (*esp_spp_cb_t)(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) SPP callback function type. When handle ESP_SPP_DATA_IND_EVT, it is strongly recommended to cache incoming data, and process them in other lower priority application task rather than in this callback directly. Param event Event type Param param Point to callback parameter, currently is union type Param event Event type Param param Point to callback parameter, currently is union type Enumerations enum esp_spp_status_t Values: enumerator ESP_SPP_SUCCESS Successful operation. enumerator ESP_SPP_SUCCESS Successful operation. enumerator ESP_SPP_FAILURE Generic failure. enumerator ESP_SPP_FAILURE Generic failure. enumerator ESP_SPP_BUSY Temporarily can not handle this request. enumerator ESP_SPP_BUSY Temporarily can not handle this request. enumerator ESP_SPP_NO_DATA No data enumerator ESP_SPP_NO_DATA No data enumerator ESP_SPP_NO_RESOURCE No more resource enumerator ESP_SPP_NO_RESOURCE No more resource enumerator ESP_SPP_NEED_INIT SPP module shall init first enumerator ESP_SPP_NEED_INIT SPP module shall init first enumerator ESP_SPP_NEED_DEINIT SPP module shall deinit first enumerator ESP_SPP_NEED_DEINIT SPP module shall deinit first enumerator ESP_SPP_NO_CONNECTION Connection may have been closed enumerator ESP_SPP_NO_CONNECTION Connection may have been closed enumerator ESP_SPP_NO_SERVER No SPP server enumerator ESP_SPP_NO_SERVER No SPP server enumerator ESP_SPP_SUCCESS enum esp_spp_role_t Values: enumerator ESP_SPP_ROLE_MASTER Role: master enumerator ESP_SPP_ROLE_MASTER Role: master enumerator ESP_SPP_ROLE_SLAVE Role: slave enumerator ESP_SPP_ROLE_SLAVE Role: slave enumerator ESP_SPP_ROLE_MASTER enum esp_spp_mode_t Values: enumerator ESP_SPP_MODE_CB When data is coming, a callback will come with data enumerator ESP_SPP_MODE_CB When data is coming, a callback will come with data enumerator ESP_SPP_MODE_VFS Use VFS to write/read data enumerator ESP_SPP_MODE_VFS Use VFS to write/read data enumerator ESP_SPP_MODE_CB enum esp_spp_cb_event_t SPP callback function events. Values: enumerator ESP_SPP_INIT_EVT When SPP is initialized, the event comes enumerator ESP_SPP_INIT_EVT When SPP is initialized, the event comes enumerator ESP_SPP_UNINIT_EVT When SPP is deinitialized, the event comes enumerator ESP_SPP_UNINIT_EVT When SPP is deinitialized, the event comes enumerator ESP_SPP_DISCOVERY_COMP_EVT When SDP discovery complete, the event comes enumerator ESP_SPP_DISCOVERY_COMP_EVT When SDP discovery complete, the event comes enumerator ESP_SPP_OPEN_EVT When SPP Client connection open, the event comes enumerator ESP_SPP_OPEN_EVT When SPP Client connection open, the event comes enumerator ESP_SPP_CLOSE_EVT When SPP connection closed, the event comes enumerator ESP_SPP_CLOSE_EVT When SPP connection closed, the event comes enumerator ESP_SPP_START_EVT When SPP server started, the event comes enumerator ESP_SPP_START_EVT When SPP server started, the event comes enumerator ESP_SPP_CL_INIT_EVT When SPP client initiated a connection, the event comes enumerator ESP_SPP_CL_INIT_EVT When SPP client initiated a connection, the event comes enumerator ESP_SPP_DATA_IND_EVT When SPP connection received data, the event comes, only for ESP_SPP_MODE_CB enumerator ESP_SPP_DATA_IND_EVT When SPP connection received data, the event comes, only for ESP_SPP_MODE_CB enumerator ESP_SPP_CONG_EVT When SPP connection congestion status changed, the event comes, only for ESP_SPP_MODE_CB enumerator ESP_SPP_CONG_EVT When SPP connection congestion status changed, the event comes, only for ESP_SPP_MODE_CB enumerator ESP_SPP_WRITE_EVT When SPP write operation completes, the event comes, only for ESP_SPP_MODE_CB enumerator ESP_SPP_WRITE_EVT When SPP write operation completes, the event comes, only for ESP_SPP_MODE_CB enumerator ESP_SPP_SRV_OPEN_EVT When SPP Server connection open, the event comes enumerator ESP_SPP_SRV_OPEN_EVT When SPP Server connection open, the event comes enumerator ESP_SPP_SRV_STOP_EVT When SPP server stopped, the event comes enumerator ESP_SPP_SRV_STOP_EVT When SPP server stopped, the event comes enumerator ESP_SPP_VFS_REGISTER_EVT When SPP VFS register, the event comes enumerator ESP_SPP_VFS_REGISTER_EVT When SPP VFS register, the event comes enumerator ESP_SPP_VFS_UNREGISTER_EVT When SPP VFS unregister, the event comes enumerator ESP_SPP_VFS_UNREGISTER_EVT When SPP VFS unregister, the event comes enumerator ESP_SPP_INIT_EVT
SPP API Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the following application: This is a SPP demo. This demo can discover the service, connect, send and recive SPP data bluetooth/bluedroid/classic_bt/bt_spp_acceptor, bluetooth/bluedroid/classic_bt/bt_spp_initiator API Reference Header File This header file can be included with: #include "esp_spp_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_spp_register_callback(esp_spp_cb_t callback) This function is called to init callbacks with SPP module. - Parameters callback -- [in] pointer to the init callback function. - Returns ESP_OK: success other: failed - - esp_err_t esp_spp_init(esp_spp_mode_t mode) This function is called to init SPP module. When the operation is completed, the callback function will be called with ESP_SPP_INIT_EVT. This function should be called after esp_bluedroid_enable() completes successfully. - Parameters mode -- [in] Choose the mode of SPP, ESP_SPP_MODE_CB or ESP_SPP_MODE_VFS. - Returns ESP_OK: success other: failed - - esp_err_t esp_spp_enhanced_init(const esp_spp_cfg_t *cfg) This function is called to init SPP module. When the operation is completed, the callback function will be called with ESP_SPP_INIT_EVT. This function should be called after esp_bluedroid_enable() completes successfully. Note The member variable enable_l2cap_etrm in esp_spp_cfg_t can affect all L2CAP channel configurations of the upper layer RFCOMM protocol. - Parameters cfg -- [in] SPP configuration. - Returns ESP_OK: success other: failed - - esp_err_t esp_spp_deinit(void) This function is called to uninit SPP module. The operation will close all active SPP connection first, then the callback function will be called with ESP_SPP_CLOSE_EVT, and the number of ESP_SPP_CLOSE_EVT is equal to the number of connection. When the operation is completed, the callback function will be called with ESP_SPP_UNINIT_EVT. This function should be called after esp_spp_init()/esp_spp_enhanced_init() completes successfully. - Returns ESP_OK: success other: failed - - esp_err_t esp_spp_start_discovery(esp_bd_addr_t bd_addr) This function is called to performs service discovery for the services provided by the given peer device. When the operation is completed, the callback function will be called with ESP_SPP_DISCOVERY_COMP_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit(). - Parameters bd_addr -- [in] Remote device bluetooth device address. - Returns ESP_OK: success other: failed - - esp_err_t esp_spp_connect(esp_spp_sec_t sec_mask, esp_spp_role_t role, uint8_t remote_scn, esp_bd_addr_t peer_bd_addr) This function makes an SPP connection to a remote BD Address. When the connection is initiated or failed to initiate, the callback is called with ESP_SPP_CL_INIT_EVT. When the connection is established or failed, the callback is called with ESP_SPP_OPEN_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit(). - Parameters sec_mask -- [in] Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE, ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only. role -- [in] Master or slave. remote_scn -- [in] Remote device bluetooth device SCN. peer_bd_addr -- [in] Remote device bluetooth device address. - - Returns ESP_OK: success other: failed - - esp_err_t esp_spp_disconnect(uint32_t handle) This function closes an SPP connection. When the operation is completed, the callback function will be called with ESP_SPP_CLOSE_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit(). - Parameters handle -- [in] The connection handle. - Returns ESP_OK: success other: failed - - esp_err_t esp_spp_start_srv(esp_spp_sec_t sec_mask, esp_spp_role_t role, uint8_t local_scn, const char *name) This function create a SPP server and starts listening for an SPP connection request from a remote Bluetooth device. When the server is started successfully, the callback is called with ESP_SPP_START_EVT. When the connection is established, the callback is called with ESP_SPP_SRV_OPEN_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit(). - Parameters sec_mask -- [in] Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE, ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only. role -- [in] Master or slave. local_scn -- [in] The specific channel you want to get. If channel is 0, means get any channel. name -- [in] Server's name. - - Returns ESP_OK: success other: failed - - esp_err_t esp_spp_stop_srv(void) This function stops all SPP servers. The operation will close all active SPP connection first, then the callback function will be called with ESP_SPP_CLOSE_EVT, and the number of ESP_SPP_CLOSE_EVT is equal to the number of connection. When the operation is completed, the callback is called with ESP_SPP_SRV_STOP_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit(). - Returns ESP_OK: success other: failed - - esp_err_t esp_spp_stop_srv_scn(uint8_t scn) This function stops a specific SPP server. The operation will close all active SPP connection first on the specific SPP server, then the callback function will be called with ESP_SPP_CLOSE_EVT, and the number of ESP_SPP_CLOSE_EVT is equal to the number of connection. When the operation is completed, the callback is called with ESP_SPP_SRV_STOP_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit(). - Parameters scn -- [in] Server channel number. - Returns ESP_OK: success other: failed - - esp_err_t esp_spp_write(uint32_t handle, int len, uint8_t *p_data) This function is used to write data, only for ESP_SPP_MODE_CB. When this function need to be called repeatedly, it is strongly recommended to call this function again after the previous event ESP_SPP_WRITE_EVT is received and the parameter 'cong' is equal to false. If the previous event ESP_SPP_WRITE_EVT with parameter 'cong' is equal to true, the function can only be called again when the event ESP_SPP_CONG_EVT with parameter 'cong' equal to false is received. This function must be called after an connection between initiator and acceptor has been established. - Parameters handle -- [in] The connection handle. len -- [in] The length of the data written. p_data -- [in] The data written. - - Returns ESP_OK: success other: failed - - esp_err_t esp_spp_vfs_register(void) This function is used to register VFS. For now, SPP only supports write, read and close. When the operation is completed, the callback function will be called with ESP_SPP_VFS_REGISTER_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit(). - Returns ESP_OK: success other: failed - - esp_err_t esp_spp_vfs_unregister(void) This function is used to unregister VFS. When the operation is completed, the callback function will be called with ESP_SPP_VFS_UNREGISTER_EVT. This function must be called after esp_spp_vfs_register() successful and before esp_spp_deinit(). - Returns ESP_OK: success other: failed - Unions - union esp_spp_cb_param_t - #include <esp_spp_api.h> SPP callback parameters union. Public Members - struct esp_spp_cb_param_t::spp_init_evt_param init SPP callback param of SPP_INIT_EVT - struct esp_spp_cb_param_t::spp_uninit_evt_param uninit SPP callback param of SPP_UNINIT_EVT - struct esp_spp_cb_param_t::spp_discovery_comp_evt_param disc_comp SPP callback param of SPP_DISCOVERY_COMP_EVT - struct esp_spp_cb_param_t::spp_open_evt_param open SPP callback param of ESP_SPP_OPEN_EVT - struct esp_spp_cb_param_t::spp_srv_open_evt_param srv_open SPP callback param of ESP_SPP_SRV_OPEN_EVT - struct esp_spp_cb_param_t::spp_close_evt_param close SPP callback param of ESP_SPP_CLOSE_EVT - struct esp_spp_cb_param_t::spp_start_evt_param start SPP callback param of ESP_SPP_START_EVT - struct esp_spp_cb_param_t::spp_srv_stop_evt_param srv_stop SPP callback param of ESP_SPP_SRV_STOP_EVT - struct esp_spp_cb_param_t::spp_cl_init_evt_param cl_init SPP callback param of ESP_SPP_CL_INIT_EVT - struct esp_spp_cb_param_t::spp_write_evt_param write SPP callback param of ESP_SPP_WRITE_EVT - struct esp_spp_cb_param_t::spp_data_ind_evt_param data_ind SPP callback param of ESP_SPP_DATA_IND_EVT - struct esp_spp_cb_param_t::spp_cong_evt_param cong SPP callback param of ESP_SPP_CONG_EVT - struct esp_spp_cb_param_t::spp_vfs_register_evt_param vfs_register SPP callback param of ESP_SPP_VFS_REGISTER_EVT - struct esp_spp_cb_param_t::spp_vfs_unregister_evt_param vfs_unregister SPP callback param of ESP_SPP_VFS_UNREGISTER_EVT - struct spp_cl_init_evt_param - #include <esp_spp_api.h> ESP_SPP_CL_INIT_EVT. Public Members - esp_spp_status_t status status - uint32_t handle The connection handle - uint8_t sec_id security ID used by this server - bool use_co TRUE to use co_rfc_data - esp_spp_status_t status - struct spp_close_evt_param - #include <esp_spp_api.h> ESP_SPP_CLOSE_EVT. Public Members - esp_spp_status_t status status - uint32_t port_status PORT status - uint32_t handle The connection handle - bool async FALSE, if local initiates disconnect - esp_spp_status_t status - struct spp_cong_evt_param - #include <esp_spp_api.h> ESP_SPP_CONG_EVT. Public Members - esp_spp_status_t status status - uint32_t handle The connection handle - bool cong TRUE, congested. FALSE, uncongested - esp_spp_status_t status - struct spp_data_ind_evt_param - #include <esp_spp_api.h> ESP_SPP_DATA_IND_EVT. Public Members - esp_spp_status_t status status - uint32_t handle The connection handle - uint16_t len The length of data - uint8_t *data The data received - esp_spp_status_t status - struct spp_discovery_comp_evt_param - #include <esp_spp_api.h> SPP_DISCOVERY_COMP_EVT. Public Members - esp_spp_status_t status status - uint8_t scn_num The num of scn_num - uint8_t scn[ESP_SPP_MAX_SCN] channel # - const char *service_name[ESP_SPP_MAX_SCN] service_name - esp_spp_status_t status - struct spp_init_evt_param - #include <esp_spp_api.h> SPP_INIT_EVT. - struct spp_open_evt_param - #include <esp_spp_api.h> ESP_SPP_OPEN_EVT. Public Members - esp_spp_status_t status status - uint32_t handle The connection handle - int fd The file descriptor only for ESP_SPP_MODE_VFS - esp_bd_addr_t rem_bda The peer address - esp_spp_status_t status - struct spp_srv_open_evt_param - #include <esp_spp_api.h> ESP_SPP_SRV_OPEN_EVT. Public Members - esp_spp_status_t status status - uint32_t handle The connection handle - uint32_t new_listen_handle The new listen handle - int fd The file descriptor only for ESP_SPP_MODE_VFS - esp_bd_addr_t rem_bda The peer address - esp_spp_status_t status - struct spp_srv_stop_evt_param - #include <esp_spp_api.h> ESP_SPP_SRV_STOP_EVT. Public Members - esp_spp_status_t status status - uint8_t scn Server channel number - esp_spp_status_t status - struct spp_start_evt_param - #include <esp_spp_api.h> ESP_SPP_START_EVT. - struct spp_uninit_evt_param - #include <esp_spp_api.h> SPP_UNINIT_EVT. - struct spp_vfs_register_evt_param - #include <esp_spp_api.h> ESP_SPP_VFS_REGISTER_EVT. - struct spp_vfs_unregister_evt_param - #include <esp_spp_api.h> ESP_SPP_VFS_UNREGISTER_EVT. - struct esp_spp_cb_param_t::spp_init_evt_param init Structures - struct esp_spp_cfg_t SPP configuration parameters. Public Members - esp_spp_mode_t mode Choose the mode of SPP, ESP_SPP_MODE_CB or ESP_SPP_MODE_VFS. - bool enable_l2cap_ertm Enable/disable Logical Link Control and Adaptation Layer Protocol enhanced retransmission mode. - uint16_t tx_buffer_size Tx buffer size for a new SPP channel. A smaller setting can save memory, but may incur a decrease in throughput. Only for ESP_SPP_MODE_VFS mode. - esp_spp_mode_t mode Macros - ESP_SPP_MAX_MTU SPP max MTU - ESP_SPP_MAX_SCN SPP max SCN - ESP_SPP_MIN_TX_BUFFER_SIZE SPP min tx buffer - ESP_SPP_MAX_TX_BUFFER_SIZE SPP max tx buffer size - BT_SPP_DEFAULT_CONFIG() SPP default configuration. - ESP_SPP_SEC_NONE No security. relate to BTA_SEC_NONE in bta/bta_api.h - ESP_SPP_SEC_AUTHORIZE Authorization required (only needed for out going connection ) relate to BTA_SEC_AUTHORIZE in bta/bta_api.h - ESP_SPP_SEC_AUTHENTICATE Authentication required. relate to BTA_SEC_AUTHENTICATE in bta/bta_api.h - ESP_SPP_SEC_ENCRYPT Encryption required. relate to BTA_SEC_ENCRYPT in bta/bta_api.h - ESP_SPP_SEC_MODE4_LEVEL4 Mode 4 level 4 service, i.e. incoming/outgoing MITM and P-256 encryption relate to BTA_SEC_MODE4_LEVEL4 in bta/bta_api.h - ESP_SPP_SEC_MITM Man-In-The_Middle protection relate to BTA_SEC_MITM in bta/bta_api.h - ESP_SPP_SEC_IN_16_DIGITS Min 16 digit for pin code relate to BTA_SEC_IN_16_DIGITS in bta/bta_api.h Type Definitions - typedef uint16_t esp_spp_sec_t - typedef void (*esp_spp_cb_t)(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) SPP callback function type. When handle ESP_SPP_DATA_IND_EVT, it is strongly recommended to cache incoming data, and process them in other lower priority application task rather than in this callback directly. - Param event Event type - Param param Point to callback parameter, currently is union type Enumerations - enum esp_spp_status_t Values: - enumerator ESP_SPP_SUCCESS Successful operation. - enumerator ESP_SPP_FAILURE Generic failure. - enumerator ESP_SPP_BUSY Temporarily can not handle this request. - enumerator ESP_SPP_NO_DATA No data - enumerator ESP_SPP_NO_RESOURCE No more resource - enumerator ESP_SPP_NEED_INIT SPP module shall init first - enumerator ESP_SPP_NEED_DEINIT SPP module shall deinit first - enumerator ESP_SPP_NO_CONNECTION Connection may have been closed - enumerator ESP_SPP_NO_SERVER No SPP server - enumerator ESP_SPP_SUCCESS - enum esp_spp_role_t Values: - enumerator ESP_SPP_ROLE_MASTER Role: master - enumerator ESP_SPP_ROLE_SLAVE Role: slave - enumerator ESP_SPP_ROLE_MASTER - enum esp_spp_mode_t Values: - enumerator ESP_SPP_MODE_CB When data is coming, a callback will come with data - enumerator ESP_SPP_MODE_VFS Use VFS to write/read data - enumerator ESP_SPP_MODE_CB - enum esp_spp_cb_event_t SPP callback function events. Values: - enumerator ESP_SPP_INIT_EVT When SPP is initialized, the event comes - enumerator ESP_SPP_UNINIT_EVT When SPP is deinitialized, the event comes - enumerator ESP_SPP_DISCOVERY_COMP_EVT When SDP discovery complete, the event comes - enumerator ESP_SPP_OPEN_EVT When SPP Client connection open, the event comes - enumerator ESP_SPP_CLOSE_EVT When SPP connection closed, the event comes - enumerator ESP_SPP_START_EVT When SPP server started, the event comes - enumerator ESP_SPP_CL_INIT_EVT When SPP client initiated a connection, the event comes - enumerator ESP_SPP_DATA_IND_EVT When SPP connection received data, the event comes, only for ESP_SPP_MODE_CB - enumerator ESP_SPP_CONG_EVT When SPP connection congestion status changed, the event comes, only for ESP_SPP_MODE_CB - enumerator ESP_SPP_WRITE_EVT When SPP write operation completes, the event comes, only for ESP_SPP_MODE_CB - enumerator ESP_SPP_SRV_OPEN_EVT When SPP Server connection open, the event comes - enumerator ESP_SPP_SRV_STOP_EVT When SPP server stopped, the event comes - enumerator ESP_SPP_VFS_REGISTER_EVT When SPP VFS register, the event comes - enumerator ESP_SPP_VFS_UNREGISTER_EVT When SPP VFS unregister, the event comes - enumerator ESP_SPP_INIT_EVT
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_spp.html
ESP-IDF Programming Guide v5.2.1 documentation
null
HFP Defines
null
espressif.com
2016-01-01
758f3be2c2aa841
null
null
HFP Defines API Reference Header File This header file can be included with: #include "esp_hf_defs.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Enumerations enum esp_hf_in_band_ring_state_t in-band ring tone state Values: enumerator ESP_HF_IN_BAND_RINGTONE_NOT_PROVIDED enumerator ESP_HF_IN_BAND_RINGTONE_NOT_PROVIDED enumerator ESP_HF_IN_BAND_RINGTONE_PROVIDED enumerator ESP_HF_IN_BAND_RINGTONE_PROVIDED enumerator ESP_HF_IN_BAND_RINGTONE_NOT_PROVIDED enum esp_hf_vr_state_t voice recognition state Values: enumerator ESP_HF_VR_STATE_DISABLED voice recognition disabled enumerator ESP_HF_VR_STATE_DISABLED voice recognition disabled enumerator ESP_HF_VR_STATE_ENABLED voice recognition enabled enumerator ESP_HF_VR_STATE_ENABLED voice recognition enabled enumerator ESP_HF_VR_STATE_DISABLED enum esp_hf_volume_control_target_t Bluetooth HFP audio volume control target. Values: enumerator ESP_HF_VOLUME_CONTROL_TARGET_SPK speaker enumerator ESP_HF_VOLUME_CONTROL_TARGET_SPK speaker enumerator ESP_HF_VOLUME_CONTROL_TARGET_MIC microphone enumerator ESP_HF_VOLUME_CONTROL_TARGET_MIC microphone enumerator ESP_HF_VOLUME_CONTROL_TARGET_SPK enum esp_hf_audio_state_t Bluetooth HFP audio connection status. Values: enumerator ESP_HF_AUDIO_STATE_DISCONNECTED audio connection released enumerator ESP_HF_AUDIO_STATE_DISCONNECTED audio connection released enumerator ESP_HF_AUDIO_STATE_CONNECTING audio connection has been initiated enumerator ESP_HF_AUDIO_STATE_CONNECTING audio connection has been initiated enumerator ESP_HF_AUDIO_STATE_CONNECTED audio connection is established enumerator ESP_HF_AUDIO_STATE_CONNECTED audio connection is established enumerator ESP_HF_AUDIO_STATE_CONNECTED_MSBC mSBC audio connection is established enumerator ESP_HF_AUDIO_STATE_CONNECTED_MSBC mSBC audio connection is established enumerator ESP_HF_AUDIO_STATE_DISCONNECTED enum esp_hf_volume_type_t Values: enumerator ESP_HF_VOLUME_TYPE_SPK enumerator ESP_HF_VOLUME_TYPE_SPK enumerator ESP_HF_VOLUME_TYPE_MIC enumerator ESP_HF_VOLUME_TYPE_MIC enumerator ESP_HF_VOLUME_TYPE_SPK enum esp_hf_network_state_t +CIND network service availability status Values: enumerator ESP_HF_NETWORK_STATE_NOT_AVAILABLE enumerator ESP_HF_NETWORK_STATE_NOT_AVAILABLE enumerator ESP_HF_NETWORK_STATE_AVAILABLE enumerator ESP_HF_NETWORK_STATE_AVAILABLE enumerator ESP_HF_NETWORK_STATE_NOT_AVAILABLE enum esp_hf_ciev_report_type_t +CIEV report type Values: enumerator ESP_HF_IND_TYPE_CALL position of call indicator enumerator ESP_HF_IND_TYPE_CALL position of call indicator enumerator ESP_HF_IND_TYPE_CALLSETUP position of callsetup indicator enumerator ESP_HF_IND_TYPE_CALLSETUP position of callsetup indicator enumerator ESP_HF_IND_TYPE_SERVICE position of service indicator enumerator ESP_HF_IND_TYPE_SERVICE position of service indicator enumerator ESP_HF_IND_TYPE_SIGNAL position of signal strength indicator, range: 0-5 enumerator ESP_HF_IND_TYPE_SIGNAL position of signal strength indicator, range: 0-5 enumerator ESP_HF_IND_TYPE_ROAM position of roaming indicator enumerator ESP_HF_IND_TYPE_ROAM position of roaming indicator enumerator ESP_HF_IND_TYPE_BATTCHG position of battery charge indicator, range: 0-5 enumerator ESP_HF_IND_TYPE_BATTCHG position of battery charge indicator, range: 0-5 enumerator ESP_HF_IND_TYPE_CALLHELD position of callheld indicator enumerator ESP_HF_IND_TYPE_CALLHELD position of callheld indicator enumerator ESP_HF_IND_TYPE_CALL enum esp_hf_service_type_t +CIEV Service type Values: enumerator ESP_HF_SERVICE_TYPE_HOME enumerator ESP_HF_SERVICE_TYPE_HOME enumerator ESP_HF_SERVICE_TYPE_ROAMING enumerator ESP_HF_SERVICE_TYPE_ROAMING enumerator ESP_HF_SERVICE_TYPE_HOME enum esp_hf_call_status_t +CIND call status indicator values Values: enumerator ESP_HF_CALL_STATUS_NO_CALLS no call in progress enumerator ESP_HF_CALL_STATUS_NO_CALLS no call in progress enumerator ESP_HF_CALL_STATUS_CALL_IN_PROGRESS call is present(active or held) enumerator ESP_HF_CALL_STATUS_CALL_IN_PROGRESS call is present(active or held) enumerator ESP_HF_CALL_STATUS_NO_CALLS enum esp_hf_call_setup_status_t +CIND call setup status indicator values Values: enumerator ESP_HF_CALL_SETUP_STATUS_IDLE no call setup in progress enumerator ESP_HF_CALL_SETUP_STATUS_IDLE no call setup in progress enumerator ESP_HF_CALL_SETUP_STATUS_INCOMING incoming call setup in progress enumerator ESP_HF_CALL_SETUP_STATUS_INCOMING incoming call setup in progress enumerator ESP_HF_CALL_SETUP_STATUS_OUTGOING_DIALING outgoing call setup in dialing state enumerator ESP_HF_CALL_SETUP_STATUS_OUTGOING_DIALING outgoing call setup in dialing state enumerator ESP_HF_CALL_SETUP_STATUS_OUTGOING_ALERTING outgoing call setup in alerting state enumerator ESP_HF_CALL_SETUP_STATUS_OUTGOING_ALERTING outgoing call setup in alerting state enumerator ESP_HF_CALL_SETUP_STATUS_IDLE enum esp_hf_roaming_status_t +CIND roaming status indicator values Values: enumerator ESP_HF_ROAMING_STATUS_INACTIVE roaming is not active enumerator ESP_HF_ROAMING_STATUS_INACTIVE roaming is not active enumerator ESP_HF_ROAMING_STATUS_ACTIVE a roaming is active enumerator ESP_HF_ROAMING_STATUS_ACTIVE a roaming is active enumerator ESP_HF_ROAMING_STATUS_INACTIVE enum esp_hf_call_held_status_t +CIND call held indicator values Values: enumerator ESP_HF_CALL_HELD_STATUS_NONE no calls held enumerator ESP_HF_CALL_HELD_STATUS_NONE no calls held enumerator ESP_HF_CALL_HELD_STATUS_HELD_AND_ACTIVE both active and held call enumerator ESP_HF_CALL_HELD_STATUS_HELD_AND_ACTIVE both active and held call enumerator ESP_HF_CALL_HELD_STATUS_HELD call on hold, no active call enumerator ESP_HF_CALL_HELD_STATUS_HELD call on hold, no active call enumerator ESP_HF_CALL_HELD_STATUS_NONE enum esp_hf_current_call_status_t +CLCC status of the call Values: enumerator ESP_HF_CURRENT_CALL_STATUS_ACTIVE active enumerator ESP_HF_CURRENT_CALL_STATUS_ACTIVE active enumerator ESP_HF_CURRENT_CALL_STATUS_HELD held enumerator ESP_HF_CURRENT_CALL_STATUS_HELD held enumerator ESP_HF_CURRENT_CALL_STATUS_DIALING dialing (outgoing calls only) enumerator ESP_HF_CURRENT_CALL_STATUS_DIALING dialing (outgoing calls only) enumerator ESP_HF_CURRENT_CALL_STATUS_ALERTING alerting (outgoing calls only) enumerator ESP_HF_CURRENT_CALL_STATUS_ALERTING alerting (outgoing calls only) enumerator ESP_HF_CURRENT_CALL_STATUS_INCOMING incoming (incoming calls only) enumerator ESP_HF_CURRENT_CALL_STATUS_INCOMING incoming (incoming calls only) enumerator ESP_HF_CURRENT_CALL_STATUS_WAITING waiting (incoming calls only) enumerator ESP_HF_CURRENT_CALL_STATUS_WAITING waiting (incoming calls only) enumerator ESP_HF_CURRENT_CALL_STATUS_HELD_BY_RESP_HOLD call held by response and hold enumerator ESP_HF_CURRENT_CALL_STATUS_HELD_BY_RESP_HOLD call held by response and hold enumerator ESP_HF_CURRENT_CALL_STATUS_ACTIVE enum esp_hf_current_call_direction_t +CLCC direction of the call Values: enumerator ESP_HF_CURRENT_CALL_DIRECTION_OUTGOING outgoing enumerator ESP_HF_CURRENT_CALL_DIRECTION_OUTGOING outgoing enumerator ESP_HF_CURRENT_CALL_DIRECTION_INCOMING incoming enumerator ESP_HF_CURRENT_CALL_DIRECTION_INCOMING incoming enumerator ESP_HF_CURRENT_CALL_DIRECTION_OUTGOING enum esp_hf_current_call_mpty_type_t +CLCC multi-party call flag Values: enumerator ESP_HF_CURRENT_CALL_MPTY_TYPE_SINGLE not a member of a multi-party call enumerator ESP_HF_CURRENT_CALL_MPTY_TYPE_SINGLE not a member of a multi-party call enumerator ESP_HF_CURRENT_CALL_MPTY_TYPE_MULTI member of a multi-party call enumerator ESP_HF_CURRENT_CALL_MPTY_TYPE_MULTI member of a multi-party call enumerator ESP_HF_CURRENT_CALL_MPTY_TYPE_SINGLE enum esp_hf_current_call_mode_t +CLCC call mode Values: enumerator ESP_HF_CURRENT_CALL_MODE_VOICE enumerator ESP_HF_CURRENT_CALL_MODE_VOICE enumerator ESP_HF_CURRENT_CALL_MODE_DATA enumerator ESP_HF_CURRENT_CALL_MODE_DATA enumerator ESP_HF_CURRENT_CALL_MODE_FAX enumerator ESP_HF_CURRENT_CALL_MODE_FAX enumerator ESP_HF_CURRENT_CALL_MODE_VOICE enum esp_hf_call_addr_type_t +CLCC address type Values: enumerator ESP_HF_CALL_ADDR_TYPE_UNKNOWN unkown address type enumerator ESP_HF_CALL_ADDR_TYPE_UNKNOWN unkown address type enumerator ESP_HF_CALL_ADDR_TYPE_INTERNATIONAL international address enumerator ESP_HF_CALL_ADDR_TYPE_INTERNATIONAL international address enumerator ESP_HF_CALL_ADDR_TYPE_UNKNOWN enum esp_hf_subscriber_service_type_t +CNUM service type of the phone number Values: enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_UNKNOWN unknown enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_UNKNOWN unknown enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_VOICE voice service enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_VOICE voice service enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_FAX fax service enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_FAX fax service enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_UNKNOWN enum esp_hf_btrh_status_t +BTRH response and hold result code Values: enumerator ESP_HF_BTRH_STATUS_HELD incoming call is put on held in AG enumerator ESP_HF_BTRH_STATUS_HELD incoming call is put on held in AG enumerator ESP_HF_BTRH_STATUS_ACCEPTED held incoming call is accepted in AG enumerator ESP_HF_BTRH_STATUS_ACCEPTED held incoming call is accepted in AG enumerator ESP_HF_BTRH_STATUS_REJECTED held incoming call is rejected in AG enumerator ESP_HF_BTRH_STATUS_REJECTED held incoming call is rejected in AG enumerator ESP_HF_BTRH_STATUS_HELD enum esp_hf_btrh_cmd_t AT+BTRH response and hold action code. Values: enumerator ESP_HF_BTRH_CMD_HOLD put the incoming call on hold enumerator ESP_HF_BTRH_CMD_HOLD put the incoming call on hold enumerator ESP_HF_BTRH_CMD_ACCEPT accept a held incoming call enumerator ESP_HF_BTRH_CMD_ACCEPT accept a held incoming call enumerator ESP_HF_BTRH_CMD_REJECT reject a held incoming call enumerator ESP_HF_BTRH_CMD_REJECT reject a held incoming call enumerator ESP_HF_BTRH_CMD_HOLD enum esp_hf_call_waiting_status_t +CCWA resposne status Values: enumerator ESP_HF_CALL_WAITING_INACTIVE enumerator ESP_HF_CALL_WAITING_INACTIVE enumerator ESP_HF_CALL_WAITING_ACTIVE enumerator ESP_HF_CALL_WAITING_ACTIVE enumerator ESP_HF_CALL_WAITING_INACTIVE enum esp_hf_wbs_config_t Values: enumerator ESP_HF_WBS_NONE enumerator ESP_HF_WBS_NONE enumerator ESP_HF_WBS_NO enumerator ESP_HF_WBS_NO enumerator ESP_HF_WBS_YES enumerator ESP_HF_WBS_YES enumerator ESP_HF_WBS_NONE enum esp_hf_connection_state_t Bluetooth HFP RFCOMM connection and service level connection status. Values: enumerator ESP_HF_CONNECTION_STATE_DISCONNECTED RFCOMM data link channel released enumerator ESP_HF_CONNECTION_STATE_DISCONNECTED RFCOMM data link channel released enumerator ESP_HF_CONNECTION_STATE_CONNECTING connecting remote device on the RFCOMM data link enumerator ESP_HF_CONNECTION_STATE_CONNECTING connecting remote device on the RFCOMM data link enumerator ESP_HF_CONNECTION_STATE_CONNECTED RFCOMM connection established enumerator ESP_HF_CONNECTION_STATE_CONNECTED RFCOMM connection established enumerator ESP_HF_CONNECTION_STATE_SLC_CONNECTED service level connection established enumerator ESP_HF_CONNECTION_STATE_SLC_CONNECTED service level connection established enumerator ESP_HF_CONNECTION_STATE_DISCONNECTING disconnecting with remote device on the RFCOMM data link enumerator ESP_HF_CONNECTION_STATE_DISCONNECTING disconnecting with remote device on the RFCOMM data link enumerator ESP_HF_CONNECTION_STATE_DISCONNECTED enum esp_hf_chld_type_t AT+CHLD command values. Values: enumerator ESP_HF_CHLD_TYPE_REL <0>, Terminate all held or set UDUB("busy") to a waiting call enumerator ESP_HF_CHLD_TYPE_REL <0>, Terminate all held or set UDUB("busy") to a waiting call enumerator ESP_HF_CHLD_TYPE_REL_ACC <1>, Terminate all active calls and accepts a waiting/held call enumerator ESP_HF_CHLD_TYPE_REL_ACC <1>, Terminate all active calls and accepts a waiting/held call enumerator ESP_HF_CHLD_TYPE_HOLD_ACC <2>, Hold all active calls and accepts a waiting/held call enumerator ESP_HF_CHLD_TYPE_HOLD_ACC <2>, Hold all active calls and accepts a waiting/held call enumerator ESP_HF_CHLD_TYPE_MERGE <3>, Add all held calls to a conference enumerator ESP_HF_CHLD_TYPE_MERGE <3>, Add all held calls to a conference enumerator ESP_HF_CHLD_TYPE_MERGE_DETACH <4>, connect the two calls and disconnects the subscriber from both calls enumerator ESP_HF_CHLD_TYPE_MERGE_DETACH <4>, connect the two calls and disconnects the subscriber from both calls enumerator ESP_HF_CHLD_TYPE_REL_X <1x>, releases specified calls only enumerator ESP_HF_CHLD_TYPE_REL_X <1x>, releases specified calls only enumerator ESP_HF_CHLD_TYPE_PRIV_X <2x>, request private consultation mode with specified call enumerator ESP_HF_CHLD_TYPE_PRIV_X <2x>, request private consultation mode with specified call enumerator ESP_HF_CHLD_TYPE_REL enum esp_hf_at_response_code_t Values: enumerator ESP_HF_AT_RESPONSE_CODE_OK acknowledges execution of a command line enumerator ESP_HF_AT_RESPONSE_CODE_OK acknowledges execution of a command line enumerator ESP_HF_AT_RESPONSE_CODE_ERR command not accepted enumerator ESP_HF_AT_RESPONSE_CODE_ERR command not accepted enumerator ESP_HF_AT_RESPONSE_CODE_NO_CARRIER connection terminated enumerator ESP_HF_AT_RESPONSE_CODE_NO_CARRIER connection terminated enumerator ESP_HF_AT_RESPONSE_CODE_BUSY busy signal detected enumerator ESP_HF_AT_RESPONSE_CODE_BUSY busy signal detected enumerator ESP_HF_AT_RESPONSE_CODE_NO_ANSWER connection completion timeout enumerator ESP_HF_AT_RESPONSE_CODE_NO_ANSWER connection completion timeout enumerator ESP_HF_AT_RESPONSE_CODE_DELAYED delayed enumerator ESP_HF_AT_RESPONSE_CODE_DELAYED delayed enumerator ESP_HF_AT_RESPONSE_CODE_BLACKLISTED blacklisted enumerator ESP_HF_AT_RESPONSE_CODE_BLACKLISTED blacklisted enumerator ESP_HF_AT_RESPONSE_CODE_CME CME error enumerator ESP_HF_AT_RESPONSE_CODE_CME CME error enumerator ESP_HF_AT_RESPONSE_CODE_OK enum esp_hf_at_response_t Values: enumerator ESP_HF_AT_RESPONSE_ERROR enumerator ESP_HF_AT_RESPONSE_ERROR enumerator ESP_HF_AT_RESPONSE_OK enumerator ESP_HF_AT_RESPONSE_OK enumerator ESP_HF_AT_RESPONSE_ERROR enum esp_hf_cme_err_t Extended Audio Gateway Error Result Code Response. Values: enumerator ESP_HF_CME_AG_FAILURE ag failure enumerator ESP_HF_CME_AG_FAILURE ag failure enumerator ESP_HF_CME_NO_CONNECTION_TO_PHONE no connection to phone enumerator ESP_HF_CME_NO_CONNECTION_TO_PHONE no connection to phone enumerator ESP_HF_CME_OPERATION_NOT_ALLOWED operation not allowed enumerator ESP_HF_CME_OPERATION_NOT_ALLOWED operation not allowed enumerator ESP_HF_CME_OPERATION_NOT_SUPPORTED operation not supported enumerator ESP_HF_CME_OPERATION_NOT_SUPPORTED operation not supported enumerator ESP_HF_CME_PH_SIM_PIN_REQUIRED PH-SIM PIN Required enumerator ESP_HF_CME_PH_SIM_PIN_REQUIRED PH-SIM PIN Required enumerator ESP_HF_CME_SIM_NOT_INSERTED SIM not inserted enumerator ESP_HF_CME_SIM_NOT_INSERTED SIM not inserted enumerator ESP_HF_CME_SIM_PIN_REQUIRED SIM PIN required enumerator ESP_HF_CME_SIM_PIN_REQUIRED SIM PIN required enumerator ESP_HF_CME_SIM_PUK_REQUIRED SIM PUK required enumerator ESP_HF_CME_SIM_PUK_REQUIRED SIM PUK required enumerator ESP_HF_CME_SIM_FAILURE SIM failure enumerator ESP_HF_CME_SIM_FAILURE SIM failure enumerator ESP_HF_CME_SIM_BUSY SIM busy enumerator ESP_HF_CME_SIM_BUSY SIM busy enumerator ESP_HF_CME_INCORRECT_PASSWORD incorrect password enumerator ESP_HF_CME_INCORRECT_PASSWORD incorrect password enumerator ESP_HF_CME_SIM_PIN2_REQUIRED SIM PIN2 required enumerator ESP_HF_CME_SIM_PIN2_REQUIRED SIM PIN2 required enumerator ESP_HF_CME_SIM_PUK2_REQUIRED SIM PUK2 required enumerator ESP_HF_CME_SIM_PUK2_REQUIRED SIM PUK2 required enumerator ESP_HF_CME_MEMORY_FULL memory full enumerator ESP_HF_CME_MEMORY_FULL memory full enumerator ESP_HF_CME_INVALID_INDEX invalid index enumerator ESP_HF_CME_INVALID_INDEX invalid index enumerator ESP_HF_CME_MEMORY_FAILURE memory failure enumerator ESP_HF_CME_MEMORY_FAILURE memory failure enumerator ESP_HF_CME_TEXT_STRING_TOO_LONG test string too long enumerator ESP_HF_CME_TEXT_STRING_TOO_LONG test string too long enumerator ESP_HF_CME_INVALID_CHARACTERS_IN_TEXT_STRING invalid characters in text string enumerator ESP_HF_CME_INVALID_CHARACTERS_IN_TEXT_STRING invalid characters in text string enumerator ESP_HF_CME_DIAL_STRING_TOO_LONG dial string too long enumerator ESP_HF_CME_DIAL_STRING_TOO_LONG dial string too long enumerator ESP_HF_CME_INVALID_CHARACTERS_IN_DIAL_STRING invalid characters in dial string enumerator ESP_HF_CME_INVALID_CHARACTERS_IN_DIAL_STRING invalid characters in dial string enumerator ESP_HF_CME_NO_NETWORK_SERVICE no network service enumerator ESP_HF_CME_NO_NETWORK_SERVICE no network service enumerator ESP_HF_CME_NETWORK_TIMEOUT network timeout enumerator ESP_HF_CME_NETWORK_TIMEOUT network timeout enumerator ESP_HF_CME_NETWORK_NOT_ALLOWED network not allowed –emergency calls only enumerator ESP_HF_CME_NETWORK_NOT_ALLOWED network not allowed –emergency calls only enumerator ESP_HF_CME_AG_FAILURE
HFP Defines API Reference Header File This header file can be included with: #include "esp_hf_defs.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Enumerations - enum esp_hf_in_band_ring_state_t in-band ring tone state Values: - enumerator ESP_HF_IN_BAND_RINGTONE_NOT_PROVIDED - enumerator ESP_HF_IN_BAND_RINGTONE_PROVIDED - enumerator ESP_HF_IN_BAND_RINGTONE_NOT_PROVIDED - enum esp_hf_vr_state_t voice recognition state Values: - enumerator ESP_HF_VR_STATE_DISABLED voice recognition disabled - enumerator ESP_HF_VR_STATE_ENABLED voice recognition enabled - enumerator ESP_HF_VR_STATE_DISABLED - enum esp_hf_volume_control_target_t Bluetooth HFP audio volume control target. Values: - enumerator ESP_HF_VOLUME_CONTROL_TARGET_SPK speaker - enumerator ESP_HF_VOLUME_CONTROL_TARGET_MIC microphone - enumerator ESP_HF_VOLUME_CONTROL_TARGET_SPK - enum esp_hf_audio_state_t Bluetooth HFP audio connection status. Values: - enumerator ESP_HF_AUDIO_STATE_DISCONNECTED audio connection released - enumerator ESP_HF_AUDIO_STATE_CONNECTING audio connection has been initiated - enumerator ESP_HF_AUDIO_STATE_CONNECTED audio connection is established - enumerator ESP_HF_AUDIO_STATE_CONNECTED_MSBC mSBC audio connection is established - enumerator ESP_HF_AUDIO_STATE_DISCONNECTED - enum esp_hf_volume_type_t Values: - enumerator ESP_HF_VOLUME_TYPE_SPK - enumerator ESP_HF_VOLUME_TYPE_MIC - enumerator ESP_HF_VOLUME_TYPE_SPK - enum esp_hf_network_state_t +CIND network service availability status Values: - enumerator ESP_HF_NETWORK_STATE_NOT_AVAILABLE - enumerator ESP_HF_NETWORK_STATE_AVAILABLE - enumerator ESP_HF_NETWORK_STATE_NOT_AVAILABLE - enum esp_hf_ciev_report_type_t +CIEV report type Values: - enumerator ESP_HF_IND_TYPE_CALL position of call indicator - enumerator ESP_HF_IND_TYPE_CALLSETUP position of callsetup indicator - enumerator ESP_HF_IND_TYPE_SERVICE position of service indicator - enumerator ESP_HF_IND_TYPE_SIGNAL position of signal strength indicator, range: 0-5 - enumerator ESP_HF_IND_TYPE_ROAM position of roaming indicator - enumerator ESP_HF_IND_TYPE_BATTCHG position of battery charge indicator, range: 0-5 - enumerator ESP_HF_IND_TYPE_CALLHELD position of callheld indicator - enumerator ESP_HF_IND_TYPE_CALL - enum esp_hf_service_type_t +CIEV Service type Values: - enumerator ESP_HF_SERVICE_TYPE_HOME - enumerator ESP_HF_SERVICE_TYPE_ROAMING - enumerator ESP_HF_SERVICE_TYPE_HOME - enum esp_hf_call_status_t +CIND call status indicator values Values: - enumerator ESP_HF_CALL_STATUS_NO_CALLS no call in progress - enumerator ESP_HF_CALL_STATUS_CALL_IN_PROGRESS call is present(active or held) - enumerator ESP_HF_CALL_STATUS_NO_CALLS - enum esp_hf_call_setup_status_t +CIND call setup status indicator values Values: - enumerator ESP_HF_CALL_SETUP_STATUS_IDLE no call setup in progress - enumerator ESP_HF_CALL_SETUP_STATUS_INCOMING incoming call setup in progress - enumerator ESP_HF_CALL_SETUP_STATUS_OUTGOING_DIALING outgoing call setup in dialing state - enumerator ESP_HF_CALL_SETUP_STATUS_OUTGOING_ALERTING outgoing call setup in alerting state - enumerator ESP_HF_CALL_SETUP_STATUS_IDLE - enum esp_hf_roaming_status_t +CIND roaming status indicator values Values: - enumerator ESP_HF_ROAMING_STATUS_INACTIVE roaming is not active - enumerator ESP_HF_ROAMING_STATUS_ACTIVE a roaming is active - enumerator ESP_HF_ROAMING_STATUS_INACTIVE - enum esp_hf_call_held_status_t +CIND call held indicator values Values: - enumerator ESP_HF_CALL_HELD_STATUS_NONE no calls held - enumerator ESP_HF_CALL_HELD_STATUS_HELD_AND_ACTIVE both active and held call - enumerator ESP_HF_CALL_HELD_STATUS_HELD call on hold, no active call - enumerator ESP_HF_CALL_HELD_STATUS_NONE - enum esp_hf_current_call_status_t +CLCC status of the call Values: - enumerator ESP_HF_CURRENT_CALL_STATUS_ACTIVE active - enumerator ESP_HF_CURRENT_CALL_STATUS_HELD held - enumerator ESP_HF_CURRENT_CALL_STATUS_DIALING dialing (outgoing calls only) - enumerator ESP_HF_CURRENT_CALL_STATUS_ALERTING alerting (outgoing calls only) - enumerator ESP_HF_CURRENT_CALL_STATUS_INCOMING incoming (incoming calls only) - enumerator ESP_HF_CURRENT_CALL_STATUS_WAITING waiting (incoming calls only) - enumerator ESP_HF_CURRENT_CALL_STATUS_HELD_BY_RESP_HOLD call held by response and hold - enumerator ESP_HF_CURRENT_CALL_STATUS_ACTIVE - enum esp_hf_current_call_direction_t +CLCC direction of the call Values: - enumerator ESP_HF_CURRENT_CALL_DIRECTION_OUTGOING outgoing - enumerator ESP_HF_CURRENT_CALL_DIRECTION_INCOMING incoming - enumerator ESP_HF_CURRENT_CALL_DIRECTION_OUTGOING - enum esp_hf_current_call_mpty_type_t +CLCC multi-party call flag Values: - enumerator ESP_HF_CURRENT_CALL_MPTY_TYPE_SINGLE not a member of a multi-party call - enumerator ESP_HF_CURRENT_CALL_MPTY_TYPE_MULTI member of a multi-party call - enumerator ESP_HF_CURRENT_CALL_MPTY_TYPE_SINGLE - enum esp_hf_current_call_mode_t +CLCC call mode Values: - enumerator ESP_HF_CURRENT_CALL_MODE_VOICE - enumerator ESP_HF_CURRENT_CALL_MODE_DATA - enumerator ESP_HF_CURRENT_CALL_MODE_FAX - enumerator ESP_HF_CURRENT_CALL_MODE_VOICE - enum esp_hf_call_addr_type_t +CLCC address type Values: - enumerator ESP_HF_CALL_ADDR_TYPE_UNKNOWN unkown address type - enumerator ESP_HF_CALL_ADDR_TYPE_INTERNATIONAL international address - enumerator ESP_HF_CALL_ADDR_TYPE_UNKNOWN - enum esp_hf_subscriber_service_type_t +CNUM service type of the phone number Values: - enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_UNKNOWN unknown - enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_VOICE voice service - enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_FAX fax service - enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_UNKNOWN - enum esp_hf_btrh_status_t +BTRH response and hold result code Values: - enumerator ESP_HF_BTRH_STATUS_HELD incoming call is put on held in AG - enumerator ESP_HF_BTRH_STATUS_ACCEPTED held incoming call is accepted in AG - enumerator ESP_HF_BTRH_STATUS_REJECTED held incoming call is rejected in AG - enumerator ESP_HF_BTRH_STATUS_HELD - enum esp_hf_btrh_cmd_t AT+BTRH response and hold action code. Values: - enumerator ESP_HF_BTRH_CMD_HOLD put the incoming call on hold - enumerator ESP_HF_BTRH_CMD_ACCEPT accept a held incoming call - enumerator ESP_HF_BTRH_CMD_REJECT reject a held incoming call - enumerator ESP_HF_BTRH_CMD_HOLD - enum esp_hf_call_waiting_status_t +CCWA resposne status Values: - enumerator ESP_HF_CALL_WAITING_INACTIVE - enumerator ESP_HF_CALL_WAITING_ACTIVE - enumerator ESP_HF_CALL_WAITING_INACTIVE - enum esp_hf_wbs_config_t Values: - enumerator ESP_HF_WBS_NONE - enumerator ESP_HF_WBS_NO - enumerator ESP_HF_WBS_YES - enumerator ESP_HF_WBS_NONE - enum esp_hf_connection_state_t Bluetooth HFP RFCOMM connection and service level connection status. Values: - enumerator ESP_HF_CONNECTION_STATE_DISCONNECTED RFCOMM data link channel released - enumerator ESP_HF_CONNECTION_STATE_CONNECTING connecting remote device on the RFCOMM data link - enumerator ESP_HF_CONNECTION_STATE_CONNECTED RFCOMM connection established - enumerator ESP_HF_CONNECTION_STATE_SLC_CONNECTED service level connection established - enumerator ESP_HF_CONNECTION_STATE_DISCONNECTING disconnecting with remote device on the RFCOMM data link - enumerator ESP_HF_CONNECTION_STATE_DISCONNECTED - enum esp_hf_chld_type_t AT+CHLD command values. Values: - enumerator ESP_HF_CHLD_TYPE_REL <0>, Terminate all held or set UDUB("busy") to a waiting call - enumerator ESP_HF_CHLD_TYPE_REL_ACC <1>, Terminate all active calls and accepts a waiting/held call - enumerator ESP_HF_CHLD_TYPE_HOLD_ACC <2>, Hold all active calls and accepts a waiting/held call - enumerator ESP_HF_CHLD_TYPE_MERGE <3>, Add all held calls to a conference - enumerator ESP_HF_CHLD_TYPE_MERGE_DETACH <4>, connect the two calls and disconnects the subscriber from both calls - enumerator ESP_HF_CHLD_TYPE_REL_X <1x>, releases specified calls only - enumerator ESP_HF_CHLD_TYPE_PRIV_X <2x>, request private consultation mode with specified call - enumerator ESP_HF_CHLD_TYPE_REL - enum esp_hf_at_response_code_t Values: - enumerator ESP_HF_AT_RESPONSE_CODE_OK acknowledges execution of a command line - enumerator ESP_HF_AT_RESPONSE_CODE_ERR command not accepted - enumerator ESP_HF_AT_RESPONSE_CODE_NO_CARRIER connection terminated - enumerator ESP_HF_AT_RESPONSE_CODE_BUSY busy signal detected - enumerator ESP_HF_AT_RESPONSE_CODE_NO_ANSWER connection completion timeout - enumerator ESP_HF_AT_RESPONSE_CODE_DELAYED delayed - enumerator ESP_HF_AT_RESPONSE_CODE_BLACKLISTED blacklisted - enumerator ESP_HF_AT_RESPONSE_CODE_CME CME error - enumerator ESP_HF_AT_RESPONSE_CODE_OK - enum esp_hf_at_response_t Values: - enumerator ESP_HF_AT_RESPONSE_ERROR - enumerator ESP_HF_AT_RESPONSE_OK - enumerator ESP_HF_AT_RESPONSE_ERROR - enum esp_hf_cme_err_t Extended Audio Gateway Error Result Code Response. Values: - enumerator ESP_HF_CME_AG_FAILURE ag failure - enumerator ESP_HF_CME_NO_CONNECTION_TO_PHONE no connection to phone - enumerator ESP_HF_CME_OPERATION_NOT_ALLOWED operation not allowed - enumerator ESP_HF_CME_OPERATION_NOT_SUPPORTED operation not supported - enumerator ESP_HF_CME_PH_SIM_PIN_REQUIRED PH-SIM PIN Required - enumerator ESP_HF_CME_SIM_NOT_INSERTED SIM not inserted - enumerator ESP_HF_CME_SIM_PIN_REQUIRED SIM PIN required - enumerator ESP_HF_CME_SIM_PUK_REQUIRED SIM PUK required - enumerator ESP_HF_CME_SIM_FAILURE SIM failure - enumerator ESP_HF_CME_SIM_BUSY SIM busy - enumerator ESP_HF_CME_INCORRECT_PASSWORD incorrect password - enumerator ESP_HF_CME_SIM_PIN2_REQUIRED SIM PIN2 required - enumerator ESP_HF_CME_SIM_PUK2_REQUIRED SIM PUK2 required - enumerator ESP_HF_CME_MEMORY_FULL memory full - enumerator ESP_HF_CME_INVALID_INDEX invalid index - enumerator ESP_HF_CME_MEMORY_FAILURE memory failure - enumerator ESP_HF_CME_TEXT_STRING_TOO_LONG test string too long - enumerator ESP_HF_CME_INVALID_CHARACTERS_IN_TEXT_STRING invalid characters in text string - enumerator ESP_HF_CME_DIAL_STRING_TOO_LONG dial string too long - enumerator ESP_HF_CME_INVALID_CHARACTERS_IN_DIAL_STRING invalid characters in dial string - enumerator ESP_HF_CME_NO_NETWORK_SERVICE no network service - enumerator ESP_HF_CME_NETWORK_TIMEOUT network timeout - enumerator ESP_HF_CME_NETWORK_NOT_ALLOWED network not allowed –emergency calls only - enumerator ESP_HF_CME_AG_FAILURE
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_hf_defs.html
ESP-IDF Programming Guide v5.2.1 documentation
null
HFP Client API
null
espressif.com
2016-01-01
2451445c6a229a51
null
null
HFP Client API API Reference Header File components/bt/host/bluedroid/api/include/api/esp_hf_client_api.h This header file can be included with: #include "esp_hf_client_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_hf_client_register_callback(esp_hf_client_cb_t callback) Register application callback function to HFP client module. This function should be called only after esp_bluedroid_enable() completes successfully. Parameters callback -- [in] HFP client event callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer ESP_OK: success Parameters callback -- [in] HFP client event callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer esp_err_t esp_hf_client_init(void) Initialize the bluetooth HFP client module. This function should be called after esp_bluedroid_enable() completes successfully. Returns ESP_OK: if the initialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the initialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the initialization request is sent successfully Returns ESP_OK: if the initialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_deinit(void) De-initialize for HFP client module. This function should be called only after esp_bluedroid_enable() completes successfully. Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_connect(esp_bd_addr_t remote_bda) Establish a Service Level Connection to remote bluetooth HFP audio gateway(AG) device. This function must be called after esp_hf_client_init() and before esp_hf_client_deinit(). Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: connect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: connect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: connect request is sent to lower layer Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: connect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_disconnect(esp_bd_addr_t remote_bda) Disconnect from the remote HFP audio gateway. This function must be called after esp_hf_client_init() and before esp_hf_client_deinit(). Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: disconnect request is sent to lower layer Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_connect_audio(esp_bd_addr_t remote_bda) Create audio connection with remote HFP AG. As a precondition to use this API, Service Level Connection shall exist with AG. Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: connect audio request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: connect audio request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: connect audio request is sent to lower layer Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: connect audio request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_disconnect_audio(esp_bd_addr_t remote_bda) Release the established audio connection with remote HFP AG. As a precondition to use this API, Service Level Connection shall exist with AG. Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: disconnect audio request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: disconnect audio request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: disconnect audio request is sent to lower layer Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: disconnect audio request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_start_voice_recognition(void) Enable voice recognition in the AG. As a precondition to use this API, Service Level Connection shall exist with AG. Returns ESP_OK: starting voice recognition is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: starting voice recognition is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: starting voice recognition is sent to lower layer Returns ESP_OK: starting voice recognition is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_stop_voice_recognition(void) Disable voice recognition in the AG. As a precondition to use this API, Service Level Connection shall exist with AG. Returns ESP_OK: stoping voice recognition is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: stoping voice recognition is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: stoping voice recognition is sent to lower layer Returns ESP_OK: stoping voice recognition is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_volume_update(esp_hf_volume_control_target_t type, int volume) Volume synchronization with AG. As a precondition to use this API, Service Level Connection shall exist with AG. Parameters type -- [in] volume control target, speaker or microphone volume -- [in] gain of the speaker of microphone, ranges 0 to 15 type -- [in] volume control target, speaker or microphone volume -- [in] gain of the speaker of microphone, ranges 0 to 15 type -- [in] volume control target, speaker or microphone Returns ESP_OK: volume update is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: volume update is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: volume update is sent to lower layer Parameters type -- [in] volume control target, speaker or microphone volume -- [in] gain of the speaker of microphone, ranges 0 to 15 Returns ESP_OK: volume update is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_dial(const char *number) Place a call with a specified number, if number is NULL, last called number is called. As a precondition to use this API, Service Level Connection shall exist with AG. Parameters number -- [in] number string of the call. If NULL, the last number is called(aka re-dial) Returns ESP_OK: a call placing is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: a call placing is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: a call placing is sent to lower layer Parameters number -- [in] number string of the call. If NULL, the last number is called(aka re-dial) Returns ESP_OK: a call placing is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_dial_memory(int location) Place a call with number specified by location(speed dial). As a precondition to use this API, Service Level Connection shall exist with AG. Parameters location -- [in] location of the number in the memory Returns ESP_OK: a memory call placing is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: a memory call placing is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: a memory call placing is sent to lower layer Parameters location -- [in] location of the number in the memory Returns ESP_OK: a memory call placing is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_send_chld_cmd(esp_hf_chld_type_t chld, int idx) Send call hold and multiparty commands, or enhanced call control commands(Use AT+CHLD). As a precondition to use this API, Service Level Connection shall exist with AG. Parameters chld -- [in] AT+CHLD call hold and multiparty handling AT command. idx -- [in] used in Enhanced Call Control Mechanisms, used if chld is ESP_HF_CHLD_TYPE_REL_X or ESP_HF_CHLD_TYPE_PRIV_X chld -- [in] AT+CHLD call hold and multiparty handling AT command. idx -- [in] used in Enhanced Call Control Mechanisms, used if chld is ESP_HF_CHLD_TYPE_REL_X or ESP_HF_CHLD_TYPE_PRIV_X chld -- [in] AT+CHLD call hold and multiparty handling AT command. Returns ESP_OK: command AT+CHLD is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: command AT+CHLD is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: command AT+CHLD is sent to lower layer Parameters chld -- [in] AT+CHLD call hold and multiparty handling AT command. idx -- [in] used in Enhanced Call Control Mechanisms, used if chld is ESP_HF_CHLD_TYPE_REL_X or ESP_HF_CHLD_TYPE_PRIV_X Returns ESP_OK: command AT+CHLD is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_send_btrh_cmd(esp_hf_btrh_cmd_t btrh) Send response and hold action command(Send AT+BTRH command) As a precondition to use this API, Service Level Connection shall exist with AG. Parameters btrh -- [in] response and hold action to send Returns ESP_OK: command AT+BTRH is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: command AT+BTRH is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: command AT+BTRH is sent to lower layer Parameters btrh -- [in] response and hold action to send Returns ESP_OK: command AT+BTRH is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_answer_call(void) Answer an incoming call(send ATA command). As a precondition to use this API, Service Level Connection shall exist with AG. Returns ESP_OK: a call answering is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: a call answering is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: a call answering is sent to lower layer Returns ESP_OK: a call answering is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_reject_call(void) Reject an incoming call or terminate an ongoing call(send AT+CHUP command). As a precondition to use this API, Service Level Connection shall exist with AG. Returns ESP_OK: the call rejecting is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: the call rejecting is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: the call rejecting is sent to lower layer Returns ESP_OK: the call rejecting is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_query_current_calls(void) Query list of current calls in AG(send AT+CLCC command). As a precondition to use this API, Service Level Connection shall exist with AG. Returns ESP_OK: query of current calls is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: query of current calls is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: query of current calls is sent to lower layer Returns ESP_OK: query of current calls is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_query_current_operator_name(void) Query the name of currently selected network operator in AG(use AT+COPS commands). As a precondition to use this API, Service Level Connection shall exist with AG. Returns ESP_OK: query of current operator name is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: query of current operator name is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: query of current operator name is sent to lower layer Returns ESP_OK: query of current operator name is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_retrieve_subscriber_info(void) Get subscriber information number from AG(send AT+CNUM command) As a precondition to use this API, Service Level Connection shall exist with AG. Returns ESP_OK: the retrieving of subscriber information is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: the retrieving of subscriber information is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: the retrieving of subscriber information is sent to lower layer Returns ESP_OK: the retrieving of subscriber information is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_send_dtmf(char code) Transmit DTMF codes during an ongoing call(use AT+VTS commands) As a precondition to use this API, Service Level Connection shall exist with AG. Parameters code -- [in] dtmf code, single ascii character in the set 0-9, #, *, A-D Returns ESP_OK: the DTMF codes are sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: the DTMF codes are sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: the DTMF codes are sent to lower layer Parameters code -- [in] dtmf code, single ascii character in the set 0-9, #, *, A-D Returns ESP_OK: the DTMF codes are sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_send_xapl(char *information, uint32_t features) Send command to enable Vendor specific feature to indicate battery level and docker status This is Apple-specific commands, but used by most device, including Android and Windows. Parameters information -- [in] XAPL vendorID-productID-version, such as "0505-1995-0610" vendorID: A string representation of the hex value of the vendor ID from the manufacturer, without the 0x prefix. productID: A string representation of the hex value of the product ID from the manufacturer, without the 0x prefix. version: The revision of the software features -- [in] A base-10 representation of a bit field. such as ESP_HF_CLIENT_XAPL_FEAT_BATTERY_REPORT information -- [in] XAPL vendorID-productID-version, such as "0505-1995-0610" vendorID: A string representation of the hex value of the vendor ID from the manufacturer, without the 0x prefix. productID: A string representation of the hex value of the product ID from the manufacturer, without the 0x prefix. version: The revision of the software features -- [in] A base-10 representation of a bit field. such as ESP_HF_CLIENT_XAPL_FEAT_BATTERY_REPORT information -- [in] XAPL vendorID-productID-version, such as "0505-1995-0610" vendorID: A string representation of the hex value of the vendor ID from the manufacturer, without the 0x prefix. productID: A string representation of the hex value of the product ID from the manufacturer, without the 0x prefix. version: The revision of the software Returns ESP_OK: Feature enable request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: Feature enable request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: Feature enable request is sent to lower layer Parameters information -- [in] XAPL vendorID-productID-version, such as "0505-1995-0610" vendorID: A string representation of the hex value of the vendor ID from the manufacturer, without the 0x prefix. productID: A string representation of the hex value of the product ID from the manufacturer, without the 0x prefix. version: The revision of the software features -- [in] A base-10 representation of a bit field. such as ESP_HF_CLIENT_XAPL_FEAT_BATTERY_REPORT Returns ESP_OK: Feature enable request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_send_iphoneaccev(uint32_t bat_level, bool docked) Send Battery level and docker status Enable this feature using XAPL command first This is Apple-specific commands, but used by most device, including Android and Windows. Parameters bat_level -- [in] Battery Level: value between 0 and 9 docked -- [in] Dock State: false = undocked, true = docked bat_level -- [in] Battery Level: value between 0 and 9 docked -- [in] Dock State: false = undocked, true = docked bat_level -- [in] Battery Level: value between 0 and 9 Returns ESP_OK: battery level is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: battery level is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: battery level is sent to lower layer Parameters bat_level -- [in] Battery Level: value between 0 and 9 docked -- [in] Dock State: false = undocked, true = docked Returns ESP_OK: battery level is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_request_last_voice_tag_number(void) Request a phone number from AG corresponding to last voice tag recorded (send AT+BINP command). As a precondition to use this API, Service Level Connection shall exist with AG. Returns ESP_OK: the phone number request corresponding to last voice tag recorded is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: the phone number request corresponding to last voice tag recorded is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: the phone number request corresponding to last voice tag recorded is sent to lower layer Returns ESP_OK: the phone number request corresponding to last voice tag recorded is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_send_nrec(void) Disable echo cancellation and noise reduction in the AG (use AT+NREC=0 command). As a precondition to use this API, Service Level Connection shall exist with AG. Returns ESP_OK: NREC=0 request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: NREC=0 request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: NREC=0 request is sent to lower layer Returns ESP_OK: NREC=0 request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_client_register_data_callback(esp_hf_client_incoming_data_cb_t recv, esp_hf_client_outgoing_data_cb_t send) Register HFP client data output function; the callback is only used in the case that Voice Over HCI is enabled. Parameters recv -- [in] HFP client incoming data callback function send -- [in] HFP client outgoing data callback function recv -- [in] HFP client incoming data callback function send -- [in] HFP client outgoing data callback function recv -- [in] HFP client incoming data callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer ESP_OK: success Parameters recv -- [in] HFP client incoming data callback function send -- [in] HFP client outgoing data callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer esp_err_t esp_hf_client_pkt_stat_nums_get(uint16_t sync_conn_handle) Get the number of packets received and sent This function is only used in the case that Voice Over HCI is enabled and the audio state is connected. When the operation is completed, the callback function will be called with ESP_HF_CLIENT_PKT_STAT_NUMS_GET_EVT. Parameters sync_conn_handle -- [in] the (e)SCO connection handle Returns ESP_OK: if the request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the request is sent successfully Parameters sync_conn_handle -- [in] the (e)SCO connection handle Returns ESP_OK: if the request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others void esp_hf_client_outgoing_data_ready(void) Trigger the lower-layer to fetch and send audio data. This function is only only used in the case that Voice Over HCI is enabled. After this function is called, lower layer will invoke esp_hf_client_outgoing_data_cb_t to fetch data. As a precondition to use this API, Service Level Connection shall exist with AG. void esp_hf_client_pcm_resample_init(uint32_t src_sps, uint32_t bits, uint32_t channels) Initialize the down sampling converter. This is a utility function that can only be used in the case that Voice Over HCI is enabled. Parameters src_sps -- [in] original samples per second(source audio data, i.e. 48000, 32000, 16000, 44100, 22050, 11025) bits -- [in] number of bits per pcm sample (16) channels -- [in] number of channels (i.e. mono(1), stereo(2)...) src_sps -- [in] original samples per second(source audio data, i.e. 48000, 32000, 16000, 44100, 22050, 11025) bits -- [in] number of bits per pcm sample (16) channels -- [in] number of channels (i.e. mono(1), stereo(2)...) src_sps -- [in] original samples per second(source audio data, i.e. 48000, 32000, 16000, 44100, 22050, 11025) Parameters src_sps -- [in] original samples per second(source audio data, i.e. 48000, 32000, 16000, 44100, 22050, 11025) bits -- [in] number of bits per pcm sample (16) channels -- [in] number of channels (i.e. mono(1), stereo(2)...) void esp_hf_client_pcm_resample_deinit(void) Deinitialize the down sampling converter. int32_t esp_hf_client_pcm_resample(void *src, uint32_t in_bytes, void *dst) Down sampling utility to convert high sampling rate into 8K/16bits 1-channel mode PCM samples. This can only be used in the case that Voice Over HCI is enabled. Parameters src -- [in] pointer to the buffer where the original sampling PCM are stored in_bytes -- [in] length of the input PCM sample buffer in byte dst -- [in] pointer to the buffer which is to be used to store the converted PCM samples src -- [in] pointer to the buffer where the original sampling PCM are stored in_bytes -- [in] length of the input PCM sample buffer in byte dst -- [in] pointer to the buffer which is to be used to store the converted PCM samples src -- [in] pointer to the buffer where the original sampling PCM are stored Returns number of samples converted Parameters src -- [in] pointer to the buffer where the original sampling PCM are stored in_bytes -- [in] length of the input PCM sample buffer in byte dst -- [in] pointer to the buffer which is to be used to store the converted PCM samples Returns number of samples converted Unions union esp_hf_client_cb_param_t #include <esp_hf_client_api.h> HFP client callback parameters. Public Members struct esp_hf_client_cb_param_t::hf_client_conn_stat_param conn_stat HF callback param of ESP_HF_CLIENT_CONNECTION_STATE_EVT struct esp_hf_client_cb_param_t::hf_client_conn_stat_param conn_stat HF callback param of ESP_HF_CLIENT_CONNECTION_STATE_EVT struct esp_hf_client_cb_param_t::hf_client_audio_stat_param audio_stat HF callback param of ESP_HF_CLIENT_AUDIO_STATE_EVT struct esp_hf_client_cb_param_t::hf_client_audio_stat_param audio_stat HF callback param of ESP_HF_CLIENT_AUDIO_STATE_EVT struct esp_hf_client_cb_param_t::hf_client_bvra_param bvra HF callback param of ESP_HF_CLIENT_BVRA_EVT struct esp_hf_client_cb_param_t::hf_client_bvra_param bvra HF callback param of ESP_HF_CLIENT_BVRA_EVT struct esp_hf_client_cb_param_t::hf_client_service_availability_param service_availability HF callback param of ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT struct esp_hf_client_cb_param_t::hf_client_service_availability_param service_availability HF callback param of ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT struct esp_hf_client_cb_param_t::hf_client_network_roaming_param roaming HF callback param of ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT struct esp_hf_client_cb_param_t::hf_client_network_roaming_param roaming HF callback param of ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT struct esp_hf_client_cb_param_t::hf_client_signal_strength_ind_param signal_strength HF callback param of ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT struct esp_hf_client_cb_param_t::hf_client_signal_strength_ind_param signal_strength HF callback param of ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT struct esp_hf_client_cb_param_t::hf_client_battery_level_ind_param battery_level HF callback param of ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT struct esp_hf_client_cb_param_t::hf_client_battery_level_ind_param battery_level HF callback param of ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT struct esp_hf_client_cb_param_t::hf_client_current_operator_param cops HF callback param of ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT struct esp_hf_client_cb_param_t::hf_client_current_operator_param cops HF callback param of ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT struct esp_hf_client_cb_param_t::hf_client_call_ind_param call HF callback param of ESP_HF_CLIENT_CIND_CALL_EVT struct esp_hf_client_cb_param_t::hf_client_call_ind_param call HF callback param of ESP_HF_CLIENT_CIND_CALL_EVT struct esp_hf_client_cb_param_t::hf_client_call_setup_ind_param call_setup HF callback param of ESP_HF_CLIENT_BVRA_EVT struct esp_hf_client_cb_param_t::hf_client_call_setup_ind_param call_setup HF callback param of ESP_HF_CLIENT_BVRA_EVT struct esp_hf_client_cb_param_t::hf_client_call_held_ind_param call_held HF callback param of ESP_HF_CLIENT_CIND_CALL_HELD_EVT struct esp_hf_client_cb_param_t::hf_client_call_held_ind_param call_held HF callback param of ESP_HF_CLIENT_CIND_CALL_HELD_EVT struct esp_hf_client_cb_param_t::hf_client_btrh_param btrh HF callback param of ESP_HF_CLIENT_BRTH_EVT struct esp_hf_client_cb_param_t::hf_client_btrh_param btrh HF callback param of ESP_HF_CLIENT_BRTH_EVT struct esp_hf_client_cb_param_t::hf_client_clip_param clip HF callback param of ESP_HF_CLIENT_CLIP_EVT struct esp_hf_client_cb_param_t::hf_client_clip_param clip HF callback param of ESP_HF_CLIENT_CLIP_EVT struct esp_hf_client_cb_param_t::hf_client_ccwa_param ccwa HF callback param of ESP_HF_CLIENT_BVRA_EVT struct esp_hf_client_cb_param_t::hf_client_ccwa_param ccwa HF callback param of ESP_HF_CLIENT_BVRA_EVT struct esp_hf_client_cb_param_t::hf_client_clcc_param clcc HF callback param of ESP_HF_CLIENT_CLCC_EVT struct esp_hf_client_cb_param_t::hf_client_clcc_param clcc HF callback param of ESP_HF_CLIENT_CLCC_EVT struct esp_hf_client_cb_param_t::hf_client_volume_control_param volume_control HF callback param of ESP_HF_CLIENT_VOLUME_CONTROL_EVT struct esp_hf_client_cb_param_t::hf_client_volume_control_param volume_control HF callback param of ESP_HF_CLIENT_VOLUME_CONTROL_EVT struct esp_hf_client_cb_param_t::hf_client_at_response_param at_response HF callback param of ESP_HF_CLIENT_AT_RESPONSE_EVT struct esp_hf_client_cb_param_t::hf_client_at_response_param at_response HF callback param of ESP_HF_CLIENT_AT_RESPONSE_EVT struct esp_hf_client_cb_param_t::hf_client_cnum_param cnum HF callback param of ESP_HF_CLIENT_CNUM_EVT struct esp_hf_client_cb_param_t::hf_client_cnum_param cnum HF callback param of ESP_HF_CLIENT_CNUM_EVT struct esp_hf_client_cb_param_t::hf_client_bsirparam bsir HF callback param of ESP_HF_CLIENT_BSIR_EVT struct esp_hf_client_cb_param_t::hf_client_bsirparam bsir HF callback param of ESP_HF_CLIENT_BSIR_EVT struct esp_hf_client_cb_param_t::hf_client_binp_param binp HF callback param of ESP_HF_CLIENT_BINP_EVT struct esp_hf_client_cb_param_t::hf_client_binp_param binp HF callback param of ESP_HF_CLIENT_BINP_EVT struct esp_hf_client_cb_param_t::hf_client_pkt_status_nums pkt_nums HF callback param of ESP_HF_CLIENT_PKT_STAT_NUMS_GET_EVT struct esp_hf_client_cb_param_t::hf_client_pkt_status_nums pkt_nums HF callback param of ESP_HF_CLIENT_PKT_STAT_NUMS_GET_EVT struct hf_client_at_response_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_AT_RESPONSE_EVT. Public Members esp_hf_at_response_code_t code AT response code esp_hf_at_response_code_t code AT response code esp_hf_cme_err_t cme Extended Audio Gateway Error Result Code esp_hf_cme_err_t cme Extended Audio Gateway Error Result Code esp_hf_at_response_code_t code struct hf_client_at_response_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_AT_RESPONSE_EVT. Public Members esp_hf_at_response_code_t code AT response code esp_hf_cme_err_t cme Extended Audio Gateway Error Result Code struct hf_client_audio_stat_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_AUDIO_STATE_EVT. Public Members esp_hf_client_audio_state_t state audio connection state esp_hf_client_audio_state_t state audio connection state esp_bd_addr_t remote_bda remote bluetooth device address esp_bd_addr_t remote_bda remote bluetooth device address uint16_t sync_conn_handle (e)SCO connection handle uint16_t sync_conn_handle (e)SCO connection handle esp_hf_client_audio_state_t state struct hf_client_audio_stat_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_AUDIO_STATE_EVT. Public Members esp_hf_client_audio_state_t state audio connection state esp_bd_addr_t remote_bda remote bluetooth device address uint16_t sync_conn_handle (e)SCO connection handle struct hf_client_battery_level_ind_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT. Public Members int value battery charge value, ranges from 0 to 5 int value battery charge value, ranges from 0 to 5 int value struct hf_client_battery_level_ind_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT. Public Members int value battery charge value, ranges from 0 to 5 struct hf_client_binp_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_BINP_EVT. Public Members const char *number phone number corresponding to the last voice tag in the HF const char *number phone number corresponding to the last voice tag in the HF const char *number struct hf_client_binp_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_BINP_EVT. Public Members const char *number phone number corresponding to the last voice tag in the HF struct hf_client_bsirparam #include <esp_hf_client_api.h> ESP_HF_CLIENT_BSIR_EVT. Public Members esp_hf_client_in_band_ring_state_t state setting state of in-band ring tone esp_hf_client_in_band_ring_state_t state setting state of in-band ring tone esp_hf_client_in_band_ring_state_t state struct hf_client_bsirparam #include <esp_hf_client_api.h> ESP_HF_CLIENT_BSIR_EVT. Public Members esp_hf_client_in_band_ring_state_t state setting state of in-band ring tone struct hf_client_btrh_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_BTRH_EVT. Public Members esp_hf_btrh_status_t status call hold and response status result code esp_hf_btrh_status_t status call hold and response status result code esp_hf_btrh_status_t status struct hf_client_btrh_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_BTRH_EVT. Public Members esp_hf_btrh_status_t status call hold and response status result code struct hf_client_bvra_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_BVRA_EVT. Public Members esp_hf_vr_state_t value voice recognition state esp_hf_vr_state_t value voice recognition state esp_hf_vr_state_t value struct hf_client_bvra_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_BVRA_EVT. Public Members esp_hf_vr_state_t value voice recognition state struct hf_client_call_held_ind_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_CALL_HELD_EVT. Public Members esp_hf_call_held_status_t status bluetooth proprietary call hold status indicator esp_hf_call_held_status_t status bluetooth proprietary call hold status indicator esp_hf_call_held_status_t status struct hf_client_call_held_ind_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_CALL_HELD_EVT. Public Members esp_hf_call_held_status_t status bluetooth proprietary call hold status indicator struct hf_client_call_ind_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_CALL_EVT. Public Members esp_hf_call_status_t status call status indicator esp_hf_call_status_t status call status indicator esp_hf_call_status_t status struct hf_client_call_ind_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_CALL_EVT. Public Members esp_hf_call_status_t status call status indicator struct hf_client_call_setup_ind_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_CALL_SETUP_EVT. Public Members esp_hf_call_setup_status_t status call setup status indicator esp_hf_call_setup_status_t status call setup status indicator esp_hf_call_setup_status_t status struct hf_client_call_setup_ind_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_CALL_SETUP_EVT. Public Members esp_hf_call_setup_status_t status call setup status indicator struct hf_client_ccwa_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CCWA_EVT. Public Members const char *number phone number string of waiting call const char *number phone number string of waiting call const char *number struct hf_client_ccwa_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CCWA_EVT. Public Members const char *number phone number string of waiting call struct hf_client_clcc_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CLCC_EVT. Public Members int idx numbering(starting with 1) of the call int idx numbering(starting with 1) of the call esp_hf_current_call_direction_t dir direction of the call esp_hf_current_call_direction_t dir direction of the call esp_hf_current_call_status_t status status of the call esp_hf_current_call_status_t status status of the call esp_hf_current_call_mpty_type_t mpty multi-party flag esp_hf_current_call_mpty_type_t mpty multi-party flag char *number phone number(optional) char *number phone number(optional) int idx struct hf_client_clcc_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CLCC_EVT. Public Members int idx numbering(starting with 1) of the call esp_hf_current_call_direction_t dir direction of the call esp_hf_current_call_status_t status status of the call esp_hf_current_call_mpty_type_t mpty multi-party flag char *number phone number(optional) struct hf_client_clip_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CLIP_EVT. Public Members const char *number phone number string of call const char *number phone number string of call const char *number struct hf_client_clip_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CLIP_EVT. Public Members const char *number phone number string of call struct hf_client_cnum_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CNUM_EVT. Public Members const char *number phone number string const char *number phone number string esp_hf_subscriber_service_type_t type service type that the phone number relates to esp_hf_subscriber_service_type_t type service type that the phone number relates to const char *number struct hf_client_cnum_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CNUM_EVT. Public Members const char *number phone number string esp_hf_subscriber_service_type_t type service type that the phone number relates to struct hf_client_conn_stat_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CONNECTION_STATE_EVT. Public Members esp_hf_client_connection_state_t state HF connection state esp_hf_client_connection_state_t state HF connection state uint32_t peer_feat AG supported features uint32_t peer_feat AG supported features uint32_t chld_feat AG supported features on call hold and multiparty services uint32_t chld_feat AG supported features on call hold and multiparty services esp_bd_addr_t remote_bda remote bluetooth device address esp_bd_addr_t remote_bda remote bluetooth device address esp_hf_client_connection_state_t state struct hf_client_conn_stat_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CONNECTION_STATE_EVT. Public Members esp_hf_client_connection_state_t state HF connection state uint32_t peer_feat AG supported features uint32_t chld_feat AG supported features on call hold and multiparty services esp_bd_addr_t remote_bda remote bluetooth device address struct hf_client_current_operator_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT. Public Members const char *name name of the network operator const char *name name of the network operator const char *name struct hf_client_current_operator_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT. Public Members const char *name name of the network operator struct hf_client_network_roaming_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT. Public Members esp_hf_roaming_status_t status roaming status esp_hf_roaming_status_t status roaming status esp_hf_roaming_status_t status struct hf_client_network_roaming_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT. Public Members esp_hf_roaming_status_t status roaming status struct hf_client_pkt_status_nums #include <esp_hf_client_api.h> ESP_HF_CLIENT_PKT_STAT_NUMS_GET_EVT. Public Members uint32_t rx_total the total number of packets received uint32_t rx_total the total number of packets received uint32_t rx_correct the total number of packets data correctly received uint32_t rx_correct the total number of packets data correctly received uint32_t rx_err the total number of packets data with possible invalid uint32_t rx_err the total number of packets data with possible invalid uint32_t rx_none the total number of packets data no received uint32_t rx_none the total number of packets data no received uint32_t rx_lost the total number of packets data partially lost uint32_t rx_lost the total number of packets data partially lost uint32_t tx_total the total number of packets send uint32_t tx_total the total number of packets send uint32_t tx_discarded the total number of packets send lost uint32_t tx_discarded the total number of packets send lost uint32_t rx_total struct hf_client_pkt_status_nums #include <esp_hf_client_api.h> ESP_HF_CLIENT_PKT_STAT_NUMS_GET_EVT. Public Members uint32_t rx_total the total number of packets received uint32_t rx_correct the total number of packets data correctly received uint32_t rx_err the total number of packets data with possible invalid uint32_t rx_none the total number of packets data no received uint32_t rx_lost the total number of packets data partially lost uint32_t tx_total the total number of packets send uint32_t tx_discarded the total number of packets send lost struct hf_client_service_availability_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT. Public Members esp_hf_network_state_t status service availability status esp_hf_network_state_t status service availability status esp_hf_network_state_t status struct hf_client_service_availability_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT. Public Members esp_hf_network_state_t status service availability status struct hf_client_signal_strength_ind_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT. Public Members int value signal strength value, ranges from 0 to 5 int value signal strength value, ranges from 0 to 5 int value struct hf_client_signal_strength_ind_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT. Public Members int value signal strength value, ranges from 0 to 5 struct hf_client_volume_control_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_VOLUME_CONTROL_EVT. Public Members esp_hf_volume_control_target_t type volume control target, speaker or microphone esp_hf_volume_control_target_t type volume control target, speaker or microphone int volume gain, ranges from 0 to 15 int volume gain, ranges from 0 to 15 esp_hf_volume_control_target_t type struct hf_client_volume_control_param #include <esp_hf_client_api.h> ESP_HF_CLIENT_VOLUME_CONTROL_EVT. Public Members esp_hf_volume_control_target_t type volume control target, speaker or microphone int volume gain, ranges from 0 to 15 struct esp_hf_client_cb_param_t::hf_client_conn_stat_param conn_stat Macros ESP_BT_HF_CLIENT_NUMBER_LEN ESP_BT_HF_CLIENT_OPERATOR_NAME_LEN ESP_BT_HF_AT_SEND_XAPL_LEN ESP_HF_CLIENT_PEER_FEAT_3WAY ESP_HF_CLIENT_PEER_FEAT_ECNR ESP_HF_CLIENT_PEER_FEAT_VREC ESP_HF_CLIENT_PEER_FEAT_INBAND ESP_HF_CLIENT_PEER_FEAT_VTAG ESP_HF_CLIENT_PEER_FEAT_REJECT ESP_HF_CLIENT_PEER_FEAT_ECS ESP_HF_CLIENT_PEER_FEAT_ECC ESP_HF_CLIENT_PEER_FEAT_EXTERR ESP_HF_CLIENT_PEER_FEAT_CODEC ESP_HF_CLIENT_PEER_FEAT_HF_IND ESP_HF_CLIENT_PEER_FEAT_ESCO_S4 ESP_HF_CLIENT_CHLD_FEAT_REL ESP_HF_CLIENT_CHLD_FEAT_REL_ACC ESP_HF_CLIENT_CHLD_FEAT_REL_X ESP_HF_CLIENT_CHLD_FEAT_HOLD_ACC ESP_HF_CLIENT_CHLD_FEAT_PRIV_X ESP_HF_CLIENT_CHLD_FEAT_MERGE ESP_HF_CLIENT_CHLD_FEAT_MERGE_DETACH ESP_HF_CLIENT_XAPL_FEAT_RESERVED ESP_HF_CLIENT_XAPL_FEAT_BATTERY_REPORT ESP_HF_CLIENT_XAPL_FEAT_DOCKED ESP_HF_CLIENT_XAPL_FEAT_SIRI_STATUS_REPORT ESP_HF_CLIENT_XAPL_NR_STATUS_REPORT Type Definitions typedef void (*esp_hf_client_incoming_data_cb_t)(const uint8_t *buf, uint32_t len) HFP client incoming data callback function, the callback is useful in case of Voice Over HCI. Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer is allocated inside bluetooth protocol stack and will be released after invoke of the callback is finished. Param len [in] : size(in bytes) in buf Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer is allocated inside bluetooth protocol stack and will be released after invoke of the callback is finished. Param len [in] : size(in bytes) in buf typedef uint32_t (*esp_hf_client_outgoing_data_cb_t)(uint8_t *buf, uint32_t len) HFP client outgoing data callback function, the callback is useful in case of Voice Over HCI. Once audio connection is set up and the application layer has prepared data to send, the lower layer will call this function to read data and then send. This callback is supposed to be implemented as non-blocking, and if data is not enough, return value 0 is supposed. Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer is allocated inside bluetooth protocol stack and will be released after invoke of the callback is finished. Param len [in] : size(in bytes) in buf Return length of data successfully read Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer is allocated inside bluetooth protocol stack and will be released after invoke of the callback is finished. Param len [in] : size(in bytes) in buf Return length of data successfully read typedef void (*esp_hf_client_cb_t)(esp_hf_client_cb_event_t event, esp_hf_client_cb_param_t *param) HFP client callback function type. Param event : Event type Param param : Pointer to callback parameter Param event : Event type Param param : Pointer to callback parameter Enumerations enum esp_hf_client_connection_state_t Bluetooth HFP RFCOMM connection and service level connection status. Values: enumerator ESP_HF_CLIENT_CONNECTION_STATE_DISCONNECTED RFCOMM data link channel released enumerator ESP_HF_CLIENT_CONNECTION_STATE_DISCONNECTED RFCOMM data link channel released enumerator ESP_HF_CLIENT_CONNECTION_STATE_CONNECTING connecting remote device on the RFCOMM data link enumerator ESP_HF_CLIENT_CONNECTION_STATE_CONNECTING connecting remote device on the RFCOMM data link enumerator ESP_HF_CLIENT_CONNECTION_STATE_CONNECTED RFCOMM connection established enumerator ESP_HF_CLIENT_CONNECTION_STATE_CONNECTED RFCOMM connection established enumerator ESP_HF_CLIENT_CONNECTION_STATE_SLC_CONNECTED service level connection established enumerator ESP_HF_CLIENT_CONNECTION_STATE_SLC_CONNECTED service level connection established enumerator ESP_HF_CLIENT_CONNECTION_STATE_DISCONNECTING disconnecting with remote device on the RFCOMM dat link enumerator ESP_HF_CLIENT_CONNECTION_STATE_DISCONNECTING disconnecting with remote device on the RFCOMM dat link enumerator ESP_HF_CLIENT_CONNECTION_STATE_DISCONNECTED enum esp_hf_client_audio_state_t Bluetooth HFP audio connection status. Values: enumerator ESP_HF_CLIENT_AUDIO_STATE_DISCONNECTED audio connection released enumerator ESP_HF_CLIENT_AUDIO_STATE_DISCONNECTED audio connection released enumerator ESP_HF_CLIENT_AUDIO_STATE_CONNECTING audio connection has been initiated enumerator ESP_HF_CLIENT_AUDIO_STATE_CONNECTING audio connection has been initiated enumerator ESP_HF_CLIENT_AUDIO_STATE_CONNECTED audio connection is established enumerator ESP_HF_CLIENT_AUDIO_STATE_CONNECTED audio connection is established enumerator ESP_HF_CLIENT_AUDIO_STATE_CONNECTED_MSBC mSBC audio connection is established enumerator ESP_HF_CLIENT_AUDIO_STATE_CONNECTED_MSBC mSBC audio connection is established enumerator ESP_HF_CLIENT_AUDIO_STATE_DISCONNECTED enum esp_hf_client_in_band_ring_state_t in-band ring tone state Values: enumerator ESP_HF_CLIENT_IN_BAND_RINGTONE_NOT_PROVIDED enumerator ESP_HF_CLIENT_IN_BAND_RINGTONE_NOT_PROVIDED enumerator ESP_HF_CLIENT_IN_BAND_RINGTONE_PROVIDED enumerator ESP_HF_CLIENT_IN_BAND_RINGTONE_PROVIDED enumerator ESP_HF_CLIENT_IN_BAND_RINGTONE_NOT_PROVIDED enum esp_hf_client_cb_event_t HF CLIENT callback events. Values: enumerator ESP_HF_CLIENT_CONNECTION_STATE_EVT connection state changed event enumerator ESP_HF_CLIENT_CONNECTION_STATE_EVT connection state changed event enumerator ESP_HF_CLIENT_AUDIO_STATE_EVT audio connection state change event enumerator ESP_HF_CLIENT_AUDIO_STATE_EVT audio connection state change event enumerator ESP_HF_CLIENT_BVRA_EVT voice recognition state change event enumerator ESP_HF_CLIENT_BVRA_EVT voice recognition state change event enumerator ESP_HF_CLIENT_CIND_CALL_EVT call indication enumerator ESP_HF_CLIENT_CIND_CALL_EVT call indication enumerator ESP_HF_CLIENT_CIND_CALL_SETUP_EVT call setup indication enumerator ESP_HF_CLIENT_CIND_CALL_SETUP_EVT call setup indication enumerator ESP_HF_CLIENT_CIND_CALL_HELD_EVT call held indication enumerator ESP_HF_CLIENT_CIND_CALL_HELD_EVT call held indication enumerator ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT network service availability indication enumerator ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT network service availability indication enumerator ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT signal strength indication enumerator ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT signal strength indication enumerator ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT roaming status indication enumerator ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT roaming status indication enumerator ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT battery level indication enumerator ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT battery level indication enumerator ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT current operator information enumerator ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT current operator information enumerator ESP_HF_CLIENT_BTRH_EVT call response and hold event enumerator ESP_HF_CLIENT_BTRH_EVT call response and hold event enumerator ESP_HF_CLIENT_CLIP_EVT Calling Line Identification notification enumerator ESP_HF_CLIENT_CLIP_EVT Calling Line Identification notification enumerator ESP_HF_CLIENT_CCWA_EVT call waiting notification enumerator ESP_HF_CLIENT_CCWA_EVT call waiting notification enumerator ESP_HF_CLIENT_CLCC_EVT list of current calls notification enumerator ESP_HF_CLIENT_CLCC_EVT list of current calls notification enumerator ESP_HF_CLIENT_VOLUME_CONTROL_EVT audio volume control command from AG, provided by +VGM or +VGS message enumerator ESP_HF_CLIENT_VOLUME_CONTROL_EVT audio volume control command from AG, provided by +VGM or +VGS message enumerator ESP_HF_CLIENT_AT_RESPONSE_EVT AT command response event enumerator ESP_HF_CLIENT_AT_RESPONSE_EVT AT command response event enumerator ESP_HF_CLIENT_CNUM_EVT subscriber information response from AG enumerator ESP_HF_CLIENT_CNUM_EVT subscriber information response from AG enumerator ESP_HF_CLIENT_BSIR_EVT setting of in-band ring tone enumerator ESP_HF_CLIENT_BSIR_EVT setting of in-band ring tone enumerator ESP_HF_CLIENT_BINP_EVT requested number of last voice tag from AG enumerator ESP_HF_CLIENT_BINP_EVT requested number of last voice tag from AG enumerator ESP_HF_CLIENT_RING_IND_EVT ring indication event enumerator ESP_HF_CLIENT_RING_IND_EVT ring indication event enumerator ESP_HF_CLIENT_PKT_STAT_NUMS_GET_EVT requested number of packet different status enumerator ESP_HF_CLIENT_PKT_STAT_NUMS_GET_EVT requested number of packet different status enumerator ESP_HF_CLIENT_CONNECTION_STATE_EVT
HFP Client API API Reference Header File components/bt/host/bluedroid/api/include/api/esp_hf_client_api.h This header file can be included with: #include "esp_hf_client_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_hf_client_register_callback(esp_hf_client_cb_t callback) Register application callback function to HFP client module. This function should be called only after esp_bluedroid_enable() completes successfully. - Parameters callback -- [in] HFP client event callback function - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer - - esp_err_t esp_hf_client_init(void) Initialize the bluetooth HFP client module. This function should be called after esp_bluedroid_enable() completes successfully. - Returns ESP_OK: if the initialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_deinit(void) De-initialize for HFP client module. This function should be called only after esp_bluedroid_enable() completes successfully. - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_connect(esp_bd_addr_t remote_bda) Establish a Service Level Connection to remote bluetooth HFP audio gateway(AG) device. This function must be called after esp_hf_client_init() and before esp_hf_client_deinit(). - Parameters remote_bda -- [in] remote bluetooth device address - Returns ESP_OK: connect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_disconnect(esp_bd_addr_t remote_bda) Disconnect from the remote HFP audio gateway. This function must be called after esp_hf_client_init() and before esp_hf_client_deinit(). - Parameters remote_bda -- [in] remote bluetooth device address - Returns ESP_OK: disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_connect_audio(esp_bd_addr_t remote_bda) Create audio connection with remote HFP AG. As a precondition to use this API, Service Level Connection shall exist with AG. - Parameters remote_bda -- [in] remote bluetooth device address - Returns ESP_OK: connect audio request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_disconnect_audio(esp_bd_addr_t remote_bda) Release the established audio connection with remote HFP AG. As a precondition to use this API, Service Level Connection shall exist with AG. - Parameters remote_bda -- [in] remote bluetooth device address - Returns ESP_OK: disconnect audio request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_start_voice_recognition(void) Enable voice recognition in the AG. As a precondition to use this API, Service Level Connection shall exist with AG. - Returns ESP_OK: starting voice recognition is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_stop_voice_recognition(void) Disable voice recognition in the AG. As a precondition to use this API, Service Level Connection shall exist with AG. - Returns ESP_OK: stoping voice recognition is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_volume_update(esp_hf_volume_control_target_t type, int volume) Volume synchronization with AG. As a precondition to use this API, Service Level Connection shall exist with AG. - Parameters type -- [in] volume control target, speaker or microphone volume -- [in] gain of the speaker of microphone, ranges 0 to 15 - - Returns ESP_OK: volume update is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_dial(const char *number) Place a call with a specified number, if number is NULL, last called number is called. As a precondition to use this API, Service Level Connection shall exist with AG. - Parameters number -- [in] number string of the call. If NULL, the last number is called(aka re-dial) - Returns ESP_OK: a call placing is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_dial_memory(int location) Place a call with number specified by location(speed dial). As a precondition to use this API, Service Level Connection shall exist with AG. - Parameters location -- [in] location of the number in the memory - Returns ESP_OK: a memory call placing is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_send_chld_cmd(esp_hf_chld_type_t chld, int idx) Send call hold and multiparty commands, or enhanced call control commands(Use AT+CHLD). As a precondition to use this API, Service Level Connection shall exist with AG. - Parameters chld -- [in] AT+CHLD call hold and multiparty handling AT command. idx -- [in] used in Enhanced Call Control Mechanisms, used if chld is ESP_HF_CHLD_TYPE_REL_X or ESP_HF_CHLD_TYPE_PRIV_X - - Returns ESP_OK: command AT+CHLD is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_send_btrh_cmd(esp_hf_btrh_cmd_t btrh) Send response and hold action command(Send AT+BTRH command) As a precondition to use this API, Service Level Connection shall exist with AG. - Parameters btrh -- [in] response and hold action to send - Returns ESP_OK: command AT+BTRH is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_answer_call(void) Answer an incoming call(send ATA command). As a precondition to use this API, Service Level Connection shall exist with AG. - Returns ESP_OK: a call answering is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_reject_call(void) Reject an incoming call or terminate an ongoing call(send AT+CHUP command). As a precondition to use this API, Service Level Connection shall exist with AG. - Returns ESP_OK: the call rejecting is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_query_current_calls(void) Query list of current calls in AG(send AT+CLCC command). As a precondition to use this API, Service Level Connection shall exist with AG. - Returns ESP_OK: query of current calls is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_query_current_operator_name(void) Query the name of currently selected network operator in AG(use AT+COPS commands). As a precondition to use this API, Service Level Connection shall exist with AG. - Returns ESP_OK: query of current operator name is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_retrieve_subscriber_info(void) Get subscriber information number from AG(send AT+CNUM command) As a precondition to use this API, Service Level Connection shall exist with AG. - Returns ESP_OK: the retrieving of subscriber information is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_send_dtmf(char code) Transmit DTMF codes during an ongoing call(use AT+VTS commands) As a precondition to use this API, Service Level Connection shall exist with AG. - Parameters code -- [in] dtmf code, single ascii character in the set 0-9, #, *, A-D - Returns ESP_OK: the DTMF codes are sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_send_xapl(char *information, uint32_t features) Send command to enable Vendor specific feature to indicate battery level and docker status This is Apple-specific commands, but used by most device, including Android and Windows. - Parameters information -- [in] XAPL vendorID-productID-version, such as "0505-1995-0610" vendorID: A string representation of the hex value of the vendor ID from the manufacturer, without the 0x prefix. productID: A string representation of the hex value of the product ID from the manufacturer, without the 0x prefix. version: The revision of the software features -- [in] A base-10 representation of a bit field. such as ESP_HF_CLIENT_XAPL_FEAT_BATTERY_REPORT - - Returns ESP_OK: Feature enable request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_send_iphoneaccev(uint32_t bat_level, bool docked) Send Battery level and docker status Enable this feature using XAPL command first This is Apple-specific commands, but used by most device, including Android and Windows. - Parameters bat_level -- [in] Battery Level: value between 0 and 9 docked -- [in] Dock State: false = undocked, true = docked - - Returns ESP_OK: battery level is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_request_last_voice_tag_number(void) Request a phone number from AG corresponding to last voice tag recorded (send AT+BINP command). As a precondition to use this API, Service Level Connection shall exist with AG. - Returns ESP_OK: the phone number request corresponding to last voice tag recorded is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_send_nrec(void) Disable echo cancellation and noise reduction in the AG (use AT+NREC=0 command). As a precondition to use this API, Service Level Connection shall exist with AG. - Returns ESP_OK: NREC=0 request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_client_register_data_callback(esp_hf_client_incoming_data_cb_t recv, esp_hf_client_outgoing_data_cb_t send) Register HFP client data output function; the callback is only used in the case that Voice Over HCI is enabled. - Parameters recv -- [in] HFP client incoming data callback function send -- [in] HFP client outgoing data callback function - - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer - - esp_err_t esp_hf_client_pkt_stat_nums_get(uint16_t sync_conn_handle) Get the number of packets received and sent This function is only used in the case that Voice Over HCI is enabled and the audio state is connected. When the operation is completed, the callback function will be called with ESP_HF_CLIENT_PKT_STAT_NUMS_GET_EVT. - Parameters sync_conn_handle -- [in] the (e)SCO connection handle - Returns ESP_OK: if the request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - void esp_hf_client_outgoing_data_ready(void) Trigger the lower-layer to fetch and send audio data. This function is only only used in the case that Voice Over HCI is enabled. After this function is called, lower layer will invoke esp_hf_client_outgoing_data_cb_t to fetch data. As a precondition to use this API, Service Level Connection shall exist with AG. - void esp_hf_client_pcm_resample_init(uint32_t src_sps, uint32_t bits, uint32_t channels) Initialize the down sampling converter. This is a utility function that can only be used in the case that Voice Over HCI is enabled. - Parameters src_sps -- [in] original samples per second(source audio data, i.e. 48000, 32000, 16000, 44100, 22050, 11025) bits -- [in] number of bits per pcm sample (16) channels -- [in] number of channels (i.e. mono(1), stereo(2)...) - - void esp_hf_client_pcm_resample_deinit(void) Deinitialize the down sampling converter. - int32_t esp_hf_client_pcm_resample(void *src, uint32_t in_bytes, void *dst) Down sampling utility to convert high sampling rate into 8K/16bits 1-channel mode PCM samples. This can only be used in the case that Voice Over HCI is enabled. - Parameters src -- [in] pointer to the buffer where the original sampling PCM are stored in_bytes -- [in] length of the input PCM sample buffer in byte dst -- [in] pointer to the buffer which is to be used to store the converted PCM samples - - Returns number of samples converted Unions - union esp_hf_client_cb_param_t - #include <esp_hf_client_api.h> HFP client callback parameters. Public Members - struct esp_hf_client_cb_param_t::hf_client_conn_stat_param conn_stat HF callback param of ESP_HF_CLIENT_CONNECTION_STATE_EVT - struct esp_hf_client_cb_param_t::hf_client_audio_stat_param audio_stat HF callback param of ESP_HF_CLIENT_AUDIO_STATE_EVT - struct esp_hf_client_cb_param_t::hf_client_bvra_param bvra HF callback param of ESP_HF_CLIENT_BVRA_EVT - struct esp_hf_client_cb_param_t::hf_client_service_availability_param service_availability HF callback param of ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT - struct esp_hf_client_cb_param_t::hf_client_network_roaming_param roaming HF callback param of ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT - struct esp_hf_client_cb_param_t::hf_client_signal_strength_ind_param signal_strength HF callback param of ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT - struct esp_hf_client_cb_param_t::hf_client_battery_level_ind_param battery_level HF callback param of ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT - struct esp_hf_client_cb_param_t::hf_client_current_operator_param cops HF callback param of ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT - struct esp_hf_client_cb_param_t::hf_client_call_ind_param call HF callback param of ESP_HF_CLIENT_CIND_CALL_EVT - struct esp_hf_client_cb_param_t::hf_client_call_setup_ind_param call_setup HF callback param of ESP_HF_CLIENT_BVRA_EVT - struct esp_hf_client_cb_param_t::hf_client_call_held_ind_param call_held HF callback param of ESP_HF_CLIENT_CIND_CALL_HELD_EVT - struct esp_hf_client_cb_param_t::hf_client_btrh_param btrh HF callback param of ESP_HF_CLIENT_BRTH_EVT - struct esp_hf_client_cb_param_t::hf_client_clip_param clip HF callback param of ESP_HF_CLIENT_CLIP_EVT - struct esp_hf_client_cb_param_t::hf_client_ccwa_param ccwa HF callback param of ESP_HF_CLIENT_BVRA_EVT - struct esp_hf_client_cb_param_t::hf_client_clcc_param clcc HF callback param of ESP_HF_CLIENT_CLCC_EVT - struct esp_hf_client_cb_param_t::hf_client_volume_control_param volume_control HF callback param of ESP_HF_CLIENT_VOLUME_CONTROL_EVT - struct esp_hf_client_cb_param_t::hf_client_at_response_param at_response HF callback param of ESP_HF_CLIENT_AT_RESPONSE_EVT - struct esp_hf_client_cb_param_t::hf_client_cnum_param cnum HF callback param of ESP_HF_CLIENT_CNUM_EVT - struct esp_hf_client_cb_param_t::hf_client_bsirparam bsir HF callback param of ESP_HF_CLIENT_BSIR_EVT - struct esp_hf_client_cb_param_t::hf_client_binp_param binp HF callback param of ESP_HF_CLIENT_BINP_EVT - struct esp_hf_client_cb_param_t::hf_client_pkt_status_nums pkt_nums HF callback param of ESP_HF_CLIENT_PKT_STAT_NUMS_GET_EVT - struct hf_client_at_response_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_AT_RESPONSE_EVT. Public Members - esp_hf_at_response_code_t code AT response code - esp_hf_cme_err_t cme Extended Audio Gateway Error Result Code - esp_hf_at_response_code_t code - struct hf_client_audio_stat_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_AUDIO_STATE_EVT. Public Members - esp_hf_client_audio_state_t state audio connection state - esp_bd_addr_t remote_bda remote bluetooth device address - uint16_t sync_conn_handle (e)SCO connection handle - esp_hf_client_audio_state_t state - struct hf_client_battery_level_ind_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT. Public Members - int value battery charge value, ranges from 0 to 5 - int value - struct hf_client_binp_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_BINP_EVT. Public Members - const char *number phone number corresponding to the last voice tag in the HF - const char *number - struct hf_client_bsirparam - #include <esp_hf_client_api.h> ESP_HF_CLIENT_BSIR_EVT. Public Members - esp_hf_client_in_band_ring_state_t state setting state of in-band ring tone - esp_hf_client_in_band_ring_state_t state - struct hf_client_btrh_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_BTRH_EVT. Public Members - esp_hf_btrh_status_t status call hold and response status result code - esp_hf_btrh_status_t status - struct hf_client_bvra_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_BVRA_EVT. Public Members - esp_hf_vr_state_t value voice recognition state - esp_hf_vr_state_t value - struct hf_client_call_held_ind_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_CALL_HELD_EVT. Public Members - esp_hf_call_held_status_t status bluetooth proprietary call hold status indicator - esp_hf_call_held_status_t status - struct hf_client_call_ind_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_CALL_EVT. Public Members - esp_hf_call_status_t status call status indicator - esp_hf_call_status_t status - struct hf_client_call_setup_ind_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_CALL_SETUP_EVT. Public Members - esp_hf_call_setup_status_t status call setup status indicator - esp_hf_call_setup_status_t status - struct hf_client_ccwa_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_CCWA_EVT. Public Members - const char *number phone number string of waiting call - const char *number - struct hf_client_clcc_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_CLCC_EVT. Public Members - int idx numbering(starting with 1) of the call - esp_hf_current_call_direction_t dir direction of the call - esp_hf_current_call_status_t status status of the call - esp_hf_current_call_mpty_type_t mpty multi-party flag - char *number phone number(optional) - int idx - struct hf_client_clip_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_CLIP_EVT. Public Members - const char *number phone number string of call - const char *number - struct hf_client_cnum_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_CNUM_EVT. Public Members - const char *number phone number string - esp_hf_subscriber_service_type_t type service type that the phone number relates to - const char *number - struct hf_client_conn_stat_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_CONNECTION_STATE_EVT. Public Members - esp_hf_client_connection_state_t state HF connection state - uint32_t peer_feat AG supported features - uint32_t chld_feat AG supported features on call hold and multiparty services - esp_bd_addr_t remote_bda remote bluetooth device address - esp_hf_client_connection_state_t state - struct hf_client_current_operator_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT. Public Members - const char *name name of the network operator - const char *name - struct hf_client_network_roaming_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT. Public Members - esp_hf_roaming_status_t status roaming status - esp_hf_roaming_status_t status - struct hf_client_pkt_status_nums - #include <esp_hf_client_api.h> ESP_HF_CLIENT_PKT_STAT_NUMS_GET_EVT. Public Members - uint32_t rx_total the total number of packets received - uint32_t rx_correct the total number of packets data correctly received - uint32_t rx_err the total number of packets data with possible invalid - uint32_t rx_none the total number of packets data no received - uint32_t rx_lost the total number of packets data partially lost - uint32_t tx_total the total number of packets send - uint32_t tx_discarded the total number of packets send lost - uint32_t rx_total - struct hf_client_service_availability_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT. Public Members - esp_hf_network_state_t status service availability status - esp_hf_network_state_t status - struct hf_client_signal_strength_ind_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT. Public Members - int value signal strength value, ranges from 0 to 5 - int value - struct hf_client_volume_control_param - #include <esp_hf_client_api.h> ESP_HF_CLIENT_VOLUME_CONTROL_EVT. Public Members - esp_hf_volume_control_target_t type volume control target, speaker or microphone - int volume gain, ranges from 0 to 15 - esp_hf_volume_control_target_t type - struct esp_hf_client_cb_param_t::hf_client_conn_stat_param conn_stat Macros - ESP_BT_HF_CLIENT_NUMBER_LEN - ESP_BT_HF_CLIENT_OPERATOR_NAME_LEN - ESP_BT_HF_AT_SEND_XAPL_LEN - ESP_HF_CLIENT_PEER_FEAT_3WAY - ESP_HF_CLIENT_PEER_FEAT_ECNR - ESP_HF_CLIENT_PEER_FEAT_VREC - ESP_HF_CLIENT_PEER_FEAT_INBAND - ESP_HF_CLIENT_PEER_FEAT_VTAG - ESP_HF_CLIENT_PEER_FEAT_REJECT - ESP_HF_CLIENT_PEER_FEAT_ECS - ESP_HF_CLIENT_PEER_FEAT_ECC - ESP_HF_CLIENT_PEER_FEAT_EXTERR - ESP_HF_CLIENT_PEER_FEAT_CODEC - ESP_HF_CLIENT_PEER_FEAT_HF_IND - ESP_HF_CLIENT_PEER_FEAT_ESCO_S4 - ESP_HF_CLIENT_CHLD_FEAT_REL - ESP_HF_CLIENT_CHLD_FEAT_REL_ACC - ESP_HF_CLIENT_CHLD_FEAT_REL_X - ESP_HF_CLIENT_CHLD_FEAT_HOLD_ACC - ESP_HF_CLIENT_CHLD_FEAT_PRIV_X - ESP_HF_CLIENT_CHLD_FEAT_MERGE - ESP_HF_CLIENT_CHLD_FEAT_MERGE_DETACH - ESP_HF_CLIENT_XAPL_FEAT_RESERVED - ESP_HF_CLIENT_XAPL_FEAT_BATTERY_REPORT - ESP_HF_CLIENT_XAPL_FEAT_DOCKED - ESP_HF_CLIENT_XAPL_FEAT_SIRI_STATUS_REPORT - ESP_HF_CLIENT_XAPL_NR_STATUS_REPORT Type Definitions - typedef void (*esp_hf_client_incoming_data_cb_t)(const uint8_t *buf, uint32_t len) HFP client incoming data callback function, the callback is useful in case of Voice Over HCI. - Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer is allocated inside bluetooth protocol stack and will be released after invoke of the callback is finished. - Param len [in] : size(in bytes) in buf - typedef uint32_t (*esp_hf_client_outgoing_data_cb_t)(uint8_t *buf, uint32_t len) HFP client outgoing data callback function, the callback is useful in case of Voice Over HCI. Once audio connection is set up and the application layer has prepared data to send, the lower layer will call this function to read data and then send. This callback is supposed to be implemented as non-blocking, and if data is not enough, return value 0 is supposed. - Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer is allocated inside bluetooth protocol stack and will be released after invoke of the callback is finished. - Param len [in] : size(in bytes) in buf - Return length of data successfully read - typedef void (*esp_hf_client_cb_t)(esp_hf_client_cb_event_t event, esp_hf_client_cb_param_t *param) HFP client callback function type. - Param event : Event type - Param param : Pointer to callback parameter Enumerations - enum esp_hf_client_connection_state_t Bluetooth HFP RFCOMM connection and service level connection status. Values: - enumerator ESP_HF_CLIENT_CONNECTION_STATE_DISCONNECTED RFCOMM data link channel released - enumerator ESP_HF_CLIENT_CONNECTION_STATE_CONNECTING connecting remote device on the RFCOMM data link - enumerator ESP_HF_CLIENT_CONNECTION_STATE_CONNECTED RFCOMM connection established - enumerator ESP_HF_CLIENT_CONNECTION_STATE_SLC_CONNECTED service level connection established - enumerator ESP_HF_CLIENT_CONNECTION_STATE_DISCONNECTING disconnecting with remote device on the RFCOMM dat link - enumerator ESP_HF_CLIENT_CONNECTION_STATE_DISCONNECTED - enum esp_hf_client_audio_state_t Bluetooth HFP audio connection status. Values: - enumerator ESP_HF_CLIENT_AUDIO_STATE_DISCONNECTED audio connection released - enumerator ESP_HF_CLIENT_AUDIO_STATE_CONNECTING audio connection has been initiated - enumerator ESP_HF_CLIENT_AUDIO_STATE_CONNECTED audio connection is established - enumerator ESP_HF_CLIENT_AUDIO_STATE_CONNECTED_MSBC mSBC audio connection is established - enumerator ESP_HF_CLIENT_AUDIO_STATE_DISCONNECTED - enum esp_hf_client_in_band_ring_state_t in-band ring tone state Values: - enumerator ESP_HF_CLIENT_IN_BAND_RINGTONE_NOT_PROVIDED - enumerator ESP_HF_CLIENT_IN_BAND_RINGTONE_PROVIDED - enumerator ESP_HF_CLIENT_IN_BAND_RINGTONE_NOT_PROVIDED - enum esp_hf_client_cb_event_t HF CLIENT callback events. Values: - enumerator ESP_HF_CLIENT_CONNECTION_STATE_EVT connection state changed event - enumerator ESP_HF_CLIENT_AUDIO_STATE_EVT audio connection state change event - enumerator ESP_HF_CLIENT_BVRA_EVT voice recognition state change event - enumerator ESP_HF_CLIENT_CIND_CALL_EVT call indication - enumerator ESP_HF_CLIENT_CIND_CALL_SETUP_EVT call setup indication - enumerator ESP_HF_CLIENT_CIND_CALL_HELD_EVT call held indication - enumerator ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT network service availability indication - enumerator ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT signal strength indication - enumerator ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT roaming status indication - enumerator ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT battery level indication - enumerator ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT current operator information - enumerator ESP_HF_CLIENT_BTRH_EVT call response and hold event - enumerator ESP_HF_CLIENT_CLIP_EVT Calling Line Identification notification - enumerator ESP_HF_CLIENT_CCWA_EVT call waiting notification - enumerator ESP_HF_CLIENT_CLCC_EVT list of current calls notification - enumerator ESP_HF_CLIENT_VOLUME_CONTROL_EVT audio volume control command from AG, provided by +VGM or +VGS message - enumerator ESP_HF_CLIENT_AT_RESPONSE_EVT AT command response event - enumerator ESP_HF_CLIENT_CNUM_EVT subscriber information response from AG - enumerator ESP_HF_CLIENT_BSIR_EVT setting of in-band ring tone - enumerator ESP_HF_CLIENT_BINP_EVT requested number of last voice tag from AG - enumerator ESP_HF_CLIENT_RING_IND_EVT ring indication event - enumerator ESP_HF_CLIENT_PKT_STAT_NUMS_GET_EVT requested number of packet different status - enumerator ESP_HF_CLIENT_CONNECTION_STATE_EVT
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_hf_client.html
ESP-IDF Programming Guide v5.2.1 documentation
null
HFP AG API
null
espressif.com
2016-01-01
24a1c05d68239b61
null
null
HFP AG API API Reference Header File components/bt/host/bluedroid/api/include/api/esp_hf_ag_api.h This header file can be included with: #include "esp_hf_ag_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_hf_ag_register_callback(esp_hf_cb_t callback) Register application callback function to HFP AG module. This function should be called only after esp_bluedroid_enable() completes successfully. Parameters callback -- [in] HFP AG event callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer ESP_OK: success Parameters callback -- [in] HFP AG event callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer esp_err_t esp_hf_ag_init(void) Initialize the bluetooth HF AG module. This function should be called after esp_bluedroid_enable() completes successfully. Returns ESP_OK: if the initialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the initialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the initialization request is sent successfully Returns ESP_OK: if the initialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_deinit(void) De-initialize for HF AG module. This function should be called only after esp_bluedroid_enable() completes successfully. Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: success Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_slc_connect(esp_bd_addr_t remote_bda) To establish a Service Level Connection to remote bluetooth HFP client device. This function must be called after esp_hf_ag_init() and before esp_hf_ag_deinit(). Parameters remote_bda -- [in] remote bluetooth HFP client device address Returns ESP_OK: connect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: connect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: connect request is sent to lower layer Parameters remote_bda -- [in] remote bluetooth HFP client device address Returns ESP_OK: connect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_slc_disconnect(esp_bd_addr_t remote_bda) Disconnect from the remote HFP client. This function must be called after esp_hf_ag_init() and before esp_hf_ag_deinit(). Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: disconnect request is sent to lower layer Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_audio_connect(esp_bd_addr_t remote_bda) Create audio connection with remote HFP client. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: audio connect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: audio connect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: audio connect request is sent to lower layer Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: audio connect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_audio_disconnect(esp_bd_addr_t remote_bda) Release the established audio connection with remote HFP client. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: audio disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: audio disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: audio disconnect request is sent to lower layer Parameters remote_bda -- [in] remote bluetooth device address Returns ESP_OK: audio disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_vra_control(esp_bd_addr_t remote_bda, esp_hf_vr_state_t value) Response of Volume Recognition Command(AT+VRA) from HFP client. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_bda -- [in] the device address of voice recognition initiator value -- [in] 0 - voice recognition disabled, 1- voice recognition enabled remote_bda -- [in] the device address of voice recognition initiator value -- [in] 0 - voice recognition disabled, 1- voice recognition enabled remote_bda -- [in] the device address of voice recognition initiator Returns ESP_OK: response of volume recognition is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: response of volume recognition is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: response of volume recognition is sent to lower layer Parameters remote_bda -- [in] the device address of voice recognition initiator value -- [in] 0 - voice recognition disabled, 1- voice recognition enabled Returns ESP_OK: response of volume recognition is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_volume_control(esp_bd_addr_t remote_bda, esp_hf_volume_control_target_t type, int volume) Volume synchronization with HFP client. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_bda -- [in] remote bluetooth device address type -- [in] volume control target, speaker or microphone volume -- [in] gain of the speaker of microphone, ranges 0 to 15 remote_bda -- [in] remote bluetooth device address type -- [in] volume control target, speaker or microphone volume -- [in] gain of the speaker of microphone, ranges 0 to 15 remote_bda -- [in] remote bluetooth device address Returns ESP_OK: volume synchronization control is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if arguments are invalid ESP_FAIL: others ESP_OK: volume synchronization control is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if arguments are invalid ESP_FAIL: others ESP_OK: volume synchronization control is sent to lower layer Parameters remote_bda -- [in] remote bluetooth device address type -- [in] volume control target, speaker or microphone volume -- [in] gain of the speaker of microphone, ranges 0 to 15 Returns ESP_OK: volume synchronization control is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if arguments are invalid ESP_FAIL: others esp_err_t esp_hf_ag_unknown_at_send(esp_bd_addr_t remote_addr, char *unat) Handle Unknown AT command from HFP Client. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_addr -- [in] remote bluetooth device address unat -- [in] User AT command response to HF Client. It will response "ERROR" by default if unat is NULL. remote_addr -- [in] remote bluetooth device address unat -- [in] User AT command response to HF Client. It will response "ERROR" by default if unat is NULL. remote_addr -- [in] remote bluetooth device address Returns ESP_OK: response of unknown AT command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: response of unknown AT command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: response of unknown AT command is sent to lower layer Parameters remote_addr -- [in] remote bluetooth device address unat -- [in] User AT command response to HF Client. It will response "ERROR" by default if unat is NULL. Returns ESP_OK: response of unknown AT command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_cmee_send(esp_bd_addr_t remote_bda, esp_hf_at_response_code_t response_code, esp_hf_cme_err_t error_code) Unsolicited send extend AT error code to HFP Client. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_bda -- [in] remote bluetooth device address response_code -- [in] AT command response code error_code -- [in] CME error code remote_bda -- [in] remote bluetooth device address response_code -- [in] AT command response code error_code -- [in] CME error code remote_bda -- [in] remote bluetooth device address Returns ESP_OK: extend error code is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: extend error code is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: extend error code is sent to lower layer Parameters remote_bda -- [in] remote bluetooth device address response_code -- [in] AT command response code error_code -- [in] CME error code Returns ESP_OK: extend error code is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_devices_status_indchange(esp_bd_addr_t remote_addr, esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, esp_hf_network_state_t ntk_state, int signal) Unsolicited send device status notification to HFP Client. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_addr -- [in] remote bluetooth device address call_state -- [in] call state call_setup_state -- [in] call setup state ntk_state -- [in] network service state signal -- [in] signal strength from 0 to 5 remote_addr -- [in] remote bluetooth device address call_state -- [in] call state call_setup_state -- [in] call setup state ntk_state -- [in] network service state signal -- [in] signal strength from 0 to 5 remote_addr -- [in] remote bluetooth device address Returns ESP_OK: device status notification is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if arguments are invalid ESP_FAIL: others ESP_OK: device status notification is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if arguments are invalid ESP_FAIL: others ESP_OK: device status notification is sent to lower layer Parameters remote_addr -- [in] remote bluetooth device address call_state -- [in] call state call_setup_state -- [in] call setup state ntk_state -- [in] network service state signal -- [in] signal strength from 0 to 5 Returns ESP_OK: device status notification is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if arguments are invalid ESP_FAIL: others esp_err_t esp_hf_ag_ciev_report(esp_bd_addr_t remote_addr, esp_hf_ciev_report_type_t ind_type, int value) Send indicator report "+CIEV: <ind> <value>" to HFP Client. "CIEV" means “indicator events reporting", and all indicator types can be sent one type at a time. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_addr -- [in] remote bluetooth device address ind_type -- [in] indicator type value -- [in] indicator value remote_addr -- [in] remote bluetooth device address ind_type -- [in] indicator type value -- [in] indicator value remote_addr -- [in] remote bluetooth device address Returns ESP_OK: indicator report is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: indicator report is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: indicator report is sent to lower layer Parameters remote_addr -- [in] remote bluetooth device address ind_type -- [in] indicator type value -- [in] indicator value Returns ESP_OK: indicator report is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_cind_response(esp_bd_addr_t remote_addr, esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, esp_hf_network_state_t ntk_state, int signal, esp_hf_roaming_status_t roam, int batt_lev, esp_hf_call_held_status_t call_held_status) Response to device individual indicators to HFP Client. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_addr -- [in] remote bluetooth device address call_state -- [in] call state call_setup_state -- [in] call setup state ntk_state -- [in] network service state signal -- [in] signal strength from 0 to 5 roam -- [in] roam state batt_lev -- [in] battery level from 0 to 5 call_held_status -- [in] call held status remote_addr -- [in] remote bluetooth device address call_state -- [in] call state call_setup_state -- [in] call setup state ntk_state -- [in] network service state signal -- [in] signal strength from 0 to 5 roam -- [in] roam state batt_lev -- [in] battery level from 0 to 5 call_held_status -- [in] call held status remote_addr -- [in] remote bluetooth device address Returns ESP_OK: response to device individual indicators is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if the arguments are invalid ESP_FAIL: others ESP_OK: response to device individual indicators is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if the arguments are invalid ESP_FAIL: others ESP_OK: response to device individual indicators is sent to lower layer Parameters remote_addr -- [in] remote bluetooth device address call_state -- [in] call state call_setup_state -- [in] call setup state ntk_state -- [in] network service state signal -- [in] signal strength from 0 to 5 roam -- [in] roam state batt_lev -- [in] battery level from 0 to 5 call_held_status -- [in] call held status Returns ESP_OK: response to device individual indicators is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if the arguments are invalid ESP_FAIL: others esp_err_t esp_hf_ag_cops_response(esp_bd_addr_t remote_addr, char *name) Reponse for AT+COPS command from HF Client. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_addr -- [in] remote bluetooth device address name -- [in] current operator name remote_addr -- [in] remote bluetooth device address name -- [in] current operator name remote_addr -- [in] remote bluetooth device address Returns ESP_OK: reponse for AT+COPS command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: reponse for AT+COPS command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: reponse for AT+COPS command is sent to lower layer Parameters remote_addr -- [in] remote bluetooth device address name -- [in] current operator name Returns ESP_OK: reponse for AT+COPS command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_clcc_response(esp_bd_addr_t remote_addr, int index, esp_hf_current_call_direction_t dir, esp_hf_current_call_status_t current_call_state, esp_hf_current_call_mode_t mode, esp_hf_current_call_mpty_type_t mpty, char *number, esp_hf_call_addr_type_t type) Response to AT+CLCC command from HFP Client. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_addr -- [in] remote bluetooth device address index -- [in] the index of current call, starting with 1, finishing response with 0 (send OK) dir -- [in] call direction (incoming/outgoing) current_call_state -- [in] current call state mode -- [in] current call mode (voice/data/fax) mpty -- [in] single or multi type number -- [in] current call number type -- [in] international type or unknow remote_addr -- [in] remote bluetooth device address index -- [in] the index of current call, starting with 1, finishing response with 0 (send OK) dir -- [in] call direction (incoming/outgoing) current_call_state -- [in] current call state mode -- [in] current call mode (voice/data/fax) mpty -- [in] single or multi type number -- [in] current call number type -- [in] international type or unknow remote_addr -- [in] remote bluetooth device address Returns ESP_OK: response to AT+CLCC command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: response to AT+CLCC command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: response to AT+CLCC command is sent to lower layer Parameters remote_addr -- [in] remote bluetooth device address index -- [in] the index of current call, starting with 1, finishing response with 0 (send OK) dir -- [in] call direction (incoming/outgoing) current_call_state -- [in] current call state mode -- [in] current call mode (voice/data/fax) mpty -- [in] single or multi type number -- [in] current call number type -- [in] international type or unknow Returns ESP_OK: response to AT+CLCC command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_cnum_response(esp_bd_addr_t remote_addr, char *number, int number_type, esp_hf_subscriber_service_type_t service_type) Response for AT+CNUM command from HF Client. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_addr -- [in] remote bluetooth device address number -- [in] registration number number_type -- [in] value of number type from 128-143: national or international, may contain prefix and/or escape digits 144-159: international, includes country code prefix, add "+" if needed 160-175: national, but no prefix nor escape digits service_type -- [in] service type (unknown/voice/fax) remote_addr -- [in] remote bluetooth device address number -- [in] registration number number_type -- [in] value of number type from 128-143: national or international, may contain prefix and/or escape digits 144-159: international, includes country code prefix, add "+" if needed 160-175: national, but no prefix nor escape digits service_type -- [in] service type (unknown/voice/fax) remote_addr -- [in] remote bluetooth device address Returns ESP_OK: response for AT+CNUM command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: response for AT+CNUM command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: response for AT+CNUM command is sent to lower layer Parameters remote_addr -- [in] remote bluetooth device address number -- [in] registration number number_type -- [in] value of number type from 128-143: national or international, may contain prefix and/or escape digits 144-159: international, includes country code prefix, add "+" if needed 160-175: national, but no prefix nor escape digits service_type -- [in] service type (unknown/voice/fax) Returns ESP_OK: response for AT+CNUM command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_bsir(esp_bd_addr_t remote_addr, esp_hf_in_band_ring_state_t state) Inform HF Client that AG Provided in-band ring tone or not. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_addr -- [in] remote bluetooth device address state -- [in] in-band ring tone state remote_addr -- [in] remote bluetooth device address state -- [in] in-band ring tone state remote_addr -- [in] remote bluetooth device address Returns ESP_OK: information of in-band ring tone is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if arguments are invalid ESP_FAIL: others ESP_OK: information of in-band ring tone is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if arguments are invalid ESP_FAIL: others ESP_OK: information of in-band ring tone is sent to lower layer Parameters remote_addr -- [in] remote bluetooth device address state -- [in] in-band ring tone state Returns ESP_OK: information of in-band ring tone is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if arguments are invalid ESP_FAIL: others esp_err_t esp_hf_ag_answer_call(esp_bd_addr_t remote_addr, int num_active, int num_held, esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, char *number, esp_hf_call_addr_type_t call_addr_type) Answer Incoming Call from AG. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the incoming call call_addr_type -- [in] call address type remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the incoming call call_addr_type -- [in] call address type remote_addr -- [in] remote bluetooth device address Returns ESP_OK: answer incoming call is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: answer incoming call is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: answer incoming call is sent to lower layer Parameters remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the incoming call call_addr_type -- [in] call address type Returns ESP_OK: answer incoming call is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_reject_call(esp_bd_addr_t remote_addr, int num_active, int num_held, esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, char *number, esp_hf_call_addr_type_t call_addr_type) Reject Incoming Call from AG. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the incoming call call_addr_type -- [in] call address type remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the incoming call call_addr_type -- [in] call address type remote_addr -- [in] remote bluetooth device address Returns ESP_OK: reject incoming call is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: reject incoming call is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: reject incoming call is sent to lower layer Parameters remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the incoming call call_addr_type -- [in] call address type Returns ESP_OK: reject incoming call is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_out_call(esp_bd_addr_t remote_addr, int num_active, int num_held, esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, char *number, esp_hf_call_addr_type_t call_addr_type) Initiate a call from AG. As a precondition to use this API, Service Level Connection shall exist with HFP client. If the AG is driven by the HF to call esp_hf_ag_out_call, it needs to response an OK or ERROR to HF. But if the AG is actively calling esp_hf_ag_out_call, it does not need to take a response to HF. Parameters remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the outgoing call call_addr_type -- [in] call address type remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the outgoing call call_addr_type -- [in] call address type remote_addr -- [in] remote bluetooth device address Returns ESP_OK: a call initiation is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: a call initiation is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: a call initiation is sent to lower layer Parameters remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the outgoing call call_addr_type -- [in] call address type Returns ESP_OK: a call initiation is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_end_call(esp_bd_addr_t remote_addr, int num_active, int num_held, esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, char *number, esp_hf_call_addr_type_t call_addr_type) End an ongoing call. As a precondition to use this API, Service Level Connection shall exist with HFP client. Parameters remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the call call_addr_type -- [in] call address type remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the call call_addr_type -- [in] call address type remote_addr -- [in] remote bluetooth device address Returns ESP_OK: end an ongoing call is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: end an ongoing call is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: end an ongoing call is sent to lower layer Parameters remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the call call_addr_type -- [in] call address type Returns ESP_OK: end an ongoing call is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others esp_err_t esp_hf_ag_register_data_callback(esp_hf_incoming_data_cb_t recv, esp_hf_outgoing_data_cb_t send) Register AG data output function. The callback is only used in the case that Voice Over HCI is enabled. Parameters recv -- [in] HFP client incoming data callback function send -- [in] HFP client outgoing data callback function recv -- [in] HFP client incoming data callback function send -- [in] HFP client outgoing data callback function recv -- [in] HFP client incoming data callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer ESP_OK: success Parameters recv -- [in] HFP client incoming data callback function send -- [in] HFP client outgoing data callback function Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer esp_err_t esp_hf_ag_pkt_stat_nums_get(uint16_t sync_conn_handle) Get the number of packets received and sent. This function is only used in the case that Voice Over HCI is enabled and the audio state is connected. When the operation is completed, the callback function will be called with ESP_HF_PKT_STAT_NUMS_GET_EVT. Parameters sync_conn_handle -- [in] the (e)SCO connection handle Returns ESP_OK: if the request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others ESP_OK: if the request is sent successfully Parameters sync_conn_handle -- [in] the (e)SCO connection handle Returns ESP_OK: if the request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others void esp_hf_ag_outgoing_data_ready(void) Trigger the lower-layer to fetch and send audio data. This function is only used in the case that Voice Over HCI is enabled. As a precondition to use this API, Service Level Connection shall exist with HFP client. After this function is called, lower layer will invoke esp_hf_client_outgoing_data_cb_t to fetch data Unions union esp_hf_cb_param_t #include <esp_hf_ag_api.h> HFP AG callback parameters. Public Members struct esp_hf_cb_param_t::hf_conn_stat_param conn_stat AG callback param of ESP_HF_CONNECTION_STATE_EVT struct esp_hf_cb_param_t::hf_conn_stat_param conn_stat AG callback param of ESP_HF_CONNECTION_STATE_EVT struct esp_hf_cb_param_t::hf_audio_stat_param audio_stat AG callback param of ESP_HF_AUDIO_STATE_EVT struct esp_hf_cb_param_t::hf_audio_stat_param audio_stat AG callback param of ESP_HF_AUDIO_STATE_EVT struct esp_hf_cb_param_t::hf_vra_rep_param vra_rep AG callback param of ESP_HF_BVRA_RESPONSE_EVT struct esp_hf_cb_param_t::hf_vra_rep_param vra_rep AG callback param of ESP_HF_BVRA_RESPONSE_EVT struct esp_hf_cb_param_t::hf_volume_control_param volume_control AG callback param of ESP_HF_VOLUME_CONTROL_EVT struct esp_hf_cb_param_t::hf_volume_control_param volume_control AG callback param of ESP_HF_VOLUME_CONTROL_EVT struct esp_hf_cb_param_t::hf_unat_rep_param unat_rep AG callback param of ESP_HF_UNAT_RESPONSE_EVT struct esp_hf_cb_param_t::hf_unat_rep_param unat_rep AG callback param of ESP_HF_UNAT_RESPONSE_EVT struct esp_hf_cb_param_t::hf_out_call_param out_call AG callback param of ESP_HF_DIAL_EVT struct esp_hf_cb_param_t::hf_out_call_param out_call AG callback param of ESP_HF_DIAL_EVT struct esp_hf_cb_param_t::hf_ind_upd_param ind_upd AG callback param of ESP_HF_IND_UPDATE_EVT struct esp_hf_cb_param_t::hf_ind_upd_param ind_upd AG callback param of ESP_HF_IND_UPDATE_EVT struct esp_hf_cb_param_t::hf_cind_rep_param cind_rep AG callback param of ESP_HF_CIND_RESPONSE_EVT struct esp_hf_cb_param_t::hf_cind_rep_param cind_rep AG callback param of ESP_HF_CIND_RESPONSE_EVT struct esp_hf_cb_param_t::hf_cops_rep_param cops_rep AG callback param of ESP_HF_COPS_RESPONSE_EVT struct esp_hf_cb_param_t::hf_cops_rep_param cops_rep AG callback param of ESP_HF_COPS_RESPONSE_EVT struct esp_hf_cb_param_t::hf_clcc_rep_param clcc_rep AG callback param of ESP_HF_CLCC_RESPONSE_EVT struct esp_hf_cb_param_t::hf_clcc_rep_param clcc_rep AG callback param of ESP_HF_CLCC_RESPONSE_EVT struct esp_hf_cb_param_t::hf_cnum_rep_param cnum_rep AG callback param of ESP_HF_CNUM_RESPONSE_EVT struct esp_hf_cb_param_t::hf_cnum_rep_param cnum_rep AG callback param of ESP_HF_CNUM_RESPONSE_EVT struct esp_hf_cb_param_t::hf_vts_rep_param vts_rep AG callback param of ESP_HF_VTS_RESPONSE_EVT struct esp_hf_cb_param_t::hf_vts_rep_param vts_rep AG callback param of ESP_HF_VTS_RESPONSE_EVT struct esp_hf_cb_param_t::hf_nrec_param nrec AG callback param of ESP_HF_NREC_RESPONSE_EVT struct esp_hf_cb_param_t::hf_nrec_param nrec AG callback param of ESP_HF_NREC_RESPONSE_EVT struct esp_hf_cb_param_t::hf_ata_rep_param ata_rep AG callback param of ESP_HF_ATA_RESPONSE_EVT struct esp_hf_cb_param_t::hf_ata_rep_param ata_rep AG callback param of ESP_HF_ATA_RESPONSE_EVT struct esp_hf_cb_param_t::hf_chup_rep_param chup_rep AG callback param of ESP_HF_CHUP_RESPONSE_EVT struct esp_hf_cb_param_t::hf_chup_rep_param chup_rep AG callback param of ESP_HF_CHUP_RESPONSE_EVT struct esp_hf_cb_param_t::hf_wbs_rep_param wbs_rep AG callback param of ESP_HF_WBS_RESPONSE_EVT struct esp_hf_cb_param_t::hf_wbs_rep_param wbs_rep AG callback param of ESP_HF_WBS_RESPONSE_EVT struct esp_hf_cb_param_t::hf_bcs_rep_param bcs_rep AG callback param of ESP_HF_BCS_RESPONSE_EVT struct esp_hf_cb_param_t::hf_bcs_rep_param bcs_rep AG callback param of ESP_HF_BCS_RESPONSE_EVT struct esp_hf_cb_param_t::ag_pkt_status_nums pkt_nums AG callback param of ESP_HF_PKT_STAT_NUMS_GET_EVT struct esp_hf_cb_param_t::ag_pkt_status_nums pkt_nums AG callback param of ESP_HF_PKT_STAT_NUMS_GET_EVT struct ag_pkt_status_nums #include <esp_hf_ag_api.h> ESP_HF_PKT_STAT_NUMS_GET_EVT. Public Members uint32_t rx_total the total number of packets received uint32_t rx_total the total number of packets received uint32_t rx_correct the total number of packets data correctly received uint32_t rx_correct the total number of packets data correctly received uint32_t rx_err the total number of packets data with possible invalid uint32_t rx_err the total number of packets data with possible invalid uint32_t rx_none the total number of packets data no received uint32_t rx_none the total number of packets data no received uint32_t rx_lost the total number of packets data partially lost uint32_t rx_lost the total number of packets data partially lost uint32_t tx_total the total number of packets send uint32_t tx_total the total number of packets send uint32_t tx_discarded the total number of packets send lost uint32_t tx_discarded the total number of packets send lost uint32_t rx_total struct ag_pkt_status_nums #include <esp_hf_ag_api.h> ESP_HF_PKT_STAT_NUMS_GET_EVT. Public Members uint32_t rx_total the total number of packets received uint32_t rx_correct the total number of packets data correctly received uint32_t rx_err the total number of packets data with possible invalid uint32_t rx_none the total number of packets data no received uint32_t rx_lost the total number of packets data partially lost uint32_t tx_total the total number of packets send uint32_t tx_discarded the total number of packets send lost struct hf_ata_rep_param #include <esp_hf_ag_api.h> ESP_HF_ATA_RESPONSE_EVT. struct hf_ata_rep_param #include <esp_hf_ag_api.h> ESP_HF_ATA_RESPONSE_EVT. struct hf_audio_stat_param #include <esp_hf_ag_api.h> ESP_HF_AUDIO_STATE_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address esp_bd_addr_t remote_addr Remote bluetooth device address esp_hf_audio_state_t state Audio connection state esp_hf_audio_state_t state Audio connection state uint16_t sync_conn_handle (e)SCO connection handle uint16_t sync_conn_handle (e)SCO connection handle esp_bd_addr_t remote_addr struct hf_audio_stat_param #include <esp_hf_ag_api.h> ESP_HF_AUDIO_STATE_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address esp_hf_audio_state_t state Audio connection state uint16_t sync_conn_handle (e)SCO connection handle struct hf_bcs_rep_param #include <esp_hf_ag_api.h> ESP_HF_BCS_RESPONSE_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address esp_bd_addr_t remote_addr Remote bluetooth device address esp_hf_wbs_config_t mode codec mode CVSD or mSBC esp_hf_wbs_config_t mode codec mode CVSD or mSBC esp_bd_addr_t remote_addr struct hf_bcs_rep_param #include <esp_hf_ag_api.h> ESP_HF_BCS_RESPONSE_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address esp_hf_wbs_config_t mode codec mode CVSD or mSBC struct hf_chup_rep_param #include <esp_hf_ag_api.h> ESP_HF_CHUP_RESPONSE_EVT. struct hf_chup_rep_param #include <esp_hf_ag_api.h> ESP_HF_CHUP_RESPONSE_EVT. struct hf_cind_rep_param #include <esp_hf_ag_api.h> ESP_HF_CIND_RESPONSE_EVT. struct hf_cind_rep_param #include <esp_hf_ag_api.h> ESP_HF_CIND_RESPONSE_EVT. struct hf_clcc_rep_param #include <esp_hf_ag_api.h> ESP_HF_CLCC_RESPONSE_EVT. struct hf_clcc_rep_param #include <esp_hf_ag_api.h> ESP_HF_CLCC_RESPONSE_EVT. struct hf_cnum_rep_param #include <esp_hf_ag_api.h> ESP_HF_CNUM_RESPONSE_EVT. struct hf_cnum_rep_param #include <esp_hf_ag_api.h> ESP_HF_CNUM_RESPONSE_EVT. struct hf_conn_stat_param #include <esp_hf_ag_api.h> ESP_HF_CONNECTION_STATE_EVT. Public Members esp_bd_addr_t remote_bda Remote bluetooth device address esp_bd_addr_t remote_bda Remote bluetooth device address esp_hf_connection_state_t state Connection state esp_hf_connection_state_t state Connection state uint32_t peer_feat HF supported features uint32_t peer_feat HF supported features uint32_t chld_feat AG supported features on call hold and multiparty services uint32_t chld_feat AG supported features on call hold and multiparty services esp_bd_addr_t remote_bda struct hf_conn_stat_param #include <esp_hf_ag_api.h> ESP_HF_CONNECTION_STATE_EVT. Public Members esp_bd_addr_t remote_bda Remote bluetooth device address esp_hf_connection_state_t state Connection state uint32_t peer_feat HF supported features uint32_t chld_feat AG supported features on call hold and multiparty services struct hf_cops_rep_param #include <esp_hf_ag_api.h> ESP_HF_COPS_RESPONSE_EVT. struct hf_cops_rep_param #include <esp_hf_ag_api.h> ESP_HF_COPS_RESPONSE_EVT. struct hf_ind_upd_param #include <esp_hf_ag_api.h> ESP_HF_IND_UPDATE_EVT. struct hf_ind_upd_param #include <esp_hf_ag_api.h> ESP_HF_IND_UPDATE_EVT. struct hf_nrec_param #include <esp_hf_ag_api.h> ESP_HF_NREC_RESPONSE_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address esp_bd_addr_t remote_addr Remote bluetooth device address esp_hf_nrec_t state NREC enabled or disabled esp_hf_nrec_t state NREC enabled or disabled esp_bd_addr_t remote_addr struct hf_nrec_param #include <esp_hf_ag_api.h> ESP_HF_NREC_RESPONSE_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address esp_hf_nrec_t state NREC enabled or disabled struct hf_out_call_param #include <esp_hf_ag_api.h> ESP_HF_DIAL_EVT. Public Members esp_bd_addr_t remote_addr remote bluetooth device address esp_bd_addr_t remote_addr remote bluetooth device address esp_hf_dial_type_t type dial type esp_hf_dial_type_t type dial type char *num_or_loc location in phone memory char *num_or_loc location in phone memory esp_bd_addr_t remote_addr struct hf_out_call_param #include <esp_hf_ag_api.h> ESP_HF_DIAL_EVT. Public Members esp_bd_addr_t remote_addr remote bluetooth device address esp_hf_dial_type_t type dial type char *num_or_loc location in phone memory struct hf_unat_rep_param #include <esp_hf_ag_api.h> ESP_HF_UNAT_RESPONSE_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address esp_bd_addr_t remote_addr Remote bluetooth device address char *unat Unknown AT command string char *unat Unknown AT command string esp_bd_addr_t remote_addr struct hf_unat_rep_param #include <esp_hf_ag_api.h> ESP_HF_UNAT_RESPONSE_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address char *unat Unknown AT command string struct hf_volume_control_param #include <esp_hf_ag_api.h> ESP_HF_VOLUME_CONTROL_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address esp_bd_addr_t remote_addr Remote bluetooth device address esp_hf_volume_type_t type Volume control target, speaker or microphone esp_hf_volume_type_t type Volume control target, speaker or microphone int volume Gain, ranges from 0 to 15 int volume Gain, ranges from 0 to 15 esp_bd_addr_t remote_addr struct hf_volume_control_param #include <esp_hf_ag_api.h> ESP_HF_VOLUME_CONTROL_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address esp_hf_volume_type_t type Volume control target, speaker or microphone int volume Gain, ranges from 0 to 15 struct hf_vra_rep_param #include <esp_hf_ag_api.h> ESP_HF_BVRA_RESPONSE_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address esp_bd_addr_t remote_addr Remote bluetooth device address esp_hf_vr_state_t value Voice recognition state esp_hf_vr_state_t value Voice recognition state esp_bd_addr_t remote_addr struct hf_vra_rep_param #include <esp_hf_ag_api.h> ESP_HF_BVRA_RESPONSE_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address esp_hf_vr_state_t value Voice recognition state struct hf_vts_rep_param #include <esp_hf_ag_api.h> ESP_HF_VTS_RESPONSE_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address esp_bd_addr_t remote_addr Remote bluetooth device address char *code MTF code from HF Client char *code MTF code from HF Client esp_bd_addr_t remote_addr struct hf_vts_rep_param #include <esp_hf_ag_api.h> ESP_HF_VTS_RESPONSE_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address char *code MTF code from HF Client struct hf_wbs_rep_param #include <esp_hf_ag_api.h> ESP_HF_WBS_RESPONSE_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address esp_bd_addr_t remote_addr Remote bluetooth device address esp_hf_wbs_config_t codec codec mode CVSD or mSBC esp_hf_wbs_config_t codec codec mode CVSD or mSBC esp_bd_addr_t remote_addr struct hf_wbs_rep_param #include <esp_hf_ag_api.h> ESP_HF_WBS_RESPONSE_EVT. Public Members esp_bd_addr_t remote_addr Remote bluetooth device address esp_hf_wbs_config_t codec codec mode CVSD or mSBC struct esp_hf_cb_param_t::hf_conn_stat_param conn_stat Macros ESP_HF_PEER_FEAT_3WAY ESP_HF_PEER_FEAT_ECNR ESP_HF_PEER_FEAT_VREC ESP_HF_PEER_FEAT_INBAND ESP_HF_PEER_FEAT_VTAG ESP_HF_PEER_FEAT_REJECT ESP_HF_PEER_FEAT_ECS ESP_HF_PEER_FEAT_ECC ESP_HF_PEER_FEAT_EXTERR ESP_HF_PEER_FEAT_CODEC ESP_HF_PEER_FEAT_HF_IND ESP_HF_PEER_FEAT_ESCO_S4 ESP_HF_CHLD_FEAT_REL ESP_HF_CHLD_FEAT_REL_ACC ESP_HF_CHLD_FEAT_REL_X ESP_HF_CHLD_FEAT_HOLD_ACC ESP_HF_CHLD_FEAT_PRIV_X ESP_HF_CHLD_FEAT_MERGE ESP_HF_CHLD_FEAT_MERGE_DETACH Type Definitions typedef void (*esp_hf_incoming_data_cb_t)(const uint8_t *buf, uint32_t len) AG incoming data callback function, the callback is useful in case of Voice Over HCI. Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer is allocated inside bluetooth protocol stack and will be released after invoke of the callback is finished. Param len [in] : size(in bytes) in buf Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer is allocated inside bluetooth protocol stack and will be released after invoke of the callback is finished. Param len [in] : size(in bytes) in buf typedef uint32_t (*esp_hf_outgoing_data_cb_t)(uint8_t *buf, uint32_t len) AG outgoing data callback function, the callback is useful in case of Voice Over HCI. Once audio connection is set up and the application layer has prepared data to send, the lower layer will call this function to read data and then send. This callback is supposed to be implemented as non-blocking, and if data is not enough, return value 0 is supposed. Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer is allocated inside bluetooth protocol stack and will be released after invoke of the callback is finished. Param len [in] : size(in bytes) in buf Return length of data successfully read Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer is allocated inside bluetooth protocol stack and will be released after invoke of the callback is finished. Param len [in] : size(in bytes) in buf Return length of data successfully read typedef void (*esp_hf_cb_t)(esp_hf_cb_event_t event, esp_hf_cb_param_t *param) HF AG callback function type. Param event : Event type Param param : Pointer to callback parameter Param event : Event type Param param : Pointer to callback parameter Enumerations enum esp_hf_cb_event_t HF callback events. Values: enumerator ESP_HF_CONNECTION_STATE_EVT Connection state changed event enumerator ESP_HF_CONNECTION_STATE_EVT Connection state changed event enumerator ESP_HF_AUDIO_STATE_EVT Audio connection state change event enumerator ESP_HF_AUDIO_STATE_EVT Audio connection state change event enumerator ESP_HF_BVRA_RESPONSE_EVT Voice recognition state change event enumerator ESP_HF_BVRA_RESPONSE_EVT Voice recognition state change event enumerator ESP_HF_VOLUME_CONTROL_EVT Audio volume control command from HF Client, provided by +VGM or +VGS message enumerator ESP_HF_VOLUME_CONTROL_EVT Audio volume control command from HF Client, provided by +VGM or +VGS message enumerator ESP_HF_UNAT_RESPONSE_EVT Unknown AT cmd Response enumerator ESP_HF_UNAT_RESPONSE_EVT Unknown AT cmd Response enumerator ESP_HF_IND_UPDATE_EVT Indicator Update Event enumerator ESP_HF_IND_UPDATE_EVT Indicator Update Event enumerator ESP_HF_CIND_RESPONSE_EVT Call And Device Indicator Response enumerator ESP_HF_CIND_RESPONSE_EVT Call And Device Indicator Response enumerator ESP_HF_COPS_RESPONSE_EVT Current operator information enumerator ESP_HF_COPS_RESPONSE_EVT Current operator information enumerator ESP_HF_CLCC_RESPONSE_EVT List of current calls notification enumerator ESP_HF_CLCC_RESPONSE_EVT List of current calls notification enumerator ESP_HF_CNUM_RESPONSE_EVT Subscriber information response from HF Client enumerator ESP_HF_CNUM_RESPONSE_EVT Subscriber information response from HF Client enumerator ESP_HF_VTS_RESPONSE_EVT Enable or not DTMF enumerator ESP_HF_VTS_RESPONSE_EVT Enable or not DTMF enumerator ESP_HF_NREC_RESPONSE_EVT Enable or not NREC enumerator ESP_HF_NREC_RESPONSE_EVT Enable or not NREC enumerator ESP_HF_ATA_RESPONSE_EVT Answer an Incoming Call enumerator ESP_HF_ATA_RESPONSE_EVT Answer an Incoming Call enumerator ESP_HF_CHUP_RESPONSE_EVT Reject an Incoming Call enumerator ESP_HF_CHUP_RESPONSE_EVT Reject an Incoming Call enumerator ESP_HF_DIAL_EVT Origin an outgoing call with specific number or the dial the last number enumerator ESP_HF_DIAL_EVT Origin an outgoing call with specific number or the dial the last number enumerator ESP_HF_WBS_RESPONSE_EVT Codec Status enumerator ESP_HF_WBS_RESPONSE_EVT Codec Status enumerator ESP_HF_BCS_RESPONSE_EVT Final Codec Choice enumerator ESP_HF_BCS_RESPONSE_EVT Final Codec Choice enumerator ESP_HF_PKT_STAT_NUMS_GET_EVT Request number of packet different status enumerator ESP_HF_PKT_STAT_NUMS_GET_EVT Request number of packet different status enumerator ESP_HF_CONNECTION_STATE_EVT
HFP AG API API Reference Header File components/bt/host/bluedroid/api/include/api/esp_hf_ag_api.h This header file can be included with: #include "esp_hf_ag_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_hf_ag_register_callback(esp_hf_cb_t callback) Register application callback function to HFP AG module. This function should be called only after esp_bluedroid_enable() completes successfully. - Parameters callback -- [in] HFP AG event callback function - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer - - esp_err_t esp_hf_ag_init(void) Initialize the bluetooth HF AG module. This function should be called after esp_bluedroid_enable() completes successfully. - Returns ESP_OK: if the initialization request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_deinit(void) De-initialize for HF AG module. This function should be called only after esp_bluedroid_enable() completes successfully. - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_slc_connect(esp_bd_addr_t remote_bda) To establish a Service Level Connection to remote bluetooth HFP client device. This function must be called after esp_hf_ag_init() and before esp_hf_ag_deinit(). - Parameters remote_bda -- [in] remote bluetooth HFP client device address - Returns ESP_OK: connect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_slc_disconnect(esp_bd_addr_t remote_bda) Disconnect from the remote HFP client. This function must be called after esp_hf_ag_init() and before esp_hf_ag_deinit(). - Parameters remote_bda -- [in] remote bluetooth device address - Returns ESP_OK: disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_audio_connect(esp_bd_addr_t remote_bda) Create audio connection with remote HFP client. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_bda -- [in] remote bluetooth device address - Returns ESP_OK: audio connect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_audio_disconnect(esp_bd_addr_t remote_bda) Release the established audio connection with remote HFP client. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_bda -- [in] remote bluetooth device address - Returns ESP_OK: audio disconnect request is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_vra_control(esp_bd_addr_t remote_bda, esp_hf_vr_state_t value) Response of Volume Recognition Command(AT+VRA) from HFP client. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_bda -- [in] the device address of voice recognition initiator value -- [in] 0 - voice recognition disabled, 1- voice recognition enabled - - Returns ESP_OK: response of volume recognition is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_volume_control(esp_bd_addr_t remote_bda, esp_hf_volume_control_target_t type, int volume) Volume synchronization with HFP client. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_bda -- [in] remote bluetooth device address type -- [in] volume control target, speaker or microphone volume -- [in] gain of the speaker of microphone, ranges 0 to 15 - - Returns ESP_OK: volume synchronization control is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if arguments are invalid ESP_FAIL: others - - esp_err_t esp_hf_ag_unknown_at_send(esp_bd_addr_t remote_addr, char *unat) Handle Unknown AT command from HFP Client. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_addr -- [in] remote bluetooth device address unat -- [in] User AT command response to HF Client. It will response "ERROR" by default if unat is NULL. - - Returns ESP_OK: response of unknown AT command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_cmee_send(esp_bd_addr_t remote_bda, esp_hf_at_response_code_t response_code, esp_hf_cme_err_t error_code) Unsolicited send extend AT error code to HFP Client. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_bda -- [in] remote bluetooth device address response_code -- [in] AT command response code error_code -- [in] CME error code - - Returns ESP_OK: extend error code is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_devices_status_indchange(esp_bd_addr_t remote_addr, esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, esp_hf_network_state_t ntk_state, int signal) Unsolicited send device status notification to HFP Client. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_addr -- [in] remote bluetooth device address call_state -- [in] call state call_setup_state -- [in] call setup state ntk_state -- [in] network service state signal -- [in] signal strength from 0 to 5 - - Returns ESP_OK: device status notification is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if arguments are invalid ESP_FAIL: others - - esp_err_t esp_hf_ag_ciev_report(esp_bd_addr_t remote_addr, esp_hf_ciev_report_type_t ind_type, int value) Send indicator report "+CIEV: <ind> <value>" to HFP Client. "CIEV" means “indicator events reporting", and all indicator types can be sent one type at a time. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_addr -- [in] remote bluetooth device address ind_type -- [in] indicator type value -- [in] indicator value - - Returns ESP_OK: indicator report is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_cind_response(esp_bd_addr_t remote_addr, esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, esp_hf_network_state_t ntk_state, int signal, esp_hf_roaming_status_t roam, int batt_lev, esp_hf_call_held_status_t call_held_status) Response to device individual indicators to HFP Client. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_addr -- [in] remote bluetooth device address call_state -- [in] call state call_setup_state -- [in] call setup state ntk_state -- [in] network service state signal -- [in] signal strength from 0 to 5 roam -- [in] roam state batt_lev -- [in] battery level from 0 to 5 call_held_status -- [in] call held status - - Returns ESP_OK: response to device individual indicators is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if the arguments are invalid ESP_FAIL: others - - esp_err_t esp_hf_ag_cops_response(esp_bd_addr_t remote_addr, char *name) Reponse for AT+COPS command from HF Client. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_addr -- [in] remote bluetooth device address name -- [in] current operator name - - Returns ESP_OK: reponse for AT+COPS command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_clcc_response(esp_bd_addr_t remote_addr, int index, esp_hf_current_call_direction_t dir, esp_hf_current_call_status_t current_call_state, esp_hf_current_call_mode_t mode, esp_hf_current_call_mpty_type_t mpty, char *number, esp_hf_call_addr_type_t type) Response to AT+CLCC command from HFP Client. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_addr -- [in] remote bluetooth device address index -- [in] the index of current call, starting with 1, finishing response with 0 (send OK) dir -- [in] call direction (incoming/outgoing) current_call_state -- [in] current call state mode -- [in] current call mode (voice/data/fax) mpty -- [in] single or multi type number -- [in] current call number type -- [in] international type or unknow - - Returns ESP_OK: response to AT+CLCC command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_cnum_response(esp_bd_addr_t remote_addr, char *number, int number_type, esp_hf_subscriber_service_type_t service_type) Response for AT+CNUM command from HF Client. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_addr -- [in] remote bluetooth device address number -- [in] registration number number_type -- [in] value of number type from 128-143: national or international, may contain prefix and/or escape digits 144-159: international, includes country code prefix, add "+" if needed 160-175: national, but no prefix nor escape digits service_type -- [in] service type (unknown/voice/fax) - - Returns ESP_OK: response for AT+CNUM command is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_bsir(esp_bd_addr_t remote_addr, esp_hf_in_band_ring_state_t state) Inform HF Client that AG Provided in-band ring tone or not. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_addr -- [in] remote bluetooth device address state -- [in] in-band ring tone state - - Returns ESP_OK: information of in-band ring tone is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_ERR_INVALID_ARG: if arguments are invalid ESP_FAIL: others - - esp_err_t esp_hf_ag_answer_call(esp_bd_addr_t remote_addr, int num_active, int num_held, esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, char *number, esp_hf_call_addr_type_t call_addr_type) Answer Incoming Call from AG. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the incoming call call_addr_type -- [in] call address type - - Returns ESP_OK: answer incoming call is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_reject_call(esp_bd_addr_t remote_addr, int num_active, int num_held, esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, char *number, esp_hf_call_addr_type_t call_addr_type) Reject Incoming Call from AG. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the incoming call call_addr_type -- [in] call address type - - Returns ESP_OK: reject incoming call is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_out_call(esp_bd_addr_t remote_addr, int num_active, int num_held, esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, char *number, esp_hf_call_addr_type_t call_addr_type) Initiate a call from AG. As a precondition to use this API, Service Level Connection shall exist with HFP client. If the AG is driven by the HF to call esp_hf_ag_out_call, it needs to response an OK or ERROR to HF. But if the AG is actively calling esp_hf_ag_out_call, it does not need to take a response to HF. - Parameters remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the outgoing call call_addr_type -- [in] call address type - - Returns ESP_OK: a call initiation is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_end_call(esp_bd_addr_t remote_addr, int num_active, int num_held, esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, char *number, esp_hf_call_addr_type_t call_addr_type) End an ongoing call. As a precondition to use this API, Service Level Connection shall exist with HFP client. - Parameters remote_addr -- [in] remote bluetooth device address num_active -- [in] the number of active call num_held -- [in] the number of held call call_state -- [in] call state call_setup_state -- [in] call setup state number -- [in] number of the call call_addr_type -- [in] call address type - - Returns ESP_OK: end an ongoing call is sent to lower layer ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - esp_err_t esp_hf_ag_register_data_callback(esp_hf_incoming_data_cb_t recv, esp_hf_outgoing_data_cb_t send) Register AG data output function. The callback is only used in the case that Voice Over HCI is enabled. - Parameters recv -- [in] HFP client incoming data callback function send -- [in] HFP client outgoing data callback function - - Returns ESP_OK: success ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: if callback is a NULL function pointer - - esp_err_t esp_hf_ag_pkt_stat_nums_get(uint16_t sync_conn_handle) Get the number of packets received and sent. This function is only used in the case that Voice Over HCI is enabled and the audio state is connected. When the operation is completed, the callback function will be called with ESP_HF_PKT_STAT_NUMS_GET_EVT. - Parameters sync_conn_handle -- [in] the (e)SCO connection handle - Returns ESP_OK: if the request is sent successfully ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled ESP_FAIL: others - - void esp_hf_ag_outgoing_data_ready(void) Trigger the lower-layer to fetch and send audio data. This function is only used in the case that Voice Over HCI is enabled. As a precondition to use this API, Service Level Connection shall exist with HFP client. After this function is called, lower layer will invoke esp_hf_client_outgoing_data_cb_t to fetch data Unions - union esp_hf_cb_param_t - #include <esp_hf_ag_api.h> HFP AG callback parameters. Public Members - struct esp_hf_cb_param_t::hf_conn_stat_param conn_stat AG callback param of ESP_HF_CONNECTION_STATE_EVT - struct esp_hf_cb_param_t::hf_audio_stat_param audio_stat AG callback param of ESP_HF_AUDIO_STATE_EVT - struct esp_hf_cb_param_t::hf_vra_rep_param vra_rep AG callback param of ESP_HF_BVRA_RESPONSE_EVT - struct esp_hf_cb_param_t::hf_volume_control_param volume_control AG callback param of ESP_HF_VOLUME_CONTROL_EVT - struct esp_hf_cb_param_t::hf_unat_rep_param unat_rep AG callback param of ESP_HF_UNAT_RESPONSE_EVT - struct esp_hf_cb_param_t::hf_out_call_param out_call AG callback param of ESP_HF_DIAL_EVT - struct esp_hf_cb_param_t::hf_ind_upd_param ind_upd AG callback param of ESP_HF_IND_UPDATE_EVT - struct esp_hf_cb_param_t::hf_cind_rep_param cind_rep AG callback param of ESP_HF_CIND_RESPONSE_EVT - struct esp_hf_cb_param_t::hf_cops_rep_param cops_rep AG callback param of ESP_HF_COPS_RESPONSE_EVT - struct esp_hf_cb_param_t::hf_clcc_rep_param clcc_rep AG callback param of ESP_HF_CLCC_RESPONSE_EVT - struct esp_hf_cb_param_t::hf_cnum_rep_param cnum_rep AG callback param of ESP_HF_CNUM_RESPONSE_EVT - struct esp_hf_cb_param_t::hf_vts_rep_param vts_rep AG callback param of ESP_HF_VTS_RESPONSE_EVT - struct esp_hf_cb_param_t::hf_nrec_param nrec AG callback param of ESP_HF_NREC_RESPONSE_EVT - struct esp_hf_cb_param_t::hf_ata_rep_param ata_rep AG callback param of ESP_HF_ATA_RESPONSE_EVT - struct esp_hf_cb_param_t::hf_chup_rep_param chup_rep AG callback param of ESP_HF_CHUP_RESPONSE_EVT - struct esp_hf_cb_param_t::hf_wbs_rep_param wbs_rep AG callback param of ESP_HF_WBS_RESPONSE_EVT - struct esp_hf_cb_param_t::hf_bcs_rep_param bcs_rep AG callback param of ESP_HF_BCS_RESPONSE_EVT - struct esp_hf_cb_param_t::ag_pkt_status_nums pkt_nums AG callback param of ESP_HF_PKT_STAT_NUMS_GET_EVT - struct ag_pkt_status_nums - #include <esp_hf_ag_api.h> ESP_HF_PKT_STAT_NUMS_GET_EVT. Public Members - uint32_t rx_total the total number of packets received - uint32_t rx_correct the total number of packets data correctly received - uint32_t rx_err the total number of packets data with possible invalid - uint32_t rx_none the total number of packets data no received - uint32_t rx_lost the total number of packets data partially lost - uint32_t tx_total the total number of packets send - uint32_t tx_discarded the total number of packets send lost - uint32_t rx_total - struct hf_ata_rep_param - #include <esp_hf_ag_api.h> ESP_HF_ATA_RESPONSE_EVT. - struct hf_audio_stat_param - #include <esp_hf_ag_api.h> ESP_HF_AUDIO_STATE_EVT. Public Members - esp_bd_addr_t remote_addr Remote bluetooth device address - esp_hf_audio_state_t state Audio connection state - uint16_t sync_conn_handle (e)SCO connection handle - esp_bd_addr_t remote_addr - struct hf_bcs_rep_param - #include <esp_hf_ag_api.h> ESP_HF_BCS_RESPONSE_EVT. Public Members - esp_bd_addr_t remote_addr Remote bluetooth device address - esp_hf_wbs_config_t mode codec mode CVSD or mSBC - esp_bd_addr_t remote_addr - struct hf_chup_rep_param - #include <esp_hf_ag_api.h> ESP_HF_CHUP_RESPONSE_EVT. - struct hf_cind_rep_param - #include <esp_hf_ag_api.h> ESP_HF_CIND_RESPONSE_EVT. - struct hf_clcc_rep_param - #include <esp_hf_ag_api.h> ESP_HF_CLCC_RESPONSE_EVT. - struct hf_cnum_rep_param - #include <esp_hf_ag_api.h> ESP_HF_CNUM_RESPONSE_EVT. - struct hf_conn_stat_param - #include <esp_hf_ag_api.h> ESP_HF_CONNECTION_STATE_EVT. Public Members - esp_bd_addr_t remote_bda Remote bluetooth device address - esp_hf_connection_state_t state Connection state - uint32_t peer_feat HF supported features - uint32_t chld_feat AG supported features on call hold and multiparty services - esp_bd_addr_t remote_bda - struct hf_cops_rep_param - #include <esp_hf_ag_api.h> ESP_HF_COPS_RESPONSE_EVT. - struct hf_ind_upd_param - #include <esp_hf_ag_api.h> ESP_HF_IND_UPDATE_EVT. - struct hf_nrec_param - #include <esp_hf_ag_api.h> ESP_HF_NREC_RESPONSE_EVT. Public Members - esp_bd_addr_t remote_addr Remote bluetooth device address - esp_hf_nrec_t state NREC enabled or disabled - esp_bd_addr_t remote_addr - struct hf_out_call_param - #include <esp_hf_ag_api.h> ESP_HF_DIAL_EVT. Public Members - esp_bd_addr_t remote_addr remote bluetooth device address - esp_hf_dial_type_t type dial type - char *num_or_loc location in phone memory - esp_bd_addr_t remote_addr - struct hf_unat_rep_param - #include <esp_hf_ag_api.h> ESP_HF_UNAT_RESPONSE_EVT. Public Members - esp_bd_addr_t remote_addr Remote bluetooth device address - char *unat Unknown AT command string - esp_bd_addr_t remote_addr - struct hf_volume_control_param - #include <esp_hf_ag_api.h> ESP_HF_VOLUME_CONTROL_EVT. Public Members - esp_bd_addr_t remote_addr Remote bluetooth device address - esp_hf_volume_type_t type Volume control target, speaker or microphone - int volume Gain, ranges from 0 to 15 - esp_bd_addr_t remote_addr - struct hf_vra_rep_param - #include <esp_hf_ag_api.h> ESP_HF_BVRA_RESPONSE_EVT. Public Members - esp_bd_addr_t remote_addr Remote bluetooth device address - esp_hf_vr_state_t value Voice recognition state - esp_bd_addr_t remote_addr - struct hf_vts_rep_param - #include <esp_hf_ag_api.h> ESP_HF_VTS_RESPONSE_EVT. Public Members - esp_bd_addr_t remote_addr Remote bluetooth device address - char *code MTF code from HF Client - esp_bd_addr_t remote_addr - struct hf_wbs_rep_param - #include <esp_hf_ag_api.h> ESP_HF_WBS_RESPONSE_EVT. Public Members - esp_bd_addr_t remote_addr Remote bluetooth device address - esp_hf_wbs_config_t codec codec mode CVSD or mSBC - esp_bd_addr_t remote_addr - struct esp_hf_cb_param_t::hf_conn_stat_param conn_stat Macros - ESP_HF_PEER_FEAT_3WAY - ESP_HF_PEER_FEAT_ECNR - ESP_HF_PEER_FEAT_VREC - ESP_HF_PEER_FEAT_INBAND - ESP_HF_PEER_FEAT_VTAG - ESP_HF_PEER_FEAT_REJECT - ESP_HF_PEER_FEAT_ECS - ESP_HF_PEER_FEAT_ECC - ESP_HF_PEER_FEAT_EXTERR - ESP_HF_PEER_FEAT_CODEC - ESP_HF_PEER_FEAT_HF_IND - ESP_HF_PEER_FEAT_ESCO_S4 - ESP_HF_CHLD_FEAT_REL - ESP_HF_CHLD_FEAT_REL_ACC - ESP_HF_CHLD_FEAT_REL_X - ESP_HF_CHLD_FEAT_HOLD_ACC - ESP_HF_CHLD_FEAT_PRIV_X - ESP_HF_CHLD_FEAT_MERGE - ESP_HF_CHLD_FEAT_MERGE_DETACH Type Definitions - typedef void (*esp_hf_incoming_data_cb_t)(const uint8_t *buf, uint32_t len) AG incoming data callback function, the callback is useful in case of Voice Over HCI. - Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer is allocated inside bluetooth protocol stack and will be released after invoke of the callback is finished. - Param len [in] : size(in bytes) in buf - typedef uint32_t (*esp_hf_outgoing_data_cb_t)(uint8_t *buf, uint32_t len) AG outgoing data callback function, the callback is useful in case of Voice Over HCI. Once audio connection is set up and the application layer has prepared data to send, the lower layer will call this function to read data and then send. This callback is supposed to be implemented as non-blocking, and if data is not enough, return value 0 is supposed. - Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer is allocated inside bluetooth protocol stack and will be released after invoke of the callback is finished. - Param len [in] : size(in bytes) in buf - Return length of data successfully read - typedef void (*esp_hf_cb_t)(esp_hf_cb_event_t event, esp_hf_cb_param_t *param) HF AG callback function type. - Param event : Event type - Param param : Pointer to callback parameter Enumerations - enum esp_hf_cb_event_t HF callback events. Values: - enumerator ESP_HF_CONNECTION_STATE_EVT Connection state changed event - enumerator ESP_HF_AUDIO_STATE_EVT Audio connection state change event - enumerator ESP_HF_BVRA_RESPONSE_EVT Voice recognition state change event - enumerator ESP_HF_VOLUME_CONTROL_EVT Audio volume control command from HF Client, provided by +VGM or +VGS message - enumerator ESP_HF_UNAT_RESPONSE_EVT Unknown AT cmd Response - enumerator ESP_HF_IND_UPDATE_EVT Indicator Update Event - enumerator ESP_HF_CIND_RESPONSE_EVT Call And Device Indicator Response - enumerator ESP_HF_COPS_RESPONSE_EVT Current operator information - enumerator ESP_HF_CLCC_RESPONSE_EVT List of current calls notification - enumerator ESP_HF_CNUM_RESPONSE_EVT Subscriber information response from HF Client - enumerator ESP_HF_VTS_RESPONSE_EVT Enable or not DTMF - enumerator ESP_HF_NREC_RESPONSE_EVT Enable or not NREC - enumerator ESP_HF_ATA_RESPONSE_EVT Answer an Incoming Call - enumerator ESP_HF_CHUP_RESPONSE_EVT Reject an Incoming Call - enumerator ESP_HF_DIAL_EVT Origin an outgoing call with specific number or the dial the last number - enumerator ESP_HF_WBS_RESPONSE_EVT Codec Status - enumerator ESP_HF_BCS_RESPONSE_EVT Final Codec Choice - enumerator ESP_HF_PKT_STAT_NUMS_GET_EVT Request number of packet different status - enumerator ESP_HF_CONNECTION_STATE_EVT
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_hf_ag.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Bluetooth® HID Device API
null
espressif.com
2016-01-01
e2caa5a2e23b941
null
null
Bluetooth® HID Device API Overview A Bluetooth HID device is a device providing the service of human or other data input and output to and from a Bluetooth HID Host. Users can use the Bluetooth HID Device APIs to make devices like keyboards, mice, joysticks and so on. Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the following application: This is an example of Bluetooth HID mouse device. The device running this example can be discovered and connected by a Bluetooth HID Host device such as a PC, and the pointer will move left and right after HID connection is established - bluetooth/bluedroid/classic_bt/bt_hid_mouse_device API Reference Header File This header file can be included with: #include "esp_hidd_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_bt_hid_device_register_callback(esp_hd_cb_t callback) This function is called to init callbacks with HID device module. Parameters callback -- [in] pointer to the init callback function. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters callback -- [in] pointer to the init callback function. Returns ESP_OK: success other: failed esp_err_t esp_bt_hid_device_init(void) Initializes HIDD interface. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_register_callback. When the operation is complete, the callback function will be called with ESP_HIDD_INIT_EVT. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Returns ESP_OK: success other: failed esp_err_t esp_bt_hid_device_deinit(void) De-initializes HIDD interface. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_DEINIT_EVT. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Returns ESP_OK: success other: failed esp_err_t esp_bt_hid_device_register_app(esp_hidd_app_param_t *app_param, esp_hidd_qos_param_t *in_qos, esp_hidd_qos_param_t *out_qos) Registers HIDD parameters with SDP and sets l2cap Quality of Service. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_REGISTER_APP_EVT. Parameters app_param -- [in] HIDD parameters in_qos -- [in] incoming QoS parameters out_qos -- [in] outgoing QoS parameters app_param -- [in] HIDD parameters in_qos -- [in] incoming QoS parameters out_qos -- [in] outgoing QoS parameters app_param -- [in] HIDD parameters Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters app_param -- [in] HIDD parameters in_qos -- [in] incoming QoS parameters out_qos -- [in] outgoing QoS parameters Returns ESP_OK: success other: failed esp_err_t esp_bt_hid_device_unregister_app(void) Removes HIDD parameters from SDP and resets l2cap Quality of Service. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_UNREGISTER_APP_EVT. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Returns ESP_OK: success other: failed esp_err_t esp_bt_hid_device_connect(esp_bd_addr_t bd_addr) Connects to the peer HID Host with virtual cable. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_OPEN_EVT. Parameters bd_addr -- [in] Remote host bluetooth device address. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters bd_addr -- [in] Remote host bluetooth device address. Returns ESP_OK: success other: failed esp_err_t esp_bt_hid_device_disconnect(void) Disconnects from the currently connected HID Host. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_CLOSE_EVT. Note The disconnect operation will not remove the virtually cabled device. If the connect request from the different HID Host, it will reject the request. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Returns ESP_OK: success other: failed esp_err_t esp_bt_hid_device_send_report(esp_hidd_report_type_t type, uint8_t id, uint16_t len, uint8_t *data) Sends HID report to the currently connected HID Host. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_SEND_REPORT_EVT. Parameters type -- [in] type of report id -- [in] report id as defined by descriptor len -- [in] length of report data -- [in] report data type -- [in] type of report id -- [in] report id as defined by descriptor len -- [in] length of report data -- [in] report data type -- [in] type of report Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters type -- [in] type of report id -- [in] report id as defined by descriptor len -- [in] length of report data -- [in] report data Returns ESP_OK: success other: failed esp_err_t esp_bt_hid_device_report_error(esp_hidd_handshake_error_t error) Sends HID Handshake with error info for invalid set_report to the currently connected HID Host. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_REPORT_ERR_EVT. Parameters error -- [in] type of error Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters error -- [in] type of error Returns ESP_OK: success other: failed esp_err_t esp_bt_hid_device_virtual_cable_unplug(void) Remove the virtually cabled device. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_VC_UNPLUG_EVT. Note If the connection exists, then HID Device will send a VIRTUAL_CABLE_UNPLUG control command to the peer HID Host, and the connection will be destroyed. If the connection does not exist, then HID Device will only unplug on it's single side. Once the unplug operation is success, the related pairing and bonding information will be removed, then the HID Device can accept connection request from the different HID Host, Returns - ESP_OK: success other: failed other: failed other: failed Returns - ESP_OK: success other: failed Unions union esp_hidd_cb_param_t #include <esp_hidd_api.h> HID device callback parameters union. Public Members struct esp_hidd_cb_param_t::hidd_init_evt_param init HIDD callback param of ESP_HIDD_INIT_EVT struct esp_hidd_cb_param_t::hidd_init_evt_param init HIDD callback param of ESP_HIDD_INIT_EVT struct esp_hidd_cb_param_t::hidd_deinit_evt_param deinit HIDD callback param of ESP_HIDD_DEINIT_EVT struct esp_hidd_cb_param_t::hidd_deinit_evt_param deinit HIDD callback param of ESP_HIDD_DEINIT_EVT struct esp_hidd_cb_param_t::hidd_register_app_evt_param register_app HIDD callback param of ESP_HIDD_REGISTER_APP_EVT struct esp_hidd_cb_param_t::hidd_register_app_evt_param register_app HIDD callback param of ESP_HIDD_REGISTER_APP_EVT struct esp_hidd_cb_param_t::hidd_unregister_app_evt_param unregister_app HIDD callback param of ESP_HIDD_UNREGISTER_APP_EVT struct esp_hidd_cb_param_t::hidd_unregister_app_evt_param unregister_app HIDD callback param of ESP_HIDD_UNREGISTER_APP_EVT struct esp_hidd_cb_param_t::hidd_open_evt_param open HIDD callback param of ESP_HIDD_OPEN_EVT struct esp_hidd_cb_param_t::hidd_open_evt_param open HIDD callback param of ESP_HIDD_OPEN_EVT struct esp_hidd_cb_param_t::hidd_close_evt_param close HIDD callback param of ESP_HIDD_CLOSE_EVT struct esp_hidd_cb_param_t::hidd_close_evt_param close HIDD callback param of ESP_HIDD_CLOSE_EVT struct esp_hidd_cb_param_t::hidd_send_report_evt_param send_report HIDD callback param of ESP_HIDD_SEND_REPORT_EVT struct esp_hidd_cb_param_t::hidd_send_report_evt_param send_report HIDD callback param of ESP_HIDD_SEND_REPORT_EVT struct esp_hidd_cb_param_t::hidd_report_err_evt_param report_err HIDD callback param of ESP_HIDD_REPORT_ERR_EVT struct esp_hidd_cb_param_t::hidd_report_err_evt_param report_err HIDD callback param of ESP_HIDD_REPORT_ERR_EVT struct esp_hidd_cb_param_t::hidd_get_report_evt_param get_report HIDD callback param of ESP_HIDD_GET_REPORT_EVT struct esp_hidd_cb_param_t::hidd_get_report_evt_param get_report HIDD callback param of ESP_HIDD_GET_REPORT_EVT struct esp_hidd_cb_param_t::hidd_set_report_evt_param set_report HIDD callback param of ESP_HIDD_SET_REPORT_EVT struct esp_hidd_cb_param_t::hidd_set_report_evt_param set_report HIDD callback param of ESP_HIDD_SET_REPORT_EVT struct esp_hidd_cb_param_t::hidd_set_protocol_evt_param set_protocol HIDD callback param of ESP_HIDD_SET_PROTOCOL_EVT struct esp_hidd_cb_param_t::hidd_set_protocol_evt_param set_protocol HIDD callback param of ESP_HIDD_SET_PROTOCOL_EVT struct esp_hidd_cb_param_t::hidd_intr_data_evt_param intr_data HIDD callback param of ESP_HIDD_INTR_DATA_EVT struct esp_hidd_cb_param_t::hidd_intr_data_evt_param intr_data HIDD callback param of ESP_HIDD_INTR_DATA_EVT struct esp_hidd_cb_param_t::hidd_vc_unplug_param vc_unplug HIDD callback param of ESP_HIDD_VC_UNPLUG_EVT struct esp_hidd_cb_param_t::hidd_vc_unplug_param vc_unplug HIDD callback param of ESP_HIDD_VC_UNPLUG_EVT struct hidd_close_evt_param #include <esp_hidd_api.h> ESP_HIDD_CLOSE_EVT. Public Members esp_hidd_status_t status operation status esp_hidd_status_t status operation status esp_hidd_connection_state_t conn_status connection status esp_hidd_connection_state_t conn_status connection status esp_hidd_status_t status struct hidd_close_evt_param #include <esp_hidd_api.h> ESP_HIDD_CLOSE_EVT. Public Members esp_hidd_status_t status operation status esp_hidd_connection_state_t conn_status connection status struct hidd_deinit_evt_param #include <esp_hidd_api.h> ESP_HIDD_DEINIT_EVT. struct hidd_deinit_evt_param #include <esp_hidd_api.h> ESP_HIDD_DEINIT_EVT. struct hidd_get_report_evt_param #include <esp_hidd_api.h> ESP_HIDD_GET_REPORT_EVT. Public Members esp_hidd_report_type_t report_type report type esp_hidd_report_type_t report_type report type uint8_t report_id report id uint8_t report_id report id uint16_t buffer_size buffer size uint16_t buffer_size buffer size esp_hidd_report_type_t report_type struct hidd_get_report_evt_param #include <esp_hidd_api.h> ESP_HIDD_GET_REPORT_EVT. Public Members esp_hidd_report_type_t report_type report type uint8_t report_id report id uint16_t buffer_size buffer size struct hidd_init_evt_param #include <esp_hidd_api.h> ESP_HIDD_INIT_EVT. struct hidd_init_evt_param #include <esp_hidd_api.h> ESP_HIDD_INIT_EVT. struct hidd_intr_data_evt_param #include <esp_hidd_api.h> ESP_HIDD_INTR_DATA_EVT. struct hidd_intr_data_evt_param #include <esp_hidd_api.h> ESP_HIDD_INTR_DATA_EVT. struct hidd_open_evt_param #include <esp_hidd_api.h> ESP_HIDD_OPEN_EVT. Public Members esp_hidd_status_t status operation status esp_hidd_status_t status operation status esp_hidd_connection_state_t conn_status connection status esp_hidd_connection_state_t conn_status connection status esp_bd_addr_t bd_addr host address esp_bd_addr_t bd_addr host address esp_hidd_status_t status struct hidd_open_evt_param #include <esp_hidd_api.h> ESP_HIDD_OPEN_EVT. Public Members esp_hidd_status_t status operation status esp_hidd_connection_state_t conn_status connection status esp_bd_addr_t bd_addr host address struct hidd_register_app_evt_param #include <esp_hidd_api.h> ESP_HIDD_REGISTER_APP_EVT. Public Members esp_hidd_status_t status operation status esp_hidd_status_t status operation status bool in_use indicate whether use virtual cable plug host address bool in_use indicate whether use virtual cable plug host address esp_bd_addr_t bd_addr host address esp_bd_addr_t bd_addr host address esp_hidd_status_t status struct hidd_register_app_evt_param #include <esp_hidd_api.h> ESP_HIDD_REGISTER_APP_EVT. Public Members esp_hidd_status_t status operation status bool in_use indicate whether use virtual cable plug host address esp_bd_addr_t bd_addr host address struct hidd_report_err_evt_param #include <esp_hidd_api.h> ESP_HIDD_REPORT_ERR_EVT. Public Members esp_hidd_status_t status operation status esp_hidd_status_t status operation status uint8_t reason lower layer failed reason(ref hiddefs.h) uint8_t reason lower layer failed reason(ref hiddefs.h) esp_hidd_status_t status struct hidd_report_err_evt_param #include <esp_hidd_api.h> ESP_HIDD_REPORT_ERR_EVT. Public Members esp_hidd_status_t status operation status uint8_t reason lower layer failed reason(ref hiddefs.h) struct hidd_send_report_evt_param #include <esp_hidd_api.h> ESP_HIDD_SEND_REPORT_EVT. Public Members esp_hidd_status_t status operation status esp_hidd_status_t status operation status uint8_t reason lower layer failed reason(ref hiddefs.h) uint8_t reason lower layer failed reason(ref hiddefs.h) esp_hidd_report_type_t report_type report type esp_hidd_report_type_t report_type report type uint8_t report_id report id uint8_t report_id report id esp_hidd_status_t status struct hidd_send_report_evt_param #include <esp_hidd_api.h> ESP_HIDD_SEND_REPORT_EVT. Public Members esp_hidd_status_t status operation status uint8_t reason lower layer failed reason(ref hiddefs.h) esp_hidd_report_type_t report_type report type uint8_t report_id report id struct hidd_set_protocol_evt_param #include <esp_hidd_api.h> ESP_HIDD_SET_PROTOCOL_EVT. Public Members esp_hidd_protocol_mode_t protocol_mode protocol mode esp_hidd_protocol_mode_t protocol_mode protocol mode esp_hidd_protocol_mode_t protocol_mode struct hidd_set_protocol_evt_param #include <esp_hidd_api.h> ESP_HIDD_SET_PROTOCOL_EVT. Public Members esp_hidd_protocol_mode_t protocol_mode protocol mode struct hidd_set_report_evt_param #include <esp_hidd_api.h> ESP_HIDD_SET_REPORT_EVT. Public Members esp_hidd_report_type_t report_type report type esp_hidd_report_type_t report_type report type uint8_t report_id report id uint8_t report_id report id uint16_t len set_report data length uint16_t len set_report data length uint8_t *data set_report data pointer uint8_t *data set_report data pointer esp_hidd_report_type_t report_type struct hidd_set_report_evt_param #include <esp_hidd_api.h> ESP_HIDD_SET_REPORT_EVT. Public Members esp_hidd_report_type_t report_type report type uint8_t report_id report id uint16_t len set_report data length uint8_t *data set_report data pointer struct hidd_unregister_app_evt_param #include <esp_hidd_api.h> ESP_HIDD_UNREGISTER_APP_EVT. struct hidd_unregister_app_evt_param #include <esp_hidd_api.h> ESP_HIDD_UNREGISTER_APP_EVT. struct hidd_vc_unplug_param #include <esp_hidd_api.h> ESP_HIDD_VC_UNPLUG_EVT. Public Members esp_hidd_status_t status operation status esp_hidd_status_t status operation status esp_hidd_connection_state_t conn_status connection status esp_hidd_connection_state_t conn_status connection status esp_hidd_status_t status struct hidd_vc_unplug_param #include <esp_hidd_api.h> ESP_HIDD_VC_UNPLUG_EVT. Public Members esp_hidd_status_t status operation status esp_hidd_connection_state_t conn_status connection status struct esp_hidd_cb_param_t::hidd_init_evt_param init Structures struct esp_hidd_app_param_t HID device characteristics for SDP server. struct esp_hidd_qos_param_t HIDD Quality of Service parameters negotiated over L2CAP. Public Members uint8_t service_type the level of service, 0 indicates no traffic uint8_t service_type the level of service, 0 indicates no traffic uint32_t token_rate token rate in bytes per second, 0 indicates "don't care" uint32_t token_rate token rate in bytes per second, 0 indicates "don't care" uint32_t token_bucket_size limit on the burstness of the application data uint32_t token_bucket_size limit on the burstness of the application data uint32_t peak_bandwidth bytes per second, value 0 indicates "don't care" uint32_t peak_bandwidth bytes per second, value 0 indicates "don't care" uint32_t access_latency maximum acceptable delay in microseconds uint32_t access_latency maximum acceptable delay in microseconds uint32_t delay_variation the difference in microseconds between the max and min delay uint32_t delay_variation the difference in microseconds between the max and min delay uint8_t service_type Macros ESP_HID_CLASS_UNKNOWN subclass of hid device unknown HID device subclass ESP_HID_CLASS_JOS joystick ESP_HID_CLASS_GPD game pad ESP_HID_CLASS_RMC remote control ESP_HID_CLASS_SED sensing device ESP_HID_CLASS_DGT digitizer tablet ESP_HID_CLASS_CDR card reader ESP_HID_CLASS_KBD keyboard ESP_HID_CLASS_MIC pointing device ESP_HID_CLASS_COM combo keyboard/pointing Type Definitions typedef void (*esp_hd_cb_t)(esp_hidd_cb_event_t event, esp_hidd_cb_param_t *param) HID device callback function type. Param event Event type Param param Point to callback parameter, currently is union type Param event Event type Param param Point to callback parameter, currently is union type Enumerations enum esp_hidd_handshake_error_t HIDD handshake result code. Values: enumerator ESP_HID_PAR_HANDSHAKE_RSP_SUCCESS successful enumerator ESP_HID_PAR_HANDSHAKE_RSP_SUCCESS successful enumerator ESP_HID_PAR_HANDSHAKE_RSP_NOT_READY not ready, device is too busy to accept data enumerator ESP_HID_PAR_HANDSHAKE_RSP_NOT_READY not ready, device is too busy to accept data enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_INVALID_REP_ID invalid report ID enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_INVALID_REP_ID invalid report ID enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_UNSUPPORTED_REQ device does not support the request enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_UNSUPPORTED_REQ device does not support the request enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_INVALID_PARAM parameter value is out of range or inappropriate enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_INVALID_PARAM parameter value is out of range or inappropriate enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_UNKNOWN device could not identify the error condition enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_UNKNOWN device could not identify the error condition enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_FATAL restart is essential to resume functionality enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_FATAL restart is essential to resume functionality enumerator ESP_HID_PAR_HANDSHAKE_RSP_SUCCESS enum esp_hidd_report_type_t HIDD report types. Values: enumerator ESP_HIDD_REPORT_TYPE_OTHER unknown report type enumerator ESP_HIDD_REPORT_TYPE_OTHER unknown report type enumerator ESP_HIDD_REPORT_TYPE_INPUT input report enumerator ESP_HIDD_REPORT_TYPE_INPUT input report enumerator ESP_HIDD_REPORT_TYPE_OUTPUT output report enumerator ESP_HIDD_REPORT_TYPE_OUTPUT output report enumerator ESP_HIDD_REPORT_TYPE_FEATURE feature report enumerator ESP_HIDD_REPORT_TYPE_FEATURE feature report enumerator ESP_HIDD_REPORT_TYPE_INTRDATA special value for reports to be sent on interrupt channel, INPUT is assumed enumerator ESP_HIDD_REPORT_TYPE_INTRDATA special value for reports to be sent on interrupt channel, INPUT is assumed enumerator ESP_HIDD_REPORT_TYPE_OTHER enum esp_hidd_connection_state_t HIDD connection state. Values: enumerator ESP_HIDD_CONN_STATE_CONNECTED HID connection established enumerator ESP_HIDD_CONN_STATE_CONNECTED HID connection established enumerator ESP_HIDD_CONN_STATE_CONNECTING connection to remote Bluetooth device enumerator ESP_HIDD_CONN_STATE_CONNECTING connection to remote Bluetooth device enumerator ESP_HIDD_CONN_STATE_DISCONNECTED connection released enumerator ESP_HIDD_CONN_STATE_DISCONNECTED connection released enumerator ESP_HIDD_CONN_STATE_DISCONNECTING disconnecting to remote Bluetooth device enumerator ESP_HIDD_CONN_STATE_DISCONNECTING disconnecting to remote Bluetooth device enumerator ESP_HIDD_CONN_STATE_UNKNOWN unknown connection state enumerator ESP_HIDD_CONN_STATE_UNKNOWN unknown connection state enumerator ESP_HIDD_CONN_STATE_CONNECTED enum esp_hidd_protocol_mode_t HID device protocol modes. Values: enumerator ESP_HIDD_REPORT_MODE Report Protocol Mode enumerator ESP_HIDD_REPORT_MODE Report Protocol Mode enumerator ESP_HIDD_BOOT_MODE Boot Protocol Mode enumerator ESP_HIDD_BOOT_MODE Boot Protocol Mode enumerator ESP_HIDD_UNSUPPORTED_MODE unsupported enumerator ESP_HIDD_UNSUPPORTED_MODE unsupported enumerator ESP_HIDD_REPORT_MODE enum esp_hidd_boot_report_id_t HID Boot Protocol report IDs. Values: enumerator ESP_HIDD_BOOT_REPORT_ID_KEYBOARD report ID of Boot Protocol keyboard report enumerator ESP_HIDD_BOOT_REPORT_ID_KEYBOARD report ID of Boot Protocol keyboard report enumerator ESP_HIDD_BOOT_REPORT_ID_MOUSE report ID of Boot Protocol mouse report enumerator ESP_HIDD_BOOT_REPORT_ID_MOUSE report ID of Boot Protocol mouse report enumerator ESP_HIDD_BOOT_REPORT_ID_KEYBOARD enum [anonymous] HID Boot Protocol report size including report ID. Values: enumerator ESP_HIDD_BOOT_REPORT_SIZE_KEYBOARD report size of Boot Protocol keyboard report enumerator ESP_HIDD_BOOT_REPORT_SIZE_KEYBOARD report size of Boot Protocol keyboard report enumerator ESP_HIDD_BOOT_REPORT_SIZE_MOUSE report size of Boot Protocol mouse report enumerator ESP_HIDD_BOOT_REPORT_SIZE_MOUSE report size of Boot Protocol mouse report enumerator ESP_HIDD_BOOT_REPORT_SIZE_KEYBOARD enum esp_hidd_cb_event_t HID device callback function events. Values: enumerator ESP_HIDD_INIT_EVT When HID device is initialized, the event comes enumerator ESP_HIDD_INIT_EVT When HID device is initialized, the event comes enumerator ESP_HIDD_DEINIT_EVT When HID device is deinitialized, the event comes enumerator ESP_HIDD_DEINIT_EVT When HID device is deinitialized, the event comes enumerator ESP_HIDD_REGISTER_APP_EVT When HID device application registered, the event comes enumerator ESP_HIDD_REGISTER_APP_EVT When HID device application registered, the event comes enumerator ESP_HIDD_UNREGISTER_APP_EVT When HID device application unregistered, the event comes enumerator ESP_HIDD_UNREGISTER_APP_EVT When HID device application unregistered, the event comes enumerator ESP_HIDD_OPEN_EVT When HID device connection to host opened, the event comes enumerator ESP_HIDD_OPEN_EVT When HID device connection to host opened, the event comes enumerator ESP_HIDD_CLOSE_EVT When HID device connection to host closed, the event comes enumerator ESP_HIDD_CLOSE_EVT When HID device connection to host closed, the event comes enumerator ESP_HIDD_SEND_REPORT_EVT When HID device send report to lower layer, the event comes enumerator ESP_HIDD_SEND_REPORT_EVT When HID device send report to lower layer, the event comes enumerator ESP_HIDD_REPORT_ERR_EVT When HID device report handshanke error to lower layer, the event comes enumerator ESP_HIDD_REPORT_ERR_EVT When HID device report handshanke error to lower layer, the event comes enumerator ESP_HIDD_GET_REPORT_EVT When HID device receives GET_REPORT request from host, the event comes enumerator ESP_HIDD_GET_REPORT_EVT When HID device receives GET_REPORT request from host, the event comes enumerator ESP_HIDD_SET_REPORT_EVT When HID device receives SET_REPORT request from host, the event comes enumerator ESP_HIDD_SET_REPORT_EVT When HID device receives SET_REPORT request from host, the event comes enumerator ESP_HIDD_SET_PROTOCOL_EVT When HID device receives SET_PROTOCOL request from host, the event comes enumerator ESP_HIDD_SET_PROTOCOL_EVT When HID device receives SET_PROTOCOL request from host, the event comes enumerator ESP_HIDD_INTR_DATA_EVT When HID device receives DATA from host on intr, the event comes enumerator ESP_HIDD_INTR_DATA_EVT When HID device receives DATA from host on intr, the event comes enumerator ESP_HIDD_VC_UNPLUG_EVT When HID device initiates Virtual Cable Unplug, the event comes enumerator ESP_HIDD_VC_UNPLUG_EVT When HID device initiates Virtual Cable Unplug, the event comes enumerator ESP_HIDD_API_ERR_EVT When HID device has API error, the event comes enumerator ESP_HIDD_API_ERR_EVT When HID device has API error, the event comes enumerator ESP_HIDD_INIT_EVT enum esp_hidd_status_t Values: enumerator ESP_HIDD_SUCCESS enumerator ESP_HIDD_SUCCESS enumerator ESP_HIDD_ERROR general ESP HD error enumerator ESP_HIDD_ERROR general ESP HD error enumerator ESP_HIDD_NO_RES out of system resources enumerator ESP_HIDD_NO_RES out of system resources enumerator ESP_HIDD_BUSY Temporarily can not handle this request. enumerator ESP_HIDD_BUSY Temporarily can not handle this request. enumerator ESP_HIDD_NO_DATA No data. enumerator ESP_HIDD_NO_DATA No data. enumerator ESP_HIDD_NEED_INIT HIDD module shall init first enumerator ESP_HIDD_NEED_INIT HIDD module shall init first enumerator ESP_HIDD_NEED_DEINIT HIDD module shall deinit first enumerator ESP_HIDD_NEED_DEINIT HIDD module shall deinit first enumerator ESP_HIDD_NEED_REG HIDD module shall register first enumerator ESP_HIDD_NEED_REG HIDD module shall register first enumerator ESP_HIDD_NEED_DEREG HIDD module shall deregister first enumerator ESP_HIDD_NEED_DEREG HIDD module shall deregister first enumerator ESP_HIDD_NO_CONNECTION connection may have been closed enumerator ESP_HIDD_NO_CONNECTION connection may have been closed enumerator ESP_HIDD_SUCCESS
Bluetooth® HID Device API Overview A Bluetooth HID device is a device providing the service of human or other data input and output to and from a Bluetooth HID Host. Users can use the Bluetooth HID Device APIs to make devices like keyboards, mice, joysticks and so on. Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the following application: This is an example of Bluetooth HID mouse device. The device running this example can be discovered and connected by a Bluetooth HID Host device such as a PC, and the pointer will move left and right after HID connection is established - bluetooth/bluedroid/classic_bt/bt_hid_mouse_device API Reference Header File This header file can be included with: #include "esp_hidd_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_bt_hid_device_register_callback(esp_hd_cb_t callback) This function is called to init callbacks with HID device module. - Parameters callback -- [in] pointer to the init callback function. - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_hid_device_init(void) Initializes HIDD interface. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_register_callback. When the operation is complete, the callback function will be called with ESP_HIDD_INIT_EVT. - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_hid_device_deinit(void) De-initializes HIDD interface. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_DEINIT_EVT. - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_hid_device_register_app(esp_hidd_app_param_t *app_param, esp_hidd_qos_param_t *in_qos, esp_hidd_qos_param_t *out_qos) Registers HIDD parameters with SDP and sets l2cap Quality of Service. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_REGISTER_APP_EVT. - Parameters app_param -- [in] HIDD parameters in_qos -- [in] incoming QoS parameters out_qos -- [in] outgoing QoS parameters - - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_hid_device_unregister_app(void) Removes HIDD parameters from SDP and resets l2cap Quality of Service. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_UNREGISTER_APP_EVT. - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_hid_device_connect(esp_bd_addr_t bd_addr) Connects to the peer HID Host with virtual cable. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_OPEN_EVT. - Parameters bd_addr -- [in] Remote host bluetooth device address. - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_hid_device_disconnect(void) Disconnects from the currently connected HID Host. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_CLOSE_EVT. Note The disconnect operation will not remove the virtually cabled device. If the connect request from the different HID Host, it will reject the request. - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_hid_device_send_report(esp_hidd_report_type_t type, uint8_t id, uint16_t len, uint8_t *data) Sends HID report to the currently connected HID Host. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_SEND_REPORT_EVT. - Parameters type -- [in] type of report id -- [in] report id as defined by descriptor len -- [in] length of report data -- [in] report data - - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_hid_device_report_error(esp_hidd_handshake_error_t error) Sends HID Handshake with error info for invalid set_report to the currently connected HID Host. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_REPORT_ERR_EVT. - Parameters error -- [in] type of error - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_hid_device_virtual_cable_unplug(void) Remove the virtually cabled device. This function should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with ESP_HIDD_VC_UNPLUG_EVT. Note If the connection exists, then HID Device will send a VIRTUAL_CABLE_UNPLUGcontrol command to the peer HID Host, and the connection will be destroyed. If the connection does not exist, then HID Device will only unplug on it's single side. Once the unplug operation is success, the related pairing and bonding information will be removed, then the HID Device can accept connection request from the different HID Host, - Returns - ESP_OK: success other: failed - Unions - union esp_hidd_cb_param_t - #include <esp_hidd_api.h> HID device callback parameters union. Public Members - struct esp_hidd_cb_param_t::hidd_init_evt_param init HIDD callback param of ESP_HIDD_INIT_EVT - struct esp_hidd_cb_param_t::hidd_deinit_evt_param deinit HIDD callback param of ESP_HIDD_DEINIT_EVT - struct esp_hidd_cb_param_t::hidd_register_app_evt_param register_app HIDD callback param of ESP_HIDD_REGISTER_APP_EVT - struct esp_hidd_cb_param_t::hidd_unregister_app_evt_param unregister_app HIDD callback param of ESP_HIDD_UNREGISTER_APP_EVT - struct esp_hidd_cb_param_t::hidd_open_evt_param open HIDD callback param of ESP_HIDD_OPEN_EVT - struct esp_hidd_cb_param_t::hidd_close_evt_param close HIDD callback param of ESP_HIDD_CLOSE_EVT - struct esp_hidd_cb_param_t::hidd_send_report_evt_param send_report HIDD callback param of ESP_HIDD_SEND_REPORT_EVT - struct esp_hidd_cb_param_t::hidd_report_err_evt_param report_err HIDD callback param of ESP_HIDD_REPORT_ERR_EVT - struct esp_hidd_cb_param_t::hidd_get_report_evt_param get_report HIDD callback param of ESP_HIDD_GET_REPORT_EVT - struct esp_hidd_cb_param_t::hidd_set_report_evt_param set_report HIDD callback param of ESP_HIDD_SET_REPORT_EVT - struct esp_hidd_cb_param_t::hidd_set_protocol_evt_param set_protocol HIDD callback param of ESP_HIDD_SET_PROTOCOL_EVT - struct esp_hidd_cb_param_t::hidd_intr_data_evt_param intr_data HIDD callback param of ESP_HIDD_INTR_DATA_EVT - struct esp_hidd_cb_param_t::hidd_vc_unplug_param vc_unplug HIDD callback param of ESP_HIDD_VC_UNPLUG_EVT - struct hidd_close_evt_param - #include <esp_hidd_api.h> ESP_HIDD_CLOSE_EVT. Public Members - esp_hidd_status_t status operation status - esp_hidd_connection_state_t conn_status connection status - esp_hidd_status_t status - struct hidd_deinit_evt_param - #include <esp_hidd_api.h> ESP_HIDD_DEINIT_EVT. - struct hidd_get_report_evt_param - #include <esp_hidd_api.h> ESP_HIDD_GET_REPORT_EVT. Public Members - esp_hidd_report_type_t report_type report type - uint8_t report_id report id - uint16_t buffer_size buffer size - esp_hidd_report_type_t report_type - struct hidd_init_evt_param - #include <esp_hidd_api.h> ESP_HIDD_INIT_EVT. - struct hidd_intr_data_evt_param - #include <esp_hidd_api.h> ESP_HIDD_INTR_DATA_EVT. - struct hidd_open_evt_param - #include <esp_hidd_api.h> ESP_HIDD_OPEN_EVT. Public Members - esp_hidd_status_t status operation status - esp_hidd_connection_state_t conn_status connection status - esp_bd_addr_t bd_addr host address - esp_hidd_status_t status - struct hidd_register_app_evt_param - #include <esp_hidd_api.h> ESP_HIDD_REGISTER_APP_EVT. Public Members - esp_hidd_status_t status operation status - bool in_use indicate whether use virtual cable plug host address - esp_bd_addr_t bd_addr host address - esp_hidd_status_t status - struct hidd_report_err_evt_param - #include <esp_hidd_api.h> ESP_HIDD_REPORT_ERR_EVT. Public Members - esp_hidd_status_t status operation status - uint8_t reason lower layer failed reason(ref hiddefs.h) - esp_hidd_status_t status - struct hidd_send_report_evt_param - #include <esp_hidd_api.h> ESP_HIDD_SEND_REPORT_EVT. Public Members - esp_hidd_status_t status operation status - uint8_t reason lower layer failed reason(ref hiddefs.h) - esp_hidd_report_type_t report_type report type - uint8_t report_id report id - esp_hidd_status_t status - struct hidd_set_protocol_evt_param - #include <esp_hidd_api.h> ESP_HIDD_SET_PROTOCOL_EVT. Public Members - esp_hidd_protocol_mode_t protocol_mode protocol mode - esp_hidd_protocol_mode_t protocol_mode - struct hidd_set_report_evt_param - #include <esp_hidd_api.h> ESP_HIDD_SET_REPORT_EVT. Public Members - esp_hidd_report_type_t report_type report type - uint8_t report_id report id - uint16_t len set_report data length - uint8_t *data set_report data pointer - esp_hidd_report_type_t report_type - struct hidd_unregister_app_evt_param - #include <esp_hidd_api.h> ESP_HIDD_UNREGISTER_APP_EVT. - struct hidd_vc_unplug_param - #include <esp_hidd_api.h> ESP_HIDD_VC_UNPLUG_EVT. Public Members - esp_hidd_status_t status operation status - esp_hidd_connection_state_t conn_status connection status - esp_hidd_status_t status - struct esp_hidd_cb_param_t::hidd_init_evt_param init Structures - struct esp_hidd_app_param_t HID device characteristics for SDP server. - struct esp_hidd_qos_param_t HIDD Quality of Service parameters negotiated over L2CAP. Public Members - uint8_t service_type the level of service, 0 indicates no traffic - uint32_t token_rate token rate in bytes per second, 0 indicates "don't care" - uint32_t token_bucket_size limit on the burstness of the application data - uint32_t peak_bandwidth bytes per second, value 0 indicates "don't care" - uint32_t access_latency maximum acceptable delay in microseconds - uint32_t delay_variation the difference in microseconds between the max and min delay - uint8_t service_type Macros - ESP_HID_CLASS_UNKNOWN subclass of hid device unknown HID device subclass - ESP_HID_CLASS_JOS joystick - ESP_HID_CLASS_GPD game pad - ESP_HID_CLASS_RMC remote control - ESP_HID_CLASS_SED sensing device - ESP_HID_CLASS_DGT digitizer tablet - ESP_HID_CLASS_CDR card reader - ESP_HID_CLASS_KBD keyboard - ESP_HID_CLASS_MIC pointing device - ESP_HID_CLASS_COM combo keyboard/pointing Type Definitions - typedef void (*esp_hd_cb_t)(esp_hidd_cb_event_t event, esp_hidd_cb_param_t *param) HID device callback function type. - Param event Event type - Param param Point to callback parameter, currently is union type Enumerations - enum esp_hidd_handshake_error_t HIDD handshake result code. Values: - enumerator ESP_HID_PAR_HANDSHAKE_RSP_SUCCESS successful - enumerator ESP_HID_PAR_HANDSHAKE_RSP_NOT_READY not ready, device is too busy to accept data - enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_INVALID_REP_ID invalid report ID - enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_UNSUPPORTED_REQ device does not support the request - enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_INVALID_PARAM parameter value is out of range or inappropriate - enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_UNKNOWN device could not identify the error condition - enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_FATAL restart is essential to resume functionality - enumerator ESP_HID_PAR_HANDSHAKE_RSP_SUCCESS - enum esp_hidd_report_type_t HIDD report types. Values: - enumerator ESP_HIDD_REPORT_TYPE_OTHER unknown report type - enumerator ESP_HIDD_REPORT_TYPE_INPUT input report - enumerator ESP_HIDD_REPORT_TYPE_OUTPUT output report - enumerator ESP_HIDD_REPORT_TYPE_FEATURE feature report - enumerator ESP_HIDD_REPORT_TYPE_INTRDATA special value for reports to be sent on interrupt channel, INPUT is assumed - enumerator ESP_HIDD_REPORT_TYPE_OTHER - enum esp_hidd_connection_state_t HIDD connection state. Values: - enumerator ESP_HIDD_CONN_STATE_CONNECTED HID connection established - enumerator ESP_HIDD_CONN_STATE_CONNECTING connection to remote Bluetooth device - enumerator ESP_HIDD_CONN_STATE_DISCONNECTED connection released - enumerator ESP_HIDD_CONN_STATE_DISCONNECTING disconnecting to remote Bluetooth device - enumerator ESP_HIDD_CONN_STATE_UNKNOWN unknown connection state - enumerator ESP_HIDD_CONN_STATE_CONNECTED - enum esp_hidd_protocol_mode_t HID device protocol modes. Values: - enumerator ESP_HIDD_REPORT_MODE Report Protocol Mode - enumerator ESP_HIDD_BOOT_MODE Boot Protocol Mode - enumerator ESP_HIDD_UNSUPPORTED_MODE unsupported - enumerator ESP_HIDD_REPORT_MODE - enum esp_hidd_boot_report_id_t HID Boot Protocol report IDs. Values: - enumerator ESP_HIDD_BOOT_REPORT_ID_KEYBOARD report ID of Boot Protocol keyboard report - enumerator ESP_HIDD_BOOT_REPORT_ID_MOUSE report ID of Boot Protocol mouse report - enumerator ESP_HIDD_BOOT_REPORT_ID_KEYBOARD - enum [anonymous] HID Boot Protocol report size including report ID. Values: - enumerator ESP_HIDD_BOOT_REPORT_SIZE_KEYBOARD report size of Boot Protocol keyboard report - enumerator ESP_HIDD_BOOT_REPORT_SIZE_MOUSE report size of Boot Protocol mouse report - enumerator ESP_HIDD_BOOT_REPORT_SIZE_KEYBOARD - enum esp_hidd_cb_event_t HID device callback function events. Values: - enumerator ESP_HIDD_INIT_EVT When HID device is initialized, the event comes - enumerator ESP_HIDD_DEINIT_EVT When HID device is deinitialized, the event comes - enumerator ESP_HIDD_REGISTER_APP_EVT When HID device application registered, the event comes - enumerator ESP_HIDD_UNREGISTER_APP_EVT When HID device application unregistered, the event comes - enumerator ESP_HIDD_OPEN_EVT When HID device connection to host opened, the event comes - enumerator ESP_HIDD_CLOSE_EVT When HID device connection to host closed, the event comes - enumerator ESP_HIDD_SEND_REPORT_EVT When HID device send report to lower layer, the event comes - enumerator ESP_HIDD_REPORT_ERR_EVT When HID device report handshanke error to lower layer, the event comes - enumerator ESP_HIDD_GET_REPORT_EVT When HID device receives GET_REPORT request from host, the event comes - enumerator ESP_HIDD_SET_REPORT_EVT When HID device receives SET_REPORT request from host, the event comes - enumerator ESP_HIDD_SET_PROTOCOL_EVT When HID device receives SET_PROTOCOL request from host, the event comes - enumerator ESP_HIDD_INTR_DATA_EVT When HID device receives DATA from host on intr, the event comes - enumerator ESP_HIDD_VC_UNPLUG_EVT When HID device initiates Virtual Cable Unplug, the event comes - enumerator ESP_HIDD_API_ERR_EVT When HID device has API error, the event comes - enumerator ESP_HIDD_INIT_EVT - enum esp_hidd_status_t Values: - enumerator ESP_HIDD_SUCCESS - enumerator ESP_HIDD_ERROR general ESP HD error - enumerator ESP_HIDD_NO_RES out of system resources - enumerator ESP_HIDD_BUSY Temporarily can not handle this request. - enumerator ESP_HIDD_NO_DATA No data. - enumerator ESP_HIDD_NEED_INIT HIDD module shall init first - enumerator ESP_HIDD_NEED_DEINIT HIDD module shall deinit first - enumerator ESP_HIDD_NEED_REG HIDD module shall register first - enumerator ESP_HIDD_NEED_DEREG HIDD module shall deregister first - enumerator ESP_HIDD_NO_CONNECTION connection may have been closed - enumerator ESP_HIDD_SUCCESS
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_hidd.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Classic Bluetooth® L2CAP API
null
espressif.com
2016-01-01
c63cac5aae238906
null
null
Classic Bluetooth® L2CAP API Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the following application: This is a BT_L2CAP demo. This demo can connect, send and receive L2CAP data bluetooth/bluedroid/classic_bt/bt_l2cap_client, bluetooth/bluedroid/classic_bt/bt_l2cap_server API Reference Header File components/bt/host/bluedroid/api/include/api/esp_l2cap_bt_api.h This header file can be included with: #include "esp_l2cap_bt_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_bt_l2cap_register_callback(esp_bt_l2cap_cb_t callback) This function is called to init callbacks with L2CAP module. Parameters callback -- [in] pointer to the init callback function. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters callback -- [in] pointer to the init callback function. Returns ESP_OK: success other: failed esp_err_t esp_bt_l2cap_init(void) This function is called to init L2CAP module. When the operation is completed, the callback function will be called with ESP_BT_L2CAP_INIT_EVT. This function should be called after esp_bluedroid_enable() completes successfully. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Returns ESP_OK: success other: failed esp_err_t esp_bt_l2cap_deinit(void) This function is called to uninit l2cap module. The operation will close all active L2CAP connection first, then the callback function will be called with ESP_BT_L2CAP_CLOSE_EVT, and the number of ESP_BT_L2CAP_CLOSE_EVT is equal to the number of connection. When the operation is completed, the callback function will be called with ESP_BT_L2CAP_UNINIT_EVT. This function should be called after esp_bt_l2cap_init() completes successfully. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Returns ESP_OK: success other: failed esp_err_t esp_bt_l2cap_connect(esp_bt_l2cap_cntl_flags_t cntl_flag, uint16_t remote_psm, esp_bd_addr_t peer_bd_addr) This function makes an L2CAP connection to a remote BD Address. When the connection is initiated or failed to initiate, the callback is called with ESP_BT_L2CAP_CL_INIT_EVT. When the connection is established or failed, the callback is called with ESP_BT_L2CAP_OPEN_EVT. This function must be called after esp_bt_l2cap_init() successful and before esp_bt_l2cap_deinit(). Parameters cntl_flag -- [in] Lower 16-bit security settings mask. remote_psm -- [in] Remote device bluetooth Profile PSM. peer_bd_addr -- [in] Remote device bluetooth device address. cntl_flag -- [in] Lower 16-bit security settings mask. remote_psm -- [in] Remote device bluetooth Profile PSM. peer_bd_addr -- [in] Remote device bluetooth device address. cntl_flag -- [in] Lower 16-bit security settings mask. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters cntl_flag -- [in] Lower 16-bit security settings mask. remote_psm -- [in] Remote device bluetooth Profile PSM. peer_bd_addr -- [in] Remote device bluetooth device address. Returns ESP_OK: success other: failed esp_err_t esp_bt_l2cap_start_srv(esp_bt_l2cap_cntl_flags_t cntl_flag, uint16_t local_psm) This function create a L2CAP server and starts listening for an L2CAP connection request from a remote Bluetooth device. When the server is started successfully, the callback is called with ESP_BT_L2CAP_START_EVT. When the connection is established, the callback is called with ESP_BT_L2CAP_OPEN_EVT. This function must be called after esp_bt_l2cap_init() successful and before esp_bt_l2cap_deinit(). Parameters cntl_flag -- [in] Lower 16-bit security settings mask. local_psm -- [in] Dynamic PSM. cntl_flag -- [in] Lower 16-bit security settings mask. local_psm -- [in] Dynamic PSM. cntl_flag -- [in] Lower 16-bit security settings mask. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters cntl_flag -- [in] Lower 16-bit security settings mask. local_psm -- [in] Dynamic PSM. Returns ESP_OK: success other: failed esp_err_t esp_bt_l2cap_stop_all_srv(void) This function stops all L2CAP servers. The operation will close all active L2CAP connection first, then the callback function will be called with ESP_BT_L2CAP_CLOSE_EVT, and the number of ESP_BT_L2CAP_CLOSE_EVT is equal to the number of connection. When the operation is completed, the callback is called with ESP_BT_L2CAP_SRV_STOP_EVT. This function must be called after esp_bt_l2cap_init() successful and before esp_bt_l2cap_deinit(). Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Returns ESP_OK: success other: failed esp_err_t esp_bt_l2cap_stop_srv(uint16_t local_psm) This function stops a specific L2CAP server. The operation will close all active L2CAP connection first on the specific L2CAP server, then the callback function will be called with ESP_BT_L2CAP_CLOSE_EVT, and the number of ESP_BT_L2CAP_CLOSE_EVT is equal to the number of connection. When the operation is completed, the callback is called with ESP_BT_L2CAP_SRV_STOP_EVT. This function must be called after esp_bt_l2cap_init() successful and before esp_bt_l2cap_deinit(). Parameters local_psm -- [in] Dynamic PSM. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters local_psm -- [in] Dynamic PSM. Returns ESP_OK: success other: failed esp_err_t esp_bt_l2cap_vfs_register(void) This function is used to register VFS. Only supports write, read and close. This function must be called after esp_bt_l2cap_init() successful and before esp_bt_l2cap_deinit(). Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Returns ESP_OK: success other: failed Unions union esp_bt_l2cap_cb_param_t #include <esp_l2cap_bt_api.h> L2CAP callback parameters union. Public Members struct esp_bt_l2cap_cb_param_t::l2cap_init_evt_param init L2CAP callback param of ESP_BT_L2CAP_INIT_EVT struct esp_bt_l2cap_cb_param_t::l2cap_init_evt_param init L2CAP callback param of ESP_BT_L2CAP_INIT_EVT struct esp_bt_l2cap_cb_param_t::l2cap_uninit_evt_param uninit L2CAP callback param of ESP_BT_L2CAP_UNINIT_EVT struct esp_bt_l2cap_cb_param_t::l2cap_uninit_evt_param uninit L2CAP callback param of ESP_BT_L2CAP_UNINIT_EVT struct esp_bt_l2cap_cb_param_t::l2cap_open_evt_param open L2CAP callback param of ESP_BT_L2CAP_OPEN_EVT struct esp_bt_l2cap_cb_param_t::l2cap_open_evt_param open L2CAP callback param of ESP_BT_L2CAP_OPEN_EVT struct esp_bt_l2cap_cb_param_t::l2cap_close_evt_param close L2CAP callback param of ESP_BT_L2CAP_CLOSE_EVT struct esp_bt_l2cap_cb_param_t::l2cap_close_evt_param close L2CAP callback param of ESP_BT_L2CAP_CLOSE_EVT struct esp_bt_l2cap_cb_param_t::l2cap_start_evt_param start L2CAP callback param of ESP_BT_L2CAP_START_EVT struct esp_bt_l2cap_cb_param_t::l2cap_start_evt_param start L2CAP callback param of ESP_BT_L2CAP_START_EVT struct esp_bt_l2cap_cb_param_t::l2cap_cl_init_evt_param cl_init L2CAP callback param of ESP_BT_L2CAP_CL_INIT_EVT struct esp_bt_l2cap_cb_param_t::l2cap_cl_init_evt_param cl_init L2CAP callback param of ESP_BT_L2CAP_CL_INIT_EVT struct esp_bt_l2cap_cb_param_t::l2cap_srv_stop_evt_param srv_stop L2CAP callback param of ESP_BT_L2CAP_SRV_STOP_EVT struct esp_bt_l2cap_cb_param_t::l2cap_srv_stop_evt_param srv_stop L2CAP callback param of ESP_BT_L2CAP_SRV_STOP_EVT struct l2cap_cl_init_evt_param #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_CL_INIT_EVT. Public Members esp_bt_l2cap_status_t status status esp_bt_l2cap_status_t status status uint32_t handle The connection handle uint32_t handle The connection handle uint8_t sec_id security ID used by this server uint8_t sec_id security ID used by this server esp_bt_l2cap_status_t status struct l2cap_cl_init_evt_param #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_CL_INIT_EVT. Public Members esp_bt_l2cap_status_t status status uint32_t handle The connection handle uint8_t sec_id security ID used by this server struct l2cap_close_evt_param #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_CLOSE_EVT. Public Members esp_bt_l2cap_status_t status status esp_bt_l2cap_status_t status status uint32_t handle The connection handle uint32_t handle The connection handle bool async FALSE, if local initiates disconnect bool async FALSE, if local initiates disconnect esp_bt_l2cap_status_t status struct l2cap_close_evt_param #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_CLOSE_EVT. Public Members esp_bt_l2cap_status_t status status uint32_t handle The connection handle bool async FALSE, if local initiates disconnect struct l2cap_init_evt_param #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_INIT_EVT. Public Members esp_bt_l2cap_status_t status status esp_bt_l2cap_status_t status status esp_bt_l2cap_status_t status struct l2cap_init_evt_param #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_INIT_EVT. Public Members esp_bt_l2cap_status_t status status struct l2cap_open_evt_param #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_OPEN_EVT. Public Members esp_bt_l2cap_status_t status status esp_bt_l2cap_status_t status status uint32_t handle The connection handle uint32_t handle The connection handle int fd File descriptor int fd File descriptor esp_bd_addr_t rem_bda The peer address esp_bd_addr_t rem_bda The peer address int32_t tx_mtu The transmit MTU int32_t tx_mtu The transmit MTU esp_bt_l2cap_status_t status struct l2cap_open_evt_param #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_OPEN_EVT. Public Members esp_bt_l2cap_status_t status status uint32_t handle The connection handle int fd File descriptor esp_bd_addr_t rem_bda The peer address int32_t tx_mtu The transmit MTU struct l2cap_srv_stop_evt_param #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_SRV_STOP_EVT. Public Members esp_bt_l2cap_status_t status status esp_bt_l2cap_status_t status status uint8_t psm local psm uint8_t psm local psm esp_bt_l2cap_status_t status struct l2cap_srv_stop_evt_param #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_SRV_STOP_EVT. Public Members esp_bt_l2cap_status_t status status uint8_t psm local psm struct l2cap_start_evt_param #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_START_EVT. Public Members esp_bt_l2cap_status_t status status esp_bt_l2cap_status_t status status uint32_t handle The connection handle uint32_t handle The connection handle uint8_t sec_id security ID used by this server uint8_t sec_id security ID used by this server esp_bt_l2cap_status_t status struct l2cap_start_evt_param #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_START_EVT. Public Members esp_bt_l2cap_status_t status status uint32_t handle The connection handle uint8_t sec_id security ID used by this server struct l2cap_uninit_evt_param #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_UNINIT_EVT. Public Members esp_bt_l2cap_status_t status status esp_bt_l2cap_status_t status status esp_bt_l2cap_status_t status struct l2cap_uninit_evt_param #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_UNINIT_EVT. Public Members esp_bt_l2cap_status_t status status struct esp_bt_l2cap_cb_param_t::l2cap_init_evt_param init Macros ESP_BT_L2CAP_SEC_NONE Security Setting Mask. Use these three mask mode: ESP_BT_L2CAP_SEC_NONE ESP_BT_L2CAP_SEC_AUTHENTICATE (ESP_BT_L2CAP_SEC_ENCRYPT|ESP_BT_L2CAP_SEC_AUTHENTICATE) No security ESP_BT_L2CAP_SEC_NONE ESP_BT_L2CAP_SEC_AUTHENTICATE (ESP_BT_L2CAP_SEC_ENCRYPT|ESP_BT_L2CAP_SEC_AUTHENTICATE) No security ESP_BT_L2CAP_SEC_NONE ESP_BT_L2CAP_SEC_AUTHORIZE Authorization required ESP_BT_L2CAP_SEC_AUTHENTICATE Authentication required ESP_BT_L2CAP_SEC_ENCRYPT Encryption required Type Definitions typedef uint32_t esp_bt_l2cap_cntl_flags_t typedef void (*esp_bt_l2cap_cb_t)(esp_bt_l2cap_cb_event_t event, esp_bt_l2cap_cb_param_t *param) L2CAP callback function type. Param event Event type Param param Point to callback parameter, currently is union type Param event Event type Param param Point to callback parameter, currently is union type Enumerations enum esp_bt_l2cap_status_t L2CAP operation success and failure codes. Values: enumerator ESP_BT_L2CAP_SUCCESS Successful operation. enumerator ESP_BT_L2CAP_SUCCESS Successful operation. enumerator ESP_BT_L2CAP_FAILURE Generic failure. enumerator ESP_BT_L2CAP_FAILURE Generic failure. enumerator ESP_BT_L2CAP_BUSY Temporarily can not handle this request. enumerator ESP_BT_L2CAP_BUSY Temporarily can not handle this request. enumerator ESP_BT_L2CAP_NO_RESOURCE No more resource enumerator ESP_BT_L2CAP_NO_RESOURCE No more resource enumerator ESP_BT_L2CAP_NEED_INIT L2CAP module shall init first enumerator ESP_BT_L2CAP_NEED_INIT L2CAP module shall init first enumerator ESP_BT_L2CAP_NEED_DEINIT L2CAP module shall deinit first enumerator ESP_BT_L2CAP_NEED_DEINIT L2CAP module shall deinit first enumerator ESP_BT_L2CAP_NO_CONNECTION Connection may have been closed enumerator ESP_BT_L2CAP_NO_CONNECTION Connection may have been closed enumerator ESP_BT_L2CAP_NO_SERVER No server enumerator ESP_BT_L2CAP_NO_SERVER No server enumerator ESP_BT_L2CAP_SUCCESS enum esp_bt_l2cap_cb_event_t L2CAP callback function events. Values: enumerator ESP_BT_L2CAP_INIT_EVT When L2CAP is initialized, the event comes enumerator ESP_BT_L2CAP_INIT_EVT When L2CAP is initialized, the event comes enumerator ESP_BT_L2CAP_UNINIT_EVT When L2CAP is deinitialized, the event comes enumerator ESP_BT_L2CAP_UNINIT_EVT When L2CAP is deinitialized, the event comes enumerator ESP_BT_L2CAP_OPEN_EVT When L2CAP Client connection open, the event comes enumerator ESP_BT_L2CAP_OPEN_EVT When L2CAP Client connection open, the event comes enumerator ESP_BT_L2CAP_CLOSE_EVT When L2CAP connection closed, the event comes enumerator ESP_BT_L2CAP_CLOSE_EVT When L2CAP connection closed, the event comes enumerator ESP_BT_L2CAP_START_EVT When L2CAP server started, the event comes enumerator ESP_BT_L2CAP_START_EVT When L2CAP server started, the event comes enumerator ESP_BT_L2CAP_CL_INIT_EVT When L2CAP client initiated a connection, the event comes enumerator ESP_BT_L2CAP_CL_INIT_EVT When L2CAP client initiated a connection, the event comes enumerator ESP_BT_L2CAP_SRV_STOP_EVT When L2CAP server stopped, the event comes enumerator ESP_BT_L2CAP_SRV_STOP_EVT When L2CAP server stopped, the event comes enumerator ESP_BT_L2CAP_INIT_EVT
Classic Bluetooth® L2CAP API Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the following application: This is a BT_L2CAP demo. This demo can connect, send and receive L2CAP data bluetooth/bluedroid/classic_bt/bt_l2cap_client, bluetooth/bluedroid/classic_bt/bt_l2cap_server API Reference Header File components/bt/host/bluedroid/api/include/api/esp_l2cap_bt_api.h This header file can be included with: #include "esp_l2cap_bt_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_bt_l2cap_register_callback(esp_bt_l2cap_cb_t callback) This function is called to init callbacks with L2CAP module. - Parameters callback -- [in] pointer to the init callback function. - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_l2cap_init(void) This function is called to init L2CAP module. When the operation is completed, the callback function will be called with ESP_BT_L2CAP_INIT_EVT. This function should be called after esp_bluedroid_enable() completes successfully. - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_l2cap_deinit(void) This function is called to uninit l2cap module. The operation will close all active L2CAP connection first, then the callback function will be called with ESP_BT_L2CAP_CLOSE_EVT, and the number of ESP_BT_L2CAP_CLOSE_EVT is equal to the number of connection. When the operation is completed, the callback function will be called with ESP_BT_L2CAP_UNINIT_EVT. This function should be called after esp_bt_l2cap_init() completes successfully. - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_l2cap_connect(esp_bt_l2cap_cntl_flags_t cntl_flag, uint16_t remote_psm, esp_bd_addr_t peer_bd_addr) This function makes an L2CAP connection to a remote BD Address. When the connection is initiated or failed to initiate, the callback is called with ESP_BT_L2CAP_CL_INIT_EVT. When the connection is established or failed, the callback is called with ESP_BT_L2CAP_OPEN_EVT. This function must be called after esp_bt_l2cap_init() successful and before esp_bt_l2cap_deinit(). - Parameters cntl_flag -- [in] Lower 16-bit security settings mask. remote_psm -- [in] Remote device bluetooth Profile PSM. peer_bd_addr -- [in] Remote device bluetooth device address. - - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_l2cap_start_srv(esp_bt_l2cap_cntl_flags_t cntl_flag, uint16_t local_psm) This function create a L2CAP server and starts listening for an L2CAP connection request from a remote Bluetooth device. When the server is started successfully, the callback is called with ESP_BT_L2CAP_START_EVT. When the connection is established, the callback is called with ESP_BT_L2CAP_OPEN_EVT. This function must be called after esp_bt_l2cap_init() successful and before esp_bt_l2cap_deinit(). - Parameters cntl_flag -- [in] Lower 16-bit security settings mask. local_psm -- [in] Dynamic PSM. - - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_l2cap_stop_all_srv(void) This function stops all L2CAP servers. The operation will close all active L2CAP connection first, then the callback function will be called with ESP_BT_L2CAP_CLOSE_EVT, and the number of ESP_BT_L2CAP_CLOSE_EVT is equal to the number of connection. When the operation is completed, the callback is called with ESP_BT_L2CAP_SRV_STOP_EVT. This function must be called after esp_bt_l2cap_init() successful and before esp_bt_l2cap_deinit(). - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_l2cap_stop_srv(uint16_t local_psm) This function stops a specific L2CAP server. The operation will close all active L2CAP connection first on the specific L2CAP server, then the callback function will be called with ESP_BT_L2CAP_CLOSE_EVT, and the number of ESP_BT_L2CAP_CLOSE_EVT is equal to the number of connection. When the operation is completed, the callback is called with ESP_BT_L2CAP_SRV_STOP_EVT. This function must be called after esp_bt_l2cap_init() successful and before esp_bt_l2cap_deinit(). - Parameters local_psm -- [in] Dynamic PSM. - Returns ESP_OK: success other: failed - - esp_err_t esp_bt_l2cap_vfs_register(void) This function is used to register VFS. Only supports write, read and close. This function must be called after esp_bt_l2cap_init() successful and before esp_bt_l2cap_deinit(). - Returns ESP_OK: success other: failed - Unions - union esp_bt_l2cap_cb_param_t - #include <esp_l2cap_bt_api.h> L2CAP callback parameters union. Public Members - struct esp_bt_l2cap_cb_param_t::l2cap_init_evt_param init L2CAP callback param of ESP_BT_L2CAP_INIT_EVT - struct esp_bt_l2cap_cb_param_t::l2cap_uninit_evt_param uninit L2CAP callback param of ESP_BT_L2CAP_UNINIT_EVT - struct esp_bt_l2cap_cb_param_t::l2cap_open_evt_param open L2CAP callback param of ESP_BT_L2CAP_OPEN_EVT - struct esp_bt_l2cap_cb_param_t::l2cap_close_evt_param close L2CAP callback param of ESP_BT_L2CAP_CLOSE_EVT - struct esp_bt_l2cap_cb_param_t::l2cap_start_evt_param start L2CAP callback param of ESP_BT_L2CAP_START_EVT - struct esp_bt_l2cap_cb_param_t::l2cap_cl_init_evt_param cl_init L2CAP callback param of ESP_BT_L2CAP_CL_INIT_EVT - struct esp_bt_l2cap_cb_param_t::l2cap_srv_stop_evt_param srv_stop L2CAP callback param of ESP_BT_L2CAP_SRV_STOP_EVT - struct l2cap_cl_init_evt_param - #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_CL_INIT_EVT. Public Members - esp_bt_l2cap_status_t status status - uint32_t handle The connection handle - uint8_t sec_id security ID used by this server - esp_bt_l2cap_status_t status - struct l2cap_close_evt_param - #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_CLOSE_EVT. Public Members - esp_bt_l2cap_status_t status status - uint32_t handle The connection handle - bool async FALSE, if local initiates disconnect - esp_bt_l2cap_status_t status - struct l2cap_init_evt_param - #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_INIT_EVT. Public Members - esp_bt_l2cap_status_t status status - esp_bt_l2cap_status_t status - struct l2cap_open_evt_param - #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_OPEN_EVT. Public Members - esp_bt_l2cap_status_t status status - uint32_t handle The connection handle - int fd File descriptor - esp_bd_addr_t rem_bda The peer address - int32_t tx_mtu The transmit MTU - esp_bt_l2cap_status_t status - struct l2cap_srv_stop_evt_param - #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_SRV_STOP_EVT. Public Members - esp_bt_l2cap_status_t status status - uint8_t psm local psm - esp_bt_l2cap_status_t status - struct l2cap_start_evt_param - #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_START_EVT. Public Members - esp_bt_l2cap_status_t status status - uint32_t handle The connection handle - uint8_t sec_id security ID used by this server - esp_bt_l2cap_status_t status - struct l2cap_uninit_evt_param - #include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_UNINIT_EVT. Public Members - esp_bt_l2cap_status_t status status - esp_bt_l2cap_status_t status - struct esp_bt_l2cap_cb_param_t::l2cap_init_evt_param init Macros - ESP_BT_L2CAP_SEC_NONE Security Setting Mask. Use these three mask mode: ESP_BT_L2CAP_SEC_NONE ESP_BT_L2CAP_SEC_AUTHENTICATE (ESP_BT_L2CAP_SEC_ENCRYPT|ESP_BT_L2CAP_SEC_AUTHENTICATE) No security - - ESP_BT_L2CAP_SEC_AUTHORIZE Authorization required - ESP_BT_L2CAP_SEC_AUTHENTICATE Authentication required - ESP_BT_L2CAP_SEC_ENCRYPT Encryption required Type Definitions - typedef uint32_t esp_bt_l2cap_cntl_flags_t - typedef void (*esp_bt_l2cap_cb_t)(esp_bt_l2cap_cb_event_t event, esp_bt_l2cap_cb_param_t *param) L2CAP callback function type. - Param event Event type - Param param Point to callback parameter, currently is union type Enumerations - enum esp_bt_l2cap_status_t L2CAP operation success and failure codes. Values: - enumerator ESP_BT_L2CAP_SUCCESS Successful operation. - enumerator ESP_BT_L2CAP_FAILURE Generic failure. - enumerator ESP_BT_L2CAP_BUSY Temporarily can not handle this request. - enumerator ESP_BT_L2CAP_NO_RESOURCE No more resource - enumerator ESP_BT_L2CAP_NEED_INIT L2CAP module shall init first - enumerator ESP_BT_L2CAP_NEED_DEINIT L2CAP module shall deinit first - enumerator ESP_BT_L2CAP_NO_CONNECTION Connection may have been closed - enumerator ESP_BT_L2CAP_NO_SERVER No server - enumerator ESP_BT_L2CAP_SUCCESS - enum esp_bt_l2cap_cb_event_t L2CAP callback function events. Values: - enumerator ESP_BT_L2CAP_INIT_EVT When L2CAP is initialized, the event comes - enumerator ESP_BT_L2CAP_UNINIT_EVT When L2CAP is deinitialized, the event comes - enumerator ESP_BT_L2CAP_OPEN_EVT When L2CAP Client connection open, the event comes - enumerator ESP_BT_L2CAP_CLOSE_EVT When L2CAP connection closed, the event comes - enumerator ESP_BT_L2CAP_START_EVT When L2CAP server started, the event comes - enumerator ESP_BT_L2CAP_CL_INIT_EVT When L2CAP client initiated a connection, the event comes - enumerator ESP_BT_L2CAP_SRV_STOP_EVT When L2CAP server stopped, the event comes - enumerator ESP_BT_L2CAP_INIT_EVT
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_l2cap_bt.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Bluetooth® SDP APIs
null
espressif.com
2016-01-01
c678f657ae4b9947
null
null
Bluetooth® SDP APIs Overview Bluetooth SDP reference APIs. API Reference Header File This header file can be included with: #include "esp_sdp_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_sdp_register_callback(esp_sdp_cb_t callback) This function is called to init callbacks with SDP module. Parameters callback -- [in] pointer to the init callback function. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters callback -- [in] pointer to the init callback function. Returns ESP_OK: success other: failed esp_err_t esp_sdp_init(void) This function is called to init SDP module. When the operation is completed, the callback function will be called with ESP_SDP_INIT_EVT. This function should be called after esp_bluedroid_enable() completes successfully. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Returns ESP_OK: success other: failed esp_err_t esp_sdp_deinit(void) This function is called to de-initialize SDP module. The operation will remove all SDP records, then the callback function will be called with ESP_SDP_REMOVE_RECORD_COMP_EVT, and the number of ESP_SDP_REMOVE_RECORD_COMP_EVT is equal to the number of SDP records.When the operation is completed, the callback function will be called with ESP_SDP_DEINIT_EVT. This function should be called after esp_sdp_init() completes successfully. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Returns ESP_OK: success other: failed esp_err_t esp_sdp_search_record(esp_bd_addr_t bd_addr, esp_bt_uuid_t uuid) This function is called to performs service discovery for the services provided by the given peer device. When the operation is completed, the callback function will be called with ESP_SDP_SEARCH_COMP_EVT. This function must be called after esp_sdp_init() successful and before esp_sdp_deinit(). Parameters bd_addr -- [in] Remote device bluetooth device address. uuid -- [in] Service UUID of the remote device. bd_addr -- [in] Remote device bluetooth device address. uuid -- [in] Service UUID of the remote device. bd_addr -- [in] Remote device bluetooth device address. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters bd_addr -- [in] Remote device bluetooth device address. uuid -- [in] Service UUID of the remote device. Returns ESP_OK: success other: failed esp_err_t esp_sdp_create_record(esp_bluetooth_sdp_record_t *record) This function is called to create SDP records. When the operation is completed, the callback function will be called with ESP_SDP_CREATE_RECORD_COMP_EVT. This function must be called after esp_sdp_init() successful and before esp_sdp_deinit(). Parameters record -- [in] The SDP record to create. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters record -- [in] The SDP record to create. Returns ESP_OK: success other: failed esp_err_t esp_sdp_remove_record(int record_handle) This function is called to remove a SDP record. When the operation is completed, the callback function will be called with ESP_SDP_REMOVE_RECORD_COMP_EVT. This function must be called after esp_sdp_init() successful and before esp_sdp_deinit(). Parameters record_handle -- [in] The SDP record handle. Returns ESP_OK: success other: failed ESP_OK: success other: failed ESP_OK: success Parameters record_handle -- [in] The SDP record handle. Returns ESP_OK: success other: failed Unions union esp_bluetooth_sdp_record_t #include <esp_sdp_api.h> SDP record parameters union. Public Members esp_bluetooth_sdp_hdr_overlay_t hdr General info esp_bluetooth_sdp_hdr_overlay_t hdr General info esp_bluetooth_sdp_mas_record_t mas Message Access Profile - Server esp_bluetooth_sdp_mas_record_t mas Message Access Profile - Server esp_bluetooth_sdp_mns_record_t mns Message Access Profile - Client (Notification Server) esp_bluetooth_sdp_mns_record_t mns Message Access Profile - Client (Notification Server) esp_bluetooth_sdp_pse_record_t pse Phone Book Profile - Server esp_bluetooth_sdp_pse_record_t pse Phone Book Profile - Server esp_bluetooth_sdp_pce_record_t pce Phone Book Profile - Client esp_bluetooth_sdp_pce_record_t pce Phone Book Profile - Client esp_bluetooth_sdp_ops_record_t ops Object Push Profile esp_bluetooth_sdp_ops_record_t ops Object Push Profile esp_bluetooth_sdp_sap_record_t sap SIM Access Profile esp_bluetooth_sdp_sap_record_t sap SIM Access Profile esp_bluetooth_sdp_hdr_overlay_t hdr union esp_sdp_cb_param_t #include <esp_sdp_api.h> SDP callback parameters union. Public Members struct esp_sdp_cb_param_t::sdp_init_evt_param init SDP callback param of ESP_SDP_INIT_EVT struct esp_sdp_cb_param_t::sdp_init_evt_param init SDP callback param of ESP_SDP_INIT_EVT struct esp_sdp_cb_param_t::sdp_deinit_evt_param deinit SDP callback param of ESP_SDP_DEINIT_EVT struct esp_sdp_cb_param_t::sdp_deinit_evt_param deinit SDP callback param of ESP_SDP_DEINIT_EVT struct esp_sdp_cb_param_t::sdp_search_evt_param search SDP callback param of ESP_SDP_SEARCH_COMP_EVT struct esp_sdp_cb_param_t::sdp_search_evt_param search SDP callback param of ESP_SDP_SEARCH_COMP_EVT struct esp_sdp_cb_param_t::sdp_crate_record_evt_param create_record SDP callback param of ESP_SDP_CREATE_RECORD_COMP_EVT struct esp_sdp_cb_param_t::sdp_crate_record_evt_param create_record SDP callback param of ESP_SDP_CREATE_RECORD_COMP_EVT struct esp_sdp_cb_param_t::sdp_remove_record_evt_param remove_record SDP callback param of ESP_SDP_REMOVE_RECORD_COMP_EVT struct esp_sdp_cb_param_t::sdp_remove_record_evt_param remove_record SDP callback param of ESP_SDP_REMOVE_RECORD_COMP_EVT struct sdp_crate_record_evt_param #include <esp_sdp_api.h> ESP_SDP_CREATE_RECORD_COMP_EVT. Public Members esp_sdp_status_t status status esp_sdp_status_t status status int record_handle SDP record handle int record_handle SDP record handle esp_sdp_status_t status struct sdp_crate_record_evt_param #include <esp_sdp_api.h> ESP_SDP_CREATE_RECORD_COMP_EVT. Public Members esp_sdp_status_t status status int record_handle SDP record handle struct sdp_deinit_evt_param #include <esp_sdp_api.h> ESP_SDP_DEINIT_EVT. struct sdp_deinit_evt_param #include <esp_sdp_api.h> ESP_SDP_DEINIT_EVT. struct sdp_init_evt_param #include <esp_sdp_api.h> ESP_SDP_INIT_EVT. struct sdp_init_evt_param #include <esp_sdp_api.h> ESP_SDP_INIT_EVT. struct sdp_remove_record_evt_param #include <esp_sdp_api.h> ESP_SDP_REMOVE_RECORD_COMP_EVT. struct sdp_remove_record_evt_param #include <esp_sdp_api.h> ESP_SDP_REMOVE_RECORD_COMP_EVT. struct sdp_search_evt_param #include <esp_sdp_api.h> ESP_SDP_SEARCH_COMP_EVT. Public Members esp_sdp_status_t status status esp_sdp_status_t status status esp_bd_addr_t remote_addr remote device address esp_bd_addr_t remote_addr remote device address esp_bt_uuid_t sdp_uuid service uuid esp_bt_uuid_t sdp_uuid service uuid int record_count Number of SDP records int record_count Number of SDP records esp_bluetooth_sdp_record_t *records SDP records esp_bluetooth_sdp_record_t *records SDP records esp_sdp_status_t status struct sdp_search_evt_param #include <esp_sdp_api.h> ESP_SDP_SEARCH_COMP_EVT. Public Members esp_sdp_status_t status status esp_bd_addr_t remote_addr remote device address esp_bt_uuid_t sdp_uuid service uuid int record_count Number of SDP records esp_bluetooth_sdp_record_t *records SDP records struct esp_sdp_cb_param_t::sdp_init_evt_param init Structures struct bluetooth_sdp_hdr_overlay Some signals need additional pointers, hence we introduce a generic way to handle these pointers. Public Members esp_bluetooth_sdp_types_t type SDP type esp_bluetooth_sdp_types_t type SDP type esp_bt_uuid_t uuid UUID type, include uuid and uuid length esp_bt_uuid_t uuid UUID type, include uuid and uuid length uint32_t service_name_length Service name length uint32_t service_name_length Service name length char *service_name service name char *service_name service name int32_t rfcomm_channel_number rfcomm channel number, if not used set to -1 int32_t rfcomm_channel_number rfcomm channel number, if not used set to -1 int32_t l2cap_psm l2cap psm, if not used set to -1 int32_t l2cap_psm l2cap psm, if not used set to -1 int32_t profile_version profile version int32_t profile_version profile version int user1_ptr_len see esp_bluetooth_sdp_ops_record_t int user1_ptr_len see esp_bluetooth_sdp_ops_record_t uint8_t *user1_ptr see esp_bluetooth_sdp_ops_record_t uint8_t *user1_ptr see esp_bluetooth_sdp_ops_record_t int user2_ptr_len see esp_bluetooth_sdp_ops_record_t int user2_ptr_len see esp_bluetooth_sdp_ops_record_t uint8_t *user2_ptr see esp_bluetooth_sdp_ops_record_t uint8_t *user2_ptr see esp_bluetooth_sdp_ops_record_t esp_bluetooth_sdp_types_t type struct bluetooth_sdp_mas_record Message Access Profile - Server parameters. Public Members esp_bluetooth_sdp_hdr_overlay_t hdr General info esp_bluetooth_sdp_hdr_overlay_t hdr General info uint32_t mas_instance_id MAS Instance ID uint32_t mas_instance_id MAS Instance ID uint32_t supported_features Map supported features uint32_t supported_features Map supported features uint32_t supported_message_types Supported message types uint32_t supported_message_types Supported message types esp_bluetooth_sdp_hdr_overlay_t hdr struct bluetooth_sdp_mns_record Message Access Profile - Client (Notification Server) parameters. Public Members esp_bluetooth_sdp_hdr_overlay_t hdr General info esp_bluetooth_sdp_hdr_overlay_t hdr General info uint32_t supported_features Supported features uint32_t supported_features Supported features esp_bluetooth_sdp_hdr_overlay_t hdr struct bluetooth_sdp_pse_record Phone Book Profile - Server parameters. Public Members esp_bluetooth_sdp_hdr_overlay_t hdr General info esp_bluetooth_sdp_hdr_overlay_t hdr General info uint32_t supported_features Pbap Supported Features uint32_t supported_features Pbap Supported Features uint32_t supported_repositories Supported Repositories uint32_t supported_repositories Supported Repositories esp_bluetooth_sdp_hdr_overlay_t hdr struct bluetooth_sdp_pce_record Phone Book Profile - Client parameters. Public Members esp_bluetooth_sdp_hdr_overlay_t hdr General info esp_bluetooth_sdp_hdr_overlay_t hdr General info esp_bluetooth_sdp_hdr_overlay_t hdr struct bluetooth_sdp_ops_record Object Push Profile parameters. Public Members esp_bluetooth_sdp_hdr_overlay_t hdr General info esp_bluetooth_sdp_hdr_overlay_t hdr General info int supported_formats_list_len Supported formats list length int supported_formats_list_len Supported formats list length uint8_t supported_formats_list[SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH] Supported formats list uint8_t supported_formats_list[SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH] Supported formats list esp_bluetooth_sdp_hdr_overlay_t hdr struct bluetooth_sdp_sap_record SIM Access Profile parameters. Public Members esp_bluetooth_sdp_hdr_overlay_t hdr General info esp_bluetooth_sdp_hdr_overlay_t hdr General info esp_bluetooth_sdp_hdr_overlay_t hdr Macros ESP_SDP_SERVER_NAME_MAX Service name max length SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH OPP supported format list maximum length Type Definitions typedef struct bluetooth_sdp_hdr_overlay esp_bluetooth_sdp_hdr_overlay_t Some signals need additional pointers, hence we introduce a generic way to handle these pointers. typedef struct bluetooth_sdp_mas_record esp_bluetooth_sdp_mas_record_t Message Access Profile - Server parameters. typedef struct bluetooth_sdp_mns_record esp_bluetooth_sdp_mns_record_t Message Access Profile - Client (Notification Server) parameters. typedef struct bluetooth_sdp_pse_record esp_bluetooth_sdp_pse_record_t Phone Book Profile - Server parameters. typedef struct bluetooth_sdp_pce_record esp_bluetooth_sdp_pce_record_t Phone Book Profile - Client parameters. typedef struct bluetooth_sdp_ops_record esp_bluetooth_sdp_ops_record_t Object Push Profile parameters. typedef struct bluetooth_sdp_sap_record esp_bluetooth_sdp_sap_record_t SIM Access Profile parameters. typedef void (*esp_sdp_cb_t)(esp_sdp_cb_event_t event, esp_sdp_cb_param_t *param) SDP callback function type. Param event Event type Param param Point to callback parameter, currently is union type Param event Event type Param param Point to callback parameter, currently is union type Enumerations enum esp_sdp_status_t Values: enumerator ESP_SDP_SUCCESS Successful operation. enumerator ESP_SDP_SUCCESS Successful operation. enumerator ESP_SDP_FAILURE Generic failure. enumerator ESP_SDP_FAILURE Generic failure. enumerator ESP_SDP_NO_RESOURCE No more resource enumerator ESP_SDP_NO_RESOURCE No more resource enumerator ESP_SDP_NEED_INIT SDP module shall init first enumerator ESP_SDP_NEED_INIT SDP module shall init first enumerator ESP_SDP_NEED_DEINIT SDP module shall deinit first enumerator ESP_SDP_NEED_DEINIT SDP module shall deinit first enumerator ESP_SDP_NO_CREATE_RECORD No record created enumerator ESP_SDP_NO_CREATE_RECORD No record created enumerator ESP_SDP_SUCCESS enum esp_sdp_cb_event_t SDP callback function events. Values: enumerator ESP_SDP_INIT_EVT When SDP is initialized, the event comes enumerator ESP_SDP_INIT_EVT When SDP is initialized, the event comes enumerator ESP_SDP_DEINIT_EVT When SDP is deinitialized, the event comes enumerator ESP_SDP_DEINIT_EVT When SDP is deinitialized, the event comes enumerator ESP_SDP_SEARCH_COMP_EVT When SDP search complete, the event comes enumerator ESP_SDP_SEARCH_COMP_EVT When SDP search complete, the event comes enumerator ESP_SDP_CREATE_RECORD_COMP_EVT When create SDP records complete, the event comes enumerator ESP_SDP_CREATE_RECORD_COMP_EVT When create SDP records complete, the event comes enumerator ESP_SDP_REMOVE_RECORD_COMP_EVT When remove a SDP record complete, the event comes enumerator ESP_SDP_REMOVE_RECORD_COMP_EVT When remove a SDP record complete, the event comes enumerator ESP_SDP_INIT_EVT enum esp_bluetooth_sdp_types_t SDP record type. Values: enumerator ESP_SDP_TYPE_RAW Used to carry raw SDP search data for unknown UUIDs enumerator ESP_SDP_TYPE_RAW Used to carry raw SDP search data for unknown UUIDs enumerator ESP_SDP_TYPE_MAP_MAS Message Access Profile - Server enumerator ESP_SDP_TYPE_MAP_MAS Message Access Profile - Server enumerator ESP_SDP_TYPE_MAP_MNS Message Access Profile - Client (Notification Server) enumerator ESP_SDP_TYPE_MAP_MNS Message Access Profile - Client (Notification Server) enumerator ESP_SDP_TYPE_PBAP_PSE Phone Book Profile - Server enumerator ESP_SDP_TYPE_PBAP_PSE Phone Book Profile - Server enumerator ESP_SDP_TYPE_PBAP_PCE Phone Book Profile - Client enumerator ESP_SDP_TYPE_PBAP_PCE Phone Book Profile - Client enumerator ESP_SDP_TYPE_OPP_SERVER Object Push Profile enumerator ESP_SDP_TYPE_OPP_SERVER Object Push Profile enumerator ESP_SDP_TYPE_SAP_SERVER SIM Access Profile enumerator ESP_SDP_TYPE_SAP_SERVER SIM Access Profile enumerator ESP_SDP_TYPE_RAW
Bluetooth® SDP APIs Overview Bluetooth SDP reference APIs. API Reference Header File This header file can be included with: #include "esp_sdp_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_sdp_register_callback(esp_sdp_cb_t callback) This function is called to init callbacks with SDP module. - Parameters callback -- [in] pointer to the init callback function. - Returns ESP_OK: success other: failed - - esp_err_t esp_sdp_init(void) This function is called to init SDP module. When the operation is completed, the callback function will be called with ESP_SDP_INIT_EVT. This function should be called after esp_bluedroid_enable() completes successfully. - Returns ESP_OK: success other: failed - - esp_err_t esp_sdp_deinit(void) This function is called to de-initialize SDP module. The operation will remove all SDP records, then the callback function will be called with ESP_SDP_REMOVE_RECORD_COMP_EVT, and the number of ESP_SDP_REMOVE_RECORD_COMP_EVT is equal to the number of SDP records.When the operation is completed, the callback function will be called with ESP_SDP_DEINIT_EVT. This function should be called after esp_sdp_init() completes successfully. - Returns ESP_OK: success other: failed - - esp_err_t esp_sdp_search_record(esp_bd_addr_t bd_addr, esp_bt_uuid_t uuid) This function is called to performs service discovery for the services provided by the given peer device. When the operation is completed, the callback function will be called with ESP_SDP_SEARCH_COMP_EVT. This function must be called after esp_sdp_init() successful and before esp_sdp_deinit(). - Parameters bd_addr -- [in] Remote device bluetooth device address. uuid -- [in] Service UUID of the remote device. - - Returns ESP_OK: success other: failed - - esp_err_t esp_sdp_create_record(esp_bluetooth_sdp_record_t *record) This function is called to create SDP records. When the operation is completed, the callback function will be called with ESP_SDP_CREATE_RECORD_COMP_EVT. This function must be called after esp_sdp_init() successful and before esp_sdp_deinit(). - Parameters record -- [in] The SDP record to create. - Returns ESP_OK: success other: failed - - esp_err_t esp_sdp_remove_record(int record_handle) This function is called to remove a SDP record. When the operation is completed, the callback function will be called with ESP_SDP_REMOVE_RECORD_COMP_EVT. This function must be called after esp_sdp_init() successful and before esp_sdp_deinit(). - Parameters record_handle -- [in] The SDP record handle. - Returns ESP_OK: success other: failed - Unions - union esp_bluetooth_sdp_record_t - #include <esp_sdp_api.h> SDP record parameters union. Public Members - esp_bluetooth_sdp_hdr_overlay_t hdr General info - esp_bluetooth_sdp_mas_record_t mas Message Access Profile - Server - esp_bluetooth_sdp_mns_record_t mns Message Access Profile - Client (Notification Server) - esp_bluetooth_sdp_pse_record_t pse Phone Book Profile - Server - esp_bluetooth_sdp_pce_record_t pce Phone Book Profile - Client - esp_bluetooth_sdp_ops_record_t ops Object Push Profile - esp_bluetooth_sdp_sap_record_t sap SIM Access Profile - esp_bluetooth_sdp_hdr_overlay_t hdr - union esp_sdp_cb_param_t - #include <esp_sdp_api.h> SDP callback parameters union. Public Members - struct esp_sdp_cb_param_t::sdp_init_evt_param init SDP callback param of ESP_SDP_INIT_EVT - struct esp_sdp_cb_param_t::sdp_deinit_evt_param deinit SDP callback param of ESP_SDP_DEINIT_EVT - struct esp_sdp_cb_param_t::sdp_search_evt_param search SDP callback param of ESP_SDP_SEARCH_COMP_EVT - struct esp_sdp_cb_param_t::sdp_crate_record_evt_param create_record SDP callback param of ESP_SDP_CREATE_RECORD_COMP_EVT - struct esp_sdp_cb_param_t::sdp_remove_record_evt_param remove_record SDP callback param of ESP_SDP_REMOVE_RECORD_COMP_EVT - struct sdp_crate_record_evt_param - #include <esp_sdp_api.h> ESP_SDP_CREATE_RECORD_COMP_EVT. Public Members - esp_sdp_status_t status status - int record_handle SDP record handle - esp_sdp_status_t status - struct sdp_deinit_evt_param - #include <esp_sdp_api.h> ESP_SDP_DEINIT_EVT. - struct sdp_init_evt_param - #include <esp_sdp_api.h> ESP_SDP_INIT_EVT. - struct sdp_remove_record_evt_param - #include <esp_sdp_api.h> ESP_SDP_REMOVE_RECORD_COMP_EVT. - struct sdp_search_evt_param - #include <esp_sdp_api.h> ESP_SDP_SEARCH_COMP_EVT. Public Members - esp_sdp_status_t status status - esp_bd_addr_t remote_addr remote device address - esp_bt_uuid_t sdp_uuid service uuid - int record_count Number of SDP records - esp_bluetooth_sdp_record_t *records SDP records - esp_sdp_status_t status - struct esp_sdp_cb_param_t::sdp_init_evt_param init Structures - struct bluetooth_sdp_hdr_overlay Some signals need additional pointers, hence we introduce a generic way to handle these pointers. Public Members - esp_bluetooth_sdp_types_t type SDP type - esp_bt_uuid_t uuid UUID type, include uuid and uuid length - uint32_t service_name_length Service name length - char *service_name service name - int32_t rfcomm_channel_number rfcomm channel number, if not used set to -1 - int32_t l2cap_psm l2cap psm, if not used set to -1 - int32_t profile_version profile version - int user1_ptr_len see esp_bluetooth_sdp_ops_record_t - uint8_t *user1_ptr see esp_bluetooth_sdp_ops_record_t - int user2_ptr_len see esp_bluetooth_sdp_ops_record_t - uint8_t *user2_ptr see esp_bluetooth_sdp_ops_record_t - esp_bluetooth_sdp_types_t type - struct bluetooth_sdp_mas_record Message Access Profile - Server parameters. Public Members - esp_bluetooth_sdp_hdr_overlay_t hdr General info - uint32_t mas_instance_id MAS Instance ID - uint32_t supported_features Map supported features - uint32_t supported_message_types Supported message types - esp_bluetooth_sdp_hdr_overlay_t hdr - struct bluetooth_sdp_mns_record Message Access Profile - Client (Notification Server) parameters. Public Members - esp_bluetooth_sdp_hdr_overlay_t hdr General info - uint32_t supported_features Supported features - esp_bluetooth_sdp_hdr_overlay_t hdr - struct bluetooth_sdp_pse_record Phone Book Profile - Server parameters. Public Members - esp_bluetooth_sdp_hdr_overlay_t hdr General info - uint32_t supported_features Pbap Supported Features - uint32_t supported_repositories Supported Repositories - esp_bluetooth_sdp_hdr_overlay_t hdr - struct bluetooth_sdp_pce_record Phone Book Profile - Client parameters. Public Members - esp_bluetooth_sdp_hdr_overlay_t hdr General info - esp_bluetooth_sdp_hdr_overlay_t hdr - struct bluetooth_sdp_ops_record Object Push Profile parameters. Public Members - esp_bluetooth_sdp_hdr_overlay_t hdr General info - int supported_formats_list_len Supported formats list length - uint8_t supported_formats_list[SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH] Supported formats list - esp_bluetooth_sdp_hdr_overlay_t hdr - struct bluetooth_sdp_sap_record SIM Access Profile parameters. Public Members - esp_bluetooth_sdp_hdr_overlay_t hdr General info - esp_bluetooth_sdp_hdr_overlay_t hdr Macros - ESP_SDP_SERVER_NAME_MAX Service name max length - SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH OPP supported format list maximum length Type Definitions - typedef struct bluetooth_sdp_hdr_overlay esp_bluetooth_sdp_hdr_overlay_t Some signals need additional pointers, hence we introduce a generic way to handle these pointers. - typedef struct bluetooth_sdp_mas_record esp_bluetooth_sdp_mas_record_t Message Access Profile - Server parameters. - typedef struct bluetooth_sdp_mns_record esp_bluetooth_sdp_mns_record_t Message Access Profile - Client (Notification Server) parameters. - typedef struct bluetooth_sdp_pse_record esp_bluetooth_sdp_pse_record_t Phone Book Profile - Server parameters. - typedef struct bluetooth_sdp_pce_record esp_bluetooth_sdp_pce_record_t Phone Book Profile - Client parameters. - typedef struct bluetooth_sdp_ops_record esp_bluetooth_sdp_ops_record_t Object Push Profile parameters. - typedef struct bluetooth_sdp_sap_record esp_bluetooth_sdp_sap_record_t SIM Access Profile parameters. - typedef void (*esp_sdp_cb_t)(esp_sdp_cb_event_t event, esp_sdp_cb_param_t *param) SDP callback function type. - Param event Event type - Param param Point to callback parameter, currently is union type Enumerations - enum esp_sdp_status_t Values: - enumerator ESP_SDP_SUCCESS Successful operation. - enumerator ESP_SDP_FAILURE Generic failure. - enumerator ESP_SDP_NO_RESOURCE No more resource - enumerator ESP_SDP_NEED_INIT SDP module shall init first - enumerator ESP_SDP_NEED_DEINIT SDP module shall deinit first - enumerator ESP_SDP_NO_CREATE_RECORD No record created - enumerator ESP_SDP_SUCCESS - enum esp_sdp_cb_event_t SDP callback function events. Values: - enumerator ESP_SDP_INIT_EVT When SDP is initialized, the event comes - enumerator ESP_SDP_DEINIT_EVT When SDP is deinitialized, the event comes - enumerator ESP_SDP_SEARCH_COMP_EVT When SDP search complete, the event comes - enumerator ESP_SDP_CREATE_RECORD_COMP_EVT When create SDP records complete, the event comes - enumerator ESP_SDP_REMOVE_RECORD_COMP_EVT When remove a SDP record complete, the event comes - enumerator ESP_SDP_INIT_EVT - enum esp_bluetooth_sdp_types_t SDP record type. Values: - enumerator ESP_SDP_TYPE_RAW Used to carry raw SDP search data for unknown UUIDs - enumerator ESP_SDP_TYPE_MAP_MAS Message Access Profile - Server - enumerator ESP_SDP_TYPE_MAP_MNS Message Access Profile - Client (Notification Server) - enumerator ESP_SDP_TYPE_PBAP_PSE Phone Book Profile - Server - enumerator ESP_SDP_TYPE_PBAP_PCE Phone Book Profile - Client - enumerator ESP_SDP_TYPE_OPP_SERVER Object Push Profile - enumerator ESP_SDP_TYPE_SAP_SERVER SIM Access Profile - enumerator ESP_SDP_TYPE_RAW
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp_sdp.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Controller && VHCI
null
espressif.com
2016-01-01
965afe94aa2a9049
null
null
Controller && VHCI Application Example Check bluetooth/hci folder in ESP-IDF examples, which contains the following application: This is a Bluetooth® Low Energy (Bluetooth LE) advertising demo with virtual HCI interface. Send Reset/ADV_PARAM/ADV_DATA/ADV_ENABLE HCI command for Bluetooth Low Energy advertising - bluetooth/hci/controller_vhci_ble_adv. API Reference Header File This header file can be included with: #include "esp_bt.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_tx_power_set(esp_ble_power_type_t power_type, esp_power_level_t power_level) Set BLE TX power Connection Tx power should only be set after connection created. Parameters power_type -- : The type of which tx power, could set Advertising/Connection/Default and etc power_level -- Power level(index) corresponding to absolute value(dbm) power_type -- : The type of which tx power, could set Advertising/Connection/Default and etc power_level -- Power level(index) corresponding to absolute value(dbm) power_type -- : The type of which tx power, could set Advertising/Connection/Default and etc Returns ESP_OK - success, other - failed Parameters power_type -- : The type of which tx power, could set Advertising/Connection/Default and etc power_level -- Power level(index) corresponding to absolute value(dbm) Returns ESP_OK - success, other - failed esp_power_level_t esp_ble_tx_power_get(esp_ble_power_type_t power_type) Get BLE TX power Connection Tx power should only be get after connection created. Parameters power_type -- : The type of which tx power, could set Advertising/Connection/Default and etc Returns >= 0 - Power level, < 0 - Invalid Parameters power_type -- : The type of which tx power, could set Advertising/Connection/Default and etc Returns >= 0 - Power level, < 0 - Invalid esp_err_t esp_bredr_tx_power_set(esp_power_level_t min_power_level, esp_power_level_t max_power_level) Set BR/EDR TX power BR/EDR power control will use the power in range of minimum value and maximum value. The power level will effect the global BR/EDR TX power, such inquire, page, connection and so on. Please call the function after esp_bt_controller_enable and before any function which cause RF do TX. So you can call the function before doing discovery, profile init and so on. For example, if you want BR/EDR use the new TX power to do inquire, you should call this function before inquire. Another word, If call this function when BR/EDR is in inquire(ING), please do inquire again after call this function. Default minimum power level is ESP_PWR_LVL_N0, and maximum power level is ESP_PWR_LVL_P3. Parameters min_power_level -- The minimum power level max_power_level -- The maximum power level min_power_level -- The minimum power level max_power_level -- The maximum power level min_power_level -- The minimum power level Returns ESP_OK - success, other - failed Parameters min_power_level -- The minimum power level max_power_level -- The maximum power level Returns ESP_OK - success, other - failed esp_err_t esp_bredr_tx_power_get(esp_power_level_t *min_power_level, esp_power_level_t *max_power_level) Get BR/EDR TX power If the argument is not NULL, then store the corresponding value. Parameters min_power_level -- The minimum power level max_power_level -- The maximum power level min_power_level -- The minimum power level max_power_level -- The maximum power level min_power_level -- The minimum power level Returns ESP_OK - success, other - failed Parameters min_power_level -- The minimum power level max_power_level -- The maximum power level Returns ESP_OK - success, other - failed esp_err_t esp_bredr_sco_datapath_set(esp_sco_data_path_t data_path) Set default SCO data path Should be called after controller is enabled, and before (e)SCO link is established. Parameters data_path -- SCO data path Returns ESP_OK - success, other - failed Parameters data_path -- SCO data path Returns ESP_OK - success, other - failed esp_err_t esp_bt_controller_init(esp_bt_controller_config_t *cfg) Initialize BT controller to allocate task and other resource. This function should be called only once, before any other BT functions are called. Parameters cfg -- Initial configuration of BT controller. Different from previous version, there's a mode and some connection configuration in "cfg" to configure controller work mode and allocate the resource which is needed. Returns ESP_OK - success, other - failed Parameters cfg -- Initial configuration of BT controller. Different from previous version, there's a mode and some connection configuration in "cfg" to configure controller work mode and allocate the resource which is needed. Returns ESP_OK - success, other - failed esp_err_t esp_bt_controller_deinit(void) De-initialize BT controller to free resource and delete task. You should stop advertising and scanning, as well as disconnect all existing connections before de-initializing BT controller. This function should be called only once, after any other BT functions are called. Returns ESP_OK - success, other - failed Returns ESP_OK - success, other - failed esp_err_t esp_bt_controller_enable(esp_bt_mode_t mode) Enable BT controller. Due to a known issue, you cannot call esp_bt_controller_enable() a second time to change the controller mode dynamically. To change controller mode, call esp_bt_controller_disable() and then call esp_bt_controller_enable() with the new mode. Parameters mode -- : the mode(BLE/BT/BTDM) to enable. For compatible of API, retain this argument. This mode must be equal as the mode in "cfg" of esp_bt_controller_init(). Returns ESP_OK - success, other - failed Parameters mode -- : the mode(BLE/BT/BTDM) to enable. For compatible of API, retain this argument. This mode must be equal as the mode in "cfg" of esp_bt_controller_init(). Returns ESP_OK - success, other - failed esp_err_t esp_bt_controller_disable(void) Disable BT controller. Returns ESP_OK - success, other - failed Returns ESP_OK - success, other - failed esp_bt_controller_status_t esp_bt_controller_get_status(void) Get BT controller is initialised/de-initialised/enabled/disabled. Returns status value Returns status value bool esp_vhci_host_check_send_available(void) esp_vhci_host_check_send_available used for check actively if the host can send packet to controller or not. Returns true for ready to send, false means cannot send packet Returns true for ready to send, false means cannot send packet void esp_vhci_host_send_packet(uint8_t *data, uint16_t len) esp_vhci_host_send_packet host send packet to controller Should not call this function from within a critical section or when the scheduler is suspended. Parameters data -- the packet point len -- the packet length data -- the packet point len -- the packet length data -- the packet point Parameters data -- the packet point len -- the packet length esp_err_t esp_vhci_host_register_callback(const esp_vhci_host_callback_t *callback) esp_vhci_host_register_callback register the vhci reference callback struct defined by vhci_host_callback structure. Parameters callback -- esp_vhci_host_callback type variable Returns ESP_OK - success, ESP_FAIL - failed Parameters callback -- esp_vhci_host_callback type variable Returns ESP_OK - success, ESP_FAIL - failed esp_err_t esp_bt_controller_mem_release(esp_bt_mode_t mode) esp_bt_controller_mem_release release the controller memory as per the mode This function releases the BSS, data and other sections of the controller to heap. The total size is about 70k bytes. esp_bt_controller_mem_release(mode) should be called only before esp_bt_controller_init() or after esp_bt_controller_deinit(). Note that once BT controller memory is released, the process cannot be reversed. It means you cannot use the bluetooth mode which you have released by this function. If your firmware will later upgrade the Bluetooth controller mode (BLE -> BT Classic or disabled -> enabled) then do not call this function. If the app calls esp_bt_controller_enable(ESP_BT_MODE_BLE) to use BLE only then it is safe to call esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT) at initialization time to free unused BT Classic memory. If the mode is ESP_BT_MODE_BTDM, then it may be useful to call API esp_bt_mem_release(ESP_BT_MODE_BTDM) instead, which internally calls esp_bt_controller_mem_release(ESP_BT_MODE_BTDM) and additionally releases the BSS and data consumed by the BT/BLE host stack to heap. For more details about usage please refer to the documentation of esp_bt_mem_release() function Parameters mode -- : the mode want to release memory Returns ESP_OK - success, other - failed Parameters mode -- : the mode want to release memory Returns ESP_OK - success, other - failed esp_err_t esp_bt_mem_release(esp_bt_mode_t mode) esp_bt_mem_release release controller memory and BSS and data section of the BT/BLE host stack as per the mode This function first releases controller memory by internally calling esp_bt_controller_mem_release(). Additionally, if the mode is set to ESP_BT_MODE_BTDM, it also releases the BSS and data consumed by the BT/BLE host stack to heap Note that once BT memory is released, the process cannot be reversed. It means you cannot use the bluetooth mode which you have released by this function. If your firmware will later upgrade the Bluetooth controller mode (BLE -> BT Classic or disabled -> enabled) then do not call this function. If you never intend to use bluetooth in a current boot-up cycle, you can call esp_bt_mem_release(ESP_BT_MODE_BTDM) before esp_bt_controller_init or after esp_bt_controller_deinit. For example, if a user only uses bluetooth for setting the WiFi configuration, and does not use bluetooth in the rest of the product operation". In such cases, after receiving the WiFi configuration, you can disable/deinit bluetooth and release its memory. Below is the sequence of APIs to be called for such scenarios: esp_bluedroid_disable(); esp_bluedroid_deinit(); esp_bt_controller_disable(); esp_bt_controller_deinit(); esp_bt_mem_release(ESP_BT_MODE_BTDM); Note In case of NimBLE host, to release BSS and data memory to heap, the mode needs to be set to ESP_BT_MODE_BTDM as controller is dual mode. Parameters mode -- : the mode whose memory is to be released Returns ESP_OK - success, other - failed Parameters mode -- : the mode whose memory is to be released Returns ESP_OK - success, other - failed esp_err_t esp_bt_sleep_enable(void) enable bluetooth to enter modem sleep Note that this function shall not be invoked before esp_bt_controller_enable() There are currently two options for bluetooth modem sleep, one is ORIG mode, and another is EVED Mode. EVED Mode is intended for BLE only. For ORIG mode: Bluetooth modem sleep is enabled in controller start up by default if CONFIG_CTRL_BTDM_MODEM_SLEEP is set and "ORIG mode" is selected. In ORIG modem sleep mode, bluetooth controller will switch off some components and pause to work every now and then, if there is no event to process; and wakeup according to the scheduled interval and resume the work. It can also wakeup earlier upon external request using function "esp_bt_controller_wakeup_request". Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Returns ESP_OK : success other : failed esp_err_t esp_bt_sleep_disable(void) disable bluetooth modem sleep Note that this function shall not be invoked before esp_bt_controller_enable() If esp_bt_sleep_disable() is called, bluetooth controller will not be allowed to enter modem sleep; If ORIG modem sleep mode is in use, if this function is called, bluetooth controller may not immediately wake up if it is dormant then. In this case, esp_bt_controller_wakeup_request() can be used to shorten the time for wakeup. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Returns ESP_OK : success other : failed esp_err_t esp_ble_scan_dupilcate_list_flush(void) Manually clear scan duplicate list. Note that scan duplicate list will be automatically cleared when the maximum amount of device in the filter is reached the amount of device in the filter can be configured in menuconfig. Note This function name is incorrectly spelled, it will be fixed in release 5.x version. Returns ESP_OK : success other : failed ESP_OK : success other : failed ESP_OK : success Returns ESP_OK : success other : failed void esp_wifi_bt_power_domain_on(void) bt Wi-Fi power domain power on void esp_wifi_bt_power_domain_off(void) bt Wi-Fi power domain power off Structures struct esp_bt_controller_config_t Controller config options, depend on config mask. Config mask indicate which functions enabled, this means some options or parameters of some functions enabled by config mask. Public Members uint16_t controller_task_stack_size Bluetooth controller task stack size uint16_t controller_task_stack_size Bluetooth controller task stack size uint8_t controller_task_prio Bluetooth controller task priority uint8_t controller_task_prio Bluetooth controller task priority uint8_t hci_uart_no If use UART1/2 as HCI IO interface, indicate UART number uint8_t hci_uart_no If use UART1/2 as HCI IO interface, indicate UART number uint32_t hci_uart_baudrate If use UART1/2 as HCI IO interface, indicate UART baudrate uint32_t hci_uart_baudrate If use UART1/2 as HCI IO interface, indicate UART baudrate uint8_t scan_duplicate_mode scan duplicate mode uint8_t scan_duplicate_mode scan duplicate mode uint8_t scan_duplicate_type scan duplicate type uint8_t scan_duplicate_type scan duplicate type uint16_t normal_adv_size Normal adv size for scan duplicate uint16_t normal_adv_size Normal adv size for scan duplicate uint16_t mesh_adv_size Mesh adv size for scan duplicate uint16_t mesh_adv_size Mesh adv size for scan duplicate uint16_t send_adv_reserved_size Controller minimum memory value uint16_t send_adv_reserved_size Controller minimum memory value uint32_t controller_debug_flag Controller debug log flag uint32_t controller_debug_flag Controller debug log flag uint8_t mode Controller mode: BR/EDR, BLE or Dual Mode uint8_t mode Controller mode: BR/EDR, BLE or Dual Mode uint8_t ble_max_conn BLE maximum connection numbers uint8_t ble_max_conn BLE maximum connection numbers uint8_t bt_max_acl_conn BR/EDR maximum ACL connection numbers uint8_t bt_max_acl_conn BR/EDR maximum ACL connection numbers uint8_t bt_sco_datapath SCO data path, i.e. HCI or PCM module uint8_t bt_sco_datapath SCO data path, i.e. HCI or PCM module bool auto_latency BLE auto latency, used to enhance classic BT performance bool auto_latency BLE auto latency, used to enhance classic BT performance bool bt_legacy_auth_vs_evt BR/EDR Legacy auth complete event required to protect from BIAS attack bool bt_legacy_auth_vs_evt BR/EDR Legacy auth complete event required to protect from BIAS attack uint8_t bt_max_sync_conn BR/EDR maximum ACL connection numbers. Effective in menuconfig uint8_t bt_max_sync_conn BR/EDR maximum ACL connection numbers. Effective in menuconfig uint8_t ble_sca BLE low power crystal accuracy index uint8_t ble_sca BLE low power crystal accuracy index uint8_t pcm_role PCM role (master & slave) uint8_t pcm_role PCM role (master & slave) uint8_t pcm_polar PCM polar trig (falling clk edge & rising clk edge) uint8_t pcm_polar PCM polar trig (falling clk edge & rising clk edge) bool hli Using high level interrupt or not bool hli Using high level interrupt or not uint16_t dup_list_refresh_period Duplicate scan list refresh period uint16_t dup_list_refresh_period Duplicate scan list refresh period uint32_t magic Magic number uint32_t magic Magic number uint16_t controller_task_stack_size struct esp_vhci_host_callback esp_vhci_host_callback used for vhci call host function to notify what host need to do Macros ESP_BT_CONTROLLER_CONFIG_MAGIC_VAL BT_CONTROLLER_INIT_CONFIG_DEFAULT() Type Definitions typedef struct esp_vhci_host_callback esp_vhci_host_callback_t esp_vhci_host_callback used for vhci call host function to notify what host need to do Enumerations enum esp_bt_mode_t Bluetooth mode for controller enable/disable. Values: enumerator ESP_BT_MODE_IDLE Bluetooth is not running enumerator ESP_BT_MODE_IDLE Bluetooth is not running enumerator ESP_BT_MODE_BLE Run BLE mode enumerator ESP_BT_MODE_BLE Run BLE mode enumerator ESP_BT_MODE_CLASSIC_BT Run Classic BT mode enumerator ESP_BT_MODE_CLASSIC_BT Run Classic BT mode enumerator ESP_BT_MODE_BTDM Run dual mode enumerator ESP_BT_MODE_BTDM Run dual mode enumerator ESP_BT_MODE_IDLE enum [anonymous] BLE sleep clock accuracy(SCA), values for ble_sca field in esp_bt_controller_config_t, currently only ESP_BLE_SCA_500PPM and ESP_BLE_SCA_250PPM are supported. Values: enumerator ESP_BLE_SCA_500PPM BLE SCA at 500ppm enumerator ESP_BLE_SCA_500PPM BLE SCA at 500ppm enumerator ESP_BLE_SCA_250PPM BLE SCA at 250ppm enumerator ESP_BLE_SCA_250PPM BLE SCA at 250ppm enumerator ESP_BLE_SCA_150PPM BLE SCA at 150ppm enumerator ESP_BLE_SCA_150PPM BLE SCA at 150ppm enumerator ESP_BLE_SCA_100PPM BLE SCA at 100ppm enumerator ESP_BLE_SCA_100PPM BLE SCA at 100ppm enumerator ESP_BLE_SCA_75PPM BLE SCA at 75ppm enumerator ESP_BLE_SCA_75PPM BLE SCA at 75ppm enumerator ESP_BLE_SCA_50PPM BLE SCA at 50ppm enumerator ESP_BLE_SCA_50PPM BLE SCA at 50ppm enumerator ESP_BLE_SCA_30PPM BLE SCA at 30ppm enumerator ESP_BLE_SCA_30PPM BLE SCA at 30ppm enumerator ESP_BLE_SCA_20PPM BLE SCA at 20ppm enumerator ESP_BLE_SCA_20PPM BLE SCA at 20ppm enumerator ESP_BLE_SCA_500PPM enum esp_bt_controller_status_t Bluetooth controller enable/disable/initialised/de-initialised status. Values: enumerator ESP_BT_CONTROLLER_STATUS_IDLE enumerator ESP_BT_CONTROLLER_STATUS_IDLE enumerator ESP_BT_CONTROLLER_STATUS_INITED enumerator ESP_BT_CONTROLLER_STATUS_INITED enumerator ESP_BT_CONTROLLER_STATUS_ENABLED enumerator ESP_BT_CONTROLLER_STATUS_ENABLED enumerator ESP_BT_CONTROLLER_STATUS_NUM enumerator ESP_BT_CONTROLLER_STATUS_NUM enumerator ESP_BT_CONTROLLER_STATUS_IDLE enum esp_ble_power_type_t BLE tx power type ESP_BLE_PWR_TYPE_CONN_HDL0-8: for each connection, and only be set after connection completed. when disconnect, the correspond TX power is not effected. ESP_BLE_PWR_TYPE_ADV : for advertising/scan response. ESP_BLE_PWR_TYPE_SCAN : for scan. ESP_BLE_PWR_TYPE_DEFAULT : if each connection's TX power is not set, it will use this default value. if neither in scan mode nor in adv mode, it will use this default value. If none of power type is set, system will use ESP_PWR_LVL_P3 as default for ADV/SCAN/CONN0-9. Values: enumerator ESP_BLE_PWR_TYPE_CONN_HDL0 For connection handle 0 enumerator ESP_BLE_PWR_TYPE_CONN_HDL0 For connection handle 0 enumerator ESP_BLE_PWR_TYPE_CONN_HDL1 For connection handle 1 enumerator ESP_BLE_PWR_TYPE_CONN_HDL1 For connection handle 1 enumerator ESP_BLE_PWR_TYPE_CONN_HDL2 For connection handle 2 enumerator ESP_BLE_PWR_TYPE_CONN_HDL2 For connection handle 2 enumerator ESP_BLE_PWR_TYPE_CONN_HDL3 For connection handle 3 enumerator ESP_BLE_PWR_TYPE_CONN_HDL3 For connection handle 3 enumerator ESP_BLE_PWR_TYPE_CONN_HDL4 For connection handle 4 enumerator ESP_BLE_PWR_TYPE_CONN_HDL4 For connection handle 4 enumerator ESP_BLE_PWR_TYPE_CONN_HDL5 For connection handle 5 enumerator ESP_BLE_PWR_TYPE_CONN_HDL5 For connection handle 5 enumerator ESP_BLE_PWR_TYPE_CONN_HDL6 For connection handle 6 enumerator ESP_BLE_PWR_TYPE_CONN_HDL6 For connection handle 6 enumerator ESP_BLE_PWR_TYPE_CONN_HDL7 For connection handle 7 enumerator ESP_BLE_PWR_TYPE_CONN_HDL7 For connection handle 7 enumerator ESP_BLE_PWR_TYPE_CONN_HDL8 For connection handle 8 enumerator ESP_BLE_PWR_TYPE_CONN_HDL8 For connection handle 8 enumerator ESP_BLE_PWR_TYPE_ADV For advertising enumerator ESP_BLE_PWR_TYPE_ADV For advertising enumerator ESP_BLE_PWR_TYPE_SCAN For scan enumerator ESP_BLE_PWR_TYPE_SCAN For scan enumerator ESP_BLE_PWR_TYPE_DEFAULT For default, if not set other, it will use default value enumerator ESP_BLE_PWR_TYPE_DEFAULT For default, if not set other, it will use default value enumerator ESP_BLE_PWR_TYPE_NUM TYPE numbers enumerator ESP_BLE_PWR_TYPE_NUM TYPE numbers enumerator ESP_BLE_PWR_TYPE_CONN_HDL0 enum esp_power_level_t Bluetooth TX power level(index), it's just a index corresponding to power(dbm). Values: enumerator ESP_PWR_LVL_N12 Corresponding to -12dbm enumerator ESP_PWR_LVL_N12 Corresponding to -12dbm enumerator ESP_PWR_LVL_N9 Corresponding to -9dbm enumerator ESP_PWR_LVL_N9 Corresponding to -9dbm enumerator ESP_PWR_LVL_N6 Corresponding to -6dbm enumerator ESP_PWR_LVL_N6 Corresponding to -6dbm enumerator ESP_PWR_LVL_N3 Corresponding to -3dbm enumerator ESP_PWR_LVL_N3 Corresponding to -3dbm enumerator ESP_PWR_LVL_N0 Corresponding to 0dbm enumerator ESP_PWR_LVL_N0 Corresponding to 0dbm enumerator ESP_PWR_LVL_P3 Corresponding to +3dbm enumerator ESP_PWR_LVL_P3 Corresponding to +3dbm enumerator ESP_PWR_LVL_P6 Corresponding to +6dbm enumerator ESP_PWR_LVL_P6 Corresponding to +6dbm enumerator ESP_PWR_LVL_P9 Corresponding to +9dbm enumerator ESP_PWR_LVL_P9 Corresponding to +9dbm enumerator ESP_PWR_LVL_N14 Backward compatibility! Setting to -14dbm will actually result to -12dbm enumerator ESP_PWR_LVL_N14 Backward compatibility! Setting to -14dbm will actually result to -12dbm enumerator ESP_PWR_LVL_N11 Backward compatibility! Setting to -11dbm will actually result to -9dbm enumerator ESP_PWR_LVL_N11 Backward compatibility! Setting to -11dbm will actually result to -9dbm enumerator ESP_PWR_LVL_N8 Backward compatibility! Setting to -8dbm will actually result to -6dbm enumerator ESP_PWR_LVL_N8 Backward compatibility! Setting to -8dbm will actually result to -6dbm enumerator ESP_PWR_LVL_N5 Backward compatibility! Setting to -5dbm will actually result to -3dbm enumerator ESP_PWR_LVL_N5 Backward compatibility! Setting to -5dbm will actually result to -3dbm enumerator ESP_PWR_LVL_N2 Backward compatibility! Setting to -2dbm will actually result to 0dbm enumerator ESP_PWR_LVL_N2 Backward compatibility! Setting to -2dbm will actually result to 0dbm enumerator ESP_PWR_LVL_P1 Backward compatibility! Setting to +1dbm will actually result to +3dbm enumerator ESP_PWR_LVL_P1 Backward compatibility! Setting to +1dbm will actually result to +3dbm enumerator ESP_PWR_LVL_P4 Backward compatibility! Setting to +4dbm will actually result to +6dbm enumerator ESP_PWR_LVL_P4 Backward compatibility! Setting to +4dbm will actually result to +6dbm enumerator ESP_PWR_LVL_P7 Backward compatibility! Setting to +7dbm will actually result to +9dbm enumerator ESP_PWR_LVL_P7 Backward compatibility! Setting to +7dbm will actually result to +9dbm enumerator ESP_PWR_LVL_N12
Controller && VHCI Application Example Check bluetooth/hci folder in ESP-IDF examples, which contains the following application: This is a Bluetooth® Low Energy (Bluetooth LE) advertising demo with virtual HCI interface. Send Reset/ADV_PARAM/ADV_DATA/ADV_ENABLE HCI command for Bluetooth Low Energy advertising - bluetooth/hci/controller_vhci_ble_adv. API Reference Header File This header file can be included with: #include "esp_bt.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_tx_power_set(esp_ble_power_type_t power_type, esp_power_level_t power_level) Set BLE TX power Connection Tx power should only be set after connection created. - Parameters power_type -- : The type of which tx power, could set Advertising/Connection/Default and etc power_level -- Power level(index) corresponding to absolute value(dbm) - - Returns ESP_OK - success, other - failed - esp_power_level_t esp_ble_tx_power_get(esp_ble_power_type_t power_type) Get BLE TX power Connection Tx power should only be get after connection created. - Parameters power_type -- : The type of which tx power, could set Advertising/Connection/Default and etc - Returns >= 0 - Power level, < 0 - Invalid - esp_err_t esp_bredr_tx_power_set(esp_power_level_t min_power_level, esp_power_level_t max_power_level) Set BR/EDR TX power BR/EDR power control will use the power in range of minimum value and maximum value. The power level will effect the global BR/EDR TX power, such inquire, page, connection and so on. Please call the function after esp_bt_controller_enable and before any function which cause RF do TX. So you can call the function before doing discovery, profile init and so on. For example, if you want BR/EDR use the new TX power to do inquire, you should call this function before inquire. Another word, If call this function when BR/EDR is in inquire(ING), please do inquire again after call this function. Default minimum power level is ESP_PWR_LVL_N0, and maximum power level is ESP_PWR_LVL_P3. - Parameters min_power_level -- The minimum power level max_power_level -- The maximum power level - - Returns ESP_OK - success, other - failed - esp_err_t esp_bredr_tx_power_get(esp_power_level_t *min_power_level, esp_power_level_t *max_power_level) Get BR/EDR TX power If the argument is not NULL, then store the corresponding value. - Parameters min_power_level -- The minimum power level max_power_level -- The maximum power level - - Returns ESP_OK - success, other - failed - esp_err_t esp_bredr_sco_datapath_set(esp_sco_data_path_t data_path) Set default SCO data path Should be called after controller is enabled, and before (e)SCO link is established. - Parameters data_path -- SCO data path - Returns ESP_OK - success, other - failed - esp_err_t esp_bt_controller_init(esp_bt_controller_config_t *cfg) Initialize BT controller to allocate task and other resource. This function should be called only once, before any other BT functions are called. - Parameters cfg -- Initial configuration of BT controller. Different from previous version, there's a mode and some connection configuration in "cfg" to configure controller work mode and allocate the resource which is needed. - Returns ESP_OK - success, other - failed - esp_err_t esp_bt_controller_deinit(void) De-initialize BT controller to free resource and delete task. You should stop advertising and scanning, as well as disconnect all existing connections before de-initializing BT controller. This function should be called only once, after any other BT functions are called. - Returns ESP_OK - success, other - failed - esp_err_t esp_bt_controller_enable(esp_bt_mode_t mode) Enable BT controller. Due to a known issue, you cannot call esp_bt_controller_enable() a second time to change the controller mode dynamically. To change controller mode, call esp_bt_controller_disable() and then call esp_bt_controller_enable() with the new mode. - Parameters mode -- : the mode(BLE/BT/BTDM) to enable. For compatible of API, retain this argument. This mode must be equal as the mode in "cfg" of esp_bt_controller_init(). - Returns ESP_OK - success, other - failed - esp_err_t esp_bt_controller_disable(void) Disable BT controller. - Returns ESP_OK - success, other - failed - esp_bt_controller_status_t esp_bt_controller_get_status(void) Get BT controller is initialised/de-initialised/enabled/disabled. - Returns status value - bool esp_vhci_host_check_send_available(void) esp_vhci_host_check_send_available used for check actively if the host can send packet to controller or not. - Returns true for ready to send, false means cannot send packet - void esp_vhci_host_send_packet(uint8_t *data, uint16_t len) esp_vhci_host_send_packet host send packet to controller Should not call this function from within a critical section or when the scheduler is suspended. - Parameters data -- the packet point len -- the packet length - - esp_err_t esp_vhci_host_register_callback(const esp_vhci_host_callback_t *callback) esp_vhci_host_register_callback register the vhci reference callback struct defined by vhci_host_callback structure. - Parameters callback -- esp_vhci_host_callback type variable - Returns ESP_OK - success, ESP_FAIL - failed - esp_err_t esp_bt_controller_mem_release(esp_bt_mode_t mode) esp_bt_controller_mem_release release the controller memory as per the mode This function releases the BSS, data and other sections of the controller to heap. The total size is about 70k bytes. esp_bt_controller_mem_release(mode) should be called only before esp_bt_controller_init() or after esp_bt_controller_deinit(). Note that once BT controller memory is released, the process cannot be reversed. It means you cannot use the bluetooth mode which you have released by this function. If your firmware will later upgrade the Bluetooth controller mode (BLE -> BT Classic or disabled -> enabled) then do not call this function. If the app calls esp_bt_controller_enable(ESP_BT_MODE_BLE) to use BLE only then it is safe to call esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT) at initialization time to free unused BT Classic memory. If the mode is ESP_BT_MODE_BTDM, then it may be useful to call API esp_bt_mem_release(ESP_BT_MODE_BTDM) instead, which internally calls esp_bt_controller_mem_release(ESP_BT_MODE_BTDM) and additionally releases the BSS and data consumed by the BT/BLE host stack to heap. For more details about usage please refer to the documentation of esp_bt_mem_release() function - Parameters mode -- : the mode want to release memory - Returns ESP_OK - success, other - failed - esp_err_t esp_bt_mem_release(esp_bt_mode_t mode) esp_bt_mem_release release controller memory and BSS and data section of the BT/BLE host stack as per the mode This function first releases controller memory by internally calling esp_bt_controller_mem_release(). Additionally, if the mode is set to ESP_BT_MODE_BTDM, it also releases the BSS and data consumed by the BT/BLE host stack to heap Note that once BT memory is released, the process cannot be reversed. It means you cannot use the bluetooth mode which you have released by this function. If your firmware will later upgrade the Bluetooth controller mode (BLE -> BT Classic or disabled -> enabled) then do not call this function. If you never intend to use bluetooth in a current boot-up cycle, you can call esp_bt_mem_release(ESP_BT_MODE_BTDM) before esp_bt_controller_init or after esp_bt_controller_deinit. For example, if a user only uses bluetooth for setting the WiFi configuration, and does not use bluetooth in the rest of the product operation". In such cases, after receiving the WiFi configuration, you can disable/deinit bluetooth and release its memory. Below is the sequence of APIs to be called for such scenarios: esp_bluedroid_disable(); esp_bluedroid_deinit(); esp_bt_controller_disable(); esp_bt_controller_deinit(); esp_bt_mem_release(ESP_BT_MODE_BTDM); Note In case of NimBLE host, to release BSS and data memory to heap, the mode needs to be set to ESP_BT_MODE_BTDM as controller is dual mode. - Parameters mode -- : the mode whose memory is to be released - Returns ESP_OK - success, other - failed - esp_err_t esp_bt_sleep_enable(void) enable bluetooth to enter modem sleep Note that this function shall not be invoked before esp_bt_controller_enable() There are currently two options for bluetooth modem sleep, one is ORIG mode, and another is EVED Mode. EVED Mode is intended for BLE only. For ORIG mode: Bluetooth modem sleep is enabled in controller start up by default if CONFIG_CTRL_BTDM_MODEM_SLEEP is set and "ORIG mode" is selected. In ORIG modem sleep mode, bluetooth controller will switch off some components and pause to work every now and then, if there is no event to process; and wakeup according to the scheduled interval and resume the work. It can also wakeup earlier upon external request using function "esp_bt_controller_wakeup_request". - Returns ESP_OK : success other : failed - - esp_err_t esp_bt_sleep_disable(void) disable bluetooth modem sleep Note that this function shall not be invoked before esp_bt_controller_enable() If esp_bt_sleep_disable() is called, bluetooth controller will not be allowed to enter modem sleep; If ORIG modem sleep mode is in use, if this function is called, bluetooth controller may not immediately wake up if it is dormant then. In this case, esp_bt_controller_wakeup_request() can be used to shorten the time for wakeup. - Returns ESP_OK : success other : failed - - esp_err_t esp_ble_scan_dupilcate_list_flush(void) Manually clear scan duplicate list. Note that scan duplicate list will be automatically cleared when the maximum amount of device in the filter is reached the amount of device in the filter can be configured in menuconfig. Note This function name is incorrectly spelled, it will be fixed in release 5.x version. - Returns ESP_OK : success other : failed - - void esp_wifi_bt_power_domain_on(void) bt Wi-Fi power domain power on - void esp_wifi_bt_power_domain_off(void) bt Wi-Fi power domain power off Structures - struct esp_bt_controller_config_t Controller config options, depend on config mask. Config mask indicate which functions enabled, this means some options or parameters of some functions enabled by config mask. Public Members - uint16_t controller_task_stack_size Bluetooth controller task stack size - uint8_t controller_task_prio Bluetooth controller task priority - uint8_t hci_uart_no If use UART1/2 as HCI IO interface, indicate UART number - uint32_t hci_uart_baudrate If use UART1/2 as HCI IO interface, indicate UART baudrate - uint8_t scan_duplicate_mode scan duplicate mode - uint8_t scan_duplicate_type scan duplicate type - uint16_t normal_adv_size Normal adv size for scan duplicate - uint16_t mesh_adv_size Mesh adv size for scan duplicate - uint16_t send_adv_reserved_size Controller minimum memory value - uint32_t controller_debug_flag Controller debug log flag - uint8_t mode Controller mode: BR/EDR, BLE or Dual Mode - uint8_t ble_max_conn BLE maximum connection numbers - uint8_t bt_max_acl_conn BR/EDR maximum ACL connection numbers - uint8_t bt_sco_datapath SCO data path, i.e. HCI or PCM module - bool auto_latency BLE auto latency, used to enhance classic BT performance - bool bt_legacy_auth_vs_evt BR/EDR Legacy auth complete event required to protect from BIAS attack - uint8_t bt_max_sync_conn BR/EDR maximum ACL connection numbers. Effective in menuconfig - uint8_t ble_sca BLE low power crystal accuracy index - uint8_t pcm_role PCM role (master & slave) - uint8_t pcm_polar PCM polar trig (falling clk edge & rising clk edge) - bool hli Using high level interrupt or not - uint16_t dup_list_refresh_period Duplicate scan list refresh period - uint32_t magic Magic number - uint16_t controller_task_stack_size - struct esp_vhci_host_callback esp_vhci_host_callback used for vhci call host function to notify what host need to do Macros - ESP_BT_CONTROLLER_CONFIG_MAGIC_VAL - BT_CONTROLLER_INIT_CONFIG_DEFAULT() Type Definitions - typedef struct esp_vhci_host_callback esp_vhci_host_callback_t esp_vhci_host_callback used for vhci call host function to notify what host need to do Enumerations - enum esp_bt_mode_t Bluetooth mode for controller enable/disable. Values: - enumerator ESP_BT_MODE_IDLE Bluetooth is not running - enumerator ESP_BT_MODE_BLE Run BLE mode - enumerator ESP_BT_MODE_CLASSIC_BT Run Classic BT mode - enumerator ESP_BT_MODE_BTDM Run dual mode - enumerator ESP_BT_MODE_IDLE - enum [anonymous] BLE sleep clock accuracy(SCA), values for ble_sca field in esp_bt_controller_config_t, currently only ESP_BLE_SCA_500PPM and ESP_BLE_SCA_250PPM are supported. Values: - enumerator ESP_BLE_SCA_500PPM BLE SCA at 500ppm - enumerator ESP_BLE_SCA_250PPM BLE SCA at 250ppm - enumerator ESP_BLE_SCA_150PPM BLE SCA at 150ppm - enumerator ESP_BLE_SCA_100PPM BLE SCA at 100ppm - enumerator ESP_BLE_SCA_75PPM BLE SCA at 75ppm - enumerator ESP_BLE_SCA_50PPM BLE SCA at 50ppm - enumerator ESP_BLE_SCA_30PPM BLE SCA at 30ppm - enumerator ESP_BLE_SCA_20PPM BLE SCA at 20ppm - enumerator ESP_BLE_SCA_500PPM - enum esp_bt_controller_status_t Bluetooth controller enable/disable/initialised/de-initialised status. Values: - enumerator ESP_BT_CONTROLLER_STATUS_IDLE - enumerator ESP_BT_CONTROLLER_STATUS_INITED - enumerator ESP_BT_CONTROLLER_STATUS_ENABLED - enumerator ESP_BT_CONTROLLER_STATUS_NUM - enumerator ESP_BT_CONTROLLER_STATUS_IDLE - enum esp_ble_power_type_t BLE tx power type ESP_BLE_PWR_TYPE_CONN_HDL0-8: for each connection, and only be set after connection completed. when disconnect, the correspond TX power is not effected. ESP_BLE_PWR_TYPE_ADV : for advertising/scan response. ESP_BLE_PWR_TYPE_SCAN : for scan. ESP_BLE_PWR_TYPE_DEFAULT : if each connection's TX power is not set, it will use this default value. if neither in scan mode nor in adv mode, it will use this default value. If none of power type is set, system will use ESP_PWR_LVL_P3 as default for ADV/SCAN/CONN0-9. Values: - enumerator ESP_BLE_PWR_TYPE_CONN_HDL0 For connection handle 0 - enumerator ESP_BLE_PWR_TYPE_CONN_HDL1 For connection handle 1 - enumerator ESP_BLE_PWR_TYPE_CONN_HDL2 For connection handle 2 - enumerator ESP_BLE_PWR_TYPE_CONN_HDL3 For connection handle 3 - enumerator ESP_BLE_PWR_TYPE_CONN_HDL4 For connection handle 4 - enumerator ESP_BLE_PWR_TYPE_CONN_HDL5 For connection handle 5 - enumerator ESP_BLE_PWR_TYPE_CONN_HDL6 For connection handle 6 - enumerator ESP_BLE_PWR_TYPE_CONN_HDL7 For connection handle 7 - enumerator ESP_BLE_PWR_TYPE_CONN_HDL8 For connection handle 8 - enumerator ESP_BLE_PWR_TYPE_ADV For advertising - enumerator ESP_BLE_PWR_TYPE_SCAN For scan - enumerator ESP_BLE_PWR_TYPE_DEFAULT For default, if not set other, it will use default value - enumerator ESP_BLE_PWR_TYPE_NUM TYPE numbers - enumerator ESP_BLE_PWR_TYPE_CONN_HDL0 - enum esp_power_level_t Bluetooth TX power level(index), it's just a index corresponding to power(dbm). Values: - enumerator ESP_PWR_LVL_N12 Corresponding to -12dbm - enumerator ESP_PWR_LVL_N9 Corresponding to -9dbm - enumerator ESP_PWR_LVL_N6 Corresponding to -6dbm - enumerator ESP_PWR_LVL_N3 Corresponding to -3dbm - enumerator ESP_PWR_LVL_N0 Corresponding to 0dbm - enumerator ESP_PWR_LVL_P3 Corresponding to +3dbm - enumerator ESP_PWR_LVL_P6 Corresponding to +6dbm - enumerator ESP_PWR_LVL_P9 Corresponding to +9dbm - enumerator ESP_PWR_LVL_N14 Backward compatibility! Setting to -14dbm will actually result to -12dbm - enumerator ESP_PWR_LVL_N11 Backward compatibility! Setting to -11dbm will actually result to -9dbm - enumerator ESP_PWR_LVL_N8 Backward compatibility! Setting to -8dbm will actually result to -6dbm - enumerator ESP_PWR_LVL_N5 Backward compatibility! Setting to -5dbm will actually result to -3dbm - enumerator ESP_PWR_LVL_N2 Backward compatibility! Setting to -2dbm will actually result to 0dbm - enumerator ESP_PWR_LVL_P1 Backward compatibility! Setting to +1dbm will actually result to +3dbm - enumerator ESP_PWR_LVL_P4 Backward compatibility! Setting to +4dbm will actually result to +6dbm - enumerator ESP_PWR_LVL_P7 Backward compatibility! Setting to +7dbm will actually result to +9dbm - enumerator ESP_PWR_LVL_N12
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/controller_vhci.html
ESP-IDF Programming Guide v5.2.1 documentation
null
ESP-BLE-MESH
Uint
espressif.com
2018-04-03
23509b5ea42b8818
null
null
ESP-BLE-MESH Note The current ESP-BLE-MESH v1.1 related code is a preview version, so the Mesh Protocol v1.1 related Structures, MACROs, and APIs involved in the code may be changed. With various features of ESP-BLE-MESH, users can create a managed flooding mesh network for several scenarios, such as lighting, sensor and etc. For an ESP32 to join and work on a ESP-BLE-MESH network, it must be provisioned firstly. By provisioning, the ESP32, as an unprovisioned device, will join the ESP-BLE-MESH network and become a ESP-BLE-MESH node, communicating with other nodes within or beyond the radio range. Apart from ESP-BLE-MESH nodes, inside ESP-BLE-MESH network, there is also ESP32 that works as ESP-BLE-MESH provisioner, which could provision unprovisioned devices into ESP-BLE-MESH nodes and configure the nodes with various features. For information how to start using ESP32 and ESP-BLE-MESH, please see the Section Getting Started with ESP-BLE-MESH. If you are interested in information on ESP-BLE-MESH architecture, including some details of software implementation, please see Section ESP-BLE-MESH Architecture. Application Examples and Demos Please refer to Sections ESP-BLE-MESH Examples and ESP-BLE-MESH Demo Videos. API Reference ESP-BLE-MESH APIs are divided into the following parts: ESP-BLE-MESH Definitions This section contains only one header file, which lists the following items of ESP-BLE-MESH. ID of all the models and related message opcodes Structs of model, element and Composition Data Structs of used by ESP-BLE-MESH Node/Provisioner for provisioning Structs used to transmit/receive messages Event types and related event parameters Header File This header file can be included with: #include "esp_ble_mesh_defs.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Unions union esp_ble_mesh_prov_cb_param_t #include <esp_ble_mesh_defs.h> BLE Mesh Node/Provisioner callback parameters union. Public Members struct esp_ble_mesh_prov_cb_param_t::ble_mesh_prov_register_comp_param prov_register_comp Event parameter of ESP_BLE_MESH_PROV_REGISTER_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_prov_register_comp_param prov_register_comp Event parameter of ESP_BLE_MESH_PROV_REGISTER_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_unprov_dev_name_comp_param node_set_unprov_dev_name_comp Event parameter of ESP_BLE_MESH_NODE_SET_UNPROV_DEV_NAME_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_unprov_dev_name_comp_param node_set_unprov_dev_name_comp Event parameter of ESP_BLE_MESH_NODE_SET_UNPROV_DEV_NAME_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_prov_enable_comp_param node_prov_enable_comp Event parameter of ESP_BLE_MESH_NODE_PROV_ENABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_prov_enable_comp_param node_prov_enable_comp Event parameter of ESP_BLE_MESH_NODE_PROV_ENABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_prov_disable_comp_param node_prov_disable_comp Event parameter of ESP_BLE_MESH_NODE_PROV_DISABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_prov_disable_comp_param node_prov_disable_comp Event parameter of ESP_BLE_MESH_NODE_PROV_DISABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_link_open_evt_param node_prov_link_open Event parameter of ESP_BLE_MESH_NODE_PROV_LINK_OPEN_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_link_open_evt_param node_prov_link_open Event parameter of ESP_BLE_MESH_NODE_PROV_LINK_OPEN_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_link_close_evt_param node_prov_link_close Event parameter of ESP_BLE_MESH_NODE_PROV_LINK_CLOSE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_link_close_evt_param node_prov_link_close Event parameter of ESP_BLE_MESH_NODE_PROV_LINK_CLOSE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_output_num_evt_param node_prov_output_num Event parameter of ESP_BLE_MESH_NODE_PROV_OUTPUT_NUMBER_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_output_num_evt_param node_prov_output_num Event parameter of ESP_BLE_MESH_NODE_PROV_OUTPUT_NUMBER_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_output_str_evt_param node_prov_output_str Event parameter of ESP_BLE_MESH_NODE_PROV_OUTPUT_STRING_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_output_str_evt_param node_prov_output_str Event parameter of ESP_BLE_MESH_NODE_PROV_OUTPUT_STRING_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_input_evt_param node_prov_input Event parameter of ESP_BLE_MESH_NODE_PROV_INPUT_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_input_evt_param node_prov_input Event parameter of ESP_BLE_MESH_NODE_PROV_INPUT_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provision_complete_evt_param node_prov_complete Event parameter of ESP_BLE_MESH_NODE_PROV_COMPLETE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provision_complete_evt_param node_prov_complete Event parameter of ESP_BLE_MESH_NODE_PROV_COMPLETE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provision_reset_param node_prov_reset Event parameter of ESP_BLE_MESH_NODE_PROV_RESET_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provision_reset_param node_prov_reset Event parameter of ESP_BLE_MESH_NODE_PROV_RESET_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_oob_pub_key_comp_param node_prov_set_oob_pub_key_comp Event parameter of ESP_BLE_MESH_NODE_PROV_SET_OOB_PUB_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_oob_pub_key_comp_param node_prov_set_oob_pub_key_comp Event parameter of ESP_BLE_MESH_NODE_PROV_SET_OOB_PUB_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_input_number_comp_param node_prov_input_num_comp Event parameter of ESP_BLE_MESH_NODE_PROV_INPUT_NUM_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_input_number_comp_param node_prov_input_num_comp Event parameter of ESP_BLE_MESH_NODE_PROV_INPUT_NUM_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_input_string_comp_param node_prov_input_str_comp Event parameter of ESP_BLE_MESH_NODE_PROV_INPUT_STR_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_input_string_comp_param node_prov_input_str_comp Event parameter of ESP_BLE_MESH_NODE_PROV_INPUT_STR_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_identity_enable_comp_param node_proxy_identity_enable_comp Event parameter of ESP_BLE_MESH_NODE_PROXY_IDENTITY_ENABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_identity_enable_comp_param node_proxy_identity_enable_comp Event parameter of ESP_BLE_MESH_NODE_PROXY_IDENTITY_ENABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_gatt_enable_comp_param node_proxy_gatt_enable_comp Event parameter of ESP_BLE_MESH_NODE_PROXY_GATT_ENABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_gatt_enable_comp_param node_proxy_gatt_enable_comp Event parameter of ESP_BLE_MESH_NODE_PROXY_GATT_ENABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_gatt_disable_comp_param node_proxy_gatt_disable_comp Event parameter of ESP_BLE_MESH_NODE_PROXY_GATT_DISABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_gatt_disable_comp_param node_proxy_gatt_disable_comp Event parameter of ESP_BLE_MESH_NODE_PROXY_GATT_DISABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_private_identity_enable_comp_param node_private_proxy_identity_enable_comp Event parameter of ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_ENABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_private_identity_enable_comp_param node_private_proxy_identity_enable_comp Event parameter of ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_ENABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_private_identity_disable_comp_param node_private_proxy_identity_disable_comp Event parameter of ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_DISABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_private_identity_disable_comp_param node_private_proxy_identity_disable_comp Event parameter of ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_DISABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_node_add_local_net_key_comp_param node_add_net_key_comp Event parameter of ESP_BLE_MESH_NODE_ADD_LOCAL_NET_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_node_add_local_net_key_comp_param node_add_net_key_comp Event parameter of ESP_BLE_MESH_NODE_ADD_LOCAL_NET_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_node_add_local_app_key_comp_param node_add_app_key_comp Event parameter of ESP_BLE_MESH_NODE_ADD_LOCAL_APP_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_node_add_local_app_key_comp_param node_add_app_key_comp Event parameter of ESP_BLE_MESH_NODE_ADD_LOCAL_APP_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_node_bind_local_mod_app_comp_param node_bind_app_key_to_model_comp Event parameter of ESP_BLE_MESH_NODE_BIND_APP_KEY_TO_MODEL_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_node_bind_local_mod_app_comp_param node_bind_app_key_to_model_comp Event parameter of ESP_BLE_MESH_NODE_BIND_APP_KEY_TO_MODEL_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_recv_unprov_adv_pkt_param provisioner_recv_unprov_adv_pkt Event parameter of ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_recv_unprov_adv_pkt_param provisioner_recv_unprov_adv_pkt Event parameter of ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_enable_comp_param provisioner_prov_enable_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_ENABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_enable_comp_param provisioner_prov_enable_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_ENABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_disable_comp_param provisioner_prov_disable_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_DISABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_disable_comp_param provisioner_prov_disable_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_DISABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_link_open_evt_param provisioner_prov_link_open Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_LINK_OPEN_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_link_open_evt_param provisioner_prov_link_open Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_LINK_OPEN_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_read_oob_pub_key_evt_param provisioner_prov_read_oob_pub_key Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_read_oob_pub_key_evt_param provisioner_prov_read_oob_pub_key Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_input_evt_param provisioner_prov_input Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_INPUT_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_input_evt_param provisioner_prov_input Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_INPUT_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_output_evt_param provisioner_prov_output Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_OUTPUT_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_output_evt_param provisioner_prov_output Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_OUTPUT_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_link_close_evt_param provisioner_prov_link_close Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_LINK_CLOSE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_link_close_evt_param provisioner_prov_link_close Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_LINK_CLOSE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_comp_param provisioner_prov_complete Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_comp_param provisioner_prov_complete Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_cert_based_prov_start_evt_param provisioner_cert_based_prov_start Event parameter of ESP_BLE_MESH_PROVISIONER_CERT_BASED_PROV_START_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_cert_based_prov_start_evt_param provisioner_cert_based_prov_start Event parameter of ESP_BLE_MESH_PROVISIONER_CERT_BASED_PROV_START_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_recv_prov_records_list_evt_param recv_provisioner_records_list Event parameter of ESP_BLE_MESH_PROVISIONER_RECV_PROV_RECORDS_LIST_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_recv_prov_records_list_evt_param recv_provisioner_records_list Event parameter of ESP_BLE_MESH_PROVISIONER_RECV_PROV_RECORDS_LIST_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_record_recv_comp_evt_param provisioner_prov_record_recv_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_RECORD_RECV_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_record_recv_comp_evt_param provisioner_prov_record_recv_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_RECORD_RECV_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_send_prov_records_get_evt_param provisioner_send_records_get Event parameter of ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORDS_GET_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_send_prov_records_get_evt_param provisioner_send_records_get Event parameter of ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORDS_GET_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_send_prov_record_req_evt_param provisioner_send_record_req Event parameter of ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORD_REQUEST_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_send_prov_record_req_evt_param provisioner_send_record_req Event parameter of ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORD_REQUEST_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_send_prov_invite_evt_param provisioner_send_prov_invite Event parameter of ESP_BLE_MESH_PROVISIONER_SEND_PROV_INVITE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_send_prov_invite_evt_param provisioner_send_prov_invite Event parameter of ESP_BLE_MESH_PROVISIONER_SEND_PROV_INVITE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_send_link_close_evt_param provisioner_send_link_close Event parameter of ESP_BLE_MESH_PROVISIONER_SEND_LINK_CLOSE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_send_link_close_evt_param provisioner_send_link_close Event parameter of ESP_BLE_MESH_PROVISIONER_SEND_LINK_CLOSE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_add_unprov_dev_comp_param provisioner_add_unprov_dev_comp Event parameter of ESP_BLE_MESH_PROVISIONER_ADD_UNPROV_DEV_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_add_unprov_dev_comp_param provisioner_add_unprov_dev_comp Event parameter of ESP_BLE_MESH_PROVISIONER_ADD_UNPROV_DEV_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_dev_with_addr_comp_param provisioner_prov_dev_with_addr_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_DEV_WITH_ADDR_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_dev_with_addr_comp_param provisioner_prov_dev_with_addr_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_DEV_WITH_ADDR_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_delete_dev_comp_param provisioner_delete_dev_comp Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_DEV_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_delete_dev_comp_param provisioner_delete_dev_comp Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_DEV_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_dev_uuid_match_comp_param provisioner_set_dev_uuid_match_comp Event parameter of ESP_BLE_MESH_PROVISIONER_SET_DEV_UUID_MATCH_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_dev_uuid_match_comp_param provisioner_set_dev_uuid_match_comp Event parameter of ESP_BLE_MESH_PROVISIONER_SET_DEV_UUID_MATCH_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_prov_data_info_comp_param provisioner_set_prov_data_info_comp Event parameter of ESP_BLE_MESH_PROVISIONER_SET_PROV_DATA_INFO_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_prov_data_info_comp_param provisioner_set_prov_data_info_comp Event parameter of ESP_BLE_MESH_PROVISIONER_SET_PROV_DATA_INFO_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_static_oob_val_comp_param provisioner_set_static_oob_val_comp Event parameter of ESP_BLE_MESH_PROVISIONER_SET_STATIC_OOB_VALUE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_static_oob_val_comp_param provisioner_set_static_oob_val_comp Event parameter of ESP_BLE_MESH_PROVISIONER_SET_STATIC_OOB_VALUE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_primary_elem_addr_comp_param provisioner_set_primary_elem_addr_comp Event parameter of ESP_BLE_MESH_PROVISIONER_SET_PRIMARY_ELEM_ADDR_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_primary_elem_addr_comp_param provisioner_set_primary_elem_addr_comp Event parameter of ESP_BLE_MESH_PROVISIONER_SET_PRIMARY_ELEM_ADDR_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_read_oob_pub_key_comp_param provisioner_prov_read_oob_pub_key_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_read_oob_pub_key_comp_param provisioner_prov_read_oob_pub_key_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_input_num_comp_param provisioner_prov_input_num_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_INPUT_NUMBER_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_input_num_comp_param provisioner_prov_input_num_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_INPUT_NUMBER_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_input_str_comp_param provisioner_prov_input_str_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_INPUT_STRING_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_input_str_comp_param provisioner_prov_input_str_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_INPUT_STRING_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_node_name_comp_param provisioner_set_node_name_comp Event parameter of ESP_BLE_MESH_PROVISIONER_SET_NODE_NAME_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_node_name_comp_param provisioner_set_node_name_comp Event parameter of ESP_BLE_MESH_PROVISIONER_SET_NODE_NAME_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_add_local_app_key_comp_param provisioner_add_app_key_comp Event parameter of ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_APP_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_add_local_app_key_comp_param provisioner_add_app_key_comp Event parameter of ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_APP_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_update_local_app_key_comp_param provisioner_update_app_key_comp Event parameter of ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_APP_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_update_local_app_key_comp_param provisioner_update_app_key_comp Event parameter of ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_APP_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_bind_local_mod_app_comp_param provisioner_bind_app_key_to_model_comp Event parameter of ESP_BLE_MESH_PROVISIONER_BIND_APP_KEY_TO_MODEL_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_bind_local_mod_app_comp_param provisioner_bind_app_key_to_model_comp Event parameter of ESP_BLE_MESH_PROVISIONER_BIND_APP_KEY_TO_MODEL_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_add_local_net_key_comp_param provisioner_add_net_key_comp Event parameter of ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_NET_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_add_local_net_key_comp_param provisioner_add_net_key_comp Event parameter of ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_NET_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_update_local_net_key_comp_param provisioner_update_net_key_comp Event parameter of ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_NET_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_update_local_net_key_comp_param provisioner_update_net_key_comp Event parameter of ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_NET_KEY_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_store_node_comp_data_comp_param provisioner_store_node_comp_data_comp Event parameter of ESP_BLE_MESH_PROVISIONER_STORE_NODE_COMP_DATA_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_store_node_comp_data_comp_param provisioner_store_node_comp_data_comp Event parameter of ESP_BLE_MESH_PROVISIONER_STORE_NODE_COMP_DATA_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_delete_node_with_uuid_comp_param provisioner_delete_node_with_uuid_comp Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_UUID_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_delete_node_with_uuid_comp_param provisioner_delete_node_with_uuid_comp Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_UUID_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_delete_node_with_addr_comp_param provisioner_delete_node_with_addr_comp Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_ADDR_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_delete_node_with_addr_comp_param provisioner_delete_node_with_addr_comp Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_ADDR_COMP_EVT int err_code Indicate the result of enabling/disabling to receive heartbeat messages by the Provisioner Indicate the result of setting the heartbeat filter type by the Provisioner Indicate the result of setting the heartbeat filter address by the Provisioner Indicate the result of directly erasing settings by the Provisioner Indicate the result of opening settings with index by the Provisioner Indicate the result of opening settings with user id by the Provisioner Indicate the result of closing settings with index by the Provisioner Indicate the result of closing settings with user id by the Provisioner Indicate the result of deleting settings with index by the Provisioner Indicate the result of deleting settings with user id by the Provisioner Indicate the result of Proxy Client send Solicitation PDU int err_code Indicate the result of enabling/disabling to receive heartbeat messages by the Provisioner Indicate the result of setting the heartbeat filter type by the Provisioner Indicate the result of setting the heartbeat filter address by the Provisioner Indicate the result of directly erasing settings by the Provisioner Indicate the result of opening settings with index by the Provisioner Indicate the result of opening settings with user id by the Provisioner Indicate the result of closing settings with index by the Provisioner Indicate the result of closing settings with user id by the Provisioner Indicate the result of deleting settings with index by the Provisioner Indicate the result of deleting settings with user id by the Provisioner Indicate the result of Proxy Client send Solicitation PDU bool enable Indicate enabling or disabling receiving heartbeat messages bool enable Indicate enabling or disabling receiving heartbeat messages struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_enable_heartbeat_recv_comp ESP_BLE_MESH_PROVISIONER_ENABLE_HEARTBEAT_RECV_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_ENABLE_HEARTBEAT_RECV_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_enable_heartbeat_recv_comp ESP_BLE_MESH_PROVISIONER_ENABLE_HEARTBEAT_RECV_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_ENABLE_HEARTBEAT_RECV_COMP_EVT uint8_t type Type of the filter used for receiving heartbeat messages uint8_t type Type of the filter used for receiving heartbeat messages struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_set_heartbeat_filter_type_comp ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_TYPE_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_TYPE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_set_heartbeat_filter_type_comp ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_TYPE_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_TYPE_COMP_EVT uint8_t op Operation (add, remove, clean) uint8_t op Operation (add, remove, clean) uint16_t hb_src Heartbeat source address uint16_t hb_src Heartbeat source address uint16_t hb_dst Heartbeat destination address uint16_t hb_dst Heartbeat destination address struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_set_heartbeat_filter_info_comp ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_INFO_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_INFO_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_set_heartbeat_filter_info_comp ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_INFO_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_INFO_COMP_EVT uint8_t init_ttl Heartbeat InitTTL uint8_t init_ttl Heartbeat InitTTL uint8_t rx_ttl Heartbeat RxTTL uint8_t rx_ttl Heartbeat RxTTL uint8_t hops Heartbeat hops (InitTTL - RxTTL + 1) uint8_t hops Heartbeat hops (InitTTL - RxTTL + 1) uint16_t feature Bit field of currently active features of the node uint16_t feature Bit field of currently active features of the node int8_t rssi RSSI of the heartbeat message int8_t rssi RSSI of the heartbeat message struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_recv_heartbeat ESP_BLE_MESH_PROVISIONER_RECV_HEARTBEAT_MESSAGE_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_RECV_HEARTBEAT_MESSAGE_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_recv_heartbeat ESP_BLE_MESH_PROVISIONER_RECV_HEARTBEAT_MESSAGE_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_RECV_HEARTBEAT_MESSAGE_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_direct_erase_settings_comp ESP_BLE_MESH_PROVISIONER_DIRECT_ERASE_SETTINGS_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_DIRECT_ERASE_SETTINGS_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_direct_erase_settings_comp ESP_BLE_MESH_PROVISIONER_DIRECT_ERASE_SETTINGS_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_DIRECT_ERASE_SETTINGS_COMP_EVT uint8_t index Index of Provisioner settings uint8_t index Index of Provisioner settings struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_open_settings_with_index_comp ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_INDEX_COMP_EVT. Event parameter of ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_INDEX_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_open_settings_with_index_comp ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_INDEX_COMP_EVT. Event parameter of ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_INDEX_COMP_EVT char uid[ESP_BLE_MESH_SETTINGS_UID_SIZE + 1] Provisioner settings user id char uid[ESP_BLE_MESH_SETTINGS_UID_SIZE + 1] Provisioner settings user id struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_open_settings_with_uid_comp ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_UID_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_UID_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_open_settings_with_uid_comp ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_UID_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_UID_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_close_settings_with_index_comp ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_INDEX_COMP_EVT. Event parameter of ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_INDEX_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_close_settings_with_index_comp ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_INDEX_COMP_EVT. Event parameter of ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_INDEX_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_close_settings_with_uid_comp ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_UID_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_UID_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_close_settings_with_uid_comp ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_UID_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_UID_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_delete_settings_with_index_comp ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_INDEX_COMP_EVT. Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_INDEX_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_delete_settings_with_index_comp ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_INDEX_COMP_EVT. Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_INDEX_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_delete_settings_with_uid_comp ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_UID_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_UID_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_delete_settings_with_uid_comp ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_UID_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_UID_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_fast_prov_info_comp_param set_fast_prov_info_comp Event parameter of ESP_BLE_MESH_SET_FAST_PROV_INFO_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_fast_prov_info_comp_param set_fast_prov_info_comp Event parameter of ESP_BLE_MESH_SET_FAST_PROV_INFO_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_fast_prov_action_comp_param set_fast_prov_action_comp Event parameter of ESP_BLE_MESH_SET_FAST_PROV_ACTION_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_fast_prov_action_comp_param set_fast_prov_action_comp Event parameter of ESP_BLE_MESH_SET_FAST_PROV_ACTION_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_heartbeat_msg_recv_param heartbeat_msg_recv Event parameter of ESP_BLE_MESH_HEARTBEAT_MESSAGE_RECV_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_heartbeat_msg_recv_param heartbeat_msg_recv Event parameter of ESP_BLE_MESH_HEARTBEAT_MESSAGE_RECV_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_enable_comp_param lpn_enable_comp Event parameter of ESP_BLE_MESH_LPN_ENABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_enable_comp_param lpn_enable_comp Event parameter of ESP_BLE_MESH_LPN_ENABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_disable_comp_param lpn_disable_comp Event parameter of ESP_BLE_MESH_LPN_DISABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_disable_comp_param lpn_disable_comp Event parameter of ESP_BLE_MESH_LPN_DISABLE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_poll_comp_param lpn_poll_comp Event parameter of ESP_BLE_MESH_LPN_POLL_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_poll_comp_param lpn_poll_comp Event parameter of ESP_BLE_MESH_LPN_POLL_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_friendship_establish_param lpn_friendship_establish Event parameter of ESP_BLE_MESH_LPN_FRIENDSHIP_ESTABLISH_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_friendship_establish_param lpn_friendship_establish Event parameter of ESP_BLE_MESH_LPN_FRIENDSHIP_ESTABLISH_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_friendship_terminate_param lpn_friendship_terminate Event parameter of ESP_BLE_MESH_LPN_FRIENDSHIP_TERMINATE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_friendship_terminate_param lpn_friendship_terminate Event parameter of ESP_BLE_MESH_LPN_FRIENDSHIP_TERMINATE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_friend_friendship_establish_param frnd_friendship_establish Event parameter of ESP_BLE_MESH_FRIEND_FRIENDSHIP_ESTABLISH_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_friend_friendship_establish_param frnd_friendship_establish Event parameter of ESP_BLE_MESH_FRIEND_FRIENDSHIP_ESTABLISH_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_friend_friendship_terminate_param frnd_friendship_terminate Event parameter of ESP_BLE_MESH_FRIEND_FRIENDSHIP_TERMINATE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_friend_friendship_terminate_param frnd_friendship_terminate Event parameter of ESP_BLE_MESH_FRIEND_FRIENDSHIP_TERMINATE_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_recv_adv_pkt_param proxy_client_recv_adv_pkt Event parameter of ESP_BLE_MESH_PROXY_CLIENT_RECV_ADV_PKT_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_recv_adv_pkt_param proxy_client_recv_adv_pkt Event parameter of ESP_BLE_MESH_PROXY_CLIENT_RECV_ADV_PKT_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_connected_param proxy_client_connected Event parameter of ESP_BLE_MESH_PROXY_CLIENT_CONNECTED_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_connected_param proxy_client_connected Event parameter of ESP_BLE_MESH_PROXY_CLIENT_CONNECTED_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_disconnected_param proxy_client_disconnected Event parameter of ESP_BLE_MESH_PROXY_CLIENT_DISCONNECTED_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_disconnected_param proxy_client_disconnected Event parameter of ESP_BLE_MESH_PROXY_CLIENT_DISCONNECTED_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_recv_filter_status_param proxy_client_recv_filter_status Event parameter of ESP_BLE_MESH_PROXY_CLIENT_RECV_FILTER_STATUS_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_recv_filter_status_param proxy_client_recv_filter_status Event parameter of ESP_BLE_MESH_PROXY_CLIENT_RECV_FILTER_STATUS_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_connect_comp_param proxy_client_connect_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_CONNECT_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_connect_comp_param proxy_client_connect_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_CONNECT_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_disconnect_comp_param proxy_client_disconnect_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_DISCONNECT_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_disconnect_comp_param proxy_client_disconnect_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_DISCONNECT_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_set_filter_type_comp_param proxy_client_set_filter_type_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_SET_FILTER_TYPE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_set_filter_type_comp_param proxy_client_set_filter_type_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_SET_FILTER_TYPE_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_add_filter_addr_comp_param proxy_client_add_filter_addr_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_ADD_FILTER_ADDR_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_add_filter_addr_comp_param proxy_client_add_filter_addr_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_ADD_FILTER_ADDR_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_remove_filter_addr_comp_param proxy_client_remove_filter_addr_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_REMOVE_FILTER_ADDR_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_remove_filter_addr_comp_param proxy_client_remove_filter_addr_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_REMOVE_FILTER_ADDR_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_directed_proxy_set_param proxy_client_directed_proxy_set_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_DIRECTED_PROXY_SET_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_directed_proxy_set_param proxy_client_directed_proxy_set_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_DIRECTED_PROXY_SET_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_server_connected_param proxy_server_connected Event parameter of ESP_BLE_MESH_PROXY_SERVER_CONNECTED_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_server_connected_param proxy_server_connected Event parameter of ESP_BLE_MESH_PROXY_SERVER_CONNECTED_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_server_disconnected_param proxy_server_disconnected Event parameter of ESP_BLE_MESH_PROXY_SERVER_DISCONNECTED_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_server_disconnected_param proxy_server_disconnected Event parameter of ESP_BLE_MESH_PROXY_SERVER_DISCONNECTED_EVT uint16_t net_idx Corresponding NetKey Index uint16_t net_idx Corresponding NetKey Index uint16_t ssrc Solicitation SRC uint16_t ssrc Solicitation SRC uint16_t dst Solicitation DST uint16_t dst Solicitation DST struct esp_ble_mesh_prov_cb_param_t::[anonymous] proxy_client_send_solic_pdu_comp ESP_BLE_MESH_PROXY_CLIENT_SEND_SOLIC_PDU_COMP_EVT. Event parameter of ESP_BLE_MESH_PROXY_CLIENT_SEND_SOLIC_PDU_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::[anonymous] proxy_client_send_solic_pdu_comp ESP_BLE_MESH_PROXY_CLIENT_SEND_SOLIC_PDU_COMP_EVT. Event parameter of ESP_BLE_MESH_PROXY_CLIENT_SEND_SOLIC_PDU_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_model_sub_group_addr_comp_param model_sub_group_addr_comp Event parameters of ESP_BLE_MESH_MODEL_SUBSCRIBE_GROUP_ADDR_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_model_sub_group_addr_comp_param model_sub_group_addr_comp Event parameters of ESP_BLE_MESH_MODEL_SUBSCRIBE_GROUP_ADDR_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_model_unsub_group_addr_comp_param model_unsub_group_addr_comp Event parameters of ESP_BLE_MESH_MODEL_UNSUBSCRIBE_GROUP_ADDR_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_model_unsub_group_addr_comp_param model_unsub_group_addr_comp Event parameters of ESP_BLE_MESH_MODEL_UNSUBSCRIBE_GROUP_ADDR_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_deinit_mesh_comp_param deinit_mesh_comp Event parameter of ESP_BLE_MESH_DEINIT_MESH_COMP_EVT struct esp_ble_mesh_prov_cb_param_t::ble_mesh_deinit_mesh_comp_param deinit_mesh_comp Event parameter of ESP_BLE_MESH_DEINIT_MESH_COMP_EVT struct ble_mesh_deinit_mesh_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_DEINIT_MESH_COMP_EVT. Public Members int err_code Indicate the result of BLE Mesh deinitialization int err_code Indicate the result of BLE Mesh deinitialization int err_code struct ble_mesh_deinit_mesh_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_DEINIT_MESH_COMP_EVT. Public Members int err_code Indicate the result of BLE Mesh deinitialization struct ble_mesh_friend_friendship_establish_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_FRIEND_FRIENDSHIP_ESTABLISH_EVT. Public Members uint16_t lpn_addr Low Power Node unicast address uint16_t lpn_addr Low Power Node unicast address uint16_t lpn_addr struct ble_mesh_friend_friendship_establish_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_FRIEND_FRIENDSHIP_ESTABLISH_EVT. Public Members uint16_t lpn_addr Low Power Node unicast address struct ble_mesh_friend_friendship_terminate_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_FRIEND_FRIENDSHIP_TERMINATE_EVT. Public Types enum [anonymous] This enum value is the reason of friendship termination on the friend node side Values: enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_ESTABLISH_FAIL Friend Offer has been sent, but Friend Offer is not received within 1 second, friendship fails to be established enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_ESTABLISH_FAIL Friend Offer has been sent, but Friend Offer is not received within 1 second, friendship fails to be established enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_POLL_TIMEOUT Friendship is established, PollTimeout timer expires and no Friend Poll/Sub Add/Sub Remove is received enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_POLL_TIMEOUT Friendship is established, PollTimeout timer expires and no Friend Poll/Sub Add/Sub Remove is received enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_RECV_FRND_REQ Receive Friend Request from existing Low Power Node enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_RECV_FRND_REQ Receive Friend Request from existing Low Power Node enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_RECV_FRND_CLEAR Receive Friend Clear from other friend node enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_RECV_FRND_CLEAR Receive Friend Clear from other friend node enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_DISABLE Friend feature disabled or corresponding NetKey is deleted enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_DISABLE Friend feature disabled or corresponding NetKey is deleted enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_ESTABLISH_FAIL enum [anonymous] This enum value is the reason of friendship termination on the friend node side Values: enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_ESTABLISH_FAIL Friend Offer has been sent, but Friend Offer is not received within 1 second, friendship fails to be established enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_POLL_TIMEOUT Friendship is established, PollTimeout timer expires and no Friend Poll/Sub Add/Sub Remove is received enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_RECV_FRND_REQ Receive Friend Request from existing Low Power Node enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_RECV_FRND_CLEAR Receive Friend Clear from other friend node enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_DISABLE Friend feature disabled or corresponding NetKey is deleted Public Members uint16_t lpn_addr Low Power Node unicast address uint16_t lpn_addr Low Power Node unicast address enum esp_ble_mesh_prov_cb_param_t::ble_mesh_friend_friendship_terminate_param::[anonymous] reason This enum value is the reason of friendship termination on the friend node side Friendship terminated reason enum esp_ble_mesh_prov_cb_param_t::ble_mesh_friend_friendship_terminate_param::[anonymous] reason This enum value is the reason of friendship termination on the friend node side Friendship terminated reason enum [anonymous] struct ble_mesh_friend_friendship_terminate_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_FRIEND_FRIENDSHIP_TERMINATE_EVT. Public Types enum [anonymous] This enum value is the reason of friendship termination on the friend node side Values: enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_ESTABLISH_FAIL Friend Offer has been sent, but Friend Offer is not received within 1 second, friendship fails to be established enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_POLL_TIMEOUT Friendship is established, PollTimeout timer expires and no Friend Poll/Sub Add/Sub Remove is received enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_RECV_FRND_REQ Receive Friend Request from existing Low Power Node enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_RECV_FRND_CLEAR Receive Friend Clear from other friend node enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_DISABLE Friend feature disabled or corresponding NetKey is deleted Public Members uint16_t lpn_addr Low Power Node unicast address enum esp_ble_mesh_prov_cb_param_t::ble_mesh_friend_friendship_terminate_param::[anonymous] reason This enum value is the reason of friendship termination on the friend node side Friendship terminated reason struct ble_mesh_heartbeat_msg_recv_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_HEARTBEAT_MESSAGE_RECV_EVT. struct ble_mesh_heartbeat_msg_recv_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_HEARTBEAT_MESSAGE_RECV_EVT. struct ble_mesh_input_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_INPUT_EVT. Public Members esp_ble_mesh_input_action_t action Action of Input OOB Authentication esp_ble_mesh_input_action_t action Action of Input OOB Authentication uint8_t size Size of Input OOB Authentication uint8_t size Size of Input OOB Authentication esp_ble_mesh_input_action_t action struct ble_mesh_input_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_INPUT_EVT. Public Members esp_ble_mesh_input_action_t action Action of Input OOB Authentication uint8_t size Size of Input OOB Authentication struct ble_mesh_input_number_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_INPUT_NUM_COMP_EVT. Public Members int err_code Indicate the result of inputting number int err_code Indicate the result of inputting number int err_code struct ble_mesh_input_number_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_INPUT_NUM_COMP_EVT. Public Members int err_code Indicate the result of inputting number struct ble_mesh_input_string_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_INPUT_STR_COMP_EVT. Public Members int err_code Indicate the result of inputting string int err_code Indicate the result of inputting string int err_code struct ble_mesh_input_string_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_INPUT_STR_COMP_EVT. Public Members int err_code Indicate the result of inputting string struct ble_mesh_link_close_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_LINK_CLOSE_EVT. Public Members esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when device link is closed esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when device link is closed uint8_t reason Reason of the closed provisioning link uint8_t reason Reason of the closed provisioning link esp_ble_mesh_prov_bearer_t bearer struct ble_mesh_link_close_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_LINK_CLOSE_EVT. Public Members esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when device link is closed uint8_t reason Reason of the closed provisioning link struct ble_mesh_link_open_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_LINK_OPEN_EVT. Public Members esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when device link is open esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when device link is open esp_ble_mesh_prov_bearer_t bearer struct ble_mesh_link_open_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_LINK_OPEN_EVT. Public Members esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when device link is open struct ble_mesh_lpn_disable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_DISABLE_COMP_EVT. Public Members int err_code Indicate the result of disabling LPN functionality int err_code Indicate the result of disabling LPN functionality int err_code struct ble_mesh_lpn_disable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_DISABLE_COMP_EVT. Public Members int err_code Indicate the result of disabling LPN functionality struct ble_mesh_lpn_enable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_ENABLE_COMP_EVT. Public Members int err_code Indicate the result of enabling LPN functionality int err_code Indicate the result of enabling LPN functionality int err_code struct ble_mesh_lpn_enable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_ENABLE_COMP_EVT. Public Members int err_code Indicate the result of enabling LPN functionality struct ble_mesh_lpn_friendship_establish_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_FRIENDSHIP_ESTABLISH_EVT. Public Members uint16_t friend_addr Friend Node unicast address uint16_t friend_addr Friend Node unicast address uint16_t friend_addr struct ble_mesh_lpn_friendship_establish_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_FRIENDSHIP_ESTABLISH_EVT. Public Members uint16_t friend_addr Friend Node unicast address struct ble_mesh_lpn_friendship_terminate_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_FRIENDSHIP_TERMINATE_EVT. Public Members uint16_t friend_addr Friend Node unicast address uint16_t friend_addr Friend Node unicast address uint16_t friend_addr struct ble_mesh_lpn_friendship_terminate_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_FRIENDSHIP_TERMINATE_EVT. Public Members uint16_t friend_addr Friend Node unicast address struct ble_mesh_lpn_poll_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_POLL_COMP_EVT. Public Members int err_code Indicate the result of sending Friend Poll int err_code Indicate the result of sending Friend Poll int err_code struct ble_mesh_lpn_poll_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_POLL_COMP_EVT. Public Members int err_code Indicate the result of sending Friend Poll struct ble_mesh_model_sub_group_addr_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_SUBSCRIBE_GROUP_ADDR_COMP_EVT. struct ble_mesh_model_sub_group_addr_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_SUBSCRIBE_GROUP_ADDR_COMP_EVT. struct ble_mesh_model_unsub_group_addr_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_UNSUBSCRIBE_GROUP_ADDR_COMP_EVT. struct ble_mesh_model_unsub_group_addr_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_UNSUBSCRIBE_GROUP_ADDR_COMP_EVT. struct ble_mesh_node_add_local_app_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_ADD_LOCAL_APP_KEY_COMP_EVT. struct ble_mesh_node_add_local_app_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_ADD_LOCAL_APP_KEY_COMP_EVT. struct ble_mesh_node_add_local_net_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_ADD_LOCAL_NET_KEY_COMP_EVT. struct ble_mesh_node_add_local_net_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_ADD_LOCAL_NET_KEY_COMP_EVT. struct ble_mesh_node_bind_local_mod_app_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_BIND_APP_KEY_TO_MODEL_COMP_EVT. struct ble_mesh_node_bind_local_mod_app_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_BIND_APP_KEY_TO_MODEL_COMP_EVT. struct ble_mesh_output_num_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_OUTPUT_NUMBER_EVT. Public Members esp_ble_mesh_output_action_t action Action of Output OOB Authentication esp_ble_mesh_output_action_t action Action of Output OOB Authentication uint32_t number Number of Output OOB Authentication uint32_t number Number of Output OOB Authentication esp_ble_mesh_output_action_t action struct ble_mesh_output_num_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_OUTPUT_NUMBER_EVT. Public Members esp_ble_mesh_output_action_t action Action of Output OOB Authentication uint32_t number Number of Output OOB Authentication struct ble_mesh_output_str_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_OUTPUT_STRING_EVT. Public Members char string[8] String of Output OOB Authentication char string[8] String of Output OOB Authentication char string[8] struct ble_mesh_output_str_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_OUTPUT_STRING_EVT. Public Members char string[8] String of Output OOB Authentication struct ble_mesh_prov_disable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_DISABLE_COMP_EVT. Public Members int err_code Indicate the result of disabling BLE Mesh device int err_code Indicate the result of disabling BLE Mesh device int err_code struct ble_mesh_prov_disable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_DISABLE_COMP_EVT. Public Members int err_code Indicate the result of disabling BLE Mesh device struct ble_mesh_prov_enable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_ENABLE_COMP_EVT. Public Members int err_code Indicate the result of enabling BLE Mesh device int err_code Indicate the result of enabling BLE Mesh device int err_code struct ble_mesh_prov_enable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_ENABLE_COMP_EVT. Public Members int err_code Indicate the result of enabling BLE Mesh device struct ble_mesh_prov_register_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROV_REGISTER_COMP_EVT. Public Members int err_code Indicate the result of BLE Mesh initialization int err_code Indicate the result of BLE Mesh initialization int err_code struct ble_mesh_prov_register_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROV_REGISTER_COMP_EVT. Public Members int err_code Indicate the result of BLE Mesh initialization struct ble_mesh_provision_complete_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_COMPLETE_EVT. struct ble_mesh_provision_complete_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_COMPLETE_EVT. struct ble_mesh_provision_reset_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_RESET_EVT. struct ble_mesh_provision_reset_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_RESET_EVT. struct ble_mesh_provisioner_add_local_app_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_APP_KEY_COMP_EVT. struct ble_mesh_provisioner_add_local_app_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_APP_KEY_COMP_EVT. struct ble_mesh_provisioner_add_local_net_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_NET_KEY_COMP_EVT. struct ble_mesh_provisioner_add_local_net_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_NET_KEY_COMP_EVT. struct ble_mesh_provisioner_add_unprov_dev_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_ADD_UNPROV_DEV_COMP_EVT. Public Members int err_code Indicate the result of adding device into queue by the Provisioner int err_code Indicate the result of adding device into queue by the Provisioner int err_code struct ble_mesh_provisioner_add_unprov_dev_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_ADD_UNPROV_DEV_COMP_EVT. Public Members int err_code Indicate the result of adding device into queue by the Provisioner struct ble_mesh_provisioner_bind_local_mod_app_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_BIND_APP_KEY_TO_MODEL_COMP_EVT. struct ble_mesh_provisioner_bind_local_mod_app_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_BIND_APP_KEY_TO_MODEL_COMP_EVT. struct ble_mesh_provisioner_cert_based_prov_start_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_CERT_BASED_PROV_START_EVT. Public Members uint16_t link_idx Index of the provisioning link uint16_t link_idx Index of the provisioning link uint16_t link_idx struct ble_mesh_provisioner_cert_based_prov_start_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_CERT_BASED_PROV_START_EVT. Public Members uint16_t link_idx Index of the provisioning link struct ble_mesh_provisioner_delete_dev_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_DELETE_DEV_COMP_EVT. Public Members int err_code Indicate the result of deleting device by the Provisioner int err_code Indicate the result of deleting device by the Provisioner int err_code struct ble_mesh_provisioner_delete_dev_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_DELETE_DEV_COMP_EVT. Public Members int err_code Indicate the result of deleting device by the Provisioner struct ble_mesh_provisioner_delete_node_with_addr_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_ADDR_COMP_EVT. struct ble_mesh_provisioner_delete_node_with_addr_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_ADDR_COMP_EVT. struct ble_mesh_provisioner_delete_node_with_uuid_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_UUID_COMP_EVT. struct ble_mesh_provisioner_delete_node_with_uuid_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_UUID_COMP_EVT. struct ble_mesh_provisioner_link_close_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_LINK_CLOSE_EVT. Public Members esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when Provisioner link is closed esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when Provisioner link is closed uint8_t reason Reason of the closed provisioning link uint8_t reason Reason of the closed provisioning link esp_ble_mesh_prov_bearer_t bearer struct ble_mesh_provisioner_link_close_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_LINK_CLOSE_EVT. Public Members esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when Provisioner link is closed uint8_t reason Reason of the closed provisioning link struct ble_mesh_provisioner_link_open_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_LINK_OPEN_EVT. Public Members esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when Provisioner link is opened esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when Provisioner link is opened esp_ble_mesh_prov_bearer_t bearer struct ble_mesh_provisioner_link_open_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_LINK_OPEN_EVT. Public Members esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when Provisioner link is opened struct ble_mesh_provisioner_prov_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT. Public Members uint16_t node_idx Index of the provisioned device uint16_t node_idx Index of the provisioned device esp_ble_mesh_octet16_t device_uuid Device UUID of the provisioned device esp_ble_mesh_octet16_t device_uuid Device UUID of the provisioned device uint16_t unicast_addr Primary address of the provisioned device uint16_t unicast_addr Primary address of the provisioned device uint8_t element_num Element count of the provisioned device uint8_t element_num Element count of the provisioned device uint16_t netkey_idx NetKey Index of the provisioned device uint16_t netkey_idx NetKey Index of the provisioned device uint16_t node_idx struct ble_mesh_provisioner_prov_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT. Public Members uint16_t node_idx Index of the provisioned device esp_ble_mesh_octet16_t device_uuid Device UUID of the provisioned device uint16_t unicast_addr Primary address of the provisioned device uint8_t element_num Element count of the provisioned device uint16_t netkey_idx NetKey Index of the provisioned device struct ble_mesh_provisioner_prov_dev_with_addr_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_DEV_WITH_ADDR_COMP_EVT. Public Members int err_code Indicate the result of Provisioner starting to provision a device int err_code Indicate the result of Provisioner starting to provision a device int err_code struct ble_mesh_provisioner_prov_dev_with_addr_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_DEV_WITH_ADDR_COMP_EVT. Public Members int err_code Indicate the result of Provisioner starting to provision a device struct ble_mesh_provisioner_prov_disable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_DISABLE_COMP_EVT. Public Members int err_code Indicate the result of disabling BLE Mesh Provisioner int err_code Indicate the result of disabling BLE Mesh Provisioner int err_code struct ble_mesh_provisioner_prov_disable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_DISABLE_COMP_EVT. Public Members int err_code Indicate the result of disabling BLE Mesh Provisioner struct ble_mesh_provisioner_prov_enable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_ENABLE_COMP_EVT. Public Members int err_code Indicate the result of enabling BLE Mesh Provisioner int err_code Indicate the result of enabling BLE Mesh Provisioner int err_code struct ble_mesh_provisioner_prov_enable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_ENABLE_COMP_EVT. Public Members int err_code Indicate the result of enabling BLE Mesh Provisioner struct ble_mesh_provisioner_prov_input_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_INPUT_EVT. Public Members esp_ble_mesh_oob_method_t method Method of device Output OOB Authentication esp_ble_mesh_oob_method_t method Method of device Output OOB Authentication esp_ble_mesh_output_action_t action Action of device Output OOB Authentication esp_ble_mesh_output_action_t action Action of device Output OOB Authentication uint8_t size Size of device Output OOB Authentication uint8_t size Size of device Output OOB Authentication uint8_t link_idx Index of the provisioning link uint8_t link_idx Index of the provisioning link esp_ble_mesh_oob_method_t method struct ble_mesh_provisioner_prov_input_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_INPUT_EVT. Public Members esp_ble_mesh_oob_method_t method Method of device Output OOB Authentication esp_ble_mesh_output_action_t action Action of device Output OOB Authentication uint8_t size Size of device Output OOB Authentication uint8_t link_idx Index of the provisioning link struct ble_mesh_provisioner_prov_input_num_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_INPUT_NUMBER_COMP_EVT. Public Members int err_code Indicate the result of inputting number by the Provisioner int err_code Indicate the result of inputting number by the Provisioner int err_code struct ble_mesh_provisioner_prov_input_num_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_INPUT_NUMBER_COMP_EVT. Public Members int err_code Indicate the result of inputting number by the Provisioner struct ble_mesh_provisioner_prov_input_str_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_INPUT_STRING_COMP_EVT. Public Members int err_code Indicate the result of inputting string by the Provisioner int err_code Indicate the result of inputting string by the Provisioner int err_code struct ble_mesh_provisioner_prov_input_str_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_INPUT_STRING_COMP_EVT. Public Members int err_code Indicate the result of inputting string by the Provisioner struct ble_mesh_provisioner_prov_output_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_OUTPUT_EVT. Public Members esp_ble_mesh_oob_method_t method Method of device Input OOB Authentication esp_ble_mesh_oob_method_t method Method of device Input OOB Authentication esp_ble_mesh_input_action_t action Action of device Input OOB Authentication esp_ble_mesh_input_action_t action Action of device Input OOB Authentication uint8_t size Size of device Input OOB Authentication uint8_t size Size of device Input OOB Authentication uint8_t link_idx Index of the provisioning link uint8_t link_idx Index of the provisioning link char string[8] String output by the Provisioner char string[8] String output by the Provisioner uint32_t number Number output by the Provisioner uint32_t number Number output by the Provisioner union esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_output_evt_param::[anonymous] [anonymous] Union of output OOB union esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_output_evt_param::[anonymous] [anonymous] Union of output OOB esp_ble_mesh_oob_method_t method struct ble_mesh_provisioner_prov_output_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_OUTPUT_EVT. Public Members esp_ble_mesh_oob_method_t method Method of device Input OOB Authentication esp_ble_mesh_input_action_t action Action of device Input OOB Authentication uint8_t size Size of device Input OOB Authentication uint8_t link_idx Index of the provisioning link char string[8] String output by the Provisioner uint32_t number Number output by the Provisioner union esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_output_evt_param::[anonymous] [anonymous] Union of output OOB struct ble_mesh_provisioner_prov_read_oob_pub_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_COMP_EVT. Public Members int err_code Indicate the result of setting OOB Public Key by the Provisioner int err_code Indicate the result of setting OOB Public Key by the Provisioner int err_code struct ble_mesh_provisioner_prov_read_oob_pub_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_COMP_EVT. Public Members int err_code Indicate the result of setting OOB Public Key by the Provisioner struct ble_mesh_provisioner_prov_read_oob_pub_key_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_EVT. Public Members uint8_t link_idx Index of the provisioning link uint8_t link_idx Index of the provisioning link uint8_t link_idx struct ble_mesh_provisioner_prov_read_oob_pub_key_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_EVT. Public Members uint8_t link_idx Index of the provisioning link struct ble_mesh_provisioner_prov_record_recv_comp_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_RECORD_RECV_COMP_EVT. Public Members uint8_t status Indicates whether or not the request was handled successfully uint8_t status Indicates whether or not the request was handled successfully uint16_t link_idx Index of the provisioning link uint16_t link_idx Index of the provisioning link uint16_t record_id Identifies the provisioning record for which the request is made uint16_t record_id Identifies the provisioning record for which the request is made uint16_t frag_offset The starting offset of the requested fragment in the provisioning record data uint16_t frag_offset The starting offset of the requested fragment in the provisioning record data uint16_t total_len Total length of the provisioning record data stored on the Provisionee uint16_t total_len Total length of the provisioning record data stored on the Provisionee uint8_t *record Provisioning record data fragment uint8_t *record Provisioning record data fragment uint8_t status struct ble_mesh_provisioner_prov_record_recv_comp_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_RECORD_RECV_COMP_EVT. Public Members uint8_t status Indicates whether or not the request was handled successfully uint16_t link_idx Index of the provisioning link uint16_t record_id Identifies the provisioning record for which the request is made uint16_t frag_offset The starting offset of the requested fragment in the provisioning record data uint16_t total_len Total length of the provisioning record data stored on the Provisionee uint8_t *record Provisioning record data fragment struct ble_mesh_provisioner_recv_prov_records_list_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_RECV_PROV_RECORDS_LIST_EVT. struct ble_mesh_provisioner_recv_prov_records_list_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_RECV_PROV_RECORDS_LIST_EVT. struct ble_mesh_provisioner_recv_unprov_adv_pkt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT. Public Members uint8_t dev_uuid[16] Device UUID of the unprovisioned device uint8_t dev_uuid[16] Device UUID of the unprovisioned device esp_ble_mesh_bd_addr_t addr Device address of the unprovisioned device esp_ble_mesh_bd_addr_t addr Device address of the unprovisioned device esp_ble_mesh_addr_type_t addr_type Device address type esp_ble_mesh_addr_type_t addr_type Device address type uint16_t oob_info OOB Info of the unprovisioned device uint16_t oob_info OOB Info of the unprovisioned device uint8_t adv_type Advertising type of the unprovisioned device uint8_t adv_type Advertising type of the unprovisioned device esp_ble_mesh_prov_bearer_t bearer Bearer of the unprovisioned device esp_ble_mesh_prov_bearer_t bearer Bearer of the unprovisioned device int8_t rssi RSSI of the received advertising packet int8_t rssi RSSI of the received advertising packet uint8_t dev_uuid[16] struct ble_mesh_provisioner_recv_unprov_adv_pkt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT. Public Members uint8_t dev_uuid[16] Device UUID of the unprovisioned device esp_ble_mesh_bd_addr_t addr Device address of the unprovisioned device esp_ble_mesh_addr_type_t addr_type Device address type uint16_t oob_info OOB Info of the unprovisioned device uint8_t adv_type Advertising type of the unprovisioned device esp_ble_mesh_prov_bearer_t bearer Bearer of the unprovisioned device int8_t rssi RSSI of the received advertising packet struct ble_mesh_provisioner_send_link_close_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SEND_LINK_CLOSE_EVT. struct ble_mesh_provisioner_send_link_close_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SEND_LINK_CLOSE_EVT. struct ble_mesh_provisioner_send_prov_invite_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SEND_PROV_INVITE_EVT. struct ble_mesh_provisioner_send_prov_invite_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SEND_PROV_INVITE_EVT. struct ble_mesh_provisioner_send_prov_record_req_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORD_REQUEST_EVT. Public Members int err_code Indicate the result of send Provisioning Record Request message int err_code Indicate the result of send Provisioning Record Request message uint16_t link_idx Index of the provisioning link uint16_t link_idx Index of the provisioning link uint16_t record_id Identifies the provisioning record for which the request is made uint16_t record_id Identifies the provisioning record for which the request is made uint16_t frag_offset The starting offset of the requested fragment in the provisioning record data uint16_t frag_offset The starting offset of the requested fragment in the provisioning record data uint16_t max_size The maximum size of the provisioning record fragment that the Provisioner can receive uint16_t max_size The maximum size of the provisioning record fragment that the Provisioner can receive int err_code struct ble_mesh_provisioner_send_prov_record_req_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORD_REQUEST_EVT. Public Members int err_code Indicate the result of send Provisioning Record Request message uint16_t link_idx Index of the provisioning link uint16_t record_id Identifies the provisioning record for which the request is made uint16_t frag_offset The starting offset of the requested fragment in the provisioning record data uint16_t max_size The maximum size of the provisioning record fragment that the Provisioner can receive struct ble_mesh_provisioner_send_prov_records_get_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORDS_GET_EVT. struct ble_mesh_provisioner_send_prov_records_get_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORDS_GET_EVT. struct ble_mesh_provisioner_set_dev_uuid_match_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_DEV_UUID_MATCH_COMP_EVT. Public Members int err_code Indicate the result of setting Device UUID match value by the Provisioner int err_code Indicate the result of setting Device UUID match value by the Provisioner int err_code struct ble_mesh_provisioner_set_dev_uuid_match_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_DEV_UUID_MATCH_COMP_EVT. Public Members int err_code Indicate the result of setting Device UUID match value by the Provisioner struct ble_mesh_provisioner_set_node_name_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_NODE_NAME_COMP_EVT. struct ble_mesh_provisioner_set_node_name_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_NODE_NAME_COMP_EVT. struct ble_mesh_provisioner_set_primary_elem_addr_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_PRIMARY_ELEM_ADDR_COMP_EVT. Public Members int err_code Indicate the result of setting unicast address of primary element by the Provisioner int err_code Indicate the result of setting unicast address of primary element by the Provisioner int err_code struct ble_mesh_provisioner_set_primary_elem_addr_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_PRIMARY_ELEM_ADDR_COMP_EVT. Public Members int err_code Indicate the result of setting unicast address of primary element by the Provisioner struct ble_mesh_provisioner_set_prov_data_info_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_PROV_DATA_INFO_COMP_EVT. Public Members int err_code Indicate the result of setting provisioning info by the Provisioner int err_code Indicate the result of setting provisioning info by the Provisioner int err_code struct ble_mesh_provisioner_set_prov_data_info_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_PROV_DATA_INFO_COMP_EVT. Public Members int err_code Indicate the result of setting provisioning info by the Provisioner struct ble_mesh_provisioner_set_static_oob_val_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_STATIC_OOB_VALUE_COMP_EVT. Public Members int err_code Indicate the result of setting static oob value by the Provisioner int err_code Indicate the result of setting static oob value by the Provisioner int err_code struct ble_mesh_provisioner_set_static_oob_val_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_STATIC_OOB_VALUE_COMP_EVT. Public Members int err_code Indicate the result of setting static oob value by the Provisioner struct ble_mesh_provisioner_store_node_comp_data_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_STORE_NODE_COMP_DATA_COMP_EVT. struct ble_mesh_provisioner_store_node_comp_data_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_STORE_NODE_COMP_DATA_COMP_EVT. struct ble_mesh_provisioner_update_local_app_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_APP_KEY_COMP_EVT. struct ble_mesh_provisioner_update_local_app_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_APP_KEY_COMP_EVT. struct ble_mesh_provisioner_update_local_net_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_NET_KEY_COMP_EVT. struct ble_mesh_provisioner_update_local_net_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_NET_KEY_COMP_EVT. struct ble_mesh_proxy_client_add_filter_addr_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_ADD_FILTER_ADDR_COMP_EVT. struct ble_mesh_proxy_client_add_filter_addr_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_ADD_FILTER_ADDR_COMP_EVT. struct ble_mesh_proxy_client_connect_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_CONNECT_COMP_EVT. Public Members int err_code Indicate the result of Proxy Client connect int err_code Indicate the result of Proxy Client connect esp_ble_mesh_bd_addr_t addr Device address of the Proxy Server esp_ble_mesh_bd_addr_t addr Device address of the Proxy Server esp_ble_mesh_addr_type_t addr_type Device address type esp_ble_mesh_addr_type_t addr_type Device address type uint16_t net_idx Corresponding NetKey Index uint16_t net_idx Corresponding NetKey Index int err_code struct ble_mesh_proxy_client_connect_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_CONNECT_COMP_EVT. Public Members int err_code Indicate the result of Proxy Client connect esp_ble_mesh_bd_addr_t addr Device address of the Proxy Server esp_ble_mesh_addr_type_t addr_type Device address type uint16_t net_idx Corresponding NetKey Index struct ble_mesh_proxy_client_connected_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_CONNECTED_EVT. Public Members esp_ble_mesh_bd_addr_t addr Device address of the Proxy Server esp_ble_mesh_bd_addr_t addr Device address of the Proxy Server esp_ble_mesh_addr_type_t addr_type Device address type esp_ble_mesh_addr_type_t addr_type Device address type uint8_t conn_handle Proxy connection handle uint8_t conn_handle Proxy connection handle uint16_t net_idx Corresponding NetKey Index uint16_t net_idx Corresponding NetKey Index esp_ble_mesh_bd_addr_t addr struct ble_mesh_proxy_client_connected_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_CONNECTED_EVT. Public Members esp_ble_mesh_bd_addr_t addr Device address of the Proxy Server esp_ble_mesh_addr_type_t addr_type Device address type uint8_t conn_handle Proxy connection handle uint16_t net_idx Corresponding NetKey Index struct ble_mesh_proxy_client_directed_proxy_set_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_DIRECTED_PROXY_CONTROL_COMP_EVT. struct ble_mesh_proxy_client_directed_proxy_set_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_DIRECTED_PROXY_CONTROL_COMP_EVT. struct ble_mesh_proxy_client_disconnect_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_DISCONNECT_COMP_EVT. struct ble_mesh_proxy_client_disconnect_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_DISCONNECT_COMP_EVT. struct ble_mesh_proxy_client_disconnected_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_DISCONNECTED_EVT. Public Members esp_ble_mesh_bd_addr_t addr Device address of the Proxy Server esp_ble_mesh_bd_addr_t addr Device address of the Proxy Server esp_ble_mesh_addr_type_t addr_type Device address type esp_ble_mesh_addr_type_t addr_type Device address type uint8_t conn_handle Proxy connection handle uint8_t conn_handle Proxy connection handle uint16_t net_idx Corresponding NetKey Index uint16_t net_idx Corresponding NetKey Index uint8_t reason Proxy disconnect reason uint8_t reason Proxy disconnect reason esp_ble_mesh_bd_addr_t addr struct ble_mesh_proxy_client_disconnected_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_DISCONNECTED_EVT. Public Members esp_ble_mesh_bd_addr_t addr Device address of the Proxy Server esp_ble_mesh_addr_type_t addr_type Device address type uint8_t conn_handle Proxy connection handle uint16_t net_idx Corresponding NetKey Index uint8_t reason Proxy disconnect reason struct ble_mesh_proxy_client_recv_adv_pkt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_RECV_ADV_PKT_EVT. Public Members esp_ble_mesh_bd_addr_t addr Device address esp_ble_mesh_bd_addr_t addr Device address esp_ble_mesh_addr_type_t addr_type Device address type esp_ble_mesh_addr_type_t addr_type Device address type uint16_t net_idx Network ID related NetKey Index uint16_t net_idx Network ID related NetKey Index uint8_t net_id[8] Network ID contained in the advertising packet uint8_t net_id[8] Network ID contained in the advertising packet int8_t rssi RSSI of the received advertising packet int8_t rssi RSSI of the received advertising packet esp_ble_mesh_bd_addr_t addr struct ble_mesh_proxy_client_recv_adv_pkt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_RECV_ADV_PKT_EVT. Public Members esp_ble_mesh_bd_addr_t addr Device address esp_ble_mesh_addr_type_t addr_type Device address type uint16_t net_idx Network ID related NetKey Index uint8_t net_id[8] Network ID contained in the advertising packet int8_t rssi RSSI of the received advertising packet struct ble_mesh_proxy_client_recv_filter_status_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_RECV_FILTER_STATUS_EVT. Public Members uint8_t conn_handle Proxy connection handle uint8_t conn_handle Proxy connection handle uint16_t server_addr Proxy Server primary element address uint16_t server_addr Proxy Server primary element address uint16_t net_idx Corresponding NetKey Index uint16_t net_idx Corresponding NetKey Index uint8_t filter_type Proxy Server filter type(whitelist or blacklist) uint8_t filter_type Proxy Server filter type(whitelist or blacklist) uint16_t list_size Number of addresses in the Proxy Server filter list uint16_t list_size Number of addresses in the Proxy Server filter list uint8_t conn_handle struct ble_mesh_proxy_client_recv_filter_status_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_RECV_FILTER_STATUS_EVT. Public Members uint8_t conn_handle Proxy connection handle uint16_t server_addr Proxy Server primary element address uint16_t net_idx Corresponding NetKey Index uint8_t filter_type Proxy Server filter type(whitelist or blacklist) uint16_t list_size Number of addresses in the Proxy Server filter list struct ble_mesh_proxy_client_remove_filter_addr_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_REMOVE_FILTER_ADDR_COMP_EVT. struct ble_mesh_proxy_client_remove_filter_addr_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_REMOVE_FILTER_ADDR_COMP_EVT. struct ble_mesh_proxy_client_set_filter_type_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_SET_FILTER_TYPE_COMP_EVT. struct ble_mesh_proxy_client_set_filter_type_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_SET_FILTER_TYPE_COMP_EVT. struct ble_mesh_proxy_gatt_disable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROXY_GATT_DISABLE_COMP_EVT. Public Members int err_code Indicate the result of disabling Mesh Proxy Service int err_code Indicate the result of disabling Mesh Proxy Service int err_code struct ble_mesh_proxy_gatt_disable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROXY_GATT_DISABLE_COMP_EVT. Public Members int err_code Indicate the result of disabling Mesh Proxy Service struct ble_mesh_proxy_gatt_enable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROXY_GATT_ENABLE_COMP_EVT. Public Members int err_code Indicate the result of enabling Mesh Proxy Service int err_code Indicate the result of enabling Mesh Proxy Service int err_code struct ble_mesh_proxy_gatt_enable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROXY_GATT_ENABLE_COMP_EVT. Public Members int err_code Indicate the result of enabling Mesh Proxy Service struct ble_mesh_proxy_identity_enable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROXY_IDENTITY_ENABLE_COMP_EVT. Public Members int err_code Indicate the result of enabling Mesh Proxy advertising int err_code Indicate the result of enabling Mesh Proxy advertising int err_code struct ble_mesh_proxy_identity_enable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROXY_IDENTITY_ENABLE_COMP_EVT. Public Members int err_code Indicate the result of enabling Mesh Proxy advertising struct ble_mesh_proxy_private_identity_disable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_DISABLE_COMP_EVT. Public Members int err_code Indicate the result of disabling Mesh Proxy private advertising int err_code Indicate the result of disabling Mesh Proxy private advertising int err_code struct ble_mesh_proxy_private_identity_disable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_DISABLE_COMP_EVT. Public Members int err_code Indicate the result of disabling Mesh Proxy private advertising struct ble_mesh_proxy_private_identity_enable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_ENABLE_COMP_EVT. Public Members int err_code Indicate the result of enabling Mesh Proxy private advertising int err_code Indicate the result of enabling Mesh Proxy private advertising int err_code struct ble_mesh_proxy_private_identity_enable_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_ENABLE_COMP_EVT. Public Members int err_code Indicate the result of enabling Mesh Proxy private advertising struct ble_mesh_proxy_server_connected_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_SERVER_CONNECTED_EVT. Public Members uint8_t conn_handle Proxy connection handle uint8_t conn_handle Proxy connection handle uint8_t conn_handle struct ble_mesh_proxy_server_connected_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_SERVER_CONNECTED_EVT. Public Members uint8_t conn_handle Proxy connection handle struct ble_mesh_proxy_server_disconnected_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_SERVER_DISCONNECTED_EVT. struct ble_mesh_proxy_server_disconnected_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_SERVER_DISCONNECTED_EVT. struct ble_mesh_set_fast_prov_action_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_SET_FAST_PROV_ACTION_COMP_EVT. Public Members uint8_t status_action Indicate the result of setting action of fast provisioning uint8_t status_action Indicate the result of setting action of fast provisioning uint8_t status_action struct ble_mesh_set_fast_prov_action_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_SET_FAST_PROV_ACTION_COMP_EVT. Public Members uint8_t status_action Indicate the result of setting action of fast provisioning struct ble_mesh_set_fast_prov_info_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_SET_FAST_PROV_INFO_COMP_EVT. struct ble_mesh_set_fast_prov_info_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_SET_FAST_PROV_INFO_COMP_EVT. struct ble_mesh_set_oob_pub_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_SET_OOB_PUB_KEY_COMP_EVT. Public Members int err_code Indicate the result of setting OOB Public Key int err_code Indicate the result of setting OOB Public Key int err_code struct ble_mesh_set_oob_pub_key_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_SET_OOB_PUB_KEY_COMP_EVT. Public Members int err_code Indicate the result of setting OOB Public Key struct esp_ble_mesh_prov_cb_param_t::ble_mesh_prov_register_comp_param prov_register_comp union esp_ble_mesh_server_state_value_t #include <esp_ble_mesh_defs.h> Server model state value union. Public Members uint8_t onoff The value of the Generic OnOff state The value of the Light LC Light OnOff state uint8_t onoff The value of the Generic OnOff state The value of the Light LC Light OnOff state struct esp_ble_mesh_server_state_value_t::[anonymous] gen_onoff The Generic OnOff state struct esp_ble_mesh_server_state_value_t::[anonymous] gen_onoff The Generic OnOff state int16_t level The value of the Generic Level state int16_t level The value of the Generic Level state struct esp_ble_mesh_server_state_value_t::[anonymous] gen_level The Generic Level state struct esp_ble_mesh_server_state_value_t::[anonymous] gen_level The Generic Level state uint8_t onpowerup The value of the Generic OnPowerUp state uint8_t onpowerup The value of the Generic OnPowerUp state struct esp_ble_mesh_server_state_value_t::[anonymous] gen_onpowerup The Generic OnPowerUp state struct esp_ble_mesh_server_state_value_t::[anonymous] gen_onpowerup The Generic OnPowerUp state uint16_t power The value of the Generic Power Actual state uint16_t power The value of the Generic Power Actual state struct esp_ble_mesh_server_state_value_t::[anonymous] gen_power_actual The Generic Power Actual state struct esp_ble_mesh_server_state_value_t::[anonymous] gen_power_actual The Generic Power Actual state uint16_t lightness The value of the Light Lightness Actual state The value of the Light Lightness Linear state The value of the Light CTL Lightness state The value of the Light HSL Lightness state The value of the Light xyL Lightness state uint16_t lightness The value of the Light Lightness Actual state The value of the Light Lightness Linear state The value of the Light CTL Lightness state The value of the Light HSL Lightness state The value of the Light xyL Lightness state struct esp_ble_mesh_server_state_value_t::[anonymous] light_lightness_actual The Light Lightness Actual state struct esp_ble_mesh_server_state_value_t::[anonymous] light_lightness_actual The Light Lightness Actual state struct esp_ble_mesh_server_state_value_t::[anonymous] light_lightness_linear The Light Lightness Linear state struct esp_ble_mesh_server_state_value_t::[anonymous] light_lightness_linear The Light Lightness Linear state struct esp_ble_mesh_server_state_value_t::[anonymous] light_ctl_lightness The Light CTL Lightness state struct esp_ble_mesh_server_state_value_t::[anonymous] light_ctl_lightness The Light CTL Lightness state uint16_t temperature The value of the Light CTL Temperature state uint16_t temperature The value of the Light CTL Temperature state int16_t delta_uv The value of the Light CTL Delta UV state int16_t delta_uv The value of the Light CTL Delta UV state struct esp_ble_mesh_server_state_value_t::[anonymous] light_ctl_temp_delta_uv The Light CTL Temperature & Delta UV states struct esp_ble_mesh_server_state_value_t::[anonymous] light_ctl_temp_delta_uv The Light CTL Temperature & Delta UV states uint16_t hue The value of the Light HSL Hue state uint16_t hue The value of the Light HSL Hue state uint16_t saturation The value of the Light HSL Saturation state uint16_t saturation The value of the Light HSL Saturation state struct esp_ble_mesh_server_state_value_t::[anonymous] light_hsl The Light HSL composite state struct esp_ble_mesh_server_state_value_t::[anonymous] light_hsl The Light HSL composite state struct esp_ble_mesh_server_state_value_t::[anonymous] light_hsl_lightness The Light HSL Lightness state struct esp_ble_mesh_server_state_value_t::[anonymous] light_hsl_lightness The Light HSL Lightness state struct esp_ble_mesh_server_state_value_t::[anonymous] light_hsl_hue The Light HSL Hue state struct esp_ble_mesh_server_state_value_t::[anonymous] light_hsl_hue The Light HSL Hue state struct esp_ble_mesh_server_state_value_t::[anonymous] light_hsl_saturation The Light HSL Saturation state struct esp_ble_mesh_server_state_value_t::[anonymous] light_hsl_saturation The Light HSL Saturation state struct esp_ble_mesh_server_state_value_t::[anonymous] light_xyl_lightness The Light xyL Lightness state struct esp_ble_mesh_server_state_value_t::[anonymous] light_xyl_lightness The Light xyL Lightness state struct esp_ble_mesh_server_state_value_t::[anonymous] light_lc_light_onoff The Light LC Light OnOff state struct esp_ble_mesh_server_state_value_t::[anonymous] light_lc_light_onoff The Light LC Light OnOff state uint8_t onoff union esp_ble_mesh_model_cb_param_t #include <esp_ble_mesh_defs.h> BLE Mesh model callback parameters union. Public Members struct esp_ble_mesh_model_cb_param_t::ble_mesh_model_operation_evt_param model_operation Event parameter of ESP_BLE_MESH_MODEL_OPERATION_EVT struct esp_ble_mesh_model_cb_param_t::ble_mesh_model_operation_evt_param model_operation Event parameter of ESP_BLE_MESH_MODEL_OPERATION_EVT struct esp_ble_mesh_model_cb_param_t::ble_mesh_model_send_comp_param model_send_comp Event parameter of ESP_BLE_MESH_MODEL_SEND_COMP_EVT struct esp_ble_mesh_model_cb_param_t::ble_mesh_model_send_comp_param model_send_comp Event parameter of ESP_BLE_MESH_MODEL_SEND_COMP_EVT struct esp_ble_mesh_model_cb_param_t::ble_mesh_model_publish_comp_param model_publish_comp Event parameter of ESP_BLE_MESH_MODEL_PUBLISH_COMP_EVT struct esp_ble_mesh_model_cb_param_t::ble_mesh_model_publish_comp_param model_publish_comp Event parameter of ESP_BLE_MESH_MODEL_PUBLISH_COMP_EVT struct esp_ble_mesh_model_cb_param_t::ble_mesh_mod_recv_publish_msg_param client_recv_publish_msg Event parameter of ESP_BLE_MESH_CLIENT_MODEL_RECV_PUBLISH_MSG_EVT struct esp_ble_mesh_model_cb_param_t::ble_mesh_mod_recv_publish_msg_param client_recv_publish_msg Event parameter of ESP_BLE_MESH_CLIENT_MODEL_RECV_PUBLISH_MSG_EVT struct esp_ble_mesh_model_cb_param_t::ble_mesh_client_model_send_timeout_param client_send_timeout Event parameter of ESP_BLE_MESH_CLIENT_MODEL_SEND_TIMEOUT_EVT struct esp_ble_mesh_model_cb_param_t::ble_mesh_client_model_send_timeout_param client_send_timeout Event parameter of ESP_BLE_MESH_CLIENT_MODEL_SEND_TIMEOUT_EVT struct esp_ble_mesh_model_cb_param_t::ble_mesh_model_publish_update_evt_param model_publish_update Event parameter of ESP_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT struct esp_ble_mesh_model_cb_param_t::ble_mesh_model_publish_update_evt_param model_publish_update Event parameter of ESP_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT struct esp_ble_mesh_model_cb_param_t::ble_mesh_server_model_update_state_comp_param server_model_update_state Event parameter of ESP_BLE_MESH_SERVER_MODEL_UPDATE_STATE_COMP_EVT struct esp_ble_mesh_model_cb_param_t::ble_mesh_server_model_update_state_comp_param server_model_update_state Event parameter of ESP_BLE_MESH_SERVER_MODEL_UPDATE_STATE_COMP_EVT struct ble_mesh_client_model_send_timeout_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_CLIENT_MODEL_SEND_TIMEOUT_EVT. Public Members uint32_t opcode Opcode of the previously sent message uint32_t opcode Opcode of the previously sent message esp_ble_mesh_model_t *model Pointer to the model which sends the previous message esp_ble_mesh_model_t *model Pointer to the model which sends the previous message esp_ble_mesh_msg_ctx_t *ctx Pointer to the context of the previous message esp_ble_mesh_msg_ctx_t *ctx Pointer to the context of the previous message uint32_t opcode struct ble_mesh_client_model_send_timeout_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_CLIENT_MODEL_SEND_TIMEOUT_EVT. Public Members uint32_t opcode Opcode of the previously sent message esp_ble_mesh_model_t *model Pointer to the model which sends the previous message esp_ble_mesh_msg_ctx_t *ctx Pointer to the context of the previous message struct ble_mesh_mod_recv_publish_msg_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_CLIENT_MODEL_RECV_PUBLISH_MSG_EVT. Public Members uint32_t opcode Opcode of the unsolicited received message uint32_t opcode Opcode of the unsolicited received message esp_ble_mesh_model_t *model Pointer to the model which receives the message esp_ble_mesh_model_t *model Pointer to the model which receives the message esp_ble_mesh_msg_ctx_t *ctx Pointer to the context of the message esp_ble_mesh_msg_ctx_t *ctx Pointer to the context of the message uint16_t length Length of the received message uint16_t length Length of the received message uint8_t *msg Value of the received message uint8_t *msg Value of the received message uint32_t opcode struct ble_mesh_mod_recv_publish_msg_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_CLIENT_MODEL_RECV_PUBLISH_MSG_EVT. Public Members uint32_t opcode Opcode of the unsolicited received message esp_ble_mesh_model_t *model Pointer to the model which receives the message esp_ble_mesh_msg_ctx_t *ctx Pointer to the context of the message uint16_t length Length of the received message uint8_t *msg Value of the received message struct ble_mesh_model_operation_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_OPERATION_EVT. Public Members uint32_t opcode Opcode of the received message uint32_t opcode Opcode of the received message esp_ble_mesh_model_t *model Pointer to the model which receives the message esp_ble_mesh_model_t *model Pointer to the model which receives the message esp_ble_mesh_msg_ctx_t *ctx Pointer to the context of the received message esp_ble_mesh_msg_ctx_t *ctx Pointer to the context of the received message uint16_t length Length of the received message uint16_t length Length of the received message uint8_t *msg Value of the received message uint8_t *msg Value of the received message uint32_t opcode struct ble_mesh_model_operation_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_OPERATION_EVT. Public Members uint32_t opcode Opcode of the received message esp_ble_mesh_model_t *model Pointer to the model which receives the message esp_ble_mesh_msg_ctx_t *ctx Pointer to the context of the received message uint16_t length Length of the received message uint8_t *msg Value of the received message struct ble_mesh_model_publish_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_PUBLISH_COMP_EVT. Public Members int err_code Indicate the result of publishing a message int err_code Indicate the result of publishing a message esp_ble_mesh_model_t *model Pointer to the model which publishes the message esp_ble_mesh_model_t *model Pointer to the model which publishes the message int err_code struct ble_mesh_model_publish_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_PUBLISH_COMP_EVT. Public Members int err_code Indicate the result of publishing a message esp_ble_mesh_model_t *model Pointer to the model which publishes the message struct ble_mesh_model_publish_update_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT. Public Members esp_ble_mesh_model_t *model Pointer to the model which is going to update its publish message esp_ble_mesh_model_t *model Pointer to the model which is going to update its publish message esp_ble_mesh_model_t *model struct ble_mesh_model_publish_update_evt_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT. Public Members esp_ble_mesh_model_t *model Pointer to the model which is going to update its publish message struct ble_mesh_model_send_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_SEND_COMP_EVT. Public Members int err_code Indicate the result of sending a message int err_code Indicate the result of sending a message uint32_t opcode Opcode of the message uint32_t opcode Opcode of the message esp_ble_mesh_model_t *model Pointer to the model which sends the message esp_ble_mesh_model_t *model Pointer to the model which sends the message esp_ble_mesh_msg_ctx_t *ctx Context of the message esp_ble_mesh_msg_ctx_t *ctx Context of the message int err_code struct ble_mesh_model_send_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_SEND_COMP_EVT. Public Members int err_code Indicate the result of sending a message uint32_t opcode Opcode of the message esp_ble_mesh_model_t *model Pointer to the model which sends the message esp_ble_mesh_msg_ctx_t *ctx Context of the message struct ble_mesh_server_model_update_state_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_SERVER_MODEL_UPDATE_STATE_COMP_EVT. Public Members int err_code Indicate the result of updating server model state int err_code Indicate the result of updating server model state esp_ble_mesh_model_t *model Pointer to the server model which state value is updated esp_ble_mesh_model_t *model Pointer to the server model which state value is updated esp_ble_mesh_server_state_type_t type Type of the updated server state esp_ble_mesh_server_state_type_t type Type of the updated server state int err_code struct ble_mesh_server_model_update_state_comp_param #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_SERVER_MODEL_UPDATE_STATE_COMP_EVT. Public Members int err_code Indicate the result of updating server model state esp_ble_mesh_model_t *model Pointer to the server model which state value is updated esp_ble_mesh_server_state_type_t type Type of the updated server state struct esp_ble_mesh_model_cb_param_t::ble_mesh_model_operation_evt_param model_operation Structures struct esp_ble_mesh_deinit_param_t BLE Mesh deinit parameters Public Members bool erase_flash Indicate if erasing flash when deinit mesh stack bool erase_flash Indicate if erasing flash when deinit mesh stack bool erase_flash struct esp_ble_mesh_uar_t Format of Unicast Address Range struct esp_ble_mesh_elem_t Abstraction that describes a BLE Mesh Element. This structure is associated with struct bt_mesh_elem in mesh_access.h Public Members uint16_t element_addr Element Address, assigned during provisioning. uint16_t element_addr Element Address, assigned during provisioning. const uint16_t location Location Descriptor (GATT Bluetooth Namespace Descriptors) const uint16_t location Location Descriptor (GATT Bluetooth Namespace Descriptors) const uint8_t sig_model_count SIG Model count const uint8_t sig_model_count SIG Model count const uint8_t vnd_model_count Vendor Model count const uint8_t vnd_model_count Vendor Model count esp_ble_mesh_model_t *sig_models SIG Models esp_ble_mesh_model_t *sig_models SIG Models esp_ble_mesh_model_t *vnd_models Vendor Models esp_ble_mesh_model_t *vnd_models Vendor Models uint16_t element_addr struct esp_ble_mesh_model_pub_t Abstraction that describes a model publication context. This structure is associated with struct bt_mesh_model_pub in mesh_access.h Public Members esp_ble_mesh_model_t *model Pointer to the model to which the context belongs. Initialized by the stack. esp_ble_mesh_model_t *model Pointer to the model to which the context belongs. Initialized by the stack. uint16_t publish_addr Publish Address. uint16_t publish_addr Publish Address. uint16_t app_idx Publish AppKey Index. uint16_t app_idx Publish AppKey Index. uint16_t cred Friendship Credentials Flag. uint16_t cred Friendship Credentials Flag. uint16_t send_rel Force reliable sending (segment acks) uint16_t send_rel Force reliable sending (segment acks) uint16_t send_szmic Size of TransMIC when publishing a Segmented Access message uint16_t send_szmic Size of TransMIC when publishing a Segmented Access message uint8_t ttl Publish Time to Live. uint8_t ttl Publish Time to Live. uint8_t retransmit Retransmit Count & Interval Steps. uint8_t retransmit Retransmit Count & Interval Steps. uint8_t period Publish Period. uint8_t period Publish Period. uint8_t period_div Divisor for the Period. uint8_t period_div Divisor for the Period. uint8_t fast_period Use FastPeriodDivisor uint8_t fast_period Use FastPeriodDivisor uint8_t count Retransmissions left. uint8_t count Retransmissions left. uint32_t period_start Start of the current period. uint32_t period_start Start of the current period. struct net_buf_simple *msg Publication buffer, containing the publication message. This will get correctly created when the publication context has been defined using the ESP_BLE_MESH_MODEL_PUB_DEFINE macro. ESP_BLE_MESH_MODEL_PUB_DEFINE(name, size); struct net_buf_simple *msg Publication buffer, containing the publication message. This will get correctly created when the publication context has been defined using the ESP_BLE_MESH_MODEL_PUB_DEFINE macro. ESP_BLE_MESH_MODEL_PUB_DEFINE(name, size); esp_ble_mesh_cb_t update Callback used to update publish message. Initialized by the stack. esp_ble_mesh_cb_t update Callback used to update publish message. Initialized by the stack. struct k_delayed_work timer Publish Period Timer. Initialized by the stack. struct k_delayed_work timer Publish Period Timer. Initialized by the stack. uint8_t dev_role Role of the device that is going to publish messages uint8_t dev_role Role of the device that is going to publish messages esp_ble_mesh_model_t *model struct esp_ble_mesh_model_op_t Abstraction that describes a model operation context. This structure is associated with struct bt_mesh_model_op in mesh_access.h Public Members const uint32_t opcode Message opcode const uint32_t opcode Message opcode const size_t min_len Message minimum length const size_t min_len Message minimum length esp_ble_mesh_cb_t param_cb Callback used to handle message. Initialized by the stack. esp_ble_mesh_cb_t param_cb Callback used to handle message. Initialized by the stack. const uint32_t opcode struct esp_ble_mesh_model_cbs_t Abstraction that describes a model callback structure. This structure is associated with struct bt_mesh_model_cb in mesh_access.h. Public Members esp_ble_mesh_cb_t init_cb Callback used during model initialization. Initialized by the stack. esp_ble_mesh_cb_t init_cb Callback used during model initialization. Initialized by the stack. esp_ble_mesh_cb_t init_cb struct esp_ble_mesh_model Abstraction that describes a Mesh Model instance. This structure is associated with struct bt_mesh_model in mesh_access.h Public Members const uint16_t model_id 16-bit model identifier const uint16_t model_id 16-bit model identifier uint16_t company_id 16-bit company identifier uint16_t company_id 16-bit company identifier uint16_t model_id 16-bit model identifier uint16_t model_id 16-bit model identifier struct esp_ble_mesh_model::[anonymous]::[anonymous] vnd Structure encapsulating a model ID with a company ID struct esp_ble_mesh_model::[anonymous]::[anonymous] vnd Structure encapsulating a model ID with a company ID union esp_ble_mesh_model::[anonymous] [anonymous] Model ID union esp_ble_mesh_model::[anonymous] [anonymous] Model ID uint8_t element_idx Internal information, mainly for persistent storage Belongs to Nth element uint8_t element_idx Internal information, mainly for persistent storage Belongs to Nth element uint8_t model_idx Is the Nth model in the element uint8_t model_idx Is the Nth model in the element uint16_t flags Information about what has changed uint16_t flags Information about what has changed esp_ble_mesh_elem_t *element The Element to which this Model belongs esp_ble_mesh_elem_t *element The Element to which this Model belongs esp_ble_mesh_model_pub_t *const pub Model Publication esp_ble_mesh_model_pub_t *const pub Model Publication uint16_t keys[CONFIG_BLE_MESH_MODEL_KEY_COUNT] AppKey List uint16_t keys[CONFIG_BLE_MESH_MODEL_KEY_COUNT] AppKey List uint16_t groups[CONFIG_BLE_MESH_MODEL_GROUP_COUNT] Subscription List (group or virtual addresses) uint16_t groups[CONFIG_BLE_MESH_MODEL_GROUP_COUNT] Subscription List (group or virtual addresses) esp_ble_mesh_model_op_t *op Model operation context esp_ble_mesh_model_op_t *op Model operation context esp_ble_mesh_model_cbs_t *cb Model callback structure esp_ble_mesh_model_cbs_t *cb Model callback structure void *user_data Model-specific user data void *user_data Model-specific user data const uint16_t model_id struct esp_ble_mesh_msg_ctx_t Message sending context. This structure is associated with struct bt_mesh_msg_ctx in mesh_access.h Public Members uint16_t net_idx NetKey Index of the subnet through which to send the message. uint16_t net_idx NetKey Index of the subnet through which to send the message. uint16_t app_idx AppKey Index for message encryption. uint16_t app_idx AppKey Index for message encryption. uint16_t addr Remote address. uint16_t addr Remote address. uint16_t recv_dst Destination address of a received message. Not used for sending. uint16_t recv_dst Destination address of a received message. Not used for sending. int8_t recv_rssi RSSI of a received message. Not used for sending. int8_t recv_rssi RSSI of a received message. Not used for sending. uint32_t recv_op Opcode of a received message. Not used for sending. uint32_t recv_op Opcode of a received message. Not used for sending. uint8_t recv_ttl Received TTL value. Not used for sending. uint8_t recv_ttl Received TTL value. Not used for sending. uint8_t recv_cred Security credentials of a received message. Not used for sending. uint8_t recv_cred Security credentials of a received message. Not used for sending. uint8_t recv_tag Tag of a received message. Not used for sending. uint8_t recv_tag Tag of a received message. Not used for sending. uint8_t send_rel Force sending reliably by using segment acknowledgement. uint8_t send_rel Force sending reliably by using segment acknowledgement. uint8_t send_szmic Size of TransMIC when sending a Segmented Access message. uint8_t send_szmic Size of TransMIC when sending a Segmented Access message. uint8_t send_ttl TTL, or ESP_BLE_MESH_TTL_DEFAULT for default TTL. uint8_t send_ttl TTL, or ESP_BLE_MESH_TTL_DEFAULT for default TTL. uint8_t send_cred Security credentials used for sending the message uint8_t send_cred Security credentials used for sending the message uint8_t send_tag Tag used for sending the message. uint8_t send_tag Tag used for sending the message. esp_ble_mesh_model_t *model Model corresponding to the message, no need to be initialized before sending message esp_ble_mesh_model_t *model Model corresponding to the message, no need to be initialized before sending message bool srv_send Indicate if the message is sent by a node server model, no need to be initialized before sending message bool srv_send Indicate if the message is sent by a node server model, no need to be initialized before sending message uint16_t net_idx struct esp_ble_mesh_prov_t Provisioning properties & capabilities. This structure is associated with struct bt_mesh_prov in mesh_access.h struct esp_ble_mesh_comp_t Node Composition data context. This structure is associated with struct bt_mesh_comp in mesh_access.h struct esp_ble_mesh_unprov_dev_add_t Information of the device which is going to be added for provisioning. Public Members esp_ble_mesh_bd_addr_t addr Device address esp_ble_mesh_bd_addr_t addr Device address esp_ble_mesh_addr_type_t addr_type Device address type esp_ble_mesh_addr_type_t addr_type Device address type uint8_t uuid[16] Device UUID uint8_t uuid[16] Device UUID uint16_t oob_info Device OOB Info ADD_DEV_START_PROV_NOW_FLAG shall not be set if the bearer has both PB-ADV and PB-GATT enabled uint16_t oob_info Device OOB Info ADD_DEV_START_PROV_NOW_FLAG shall not be set if the bearer has both PB-ADV and PB-GATT enabled esp_ble_mesh_prov_bearer_t bearer Provisioning Bearer esp_ble_mesh_prov_bearer_t bearer Provisioning Bearer esp_ble_mesh_bd_addr_t addr struct esp_ble_mesh_device_delete_t Information of the device which is going to be deleted. Public Members esp_ble_mesh_bd_addr_t addr Device address esp_ble_mesh_bd_addr_t addr Device address esp_ble_mesh_addr_type_t addr_type Device address type esp_ble_mesh_addr_type_t addr_type Device address type uint8_t uuid[16] Device UUID uint8_t uuid[16] Device UUID union esp_ble_mesh_device_delete_t::[anonymous] [anonymous] Union of Device information union esp_ble_mesh_device_delete_t::[anonymous] [anonymous] Union of Device information uint8_t flag BIT0: device address; BIT1: device UUID uint8_t flag BIT0: device address; BIT1: device UUID esp_ble_mesh_bd_addr_t addr struct esp_ble_mesh_prov_data_info_t Information of the provisioner which is going to be updated. struct esp_ble_mesh_node_t Information of the provisioned node Public Members esp_ble_mesh_bd_addr_t addr Node device address esp_ble_mesh_bd_addr_t addr Node device address esp_ble_mesh_addr_type_t addr_type Node device address type esp_ble_mesh_addr_type_t addr_type Node device address type uint8_t dev_uuid[16] Device UUID uint8_t dev_uuid[16] Device UUID uint16_t oob_info Node OOB information uint16_t oob_info Node OOB information uint16_t unicast_addr Node unicast address uint16_t unicast_addr Node unicast address uint8_t element_num Node element number uint8_t element_num Node element number uint16_t net_idx Node NetKey Index uint16_t net_idx Node NetKey Index uint8_t flags Node key refresh flag and iv update flag uint8_t flags Node key refresh flag and iv update flag uint32_t iv_index Node IV Index uint32_t iv_index Node IV Index uint8_t dev_key[16] Node device key uint8_t dev_key[16] Node device key char name[ESP_BLE_MESH_NODE_NAME_MAX_LEN + 1] Node name char name[ESP_BLE_MESH_NODE_NAME_MAX_LEN + 1] Node name uint16_t comp_length Length of Composition Data uint16_t comp_length Length of Composition Data uint8_t *comp_data Value of Composition Data uint8_t *comp_data Value of Composition Data esp_ble_mesh_bd_addr_t addr struct esp_ble_mesh_fast_prov_info_t Context of fast provisioning which need to be set. Public Members uint16_t unicast_min Minimum unicast address used for fast provisioning uint16_t unicast_min Minimum unicast address used for fast provisioning uint16_t unicast_max Maximum unicast address used for fast provisioning uint16_t unicast_max Maximum unicast address used for fast provisioning uint16_t net_idx Netkey index used for fast provisioning uint16_t net_idx Netkey index used for fast provisioning uint8_t flags Flags used for fast provisioning uint8_t flags Flags used for fast provisioning uint32_t iv_index IV Index used for fast provisioning uint32_t iv_index IV Index used for fast provisioning uint8_t offset Offset of the UUID to be compared uint8_t offset Offset of the UUID to be compared uint8_t match_len Length of the UUID to be compared uint8_t match_len Length of the UUID to be compared uint8_t match_val[16] Value of UUID to be compared uint8_t match_val[16] Value of UUID to be compared uint16_t unicast_min struct esp_ble_mesh_heartbeat_filter_info_t Context of Provisioner heartbeat filter information to be set struct esp_ble_mesh_client_op_pair_t BLE Mesh client models related definitions. Client model Get/Set message opcode and corresponding Status message opcode struct esp_ble_mesh_client_t Client Model user data context. Public Members esp_ble_mesh_model_t *model Pointer to the client model. Initialized by the stack. esp_ble_mesh_model_t *model Pointer to the client model. Initialized by the stack. uint32_t op_pair_size Size of the op_pair uint32_t op_pair_size Size of the op_pair const esp_ble_mesh_client_op_pair_t *op_pair Table containing get/set message opcode and corresponding status message opcode const esp_ble_mesh_client_op_pair_t *op_pair Table containing get/set message opcode and corresponding status message opcode uint32_t publish_status Callback used to handle the received unsolicited message. Initialized by the stack. uint32_t publish_status Callback used to handle the received unsolicited message. Initialized by the stack. void *internal_data Pointer to the internal data of client model void *internal_data Pointer to the internal data of client model void *vendor_data Pointer to the vendor data of client model void *vendor_data Pointer to the vendor data of client model uint8_t msg_role Role of the device (Node/Provisioner) that is going to send messages uint8_t msg_role Role of the device (Node/Provisioner) that is going to send messages esp_ble_mesh_model_t *model struct esp_ble_mesh_client_common_param_t Common parameters of the messages sent by Client Model. Public Members esp_ble_mesh_opcode_t opcode Message opcode esp_ble_mesh_opcode_t opcode Message opcode esp_ble_mesh_model_t *model Pointer to the client model structure esp_ble_mesh_model_t *model Pointer to the client model structure esp_ble_mesh_msg_ctx_t ctx The context used to send message esp_ble_mesh_msg_ctx_t ctx The context used to send message int32_t msg_timeout Timeout value (ms) to get response to the sent message Note: if using default timeout value in menuconfig, make sure to set this value to 0 int32_t msg_timeout Timeout value (ms) to get response to the sent message Note: if using default timeout value in menuconfig, make sure to set this value to 0 uint8_t msg_role Role of the device - Node/Provisioner uint8_t msg_role Role of the device - Node/Provisioner esp_ble_mesh_opcode_t opcode struct esp_ble_mesh_state_transition_t Parameters of the server model state transition Public Functions BLE_MESH_ATOMIC_DEFINE(flag, ESP_BLE_MESH_SERVER_FLAG_MAX) Flag used to indicate if the transition timer has been started internally. If the model which contains esp_ble_mesh_state_transition_t sets "set_auto_rsp" to ESP_BLE_MESH_SERVER_RSP_BY_APP, the handler of the timer shall be initialized by the users. And users can use this flag to indicate whether the timer is started or not. BLE_MESH_ATOMIC_DEFINE(flag, ESP_BLE_MESH_SERVER_FLAG_MAX) Flag used to indicate if the transition timer has been started internally. If the model which contains esp_ble_mesh_state_transition_t sets "set_auto_rsp" to ESP_BLE_MESH_SERVER_RSP_BY_APP, the handler of the timer shall be initialized by the users. And users can use this flag to indicate whether the timer is started or not. Public Members bool just_started Indicate if the state transition has just started bool just_started Indicate if the state transition has just started uint8_t trans_time State transition time uint8_t trans_time State transition time uint8_t remain_time Remaining time of state transition uint8_t remain_time Remaining time of state transition uint8_t delay Delay before starting state transition uint8_t delay Delay before starting state transition uint32_t quo_tt Duration of each divided transition step uint32_t quo_tt Duration of each divided transition step uint32_t counter Number of steps which the transition duration is divided uint32_t counter Number of steps which the transition duration is divided uint32_t total_duration State transition total duration uint32_t total_duration State transition total duration int64_t start_timestamp Time when the state transition is started int64_t start_timestamp Time when the state transition is started struct k_delayed_work timer Timer used for state transition struct k_delayed_work timer Timer used for state transition BLE_MESH_ATOMIC_DEFINE(flag, ESP_BLE_MESH_SERVER_FLAG_MAX) struct esp_ble_mesh_last_msg_info_t Parameters of the server model received last same set message. struct esp_ble_mesh_server_rsp_ctrl_t Parameters of the Server Model response control Public Members uint8_t get_auto_rsp BLE Mesh Server Response Option. If get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, then the response of Client Get messages need to be replied by the application; If get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, then the response of Client Get messages will be replied by the server models; If set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, then the response of Client Set messages need to be replied by the application; If set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, then the response of Client Set messages will be replied by the server models; If status_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, then the response of Server Status messages need to be replied by the application; If status_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, then the response of Server Status messages will be replied by the server models; Response control for Client Get messages If get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, then the response of Client Get messages need to be replied by the application; If get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, then the response of Client Get messages will be replied by the server models; If set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, then the response of Client Set messages need to be replied by the application; If set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, then the response of Client Set messages will be replied by the server models; If status_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, then the response of Server Status messages need to be replied by the application; If status_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, then the response of Server Status messages will be replied by the server models; Response control for Client Get messages If get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, then the response of Client Get messages need to be replied by the application; uint8_t get_auto_rsp BLE Mesh Server Response Option. If get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, then the response of Client Get messages need to be replied by the application; If get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, then the response of Client Get messages will be replied by the server models; If set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, then the response of Client Set messages need to be replied by the application; If set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, then the response of Client Set messages will be replied by the server models; If status_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, then the response of Server Status messages need to be replied by the application; If status_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, then the response of Server Status messages will be replied by the server models; Response control for Client Get messages uint8_t set_auto_rsp Response control for Client Set messages uint8_t set_auto_rsp Response control for Client Set messages uint8_t status_auto_rsp Response control for Server Status messages uint8_t status_auto_rsp Response control for Server Status messages uint8_t get_auto_rsp Macros ESP_BLE_MESH_SDU_MAX_LEN < The maximum length of a BLE Mesh message, including Opcode, Payload and TransMIC Length of a short Mesh MIC. ESP_BLE_MESH_MIC_SHORT Length of a long Mesh MIC. ESP_BLE_MESH_MIC_LONG The maximum length of a BLE Mesh provisioned node name ESP_BLE_MESH_NODE_NAME_MAX_LEN The maximum length of a BLE Mesh unprovisioned device name ESP_BLE_MESH_DEVICE_NAME_MAX_LEN The maximum length of settings user id ESP_BLE_MESH_SETTINGS_UID_SIZE The default value of Random Update Interval Steps ESP_BLE_MESH_RAND_UPDATE_INTERVAL_DEFAULT Invalid settings index ESP_BLE_MESH_INVALID_SETTINGS_IDX Define the BLE Mesh octet 16 bytes size ESP_BLE_MESH_OCTET16_LEN ESP_BLE_MESH_OCTET8_LEN ESP_BLE_MESH_CID_NVAL Special TTL value to request using configured default TTL ESP_BLE_MESH_TTL_DEFAULT Maximum allowed TTL value ESP_BLE_MESH_TTL_MAX ESP_BLE_MESH_ADDR_UNASSIGNED ESP_BLE_MESH_ADDR_ALL_NODES ESP_BLE_MESH_ADDR_PROXIES ESP_BLE_MESH_ADDR_FRIENDS ESP_BLE_MESH_ADDR_RELAYS ESP_BLE_MESH_KEY_UNUSED ESP_BLE_MESH_KEY_DEV ESP_BLE_MESH_KEY_PRIMARY ESP_BLE_MESH_KEY_ANY Internal macros used to initialize array members ESP_BLE_MESH_KEY_UNUSED_ELT_(IDX, _) ESP_BLE_MESH_ADDR_UNASSIGNED_ELT_(IDX, _) ESP_BLE_MESH_MODEL_KEYS_UNUSED ESP_BLE_MESH_MODEL_GROUPS_UNASSIGNED Primary Network Key index ESP_BLE_MESH_NET_PRIMARY Relay state value ESP_BLE_MESH_RELAY_DISABLED ESP_BLE_MESH_RELAY_ENABLED ESP_BLE_MESH_RELAY_NOT_SUPPORTED Beacon state value ESP_BLE_MESH_BEACON_DISABLED ESP_BLE_MESH_BEACON_ENABLED ESP_BLE_MESH_PRIVATE_BEACON_DISABLE ESP_BLE_MESH_PRIVATE_BEACON_ENABLE GATT Proxy state value ESP_BLE_MESH_GATT_PROXY_DISABLED ESP_BLE_MESH_GATT_PROXY_ENABLED ESP_BLE_MESH_GATT_PROXY_NOT_SUPPORTED ESP_BLE_MESH_PRIVATE_GATT_PROXY_DISABLED ESP_BLE_MESH_PRIVATE_GATT_PROXY_ENABLED ESP_BLE_MESH_PRIVATE_GATT_PROXY_NOT_SUPPORTED ESP_BLE_MESH_PRIVATE_NODE_IDENTITY_DISABLED ESP_BLE_MESH_PRIVATE_NODE_IDENTITY_ENABLED ESP_BLE_MESH_PRIVATE_NODE_IDENTITY_NOT_SUPPORTED Friend state value ESP_BLE_MESH_FRIEND_DISABLED ESP_BLE_MESH_FRIEND_ENABLED ESP_BLE_MESH_FRIEND_NOT_SUPPORTED Node identity state value ESP_BLE_MESH_NODE_IDENTITY_STOPPED ESP_BLE_MESH_NODE_IDENTITY_RUNNING ESP_BLE_MESH_NODE_IDENTITY_NOT_SUPPORTED Subnet Bridge state value ESP_BLE_MESH_SUBNET_BRIDGE_DISABLED ESP_BLE_MESH_SUBNET_BRIDGE_ENABLED Supported features ESP_BLE_MESH_FEATURE_RELAY ESP_BLE_MESH_FEATURE_PROXY ESP_BLE_MESH_FEATURE_FRIEND ESP_BLE_MESH_FEATURE_LOW_POWER ESP_BLE_MESH_FEATURE_ALL_SUPPORTED ESP_BLE_MESH_ADDR_IS_UNICAST(addr) ESP_BLE_MESH_ADDR_IS_GROUP(addr) ESP_BLE_MESH_ADDR_IS_VIRTUAL(addr) ESP_BLE_MESH_ADDR_IS_RFU(addr) ESP_BLE_MESH_INVALID_NODE_INDEX ESP_BLE_MESH_PROV_RECORD_MAX_ID ESP_BLE_MESH_TRANSMIT(count, int_ms) Encode transmission count & interval steps. Note For example, ESP_BLE_MESH_TRANSMIT(2, 20) means that the message will be sent about 90ms(count is 3, step is 1, interval is 30 ms which includes 10ms of advertising interval random delay). Parameters count -- Number of retransmissions (first transmission is excluded). int_ms -- Interval steps in milliseconds. Must be greater than 0 and a multiple of 10. count -- Number of retransmissions (first transmission is excluded). int_ms -- Interval steps in milliseconds. Must be greater than 0 and a multiple of 10. count -- Number of retransmissions (first transmission is excluded). Returns BLE Mesh transmit value that can be used e.g. for the default values of the Configuration Model data. Parameters count -- Number of retransmissions (first transmission is excluded). int_ms -- Interval steps in milliseconds. Must be greater than 0 and a multiple of 10. Returns BLE Mesh transmit value that can be used e.g. for the default values of the Configuration Model data. ESP_BLE_MESH_GET_TRANSMIT_COUNT(transmit) Decode transmit count from a transmit value. Parameters transmit -- Encoded transmit count & interval value. transmit -- Encoded transmit count & interval value. transmit -- Encoded transmit count & interval value. Returns Transmission count (actual transmissions equal to N + 1). Parameters transmit -- Encoded transmit count & interval value. Returns Transmission count (actual transmissions equal to N + 1). ESP_BLE_MESH_GET_TRANSMIT_INTERVAL(transmit) Decode transmit interval from a transmit value. Parameters transmit -- Encoded transmit count & interval value. transmit -- Encoded transmit count & interval value. transmit -- Encoded transmit count & interval value. Returns Transmission interval in milliseconds. Parameters transmit -- Encoded transmit count & interval value. Returns Transmission interval in milliseconds. ESP_BLE_MESH_PUBLISH_TRANSMIT(count, int_ms) Encode Publish Retransmit count & interval steps. Parameters count -- Number of retransmissions (first transmission is excluded). int_ms -- Interval steps in milliseconds. Must be greater than 0 and a multiple of 50. count -- Number of retransmissions (first transmission is excluded). int_ms -- Interval steps in milliseconds. Must be greater than 0 and a multiple of 50. count -- Number of retransmissions (first transmission is excluded). Returns BLE Mesh transmit value that can be used e.g. for the default values of the Configuration Model data. Parameters count -- Number of retransmissions (first transmission is excluded). int_ms -- Interval steps in milliseconds. Must be greater than 0 and a multiple of 50. Returns BLE Mesh transmit value that can be used e.g. for the default values of the Configuration Model data. ESP_BLE_MESH_GET_PUBLISH_TRANSMIT_COUNT(transmit) Decode Publish Retransmit count from a given value. Parameters transmit -- Encoded Publish Retransmit count & interval value. transmit -- Encoded Publish Retransmit count & interval value. transmit -- Encoded Publish Retransmit count & interval value. Returns Retransmission count (actual transmissions equal to N + 1). Parameters transmit -- Encoded Publish Retransmit count & interval value. Returns Retransmission count (actual transmissions equal to N + 1). ESP_BLE_MESH_GET_PUBLISH_TRANSMIT_INTERVAL(transmit) Decode Publish Retransmit interval from a given value. Callbacks which are not needed to be initialized by users (set with 0 and will be initialized internally) Parameters transmit -- Encoded Publish Retransmit count & interval value. transmit -- Encoded Publish Retransmit count & interval value. transmit -- Encoded Publish Retransmit count & interval value. Returns Transmission interval in milliseconds. Parameters transmit -- Encoded Publish Retransmit count & interval value. Returns Transmission interval in milliseconds. ESP_BLE_MESH_PROV_STATIC_OOB_MAX_LEN Maximum length of string used by Output OOB authentication ESP_BLE_MESH_PROV_OUTPUT_OOB_MAX_LEN Maximum length of string used by Output OOB authentication ESP_BLE_MESH_PROV_INPUT_OOB_MAX_LEN Macros used to define message opcode ESP_BLE_MESH_MODEL_OP_1(b0) ESP_BLE_MESH_MODEL_OP_2(b0, b1) ESP_BLE_MESH_MODEL_OP_3(b0, cid) This macro is associated with BLE_MESH_MODEL_CB in mesh_access.h ESP_BLE_MESH_SIG_MODEL(_id, _op, _pub, _user_data) This macro is associated with BLE_MESH_MODEL_VND_CB in mesh_access.h ESP_BLE_MESH_VENDOR_MODEL(_company, _id, _op, _pub, _user_data) ESP_BLE_MESH_ELEMENT(_loc, _mods, _vnd_mods) Helper to define a BLE Mesh element within an array. In case the element has no SIG or Vendor models, the helper macro ESP_BLE_MESH_MODEL_NONE can be given instead. Note This macro is associated with BLE_MESH_ELEM in mesh_access.h Parameters _loc -- Location Descriptor. _mods -- Array of SIG models. _vnd_mods -- Array of vendor models. _loc -- Location Descriptor. _mods -- Array of SIG models. _vnd_mods -- Array of vendor models. _loc -- Location Descriptor. Parameters _loc -- Location Descriptor. _mods -- Array of SIG models. _vnd_mods -- Array of vendor models. ESP_BLE_MESH_PROV(uuid, sta_val, sta_val_len, out_size, out_act, in_size, in_act) BT_OCTET32_LEN BD_ADDR_LEN ESP_BLE_MESH_ADDR_TYPE_PUBLIC ESP_BLE_MESH_ADDR_TYPE_RANDOM ESP_BLE_MESH_ADDR_TYPE_RPA_PUBLIC ESP_BLE_MESH_ADDR_TYPE_RPA_RANDOM ESP_BLE_MESH_DIRECTED_FORWARDING_DISABLED ESP_BLE_MESH_DIRECTED_FORWARDING_ENABLED ESP_BLE_MESH_DIRECTED_RELAY_DISABLED ESP_BLE_MESH_DIRECTED_RELAY_ENABLED ESP_BLE_MESH_DIRECTED_PROXY_IGNORE ESP_BLE_MESH_DIRECTED_PROXY_USE_DEFAULT_IGNORE ESP_BLE_MESH_DIRECTED_FRIEND_IGNORE ESP_BLE_MESH_DIRECTED_PROXY_DISABLED ESP_BLE_MESH_DIRECTED_PROXY_ENABLED ESP_BLE_MESH_DIRECTED_PROXY_NOT_SUPPORTED ESP_BLE_MESH_DIRECTED_PROXY_USE_DEF_DISABLED ESP_BLE_MESH_DIRECTED_PROXY_USE_DEF_ENABLED ESP_BLE_MESH_DIRECTED_PROXY_USE_DEF_NOT_SUPPORTED ESP_BLE_MESH_DIRECTED_FRIEND_DISABLED ESP_BLE_MESH_DIRECTED_FRIEND_ENABLED ESP_BLE_MESH_DIRECTED_FRIEND_NOT_SUPPORTED ESP_BLE_MESH_DIRECTED_PUB_POLICY_FLOODING ESP_BLE_MESH_DIRECTED_PUB_POLICY_FORWARD ESP_BLE_MESH_PROXY_USE_DIRECTED_DISABLED ESP_BLE_MESH_PROXY_USE_DIRECTED_ENABLED ESP_BLE_MESH_FLOODING_CRED ESP_BLE_MESH_FRIENDSHIP_CRED ESP_BLE_MESH_DIRECTED_CRED ESP_BLE_MESH_TAG_SEND_SEGMENTED ESP_BLE_MESH_TAG_IMMUTABLE_CRED ESP_BLE_MESH_TAG_USE_DIRECTED ESP_BLE_MESH_TAG_RELAY ESP_BLE_MESH_TAG_FRIENDSHIP ESP_BLE_MESH_SEG_SZMIC_SHORT ESP_BLE_MESH_SEG_SZMIC_LONG ESP_BLE_MESH_MODEL_PUB_DEFINE(_name, _msg_len, _role) Define a model publication context. Parameters _name -- Variable name given to the context. _msg_len -- Length of the publication message. _role -- Role of the device which contains the model. _name -- Variable name given to the context. _msg_len -- Length of the publication message. _role -- Role of the device which contains the model. _name -- Variable name given to the context. Parameters _name -- Variable name given to the context. _msg_len -- Length of the publication message. _role -- Role of the device which contains the model. ESP_BLE_MESH_MODEL_OP(_opcode, _min_len) Define a model operation context. Parameters _opcode -- Message opcode. _min_len -- Message minimum length. _opcode -- Message opcode. _min_len -- Message minimum length. _opcode -- Message opcode. Parameters _opcode -- Message opcode. _min_len -- Message minimum length. ESP_BLE_MESH_MODEL_OP_END Define the terminator for the model operation table. Each model operation struct array must use this terminator as the end tag of the operation unit. ESP_BLE_MESH_MODEL_NONE Helper to define an empty model array. This structure is associated with BLE_MESH_MODEL_NONE in mesh_access.h ADD_DEV_RM_AFTER_PROV_FLAG Device will be removed from queue after provisioned successfully ADD_DEV_START_PROV_NOW_FLAG Start provisioning device immediately ADD_DEV_FLUSHABLE_DEV_FLAG Device can be remove when queue is full and new device is going to added DEL_DEV_ADDR_FLAG DEL_DEV_UUID_FLAG PROV_DATA_NET_IDX_FLAG PROV_DATA_FLAGS_FLAG PROV_DATA_IV_INDEX_FLAG ESP_BLE_MESH_HEARTBEAT_FILTER_ACCEPTLIST ESP_BLE_MESH_HEARTBEAT_FILTER_REJECTLIST Provisioner heartbeat filter operation ESP_BLE_MESH_HEARTBEAT_FILTER_ADD ESP_BLE_MESH_HEARTBEAT_FILTER_REMOVE ESP_BLE_MESH_MODEL_ID_CONFIG_SRV BLE Mesh models related Model ID and Opcode definitions. < Foundation Models ESP_BLE_MESH_MODEL_ID_CONFIG_CLI ESP_BLE_MESH_MODEL_ID_HEALTH_SRV ESP_BLE_MESH_MODEL_ID_HEALTH_CLI ESP_BLE_MESH_MODEL_ID_RPR_SRV ESP_BLE_MESH_MODEL_ID_RPR_CLI ESP_BLE_MESH_MODEL_ID_DF_SRV ESP_BLE_MESH_MODEL_ID_DF_CLI ESP_BLE_MESH_MODEL_ID_BRC_SRV ESP_BLE_MESH_MODEL_ID_BRC_CLI ESP_BLE_MESH_MODEL_ID_PRB_SRV ESP_BLE_MESH_MODEL_ID_PRB_CLI ESP_BLE_MESH_MODEL_ID_ODP_SRV ESP_BLE_MESH_MODEL_ID_ODP_CLI ESP_BLE_MESH_MODEL_ID_SAR_SRV ESP_BLE_MESH_MODEL_ID_SAR_CLI ESP_BLE_MESH_MODEL_ID_AGG_SRV ESP_BLE_MESH_MODEL_ID_AGG_CLI ESP_BLE_MESH_MODEL_ID_LCD_SRV ESP_BLE_MESH_MODEL_ID_LCD_CLI ESP_BLE_MESH_MODEL_ID_SRPL_SRV ESP_BLE_MESH_MODEL_ID_SRPL_CLI Models from the Mesh Model Specification ESP_BLE_MESH_MODEL_ID_GEN_ONOFF_SRV ESP_BLE_MESH_MODEL_ID_GEN_ONOFF_CLI ESP_BLE_MESH_MODEL_ID_GEN_LEVEL_SRV ESP_BLE_MESH_MODEL_ID_GEN_LEVEL_CLI ESP_BLE_MESH_MODEL_ID_GEN_DEF_TRANS_TIME_SRV ESP_BLE_MESH_MODEL_ID_GEN_DEF_TRANS_TIME_CLI ESP_BLE_MESH_MODEL_ID_GEN_POWER_ONOFF_SRV ESP_BLE_MESH_MODEL_ID_GEN_POWER_ONOFF_SETUP_SRV ESP_BLE_MESH_MODEL_ID_GEN_POWER_ONOFF_CLI ESP_BLE_MESH_MODEL_ID_GEN_POWER_LEVEL_SRV ESP_BLE_MESH_MODEL_ID_GEN_POWER_LEVEL_SETUP_SRV ESP_BLE_MESH_MODEL_ID_GEN_POWER_LEVEL_CLI ESP_BLE_MESH_MODEL_ID_GEN_BATTERY_SRV ESP_BLE_MESH_MODEL_ID_GEN_BATTERY_CLI ESP_BLE_MESH_MODEL_ID_GEN_LOCATION_SRV ESP_BLE_MESH_MODEL_ID_GEN_LOCATION_SETUP_SRV ESP_BLE_MESH_MODEL_ID_GEN_LOCATION_CLI ESP_BLE_MESH_MODEL_ID_GEN_ADMIN_PROP_SRV ESP_BLE_MESH_MODEL_ID_GEN_MANUFACTURER_PROP_SRV ESP_BLE_MESH_MODEL_ID_GEN_USER_PROP_SRV ESP_BLE_MESH_MODEL_ID_GEN_CLIENT_PROP_SRV ESP_BLE_MESH_MODEL_ID_GEN_PROP_CLI ESP_BLE_MESH_MODEL_ID_SENSOR_SRV ESP_BLE_MESH_MODEL_ID_SENSOR_SETUP_SRV ESP_BLE_MESH_MODEL_ID_SENSOR_CLI ESP_BLE_MESH_MODEL_ID_TIME_SRV ESP_BLE_MESH_MODEL_ID_TIME_SETUP_SRV ESP_BLE_MESH_MODEL_ID_TIME_CLI ESP_BLE_MESH_MODEL_ID_SCENE_SRV ESP_BLE_MESH_MODEL_ID_SCENE_SETUP_SRV ESP_BLE_MESH_MODEL_ID_SCENE_CLI ESP_BLE_MESH_MODEL_ID_SCHEDULER_SRV ESP_BLE_MESH_MODEL_ID_SCHEDULER_SETUP_SRV ESP_BLE_MESH_MODEL_ID_SCHEDULER_CLI ESP_BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_SRV ESP_BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_SETUP_SRV ESP_BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_CLI ESP_BLE_MESH_MODEL_ID_LIGHT_CTL_SRV ESP_BLE_MESH_MODEL_ID_LIGHT_CTL_SETUP_SRV ESP_BLE_MESH_MODEL_ID_LIGHT_CTL_CLI ESP_BLE_MESH_MODEL_ID_LIGHT_CTL_TEMP_SRV ESP_BLE_MESH_MODEL_ID_LIGHT_HSL_SRV ESP_BLE_MESH_MODEL_ID_LIGHT_HSL_SETUP_SRV ESP_BLE_MESH_MODEL_ID_LIGHT_HSL_CLI ESP_BLE_MESH_MODEL_ID_LIGHT_HSL_HUE_SRV ESP_BLE_MESH_MODEL_ID_LIGHT_HSL_SAT_SRV ESP_BLE_MESH_MODEL_ID_LIGHT_XYL_SRV ESP_BLE_MESH_MODEL_ID_LIGHT_XYL_SETUP_SRV ESP_BLE_MESH_MODEL_ID_LIGHT_XYL_CLI ESP_BLE_MESH_MODEL_ID_LIGHT_LC_SRV ESP_BLE_MESH_MODEL_ID_LIGHT_LC_SETUP_SRV ESP_BLE_MESH_MODEL_ID_LIGHT_LC_CLI ESP_BLE_MESH_MODEL_ID_MBT_SRV ESP_BLE_MESH_MODEL_ID_MBT_CLI ESP_BLE_MESH_MODEL_OP_BEACON_GET Config Beacon Get ESP_BLE_MESH_MODEL_OP_COMPOSITION_DATA_GET Config Composition Data Get ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_GET Config Default TTL Get ESP_BLE_MESH_MODEL_OP_GATT_PROXY_GET Config GATT Proxy Get ESP_BLE_MESH_MODEL_OP_RELAY_GET Config Relay Get ESP_BLE_MESH_MODEL_OP_MODEL_PUB_GET Config Model Publication Get ESP_BLE_MESH_MODEL_OP_FRIEND_GET Config Friend Get ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_GET Config Heartbeat Publication Get ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_GET Config Heartbeat Subscription Get ESP_BLE_MESH_MODEL_OP_NET_KEY_GET Config NetKey Get ESP_BLE_MESH_MODEL_OP_APP_KEY_GET Config AppKey Get ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_GET Config Node Identity Get ESP_BLE_MESH_MODEL_OP_SIG_MODEL_SUB_GET Config SIG Model Subscription Get ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_SUB_GET Config Vendor Model Subscription Get ESP_BLE_MESH_MODEL_OP_SIG_MODEL_APP_GET Config SIG Model App Get ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_APP_GET Config Vendor Model App Get ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_GET Config Key Refresh Phase Get ESP_BLE_MESH_MODEL_OP_LPN_POLLTIMEOUT_GET Config Low Power Node PollTimeout Get ESP_BLE_MESH_MODEL_OP_NETWORK_TRANSMIT_GET Config Network Transmit Get ESP_BLE_MESH_MODEL_OP_BEACON_SET Config Beacon Set ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_SET Config Default TTL Set ESP_BLE_MESH_MODEL_OP_GATT_PROXY_SET Config GATT Proxy Set ESP_BLE_MESH_MODEL_OP_RELAY_SET Config Relay Set ESP_BLE_MESH_MODEL_OP_MODEL_PUB_SET Config Model Publication Set ESP_BLE_MESH_MODEL_OP_MODEL_SUB_ADD Config Model Subscription Add ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_ADD Config Model Subscription Virtual Address Add ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE Config Model Subscription Delete ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_DELETE Config Model Subscription Virtual Address Delete ESP_BLE_MESH_MODEL_OP_MODEL_SUB_OVERWRITE Config Model Subscription Overwrite ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_OVERWRITE Config Model Subscription Virtual Address Overwrite ESP_BLE_MESH_MODEL_OP_NET_KEY_ADD Config NetKey Add ESP_BLE_MESH_MODEL_OP_APP_KEY_ADD Config AppKey Add ESP_BLE_MESH_MODEL_OP_MODEL_APP_BIND Config Model App Bind ESP_BLE_MESH_MODEL_OP_NODE_RESET Config Node Reset ESP_BLE_MESH_MODEL_OP_FRIEND_SET Config Friend Set ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_SET Config Heartbeat Publication Set ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_SET Config Heartbeat Subscription Set ESP_BLE_MESH_MODEL_OP_NET_KEY_UPDATE Config NetKey Update ESP_BLE_MESH_MODEL_OP_NET_KEY_DELETE Config NetKey Delete ESP_BLE_MESH_MODEL_OP_APP_KEY_UPDATE Config AppKey Update ESP_BLE_MESH_MODEL_OP_APP_KEY_DELETE Config AppKey Delete ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_SET Config Node Identity Set ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_SET Config Key Refresh Phase Set ESP_BLE_MESH_MODEL_OP_MODEL_PUB_VIRTUAL_ADDR_SET Config Model Publication Virtual Address Set ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE_ALL Config Model Subscription Delete All ESP_BLE_MESH_MODEL_OP_MODEL_APP_UNBIND Config Model App Unbind ESP_BLE_MESH_MODEL_OP_NETWORK_TRANSMIT_SET Config Network Transmit Set ESP_BLE_MESH_MODEL_OP_BEACON_STATUS ESP_BLE_MESH_MODEL_OP_COMPOSITION_DATA_STATUS ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_STATUS ESP_BLE_MESH_MODEL_OP_GATT_PROXY_STATUS ESP_BLE_MESH_MODEL_OP_RELAY_STATUS ESP_BLE_MESH_MODEL_OP_MODEL_PUB_STATUS ESP_BLE_MESH_MODEL_OP_MODEL_SUB_STATUS ESP_BLE_MESH_MODEL_OP_SIG_MODEL_SUB_LIST ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_SUB_LIST ESP_BLE_MESH_MODEL_OP_NET_KEY_STATUS ESP_BLE_MESH_MODEL_OP_NET_KEY_LIST ESP_BLE_MESH_MODEL_OP_APP_KEY_STATUS ESP_BLE_MESH_MODEL_OP_APP_KEY_LIST ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_STATUS ESP_BLE_MESH_MODEL_OP_MODEL_APP_STATUS ESP_BLE_MESH_MODEL_OP_SIG_MODEL_APP_LIST ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_APP_LIST ESP_BLE_MESH_MODEL_OP_NODE_RESET_STATUS ESP_BLE_MESH_MODEL_OP_FRIEND_STATUS ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_STATUS ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_STATUS ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_STATUS ESP_BLE_MESH_MODEL_OP_LPN_POLLTIMEOUT_STATUS ESP_BLE_MESH_MODEL_OP_NETWORK_TRANSMIT_STATUS ESP_BLE_MESH_CFG_STATUS_SUCCESS ESP_BLE_MESH_CFG_STATUS_INVALID_ADDRESS ESP_BLE_MESH_CFG_STATUS_INVALID_MODEL ESP_BLE_MESH_CFG_STATUS_INVALID_APPKEY ESP_BLE_MESH_CFG_STATUS_INVALID_NETKEY ESP_BLE_MESH_CFG_STATUS_INSUFFICIENT_RESOURCES ESP_BLE_MESH_CFG_STATUS_KEY_INDEX_ALREADY_STORED ESP_BLE_MESH_CFG_STATUS_INVALID_PUBLISH_PARAMETERS ESP_BLE_MESH_CFG_STATUS_NOT_A_SUBSCRIBE_MODEL ESP_BLE_MESH_CFG_STATUS_STORAGE_FAILURE ESP_BLE_MESH_CFG_STATUS_FEATURE_NOT_SUPPORTED ESP_BLE_MESH_CFG_STATUS_CANNOT_UPDATE ESP_BLE_MESH_CFG_STATUS_CANNOT_REMOVE ESP_BLE_MESH_CFG_STATUS_CANNOT_BIND ESP_BLE_MESH_CFG_STATUS_TEMP_UNABLE_TO_CHANGE_STATE ESP_BLE_MESH_CFG_STATUS_CANNOT_SET ESP_BLE_MESH_CFG_STATUS_UNSPECIFIED_ERROR ESP_BLE_MESH_CFG_STATUS_INVALID_BINDING ESP_BLE_MESH_CFG_STATUS_INVALID_PATH_ENTRY ESP_BLE_MESH_CFG_STATUS_CANNOT_GET ESP_BLE_MESH_CFG_STATUS_OBSOLETE_INFO ESP_BLE_MESH_CFG_STATUS_INVALID_BEARER ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_GET Health Fault Get ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_GET Health Period Get ESP_BLE_MESH_MODEL_OP_ATTENTION_GET Health Attention Get ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR Health Fault Clear ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR_UNACK Health Fault Clear Unacknowledged ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST Health Fault Test ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST_UNACK Health Fault Test Unacknowledged ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET Health Period Set ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET_UNACK Health Period Set Unacknowledged ESP_BLE_MESH_MODEL_OP_ATTENTION_SET Health Attention Set ESP_BLE_MESH_MODEL_OP_ATTENTION_SET_UNACK Health Attention Set Unacknowledged ESP_BLE_MESH_MODEL_OP_HEALTH_CURRENT_STATUS ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_STATUS ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_STATUS ESP_BLE_MESH_MODEL_OP_ATTENTION_STATUS ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_GET ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_SET ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_SET_UNACK ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_STATUS Generic Level Message Opcode ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_GET ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_SET ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_SET_UNACK ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_STATUS ESP_BLE_MESH_MODEL_OP_GEN_DELTA_SET ESP_BLE_MESH_MODEL_OP_GEN_DELTA_SET_UNACK ESP_BLE_MESH_MODEL_OP_GEN_MOVE_SET ESP_BLE_MESH_MODEL_OP_GEN_MOVE_SET_UNACK Generic Default Transition Time Message Opcode ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_GET ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET_UNACK ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_STATUS Generic Power OnOff Message Opcode ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_GET ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_STATUS Generic Power OnOff Setup Message Opcode ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET_UNACK Generic Power Level Message Opcode ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_GET ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET_UNACK ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_STATUS ESP_BLE_MESH_MODEL_OP_GEN_POWER_LAST_GET ESP_BLE_MESH_MODEL_OP_GEN_POWER_LAST_STATUS ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_GET ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_STATUS ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_GET ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_STATUS Generic Power Level Setup Message Opcode ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET_UNACK ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET_UNACK Generic Battery Message Opcode ESP_BLE_MESH_MODEL_OP_GEN_BATTERY_GET ESP_BLE_MESH_MODEL_OP_GEN_BATTERY_STATUS Generic Location Message Opcode ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_GET ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_STATUS ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_GET ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_STATUS Generic Location Setup Message Opcode ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET_UNACK ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET_UNACK Generic Manufacturer Property Message Opcode ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTIES_GET ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTIES_STATUS ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_GET ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET_UNACK ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_STATUS Generic Admin Property Message Opcode ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTIES_GET ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTIES_STATUS ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_GET ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET_UNACK ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_STATUS Generic User Property Message Opcode ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTIES_GET ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTIES_STATUS ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_GET ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET_UNACK ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_STATUS Generic Client Property Message Opcode ESP_BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_GET ESP_BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_STATUS ESP_BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_GET ESP_BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_STATUS ESP_BLE_MESH_MODEL_OP_SENSOR_GET ESP_BLE_MESH_MODEL_OP_SENSOR_STATUS ESP_BLE_MESH_MODEL_OP_SENSOR_COLUMN_GET ESP_BLE_MESH_MODEL_OP_SENSOR_COLUMN_STATUS ESP_BLE_MESH_MODEL_OP_SENSOR_SERIES_GET ESP_BLE_MESH_MODEL_OP_SENSOR_SERIES_STATUS Sensor Setup Message Opcode ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_GET ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET_UNACK ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_STATUS ESP_BLE_MESH_MODEL_OP_SENSOR_SETTINGS_GET ESP_BLE_MESH_MODEL_OP_SENSOR_SETTINGS_STATUS ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_GET ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_SET ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_SET_UNACK ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_STATUS ESP_BLE_MESH_MODEL_OP_TIME_GET ESP_BLE_MESH_MODEL_OP_TIME_SET ESP_BLE_MESH_MODEL_OP_TIME_STATUS ESP_BLE_MESH_MODEL_OP_TIME_ROLE_GET ESP_BLE_MESH_MODEL_OP_TIME_ROLE_SET ESP_BLE_MESH_MODEL_OP_TIME_ROLE_STATUS ESP_BLE_MESH_MODEL_OP_TIME_ZONE_GET ESP_BLE_MESH_MODEL_OP_TIME_ZONE_SET ESP_BLE_MESH_MODEL_OP_TIME_ZONE_STATUS ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_GET ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_SET ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_STATUS Scene Message Opcode ESP_BLE_MESH_MODEL_OP_SCENE_GET ESP_BLE_MESH_MODEL_OP_SCENE_RECALL ESP_BLE_MESH_MODEL_OP_SCENE_RECALL_UNACK ESP_BLE_MESH_MODEL_OP_SCENE_STATUS ESP_BLE_MESH_MODEL_OP_SCENE_REGISTER_GET ESP_BLE_MESH_MODEL_OP_SCENE_REGISTER_STATUS Scene Setup Message Opcode ESP_BLE_MESH_MODEL_OP_SCENE_STORE ESP_BLE_MESH_MODEL_OP_SCENE_STORE_UNACK ESP_BLE_MESH_MODEL_OP_SCENE_DELETE ESP_BLE_MESH_MODEL_OP_SCENE_DELETE_UNACK Scheduler Message Opcode ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_GET ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_STATUS ESP_BLE_MESH_MODEL_OP_SCHEDULER_GET ESP_BLE_MESH_MODEL_OP_SCHEDULER_STATUS Scheduler Setup Message Opcode ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_GET ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_GET ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LAST_GET ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LAST_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_GET ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_GET ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_STATUS Light Lightness Setup Message Opcode ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET_UNACK Light CTL Message Opcode ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_GET ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_SET ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_GET ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_GET ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_GET ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_STATUS Light CTL Setup Message Opcode ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET_UNACK Light HSL Message Opcode ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_GET ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_GET ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_SET ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_GET ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SET ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_TARGET_GET ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_TARGET_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_GET ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_GET ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_STATUS Light HSL Setup Message Opcode ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET_UNACK Light xyL Message Opcode ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_GET ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_SET ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_TARGET_GET ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_TARGET_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_GET ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_GET ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_STATUS Light xyL Setup Message Opcode ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET_UNACK Light Control Message Opcode ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_GET ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_GET ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_GET ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_STATUS ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_GET ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET_UNACK ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_STATUS ESP_BLE_MESH_MODEL_STATUS_SUCCESS ESP_BLE_MESH_MODEL_STATUS_CANNOT_SET_RANGE_MIN ESP_BLE_MESH_MODEL_STATUS_CANNOT_SET_RANGE_MAX ESP_BLE_MESH_SERVER_RSP_BY_APP Response need to be sent in the application ESP_BLE_MESH_SERVER_AUTO_RSP Response will be sent internally Type Definitions typedef uint8_t esp_ble_mesh_octet16_t[ESP_BLE_MESH_OCTET16_LEN] Define the BLE Mesh octet 8 bytes size typedef uint8_t esp_ble_mesh_octet8_t[ESP_BLE_MESH_OCTET8_LEN] Invalid Company ID typedef uint32_t esp_ble_mesh_cb_t typedef uint8_t UINT8 typedef uint16_t UINT16 typedef uint32_t UINT32 typedef uint64_t UINT64 typedef uint8_t BD_ADDR[BD_ADDR_LEN] typedef uint8_t esp_ble_mesh_bd_addr_t[BD_ADDR_LEN] typedef uint8_t esp_ble_mesh_addr_type_t BLE device address type. typedef struct esp_ble_mesh_model esp_ble_mesh_model_t typedef uint8_t esp_ble_mesh_dev_add_flag_t typedef uint32_t esp_ble_mesh_opcode_config_client_get_t esp_ble_mesh_opcode_config_client_get_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by esp_ble_mesh_config_client_get_state. The following opcodes will only be used in the esp_ble_mesh_config_client_get_state function. typedef uint32_t esp_ble_mesh_opcode_config_client_set_t esp_ble_mesh_opcode_config_client_set_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by esp_ble_mesh_config_client_set_state. The following opcodes will only be used in the esp_ble_mesh_config_client_set_state function. typedef uint32_t esp_ble_mesh_opcode_config_status_t esp_ble_mesh_opcode_config_status_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by the Config Model messages The following opcodes are used by the BLE Mesh Config Server Model internally to respond to the Config Client Model's request messages. typedef uint8_t esp_ble_mesh_cfg_status_t This typedef is only used to indicate the status code contained in some of the Configuration Server Model status message. typedef uint32_t esp_ble_mesh_opcode_health_client_get_t esp_ble_mesh_opcode_health_client_get_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by esp_ble_mesh_health_client_get_state. The following opcodes will only be used in the esp_ble_mesh_health_client_get_state function. typedef uint32_t esp_ble_mesh_opcode_health_client_set_t esp_ble_mesh_opcode_health_client_set_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by esp_ble_mesh_health_client_set_state. The following opcodes will only be used in the esp_ble_mesh_health_client_set_state function. typedef uint32_t esp_ble_mesh_health_model_status_t esp_ble_mesh_health_model_status_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by the Health Model messages. The following opcodes are used by the BLE Mesh Health Server Model internally to respond to the Health Client Model's request messages. typedef uint32_t esp_ble_mesh_generic_message_opcode_t esp_ble_mesh_generic_message_opcode_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by functions esp_ble_mesh_generic_client_get_state & esp_ble_mesh_generic_client_set_state. Generic OnOff Message Opcode typedef uint32_t esp_ble_mesh_sensor_message_opcode_t esp_ble_mesh_sensor_message_opcode_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by functions esp_ble_mesh_sensor_client_get_state & esp_ble_mesh_sensor_client_set_state. Sensor Message Opcode typedef uint32_t esp_ble_mesh_time_scene_message_opcode_t esp_ble_mesh_time_scene_message_opcode_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by functions esp_ble_mesh_time_scene_client_get_state & esp_ble_mesh_time_scene_client_set_state. Time Message Opcode typedef uint32_t esp_ble_mesh_light_message_opcode_t esp_ble_mesh_light_message_opcode_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by functions esp_ble_mesh_light_client_get_state & esp_ble_mesh_light_client_set_state. Light Lightness Message Opcode typedef uint32_t esp_ble_mesh_opcode_t End of defines of esp_ble_mesh_opcode_t typedef uint8_t esp_ble_mesh_model_status_t This typedef is only used to indicate the status code contained in some of the server models (e.g. Generic Server Model) status message. Enumerations enum esp_ble_mesh_cb_type_t Values: enumerator ESP_BLE_MESH_TYPE_PROV_CB enumerator ESP_BLE_MESH_TYPE_PROV_CB enumerator ESP_BLE_MESH_TYPE_OUTPUT_NUM_CB enumerator ESP_BLE_MESH_TYPE_OUTPUT_NUM_CB enumerator ESP_BLE_MESH_TYPE_OUTPUT_STR_CB enumerator ESP_BLE_MESH_TYPE_OUTPUT_STR_CB enumerator ESP_BLE_MESH_TYPE_INTPUT_CB enumerator ESP_BLE_MESH_TYPE_INTPUT_CB enumerator ESP_BLE_MESH_TYPE_LINK_OPEN_CB enumerator ESP_BLE_MESH_TYPE_LINK_OPEN_CB enumerator ESP_BLE_MESH_TYPE_LINK_CLOSE_CB enumerator ESP_BLE_MESH_TYPE_LINK_CLOSE_CB enumerator ESP_BLE_MESH_TYPE_COMPLETE_CB enumerator ESP_BLE_MESH_TYPE_COMPLETE_CB enumerator ESP_BLE_MESH_TYPE_RESET_CB enumerator ESP_BLE_MESH_TYPE_RESET_CB enumerator ESP_BLE_MESH_TYPE_PROV_CB enum esp_ble_mesh_oob_method_t Values: enumerator ESP_BLE_MESH_NO_OOB enumerator ESP_BLE_MESH_NO_OOB enumerator ESP_BLE_MESH_STATIC_OOB enumerator ESP_BLE_MESH_STATIC_OOB enumerator ESP_BLE_MESH_OUTPUT_OOB enumerator ESP_BLE_MESH_OUTPUT_OOB enumerator ESP_BLE_MESH_INPUT_OOB enumerator ESP_BLE_MESH_INPUT_OOB enumerator ESP_BLE_MESH_NO_OOB enum esp_ble_mesh_output_action_t Values: enumerator ESP_BLE_MESH_NO_OUTPUT enumerator ESP_BLE_MESH_NO_OUTPUT enumerator ESP_BLE_MESH_BLINK enumerator ESP_BLE_MESH_BLINK enumerator ESP_BLE_MESH_BEEP enumerator ESP_BLE_MESH_BEEP enumerator ESP_BLE_MESH_VIBRATE enumerator ESP_BLE_MESH_VIBRATE enumerator ESP_BLE_MESH_DISPLAY_NUMBER enumerator ESP_BLE_MESH_DISPLAY_NUMBER enumerator ESP_BLE_MESH_DISPLAY_STRING enumerator ESP_BLE_MESH_DISPLAY_STRING enumerator ESP_BLE_MESH_NO_OUTPUT enum esp_ble_mesh_input_action_t Values: enumerator ESP_BLE_MESH_NO_INPUT enumerator ESP_BLE_MESH_NO_INPUT enumerator ESP_BLE_MESH_PUSH enumerator ESP_BLE_MESH_PUSH enumerator ESP_BLE_MESH_TWIST enumerator ESP_BLE_MESH_TWIST enumerator ESP_BLE_MESH_ENTER_NUMBER enumerator ESP_BLE_MESH_ENTER_NUMBER enumerator ESP_BLE_MESH_ENTER_STRING enumerator ESP_BLE_MESH_ENTER_STRING enumerator ESP_BLE_MESH_NO_INPUT enum esp_ble_mesh_prov_bearer_t Values: enumerator ESP_BLE_MESH_PROV_ADV enumerator ESP_BLE_MESH_PROV_ADV enumerator ESP_BLE_MESH_PROV_GATT enumerator ESP_BLE_MESH_PROV_GATT enumerator ESP_BLE_MESH_PROV_ADV enum esp_ble_mesh_prov_oob_info_t Values: enumerator ESP_BLE_MESH_PROV_OOB_OTHER enumerator ESP_BLE_MESH_PROV_OOB_OTHER enumerator ESP_BLE_MESH_PROV_OOB_URI enumerator ESP_BLE_MESH_PROV_OOB_URI enumerator ESP_BLE_MESH_PROV_OOB_2D_CODE enumerator ESP_BLE_MESH_PROV_OOB_2D_CODE enumerator ESP_BLE_MESH_PROV_OOB_BAR_CODE enumerator ESP_BLE_MESH_PROV_OOB_BAR_CODE enumerator ESP_BLE_MESH_PROV_OOB_NFC enumerator ESP_BLE_MESH_PROV_OOB_NFC enumerator ESP_BLE_MESH_PROV_OOB_NUMBER enumerator ESP_BLE_MESH_PROV_OOB_NUMBER enumerator ESP_BLE_MESH_PROV_OOB_STRING enumerator ESP_BLE_MESH_PROV_OOB_STRING enumerator ESP_BLE_MESH_PROV_CERT_BASED enumerator ESP_BLE_MESH_PROV_CERT_BASED enumerator ESP_BLE_MESH_PROV_RECORDS enumerator ESP_BLE_MESH_PROV_RECORDS enumerator ESP_BLE_MESH_PROV_OOB_ON_BOX enumerator ESP_BLE_MESH_PROV_OOB_ON_BOX enumerator ESP_BLE_MESH_PROV_OOB_IN_BOX enumerator ESP_BLE_MESH_PROV_OOB_IN_BOX enumerator ESP_BLE_MESH_PROV_OOB_ON_PAPER enumerator ESP_BLE_MESH_PROV_OOB_ON_PAPER enumerator ESP_BLE_MESH_PROV_OOB_IN_MANUAL enumerator ESP_BLE_MESH_PROV_OOB_IN_MANUAL enumerator ESP_BLE_MESH_PROV_OOB_ON_DEV enumerator ESP_BLE_MESH_PROV_OOB_ON_DEV enumerator ESP_BLE_MESH_PROV_OOB_OTHER enum esp_ble_mesh_dev_role_t Values: enumerator ROLE_NODE enumerator ROLE_NODE enumerator ROLE_PROVISIONER enumerator ROLE_PROVISIONER enumerator ROLE_FAST_PROV enumerator ROLE_FAST_PROV enumerator ROLE_NODE enum esp_ble_mesh_fast_prov_action_t Values: enumerator FAST_PROV_ACT_NONE enumerator FAST_PROV_ACT_NONE enumerator FAST_PROV_ACT_ENTER enumerator FAST_PROV_ACT_ENTER enumerator FAST_PROV_ACT_SUSPEND enumerator FAST_PROV_ACT_SUSPEND enumerator FAST_PROV_ACT_EXIT enumerator FAST_PROV_ACT_EXIT enumerator FAST_PROV_ACT_MAX enumerator FAST_PROV_ACT_MAX enumerator FAST_PROV_ACT_NONE enum esp_ble_mesh_proxy_filter_type_t Values: enumerator PROXY_FILTER_WHITELIST enumerator PROXY_FILTER_WHITELIST enumerator PROXY_FILTER_BLACKLIST enumerator PROXY_FILTER_BLACKLIST enumerator PROXY_FILTER_WHITELIST enum esp_ble_mesh_prov_cb_event_t Values: enumerator ESP_BLE_MESH_PROV_REGISTER_COMP_EVT Initialize BLE Mesh provisioning capabilities and internal data information completion event enumerator ESP_BLE_MESH_PROV_REGISTER_COMP_EVT Initialize BLE Mesh provisioning capabilities and internal data information completion event enumerator ESP_BLE_MESH_NODE_SET_UNPROV_DEV_NAME_COMP_EVT Set the unprovisioned device name completion event enumerator ESP_BLE_MESH_NODE_SET_UNPROV_DEV_NAME_COMP_EVT Set the unprovisioned device name completion event enumerator ESP_BLE_MESH_NODE_PROV_ENABLE_COMP_EVT Enable node provisioning functionality completion event enumerator ESP_BLE_MESH_NODE_PROV_ENABLE_COMP_EVT Enable node provisioning functionality completion event enumerator ESP_BLE_MESH_NODE_PROV_DISABLE_COMP_EVT Disable node provisioning functionality completion event enumerator ESP_BLE_MESH_NODE_PROV_DISABLE_COMP_EVT Disable node provisioning functionality completion event enumerator ESP_BLE_MESH_NODE_PROV_LINK_OPEN_EVT Establish a BLE Mesh link event enumerator ESP_BLE_MESH_NODE_PROV_LINK_OPEN_EVT Establish a BLE Mesh link event enumerator ESP_BLE_MESH_NODE_PROV_LINK_CLOSE_EVT Close a BLE Mesh link event enumerator ESP_BLE_MESH_NODE_PROV_LINK_CLOSE_EVT Close a BLE Mesh link event enumerator ESP_BLE_MESH_NODE_PROV_OOB_PUB_KEY_EVT Generate Node input OOB public key event enumerator ESP_BLE_MESH_NODE_PROV_OOB_PUB_KEY_EVT Generate Node input OOB public key event enumerator ESP_BLE_MESH_NODE_PROV_OUTPUT_NUMBER_EVT Generate Node Output Number event enumerator ESP_BLE_MESH_NODE_PROV_OUTPUT_NUMBER_EVT Generate Node Output Number event enumerator ESP_BLE_MESH_NODE_PROV_OUTPUT_STRING_EVT Generate Node Output String event enumerator ESP_BLE_MESH_NODE_PROV_OUTPUT_STRING_EVT Generate Node Output String event enumerator ESP_BLE_MESH_NODE_PROV_INPUT_EVT Event requiring the user to input a number or string enumerator ESP_BLE_MESH_NODE_PROV_INPUT_EVT Event requiring the user to input a number or string enumerator ESP_BLE_MESH_NODE_PROV_COMPLETE_EVT Provisioning done event enumerator ESP_BLE_MESH_NODE_PROV_COMPLETE_EVT Provisioning done event enumerator ESP_BLE_MESH_NODE_PROV_RESET_EVT Provisioning reset event enumerator ESP_BLE_MESH_NODE_PROV_RESET_EVT Provisioning reset event enumerator ESP_BLE_MESH_NODE_PROV_SET_OOB_PUB_KEY_COMP_EVT Node set oob public key completion event enumerator ESP_BLE_MESH_NODE_PROV_SET_OOB_PUB_KEY_COMP_EVT Node set oob public key completion event enumerator ESP_BLE_MESH_NODE_PROV_INPUT_NUMBER_COMP_EVT Node input number completion event enumerator ESP_BLE_MESH_NODE_PROV_INPUT_NUMBER_COMP_EVT Node input number completion event enumerator ESP_BLE_MESH_NODE_PROV_INPUT_STRING_COMP_EVT Node input string completion event enumerator ESP_BLE_MESH_NODE_PROV_INPUT_STRING_COMP_EVT Node input string completion event enumerator ESP_BLE_MESH_NODE_PROXY_IDENTITY_ENABLE_COMP_EVT Enable BLE Mesh Proxy Identity advertising completion event enumerator ESP_BLE_MESH_NODE_PROXY_IDENTITY_ENABLE_COMP_EVT Enable BLE Mesh Proxy Identity advertising completion event enumerator ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_ENABLE_COMP_EVT Enable BLE Mesh Private Proxy Identity advertising completion event enumerator ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_ENABLE_COMP_EVT Enable BLE Mesh Private Proxy Identity advertising completion event enumerator ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_DISABLE_COMP_EVT Disable BLE Mesh Private Proxy Identity advertising completion event enumerator ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_DISABLE_COMP_EVT Disable BLE Mesh Private Proxy Identity advertising completion event enumerator ESP_BLE_MESH_NODE_PROXY_GATT_ENABLE_COMP_EVT Enable BLE Mesh GATT Proxy Service completion event enumerator ESP_BLE_MESH_NODE_PROXY_GATT_ENABLE_COMP_EVT Enable BLE Mesh GATT Proxy Service completion event enumerator ESP_BLE_MESH_NODE_PROXY_GATT_DISABLE_COMP_EVT Disable BLE Mesh GATT Proxy Service completion event enumerator ESP_BLE_MESH_NODE_PROXY_GATT_DISABLE_COMP_EVT Disable BLE Mesh GATT Proxy Service completion event enumerator ESP_BLE_MESH_NODE_ADD_LOCAL_NET_KEY_COMP_EVT Node add NetKey locally completion event enumerator ESP_BLE_MESH_NODE_ADD_LOCAL_NET_KEY_COMP_EVT Node add NetKey locally completion event enumerator ESP_BLE_MESH_NODE_ADD_LOCAL_APP_KEY_COMP_EVT Node add AppKey locally completion event enumerator ESP_BLE_MESH_NODE_ADD_LOCAL_APP_KEY_COMP_EVT Node add AppKey locally completion event enumerator ESP_BLE_MESH_NODE_BIND_APP_KEY_TO_MODEL_COMP_EVT Node bind AppKey to model locally completion event enumerator ESP_BLE_MESH_NODE_BIND_APP_KEY_TO_MODEL_COMP_EVT Node bind AppKey to model locally completion event enumerator ESP_BLE_MESH_PROVISIONER_PROV_ENABLE_COMP_EVT Provisioner enable provisioning functionality completion event enumerator ESP_BLE_MESH_PROVISIONER_PROV_ENABLE_COMP_EVT Provisioner enable provisioning functionality completion event enumerator ESP_BLE_MESH_PROVISIONER_PROV_DISABLE_COMP_EVT Provisioner disable provisioning functionality completion event enumerator ESP_BLE_MESH_PROVISIONER_PROV_DISABLE_COMP_EVT Provisioner disable provisioning functionality completion event enumerator ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT Provisioner receives unprovisioned device beacon event enumerator ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT Provisioner receives unprovisioned device beacon event enumerator ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_EVT Provisioner read unprovisioned device OOB public key event enumerator ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_EVT Provisioner read unprovisioned device OOB public key event enumerator ESP_BLE_MESH_PROVISIONER_PROV_INPUT_EVT Provisioner input value for provisioning procedure event enumerator ESP_BLE_MESH_PROVISIONER_PROV_INPUT_EVT Provisioner input value for provisioning procedure event enumerator ESP_BLE_MESH_PROVISIONER_PROV_OUTPUT_EVT Provisioner output value for provisioning procedure event enumerator ESP_BLE_MESH_PROVISIONER_PROV_OUTPUT_EVT Provisioner output value for provisioning procedure event enumerator ESP_BLE_MESH_PROVISIONER_PROV_LINK_OPEN_EVT Provisioner establish a BLE Mesh link event enumerator ESP_BLE_MESH_PROVISIONER_PROV_LINK_OPEN_EVT Provisioner establish a BLE Mesh link event enumerator ESP_BLE_MESH_PROVISIONER_PROV_LINK_CLOSE_EVT Provisioner close a BLE Mesh link event enumerator ESP_BLE_MESH_PROVISIONER_PROV_LINK_CLOSE_EVT Provisioner close a BLE Mesh link event enumerator ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT Provisioner provisioning done event enumerator ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT Provisioner provisioning done event enumerator ESP_BLE_MESH_PROVISIONER_CERT_BASED_PROV_START_EVT Provisioner initiate a certificate based provisioning enumerator ESP_BLE_MESH_PROVISIONER_CERT_BASED_PROV_START_EVT Provisioner initiate a certificate based provisioning enumerator ESP_BLE_MESH_PROVISIONER_RECV_PROV_RECORDS_LIST_EVT Provisioner receive provisioning records list event enumerator ESP_BLE_MESH_PROVISIONER_RECV_PROV_RECORDS_LIST_EVT Provisioner receive provisioning records list event enumerator ESP_BLE_MESH_PROVISIONER_PROV_RECORD_RECV_COMP_EVT Provisioner receive provisioning record complete event enumerator ESP_BLE_MESH_PROVISIONER_PROV_RECORD_RECV_COMP_EVT Provisioner receive provisioning record complete event enumerator ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORDS_GET_EVT Provisioner send provisioning records get to device event enumerator ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORDS_GET_EVT Provisioner send provisioning records get to device event enumerator ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORD_REQUEST_EVT Provisioner send provisioning record request to device event enumerator ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORD_REQUEST_EVT Provisioner send provisioning record request to device event enumerator ESP_BLE_MESH_PROVISIONER_SEND_PROV_INVITE_EVT Provisioner send provisioning invite to device event enumerator ESP_BLE_MESH_PROVISIONER_SEND_PROV_INVITE_EVT Provisioner send provisioning invite to device event enumerator ESP_BLE_MESH_PROVISIONER_SEND_LINK_CLOSE_EVT Provisioner send link close to device event enumerator ESP_BLE_MESH_PROVISIONER_SEND_LINK_CLOSE_EVT Provisioner send link close to device event enumerator ESP_BLE_MESH_PROVISIONER_ADD_UNPROV_DEV_COMP_EVT Provisioner add a device to the list which contains devices that are waiting/going to be provisioned completion event enumerator ESP_BLE_MESH_PROVISIONER_ADD_UNPROV_DEV_COMP_EVT Provisioner add a device to the list which contains devices that are waiting/going to be provisioned completion event enumerator ESP_BLE_MESH_PROVISIONER_PROV_DEV_WITH_ADDR_COMP_EVT Provisioner start to provision an unprovisioned device completion event enumerator ESP_BLE_MESH_PROVISIONER_PROV_DEV_WITH_ADDR_COMP_EVT Provisioner start to provision an unprovisioned device completion event enumerator ESP_BLE_MESH_PROVISIONER_DELETE_DEV_COMP_EVT Provisioner delete a device from the list, close provisioning link with the device completion event enumerator ESP_BLE_MESH_PROVISIONER_DELETE_DEV_COMP_EVT Provisioner delete a device from the list, close provisioning link with the device completion event enumerator ESP_BLE_MESH_PROVISIONER_SET_DEV_UUID_MATCH_COMP_EVT Provisioner set the value to be compared with part of the unprovisioned device UUID completion event enumerator ESP_BLE_MESH_PROVISIONER_SET_DEV_UUID_MATCH_COMP_EVT Provisioner set the value to be compared with part of the unprovisioned device UUID completion event enumerator ESP_BLE_MESH_PROVISIONER_SET_PROV_DATA_INFO_COMP_EVT Provisioner set net_idx/flags/iv_index used for provisioning completion event enumerator ESP_BLE_MESH_PROVISIONER_SET_PROV_DATA_INFO_COMP_EVT Provisioner set net_idx/flags/iv_index used for provisioning completion event enumerator ESP_BLE_MESH_PROVISIONER_SET_STATIC_OOB_VALUE_COMP_EVT Provisioner set static oob value used for provisioning completion event enumerator ESP_BLE_MESH_PROVISIONER_SET_STATIC_OOB_VALUE_COMP_EVT Provisioner set static oob value used for provisioning completion event enumerator ESP_BLE_MESH_PROVISIONER_SET_PRIMARY_ELEM_ADDR_COMP_EVT Provisioner set unicast address of primary element completion event enumerator ESP_BLE_MESH_PROVISIONER_SET_PRIMARY_ELEM_ADDR_COMP_EVT Provisioner set unicast address of primary element completion event enumerator ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_COMP_EVT Provisioner read unprovisioned device OOB public key completion event enumerator ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_COMP_EVT Provisioner read unprovisioned device OOB public key completion event enumerator ESP_BLE_MESH_PROVISIONER_PROV_INPUT_NUMBER_COMP_EVT Provisioner input number completion event enumerator ESP_BLE_MESH_PROVISIONER_PROV_INPUT_NUMBER_COMP_EVT Provisioner input number completion event enumerator ESP_BLE_MESH_PROVISIONER_PROV_INPUT_STRING_COMP_EVT Provisioner input string completion event enumerator ESP_BLE_MESH_PROVISIONER_PROV_INPUT_STRING_COMP_EVT Provisioner input string completion event enumerator ESP_BLE_MESH_PROVISIONER_SET_NODE_NAME_COMP_EVT Provisioner set node name completion event enumerator ESP_BLE_MESH_PROVISIONER_SET_NODE_NAME_COMP_EVT Provisioner set node name completion event enumerator ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_APP_KEY_COMP_EVT Provisioner add local app key completion event enumerator ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_APP_KEY_COMP_EVT Provisioner add local app key completion event enumerator ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_APP_KEY_COMP_EVT Provisioner update local app key completion event enumerator ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_APP_KEY_COMP_EVT Provisioner update local app key completion event enumerator ESP_BLE_MESH_PROVISIONER_BIND_APP_KEY_TO_MODEL_COMP_EVT Provisioner bind local model with local app key completion event enumerator ESP_BLE_MESH_PROVISIONER_BIND_APP_KEY_TO_MODEL_COMP_EVT Provisioner bind local model with local app key completion event enumerator ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_NET_KEY_COMP_EVT Provisioner add local network key completion event enumerator ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_NET_KEY_COMP_EVT Provisioner add local network key completion event enumerator ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_NET_KEY_COMP_EVT Provisioner update local network key completion event enumerator ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_NET_KEY_COMP_EVT Provisioner update local network key completion event enumerator ESP_BLE_MESH_PROVISIONER_STORE_NODE_COMP_DATA_COMP_EVT Provisioner store node composition data completion event enumerator ESP_BLE_MESH_PROVISIONER_STORE_NODE_COMP_DATA_COMP_EVT Provisioner store node composition data completion event enumerator ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_UUID_COMP_EVT Provisioner delete node with uuid completion event enumerator ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_UUID_COMP_EVT Provisioner delete node with uuid completion event enumerator ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_ADDR_COMP_EVT Provisioner delete node with unicast address completion event enumerator ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_ADDR_COMP_EVT Provisioner delete node with unicast address completion event enumerator ESP_BLE_MESH_PROVISIONER_ENABLE_HEARTBEAT_RECV_COMP_EVT Provisioner start to receive heartbeat message completion event enumerator ESP_BLE_MESH_PROVISIONER_ENABLE_HEARTBEAT_RECV_COMP_EVT Provisioner start to receive heartbeat message completion event enumerator ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_TYPE_COMP_EVT Provisioner set the heartbeat filter type completion event enumerator ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_TYPE_COMP_EVT Provisioner set the heartbeat filter type completion event enumerator ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_INFO_COMP_EVT Provisioner set the heartbeat filter information completion event enumerator ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_INFO_COMP_EVT Provisioner set the heartbeat filter information completion event enumerator ESP_BLE_MESH_PROVISIONER_RECV_HEARTBEAT_MESSAGE_EVT Provisioner receive heartbeat message event enumerator ESP_BLE_MESH_PROVISIONER_RECV_HEARTBEAT_MESSAGE_EVT Provisioner receive heartbeat message event enumerator ESP_BLE_MESH_PROVISIONER_DIRECT_ERASE_SETTINGS_COMP_EVT Provisioner directly erase settings completion event enumerator ESP_BLE_MESH_PROVISIONER_DIRECT_ERASE_SETTINGS_COMP_EVT Provisioner directly erase settings completion event enumerator ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_INDEX_COMP_EVT Provisioner open settings with index completion event enumerator ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_INDEX_COMP_EVT Provisioner open settings with index completion event enumerator ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_UID_COMP_EVT Provisioner open settings with user id completion event enumerator ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_UID_COMP_EVT Provisioner open settings with user id completion event enumerator ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_INDEX_COMP_EVT Provisioner close settings with index completion event enumerator ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_INDEX_COMP_EVT Provisioner close settings with index completion event enumerator ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_UID_COMP_EVT Provisioner close settings with user id completion event enumerator ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_UID_COMP_EVT Provisioner close settings with user id completion event enumerator ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_INDEX_COMP_EVT Provisioner delete settings with index completion event enumerator ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_INDEX_COMP_EVT Provisioner delete settings with index completion event enumerator ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_UID_COMP_EVT Provisioner delete settings with user id completion event enumerator ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_UID_COMP_EVT Provisioner delete settings with user id completion event enumerator ESP_BLE_MESH_SET_FAST_PROV_INFO_COMP_EVT Set fast provisioning information (e.g. unicast address range, net_idx, etc.) completion event enumerator ESP_BLE_MESH_SET_FAST_PROV_INFO_COMP_EVT Set fast provisioning information (e.g. unicast address range, net_idx, etc.) completion event enumerator ESP_BLE_MESH_SET_FAST_PROV_ACTION_COMP_EVT Set fast provisioning action completion event enumerator ESP_BLE_MESH_SET_FAST_PROV_ACTION_COMP_EVT Set fast provisioning action completion event enumerator ESP_BLE_MESH_HEARTBEAT_MESSAGE_RECV_EVT Receive Heartbeat message event enumerator ESP_BLE_MESH_HEARTBEAT_MESSAGE_RECV_EVT Receive Heartbeat message event enumerator ESP_BLE_MESH_LPN_ENABLE_COMP_EVT Enable Low Power Node completion event enumerator ESP_BLE_MESH_LPN_ENABLE_COMP_EVT Enable Low Power Node completion event enumerator ESP_BLE_MESH_LPN_DISABLE_COMP_EVT Disable Low Power Node completion event enumerator ESP_BLE_MESH_LPN_DISABLE_COMP_EVT Disable Low Power Node completion event enumerator ESP_BLE_MESH_LPN_POLL_COMP_EVT Low Power Node send Friend Poll completion event enumerator ESP_BLE_MESH_LPN_POLL_COMP_EVT Low Power Node send Friend Poll completion event enumerator ESP_BLE_MESH_LPN_FRIENDSHIP_ESTABLISH_EVT Low Power Node establishes friendship event enumerator ESP_BLE_MESH_LPN_FRIENDSHIP_ESTABLISH_EVT Low Power Node establishes friendship event enumerator ESP_BLE_MESH_LPN_FRIENDSHIP_TERMINATE_EVT Low Power Node terminates friendship event enumerator ESP_BLE_MESH_LPN_FRIENDSHIP_TERMINATE_EVT Low Power Node terminates friendship event enumerator ESP_BLE_MESH_FRIEND_FRIENDSHIP_ESTABLISH_EVT Friend Node establishes friendship event enumerator ESP_BLE_MESH_FRIEND_FRIENDSHIP_ESTABLISH_EVT Friend Node establishes friendship event enumerator ESP_BLE_MESH_FRIEND_FRIENDSHIP_TERMINATE_EVT Friend Node terminates friendship event enumerator ESP_BLE_MESH_FRIEND_FRIENDSHIP_TERMINATE_EVT Friend Node terminates friendship event enumerator ESP_BLE_MESH_PROXY_CLIENT_RECV_ADV_PKT_EVT Proxy Client receives Network ID advertising packet event enumerator ESP_BLE_MESH_PROXY_CLIENT_RECV_ADV_PKT_EVT Proxy Client receives Network ID advertising packet event enumerator ESP_BLE_MESH_PROXY_CLIENT_CONNECTED_EVT Proxy Client establishes connection successfully event enumerator ESP_BLE_MESH_PROXY_CLIENT_CONNECTED_EVT Proxy Client establishes connection successfully event enumerator ESP_BLE_MESH_PROXY_CLIENT_DISCONNECTED_EVT Proxy Client terminates connection successfully event enumerator ESP_BLE_MESH_PROXY_CLIENT_DISCONNECTED_EVT Proxy Client terminates connection successfully event enumerator ESP_BLE_MESH_PROXY_CLIENT_RECV_FILTER_STATUS_EVT Proxy Client receives Proxy Filter Status event enumerator ESP_BLE_MESH_PROXY_CLIENT_RECV_FILTER_STATUS_EVT Proxy Client receives Proxy Filter Status event enumerator ESP_BLE_MESH_PROXY_CLIENT_CONNECT_COMP_EVT Proxy Client connect completion event enumerator ESP_BLE_MESH_PROXY_CLIENT_CONNECT_COMP_EVT Proxy Client connect completion event enumerator ESP_BLE_MESH_PROXY_CLIENT_DISCONNECT_COMP_EVT Proxy Client disconnect completion event enumerator ESP_BLE_MESH_PROXY_CLIENT_DISCONNECT_COMP_EVT Proxy Client disconnect completion event enumerator ESP_BLE_MESH_PROXY_CLIENT_SET_FILTER_TYPE_COMP_EVT Proxy Client set filter type completion event enumerator ESP_BLE_MESH_PROXY_CLIENT_SET_FILTER_TYPE_COMP_EVT Proxy Client set filter type completion event enumerator ESP_BLE_MESH_PROXY_CLIENT_ADD_FILTER_ADDR_COMP_EVT Proxy Client add filter address completion event enumerator ESP_BLE_MESH_PROXY_CLIENT_ADD_FILTER_ADDR_COMP_EVT Proxy Client add filter address completion event enumerator ESP_BLE_MESH_PROXY_CLIENT_REMOVE_FILTER_ADDR_COMP_EVT Proxy Client remove filter address completion event enumerator ESP_BLE_MESH_PROXY_CLIENT_REMOVE_FILTER_ADDR_COMP_EVT Proxy Client remove filter address completion event enumerator ESP_BLE_MESH_PROXY_CLIENT_DIRECTED_PROXY_SET_COMP_EVT Proxy Client directed proxy set completion event enumerator ESP_BLE_MESH_PROXY_CLIENT_DIRECTED_PROXY_SET_COMP_EVT Proxy Client directed proxy set completion event enumerator ESP_BLE_MESH_PROXY_SERVER_CONNECTED_EVT Proxy Server establishes connection successfully event enumerator ESP_BLE_MESH_PROXY_SERVER_CONNECTED_EVT Proxy Server establishes connection successfully event enumerator ESP_BLE_MESH_PROXY_SERVER_DISCONNECTED_EVT Proxy Server terminates connection successfully event enumerator ESP_BLE_MESH_PROXY_SERVER_DISCONNECTED_EVT Proxy Server terminates connection successfully event enumerator ESP_BLE_MESH_PROXY_CLIENT_SEND_SOLIC_PDU_COMP_EVT Proxy Client send Solicitation PDU completion event enumerator ESP_BLE_MESH_PROXY_CLIENT_SEND_SOLIC_PDU_COMP_EVT Proxy Client send Solicitation PDU completion event enumerator ESP_BLE_MESH_MODEL_SUBSCRIBE_GROUP_ADDR_COMP_EVT Local model subscribes group address completion event enumerator ESP_BLE_MESH_MODEL_SUBSCRIBE_GROUP_ADDR_COMP_EVT Local model subscribes group address completion event enumerator ESP_BLE_MESH_MODEL_UNSUBSCRIBE_GROUP_ADDR_COMP_EVT Local model unsubscribes group address completion event enumerator ESP_BLE_MESH_MODEL_UNSUBSCRIBE_GROUP_ADDR_COMP_EVT Local model unsubscribes group address completion event enumerator ESP_BLE_MESH_DEINIT_MESH_COMP_EVT De-initialize BLE Mesh stack completion event enumerator ESP_BLE_MESH_DEINIT_MESH_COMP_EVT De-initialize BLE Mesh stack completion event enumerator ESP_BLE_MESH_PROV_EVT_MAX enumerator ESP_BLE_MESH_PROV_EVT_MAX enumerator ESP_BLE_MESH_PROV_REGISTER_COMP_EVT enum [anonymous] BLE Mesh server models related definitions. This enum value is the flag of transition timer operation Values: enumerator ESP_BLE_MESH_SERVER_TRANS_TIMER_START enumerator ESP_BLE_MESH_SERVER_TRANS_TIMER_START enumerator ESP_BLE_MESH_SERVER_FLAG_MAX enumerator ESP_BLE_MESH_SERVER_FLAG_MAX enumerator ESP_BLE_MESH_SERVER_TRANS_TIMER_START enum esp_ble_mesh_server_state_type_t This enum value is the type of server model states Values: enumerator ESP_BLE_MESH_GENERIC_ONOFF_STATE enumerator ESP_BLE_MESH_GENERIC_ONOFF_STATE enumerator ESP_BLE_MESH_GENERIC_LEVEL_STATE enumerator ESP_BLE_MESH_GENERIC_LEVEL_STATE enumerator ESP_BLE_MESH_GENERIC_ONPOWERUP_STATE enumerator ESP_BLE_MESH_GENERIC_ONPOWERUP_STATE enumerator ESP_BLE_MESH_GENERIC_POWER_ACTUAL_STATE enumerator ESP_BLE_MESH_GENERIC_POWER_ACTUAL_STATE enumerator ESP_BLE_MESH_LIGHT_LIGHTNESS_ACTUAL_STATE enumerator ESP_BLE_MESH_LIGHT_LIGHTNESS_ACTUAL_STATE enumerator ESP_BLE_MESH_LIGHT_LIGHTNESS_LINEAR_STATE enumerator ESP_BLE_MESH_LIGHT_LIGHTNESS_LINEAR_STATE enumerator ESP_BLE_MESH_LIGHT_CTL_LIGHTNESS_STATE enumerator ESP_BLE_MESH_LIGHT_CTL_LIGHTNESS_STATE enumerator ESP_BLE_MESH_LIGHT_CTL_TEMP_DELTA_UV_STATE enumerator ESP_BLE_MESH_LIGHT_CTL_TEMP_DELTA_UV_STATE enumerator ESP_BLE_MESH_LIGHT_HSL_STATE enumerator ESP_BLE_MESH_LIGHT_HSL_STATE enumerator ESP_BLE_MESH_LIGHT_HSL_LIGHTNESS_STATE enumerator ESP_BLE_MESH_LIGHT_HSL_LIGHTNESS_STATE enumerator ESP_BLE_MESH_LIGHT_HSL_HUE_STATE enumerator ESP_BLE_MESH_LIGHT_HSL_HUE_STATE enumerator ESP_BLE_MESH_LIGHT_HSL_SATURATION_STATE enumerator ESP_BLE_MESH_LIGHT_HSL_SATURATION_STATE enumerator ESP_BLE_MESH_LIGHT_XYL_LIGHTNESS_STATE enumerator ESP_BLE_MESH_LIGHT_XYL_LIGHTNESS_STATE enumerator ESP_BLE_MESH_LIGHT_LC_LIGHT_ONOFF_STATE enumerator ESP_BLE_MESH_LIGHT_LC_LIGHT_ONOFF_STATE enumerator ESP_BLE_MESH_SERVER_MODEL_STATE_MAX enumerator ESP_BLE_MESH_SERVER_MODEL_STATE_MAX enumerator ESP_BLE_MESH_GENERIC_ONOFF_STATE enum esp_ble_mesh_model_cb_event_t Values: enumerator ESP_BLE_MESH_MODEL_OPERATION_EVT User-defined models receive messages from peer devices (e.g. get, set, status, etc) event enumerator ESP_BLE_MESH_MODEL_OPERATION_EVT User-defined models receive messages from peer devices (e.g. get, set, status, etc) event enumerator ESP_BLE_MESH_MODEL_SEND_COMP_EVT User-defined models send messages completion event enumerator ESP_BLE_MESH_MODEL_SEND_COMP_EVT User-defined models send messages completion event enumerator ESP_BLE_MESH_MODEL_PUBLISH_COMP_EVT User-defined models publish messages completion event enumerator ESP_BLE_MESH_MODEL_PUBLISH_COMP_EVT User-defined models publish messages completion event enumerator ESP_BLE_MESH_CLIENT_MODEL_RECV_PUBLISH_MSG_EVT User-defined client models receive publish messages event enumerator ESP_BLE_MESH_CLIENT_MODEL_RECV_PUBLISH_MSG_EVT User-defined client models receive publish messages event enumerator ESP_BLE_MESH_CLIENT_MODEL_SEND_TIMEOUT_EVT Timeout event for the user-defined client models that failed to receive response from peer server models enumerator ESP_BLE_MESH_CLIENT_MODEL_SEND_TIMEOUT_EVT Timeout event for the user-defined client models that failed to receive response from peer server models enumerator ESP_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT When a model is configured to publish messages periodically, this event will occur during every publish period enumerator ESP_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT When a model is configured to publish messages periodically, this event will occur during every publish period enumerator ESP_BLE_MESH_SERVER_MODEL_UPDATE_STATE_COMP_EVT Server models update state value completion event enumerator ESP_BLE_MESH_SERVER_MODEL_UPDATE_STATE_COMP_EVT Server models update state value completion event enumerator ESP_BLE_MESH_MODEL_EVT_MAX enumerator ESP_BLE_MESH_MODEL_EVT_MAX enumerator ESP_BLE_MESH_MODEL_OPERATION_EVT ESP-BLE-MESH Core API Reference This section contains ESP-BLE-MESH Core related APIs, which can be used to initialize ESP-BLE-MESH stack, provision, send/publish messages, etc. This API reference covers six components: ESP-BLE-MESH Stack Initialization Header File components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_common_api.h This header file can be included with: #include "esp_ble_mesh_common_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_init(esp_ble_mesh_prov_t *prov, esp_ble_mesh_comp_t *comp) Initialize BLE Mesh module. This API initializes provisioning capabilities and composition data information. Note After calling this API, the device needs to call esp_ble_mesh_prov_enable() to enable provisioning functionality again. Parameters prov -- [in] Pointer to the device provisioning capabilities. This pointer must remain valid during the lifetime of the BLE Mesh device. comp -- [in] Pointer to the device composition data information. This pointer must remain valid during the lifetime of the BLE Mesh device. prov -- [in] Pointer to the device provisioning capabilities. This pointer must remain valid during the lifetime of the BLE Mesh device. comp -- [in] Pointer to the device composition data information. This pointer must remain valid during the lifetime of the BLE Mesh device. prov -- [in] Pointer to the device provisioning capabilities. This pointer must remain valid during the lifetime of the BLE Mesh device. Returns ESP_OK on success or error code otherwise. Parameters prov -- [in] Pointer to the device provisioning capabilities. This pointer must remain valid during the lifetime of the BLE Mesh device. comp -- [in] Pointer to the device composition data information. This pointer must remain valid during the lifetime of the BLE Mesh device. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_deinit(esp_ble_mesh_deinit_param_t *param) De-initialize BLE Mesh module. Note This function shall be invoked after esp_ble_mesh_client_model_deinit(). Parameters param -- [in] Pointer to the structure of BLE Mesh deinit parameters. Returns ESP_OK on success or error code otherwise. Parameters param -- [in] Pointer to the structure of BLE Mesh deinit parameters. Returns ESP_OK on success or error code otherwise. Reading of Local Data Information Header File components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_local_data_operation_api.h This header file can be included with: #include "esp_ble_mesh_local_data_operation_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions int32_t esp_ble_mesh_get_model_publish_period(esp_ble_mesh_model_t *model) Get the model publish period, the unit is ms. Parameters model -- [in] Model instance pointer. Returns Publish period value on success, 0 or (negative) error code from errno.h on failure. Parameters model -- [in] Model instance pointer. Returns Publish period value on success, 0 or (negative) error code from errno.h on failure. uint16_t esp_ble_mesh_get_primary_element_address(void) Get the address of the primary element. Returns Address of the primary element on success, or ESP_BLE_MESH_ADDR_UNASSIGNED on failure which means the device has not been provisioned. Returns Address of the primary element on success, or ESP_BLE_MESH_ADDR_UNASSIGNED on failure which means the device has not been provisioned. uint16_t *esp_ble_mesh_is_model_subscribed_to_group(esp_ble_mesh_model_t *model, uint16_t group_addr) Check if the model has subscribed to the given group address. Note: E.g., once a status message is received and the destination address is a group address, the model uses this API to check if it is successfully subscribed to the given group address. Parameters model -- [in] Pointer to the model. group_addr -- [in] Group address. model -- [in] Pointer to the model. group_addr -- [in] Group address. model -- [in] Pointer to the model. Returns Pointer to the group address within the Subscription List of the model on success, or NULL on failure which means the model has not subscribed to the given group address. Note: With the pointer to the group address returned, you can reset the group address to 0x0000 in order to unsubscribe the model from the group. Parameters model -- [in] Pointer to the model. group_addr -- [in] Group address. Returns Pointer to the group address within the Subscription List of the model on success, or NULL on failure which means the model has not subscribed to the given group address. Note: With the pointer to the group address returned, you can reset the group address to 0x0000 in order to unsubscribe the model from the group. esp_ble_mesh_elem_t *esp_ble_mesh_find_element(uint16_t element_addr) Find the BLE Mesh element pointer via the element address. Parameters element_addr -- [in] Element address. Returns Pointer to the element on success, or NULL on failure. Parameters element_addr -- [in] Element address. Returns Pointer to the element on success, or NULL on failure. uint8_t esp_ble_mesh_get_element_count(void) Get the number of elements that have been registered. Returns Number of elements. Returns Number of elements. esp_ble_mesh_model_t *esp_ble_mesh_find_vendor_model(const esp_ble_mesh_elem_t *element, uint16_t company_id, uint16_t model_id) Find the Vendor specific model with the given element, the company ID and the Vendor Model ID. Parameters element -- [in] Element to which the model belongs. company_id -- [in] A 16-bit company identifier assigned by the Bluetooth SIG. model_id -- [in] A 16-bit vendor-assigned model identifier. element -- [in] Element to which the model belongs. company_id -- [in] A 16-bit company identifier assigned by the Bluetooth SIG. model_id -- [in] A 16-bit vendor-assigned model identifier. element -- [in] Element to which the model belongs. Returns Pointer to the Vendor Model on success, or NULL on failure which means the Vendor Model is not found. Parameters element -- [in] Element to which the model belongs. company_id -- [in] A 16-bit company identifier assigned by the Bluetooth SIG. model_id -- [in] A 16-bit vendor-assigned model identifier. Returns Pointer to the Vendor Model on success, or NULL on failure which means the Vendor Model is not found. esp_ble_mesh_model_t *esp_ble_mesh_find_sig_model(const esp_ble_mesh_elem_t *element, uint16_t model_id) Find the SIG model with the given element and Model id. Parameters element -- [in] Element to which the model belongs. model_id -- [in] SIG model identifier. element -- [in] Element to which the model belongs. model_id -- [in] SIG model identifier. element -- [in] Element to which the model belongs. Returns Pointer to the SIG Model on success, or NULL on failure which means the SIG Model is not found. Parameters element -- [in] Element to which the model belongs. model_id -- [in] SIG model identifier. Returns Pointer to the SIG Model on success, or NULL on failure which means the SIG Model is not found. const esp_ble_mesh_comp_t *esp_ble_mesh_get_composition_data(void) Get the Composition data which has been registered. Returns Pointer to the Composition data on success, or NULL on failure which means the Composition data is not initialized. Returns Pointer to the Composition data on success, or NULL on failure which means the Composition data is not initialized. esp_err_t esp_ble_mesh_model_subscribe_group_addr(uint16_t element_addr, uint16_t company_id, uint16_t model_id, uint16_t group_addr) A local model of node or Provisioner subscribes a group address. Note This function shall not be invoked before node is provisioned or Provisioner is enabled. Parameters element_addr -- [in] Unicast address of the element to which the model belongs. company_id -- [in] A 16-bit company identifier. model_id -- [in] A 16-bit model identifier. group_addr -- [in] The group address to be subscribed. element_addr -- [in] Unicast address of the element to which the model belongs. company_id -- [in] A 16-bit company identifier. model_id -- [in] A 16-bit model identifier. group_addr -- [in] The group address to be subscribed. element_addr -- [in] Unicast address of the element to which the model belongs. Returns ESP_OK on success or error code otherwise. Parameters element_addr -- [in] Unicast address of the element to which the model belongs. company_id -- [in] A 16-bit company identifier. model_id -- [in] A 16-bit model identifier. group_addr -- [in] The group address to be subscribed. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_model_unsubscribe_group_addr(uint16_t element_addr, uint16_t company_id, uint16_t model_id, uint16_t group_addr) A local model of node or Provisioner unsubscribes a group address. Note This function shall not be invoked before node is provisioned or Provisioner is enabled. Parameters element_addr -- [in] Unicast address of the element to which the model belongs. company_id -- [in] A 16-bit company identifier. model_id -- [in] A 16-bit model identifier. group_addr -- [in] The subscribed group address. element_addr -- [in] Unicast address of the element to which the model belongs. company_id -- [in] A 16-bit company identifier. model_id -- [in] A 16-bit model identifier. group_addr -- [in] The subscribed group address. element_addr -- [in] Unicast address of the element to which the model belongs. Returns ESP_OK on success or error code otherwise. Parameters element_addr -- [in] Unicast address of the element to which the model belongs. company_id -- [in] A 16-bit company identifier. model_id -- [in] A 16-bit model identifier. group_addr -- [in] The subscribed group address. Returns ESP_OK on success or error code otherwise. const uint8_t *esp_ble_mesh_node_get_local_net_key(uint16_t net_idx) This function is called by Node to get the local NetKey. Parameters net_idx -- [in] NetKey index. Returns NetKey on success, or NULL on failure. Parameters net_idx -- [in] NetKey index. Returns NetKey on success, or NULL on failure. const uint8_t *esp_ble_mesh_node_get_local_app_key(uint16_t app_idx) This function is called by Node to get the local AppKey. Parameters app_idx -- [in] AppKey index. Returns AppKey on success, or NULL on failure. Parameters app_idx -- [in] AppKey index. Returns AppKey on success, or NULL on failure. esp_err_t esp_ble_mesh_node_add_local_net_key(const uint8_t net_key[16], uint16_t net_idx) This function is called by Node to add a local NetKey. Note This function can only be called after the device is provisioned. Parameters net_key -- [in] NetKey to be added. net_idx -- [in] NetKey Index. net_key -- [in] NetKey to be added. net_idx -- [in] NetKey Index. net_key -- [in] NetKey to be added. Returns ESP_OK on success or error code otherwise. Parameters net_key -- [in] NetKey to be added. net_idx -- [in] NetKey Index. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_node_add_local_app_key(const uint8_t app_key[16], uint16_t net_idx, uint16_t app_idx) This function is called by Node to add a local AppKey. Note The net_idx must be an existing one. This function can only be called after the device is provisioned. Parameters app_key -- [in] AppKey to be added. net_idx -- [in] NetKey Index. app_idx -- [in] AppKey Index. app_key -- [in] AppKey to be added. net_idx -- [in] NetKey Index. app_idx -- [in] AppKey Index. app_key -- [in] AppKey to be added. Returns ESP_OK on success or error code otherwise. Parameters app_key -- [in] AppKey to be added. net_idx -- [in] NetKey Index. app_idx -- [in] AppKey Index. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_node_bind_app_key_to_local_model(uint16_t element_addr, uint16_t company_id, uint16_t model_id, uint16_t app_idx) This function is called by Node to bind AppKey to model locally. Note If going to bind app_key with local vendor model, the company_id shall be set to 0xFFFF. This function can only be called after the device is provisioned. Parameters element_addr -- [in] Node local element address company_id -- [in] Node local company id model_id -- [in] Node local model id app_idx -- [in] Node local appkey index element_addr -- [in] Node local element address company_id -- [in] Node local company id model_id -- [in] Node local model id app_idx -- [in] Node local appkey index element_addr -- [in] Node local element address Returns ESP_OK on success or error code otherwise. Parameters element_addr -- [in] Node local element address company_id -- [in] Node local company id model_id -- [in] Node local model id app_idx -- [in] Node local appkey index Returns ESP_OK on success or error code otherwise. Low Power Operation (Updating) Header File components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_low_power_api.h This header file can be included with: #include "esp_ble_mesh_low_power_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_lpn_enable(void) Enable BLE Mesh device LPN functionality. Note This API enables LPN functionality. Once called, the proper Friend Request will be sent. Returns ESP_OK on success or error code otherwise. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_lpn_disable(bool force) Disable BLE Mesh device LPN functionality. Parameters force -- [in] when disabling LPN functionality, use this flag to indicate whether directly clear corresponding information or just send friend clear to disable it if friendship has already been established. Returns ESP_OK on success or error code otherwise. Parameters force -- [in] when disabling LPN functionality, use this flag to indicate whether directly clear corresponding information or just send friend clear to disable it if friendship has already been established. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_lpn_poll(void) LPN tries to poll messages from the Friend Node. Note The Friend Poll message is sent by a Low Power node to ask the Friend node to send a message that it has stored for the Low Power node. Users can call this API to send Friend Poll message manually. If this API is not invoked, the bottom layer of the Low Power node will send Friend Poll before the PollTimeout timer expires. If the corresponding Friend Update is received and MD is set to 0, which means there are no messages for the Low Power node, then the Low Power node will stop scanning. Returns ESP_OK on success or error code otherwise. Returns ESP_OK on success or error code otherwise. Send/Publish Messages, Add Local AppKey, Etc. Header File components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_networking_api.h This header file can be included with: #include "esp_ble_mesh_networking_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_custom_model_callback(esp_ble_mesh_model_cb_t callback) Register BLE Mesh callback for user-defined models' operations. This callback can report the following events generated for the user-defined models: Call back the messages received by user-defined client and server models to the application layer; If users call esp_ble_mesh_server/client_model_send, this callback notifies the application layer of the send_complete event; If user-defined client model sends a message that requires response, and the response message is received after the timer expires, the response message will be reported to the application layer as published by a peer device; If the user-defined client model fails to receive the response message during a specified period of time, a timeout event will be reported to the application layer. Call back the messages received by user-defined client and server models to the application layer; If users call esp_ble_mesh_server/client_model_send, this callback notifies the application layer of the send_complete event; If user-defined client model sends a message that requires response, and the response message is received after the timer expires, the response message will be reported to the application layer as published by a peer device; If the user-defined client model fails to receive the response message during a specified period of time, a timeout event will be reported to the application layer. Note The client models (i.e. Config Client model, Health Client model, Generic Client models, Sensor Client model, Scene Client model and Lighting Client models) that have been realized internally have their specific register functions. For example, esp_ble_mesh_register_config_client_callback is the register function for Config Client Model. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Call back the messages received by user-defined client and server models to the application layer; esp_err_t esp_ble_mesh_model_msg_opcode_init(uint8_t *data, uint32_t opcode) Add the message opcode to the beginning of the model message before sending or publishing the model message. Note This API is only used to set the opcode of the message. Parameters data -- [in] Pointer to the message data. opcode -- [in] The message opcode. data -- [in] Pointer to the message data. opcode -- [in] The message opcode. data -- [in] Pointer to the message data. Returns ESP_OK on success or error code otherwise. Parameters data -- [in] Pointer to the message data. opcode -- [in] The message opcode. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_client_model_init(esp_ble_mesh_model_t *model) Initialize the user-defined client model. All user-defined client models shall call this function to initialize the client model internal data. Node: Before calling this API, the op_pair_size and op_pair variables within the user_data(defined using esp_ble_mesh_client_t_) of the client model need to be initialized. Parameters model -- [in] BLE Mesh Client model to which the message belongs. Returns ESP_OK on success or error code otherwise. Parameters model -- [in] BLE Mesh Client model to which the message belongs. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_client_model_deinit(esp_ble_mesh_model_t *model) De-initialize the user-defined client model. Note This function shall be invoked before esp_ble_mesh_deinit() is called. Parameters model -- [in] Pointer of the Client model. Returns ESP_OK on success or error code otherwise. Parameters model -- [in] Pointer of the Client model. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_server_model_send_msg(esp_ble_mesh_model_t *model, esp_ble_mesh_msg_ctx_t *ctx, uint32_t opcode, uint16_t length, uint8_t *data) Send server model messages(such as server model status messages). Parameters model -- [in] BLE Mesh Server Model to which the message belongs. ctx -- [in] Message context, includes keys, TTL, etc. opcode -- [in] Message opcode. length -- [in] Message length (exclude the message opcode). data -- [in] Parameters of Access Payload (exclude the message opcode) to be sent. model -- [in] BLE Mesh Server Model to which the message belongs. ctx -- [in] Message context, includes keys, TTL, etc. opcode -- [in] Message opcode. length -- [in] Message length (exclude the message opcode). data -- [in] Parameters of Access Payload (exclude the message opcode) to be sent. model -- [in] BLE Mesh Server Model to which the message belongs. Returns ESP_OK on success or error code otherwise. Parameters model -- [in] BLE Mesh Server Model to which the message belongs. ctx -- [in] Message context, includes keys, TTL, etc. opcode -- [in] Message opcode. length -- [in] Message length (exclude the message opcode). data -- [in] Parameters of Access Payload (exclude the message opcode) to be sent. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_client_model_send_msg(esp_ble_mesh_model_t *model, esp_ble_mesh_msg_ctx_t *ctx, uint32_t opcode, uint16_t length, uint8_t *data, int32_t msg_timeout, bool need_rsp, esp_ble_mesh_dev_role_t device_role) Send client model message (such as model get, set, etc). Parameters model -- [in] BLE Mesh Client Model to which the message belongs. ctx -- [in] Message context, includes keys, TTL, etc. opcode -- [in] Message opcode. length -- [in] Message length (exclude the message opcode). data -- [in] Parameters of the Access Payload (exclude the message opcode) to be sent. msg_timeout -- [in] Time to get response to the message (in milliseconds). need_rsp -- [in] TRUE if the opcode requires the peer device to reply, FALSE otherwise. device_role -- [in] Role of the device (Node/Provisioner) that sends the message. model -- [in] BLE Mesh Client Model to which the message belongs. ctx -- [in] Message context, includes keys, TTL, etc. opcode -- [in] Message opcode. length -- [in] Message length (exclude the message opcode). data -- [in] Parameters of the Access Payload (exclude the message opcode) to be sent. msg_timeout -- [in] Time to get response to the message (in milliseconds). need_rsp -- [in] TRUE if the opcode requires the peer device to reply, FALSE otherwise. device_role -- [in] Role of the device (Node/Provisioner) that sends the message. model -- [in] BLE Mesh Client Model to which the message belongs. Returns ESP_OK on success or error code otherwise. Parameters model -- [in] BLE Mesh Client Model to which the message belongs. ctx -- [in] Message context, includes keys, TTL, etc. opcode -- [in] Message opcode. length -- [in] Message length (exclude the message opcode). data -- [in] Parameters of the Access Payload (exclude the message opcode) to be sent. msg_timeout -- [in] Time to get response to the message (in milliseconds). need_rsp -- [in] TRUE if the opcode requires the peer device to reply, FALSE otherwise. device_role -- [in] Role of the device (Node/Provisioner) that sends the message. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_model_publish(esp_ble_mesh_model_t *model, uint32_t opcode, uint16_t length, uint8_t *data, esp_ble_mesh_dev_role_t device_role) Send a model publication message. Note Before calling this function, the user needs to ensure that the model publication message (esp_ble_mesh_model_pub_t::msg) contains a valid message to be sent. And if users want to update the publishing message, this API should be called in ESP_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT with the message updated. Parameters model -- [in] Mesh (client) Model publishing the message. opcode -- [in] Message opcode. length -- [in] Message length (exclude the message opcode). data -- [in] Parameters of the Access Payload (exclude the message opcode) to be sent. device_role -- [in] Role of the device (node/provisioner) publishing the message of the type esp_ble_mesh_dev_role_t. model -- [in] Mesh (client) Model publishing the message. opcode -- [in] Message opcode. length -- [in] Message length (exclude the message opcode). data -- [in] Parameters of the Access Payload (exclude the message opcode) to be sent. device_role -- [in] Role of the device (node/provisioner) publishing the message of the type esp_ble_mesh_dev_role_t. model -- [in] Mesh (client) Model publishing the message. Returns ESP_OK on success or error code otherwise. Parameters model -- [in] Mesh (client) Model publishing the message. opcode -- [in] Message opcode. length -- [in] Message length (exclude the message opcode). data -- [in] Parameters of the Access Payload (exclude the message opcode) to be sent. device_role -- [in] Role of the device (node/provisioner) publishing the message of the type esp_ble_mesh_dev_role_t. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_server_model_update_state(esp_ble_mesh_model_t *model, esp_ble_mesh_server_state_type_t type, esp_ble_mesh_server_state_value_t *value) Update a server model state value. If the model publication state is set properly (e.g. publish address is set to a valid address), it will publish corresponding status message. Note Currently this API is used to update bound state value, not for all server model states. Parameters model -- [in] Server model which is going to update the state. type -- [in] Server model state type. value -- [in] Server model state value. model -- [in] Server model which is going to update the state. type -- [in] Server model state type. value -- [in] Server model state value. model -- [in] Server model which is going to update the state. Returns ESP_OK on success or error code otherwise. Parameters model -- [in] Server model which is going to update the state. type -- [in] Server model state type. value -- [in] Server model state value. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_node_local_reset(void) Reset the provisioning procedure of the local BLE Mesh node. Note All provisioning information in this node will be deleted and the node needs to be re-provisioned. The API function esp_ble_mesh_node_prov_enable() needs to be called to start a new provisioning procedure. Returns ESP_OK on success or error code otherwise. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_set_node_name(uint16_t index, const char *name) This function is called to set the node (provisioned device) name. Note index is obtained from the parameters of ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT. Parameters index -- [in] Index of the node in the node queue. name -- [in] Name (end by '\0') to be set for the node. index -- [in] Index of the node in the node queue. name -- [in] Name (end by '\0') to be set for the node. index -- [in] Index of the node in the node queue. Returns ESP_OK on success or error code otherwise. Parameters index -- [in] Index of the node in the node queue. name -- [in] Name (end by '\0') to be set for the node. Returns ESP_OK on success or error code otherwise. const char *esp_ble_mesh_provisioner_get_node_name(uint16_t index) This function is called to get the node (provisioned device) name. Note index is obtained from the parameters of ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT. Parameters index -- [in] Index of the node in the node queue. Returns Node name on success, or NULL on failure. Parameters index -- [in] Index of the node in the node queue. Returns Node name on success, or NULL on failure. uint16_t esp_ble_mesh_provisioner_get_node_index(const char *name) This function is called to get the node (provisioned device) index. Parameters name -- [in] Name of the node (end by '\0'). Returns Node index on success, or an invalid value (0xFFFF) on failure. Parameters name -- [in] Name of the node (end by '\0'). Returns Node index on success, or an invalid value (0xFFFF) on failure. esp_err_t esp_ble_mesh_provisioner_store_node_comp_data(uint16_t unicast_addr, uint8_t *data, uint16_t length) This function is called to store the Composition Data of the node. Parameters unicast_addr -- [in] Element address of the node data -- [in] Pointer of Composition Data length -- [in] Length of Composition Data unicast_addr -- [in] Element address of the node data -- [in] Pointer of Composition Data length -- [in] Length of Composition Data unicast_addr -- [in] Element address of the node Returns ESP_OK on success or error code otherwise. Parameters unicast_addr -- [in] Element address of the node data -- [in] Pointer of Composition Data length -- [in] Length of Composition Data Returns ESP_OK on success or error code otherwise. esp_ble_mesh_node_t *esp_ble_mesh_provisioner_get_node_with_uuid(const uint8_t uuid[16]) This function is called to get the provisioned node information with the node device uuid. Parameters uuid -- [in] Device UUID of the node Returns Pointer of the node info struct or NULL on failure. Parameters uuid -- [in] Device UUID of the node Returns Pointer of the node info struct or NULL on failure. esp_ble_mesh_node_t *esp_ble_mesh_provisioner_get_node_with_addr(uint16_t unicast_addr) This function is called to get the provisioned node information with the node unicast address. Parameters unicast_addr -- [in] Unicast address of the node Returns Pointer of the node info struct or NULL on failure. Parameters unicast_addr -- [in] Unicast address of the node Returns Pointer of the node info struct or NULL on failure. esp_ble_mesh_node_t *esp_ble_mesh_provisioner_get_node_with_name(const char *name) This function is called to get the provisioned node information with the node name. Parameters name -- [in] Name of the node (end by '\0'). Returns Pointer of the node info struct or NULL on failure. Parameters name -- [in] Name of the node (end by '\0'). Returns Pointer of the node info struct or NULL on failure. uint16_t esp_ble_mesh_provisioner_get_prov_node_count(void) This function is called by Provisioner to get provisioned node count. Returns Number of the provisioned nodes. Returns Number of the provisioned nodes. const esp_ble_mesh_node_t **esp_ble_mesh_provisioner_get_node_table_entry(void) This function is called by Provisioner to get the entry of the node table. Note After invoking the function to get the entry of nodes, users can use the "for" loop combined with the macro CONFIG_BLE_MESH_MAX_PROV_NODES to get each node's information. Before trying to read the node's information, users need to check if the node exists, i.e. if the *(esp_ble_mesh_node_t **node) is NULL. For example: ``` const esp_ble_mesh_node_t **entry = esp_ble_mesh_provisioner_get_node_table_entry(); for (int i = 0; i < CONFIG_BLE_MESH_MAX_PROV_NODES; i++) { const esp_ble_mesh_node_t *node = entry[i]; if (node) { ...... } } ``` Returns Pointer to the start of the node table. Returns Pointer to the start of the node table. esp_err_t esp_ble_mesh_provisioner_delete_node_with_uuid(const uint8_t uuid[16]) This function is called to delete the provisioned node information with the node device uuid. Parameters uuid -- [in] Device UUID of the node Returns ESP_OK on success or error code otherwise. Parameters uuid -- [in] Device UUID of the node Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_delete_node_with_addr(uint16_t unicast_addr) This function is called to delete the provisioned node information with the node unicast address. Parameters unicast_addr -- [in] Unicast address of the node Returns ESP_OK on success or error code otherwise. Parameters unicast_addr -- [in] Unicast address of the node Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_add_local_app_key(const uint8_t app_key[16], uint16_t net_idx, uint16_t app_idx) This function is called to add a local AppKey for Provisioner. Note app_key: If set to NULL, app_key will be generated internally. net_idx: Should be an existing one. app_idx: If it is going to be generated internally, it should be set to 0xFFFF, and the new app_idx will be reported via an event. Parameters app_key -- [in] The app key to be set for the local BLE Mesh stack. net_idx -- [in] The network key index. app_idx -- [in] The app key index. app_key -- [in] The app key to be set for the local BLE Mesh stack. net_idx -- [in] The network key index. app_idx -- [in] The app key index. app_key -- [in] The app key to be set for the local BLE Mesh stack. Returns ESP_OK on success or error code otherwise. Parameters app_key -- [in] The app key to be set for the local BLE Mesh stack. net_idx -- [in] The network key index. app_idx -- [in] The app key index. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_update_local_app_key(const uint8_t app_key[16], uint16_t net_idx, uint16_t app_idx) This function is used to update a local AppKey for Provisioner. Parameters app_key -- [in] Value of the AppKey. net_idx -- [in] Corresponding NetKey Index. app_idx -- [in] The AppKey Index app_key -- [in] Value of the AppKey. net_idx -- [in] Corresponding NetKey Index. app_idx -- [in] The AppKey Index app_key -- [in] Value of the AppKey. Returns ESP_OK on success or error code otherwise. Parameters app_key -- [in] Value of the AppKey. net_idx -- [in] Corresponding NetKey Index. app_idx -- [in] The AppKey Index Returns ESP_OK on success or error code otherwise. const uint8_t *esp_ble_mesh_provisioner_get_local_app_key(uint16_t net_idx, uint16_t app_idx) This function is called by Provisioner to get the local app key value. Parameters net_idx -- [in] Network key index. app_idx -- [in] Application key index. net_idx -- [in] Network key index. app_idx -- [in] Application key index. net_idx -- [in] Network key index. Returns App key on success, or NULL on failure. Parameters net_idx -- [in] Network key index. app_idx -- [in] Application key index. Returns App key on success, or NULL on failure. esp_err_t esp_ble_mesh_provisioner_bind_app_key_to_local_model(uint16_t element_addr, uint16_t app_idx, uint16_t model_id, uint16_t company_id) This function is called by Provisioner to bind own model with proper app key. Note company_id: If going to bind app_key with local vendor model, company_id should be set to 0xFFFF. Parameters element_addr -- [in] Provisioner local element address app_idx -- [in] Provisioner local appkey index model_id -- [in] Provisioner local model id company_id -- [in] Provisioner local company id element_addr -- [in] Provisioner local element address app_idx -- [in] Provisioner local appkey index model_id -- [in] Provisioner local model id company_id -- [in] Provisioner local company id element_addr -- [in] Provisioner local element address Returns ESP_OK on success or error code otherwise. Parameters element_addr -- [in] Provisioner local element address app_idx -- [in] Provisioner local appkey index model_id -- [in] Provisioner local model id company_id -- [in] Provisioner local company id Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_add_local_net_key(const uint8_t net_key[16], uint16_t net_idx) This function is called by Provisioner to add local network key. Note net_key: If set to NULL, net_key will be generated internally. net_idx: If it is going to be generated internally, it should be set to 0xFFFF, and the new net_idx will be reported via an event. Parameters net_key -- [in] The network key to be added to the Provisioner local BLE Mesh stack. net_idx -- [in] The network key index. net_key -- [in] The network key to be added to the Provisioner local BLE Mesh stack. net_idx -- [in] The network key index. net_key -- [in] The network key to be added to the Provisioner local BLE Mesh stack. Returns ESP_OK on success or error code otherwise. Parameters net_key -- [in] The network key to be added to the Provisioner local BLE Mesh stack. net_idx -- [in] The network key index. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_update_local_net_key(const uint8_t net_key[16], uint16_t net_idx) This function is called by Provisioner to update a local network key. Parameters net_key -- [in] Value of the NetKey. net_idx -- [in] The NetKey Index. net_key -- [in] Value of the NetKey. net_idx -- [in] The NetKey Index. net_key -- [in] Value of the NetKey. Returns ESP_OK on success or error code otherwise. Parameters net_key -- [in] Value of the NetKey. net_idx -- [in] The NetKey Index. Returns ESP_OK on success or error code otherwise. const uint8_t *esp_ble_mesh_provisioner_get_local_net_key(uint16_t net_idx) This function is called by Provisioner to get the local network key value. Parameters net_idx -- [in] Network key index. Returns Network key on success, or NULL on failure. Parameters net_idx -- [in] Network key index. Returns Network key on success, or NULL on failure. esp_err_t esp_ble_mesh_provisioner_recv_heartbeat(bool enable) This function is called by Provisioner to enable or disable receiving heartbeat messages. Note If enabling receiving heartbeat message successfully, the filter will be an empty rejectlist by default, which means all heartbeat messages received by the Provisioner will be reported to the application layer. Parameters enable -- [in] Enable or disable receiving heartbeat messages. Returns ESP_OK on success or error code otherwise. Parameters enable -- [in] Enable or disable receiving heartbeat messages. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_set_heartbeat_filter_type(uint8_t type) This function is called by Provisioner to set the heartbeat filter type. Note 1. If the filter type is not the same with the current value, then all the filter entries will be cleaned. If the previous type is rejectlist, and changed to acceptlist, then the filter will be an empty acceptlist, which means no heartbeat messages will be reported. Users need to add SRC or DST into the filter entry, then heartbeat messages from the SRC or to the DST will be reported. If the previous type is rejectlist, and changed to acceptlist, then the filter will be an empty acceptlist, which means no heartbeat messages will be reported. Users need to add SRC or DST into the filter entry, then heartbeat messages from the SRC or to the DST will be reported. Parameters type -- [in] Heartbeat filter type (acceptlist or rejectlist). Returns ESP_OK on success or error code otherwise. Parameters type -- [in] Heartbeat filter type (acceptlist or rejectlist). Returns ESP_OK on success or error code otherwise. If the previous type is rejectlist, and changed to acceptlist, then the filter will be an empty acceptlist, which means no heartbeat messages will be reported. Users need to add SRC or DST into the filter entry, then heartbeat messages from the SRC or to the DST will be reported. esp_err_t esp_ble_mesh_provisioner_set_heartbeat_filter_info(uint8_t op, esp_ble_mesh_heartbeat_filter_info_t *info) This function is called by Provisioner to add or remove a heartbeat filter entry. If the operation is "REMOVE", the "hb_src" can be set to the SRC (can only be a unicast address) of heartbeat messages, and the "hb_dst" can be set to the DST (unicast address or group address), at least one of them needs to be set. The filter entry with the same SRC or DST will be removed. The filter entry with the same SRC or DST will be removed. The filter entry with the same SRC or DST will be removed. If the operation is "REMOVE", the "hb_src" can be set to the SRC (can only be a unicast address) of heartbeat messages, and the "hb_dst" can be set to the DST (unicast address or group address), at least one of them needs to be set. The filter entry with the same SRC or DST will be removed. Note 1. If the operation is "ADD", the "hb_src" can be set to the SRC (can only be a unicast address) of heartbeat messages, and the "hb_dst" can be set to the DST (unicast address or group address), at least one of them needs to be set. If only one of them is set, the filter entry will only use the configured SRC or DST to filter heartbeat messages. If both of them are set, the SRC and DST will both be used to decide if a heartbeat message will be handled. If SRC or DST already exists in some filter entry, then the corresponding entry will be cleaned firstly, then a new entry will be allocated to store the information. If only one of them is set, the filter entry will only use the configured SRC or DST to filter heartbeat messages. If both of them are set, the SRC and DST will both be used to decide if a heartbeat message will be handled. If SRC or DST already exists in some filter entry, then the corresponding entry will be cleaned firstly, then a new entry will be allocated to store the information. Parameters op -- [in] Add or REMOVE info -- [in] Heartbeat filter entry information, including: hb_src - Heartbeat source address; hb_dst - Heartbeat destination address; op -- [in] Add or REMOVE info -- [in] Heartbeat filter entry information, including: hb_src - Heartbeat source address; hb_dst - Heartbeat destination address; op -- [in] Add or REMOVE Returns ESP_OK on success or error code otherwise. Parameters op -- [in] Add or REMOVE info -- [in] Heartbeat filter entry information, including: hb_src - Heartbeat source address; hb_dst - Heartbeat destination address; Returns ESP_OK on success or error code otherwise. If the operation is "REMOVE", the "hb_src" can be set to the SRC (can only be a unicast address) of heartbeat messages, and the "hb_dst" can be set to the DST (unicast address or group address), at least one of them needs to be set. The filter entry with the same SRC or DST will be removed. esp_err_t esp_ble_mesh_provisioner_direct_erase_settings(void) This function is called by Provisioner to directly erase the mesh information from nvs namespace. Note This function can be invoked when the mesh stack is not initialized or has been de-initialized. Returns ESP_OK on success or error code otherwise. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_open_settings_with_index(uint8_t index) This function is called by Provisioner to open a nvs namespace for storing mesh information. Note Before open another nvs namespace, the previously opened nvs namespace must be closed firstly. Parameters index -- [in] Settings index. Returns ESP_OK on success or error code otherwise. Parameters index -- [in] Settings index. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_open_settings_with_uid(const char *uid) This function is called by Provisioner to open a nvs namespace for storing mesh information. Note Before open another nvs namespace, the previously opened nvs namespace must be closed firstly. Parameters uid -- [in] Settings user id. Returns ESP_OK on success or error code otherwise. Parameters uid -- [in] Settings user id. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_close_settings_with_index(uint8_t index, bool erase) This function is called by Provisioner to close a nvs namespace which is opened previously for storing mesh information. Note 1. Before closing the nvs namespace, it must be open. When the function is invoked, the Provisioner functionality will be disabled firstly, and: a) If the "erase" flag is set to false, the mesh information will be cleaned (e.g. removing NetKey, AppKey, nodes, etc) from the mesh stack. b) If the "erase" flag is set to true, the mesh information stored in the nvs namespace will also be erased besides been cleaned from the mesh stack. If Provisioner tries to work properly again, we can invoke the open function to open a new nvs namespace or a previously added one, and restore the mesh information from it if not erased. The working process shall be as following: a) Open settings A b) Start to provision and control nodes c) Close settings A d) Open settings B e) Start to provision and control other nodes f) Close settings B g) ...... When the function is invoked, the Provisioner functionality will be disabled firstly, and: a) If the "erase" flag is set to false, the mesh information will be cleaned (e.g. removing NetKey, AppKey, nodes, etc) from the mesh stack. b) If the "erase" flag is set to true, the mesh information stored in the nvs namespace will also be erased besides been cleaned from the mesh stack. If Provisioner tries to work properly again, we can invoke the open function to open a new nvs namespace or a previously added one, and restore the mesh information from it if not erased. The working process shall be as following: a) Open settings A b) Start to provision and control nodes c) Close settings A d) Open settings B e) Start to provision and control other nodes f) Close settings B g) ...... Parameters index -- [in] Settings index. erase -- [in] Indicate if erasing mesh information. index -- [in] Settings index. erase -- [in] Indicate if erasing mesh information. index -- [in] Settings index. Returns ESP_OK on success or error code otherwise. Parameters index -- [in] Settings index. erase -- [in] Indicate if erasing mesh information. Returns ESP_OK on success or error code otherwise. When the function is invoked, the Provisioner functionality will be disabled firstly, and: a) If the "erase" flag is set to false, the mesh information will be cleaned (e.g. removing NetKey, AppKey, nodes, etc) from the mesh stack. b) If the "erase" flag is set to true, the mesh information stored in the nvs namespace will also be erased besides been cleaned from the mesh stack. esp_err_t esp_ble_mesh_provisioner_close_settings_with_uid(const char *uid, bool erase) This function is called by Provisioner to close a nvs namespace which is opened previously for storing mesh information. Note 1. Before closing the nvs namespace, it must be open. When the function is invoked, the Provisioner functionality will be disabled firstly, and: a) If the "erase" flag is set to false, the mesh information will be cleaned (e.g. removing NetKey, AppKey, nodes, etc) from the mesh stack. b) If the "erase" flag is set to true, the mesh information stored in the nvs namespace will also be erased besides been cleaned from the mesh stack. If Provisioner tries to work properly again, we can invoke the open function to open a new nvs namespace or a previously added one, and restore the mesh information from it if not erased. The working process shall be as following: a) Open settings A b) Start to provision and control nodes c) Close settings A d) Open settings B e) Start to provision and control other nodes f) Close settings B g) ...... When the function is invoked, the Provisioner functionality will be disabled firstly, and: a) If the "erase" flag is set to false, the mesh information will be cleaned (e.g. removing NetKey, AppKey, nodes, etc) from the mesh stack. b) If the "erase" flag is set to true, the mesh information stored in the nvs namespace will also be erased besides been cleaned from the mesh stack. If Provisioner tries to work properly again, we can invoke the open function to open a new nvs namespace or a previously added one, and restore the mesh information from it if not erased. The working process shall be as following: a) Open settings A b) Start to provision and control nodes c) Close settings A d) Open settings B e) Start to provision and control other nodes f) Close settings B g) ...... Parameters uid -- [in] Settings user id. erase -- [in] Indicate if erasing mesh information. uid -- [in] Settings user id. erase -- [in] Indicate if erasing mesh information. uid -- [in] Settings user id. Returns ESP_OK on success or error code otherwise. Parameters uid -- [in] Settings user id. erase -- [in] Indicate if erasing mesh information. Returns ESP_OK on success or error code otherwise. When the function is invoked, the Provisioner functionality will be disabled firstly, and: a) If the "erase" flag is set to false, the mesh information will be cleaned (e.g. removing NetKey, AppKey, nodes, etc) from the mesh stack. b) If the "erase" flag is set to true, the mesh information stored in the nvs namespace will also be erased besides been cleaned from the mesh stack. esp_err_t esp_ble_mesh_provisioner_delete_settings_with_index(uint8_t index) This function is called by Provisioner to erase the mesh information and settings user id from a nvs namespace. Note When this function is called, the nvs namespace must not be open. This function is used to erase the mesh information and settings user id which are not used currently. Parameters index -- [in] Settings index. Returns ESP_OK on success or error code otherwise. Parameters index -- [in] Settings index. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_delete_settings_with_uid(const char *uid) This function is called by Provisioner to erase the mesh information and settings user id from a nvs namespace. Note When this function is called, the nvs namespace must not be open. This function is used to erase the mesh information and settings user id which are not used currently. Parameters uid -- [in] Settings user id. Returns ESP_OK on success or error code otherwise. Parameters uid -- [in] Settings user id. Returns ESP_OK on success or error code otherwise. const char *esp_ble_mesh_provisioner_get_settings_uid(uint8_t index) This function is called by Provisioner to get settings user id. Parameters index -- [in] Settings index. Returns Setting user id on success or NULL on failure. Parameters index -- [in] Settings index. Returns Setting user id on success or NULL on failure. uint8_t esp_ble_mesh_provisioner_get_settings_index(const char *uid) This function is called by Provisioner to get settings index. Parameters uid -- [in] Settings user id. Returns Settings index. Parameters uid -- [in] Settings user id. Returns Settings index. uint8_t esp_ble_mesh_provisioner_get_free_settings_count(void) This function is called by Provisioner to get the number of free settings user id. Returns Number of free settings user id. Returns Number of free settings user id. const uint8_t *esp_ble_mesh_get_fast_prov_app_key(uint16_t net_idx, uint16_t app_idx) This function is called to get fast provisioning application key. Parameters net_idx -- [in] Network key index. app_idx -- [in] Application key index. net_idx -- [in] Network key index. app_idx -- [in] Application key index. net_idx -- [in] Network key index. Returns Application key on success, or NULL on failure. Parameters net_idx -- [in] Network key index. app_idx -- [in] Application key index. Returns Application key on success, or NULL on failure. Type Definitions typedef void (*esp_ble_mesh_model_cb_t)(esp_ble_mesh_model_cb_event_t event, esp_ble_mesh_model_cb_param_t *param) : event, event code of user-defined model events; param, parameters of user-defined model events ESP-BLE-MESH Node/Provisioner Provisioning Header File components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_provisioning_api.h This header file can be included with: #include "esp_ble_mesh_provisioning_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_prov_callback(esp_ble_mesh_prov_cb_t callback) Register BLE Mesh provisioning callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. bool esp_ble_mesh_node_is_provisioned(void) Check if a device has been provisioned. Returns TRUE if the device is provisioned, FALSE if the device is unprovisioned. Returns TRUE if the device is provisioned, FALSE if the device is unprovisioned. esp_err_t esp_ble_mesh_node_prov_enable(esp_ble_mesh_prov_bearer_t bearers) Enable specific provisioning bearers to get the device ready for provisioning. Note PB-ADV: send unprovisioned device beacon. PB-GATT: send connectable advertising packets. Parameters bearers -- Bit-wise OR of provisioning bearers. Returns ESP_OK on success or error code otherwise. Parameters bearers -- Bit-wise OR of provisioning bearers. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_node_prov_disable(esp_ble_mesh_prov_bearer_t bearers) Disable specific provisioning bearers to make a device inaccessible for provisioning. Parameters bearers -- Bit-wise OR of provisioning bearers. Returns ESP_OK on success or error code otherwise. Parameters bearers -- Bit-wise OR of provisioning bearers. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_node_set_oob_pub_key(uint8_t pub_key_x[32], uint8_t pub_key_y[32], uint8_t private_key[32]) Unprovisioned device set own oob public key & private key pair. Note In order to avoid suffering brute-forcing attack (CVE-2020-26559). The Bluetooth SIG recommends that potentially vulnerable mesh provisioners use an out-of-band mechanism to exchange the public keys. So as an unprovisioned device, it should use this function to input the Public Key exchanged through the out-of-band mechanism. Parameters pub_key_x -- [in] Unprovisioned device's Public Key X pub_key_y -- [in] Unprovisioned device's Public Key Y private_key -- [in] Unprovisioned device's Private Key pub_key_x -- [in] Unprovisioned device's Public Key X pub_key_y -- [in] Unprovisioned device's Public Key Y private_key -- [in] Unprovisioned device's Private Key pub_key_x -- [in] Unprovisioned device's Public Key X Returns ESP_OK on success or error code otherwise. Parameters pub_key_x -- [in] Unprovisioned device's Public Key X pub_key_y -- [in] Unprovisioned device's Public Key Y private_key -- [in] Unprovisioned device's Private Key Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_node_input_number(uint32_t number) Provide provisioning input OOB number. Note This is intended to be called if the user has received ESP_BLE_MESH_NODE_PROV_INPUT_EVT with ESP_BLE_MESH_ENTER_NUMBER as the action. Parameters number -- [in] Number input by device. Returns ESP_OK on success or error code otherwise. Parameters number -- [in] Number input by device. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_node_input_string(const char *string) Provide provisioning input OOB string. Note This is intended to be called if the user has received ESP_BLE_MESH_NODE_PROV_INPUT_EVT with ESP_BLE_MESH_ENTER_STRING as the action. Parameters string -- [in] String input by device. Returns ESP_OK on success or error code otherwise. Parameters string -- [in] String input by device. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_set_unprovisioned_device_name(const char *name) Using this function, an unprovisioned device can set its own device name, which will be broadcasted in its advertising data. Note This API applicable to PB-GATT mode only by setting the name to the scan response data, it doesn't apply to PB-ADV mode. Parameters name -- [in] Unprovisioned device name Returns ESP_OK on success or error code otherwise. Parameters name -- [in] Unprovisioned device name Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_read_oob_pub_key(uint8_t link_idx, uint8_t pub_key_x[32], uint8_t pub_key_y[32]) Provisioner inputs unprovisioned device's oob public key. Note In order to avoid suffering brute-forcing attack (CVE-2020-26559). The Bluetooth SIG recommends that potentially vulnerable mesh provisioners use an out-of-band mechanism to exchange the public keys. Parameters link_idx -- [in] The provisioning link index pub_key_x -- [in] Unprovisioned device's Public Key X pub_key_y -- [in] Unprovisioned device's Public Key Y link_idx -- [in] The provisioning link index pub_key_x -- [in] Unprovisioned device's Public Key X pub_key_y -- [in] Unprovisioned device's Public Key Y link_idx -- [in] The provisioning link index Returns ESP_OK on success or error code otherwise. Parameters link_idx -- [in] The provisioning link index pub_key_x -- [in] Unprovisioned device's Public Key X pub_key_y -- [in] Unprovisioned device's Public Key Y Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_input_string(const char *string, uint8_t link_idx) Provide provisioning input OOB string. This is intended to be called after the esp_ble_mesh_prov_t prov_input_num callback has been called with ESP_BLE_MESH_ENTER_STRING as the action. Parameters string -- [in] String input by Provisioner. link_idx -- [in] The provisioning link index. string -- [in] String input by Provisioner. link_idx -- [in] The provisioning link index. string -- [in] String input by Provisioner. Returns ESP_OK on success or error code otherwise. Parameters string -- [in] String input by Provisioner. link_idx -- [in] The provisioning link index. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_input_number(uint32_t number, uint8_t link_idx) Provide provisioning input OOB number. This is intended to be called after the esp_ble_mesh_prov_t prov_input_num callback has been called with ESP_BLE_MESH_ENTER_NUMBER as the action. Parameters number -- [in] Number input by Provisioner. link_idx -- [in] The provisioning link index. number -- [in] Number input by Provisioner. link_idx -- [in] The provisioning link index. number -- [in] Number input by Provisioner. Returns ESP_OK on success or error code otherwise. Parameters number -- [in] Number input by Provisioner. link_idx -- [in] The provisioning link index. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_prov_enable(esp_ble_mesh_prov_bearer_t bearers) Enable one or more provisioning bearers. Note PB-ADV: Enable BLE scan. PB-GATT: Initialize corresponding BLE Mesh Proxy info. Parameters bearers -- [in] Bit-wise OR of provisioning bearers. Returns ESP_OK on success or error code otherwise. Parameters bearers -- [in] Bit-wise OR of provisioning bearers. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_prov_disable(esp_ble_mesh_prov_bearer_t bearers) Disable one or more provisioning bearers. Note PB-ADV: Disable BLE scan. PB-GATT: Break any existing BLE Mesh Provisioning connections. Parameters bearers -- [in] Bit-wise OR of provisioning bearers. Returns ESP_OK on success or error code otherwise. Parameters bearers -- [in] Bit-wise OR of provisioning bearers. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_add_unprov_dev(esp_ble_mesh_unprov_dev_add_t *add_dev, esp_ble_mesh_dev_add_flag_t flags) Add unprovisioned device info to the unprov_dev queue. Note : 1. Currently address type only supports public address and static random address. If device UUID and/or device address as well as address type already exist in the device queue, but the bearer is different from the existing one, add operation will also be successful and it will update the provision bearer supported by the device. For example, if the Provisioner wants to add an unprovisioned device info before receiving its unprovisioned device beacon or Mesh Provisioning advertising packets, the Provisioner can use this API to add the device info with each one or both of device UUID and device address added. When the Provisioner gets the device's advertising packets, it will start provisioning the device internally. In this situation, the Provisioner can set bearers with each one or both of ESP_BLE_MESH_PROV_ADV and ESP_BLE_MESH_PROV_GATT enabled, and cannot set flags with ADD_DEV_START_PROV_NOW_FLAG enabled. In this situation, the Provisioner can set bearers with each one or both of ESP_BLE_MESH_PROV_ADV and ESP_BLE_MESH_PROV_GATT enabled, and cannot set flags with ADD_DEV_START_PROV_NOW_FLAG enabled. In this situation, the Provisioner can set bearers with each one or both of ESP_BLE_MESH_PROV_ADV and ESP_BLE_MESH_PROV_GATT enabled, and cannot set flags with ADD_DEV_START_PROV_NOW_FLAG enabled. Another example is when the Provisioner receives the unprovisioned device's beacon or Mesh Provisioning advertising packets, the advertising packets will be reported on to the application layer using the callback registered by the function esp_ble_mesh_register_prov_callback. And in the callback, the Provisioner can call this API to start provisioning the device. If the Provisioner uses PB-ADV to provision, either one or both of device UUID and device address can be added, bearers shall be set with ESP_BLE_MESH_PROV_ADV enabled and the flags shall be set with ADD_DEV_START_PROV_NOW_FLAG enabled. If the Provisioner uses PB-GATT to provision, both the device UUID and device address need to be added, bearers shall be set with ESP_BLE_MESH_PROV_GATT enabled, and the flags shall be set with ADD_DEV_START_PROV_NOW_FLAG enabled. If the Provisioner just wants to store the unprovisioned device info when receiving its advertising packets and start to provision it the next time (e.g. after receiving its advertising packets again), then it can add the device info with either one or both of device UUID and device address included. Bearers can be set with either one or both of ESP_BLE_MESH_PROV_ADV and ESP_BLE_MESH_PROV_GATT enabled (recommend to enable the bearer which will receive its advertising packets, because if the other bearer is enabled, the Provisioner is not aware if the device supports the bearer), and flags cannot be set with ADD_DEV_START_PROV_NOW_FLAG enabled. Note: ESP_BLE_MESH_PROV_ADV, ESP_BLE_MESH_PROV_GATT and ADD_DEV_START_PROV_NOW_FLAG can not be enabled at the same time. If the Provisioner uses PB-ADV to provision, either one or both of device UUID and device address can be added, bearers shall be set with ESP_BLE_MESH_PROV_ADV enabled and the flags shall be set with ADD_DEV_START_PROV_NOW_FLAG enabled. If the Provisioner uses PB-GATT to provision, both the device UUID and device address need to be added, bearers shall be set with ESP_BLE_MESH_PROV_GATT enabled, and the flags shall be set with ADD_DEV_START_PROV_NOW_FLAG enabled. If the Provisioner just wants to store the unprovisioned device info when receiving its advertising packets and start to provision it the next time (e.g. after receiving its advertising packets again), then it can add the device info with either one or both of device UUID and device address included. Bearers can be set with either one or both of ESP_BLE_MESH_PROV_ADV and ESP_BLE_MESH_PROV_GATT enabled (recommend to enable the bearer which will receive its advertising packets, because if the other bearer is enabled, the Provisioner is not aware if the device supports the bearer), and flags cannot be set with ADD_DEV_START_PROV_NOW_FLAG enabled. Note: ESP_BLE_MESH_PROV_ADV, ESP_BLE_MESH_PROV_GATT and ADD_DEV_START_PROV_NOW_FLAG can not be enabled at the same time. If the Provisioner uses PB-ADV to provision, either one or both of device UUID and device address can be added, bearers shall be set with ESP_BLE_MESH_PROV_ADV enabled and the flags shall be set with ADD_DEV_START_PROV_NOW_FLAG enabled. If device UUID and/or device address as well as address type already exist in the device queue, but the bearer is different from the existing one, add operation will also be successful and it will update the provision bearer supported by the device. For example, if the Provisioner wants to add an unprovisioned device info before receiving its unprovisioned device beacon or Mesh Provisioning advertising packets, the Provisioner can use this API to add the device info with each one or both of device UUID and device address added. When the Provisioner gets the device's advertising packets, it will start provisioning the device internally. In this situation, the Provisioner can set bearers with each one or both of ESP_BLE_MESH_PROV_ADV and ESP_BLE_MESH_PROV_GATT enabled, and cannot set flags with ADD_DEV_START_PROV_NOW_FLAG enabled. Another example is when the Provisioner receives the unprovisioned device's beacon or Mesh Provisioning advertising packets, the advertising packets will be reported on to the application layer using the callback registered by the function esp_ble_mesh_register_prov_callback. And in the callback, the Provisioner can call this API to start provisioning the device. If the Provisioner uses PB-ADV to provision, either one or both of device UUID and device address can be added, bearers shall be set with ESP_BLE_MESH_PROV_ADV enabled and the flags shall be set with ADD_DEV_START_PROV_NOW_FLAG enabled. If the Provisioner uses PB-GATT to provision, both the device UUID and device address need to be added, bearers shall be set with ESP_BLE_MESH_PROV_GATT enabled, and the flags shall be set with ADD_DEV_START_PROV_NOW_FLAG enabled. If the Provisioner just wants to store the unprovisioned device info when receiving its advertising packets and start to provision it the next time (e.g. after receiving its advertising packets again), then it can add the device info with either one or both of device UUID and device address included. Bearers can be set with either one or both of ESP_BLE_MESH_PROV_ADV and ESP_BLE_MESH_PROV_GATT enabled (recommend to enable the bearer which will receive its advertising packets, because if the other bearer is enabled, the Provisioner is not aware if the device supports the bearer), and flags cannot be set with ADD_DEV_START_PROV_NOW_FLAG enabled. Note: ESP_BLE_MESH_PROV_ADV, ESP_BLE_MESH_PROV_GATT and ADD_DEV_START_PROV_NOW_FLAG can not be enabled at the same time. Parameters add_dev -- [in] Pointer to a struct containing the device information flags -- [in] Flags indicate several operations on the device information Remove device information from queue after device has been provisioned (BIT0) Start provisioning immediately after device is added to queue (BIT1) Device can be removed if device queue is full (BIT2) Remove device information from queue after device has been provisioned (BIT0) Start provisioning immediately after device is added to queue (BIT1) Device can be removed if device queue is full (BIT2) Remove device information from queue after device has been provisioned (BIT0) add_dev -- [in] Pointer to a struct containing the device information flags -- [in] Flags indicate several operations on the device information Remove device information from queue after device has been provisioned (BIT0) Start provisioning immediately after device is added to queue (BIT1) Device can be removed if device queue is full (BIT2) add_dev -- [in] Pointer to a struct containing the device information Returns ESP_OK on success or error code otherwise. Parameters add_dev -- [in] Pointer to a struct containing the device information flags -- [in] Flags indicate several operations on the device information Remove device information from queue after device has been provisioned (BIT0) Start provisioning immediately after device is added to queue (BIT1) Device can be removed if device queue is full (BIT2) Returns ESP_OK on success or error code otherwise. If device UUID and/or device address as well as address type already exist in the device queue, but the bearer is different from the existing one, add operation will also be successful and it will update the provision bearer supported by the device. esp_err_t esp_ble_mesh_provisioner_prov_device_with_addr(const uint8_t uuid[16], esp_ble_mesh_bd_addr_t addr, esp_ble_mesh_addr_type_t addr_type, esp_ble_mesh_prov_bearer_t bearer, uint16_t oob_info, uint16_t unicast_addr) Provision an unprovisioned device and assign a fixed unicast address for it in advance. Note : 1. Currently address type only supports public address and static random address. Bearer must be equal to ESP_BLE_MESH_PROV_ADV or ESP_BLE_MESH_PROV_GATT, since Provisioner will start to provision a device immediately once this function is invoked. And the input bearer must be identical with the one within the parameters of the ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT event. If this function is used by a Provisioner to provision devices, the application should take care of the assigned unicast address and avoid overlap of the unicast addresses of different nodes. Recommend to use only one of the functions "esp_ble_mesh_provisioner_add_unprov_dev" and "esp_ble_mesh_provisioner_prov_device_with_addr" by a Provisioner. Bearer must be equal to ESP_BLE_MESH_PROV_ADV or ESP_BLE_MESH_PROV_GATT, since Provisioner will start to provision a device immediately once this function is invoked. And the input bearer must be identical with the one within the parameters of the ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT event. If this function is used by a Provisioner to provision devices, the application should take care of the assigned unicast address and avoid overlap of the unicast addresses of different nodes. Recommend to use only one of the functions "esp_ble_mesh_provisioner_add_unprov_dev" and "esp_ble_mesh_provisioner_prov_device_with_addr" by a Provisioner. Parameters uuid -- [in] Device UUID of the unprovisioned device addr -- [in] Device address of the unprovisioned device addr_type -- [in] Device address type of the unprovisioned device bearer -- [in] Provisioning bearer going to be used by Provisioner oob_info -- [in] OOB info of the unprovisioned device unicast_addr -- [in] Unicast address going to be allocated for the unprovisioned device uuid -- [in] Device UUID of the unprovisioned device addr -- [in] Device address of the unprovisioned device addr_type -- [in] Device address type of the unprovisioned device bearer -- [in] Provisioning bearer going to be used by Provisioner oob_info -- [in] OOB info of the unprovisioned device unicast_addr -- [in] Unicast address going to be allocated for the unprovisioned device uuid -- [in] Device UUID of the unprovisioned device Returns Zero on success or (negative) error code otherwise. Parameters uuid -- [in] Device UUID of the unprovisioned device addr -- [in] Device address of the unprovisioned device addr_type -- [in] Device address type of the unprovisioned device bearer -- [in] Provisioning bearer going to be used by Provisioner oob_info -- [in] OOB info of the unprovisioned device unicast_addr -- [in] Unicast address going to be allocated for the unprovisioned device Returns Zero on success or (negative) error code otherwise. Bearer must be equal to ESP_BLE_MESH_PROV_ADV or ESP_BLE_MESH_PROV_GATT, since Provisioner will start to provision a device immediately once this function is invoked. And the input bearer must be identical with the one within the parameters of the ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT event. esp_err_t esp_ble_mesh_provisioner_delete_dev(esp_ble_mesh_device_delete_t *del_dev) Delete device from queue, and reset current provisioning link with the device. Note If the device is in the queue, remove it from the queue; if the device is being provisioned, terminate the provisioning procedure. Either one of the device address or device UUID can be used as input. Parameters del_dev -- [in] Pointer to a struct containing the device information. Returns ESP_OK on success or error code otherwise. Parameters del_dev -- [in] Pointer to a struct containing the device information. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_set_dev_uuid_match(const uint8_t *match_val, uint8_t match_len, uint8_t offset, bool prov_after_match) This function is called by Provisioner to set the part of the device UUID to be compared before starting to provision. Parameters match_val -- [in] Value to be compared with the part of the device UUID. match_len -- [in] Length of the compared match value. offset -- [in] Offset of the device UUID to be compared (based on zero). prov_after_match -- [in] Flag used to indicate whether provisioner should start to provision the device immediately if the part of the UUID matches. match_val -- [in] Value to be compared with the part of the device UUID. match_len -- [in] Length of the compared match value. offset -- [in] Offset of the device UUID to be compared (based on zero). prov_after_match -- [in] Flag used to indicate whether provisioner should start to provision the device immediately if the part of the UUID matches. match_val -- [in] Value to be compared with the part of the device UUID. Returns ESP_OK on success or error code otherwise. Parameters match_val -- [in] Value to be compared with the part of the device UUID. match_len -- [in] Length of the compared match value. offset -- [in] Offset of the device UUID to be compared (based on zero). prov_after_match -- [in] Flag used to indicate whether provisioner should start to provision the device immediately if the part of the UUID matches. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_set_prov_data_info(esp_ble_mesh_prov_data_info_t *prov_data_info) This function is called by Provisioner to set provisioning data information before starting to provision. Parameters prov_data_info -- [in] Pointer to a struct containing net_idx or flags or iv_index. Returns ESP_OK on success or error code otherwise. Parameters prov_data_info -- [in] Pointer to a struct containing net_idx or flags or iv_index. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_set_static_oob_value(const uint8_t *value, uint8_t length) This function is called by Provisioner to set static oob value used for provisioning. AuthValues selected using a cryptographically secure random or pseudorandom number generator and having the maximum permitted entropy (128-bits) will be most difficult to brute-force. AuthValues with reduced entropy or generated in a predictable manner will not grant the same level of protection against this vulnerability. Selecting a new AuthValue with each provisioning attempt can also make it more difficult to launch a brute-force attack by requiring the attacker to restart the search with each provisioning attempt (CVE-2020-26556). Note The Bluetooth SIG recommends that mesh implementations enforce a randomly selected AuthValue using all of the available bits, where permitted by the implementation. A large entropy helps ensure that a brute-force of the AuthValue, even a static AuthValue, cannot normally be completed in a reasonable time (CVE-2020-26557). Parameters value -- [in] Pointer to the static oob value. length -- [in] Length of the static oob value. value -- [in] Pointer to the static oob value. length -- [in] Length of the static oob value. value -- [in] Pointer to the static oob value. Returns ESP_OK on success or error code otherwise. Parameters value -- [in] Pointer to the static oob value. length -- [in] Length of the static oob value. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_provisioner_set_primary_elem_addr(uint16_t addr) This function is called by Provisioner to set own Primary element address. Note This API must be invoked when BLE Mesh initialization is completed successfully, and can be invoked before Provisioner functionality is enabled. Once this API is invoked successfully, the prov_unicast_addr value in the struct esp_ble_mesh_prov_t will be ignored, and Provisioner will use this address as its own primary element address. And if the unicast address going to assigned for the next unprovisioned device is smaller than the input address + element number of Provisioner, then the address for the next unprovisioned device will be recalculated internally. Parameters addr -- [in] Unicast address of the Primary element of Provisioner. Returns ESP_OK on success or error code otherwise. Parameters addr -- [in] Unicast address of the Primary element of Provisioner. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_set_fast_prov_info(esp_ble_mesh_fast_prov_info_t *fast_prov_info) This function is called to set provisioning data information before starting fast provisioning. Parameters fast_prov_info -- [in] Pointer to a struct containing unicast address range, net_idx, etc. Returns ESP_OK on success or error code otherwise. Parameters fast_prov_info -- [in] Pointer to a struct containing unicast address range, net_idx, etc. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_set_fast_prov_action(esp_ble_mesh_fast_prov_action_t action) This function is called to start/suspend/exit fast provisioning. Parameters action -- [in] fast provisioning action (i.e. enter, suspend, exit). Returns ESP_OK on success or error code otherwise. Parameters action -- [in] fast provisioning action (i.e. enter, suspend, exit). Returns ESP_OK on success or error code otherwise. Type Definitions typedef void (*esp_ble_mesh_prov_cb_t)(esp_ble_mesh_prov_cb_event_t event, esp_ble_mesh_prov_cb_param_t *param) : event, event code of provisioning events; param, parameters of provisioning events typedef void (*esp_ble_mesh_prov_adv_cb_t)(const esp_ble_mesh_bd_addr_t addr, const esp_ble_mesh_addr_type_t addr_type, const uint8_t adv_type, const uint8_t *dev_uuid, uint16_t oob_info, esp_ble_mesh_prov_bearer_t bearer) Callback for Provisioner that received advertising packets from unprovisioned devices which are not in the unprovisioned device queue. Report on the unprovisioned device beacon and mesh provisioning service adv data to application. Param addr [in] Pointer to the unprovisioned device address. Param addr_type [in] Unprovisioned device address type. Param adv_type [in] Adv packet type(ADV_IND or ADV_NONCONN_IND). Param dev_uuid [in] Unprovisioned device UUID pointer. Param oob_info [in] OOB information of the unprovisioned device. Param bearer [in] Adv packet received from PB-GATT or PB-ADV bearer. Param addr [in] Pointer to the unprovisioned device address. Param addr_type [in] Unprovisioned device address type. Param adv_type [in] Adv packet type(ADV_IND or ADV_NONCONN_IND). Param dev_uuid [in] Unprovisioned device UUID pointer. Param oob_info [in] OOB information of the unprovisioned device. Param bearer [in] Adv packet received from PB-GATT or PB-ADV bearer. ESP-BLE-MESH GATT Proxy Server Header File components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_proxy_api.h This header file can be included with: #include "esp_ble_mesh_proxy_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_proxy_identity_enable(void) Enable advertising with Node Identity. Note This API requires that GATT Proxy support be enabled. Once called, each subnet starts advertising using Node Identity for the next 60 seconds, and after 60s Network ID will be advertised. Under normal conditions, the BLE Mesh Proxy Node Identity and Network ID advertising will be enabled automatically by BLE Mesh stack after the device is provisioned. Returns ESP_OK on success or error code otherwise. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_proxy_gatt_enable(void) Enable BLE Mesh GATT Proxy Service. Returns ESP_OK on success or error code otherwise. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_proxy_gatt_disable(void) Disconnect the BLE Mesh GATT Proxy connection if there is any, and disable the BLE Mesh GATT Proxy Service. Returns ESP_OK on success or error code otherwise. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_private_proxy_identity_enable(void) Enable advertising with Private Node Identity. Note This API requires that GATT Proxy support be enabled. Once called, each subnet starts advertising using Private Node Identity for the next 60 seconds, and after 60s Private Network ID will be advertised. Under normal conditions, the BLE Mesh Proxy Node Identity, Network ID advertising, Proxy Private Node Identity and Private Network ID advertising will be enabled automatically by BLE Mesh stack after the device is provisioned. Returns ESP_OK on success or error code otherwise. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_private_proxy_identity_disable(void) Disable advertising with Private Node Identity. Returns ESP_OK on success or error code otherwise. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_proxy_client_connect(esp_ble_mesh_bd_addr_t addr, esp_ble_mesh_addr_type_t addr_type, uint16_t net_idx) Proxy Client creates a connection with the Proxy Server. Parameters addr -- [in] Device address of the Proxy Server. addr_type -- [in] Device address type(public or static random). net_idx -- [in] NetKey Index related with Network ID in the Mesh Proxy advertising packet. addr -- [in] Device address of the Proxy Server. addr_type -- [in] Device address type(public or static random). net_idx -- [in] NetKey Index related with Network ID in the Mesh Proxy advertising packet. addr -- [in] Device address of the Proxy Server. Returns ESP_OK on success or error code otherwise. Parameters addr -- [in] Device address of the Proxy Server. addr_type -- [in] Device address type(public or static random). net_idx -- [in] NetKey Index related with Network ID in the Mesh Proxy advertising packet. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_proxy_client_disconnect(uint8_t conn_handle) Proxy Client terminates a connection with the Proxy Server. Parameters conn_handle -- [in] Proxy connection handle. Returns ESP_OK on success or error code otherwise. Parameters conn_handle -- [in] Proxy connection handle. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_proxy_client_set_filter_type(uint8_t conn_handle, uint16_t net_idx, esp_ble_mesh_proxy_filter_type_t filter_type) Proxy Client sets the filter type of the Proxy Server. Parameters conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. filter_type -- [in] whitelist or blacklist. conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. filter_type -- [in] whitelist or blacklist. conn_handle -- [in] Proxy connection handle. Returns ESP_OK on success or error code otherwise. Parameters conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. filter_type -- [in] whitelist or blacklist. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_proxy_client_add_filter_addr(uint8_t conn_handle, uint16_t net_idx, uint16_t *addr, uint16_t addr_num) Proxy Client adds address to the Proxy Server filter list. Parameters conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. addr -- [in] Pointer to the filter address. addr_num -- [in] Number of the filter address. conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. addr -- [in] Pointer to the filter address. addr_num -- [in] Number of the filter address. conn_handle -- [in] Proxy connection handle. Returns ESP_OK on success or error code otherwise. Parameters conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. addr -- [in] Pointer to the filter address. addr_num -- [in] Number of the filter address. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_proxy_client_remove_filter_addr(uint8_t conn_handle, uint16_t net_idx, uint16_t *addr, uint16_t addr_num) Proxy Client removes address from the Proxy Server filter list. Parameters conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. addr -- [in] Pointer to the filter address. addr_num -- [in] Number of the filter address. conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. addr -- [in] Pointer to the filter address. addr_num -- [in] Number of the filter address. conn_handle -- [in] Proxy connection handle. Returns ESP_OK on success or error code otherwise. Parameters conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. addr -- [in] Pointer to the filter address. addr_num -- [in] Number of the filter address. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_proxy_client_directed_proxy_set(uint8_t conn_handle, uint16_t net_idx, uint8_t use_directed) Proxy Client sets whether or not the Directed Proxy Server uses directed forwarding for Directed Proxy Client messages. Parameters conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. use_directed -- [in] Whether or not to send message by directed forwarding. conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. use_directed -- [in] Whether or not to send message by directed forwarding. conn_handle -- [in] Proxy connection handle. Returns ESP_OK on success or error code otherwise. Parameters conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. use_directed -- [in] Whether or not to send message by directed forwarding. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_proxy_client_send_solic_pdu(uint8_t net_idx, uint16_t ssrc, uint16_t dst) Proxy Client sends Solicitation PDU. Parameters net_idx -- [in] Corresponding NetKey Index. ssrc -- [in] Solicitation SRC, shall be one of its element address. dst -- [in] Solicitation DST (TBD). net_idx -- [in] Corresponding NetKey Index. ssrc -- [in] Solicitation SRC, shall be one of its element address. dst -- [in] Solicitation DST (TBD). net_idx -- [in] Corresponding NetKey Index. Returns ESP_OK on success or error code otherwise. Parameters net_idx -- [in] Corresponding NetKey Index. ssrc -- [in] Solicitation SRC, shall be one of its element address. dst -- [in] Solicitation DST (TBD). Returns ESP_OK on success or error code otherwise. Macros ESP_BLE_MESH_PROXY_CLI_DIRECTED_FORWARDING_ENABLE ESP_BLE_MESH_PROXY_CLI_DIRECTED_FORWARDING_DISABLE ESP-BLE-MESH Models API Reference This section contains ESP-BLE-MESH Model related APIs, event types, event parameters, etc. There are six categories of models: Note Definitions related to Server Models are being updated, and will be released soon. Configuration Client/Server Models Header File components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_config_model_api.h This header file can be included with: #include "esp_ble_mesh_config_model_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_config_client_callback(esp_ble_mesh_cfg_client_cb_t callback) Register BLE Mesh Config Client Model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_register_config_server_callback(esp_ble_mesh_cfg_server_cb_t callback) Register BLE Mesh Config Server Model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_config_client_get_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_cfg_client_get_state_t *get_state) Get the value of Config Server Model states using the Config Client Model get messages. Note If you want to find the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_opcode_config_client_get_t in esp_ble_mesh_defs.h Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_config_client_set_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_cfg_client_set_state_t *set_state) Set the value of the Configuration Server Model states using the Config Client Model set messages. Note If you want to find the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_opcode_config_client_set_t in esp_ble_mesh_defs.h Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. Returns ESP_OK on success or error code otherwise. Unions union esp_ble_mesh_cfg_client_get_state_t #include <esp_ble_mesh_config_model_api.h> For ESP_BLE_MESH_MODEL_OP_BEACON_GET ESP_BLE_MESH_MODEL_OP_COMPOSITION_DATA_GET ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_GET ESP_BLE_MESH_MODEL_OP_GATT_PROXY_GET ESP_BLE_MESH_MODEL_OP_RELAY_GET ESP_BLE_MESH_MODEL_OP_MODEL_PUB_GET ESP_BLE_MESH_MODEL_OP_FRIEND_GET ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_GET ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_GET the get_state parameter in the esp_ble_mesh_config_client_get_state function should not be set to NULL. Public Members esp_ble_mesh_cfg_model_pub_get_t model_pub_get For ESP_BLE_MESH_MODEL_OP_MODEL_PUB_GET. esp_ble_mesh_cfg_model_pub_get_t model_pub_get For ESP_BLE_MESH_MODEL_OP_MODEL_PUB_GET. esp_ble_mesh_cfg_composition_data_get_t comp_data_get For ESP_BLE_MESH_MODEL_OP_COMPOSITION_DATA_GET. esp_ble_mesh_cfg_composition_data_get_t comp_data_get For ESP_BLE_MESH_MODEL_OP_COMPOSITION_DATA_GET. esp_ble_mesh_cfg_sig_model_sub_get_t sig_model_sub_get For ESP_BLE_MESH_MODEL_OP_SIG_MODEL_SUB_GET esp_ble_mesh_cfg_sig_model_sub_get_t sig_model_sub_get For ESP_BLE_MESH_MODEL_OP_SIG_MODEL_SUB_GET esp_ble_mesh_cfg_vnd_model_sub_get_t vnd_model_sub_get For ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_SUB_GET esp_ble_mesh_cfg_vnd_model_sub_get_t vnd_model_sub_get For ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_SUB_GET esp_ble_mesh_cfg_app_key_get_t app_key_get For ESP_BLE_MESH_MODEL_OP_APP_KEY_GET. esp_ble_mesh_cfg_app_key_get_t app_key_get For ESP_BLE_MESH_MODEL_OP_APP_KEY_GET. esp_ble_mesh_cfg_node_identity_get_t node_identity_get For ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_GET. esp_ble_mesh_cfg_node_identity_get_t node_identity_get For ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_GET. esp_ble_mesh_cfg_sig_model_app_get_t sig_model_app_get For ESP_BLE_MESH_MODEL_OP_SIG_MODEL_APP_GET esp_ble_mesh_cfg_sig_model_app_get_t sig_model_app_get For ESP_BLE_MESH_MODEL_OP_SIG_MODEL_APP_GET esp_ble_mesh_cfg_vnd_model_app_get_t vnd_model_app_get For ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_APP_GET esp_ble_mesh_cfg_vnd_model_app_get_t vnd_model_app_get For ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_APP_GET esp_ble_mesh_cfg_kr_phase_get_t kr_phase_get For ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_GET esp_ble_mesh_cfg_kr_phase_get_t kr_phase_get For ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_GET esp_ble_mesh_cfg_lpn_polltimeout_get_t lpn_pollto_get For ESP_BLE_MESH_MODEL_OP_LPN_POLLTIMEOUT_GET esp_ble_mesh_cfg_lpn_polltimeout_get_t lpn_pollto_get For ESP_BLE_MESH_MODEL_OP_LPN_POLLTIMEOUT_GET esp_ble_mesh_cfg_model_pub_get_t model_pub_get union esp_ble_mesh_cfg_client_set_state_t #include <esp_ble_mesh_config_model_api.h> For ESP_BLE_MESH_MODEL_OP_BEACON_SET ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_SET ESP_BLE_MESH_MODEL_OP_GATT_PROXY_SET ESP_BLE_MESH_MODEL_OP_RELAY_SET ESP_BLE_MESH_MODEL_OP_MODEL_PUB_SET ESP_BLE_MESH_MODEL_OP_MODEL_SUB_ADD ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_ADD ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_DELETE ESP_BLE_MESH_MODEL_OP_MODEL_SUB_OVERWRITE ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_OVERWRITE ESP_BLE_MESH_MODEL_OP_NET_KEY_ADD ESP_BLE_MESH_MODEL_OP_APP_KEY_ADD ESP_BLE_MESH_MODEL_OP_MODEL_APP_BIND ESP_BLE_MESH_MODEL_OP_NODE_RESET ESP_BLE_MESH_MODEL_OP_FRIEND_SET ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_SET ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_SET the set_state parameter in the esp_ble_mesh_config_client_set_state function should not be set to NULL. Public Members esp_ble_mesh_cfg_beacon_set_t beacon_set For ESP_BLE_MESH_MODEL_OP_BEACON_SET esp_ble_mesh_cfg_beacon_set_t beacon_set For ESP_BLE_MESH_MODEL_OP_BEACON_SET esp_ble_mesh_cfg_default_ttl_set_t default_ttl_set For ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_SET esp_ble_mesh_cfg_default_ttl_set_t default_ttl_set For ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_SET esp_ble_mesh_cfg_friend_set_t friend_set For ESP_BLE_MESH_MODEL_OP_FRIEND_SET esp_ble_mesh_cfg_friend_set_t friend_set For ESP_BLE_MESH_MODEL_OP_FRIEND_SET esp_ble_mesh_cfg_gatt_proxy_set_t gatt_proxy_set For ESP_BLE_MESH_MODEL_OP_GATT_PROXY_SET esp_ble_mesh_cfg_gatt_proxy_set_t gatt_proxy_set For ESP_BLE_MESH_MODEL_OP_GATT_PROXY_SET esp_ble_mesh_cfg_relay_set_t relay_set For ESP_BLE_MESH_MODEL_OP_RELAY_SET esp_ble_mesh_cfg_relay_set_t relay_set For ESP_BLE_MESH_MODEL_OP_RELAY_SET esp_ble_mesh_cfg_net_key_add_t net_key_add For ESP_BLE_MESH_MODEL_OP_NET_KEY_ADD esp_ble_mesh_cfg_net_key_add_t net_key_add For ESP_BLE_MESH_MODEL_OP_NET_KEY_ADD esp_ble_mesh_cfg_app_key_add_t app_key_add For ESP_BLE_MESH_MODEL_OP_APP_KEY_ADD esp_ble_mesh_cfg_app_key_add_t app_key_add For ESP_BLE_MESH_MODEL_OP_APP_KEY_ADD esp_ble_mesh_cfg_model_app_bind_t model_app_bind For ESP_BLE_MESH_MODEL_OP_MODEL_APP_BIND esp_ble_mesh_cfg_model_app_bind_t model_app_bind For ESP_BLE_MESH_MODEL_OP_MODEL_APP_BIND esp_ble_mesh_cfg_model_pub_set_t model_pub_set For ESP_BLE_MESH_MODEL_OP_MODEL_PUB_SET esp_ble_mesh_cfg_model_pub_set_t model_pub_set For ESP_BLE_MESH_MODEL_OP_MODEL_PUB_SET esp_ble_mesh_cfg_model_sub_add_t model_sub_add For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_ADD esp_ble_mesh_cfg_model_sub_add_t model_sub_add For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_ADD esp_ble_mesh_cfg_model_sub_delete_t model_sub_delete For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE esp_ble_mesh_cfg_model_sub_delete_t model_sub_delete For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE esp_ble_mesh_cfg_model_sub_overwrite_t model_sub_overwrite For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_OVERWRITE esp_ble_mesh_cfg_model_sub_overwrite_t model_sub_overwrite For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_OVERWRITE esp_ble_mesh_cfg_model_sub_va_add_t model_sub_va_add For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_ADD esp_ble_mesh_cfg_model_sub_va_add_t model_sub_va_add For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_ADD esp_ble_mesh_cfg_model_sub_va_delete_t model_sub_va_delete For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_DELETE esp_ble_mesh_cfg_model_sub_va_delete_t model_sub_va_delete For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_DELETE esp_ble_mesh_cfg_model_sub_va_overwrite_t model_sub_va_overwrite For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_OVERWRITE esp_ble_mesh_cfg_model_sub_va_overwrite_t model_sub_va_overwrite For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_OVERWRITE esp_ble_mesh_cfg_heartbeat_pub_set_t heartbeat_pub_set For ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_SET esp_ble_mesh_cfg_heartbeat_pub_set_t heartbeat_pub_set For ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_SET esp_ble_mesh_cfg_heartbeat_sub_set_t heartbeat_sub_set For ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_SET esp_ble_mesh_cfg_heartbeat_sub_set_t heartbeat_sub_set For ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_SET esp_ble_mesh_cfg_model_pub_va_set_t model_pub_va_set For ESP_BLE_MESH_MODEL_OP_MODEL_PUB_VIRTUAL_ADDR_SET esp_ble_mesh_cfg_model_pub_va_set_t model_pub_va_set For ESP_BLE_MESH_MODEL_OP_MODEL_PUB_VIRTUAL_ADDR_SET esp_ble_mesh_cfg_model_sub_delete_all_t model_sub_delete_all For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE_ALL esp_ble_mesh_cfg_model_sub_delete_all_t model_sub_delete_all For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE_ALL esp_ble_mesh_cfg_net_key_update_t net_key_update For ESP_BLE_MESH_MODEL_OP_NET_KEY_UPDATE esp_ble_mesh_cfg_net_key_update_t net_key_update For ESP_BLE_MESH_MODEL_OP_NET_KEY_UPDATE esp_ble_mesh_cfg_net_key_delete_t net_key_delete For ESP_BLE_MESH_MODEL_OP_NET_KEY_DELETE esp_ble_mesh_cfg_net_key_delete_t net_key_delete For ESP_BLE_MESH_MODEL_OP_NET_KEY_DELETE esp_ble_mesh_cfg_app_key_update_t app_key_update For ESP_BLE_MESH_MODEL_OP_APP_KEY_UPDATE esp_ble_mesh_cfg_app_key_update_t app_key_update For ESP_BLE_MESH_MODEL_OP_APP_KEY_UPDATE esp_ble_mesh_cfg_app_key_delete_t app_key_delete For ESP_BLE_MESH_MODEL_OP_APP_KEY_DELETE esp_ble_mesh_cfg_app_key_delete_t app_key_delete For ESP_BLE_MESH_MODEL_OP_APP_KEY_DELETE esp_ble_mesh_cfg_node_identity_set_t node_identity_set For ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_SET esp_ble_mesh_cfg_node_identity_set_t node_identity_set For ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_SET esp_ble_mesh_cfg_model_app_unbind_t model_app_unbind For ESP_BLE_MESH_MODEL_OP_MODEL_APP_UNBIND esp_ble_mesh_cfg_model_app_unbind_t model_app_unbind For ESP_BLE_MESH_MODEL_OP_MODEL_APP_UNBIND esp_ble_mesh_cfg_kr_phase_set_t kr_phase_set For ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_SET esp_ble_mesh_cfg_kr_phase_set_t kr_phase_set For ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_SET esp_ble_mesh_cfg_net_transmit_set_t net_transmit_set For ESP_BLE_MESH_MODEL_OP_NETWORK_TRANSMIT_SET esp_ble_mesh_cfg_net_transmit_set_t net_transmit_set For ESP_BLE_MESH_MODEL_OP_NETWORK_TRANSMIT_SET esp_ble_mesh_cfg_beacon_set_t beacon_set union esp_ble_mesh_cfg_client_common_cb_param_t #include <esp_ble_mesh_config_model_api.h> Configuration Client Model received message union. Public Members esp_ble_mesh_cfg_beacon_status_cb_t beacon_status The beacon status value esp_ble_mesh_cfg_beacon_status_cb_t beacon_status The beacon status value esp_ble_mesh_cfg_comp_data_status_cb_t comp_data_status The composition data status value esp_ble_mesh_cfg_comp_data_status_cb_t comp_data_status The composition data status value esp_ble_mesh_cfg_default_ttl_status_cb_t default_ttl_status The default_ttl status value esp_ble_mesh_cfg_default_ttl_status_cb_t default_ttl_status The default_ttl status value esp_ble_mesh_cfg_gatt_proxy_status_cb_t gatt_proxy_status The gatt_proxy status value esp_ble_mesh_cfg_gatt_proxy_status_cb_t gatt_proxy_status The gatt_proxy status value esp_ble_mesh_cfg_relay_status_cb_t relay_status The relay status value esp_ble_mesh_cfg_relay_status_cb_t relay_status The relay status value esp_ble_mesh_cfg_model_pub_status_cb_t model_pub_status The model publication status value esp_ble_mesh_cfg_model_pub_status_cb_t model_pub_status The model publication status value esp_ble_mesh_cfg_model_sub_status_cb_t model_sub_status The model subscription status value esp_ble_mesh_cfg_model_sub_status_cb_t model_sub_status The model subscription status value esp_ble_mesh_cfg_net_key_status_cb_t netkey_status The netkey status value esp_ble_mesh_cfg_net_key_status_cb_t netkey_status The netkey status value esp_ble_mesh_cfg_app_key_status_cb_t appkey_status The appkey status value esp_ble_mesh_cfg_app_key_status_cb_t appkey_status The appkey status value esp_ble_mesh_cfg_mod_app_status_cb_t model_app_status The model app status value esp_ble_mesh_cfg_mod_app_status_cb_t model_app_status The model app status value esp_ble_mesh_cfg_friend_status_cb_t friend_status The friend status value esp_ble_mesh_cfg_friend_status_cb_t friend_status The friend status value esp_ble_mesh_cfg_hb_pub_status_cb_t heartbeat_pub_status The heartbeat publication status value esp_ble_mesh_cfg_hb_pub_status_cb_t heartbeat_pub_status The heartbeat publication status value esp_ble_mesh_cfg_hb_sub_status_cb_t heartbeat_sub_status The heartbeat subscription status value esp_ble_mesh_cfg_hb_sub_status_cb_t heartbeat_sub_status The heartbeat subscription status value esp_ble_mesh_cfg_net_trans_status_cb_t net_transmit_status The network transmit status value esp_ble_mesh_cfg_net_trans_status_cb_t net_transmit_status The network transmit status value esp_ble_mesh_cfg_model_sub_list_cb_t model_sub_list The model subscription list value esp_ble_mesh_cfg_model_sub_list_cb_t model_sub_list The model subscription list value esp_ble_mesh_cfg_net_key_list_cb_t netkey_list The network key index list value esp_ble_mesh_cfg_net_key_list_cb_t netkey_list The network key index list value esp_ble_mesh_cfg_app_key_list_cb_t appkey_list The application key index list value esp_ble_mesh_cfg_app_key_list_cb_t appkey_list The application key index list value esp_ble_mesh_cfg_node_id_status_cb_t node_identity_status The node identity status value esp_ble_mesh_cfg_node_id_status_cb_t node_identity_status The node identity status value esp_ble_mesh_cfg_model_app_list_cb_t model_app_list The model application key index list value esp_ble_mesh_cfg_model_app_list_cb_t model_app_list The model application key index list value esp_ble_mesh_cfg_kr_phase_status_cb_t kr_phase_status The key refresh phase status value esp_ble_mesh_cfg_kr_phase_status_cb_t kr_phase_status The key refresh phase status value esp_ble_mesh_cfg_lpn_pollto_status_cb_t lpn_timeout_status The low power node poll timeout status value esp_ble_mesh_cfg_lpn_pollto_status_cb_t lpn_timeout_status The low power node poll timeout status value esp_ble_mesh_cfg_beacon_status_cb_t beacon_status union esp_ble_mesh_cfg_server_state_change_t #include <esp_ble_mesh_config_model_api.h> Configuration Server model state change value union. Public Members esp_ble_mesh_state_change_cfg_mod_pub_set_t mod_pub_set The recv_op in ctx can be used to decide which state is changed. Config Model Publication Set esp_ble_mesh_state_change_cfg_mod_pub_set_t mod_pub_set The recv_op in ctx can be used to decide which state is changed. Config Model Publication Set esp_ble_mesh_state_change_cfg_mod_pub_va_set_t mod_pub_va_set Config Model Publication Virtual Address Set esp_ble_mesh_state_change_cfg_mod_pub_va_set_t mod_pub_va_set Config Model Publication Virtual Address Set esp_ble_mesh_state_change_cfg_model_sub_add_t mod_sub_add Config Model Subscription Add esp_ble_mesh_state_change_cfg_model_sub_add_t mod_sub_add Config Model Subscription Add esp_ble_mesh_state_change_cfg_model_sub_delete_t mod_sub_delete Config Model Subscription Delete esp_ble_mesh_state_change_cfg_model_sub_delete_t mod_sub_delete Config Model Subscription Delete esp_ble_mesh_state_change_cfg_netkey_add_t netkey_add Config NetKey Add esp_ble_mesh_state_change_cfg_netkey_add_t netkey_add Config NetKey Add esp_ble_mesh_state_change_cfg_netkey_update_t netkey_update Config NetKey Update esp_ble_mesh_state_change_cfg_netkey_update_t netkey_update Config NetKey Update esp_ble_mesh_state_change_cfg_netkey_delete_t netkey_delete Config NetKey Delete esp_ble_mesh_state_change_cfg_netkey_delete_t netkey_delete Config NetKey Delete esp_ble_mesh_state_change_cfg_appkey_add_t appkey_add Config AppKey Add esp_ble_mesh_state_change_cfg_appkey_add_t appkey_add Config AppKey Add esp_ble_mesh_state_change_cfg_appkey_update_t appkey_update Config AppKey Update esp_ble_mesh_state_change_cfg_appkey_update_t appkey_update Config AppKey Update esp_ble_mesh_state_change_cfg_appkey_delete_t appkey_delete Config AppKey Delete esp_ble_mesh_state_change_cfg_appkey_delete_t appkey_delete Config AppKey Delete esp_ble_mesh_state_change_cfg_model_app_bind_t mod_app_bind Config Model App Bind esp_ble_mesh_state_change_cfg_model_app_bind_t mod_app_bind Config Model App Bind esp_ble_mesh_state_change_cfg_model_app_unbind_t mod_app_unbind Config Model App Unbind esp_ble_mesh_state_change_cfg_model_app_unbind_t mod_app_unbind Config Model App Unbind esp_ble_mesh_state_change_cfg_kr_phase_set_t kr_phase_set Config Key Refresh Phase Set esp_ble_mesh_state_change_cfg_kr_phase_set_t kr_phase_set Config Key Refresh Phase Set esp_ble_mesh_state_change_cfg_mod_pub_set_t mod_pub_set union esp_ble_mesh_cfg_server_cb_value_t #include <esp_ble_mesh_config_model_api.h> Configuration Server model callback value union. Public Members esp_ble_mesh_cfg_server_state_change_t state_change ESP_BLE_MESH_CFG_SERVER_STATE_CHANGE_EVT esp_ble_mesh_cfg_server_state_change_t state_change ESP_BLE_MESH_CFG_SERVER_STATE_CHANGE_EVT esp_ble_mesh_cfg_server_state_change_t state_change Structures struct esp_ble_mesh_cfg_srv_t Configuration Server Model context Public Members esp_ble_mesh_model_t *model Pointer to Configuration Server Model esp_ble_mesh_model_t *model Pointer to Configuration Server Model uint8_t net_transmit Network Transmit state uint8_t net_transmit Network Transmit state uint8_t relay Relay Mode state uint8_t relay Relay Mode state uint8_t relay_retransmit Relay Retransmit state uint8_t relay_retransmit Relay Retransmit state uint8_t beacon Secure Network Beacon state uint8_t beacon Secure Network Beacon state uint8_t gatt_proxy GATT Proxy state uint8_t gatt_proxy GATT Proxy state uint8_t friend_state Friend state uint8_t friend_state Friend state uint8_t default_ttl Default TTL uint8_t default_ttl Default TTL struct k_delayed_work timer Heartbeat Publication timer struct k_delayed_work timer Heartbeat Publication timer uint16_t dst Destination address for Heartbeat messages uint16_t dst Destination address for Heartbeat messages uint16_t count Number of Heartbeat messages to be sent Number of Heartbeat messages received uint16_t count Number of Heartbeat messages to be sent Number of Heartbeat messages received uint8_t period Period for sending Heartbeat messages uint8_t period Period for sending Heartbeat messages uint8_t ttl TTL to be used when sending Heartbeat messages uint8_t ttl TTL to be used when sending Heartbeat messages uint16_t feature Bit field indicating features that trigger Heartbeat messages when changed uint16_t feature Bit field indicating features that trigger Heartbeat messages when changed uint16_t net_idx NetKey Index used by Heartbeat Publication uint16_t net_idx NetKey Index used by Heartbeat Publication struct esp_ble_mesh_cfg_srv_t::[anonymous] heartbeat_pub Heartbeat Publication struct esp_ble_mesh_cfg_srv_t::[anonymous] heartbeat_pub Heartbeat Publication int64_t expiry Timestamp when Heartbeat subscription period is expired int64_t expiry Timestamp when Heartbeat subscription period is expired uint16_t src Source address for Heartbeat messages uint16_t src Source address for Heartbeat messages uint8_t min_hops Minimum hops when receiving Heartbeat messages uint8_t min_hops Minimum hops when receiving Heartbeat messages uint8_t max_hops Maximum hops when receiving Heartbeat messages uint8_t max_hops Maximum hops when receiving Heartbeat messages esp_ble_mesh_cb_t heartbeat_recv_cb Optional heartbeat subscription tracking function esp_ble_mesh_cb_t heartbeat_recv_cb Optional heartbeat subscription tracking function struct esp_ble_mesh_cfg_srv_t::[anonymous] heartbeat_sub Heartbeat Subscription struct esp_ble_mesh_cfg_srv_t::[anonymous] heartbeat_sub Heartbeat Subscription esp_ble_mesh_model_t *model struct esp_ble_mesh_cfg_composition_data_get_t Parameters of Config Composition Data Get. Public Members uint8_t page Page number of the Composition Data. uint8_t page Page number of the Composition Data. uint8_t page struct esp_ble_mesh_cfg_model_pub_get_t Parameters of Config Model Publication Get. struct esp_ble_mesh_cfg_sig_model_sub_get_t Parameters of Config SIG Model Subscription Get. struct esp_ble_mesh_cfg_vnd_model_sub_get_t Parameters of Config Vendor Model Subscription Get. struct esp_ble_mesh_cfg_app_key_get_t Parameters of Config AppKey Get. struct esp_ble_mesh_cfg_node_identity_get_t Parameters of Config Node Identity Get. struct esp_ble_mesh_cfg_sig_model_app_get_t Parameters of Config SIG Model App Get. struct esp_ble_mesh_cfg_vnd_model_app_get_t Parameters of Config Vendor Model App Get. struct esp_ble_mesh_cfg_kr_phase_get_t Parameters of Config Key Refresh Phase Get. struct esp_ble_mesh_cfg_lpn_polltimeout_get_t Parameters of Config Low Power Node PollTimeout Get. Public Members uint16_t lpn_addr The unicast address of the Low Power node uint16_t lpn_addr The unicast address of the Low Power node uint16_t lpn_addr struct esp_ble_mesh_cfg_beacon_set_t Parameters of Config Beacon Set. Public Members uint8_t beacon New Secure Network Beacon state uint8_t beacon New Secure Network Beacon state uint8_t beacon struct esp_ble_mesh_cfg_default_ttl_set_t Parameters of Config Default TTL Set. Public Members uint8_t ttl The default TTL state value uint8_t ttl The default TTL state value uint8_t ttl struct esp_ble_mesh_cfg_friend_set_t Parameters of Config Friend Set. Public Members uint8_t friend_state The friend state value uint8_t friend_state The friend state value uint8_t friend_state struct esp_ble_mesh_cfg_gatt_proxy_set_t Parameters of Config GATT Proxy Set. Public Members uint8_t gatt_proxy The GATT Proxy state value uint8_t gatt_proxy The GATT Proxy state value uint8_t gatt_proxy struct esp_ble_mesh_cfg_relay_set_t Parameters of Config Relay Set. struct esp_ble_mesh_cfg_net_key_add_t Parameters of Config NetKey Add. struct esp_ble_mesh_cfg_app_key_add_t Parameters of Config AppKey Add. struct esp_ble_mesh_cfg_model_app_bind_t Parameters of Config Model App Bind. struct esp_ble_mesh_cfg_model_pub_set_t Parameters of Config Model Publication Set. Public Members uint16_t element_addr The element address uint16_t element_addr The element address uint16_t publish_addr Value of the publish address uint16_t publish_addr Value of the publish address uint16_t publish_app_idx Index of the application key uint16_t publish_app_idx Index of the application key bool cred_flag Value of the Friendship Credential Flag bool cred_flag Value of the Friendship Credential Flag uint8_t publish_ttl Default TTL value for the publishing messages uint8_t publish_ttl Default TTL value for the publishing messages uint8_t publish_period Period for periodic status publishing uint8_t publish_period Period for periodic status publishing uint8_t publish_retransmit Number of retransmissions and number of 50-millisecond steps between retransmissions uint8_t publish_retransmit Number of retransmissions and number of 50-millisecond steps between retransmissions uint16_t model_id The model id uint16_t model_id The model id uint16_t company_id The company id, if not a vendor model, shall set to 0xFFFF uint16_t company_id The company id, if not a vendor model, shall set to 0xFFFF uint16_t element_addr struct esp_ble_mesh_cfg_model_sub_add_t Parameters of Config Model Subscription Add. struct esp_ble_mesh_cfg_model_sub_delete_t Parameters of Config Model Subscription Delete. struct esp_ble_mesh_cfg_model_sub_overwrite_t Parameters of Config Model Subscription Overwrite. struct esp_ble_mesh_cfg_model_sub_va_add_t Parameters of Config Model Subscription Virtual Address Add. struct esp_ble_mesh_cfg_model_sub_va_delete_t Parameters of Config Model Subscription Virtual Address Delete. struct esp_ble_mesh_cfg_model_sub_va_overwrite_t Parameters of Config Model Subscription Virtual Address Overwrite. struct esp_ble_mesh_cfg_model_pub_va_set_t Parameters of Config Model Publication Virtual Address Set. Public Members uint16_t element_addr The element address uint16_t element_addr The element address uint8_t label_uuid[16] Value of the Label UUID publish address uint8_t label_uuid[16] Value of the Label UUID publish address uint16_t publish_app_idx Index of the application key uint16_t publish_app_idx Index of the application key bool cred_flag Value of the Friendship Credential Flag bool cred_flag Value of the Friendship Credential Flag uint8_t publish_ttl Default TTL value for the publishing messages uint8_t publish_ttl Default TTL value for the publishing messages uint8_t publish_period Period for periodic status publishing uint8_t publish_period Period for periodic status publishing uint8_t publish_retransmit Number of retransmissions and number of 50-millisecond steps between retransmissions uint8_t publish_retransmit Number of retransmissions and number of 50-millisecond steps between retransmissions uint16_t model_id The model id uint16_t model_id The model id uint16_t company_id The company id, if not a vendor model, shall set to 0xFFFF uint16_t company_id The company id, if not a vendor model, shall set to 0xFFFF uint16_t element_addr struct esp_ble_mesh_cfg_model_sub_delete_all_t Parameters of Config Model Subscription Delete All. struct esp_ble_mesh_cfg_net_key_update_t Parameters of Config NetKey Update. struct esp_ble_mesh_cfg_net_key_delete_t Parameters of Config NetKey Delete. struct esp_ble_mesh_cfg_app_key_update_t Parameters of Config AppKey Update. struct esp_ble_mesh_cfg_app_key_delete_t Parameters of Config AppKey Delete. struct esp_ble_mesh_cfg_node_identity_set_t Parameters of Config Node Identity Set. struct esp_ble_mesh_cfg_model_app_unbind_t Parameters of Config Model App Unbind. struct esp_ble_mesh_cfg_kr_phase_set_t Parameters of Config Key Refresh Phase Set. struct esp_ble_mesh_cfg_net_transmit_set_t Parameters of Config Network Transmit Set. Public Members uint8_t net_transmit Network Transmit State uint8_t net_transmit Network Transmit State uint8_t net_transmit struct esp_ble_mesh_cfg_heartbeat_pub_set_t Parameters of Config Model Heartbeat Publication Set. Public Members uint16_t dst Destination address for Heartbeat messages uint16_t dst Destination address for Heartbeat messages uint8_t count Number of Heartbeat messages to be sent uint8_t count Number of Heartbeat messages to be sent uint8_t period Period for sending Heartbeat messages uint8_t period Period for sending Heartbeat messages uint8_t ttl TTL to be used when sending Heartbeat messages uint8_t ttl TTL to be used when sending Heartbeat messages uint16_t feature Bit field indicating features that trigger Heartbeat messages when changed uint16_t feature Bit field indicating features that trigger Heartbeat messages when changed uint16_t net_idx NetKey Index uint16_t net_idx NetKey Index uint16_t dst struct esp_ble_mesh_cfg_heartbeat_sub_set_t Parameters of Config Model Heartbeat Subscription Set. struct esp_ble_mesh_cfg_beacon_status_cb_t Parameter of Config Beacon Status Public Members uint8_t beacon Secure Network Beacon state value uint8_t beacon Secure Network Beacon state value uint8_t beacon struct esp_ble_mesh_cfg_comp_data_status_cb_t Parameters of Config Composition Data Status struct esp_ble_mesh_cfg_default_ttl_status_cb_t Parameter of Config Default TTL Status Public Members uint8_t default_ttl Default TTL state value uint8_t default_ttl Default TTL state value uint8_t default_ttl struct esp_ble_mesh_cfg_gatt_proxy_status_cb_t Parameter of Config GATT Proxy Status Public Members uint8_t gatt_proxy GATT Proxy state value uint8_t gatt_proxy GATT Proxy state value uint8_t gatt_proxy struct esp_ble_mesh_cfg_relay_status_cb_t Parameters of Config Relay Status struct esp_ble_mesh_cfg_model_pub_status_cb_t Parameters of Config Model Publication Status Public Members uint8_t status Status Code for the request message uint8_t status Status Code for the request message uint16_t element_addr Address of the element uint16_t element_addr Address of the element uint16_t publish_addr Value of the publish address uint16_t publish_addr Value of the publish address uint16_t app_idx Index of the application key uint16_t app_idx Index of the application key bool cred_flag Value of the Friendship Credential Flag bool cred_flag Value of the Friendship Credential Flag uint8_t ttl Default TTL value for the outgoing messages uint8_t ttl Default TTL value for the outgoing messages uint8_t period Period for periodic status publishing uint8_t period Period for periodic status publishing uint8_t transmit Number of retransmissions and number of 50-millisecond steps between retransmissions uint8_t transmit Number of retransmissions and number of 50-millisecond steps between retransmissions uint16_t company_id Company ID uint16_t company_id Company ID uint16_t model_id Model ID uint16_t model_id Model ID uint8_t status struct esp_ble_mesh_cfg_model_sub_status_cb_t Parameters of Config Model Subscription Status struct esp_ble_mesh_cfg_net_key_status_cb_t Parameters of Config NetKey Status struct esp_ble_mesh_cfg_app_key_status_cb_t Parameters of Config AppKey Status struct esp_ble_mesh_cfg_mod_app_status_cb_t Parameters of Config Model App Status struct esp_ble_mesh_cfg_friend_status_cb_t Parameter of Config Friend Status Public Members uint8_t friend_state Friend state value uint8_t friend_state Friend state value uint8_t friend_state struct esp_ble_mesh_cfg_hb_pub_status_cb_t Parameters of Config Heartbeat Publication Status Public Members uint8_t status Status Code for the request message uint8_t status Status Code for the request message uint16_t dst Destination address for Heartbeat messages uint16_t dst Destination address for Heartbeat messages uint8_t count Number of Heartbeat messages remaining to be sent uint8_t count Number of Heartbeat messages remaining to be sent uint8_t period Period for sending Heartbeat messages uint8_t period Period for sending Heartbeat messages uint8_t ttl TTL to be used when sending Heartbeat messages uint8_t ttl TTL to be used when sending Heartbeat messages uint16_t features Features that trigger Heartbeat messages when changed uint16_t features Features that trigger Heartbeat messages when changed uint16_t net_idx Index of the NetKey uint16_t net_idx Index of the NetKey uint8_t status struct esp_ble_mesh_cfg_hb_sub_status_cb_t Parameters of Config Heartbeat Subscription Status Public Members uint8_t status Status Code for the request message uint8_t status Status Code for the request message uint16_t src Source address for Heartbeat messages uint16_t src Source address for Heartbeat messages uint16_t dst Destination address for Heartbeat messages uint16_t dst Destination address for Heartbeat messages uint8_t period Remaining Period for processing Heartbeat messages uint8_t period Remaining Period for processing Heartbeat messages uint8_t count Number of Heartbeat messages received uint8_t count Number of Heartbeat messages received uint8_t min_hops Minimum hops when receiving Heartbeat messages uint8_t min_hops Minimum hops when receiving Heartbeat messages uint8_t max_hops Maximum hops when receiving Heartbeat messages uint8_t max_hops Maximum hops when receiving Heartbeat messages uint8_t status struct esp_ble_mesh_cfg_net_trans_status_cb_t Parameters of Config Network Transmit Status struct esp_ble_mesh_cfg_model_sub_list_cb_t Parameters of Config SIG/Vendor Subscription List struct esp_ble_mesh_cfg_net_key_list_cb_t Parameter of Config NetKey List Public Members struct net_buf_simple *net_idx A list of NetKey Indexes known to the node struct net_buf_simple *net_idx A list of NetKey Indexes known to the node struct net_buf_simple *net_idx struct esp_ble_mesh_cfg_app_key_list_cb_t Parameters of Config AppKey List struct esp_ble_mesh_cfg_node_id_status_cb_t Parameters of Config Node Identity Status struct esp_ble_mesh_cfg_model_app_list_cb_t Parameters of Config SIG/Vendor Model App List struct esp_ble_mesh_cfg_kr_phase_status_cb_t Parameters of Config Key Refresh Phase Status struct esp_ble_mesh_cfg_lpn_pollto_status_cb_t Parameters of Config Low Power Node PollTimeout Status struct esp_ble_mesh_cfg_client_cb_param_t Configuration Client Model callback parameters Public Members int error_code Appropriate error code int error_code Appropriate error code esp_ble_mesh_client_common_param_t *params The client common parameters esp_ble_mesh_client_common_param_t *params The client common parameters esp_ble_mesh_cfg_client_common_cb_param_t status_cb The config status message callback values esp_ble_mesh_cfg_client_common_cb_param_t status_cb The config status message callback values int error_code struct esp_ble_mesh_state_change_cfg_mod_pub_set_t Configuration Server model related context. Parameters of Config Model Publication Set Public Members uint16_t element_addr Element Address uint16_t element_addr Element Address uint16_t pub_addr Publish Address uint16_t pub_addr Publish Address uint16_t app_idx AppKey Index uint16_t app_idx AppKey Index bool cred_flag Friendship Credential Flag bool cred_flag Friendship Credential Flag uint8_t pub_ttl Publish TTL uint8_t pub_ttl Publish TTL uint8_t pub_period Publish Period uint8_t pub_period Publish Period uint8_t pub_retransmit Publish Retransmit uint8_t pub_retransmit Publish Retransmit uint16_t company_id Company ID uint16_t company_id Company ID uint16_t model_id Model ID uint16_t model_id Model ID uint16_t element_addr struct esp_ble_mesh_state_change_cfg_mod_pub_va_set_t Parameters of Config Model Publication Virtual Address Set Public Members uint16_t element_addr Element Address uint16_t element_addr Element Address uint8_t label_uuid[16] Label UUID uint8_t label_uuid[16] Label UUID uint16_t app_idx AppKey Index uint16_t app_idx AppKey Index bool cred_flag Friendship Credential Flag bool cred_flag Friendship Credential Flag uint8_t pub_ttl Publish TTL uint8_t pub_ttl Publish TTL uint8_t pub_period Publish Period uint8_t pub_period Publish Period uint8_t pub_retransmit Publish Retransmit uint8_t pub_retransmit Publish Retransmit uint16_t company_id Company ID uint16_t company_id Company ID uint16_t model_id Model ID uint16_t model_id Model ID uint16_t element_addr struct esp_ble_mesh_state_change_cfg_model_sub_add_t Parameters of Config Model Subscription Add struct esp_ble_mesh_state_change_cfg_model_sub_delete_t Parameters of Config Model Subscription Delete struct esp_ble_mesh_state_change_cfg_netkey_add_t Parameters of Config NetKey Add struct esp_ble_mesh_state_change_cfg_netkey_update_t Parameters of Config NetKey Update struct esp_ble_mesh_state_change_cfg_netkey_delete_t Parameter of Config NetKey Delete struct esp_ble_mesh_state_change_cfg_appkey_add_t Parameters of Config AppKey Add struct esp_ble_mesh_state_change_cfg_appkey_update_t Parameters of Config AppKey Update struct esp_ble_mesh_state_change_cfg_appkey_delete_t Parameters of Config AppKey Delete struct esp_ble_mesh_state_change_cfg_model_app_bind_t Parameters of Config Model App Bind struct esp_ble_mesh_state_change_cfg_model_app_unbind_t Parameters of Config Model App Unbind struct esp_ble_mesh_state_change_cfg_kr_phase_set_t Parameters of Config Key Refresh Phase Set struct esp_ble_mesh_cfg_server_cb_param_t Configuration Server model callback parameters Public Members esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_cfg_server_cb_value_t value Value of the received configuration messages esp_ble_mesh_cfg_server_cb_value_t value Value of the received configuration messages esp_ble_mesh_model_t *model Macros ESP_BLE_MESH_MODEL_CFG_SRV(srv_data) Define a new Config Server Model. Note The Config Server Model can only be included by a Primary Element. Parameters srv_data -- Pointer to a unique Config Server Model user_data. srv_data -- Pointer to a unique Config Server Model user_data. srv_data -- Pointer to a unique Config Server Model user_data. Returns New Config Server Model instance. Parameters srv_data -- Pointer to a unique Config Server Model user_data. Returns New Config Server Model instance. ESP_BLE_MESH_MODEL_CFG_CLI(cli_data) Define a new Config Client Model. Note The Config Client Model can only be included by a Primary Element. Parameters cli_data -- Pointer to a unique struct esp_ble_mesh_client_t. cli_data -- Pointer to a unique struct esp_ble_mesh_client_t. cli_data -- Pointer to a unique struct esp_ble_mesh_client_t. Returns New Config Client Model instance. Parameters cli_data -- Pointer to a unique struct esp_ble_mesh_client_t. Returns New Config Client Model instance. Type Definitions typedef void (*esp_ble_mesh_cfg_client_cb_t)(esp_ble_mesh_cfg_client_cb_event_t event, esp_ble_mesh_cfg_client_cb_param_t *param) Bluetooth Mesh Config Client and Server Model functions. Configuration Client Model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter typedef void (*esp_ble_mesh_cfg_server_cb_t)(esp_ble_mesh_cfg_server_cb_event_t event, esp_ble_mesh_cfg_server_cb_param_t *param) Configuration Server Model callback function type. Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter Enumerations enum esp_ble_mesh_cfg_client_cb_event_t This enum value is the event of Configuration Client Model Values: enumerator ESP_BLE_MESH_CFG_CLIENT_GET_STATE_EVT enumerator ESP_BLE_MESH_CFG_CLIENT_GET_STATE_EVT enumerator ESP_BLE_MESH_CFG_CLIENT_SET_STATE_EVT enumerator ESP_BLE_MESH_CFG_CLIENT_SET_STATE_EVT enumerator ESP_BLE_MESH_CFG_CLIENT_PUBLISH_EVT enumerator ESP_BLE_MESH_CFG_CLIENT_PUBLISH_EVT enumerator ESP_BLE_MESH_CFG_CLIENT_TIMEOUT_EVT enumerator ESP_BLE_MESH_CFG_CLIENT_TIMEOUT_EVT enumerator ESP_BLE_MESH_CFG_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_CFG_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_CFG_CLIENT_GET_STATE_EVT Health Client/Server Models Header File components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_health_model_api.h This header file can be included with: #include "esp_ble_mesh_health_model_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_health_client_callback(esp_ble_mesh_health_client_cb_t callback) Register BLE Mesh Health Model callback, the callback will report Health Client & Server Model events. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_register_health_server_callback(esp_ble_mesh_health_server_cb_t callback) Register BLE Mesh Health Server Model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_health_client_get_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_health_client_get_state_t *get_state) This function is called to get the Health Server states using the Health Client Model get messages. Note If you want to find the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_opcode_health_client_get_t in esp_ble_mesh_defs.h Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_health_client_set_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_health_client_set_state_t *set_state) This function is called to set the Health Server states using the Health Client Model set messages. Note If you want to find the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_opcode_health_client_set_t in esp_ble_mesh_defs.h Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_health_server_fault_update(esp_ble_mesh_elem_t *element) This function is called by the Health Server Model to update the context of its Health Current status. Parameters element -- [in] The element to which the Health Server Model belongs. Returns ESP_OK on success or error code otherwise. Parameters element -- [in] The element to which the Health Server Model belongs. Returns ESP_OK on success or error code otherwise. Unions union esp_ble_mesh_health_client_get_state_t #include <esp_ble_mesh_health_model_api.h> For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_GET ESP_BLE_MESH_MODEL_OP_ATTENTION_GET ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_GET the get_state parameter in the esp_ble_mesh_health_client_get_state function should not be set to NULL. Public Members esp_ble_mesh_health_fault_get_t fault_get For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_GET. esp_ble_mesh_health_fault_get_t fault_get For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_GET. esp_ble_mesh_health_fault_get_t fault_get union esp_ble_mesh_health_client_set_state_t #include <esp_ble_mesh_health_model_api.h> For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR_UNACK ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST_UNACK ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET_UNACK ESP_BLE_MESH_MODEL_OP_ATTENTION_SET ESP_BLE_MESH_MODEL_OP_ATTENTION_SET_UNACK the set_state parameter in the esp_ble_mesh_health_client_set_state function should not be set to NULL. Public Members esp_ble_mesh_health_attention_set_t attention_set For ESP_BLE_MESH_MODEL_OP_ATTENTION_SET or ESP_BLE_MESH_MODEL_OP_ATTENTION_SET_UNACK. esp_ble_mesh_health_attention_set_t attention_set For ESP_BLE_MESH_MODEL_OP_ATTENTION_SET or ESP_BLE_MESH_MODEL_OP_ATTENTION_SET_UNACK. esp_ble_mesh_health_period_set_t period_set For ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET or ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET_UNACK. esp_ble_mesh_health_period_set_t period_set For ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET or ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET_UNACK. esp_ble_mesh_health_fault_test_t fault_test For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST or ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST_UNACK. esp_ble_mesh_health_fault_test_t fault_test For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST or ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST_UNACK. esp_ble_mesh_health_fault_clear_t fault_clear For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR or ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR_UNACK. esp_ble_mesh_health_fault_clear_t fault_clear For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR or ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR_UNACK. esp_ble_mesh_health_attention_set_t attention_set union esp_ble_mesh_health_client_common_cb_param_t #include <esp_ble_mesh_health_model_api.h> Health Client Model received message union. Public Members esp_ble_mesh_health_current_status_cb_t current_status The health current status value esp_ble_mesh_health_current_status_cb_t current_status The health current status value esp_ble_mesh_health_fault_status_cb_t fault_status The health fault status value esp_ble_mesh_health_fault_status_cb_t fault_status The health fault status value esp_ble_mesh_health_period_status_cb_t period_status The health period status value esp_ble_mesh_health_period_status_cb_t period_status The health period status value esp_ble_mesh_health_attention_status_cb_t attention_status The health attention status value esp_ble_mesh_health_attention_status_cb_t attention_status The health attention status value esp_ble_mesh_health_current_status_cb_t current_status union esp_ble_mesh_health_server_cb_param_t #include <esp_ble_mesh_health_model_api.h> Health Server Model callback parameters union. Public Members esp_ble_mesh_health_fault_update_comp_cb_t fault_update_comp ESP_BLE_MESH_HEALTH_SERVER_FAULT_UPDATE_COMP_EVT esp_ble_mesh_health_fault_update_comp_cb_t fault_update_comp ESP_BLE_MESH_HEALTH_SERVER_FAULT_UPDATE_COMP_EVT esp_ble_mesh_health_fault_clear_cb_t fault_clear ESP_BLE_MESH_HEALTH_SERVER_FAULT_CLEAR_EVT esp_ble_mesh_health_fault_clear_cb_t fault_clear ESP_BLE_MESH_HEALTH_SERVER_FAULT_CLEAR_EVT esp_ble_mesh_health_fault_test_cb_t fault_test ESP_BLE_MESH_HEALTH_SERVER_FAULT_TEST_EVT esp_ble_mesh_health_fault_test_cb_t fault_test ESP_BLE_MESH_HEALTH_SERVER_FAULT_TEST_EVT esp_ble_mesh_health_attention_on_cb_t attention_on ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_ON_EVT esp_ble_mesh_health_attention_on_cb_t attention_on ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_ON_EVT esp_ble_mesh_health_attention_off_cb_t attention_off ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_OFF_EVT esp_ble_mesh_health_attention_off_cb_t attention_off ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_OFF_EVT esp_ble_mesh_health_fault_update_comp_cb_t fault_update_comp Structures struct esp_ble_mesh_health_srv_cb_t ESP BLE Mesh Health Server callback Public Members esp_ble_mesh_cb_t fault_clear Clear health registered faults. Initialized by the stack. esp_ble_mesh_cb_t fault_clear Clear health registered faults. Initialized by the stack. esp_ble_mesh_cb_t fault_test Run a specific health test. Initialized by the stack. esp_ble_mesh_cb_t fault_test Run a specific health test. Initialized by the stack. esp_ble_mesh_cb_t attention_on Health attention on callback. Initialized by the stack. esp_ble_mesh_cb_t attention_on Health attention on callback. Initialized by the stack. esp_ble_mesh_cb_t attention_off Health attention off callback. Initialized by the stack. esp_ble_mesh_cb_t attention_off Health attention off callback. Initialized by the stack. esp_ble_mesh_cb_t fault_clear struct esp_ble_mesh_health_test_t ESP BLE Mesh Health Server test Context Public Members uint8_t id_count Number of Health self-test ID uint8_t id_count Number of Health self-test ID const uint8_t *test_ids Array of Health self-test IDs const uint8_t *test_ids Array of Health self-test IDs uint16_t company_id Company ID used to identify the Health Fault state uint16_t company_id Company ID used to identify the Health Fault state uint8_t prev_test_id Current test ID of the health fault test uint8_t prev_test_id Current test ID of the health fault test uint8_t current_faults[ESP_BLE_MESH_HEALTH_FAULT_ARRAY_SIZE] Array of current faults uint8_t current_faults[ESP_BLE_MESH_HEALTH_FAULT_ARRAY_SIZE] Array of current faults uint8_t registered_faults[ESP_BLE_MESH_HEALTH_FAULT_ARRAY_SIZE] Array of registered faults uint8_t registered_faults[ESP_BLE_MESH_HEALTH_FAULT_ARRAY_SIZE] Array of registered faults uint8_t id_count struct esp_ble_mesh_health_srv_t ESP BLE Mesh Health Server Model Context Public Members esp_ble_mesh_model_t *model Pointer to Health Server Model esp_ble_mesh_model_t *model Pointer to Health Server Model esp_ble_mesh_health_srv_cb_t health_cb Health callback struct esp_ble_mesh_health_srv_cb_t health_cb Health callback struct struct k_delayed_work attention_timer Attention Timer state struct k_delayed_work attention_timer Attention Timer state bool attention_timer_start Attention Timer start flag bool attention_timer_start Attention Timer start flag esp_ble_mesh_health_test_t health_test Health Server fault test esp_ble_mesh_health_test_t health_test Health Server fault test esp_ble_mesh_model_t *model struct esp_ble_mesh_health_fault_get_t Parameter of Health Fault Get Public Members uint16_t company_id Bluetooth assigned 16-bit Company ID uint16_t company_id Bluetooth assigned 16-bit Company ID uint16_t company_id struct esp_ble_mesh_health_attention_set_t Parameter of Health Attention Set Public Members uint8_t attention Value of the Attention Timer state uint8_t attention Value of the Attention Timer state uint8_t attention struct esp_ble_mesh_health_period_set_t Parameter of Health Period Set Public Members uint8_t fast_period_divisor Divider for the Publish Period uint8_t fast_period_divisor Divider for the Publish Period uint8_t fast_period_divisor struct esp_ble_mesh_health_fault_test_t Parameter of Health Fault Test struct esp_ble_mesh_health_fault_clear_t Parameter of Health Fault Clear Public Members uint16_t company_id Bluetooth assigned 16-bit Company ID uint16_t company_id Bluetooth assigned 16-bit Company ID uint16_t company_id struct esp_ble_mesh_health_current_status_cb_t Parameters of Health Current Status struct esp_ble_mesh_health_fault_status_cb_t Parameters of Health Fault Status struct esp_ble_mesh_health_period_status_cb_t Parameter of Health Period Status Public Members uint8_t fast_period_divisor Divider for the Publish Period uint8_t fast_period_divisor Divider for the Publish Period uint8_t fast_period_divisor struct esp_ble_mesh_health_attention_status_cb_t Parameter of Health Attention Status Public Members uint8_t attention Value of the Attention Timer state uint8_t attention Value of the Attention Timer state uint8_t attention struct esp_ble_mesh_health_client_cb_param_t Health Client Model callback parameters Public Members int error_code Appropriate error code int error_code Appropriate error code esp_ble_mesh_client_common_param_t *params The client common parameters. esp_ble_mesh_client_common_param_t *params The client common parameters. esp_ble_mesh_health_client_common_cb_param_t status_cb The health message status callback values esp_ble_mesh_health_client_common_cb_param_t status_cb The health message status callback values int error_code struct esp_ble_mesh_health_fault_update_comp_cb_t Parameter of publishing Health Current Status completion event Public Members int error_code The result of publishing Health Current Status int error_code The result of publishing Health Current Status esp_ble_mesh_elem_t *element Pointer to the element which contains the Health Server Model esp_ble_mesh_elem_t *element Pointer to the element which contains the Health Server Model int error_code struct esp_ble_mesh_health_fault_clear_cb_t Parameters of Health Fault Clear event Public Members esp_ble_mesh_model_t *model Pointer to the Health Server Model esp_ble_mesh_model_t *model Pointer to the Health Server Model uint16_t company_id Bluetooth assigned 16-bit Company ID uint16_t company_id Bluetooth assigned 16-bit Company ID esp_ble_mesh_model_t *model struct esp_ble_mesh_health_fault_test_cb_t Parameters of Health Fault Test event Public Members esp_ble_mesh_model_t *model Pointer to the Health Server Model esp_ble_mesh_model_t *model Pointer to the Health Server Model uint8_t test_id ID of a specific test to be performed uint8_t test_id ID of a specific test to be performed uint16_t company_id Bluetooth assigned 16-bit Company ID uint16_t company_id Bluetooth assigned 16-bit Company ID esp_ble_mesh_model_t *model struct esp_ble_mesh_health_attention_on_cb_t Parameter of Health Attention On event Public Members esp_ble_mesh_model_t *model Pointer to the Health Server Model esp_ble_mesh_model_t *model Pointer to the Health Server Model uint8_t time Duration of attention timer on (in seconds) uint8_t time Duration of attention timer on (in seconds) esp_ble_mesh_model_t *model struct esp_ble_mesh_health_attention_off_cb_t Parameter of Health Attention Off event Public Members esp_ble_mesh_model_t *model Pointer to the Health Server Model esp_ble_mesh_model_t *model Pointer to the Health Server Model esp_ble_mesh_model_t *model Macros ESP_BLE_MESH_MODEL_HEALTH_SRV(srv, pub) Define a new Health Server Model. Note The Health Server Model can only be included by a Primary Element. Parameters srv -- Pointer to the unique struct esp_ble_mesh_health_srv_t. pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv -- Pointer to the unique struct esp_ble_mesh_health_srv_t. pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv -- Pointer to the unique struct esp_ble_mesh_health_srv_t. Returns New Health Server Model instance. Parameters srv -- Pointer to the unique struct esp_ble_mesh_health_srv_t. pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Health Server Model instance. ESP_BLE_MESH_MODEL_HEALTH_CLI(cli_data) Define a new Health Client Model. Note This API needs to be called for each element on which the application needs to have a Health Client Model. Parameters cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Health Client Model instance. Parameters cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Health Client Model instance. ESP_BLE_MESH_HEALTH_PUB_DEFINE(_name, _max, _role) A helper to define a health publication context Parameters _name -- Name given to the publication context variable. _max -- Maximum number of faults the element can have. _role -- Role of the device which contains the model. _name -- Name given to the publication context variable. _max -- Maximum number of faults the element can have. _role -- Role of the device which contains the model. _name -- Name given to the publication context variable. Parameters _name -- Name given to the publication context variable. _max -- Maximum number of faults the element can have. _role -- Role of the device which contains the model. ESP_BLE_MESH_HEALTH_STANDARD_TEST SIG identifier of Health Fault Test. 0x01 ~ 0xFF: Vendor Specific Test. ESP_BLE_MESH_NO_FAULT Fault values of Health Fault Test. 0x33 ~ 0x7F: Reserved for Future Use. 0x80 ~ 0xFF: Vendor Specific Warning/Error. ESP_BLE_MESH_BATTERY_LOW_WARNING ESP_BLE_MESH_BATTERY_LOW_ERROR ESP_BLE_MESH_SUPPLY_VOLTAGE_TOO_LOW_WARNING ESP_BLE_MESH_SUPPLY_VOLTAGE_TOO_LOW_ERROR ESP_BLE_MESH_SUPPLY_VOLTAGE_TOO_HIGH_WARNING ESP_BLE_MESH_SUPPLY_VOLTAGE_TOO_HIGH_ERROR ESP_BLE_MESH_POWER_SUPPLY_INTERRUPTED_WARNING ESP_BLE_MESH_POWER_SUPPLY_INTERRUPTED_ERROR ESP_BLE_MESH_NO_LOAD_WARNING ESP_BLE_MESH_NO_LOAD_ERROR ESP_BLE_MESH_OVERLOAD_WARNING ESP_BLE_MESH_OVERLOAD_ERROR ESP_BLE_MESH_OVERHEAT_WARNING ESP_BLE_MESH_OVERHEAT_ERROR ESP_BLE_MESH_CONDENSATION_WARNING ESP_BLE_MESH_CONDENSATION_ERROR ESP_BLE_MESH_VIBRATION_WARNING ESP_BLE_MESH_VIBRATION_ERROR ESP_BLE_MESH_CONFIGURATION_WARNING ESP_BLE_MESH_CONFIGURATION_ERROR ESP_BLE_MESH_ELEMENT_NOT_CALIBRATED_WARNING ESP_BLE_MESH_ELEMENT_NOT_CALIBRATED_ERROR ESP_BLE_MESH_MEMORY_WARNING ESP_BLE_MESH_MEMORY_ERROR ESP_BLE_MESH_SELF_TEST_WARNING ESP_BLE_MESH_SELF_TEST_ERROR ESP_BLE_MESH_INPUT_TOO_LOW_WARNING ESP_BLE_MESH_INPUT_TOO_LOW_ERROR ESP_BLE_MESH_INPUT_TOO_HIGH_WARNING ESP_BLE_MESH_INPUT_TOO_HIGH_ERROR ESP_BLE_MESH_INPUT_NO_CHANGE_WARNING ESP_BLE_MESH_INPUT_NO_CHANGE_ERROR ESP_BLE_MESH_ACTUATOR_BLOCKED_WARNING ESP_BLE_MESH_ACTUATOR_BLOCKED_ERROR ESP_BLE_MESH_HOUSING_OPENED_WARNING ESP_BLE_MESH_HOUSING_OPENED_ERROR ESP_BLE_MESH_TAMPER_WARNING ESP_BLE_MESH_TAMPER_ERROR ESP_BLE_MESH_DEVICE_MOVED_WARNING ESP_BLE_MESH_DEVICE_MOVED_ERROR ESP_BLE_MESH_DEVICE_DROPPED_WARNING ESP_BLE_MESH_DEVICE_DROPPED_ERROR ESP_BLE_MESH_OVERFLOW_WARNING ESP_BLE_MESH_OVERFLOW_ERROR ESP_BLE_MESH_EMPTY_WARNING ESP_BLE_MESH_EMPTY_ERROR ESP_BLE_MESH_INTERNAL_BUS_WARNING ESP_BLE_MESH_INTERNAL_BUS_ERROR ESP_BLE_MESH_MECHANISM_JAMMED_WARNING ESP_BLE_MESH_MECHANISM_JAMMED_ERROR ESP_BLE_MESH_HEALTH_FAULT_ARRAY_SIZE Type Definitions typedef void (*esp_ble_mesh_health_client_cb_t)(esp_ble_mesh_health_client_cb_event_t event, esp_ble_mesh_health_client_cb_param_t *param) Bluetooth Mesh Health Client and Server Model function. Health Client Model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter typedef void (*esp_ble_mesh_health_server_cb_t)(esp_ble_mesh_health_server_cb_event_t event, esp_ble_mesh_health_server_cb_param_t *param) Health Server Model callback function type. Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter Enumerations enum esp_ble_mesh_health_client_cb_event_t This enum value is the event of Health Client Model Values: enumerator ESP_BLE_MESH_HEALTH_CLIENT_GET_STATE_EVT enumerator ESP_BLE_MESH_HEALTH_CLIENT_GET_STATE_EVT enumerator ESP_BLE_MESH_HEALTH_CLIENT_SET_STATE_EVT enumerator ESP_BLE_MESH_HEALTH_CLIENT_SET_STATE_EVT enumerator ESP_BLE_MESH_HEALTH_CLIENT_PUBLISH_EVT enumerator ESP_BLE_MESH_HEALTH_CLIENT_PUBLISH_EVT enumerator ESP_BLE_MESH_HEALTH_CLIENT_TIMEOUT_EVT enumerator ESP_BLE_MESH_HEALTH_CLIENT_TIMEOUT_EVT enumerator ESP_BLE_MESH_HEALTH_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_HEALTH_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_HEALTH_CLIENT_GET_STATE_EVT enum esp_ble_mesh_health_server_cb_event_t This enum value is the event of Health Server Model Values: enumerator ESP_BLE_MESH_HEALTH_SERVER_FAULT_UPDATE_COMP_EVT enumerator ESP_BLE_MESH_HEALTH_SERVER_FAULT_UPDATE_COMP_EVT enumerator ESP_BLE_MESH_HEALTH_SERVER_FAULT_CLEAR_EVT enumerator ESP_BLE_MESH_HEALTH_SERVER_FAULT_CLEAR_EVT enumerator ESP_BLE_MESH_HEALTH_SERVER_FAULT_TEST_EVT enumerator ESP_BLE_MESH_HEALTH_SERVER_FAULT_TEST_EVT enumerator ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_ON_EVT enumerator ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_ON_EVT enumerator ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_OFF_EVT enumerator ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_OFF_EVT enumerator ESP_BLE_MESH_HEALTH_SERVER_EVT_MAX enumerator ESP_BLE_MESH_HEALTH_SERVER_EVT_MAX enumerator ESP_BLE_MESH_HEALTH_SERVER_FAULT_UPDATE_COMP_EVT Generic Client/Server Models Header File components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_generic_model_api.h This header file can be included with: #include "esp_ble_mesh_generic_model_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_generic_client_callback(esp_ble_mesh_generic_client_cb_t callback) Register BLE Mesh Generic Client Model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_generic_client_get_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_generic_client_get_state_t *get_state) Get the value of Generic Server Model states using the Generic Client Model get messages. Note If you want to find the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_generic_message_opcode_t in esp_ble_mesh_defs.h Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to generic get message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to generic get message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to generic get message value. Shall not be set to NULL. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_generic_client_set_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_generic_client_set_state_t *set_state) Set the value of Generic Server Model states using the Generic Client Model set messages. Note If you want to find the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_generic_message_opcode_t in esp_ble_mesh_defs.h Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to generic set message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to generic set message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to generic set message value. Shall not be set to NULL. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_register_generic_server_callback(esp_ble_mesh_generic_server_cb_t callback) Register BLE Mesh Generic Server Model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Unions union esp_ble_mesh_generic_client_get_state_t #include <esp_ble_mesh_generic_model_api.h> Generic Client Model get message union. Public Members esp_ble_mesh_gen_user_property_get_t user_property_get For ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_GET esp_ble_mesh_gen_user_property_get_t user_property_get For ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_GET esp_ble_mesh_gen_admin_property_get_t admin_property_get For ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_GET esp_ble_mesh_gen_admin_property_get_t admin_property_get For ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_GET esp_ble_mesh_gen_manufacturer_property_get_t manufacturer_property_get For ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET esp_ble_mesh_gen_manufacturer_property_get_t manufacturer_property_get For ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET esp_ble_mesh_gen_client_properties_get_t client_properties_get For ESP_BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_GET esp_ble_mesh_gen_client_properties_get_t client_properties_get For ESP_BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_GET esp_ble_mesh_gen_user_property_get_t user_property_get union esp_ble_mesh_generic_client_set_state_t #include <esp_ble_mesh_generic_model_api.h> Generic Client Model set message union. Public Members esp_ble_mesh_gen_onoff_set_t onoff_set For ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_SET & ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_SET_UNACK esp_ble_mesh_gen_onoff_set_t onoff_set For ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_SET & ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_SET_UNACK esp_ble_mesh_gen_level_set_t level_set For ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_SET & ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_SET_UNACK esp_ble_mesh_gen_level_set_t level_set For ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_SET & ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_SET_UNACK esp_ble_mesh_gen_delta_set_t delta_set For ESP_BLE_MESH_MODEL_OP_GEN_DELTA_SET & ESP_BLE_MESH_MODEL_OP_GEN_DELTA_SET_UNACK esp_ble_mesh_gen_delta_set_t delta_set For ESP_BLE_MESH_MODEL_OP_GEN_DELTA_SET & ESP_BLE_MESH_MODEL_OP_GEN_DELTA_SET_UNACK esp_ble_mesh_gen_move_set_t move_set For ESP_BLE_MESH_MODEL_OP_GEN_MOVE_SET & ESP_BLE_MESH_MODEL_OP_GEN_MOVE_SET_UNACK esp_ble_mesh_gen_move_set_t move_set For ESP_BLE_MESH_MODEL_OP_GEN_MOVE_SET & ESP_BLE_MESH_MODEL_OP_GEN_MOVE_SET_UNACK esp_ble_mesh_gen_def_trans_time_set_t def_trans_time_set For ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET & ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET_UNACK esp_ble_mesh_gen_def_trans_time_set_t def_trans_time_set For ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET & ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET_UNACK esp_ble_mesh_gen_onpowerup_set_t power_set For ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET & ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET_UNACK esp_ble_mesh_gen_onpowerup_set_t power_set For ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET & ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET_UNACK esp_ble_mesh_gen_power_level_set_t power_level_set For ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET & ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET_UNACK esp_ble_mesh_gen_power_level_set_t power_level_set For ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET & ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET_UNACK esp_ble_mesh_gen_power_default_set_t power_default_set For ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET & ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET_UNACK esp_ble_mesh_gen_power_default_set_t power_default_set For ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET & ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET_UNACK esp_ble_mesh_gen_power_range_set_t power_range_set For ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET & ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET_UNACK esp_ble_mesh_gen_power_range_set_t power_range_set For ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET & ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET_UNACK esp_ble_mesh_gen_loc_global_set_t loc_global_set For ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET & ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET_UNACK esp_ble_mesh_gen_loc_global_set_t loc_global_set For ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET & ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET_UNACK esp_ble_mesh_gen_loc_local_set_t loc_local_set For ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET & ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET_UNACK esp_ble_mesh_gen_loc_local_set_t loc_local_set For ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET & ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET_UNACK esp_ble_mesh_gen_user_property_set_t user_property_set For ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET & ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET_UNACK esp_ble_mesh_gen_user_property_set_t user_property_set For ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET & ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET_UNACK esp_ble_mesh_gen_admin_property_set_t admin_property_set For ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET & ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET_UNACK esp_ble_mesh_gen_admin_property_set_t admin_property_set For ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET & ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET_UNACK esp_ble_mesh_gen_manufacturer_property_set_t manufacturer_property_set For ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET & ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET_UNACK esp_ble_mesh_gen_manufacturer_property_set_t manufacturer_property_set For ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET & ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET_UNACK esp_ble_mesh_gen_onoff_set_t onoff_set union esp_ble_mesh_gen_client_status_cb_t #include <esp_ble_mesh_generic_model_api.h> Generic Client Model received message union. Public Members esp_ble_mesh_gen_onoff_status_cb_t onoff_status For ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_STATUS esp_ble_mesh_gen_onoff_status_cb_t onoff_status For ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_STATUS esp_ble_mesh_gen_level_status_cb_t level_status For ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_STATUS esp_ble_mesh_gen_level_status_cb_t level_status For ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_STATUS esp_ble_mesh_gen_def_trans_time_status_cb_t def_trans_time_status For ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_STATUS esp_ble_mesh_gen_def_trans_time_status_cb_t def_trans_time_status For ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_STATUS esp_ble_mesh_gen_onpowerup_status_cb_t onpowerup_status For ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_STATUS esp_ble_mesh_gen_onpowerup_status_cb_t onpowerup_status For ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_STATUS esp_ble_mesh_gen_power_level_status_cb_t power_level_status For ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_STATUS esp_ble_mesh_gen_power_level_status_cb_t power_level_status For ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_STATUS esp_ble_mesh_gen_power_last_status_cb_t power_last_status For ESP_BLE_MESH_MODEL_OP_GEN_POWER_LAST_STATUS esp_ble_mesh_gen_power_last_status_cb_t power_last_status For ESP_BLE_MESH_MODEL_OP_GEN_POWER_LAST_STATUS esp_ble_mesh_gen_power_default_status_cb_t power_default_status For ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_STATUS esp_ble_mesh_gen_power_default_status_cb_t power_default_status For ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_STATUS esp_ble_mesh_gen_power_range_status_cb_t power_range_status For ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_STATUS esp_ble_mesh_gen_power_range_status_cb_t power_range_status For ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_STATUS esp_ble_mesh_gen_battery_status_cb_t battery_status For ESP_BLE_MESH_MODEL_OP_GEN_BATTERY_STATUS esp_ble_mesh_gen_battery_status_cb_t battery_status For ESP_BLE_MESH_MODEL_OP_GEN_BATTERY_STATUS esp_ble_mesh_gen_loc_global_status_cb_t location_global_status For ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_STATUS esp_ble_mesh_gen_loc_global_status_cb_t location_global_status For ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_STATUS esp_ble_mesh_gen_loc_local_status_cb_t location_local_status ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_STATUS esp_ble_mesh_gen_loc_local_status_cb_t location_local_status ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_STATUS esp_ble_mesh_gen_user_properties_status_cb_t user_properties_status ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTIES_STATUS esp_ble_mesh_gen_user_properties_status_cb_t user_properties_status ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTIES_STATUS esp_ble_mesh_gen_user_property_status_cb_t user_property_status ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_STATUS esp_ble_mesh_gen_user_property_status_cb_t user_property_status ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_STATUS esp_ble_mesh_gen_admin_properties_status_cb_t admin_properties_status ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTIES_STATUS esp_ble_mesh_gen_admin_properties_status_cb_t admin_properties_status ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTIES_STATUS esp_ble_mesh_gen_admin_property_status_cb_t admin_property_status ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_STATUS esp_ble_mesh_gen_admin_property_status_cb_t admin_property_status ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_STATUS esp_ble_mesh_gen_manufacturer_properties_status_cb_t manufacturer_properties_status ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTIES_STATUS esp_ble_mesh_gen_manufacturer_properties_status_cb_t manufacturer_properties_status ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTIES_STATUS esp_ble_mesh_gen_manufacturer_property_status_cb_t manufacturer_property_status ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_STATUS esp_ble_mesh_gen_manufacturer_property_status_cb_t manufacturer_property_status ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_STATUS esp_ble_mesh_gen_client_properties_status_cb_t client_properties_status ESP_BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_STATUS esp_ble_mesh_gen_client_properties_status_cb_t client_properties_status ESP_BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_STATUS esp_ble_mesh_gen_onoff_status_cb_t onoff_status union esp_ble_mesh_generic_server_state_change_t #include <esp_ble_mesh_generic_model_api.h> Generic Server Model state change value union. Public Members esp_ble_mesh_state_change_gen_onoff_set_t onoff_set The recv_op in ctx can be used to decide which state is changed. Generic OnOff Set esp_ble_mesh_state_change_gen_onoff_set_t onoff_set The recv_op in ctx can be used to decide which state is changed. Generic OnOff Set esp_ble_mesh_state_change_gen_level_set_t level_set Generic Level Set esp_ble_mesh_state_change_gen_level_set_t level_set Generic Level Set esp_ble_mesh_state_change_gen_delta_set_t delta_set Generic Delta Set esp_ble_mesh_state_change_gen_delta_set_t delta_set Generic Delta Set esp_ble_mesh_state_change_gen_move_set_t move_set Generic Move Set esp_ble_mesh_state_change_gen_move_set_t move_set Generic Move Set esp_ble_mesh_state_change_gen_def_trans_time_set_t def_trans_time_set Generic Default Transition Time Set esp_ble_mesh_state_change_gen_def_trans_time_set_t def_trans_time_set Generic Default Transition Time Set esp_ble_mesh_state_change_gen_onpowerup_set_t onpowerup_set Generic OnPowerUp Set esp_ble_mesh_state_change_gen_onpowerup_set_t onpowerup_set Generic OnPowerUp Set esp_ble_mesh_state_change_gen_power_level_set_t power_level_set Generic Power Level Set esp_ble_mesh_state_change_gen_power_level_set_t power_level_set Generic Power Level Set esp_ble_mesh_state_change_gen_power_default_set_t power_default_set Generic Power Default Set esp_ble_mesh_state_change_gen_power_default_set_t power_default_set Generic Power Default Set esp_ble_mesh_state_change_gen_power_range_set_t power_range_set Generic Power Range Set esp_ble_mesh_state_change_gen_power_range_set_t power_range_set Generic Power Range Set esp_ble_mesh_state_change_gen_loc_global_set_t loc_global_set Generic Location Global Set esp_ble_mesh_state_change_gen_loc_global_set_t loc_global_set Generic Location Global Set esp_ble_mesh_state_change_gen_loc_local_set_t loc_local_set Generic Location Local Set esp_ble_mesh_state_change_gen_loc_local_set_t loc_local_set Generic Location Local Set esp_ble_mesh_state_change_gen_user_property_set_t user_property_set Generic User Property Set esp_ble_mesh_state_change_gen_user_property_set_t user_property_set Generic User Property Set esp_ble_mesh_state_change_gen_admin_property_set_t admin_property_set Generic Admin Property Set esp_ble_mesh_state_change_gen_admin_property_set_t admin_property_set Generic Admin Property Set esp_ble_mesh_state_change_gen_manu_property_set_t manu_property_set Generic Manufacturer Property Set esp_ble_mesh_state_change_gen_manu_property_set_t manu_property_set Generic Manufacturer Property Set esp_ble_mesh_state_change_gen_onoff_set_t onoff_set union esp_ble_mesh_generic_server_recv_get_msg_t #include <esp_ble_mesh_generic_model_api.h> Generic Server Model received get message union. Public Members esp_ble_mesh_server_recv_gen_user_property_get_t user_property Generic User Property Get esp_ble_mesh_server_recv_gen_user_property_get_t user_property Generic User Property Get esp_ble_mesh_server_recv_gen_admin_property_get_t admin_property Generic Admin Property Get esp_ble_mesh_server_recv_gen_admin_property_get_t admin_property Generic Admin Property Get esp_ble_mesh_server_recv_gen_manufacturer_property_get_t manu_property Generic Manufacturer Property Get esp_ble_mesh_server_recv_gen_manufacturer_property_get_t manu_property Generic Manufacturer Property Get esp_ble_mesh_server_recv_gen_client_properties_get_t client_properties Generic Client Properties Get esp_ble_mesh_server_recv_gen_client_properties_get_t client_properties Generic Client Properties Get esp_ble_mesh_server_recv_gen_user_property_get_t user_property union esp_ble_mesh_generic_server_recv_set_msg_t #include <esp_ble_mesh_generic_model_api.h> Generic Server Model received set message union. Public Members esp_ble_mesh_server_recv_gen_onoff_set_t onoff Generic OnOff Set/Generic OnOff Set Unack esp_ble_mesh_server_recv_gen_onoff_set_t onoff Generic OnOff Set/Generic OnOff Set Unack esp_ble_mesh_server_recv_gen_level_set_t level Generic Level Set/Generic Level Set Unack esp_ble_mesh_server_recv_gen_level_set_t level Generic Level Set/Generic Level Set Unack esp_ble_mesh_server_recv_gen_delta_set_t delta Generic Delta Set/Generic Delta Set Unack esp_ble_mesh_server_recv_gen_delta_set_t delta Generic Delta Set/Generic Delta Set Unack esp_ble_mesh_server_recv_gen_move_set_t move Generic Move Set/Generic Move Set Unack esp_ble_mesh_server_recv_gen_move_set_t move Generic Move Set/Generic Move Set Unack esp_ble_mesh_server_recv_gen_def_trans_time_set_t def_trans_time Generic Default Transition Time Set/Generic Default Transition Time Set Unack esp_ble_mesh_server_recv_gen_def_trans_time_set_t def_trans_time Generic Default Transition Time Set/Generic Default Transition Time Set Unack esp_ble_mesh_server_recv_gen_onpowerup_set_t onpowerup Generic OnPowerUp Set/Generic OnPowerUp Set Unack esp_ble_mesh_server_recv_gen_onpowerup_set_t onpowerup Generic OnPowerUp Set/Generic OnPowerUp Set Unack esp_ble_mesh_server_recv_gen_power_level_set_t power_level Generic Power Level Set/Generic Power Level Set Unack esp_ble_mesh_server_recv_gen_power_level_set_t power_level Generic Power Level Set/Generic Power Level Set Unack esp_ble_mesh_server_recv_gen_power_default_set_t power_default Generic Power Default Set/Generic Power Default Set Unack esp_ble_mesh_server_recv_gen_power_default_set_t power_default Generic Power Default Set/Generic Power Default Set Unack esp_ble_mesh_server_recv_gen_power_range_set_t power_range Generic Power Range Set/Generic Power Range Set Unack esp_ble_mesh_server_recv_gen_power_range_set_t power_range Generic Power Range Set/Generic Power Range Set Unack esp_ble_mesh_server_recv_gen_loc_global_set_t location_global Generic Location Global Set/Generic Location Global Set Unack esp_ble_mesh_server_recv_gen_loc_global_set_t location_global Generic Location Global Set/Generic Location Global Set Unack esp_ble_mesh_server_recv_gen_loc_local_set_t location_local Generic Location Local Set/Generic Location Local Set Unack esp_ble_mesh_server_recv_gen_loc_local_set_t location_local Generic Location Local Set/Generic Location Local Set Unack esp_ble_mesh_server_recv_gen_user_property_set_t user_property Generic User Property Set/Generic User Property Set Unack esp_ble_mesh_server_recv_gen_user_property_set_t user_property Generic User Property Set/Generic User Property Set Unack esp_ble_mesh_server_recv_gen_admin_property_set_t admin_property Generic Admin Property Set/Generic Admin Property Set Unack esp_ble_mesh_server_recv_gen_admin_property_set_t admin_property Generic Admin Property Set/Generic Admin Property Set Unack esp_ble_mesh_server_recv_gen_manufacturer_property_set_t manu_property Generic Manufacturer Property Set/Generic Manufacturer Property Set Unack esp_ble_mesh_server_recv_gen_manufacturer_property_set_t manu_property Generic Manufacturer Property Set/Generic Manufacturer Property Set Unack esp_ble_mesh_server_recv_gen_onoff_set_t onoff union esp_ble_mesh_generic_server_cb_value_t #include <esp_ble_mesh_generic_model_api.h> Generic Server Model callback value union. Public Members esp_ble_mesh_generic_server_state_change_t state_change ESP_BLE_MESH_GENERIC_SERVER_STATE_CHANGE_EVT esp_ble_mesh_generic_server_state_change_t state_change ESP_BLE_MESH_GENERIC_SERVER_STATE_CHANGE_EVT esp_ble_mesh_generic_server_recv_get_msg_t get ESP_BLE_MESH_GENERIC_SERVER_RECV_GET_MSG_EVT esp_ble_mesh_generic_server_recv_get_msg_t get ESP_BLE_MESH_GENERIC_SERVER_RECV_GET_MSG_EVT esp_ble_mesh_generic_server_recv_set_msg_t set ESP_BLE_MESH_GENERIC_SERVER_RECV_SET_MSG_EVT esp_ble_mesh_generic_server_recv_set_msg_t set ESP_BLE_MESH_GENERIC_SERVER_RECV_SET_MSG_EVT esp_ble_mesh_generic_server_state_change_t state_change Structures struct esp_ble_mesh_gen_onoff_set_t Bluetooth Mesh Generic Client Model Get and Set parameters structure. Parameters of Generic OnOff Set. struct esp_ble_mesh_gen_level_set_t Parameters of Generic Level Set. struct esp_ble_mesh_gen_delta_set_t Parameters of Generic Delta Set. struct esp_ble_mesh_gen_move_set_t Parameters of Generic Move Set. Public Members bool op_en Indicate if optional parameters are included bool op_en Indicate if optional parameters are included int16_t delta_level Delta Level step to calculate Move speed for Generic Level state int16_t delta_level Delta Level step to calculate Move speed for Generic Level state uint8_t tid Transaction ID uint8_t tid Transaction ID uint8_t trans_time Time to complete state transition (optional) uint8_t trans_time Time to complete state transition (optional) uint8_t delay Indicate message execution delay (C.1) uint8_t delay Indicate message execution delay (C.1) bool op_en struct esp_ble_mesh_gen_def_trans_time_set_t Parameter of Generic Default Transition Time Set. struct esp_ble_mesh_gen_onpowerup_set_t Parameter of Generic OnPowerUp Set. struct esp_ble_mesh_gen_power_level_set_t Parameters of Generic Power Level Set. struct esp_ble_mesh_gen_power_default_set_t Parameter of Generic Power Default Set. Public Members uint16_t power The value of the Generic Power Default state uint16_t power The value of the Generic Power Default state uint16_t power struct esp_ble_mesh_gen_power_range_set_t Parameters of Generic Power Range Set. struct esp_ble_mesh_gen_loc_global_set_t Parameters of Generic Location Global Set. struct esp_ble_mesh_gen_loc_local_set_t Parameters of Generic Location Local Set. struct esp_ble_mesh_gen_user_property_get_t Parameter of Generic User Property Get. Public Members uint16_t property_id Property ID identifying a Generic User Property uint16_t property_id Property ID identifying a Generic User Property uint16_t property_id struct esp_ble_mesh_gen_user_property_set_t Parameters of Generic User Property Set. struct esp_ble_mesh_gen_admin_property_get_t Parameter of Generic Admin Property Get. Public Members uint16_t property_id Property ID identifying a Generic Admin Property uint16_t property_id Property ID identifying a Generic Admin Property uint16_t property_id struct esp_ble_mesh_gen_admin_property_set_t Parameters of Generic Admin Property Set. struct esp_ble_mesh_gen_manufacturer_property_get_t Parameter of Generic Manufacturer Property Get. Public Members uint16_t property_id Property ID identifying a Generic Manufacturer Property uint16_t property_id Property ID identifying a Generic Manufacturer Property uint16_t property_id struct esp_ble_mesh_gen_manufacturer_property_set_t Parameters of Generic Manufacturer Property Set. struct esp_ble_mesh_gen_client_properties_get_t Parameter of Generic Client Properties Get. Public Members uint16_t property_id A starting Client Property ID present within an element uint16_t property_id A starting Client Property ID present within an element uint16_t property_id struct esp_ble_mesh_gen_onoff_status_cb_t Bluetooth Mesh Generic Client Model Get and Set callback parameters structure. Parameters of Generic OnOff Status. struct esp_ble_mesh_gen_level_status_cb_t Parameters of Generic Level Status. struct esp_ble_mesh_gen_def_trans_time_status_cb_t Parameter of Generic Default Transition Time Status. struct esp_ble_mesh_gen_onpowerup_status_cb_t Parameter of Generic OnPowerUp Status. struct esp_ble_mesh_gen_power_level_status_cb_t Parameters of Generic Power Level Status. struct esp_ble_mesh_gen_power_last_status_cb_t Parameter of Generic Power Last Status. Public Members uint16_t power The value of the Generic Power Last state uint16_t power The value of the Generic Power Last state uint16_t power struct esp_ble_mesh_gen_power_default_status_cb_t Parameter of Generic Power Default Status. Public Members uint16_t power The value of the Generic Default Last state uint16_t power The value of the Generic Default Last state uint16_t power struct esp_ble_mesh_gen_power_range_status_cb_t Parameters of Generic Power Range Status. struct esp_ble_mesh_gen_battery_status_cb_t Parameters of Generic Battery Status. struct esp_ble_mesh_gen_loc_global_status_cb_t Parameters of Generic Location Global Status. struct esp_ble_mesh_gen_loc_local_status_cb_t Parameters of Generic Location Local Status. struct esp_ble_mesh_gen_user_properties_status_cb_t Parameter of Generic User Properties Status. Public Members struct net_buf_simple *property_ids Buffer contains a sequence of N User Property IDs struct net_buf_simple *property_ids Buffer contains a sequence of N User Property IDs struct net_buf_simple *property_ids struct esp_ble_mesh_gen_user_property_status_cb_t Parameters of Generic User Property Status. struct esp_ble_mesh_gen_admin_properties_status_cb_t Parameter of Generic Admin Properties Status. Public Members struct net_buf_simple *property_ids Buffer contains a sequence of N Admin Property IDs struct net_buf_simple *property_ids Buffer contains a sequence of N Admin Property IDs struct net_buf_simple *property_ids struct esp_ble_mesh_gen_admin_property_status_cb_t Parameters of Generic Admin Property Status. struct esp_ble_mesh_gen_manufacturer_properties_status_cb_t Parameter of Generic Manufacturer Properties Status. Public Members struct net_buf_simple *property_ids Buffer contains a sequence of N Manufacturer Property IDs struct net_buf_simple *property_ids Buffer contains a sequence of N Manufacturer Property IDs struct net_buf_simple *property_ids struct esp_ble_mesh_gen_manufacturer_property_status_cb_t Parameters of Generic Manufacturer Property Status. Public Members bool op_en Indicate if optional parameters are included bool op_en Indicate if optional parameters are included uint16_t property_id Property ID identifying a Generic Manufacturer Property uint16_t property_id Property ID identifying a Generic Manufacturer Property uint8_t user_access Enumeration indicating user access (optional) uint8_t user_access Enumeration indicating user access (optional) struct net_buf_simple *property_value Raw value for the Manufacturer Property (C.1) struct net_buf_simple *property_value Raw value for the Manufacturer Property (C.1) bool op_en struct esp_ble_mesh_gen_client_properties_status_cb_t Parameter of Generic Client Properties Status. Public Members struct net_buf_simple *property_ids Buffer contains a sequence of N Client Property IDs struct net_buf_simple *property_ids Buffer contains a sequence of N Client Property IDs struct net_buf_simple *property_ids struct esp_ble_mesh_generic_client_cb_param_t Generic Client Model callback parameters Public Members int error_code Appropriate error code int error_code Appropriate error code esp_ble_mesh_client_common_param_t *params The client common parameters. esp_ble_mesh_client_common_param_t *params The client common parameters. esp_ble_mesh_gen_client_status_cb_t status_cb The generic status message callback values esp_ble_mesh_gen_client_status_cb_t status_cb The generic status message callback values int error_code struct esp_ble_mesh_gen_onoff_state_t Parameters of Generic OnOff state struct esp_ble_mesh_gen_onoff_srv_t User data of Generic OnOff Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Generic OnOff Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Generic OnOff Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_gen_onoff_state_t state Parameters of the Generic OnOff state esp_ble_mesh_gen_onoff_state_t state Parameters of the Generic OnOff state esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_state_transition_t transition Parameters of state transition esp_ble_mesh_state_transition_t transition Parameters of state transition esp_ble_mesh_model_t *model struct esp_ble_mesh_gen_level_state_t Parameters of Generic Level state Public Members int16_t level The present value of the Generic Level state int16_t level The present value of the Generic Level state int16_t target_level The target value of the Generic Level state int16_t target_level The target value of the Generic Level state int16_t last_level When a new transaction starts, level should be set to last_last, and use "level + incoming delta" to calculate the target level. In another word, "last_level" is used to record "level" of the last transaction, and "last_delta" is used to record the previously received delta_level value. The last value of the Generic Level state int16_t last_level When a new transaction starts, level should be set to last_last, and use "level + incoming delta" to calculate the target level. In another word, "last_level" is used to record "level" of the last transaction, and "last_delta" is used to record the previously received delta_level value. The last value of the Generic Level state int32_t last_delta The last delta change of the Generic Level state int32_t last_delta The last delta change of the Generic Level state bool move_start Indicate if the transition of the Generic Level state has been started bool move_start Indicate if the transition of the Generic Level state has been started bool positive Indicate if the transition is positive or negative bool positive Indicate if the transition is positive or negative int16_t level struct esp_ble_mesh_gen_level_srv_t User data of Generic Level Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Generic Level Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Generic Level Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_gen_level_state_t state Parameters of the Generic Level state esp_ble_mesh_gen_level_state_t state Parameters of the Generic Level state esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_state_transition_t transition Parameters of state transition esp_ble_mesh_state_transition_t transition Parameters of state transition int32_t tt_delta_level Delta change value of level state transition int32_t tt_delta_level Delta change value of level state transition esp_ble_mesh_model_t *model struct esp_ble_mesh_gen_def_trans_time_state_t Parameter of Generic Default Transition Time state struct esp_ble_mesh_gen_def_trans_time_srv_t User data of Generic Default Transition Time Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Generic Default Transition Time Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Generic Default Transition Time Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_gen_def_trans_time_state_t state Parameters of the Generic Default Transition Time state esp_ble_mesh_gen_def_trans_time_state_t state Parameters of the Generic Default Transition Time state esp_ble_mesh_model_t *model struct esp_ble_mesh_gen_onpowerup_state_t Parameter of Generic OnPowerUp state struct esp_ble_mesh_gen_power_onoff_srv_t User data of Generic Power OnOff Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Generic Power OnOff Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Generic Power OnOff Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_gen_onpowerup_state_t *state Parameters of the Generic OnPowerUp state esp_ble_mesh_gen_onpowerup_state_t *state Parameters of the Generic OnPowerUp state esp_ble_mesh_model_t *model struct esp_ble_mesh_gen_power_onoff_setup_srv_t User data of Generic Power OnOff Setup Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Generic Power OnOff Setup Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Generic Power OnOff Setup Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_gen_onpowerup_state_t *state Parameters of the Generic OnPowerUp state esp_ble_mesh_gen_onpowerup_state_t *state Parameters of the Generic OnPowerUp state esp_ble_mesh_model_t *model struct esp_ble_mesh_gen_power_level_state_t Parameters of Generic Power Level state Public Members uint16_t power_actual The present value of the Generic Power Actual state uint16_t power_actual The present value of the Generic Power Actual state uint16_t target_power_actual The target value of the Generic Power Actual state uint16_t target_power_actual The target value of the Generic Power Actual state uint16_t power_last The value of the Generic Power Last state uint16_t power_last The value of the Generic Power Last state uint16_t power_default The value of the Generic Power Default state uint16_t power_default The value of the Generic Power Default state uint8_t status_code The status code of setting Generic Power Range state uint8_t status_code The status code of setting Generic Power Range state uint16_t power_range_min The minimum value of the Generic Power Range state uint16_t power_range_min The minimum value of the Generic Power Range state uint16_t power_range_max The maximum value of the Generic Power Range state uint16_t power_range_max The maximum value of the Generic Power Range state uint16_t power_actual struct esp_ble_mesh_gen_power_level_srv_t User data of Generic Power Level Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Generic Power Level Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Generic Power Level Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_gen_power_level_state_t *state Parameters of the Generic Power Level state esp_ble_mesh_gen_power_level_state_t *state Parameters of the Generic Power Level state esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_state_transition_t transition Parameters of state transition esp_ble_mesh_state_transition_t transition Parameters of state transition int32_t tt_delta_level Delta change value of level state transition int32_t tt_delta_level Delta change value of level state transition esp_ble_mesh_model_t *model struct esp_ble_mesh_gen_power_level_setup_srv_t User data of Generic Power Level Setup Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Generic Power Level Setup Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Generic Power Level Setup Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_gen_power_level_state_t *state Parameters of the Generic Power Level state esp_ble_mesh_gen_power_level_state_t *state Parameters of the Generic Power Level state esp_ble_mesh_model_t *model struct esp_ble_mesh_gen_battery_state_t Parameters of Generic Battery state Public Members uint32_t battery_level The value of the Generic Battery Level state uint32_t battery_level The value of the Generic Battery Level state uint32_t time_to_discharge The value of the Generic Battery Time to Discharge state uint32_t time_to_discharge The value of the Generic Battery Time to Discharge state uint32_t time_to_charge The value of the Generic Battery Time to Charge state uint32_t time_to_charge The value of the Generic Battery Time to Charge state uint32_t battery_flags The value of the Generic Battery Flags state uint32_t battery_flags The value of the Generic Battery Flags state uint32_t battery_level struct esp_ble_mesh_gen_battery_srv_t User data of Generic Battery Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Generic Battery Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Generic Battery Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_gen_battery_state_t state Parameters of the Generic Battery state esp_ble_mesh_gen_battery_state_t state Parameters of the Generic Battery state esp_ble_mesh_model_t *model struct esp_ble_mesh_gen_location_state_t Parameters of Generic Location state Public Members int32_t global_latitude The value of the Global Latitude field int32_t global_latitude The value of the Global Latitude field int32_t global_longitude The value of the Global Longitude field int32_t global_longitude The value of the Global Longitude field int16_t global_altitude The value of the Global Altitude field int16_t global_altitude The value of the Global Altitude field int16_t local_north The value of the Local North field int16_t local_north The value of the Local North field int16_t local_east The value of the Local East field int16_t local_east The value of the Local East field int16_t local_altitude The value of the Local Altitude field int16_t local_altitude The value of the Local Altitude field uint8_t floor_number The value of the Floor Number field uint8_t floor_number The value of the Floor Number field uint16_t uncertainty The value of the Uncertainty field uint16_t uncertainty The value of the Uncertainty field int32_t global_latitude struct esp_ble_mesh_gen_location_srv_t User data of Generic Location Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Generic Location Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Generic Location Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_gen_location_state_t *state Parameters of the Generic Location state esp_ble_mesh_gen_location_state_t *state Parameters of the Generic Location state esp_ble_mesh_model_t *model struct esp_ble_mesh_gen_location_setup_srv_t User data of Generic Location Setup Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Generic Location Setup Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Generic Location Setup Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_gen_location_state_t *state Parameters of the Generic Location state esp_ble_mesh_gen_location_state_t *state Parameters of the Generic Location state esp_ble_mesh_model_t *model struct esp_ble_mesh_generic_property_t Parameters of Generic Property states Public Members uint16_t id The value of User/Admin/Manufacturer Property ID uint16_t id The value of User/Admin/Manufacturer Property ID uint8_t user_access The value of User Access field uint8_t user_access The value of User Access field uint8_t admin_access The value of Admin Access field uint8_t admin_access The value of Admin Access field uint8_t manu_access The value of Manufacturer Access field uint8_t manu_access The value of Manufacturer Access field struct net_buf_simple *val The value of User/Admin/Manufacturer Property struct net_buf_simple *val The value of User/Admin/Manufacturer Property uint16_t id struct esp_ble_mesh_gen_user_prop_srv_t User data of Generic User Property Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Generic User Property Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Generic User Property Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages uint8_t property_count Generic User Property count uint8_t property_count Generic User Property count esp_ble_mesh_generic_property_t *properties Parameters of the Generic User Property state esp_ble_mesh_generic_property_t *properties Parameters of the Generic User Property state esp_ble_mesh_model_t *model struct esp_ble_mesh_gen_admin_prop_srv_t User data of Generic Admin Property Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Generic Admin Property Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Generic Admin Property Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages uint8_t property_count Generic Admin Property count uint8_t property_count Generic Admin Property count esp_ble_mesh_generic_property_t *properties Parameters of the Generic Admin Property state esp_ble_mesh_generic_property_t *properties Parameters of the Generic Admin Property state esp_ble_mesh_model_t *model struct esp_ble_mesh_gen_manu_prop_srv_t User data of Generic Manufacturer Property Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Generic Manufacturer Property Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Generic Manufacturer Property Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages uint8_t property_count Generic Manufacturer Property count uint8_t property_count Generic Manufacturer Property count esp_ble_mesh_generic_property_t *properties Parameters of the Generic Manufacturer Property state esp_ble_mesh_generic_property_t *properties Parameters of the Generic Manufacturer Property state esp_ble_mesh_model_t *model struct esp_ble_mesh_gen_client_prop_srv_t User data of Generic Client Property Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Generic Client Property Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Generic Client Property Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages uint8_t id_count Generic Client Property ID count uint8_t id_count Generic Client Property ID count uint16_t *property_ids Parameters of the Generic Client Property state uint16_t *property_ids Parameters of the Generic Client Property state esp_ble_mesh_model_t *model struct esp_ble_mesh_state_change_gen_onoff_set_t Parameter of Generic OnOff Set state change event Public Members uint8_t onoff The value of Generic OnOff state uint8_t onoff The value of Generic OnOff state uint8_t onoff struct esp_ble_mesh_state_change_gen_level_set_t Parameter of Generic Level Set state change event struct esp_ble_mesh_state_change_gen_delta_set_t Parameter of Generic Delta Set state change event struct esp_ble_mesh_state_change_gen_move_set_t Parameter of Generic Move Set state change event struct esp_ble_mesh_state_change_gen_def_trans_time_set_t Parameter of Generic Default Transition Time Set state change event Public Members uint8_t trans_time The value of Generic Default Transition Time state uint8_t trans_time The value of Generic Default Transition Time state uint8_t trans_time struct esp_ble_mesh_state_change_gen_onpowerup_set_t Parameter of Generic OnPowerUp Set state change event Public Members uint8_t onpowerup The value of Generic OnPowerUp state uint8_t onpowerup The value of Generic OnPowerUp state uint8_t onpowerup struct esp_ble_mesh_state_change_gen_power_level_set_t Parameter of Generic Power Level Set state change event Public Members uint16_t power The value of Generic Power Actual state uint16_t power The value of Generic Power Actual state uint16_t power struct esp_ble_mesh_state_change_gen_power_default_set_t Parameter of Generic Power Default Set state change event Public Members uint16_t power The value of Generic Power Default state uint16_t power The value of Generic Power Default state uint16_t power struct esp_ble_mesh_state_change_gen_power_range_set_t Parameters of Generic Power Range Set state change event struct esp_ble_mesh_state_change_gen_loc_global_set_t Parameters of Generic Location Global Set state change event struct esp_ble_mesh_state_change_gen_loc_local_set_t Parameters of Generic Location Local Set state change event Public Members int16_t north The Local North value of Generic Location state int16_t north The Local North value of Generic Location state int16_t east The Local East value of Generic Location state int16_t east The Local East value of Generic Location state int16_t altitude The Local Altitude value of Generic Location state int16_t altitude The Local Altitude value of Generic Location state uint8_t floor_number The Floor Number value of Generic Location state uint8_t floor_number The Floor Number value of Generic Location state uint16_t uncertainty The Uncertainty value of Generic Location state uint16_t uncertainty The Uncertainty value of Generic Location state int16_t north struct esp_ble_mesh_state_change_gen_user_property_set_t Parameters of Generic User Property Set state change event struct esp_ble_mesh_state_change_gen_admin_property_set_t Parameters of Generic Admin Property Set state change event struct esp_ble_mesh_state_change_gen_manu_property_set_t Parameters of Generic Manufacturer Property Set state change event struct esp_ble_mesh_server_recv_gen_user_property_get_t Context of the received Generic User Property Get message Public Members uint16_t property_id Property ID identifying a Generic User Property uint16_t property_id Property ID identifying a Generic User Property uint16_t property_id struct esp_ble_mesh_server_recv_gen_admin_property_get_t Context of the received Generic Admin Property Get message Public Members uint16_t property_id Property ID identifying a Generic Admin Property uint16_t property_id Property ID identifying a Generic Admin Property uint16_t property_id struct esp_ble_mesh_server_recv_gen_manufacturer_property_get_t Context of the received Generic Manufacturer Property message Public Members uint16_t property_id Property ID identifying a Generic Manufacturer Property uint16_t property_id Property ID identifying a Generic Manufacturer Property uint16_t property_id struct esp_ble_mesh_server_recv_gen_client_properties_get_t Context of the received Generic Client Properties Get message Public Members uint16_t property_id A starting Client Property ID present within an element uint16_t property_id A starting Client Property ID present within an element uint16_t property_id struct esp_ble_mesh_server_recv_gen_onoff_set_t Context of the received Generic OnOff Set message struct esp_ble_mesh_server_recv_gen_level_set_t Context of the received Generic Level Set message struct esp_ble_mesh_server_recv_gen_delta_set_t Context of the received Generic Delta Set message struct esp_ble_mesh_server_recv_gen_move_set_t Context of the received Generic Move Set message Public Members bool op_en Indicate if optional parameters are included bool op_en Indicate if optional parameters are included int16_t delta_level Delta Level step to calculate Move speed for Generic Level state int16_t delta_level Delta Level step to calculate Move speed for Generic Level state uint8_t tid Transaction ID uint8_t tid Transaction ID uint8_t trans_time Time to complete state transition (optional) uint8_t trans_time Time to complete state transition (optional) uint8_t delay Indicate message execution delay (C.1) uint8_t delay Indicate message execution delay (C.1) bool op_en struct esp_ble_mesh_server_recv_gen_def_trans_time_set_t Context of the received Generic Default Transition Time Set message struct esp_ble_mesh_server_recv_gen_onpowerup_set_t Context of the received Generic OnPowerUp Set message struct esp_ble_mesh_server_recv_gen_power_level_set_t Context of the received Generic Power Level Set message struct esp_ble_mesh_server_recv_gen_power_default_set_t Context of the received Generic Power Default Set message Public Members uint16_t power The value of the Generic Power Default state uint16_t power The value of the Generic Power Default state uint16_t power struct esp_ble_mesh_server_recv_gen_power_range_set_t Context of the received Generic Power Range Set message struct esp_ble_mesh_server_recv_gen_loc_global_set_t Context of the received Generic Location Global Set message struct esp_ble_mesh_server_recv_gen_loc_local_set_t Context of the received Generic Location Local Set message struct esp_ble_mesh_server_recv_gen_user_property_set_t Context of the received Generic User Property Set message struct esp_ble_mesh_server_recv_gen_admin_property_set_t Context of the received Generic Admin Property Set message struct esp_ble_mesh_server_recv_gen_manufacturer_property_set_t Context of the received Generic Manufacturer Property Set message struct esp_ble_mesh_generic_server_cb_param_t Generic Server Model callback parameters Public Members esp_ble_mesh_model_t *model Pointer to Generic Server Models esp_ble_mesh_model_t *model Pointer to Generic Server Models esp_ble_mesh_msg_ctx_t ctx Context of the received messages esp_ble_mesh_msg_ctx_t ctx Context of the received messages esp_ble_mesh_generic_server_cb_value_t value Value of the received Generic Messages esp_ble_mesh_generic_server_cb_value_t value Value of the received Generic Messages esp_ble_mesh_model_t *model Macros ESP_BLE_MESH_MODEL_GEN_ONOFF_CLI(cli_pub, cli_data) Define a new Generic OnOff Client Model. Note This API needs to be called for each element on which the application needs to have a Generic OnOff Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic OnOff Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Generic OnOff Client Model instance. ESP_BLE_MESH_MODEL_GEN_LEVEL_CLI(cli_pub, cli_data) Define a new Generic Level Client Model. Note This API needs to be called for each element on which the application needs to have a Generic Level Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Level Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Generic Level Client Model instance. ESP_BLE_MESH_MODEL_GEN_DEF_TRANS_TIME_CLI(cli_pub, cli_data) Define a new Generic Default Transition Time Client Model. Note This API needs to be called for each element on which the application needs to have a Generic Default Transition Time Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Default Transition Time Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Generic Default Transition Time Client Model instance. ESP_BLE_MESH_MODEL_GEN_POWER_ONOFF_CLI(cli_pub, cli_data) Define a new Generic Power OnOff Client Model. Note This API needs to be called for each element on which the application needs to have a Generic Power OnOff Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Power OnOff Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Generic Power OnOff Client Model instance. ESP_BLE_MESH_MODEL_GEN_POWER_LEVEL_CLI(cli_pub, cli_data) Define a new Generic Power Level Client Model. Note This API needs to be called for each element on which the application needs to have a Generic Power Level Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Power Level Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Generic Power Level Client Model instance. ESP_BLE_MESH_MODEL_GEN_BATTERY_CLI(cli_pub, cli_data) Define a new Generic Battery Client Model. Note This API needs to be called for each element on which the application needs to have a Generic Battery Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Battery Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Generic Battery Client Model instance. ESP_BLE_MESH_MODEL_GEN_LOCATION_CLI(cli_pub, cli_data) Define a new Generic Location Client Model. Note This API needs to be called for each element on which the application needs to have a Generic Location Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Location Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Generic Location Client Model instance. ESP_BLE_MESH_MODEL_GEN_PROPERTY_CLI(cli_pub, cli_data) Define a new Generic Property Client Model. Note This API needs to be called for each element on which the application needs to have a Generic Property Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Location Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Generic Location Client Model instance. ESP_BLE_MESH_MODEL_GEN_ONOFF_SRV(srv_pub, srv_data) Generic Server Models related context. Define a new Generic OnOff Server Model. Note 1. The Generic OnOff Server Model is a root model. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_onoff_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_onoff_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic OnOff Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_onoff_srv_t. Returns New Generic OnOff Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_GEN_LEVEL_SRV(srv_pub, srv_data) Define a new Generic Level Server Model. Note 1. The Generic Level Server Model is a root model. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_level_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_level_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Level Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_level_srv_t. Returns New Generic Level Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_GEN_DEF_TRANS_TIME_SRV(srv_pub, srv_data) Define a new Generic Default Transition Time Server Model. Note 1. The Generic Default Transition Time Server Model is a root model. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_def_trans_time_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_def_trans_time_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Default Transition Time Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_def_trans_time_srv_t. Returns New Generic Default Transition Time Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_GEN_POWER_ONOFF_SRV(srv_pub, srv_data) Define a new Generic Power OnOff Server Model. Note 1. The Generic Power OnOff Server model extends the Generic OnOff Server model. When this model is present on an element, the corresponding Generic Power OnOff Setup Server model shall also be present. This model may be used to represent a variety of devices that do not fit any of the model descriptions that have been defined but support the generic properties of On/Off. This model shall support model publication and model subscription. This model may be used to represent a variety of devices that do not fit any of the model descriptions that have been defined but support the generic properties of On/Off. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_onoff_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_onoff_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Power OnOff Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_onoff_srv_t. Returns New Generic Power OnOff Server Model instance. This model may be used to represent a variety of devices that do not fit any of the model descriptions that have been defined but support the generic properties of On/Off. ESP_BLE_MESH_MODEL_GEN_POWER_ONOFF_SETUP_SRV(srv_pub, srv_data) Define a new Generic Power OnOff Setup Server Model. Note 1. The Generic Power OnOff Setup Server model extends the Generic Power OnOff Server model and the Generic Default Transition Time Server model. This model shall support model subscription. This model shall support model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_onoff_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_onoff_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Power OnOff Setup Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_onoff_setup_srv_t. Returns New Generic Power OnOff Setup Server Model instance. This model shall support model subscription. ESP_BLE_MESH_MODEL_GEN_POWER_LEVEL_SRV(srv_pub, srv_data) Define a new Generic Power Level Server Model. Note 1. The Generic Power Level Server model extends the Generic Power OnOff Server model and the Generic Level Server model. When this model is present on an Element, the corresponding Generic Power Level Setup Server model shall also be present. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_level_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_level_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Power Level Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_level_srv_t. Returns New Generic Power Level Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_GEN_POWER_LEVEL_SETUP_SRV(srv_pub, srv_data) Define a new Generic Power Level Setup Server Model. Note 1. The Generic Power Level Setup Server model extends the Generic Power Level Server model and the Generic Power OnOff Setup Server model. This model shall support model subscription. This model shall support model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_level_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_level_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Power Level Setup Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_level_setup_srv_t. Returns New Generic Power Level Setup Server Model instance. This model shall support model subscription. ESP_BLE_MESH_MODEL_GEN_BATTERY_SRV(srv_pub, srv_data) Define a new Generic Battery Server Model. Note 1. The Generic Battery Server Model is a root model. This model shall support model publication and model subscription. The model may be used to represent an element that is powered by a battery. This model shall support model publication and model subscription. The model may be used to represent an element that is powered by a battery. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_battery_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_battery_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Battery Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_battery_srv_t. Returns New Generic Battery Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_GEN_LOCATION_SRV(srv_pub, srv_data) Define a new Generic Location Server Model. Note 1. The Generic Location Server model is a root model. When this model is present on an Element, the corresponding Generic Location Setup Server model shall also be present. This model shall support model publication and model subscription. The model may be used to represent an element that knows its location (global or local). This model shall support model publication and model subscription. The model may be used to represent an element that knows its location (global or local). Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_location_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_location_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Location Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_location_srv_t. Returns New Generic Location Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_GEN_LOCATION_SETUP_SRV(srv_pub, srv_data) Define a new Generic Location Setup Server Model. Note 1. The Generic Location Setup Server model extends the Generic Location Server model. This model shall support model subscription. This model shall support model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_location_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_location_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Location Setup Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_location_setup_srv_t. Returns New Generic Location Setup Server Model instance. This model shall support model subscription. ESP_BLE_MESH_MODEL_GEN_USER_PROP_SRV(srv_pub, srv_data) Define a new Generic User Property Server Model. Note 1. The Generic User Property Server model is a root model. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_user_prop_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_user_prop_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic User Property Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_user_prop_srv_t. Returns New Generic User Property Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_GEN_ADMIN_PROP_SRV(srv_pub, srv_data) Define a new Generic Admin Property Server Model. Note 1. The Generic Admin Property Server model extends the Generic User Property Server model. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_admin_prop_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_admin_prop_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Admin Property Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_admin_prop_srv_t. Returns New Generic Admin Property Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_GEN_MANUFACTURER_PROP_SRV(srv_pub, srv_data) Define a new Generic Manufacturer Property Server Model. Note 1. The Generic Manufacturer Property Server model extends the Generic User Property Server model. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_manu_prop_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_manu_prop_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Manufacturer Property Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_manu_prop_srv_t. Returns New Generic Manufacturer Property Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_GEN_CLIENT_PROP_SRV(srv_pub, srv_data) Define a new Generic User Property Server Model. Note 1. The Generic Client Property Server model is a root model. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_client_prop_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_client_prop_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Generic Client Property Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_client_prop_srv_t. Returns New Generic Client Property Server Model instance. This model shall support model publication and model subscription. Type Definitions typedef void (*esp_ble_mesh_generic_client_cb_t)(esp_ble_mesh_generic_client_cb_event_t event, esp_ble_mesh_generic_client_cb_param_t *param) Bluetooth Mesh Generic Client Model function. Generic Client Model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter typedef void (*esp_ble_mesh_generic_server_cb_t)(esp_ble_mesh_generic_server_cb_event_t event, esp_ble_mesh_generic_server_cb_param_t *param) Bluetooth Mesh Generic Server Model function. Generic Server Model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter Enumerations enum esp_ble_mesh_generic_client_cb_event_t This enum value is the event of Generic Client Model Values: enumerator ESP_BLE_MESH_GENERIC_CLIENT_GET_STATE_EVT enumerator ESP_BLE_MESH_GENERIC_CLIENT_GET_STATE_EVT enumerator ESP_BLE_MESH_GENERIC_CLIENT_SET_STATE_EVT enumerator ESP_BLE_MESH_GENERIC_CLIENT_SET_STATE_EVT enumerator ESP_BLE_MESH_GENERIC_CLIENT_PUBLISH_EVT enumerator ESP_BLE_MESH_GENERIC_CLIENT_PUBLISH_EVT enumerator ESP_BLE_MESH_GENERIC_CLIENT_TIMEOUT_EVT enumerator ESP_BLE_MESH_GENERIC_CLIENT_TIMEOUT_EVT enumerator ESP_BLE_MESH_GENERIC_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_GENERIC_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_GENERIC_CLIENT_GET_STATE_EVT enum esp_ble_mesh_gen_user_prop_access_t This enum value is the access value of Generic User Property Values: enumerator ESP_BLE_MESH_GEN_USER_ACCESS_PROHIBIT enumerator ESP_BLE_MESH_GEN_USER_ACCESS_PROHIBIT enumerator ESP_BLE_MESH_GEN_USER_ACCESS_READ enumerator ESP_BLE_MESH_GEN_USER_ACCESS_READ enumerator ESP_BLE_MESH_GEN_USER_ACCESS_WRITE enumerator ESP_BLE_MESH_GEN_USER_ACCESS_WRITE enumerator ESP_BLE_MESH_GEN_USER_ACCESS_READ_WRITE enumerator ESP_BLE_MESH_GEN_USER_ACCESS_READ_WRITE enumerator ESP_BLE_MESH_GEN_USER_ACCESS_PROHIBIT enum esp_ble_mesh_gen_admin_prop_access_t This enum value is the access value of Generic Admin Property Values: enumerator ESP_BLE_MESH_GEN_ADMIN_NOT_USER_PROP enumerator ESP_BLE_MESH_GEN_ADMIN_NOT_USER_PROP enumerator ESP_BLE_MESH_GEN_ADMIN_ACCESS_READ enumerator ESP_BLE_MESH_GEN_ADMIN_ACCESS_READ enumerator ESP_BLE_MESH_GEN_ADMIN_ACCESS_WRITE enumerator ESP_BLE_MESH_GEN_ADMIN_ACCESS_WRITE enumerator ESP_BLE_MESH_GEN_ADMIN_ACCESS_READ_WRITE enumerator ESP_BLE_MESH_GEN_ADMIN_ACCESS_READ_WRITE enumerator ESP_BLE_MESH_GEN_ADMIN_NOT_USER_PROP enum esp_ble_mesh_gen_manu_prop_access_t This enum value is the access value of Generic Manufacturer Property Values: enumerator ESP_BLE_MESH_GEN_MANU_NOT_USER_PROP enumerator ESP_BLE_MESH_GEN_MANU_NOT_USER_PROP enumerator ESP_BLE_MESH_GEN_MANU_ACCESS_READ enumerator ESP_BLE_MESH_GEN_MANU_ACCESS_READ enumerator ESP_BLE_MESH_GEN_MANU_NOT_USER_PROP enum esp_ble_mesh_generic_server_cb_event_t This enum value is the event of Generic Server Model Values: enumerator ESP_BLE_MESH_GENERIC_SERVER_STATE_CHANGE_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Generic Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Generic Set/Set Unack messages are received. When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Generic Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Generic Set/Set Unack messages are received. When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Generic Get messages are received. enumerator ESP_BLE_MESH_GENERIC_SERVER_STATE_CHANGE_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Generic Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Generic Set/Set Unack messages are received. enumerator ESP_BLE_MESH_GENERIC_SERVER_RECV_GET_MSG_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Generic Get messages are received. enumerator ESP_BLE_MESH_GENERIC_SERVER_RECV_GET_MSG_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Generic Get messages are received. enumerator ESP_BLE_MESH_GENERIC_SERVER_RECV_SET_MSG_EVT When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Generic Set/Set Unack messages are received. enumerator ESP_BLE_MESH_GENERIC_SERVER_RECV_SET_MSG_EVT When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Generic Set/Set Unack messages are received. enumerator ESP_BLE_MESH_GENERIC_SERVER_EVT_MAX enumerator ESP_BLE_MESH_GENERIC_SERVER_EVT_MAX enumerator ESP_BLE_MESH_GENERIC_SERVER_STATE_CHANGE_EVT Sensor Client/Server Models Header File components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_sensor_model_api.h This header file can be included with: #include "esp_ble_mesh_sensor_model_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_sensor_client_callback(esp_ble_mesh_sensor_client_cb_t callback) Register BLE Mesh Sensor Client Model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_sensor_client_get_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_sensor_client_get_state_t *get_state) Get the value of Sensor Server Model states using the Sensor Client Model get messages. Note If you want to know the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_sensor_message_opcode_t in esp_ble_mesh_defs.h Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to sensor get message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to sensor get message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to sensor get message value. Shall not be set to NULL. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_sensor_client_set_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_sensor_client_set_state_t *set_state) Set the value of Sensor Server Model states using the Sensor Client Model set messages. Note If you want to know the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_sensor_message_opcode_t in esp_ble_mesh_defs.h Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to sensor set message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to sensor set message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to sensor set message value. Shall not be set to NULL. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_register_sensor_server_callback(esp_ble_mesh_sensor_server_cb_t callback) Register BLE Mesh Sensor Server Model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Unions union esp_ble_mesh_sensor_client_get_state_t #include <esp_ble_mesh_sensor_model_api.h> Sensor Client Model get message union. Public Members esp_ble_mesh_sensor_descriptor_get_t descriptor_get For ESP_BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_GET esp_ble_mesh_sensor_descriptor_get_t descriptor_get For ESP_BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_GET esp_ble_mesh_sensor_cadence_get_t cadence_get For ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_GET esp_ble_mesh_sensor_cadence_get_t cadence_get For ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_GET esp_ble_mesh_sensor_settings_get_t settings_get For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTINGS_GET esp_ble_mesh_sensor_settings_get_t settings_get For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTINGS_GET esp_ble_mesh_sensor_setting_get_t setting_get For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_GET esp_ble_mesh_sensor_setting_get_t setting_get For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_GET esp_ble_mesh_sensor_get_t sensor_get For ESP_BLE_MESH_MODEL_OP_SENSOR_GET esp_ble_mesh_sensor_get_t sensor_get For ESP_BLE_MESH_MODEL_OP_SENSOR_GET esp_ble_mesh_sensor_column_get_t column_get For ESP_BLE_MESH_MODEL_OP_SENSOR_COLUMN_GET esp_ble_mesh_sensor_column_get_t column_get For ESP_BLE_MESH_MODEL_OP_SENSOR_COLUMN_GET esp_ble_mesh_sensor_series_get_t series_get For ESP_BLE_MESH_MODEL_OP_SENSOR_SERIES_GET esp_ble_mesh_sensor_series_get_t series_get For ESP_BLE_MESH_MODEL_OP_SENSOR_SERIES_GET esp_ble_mesh_sensor_descriptor_get_t descriptor_get union esp_ble_mesh_sensor_client_set_state_t #include <esp_ble_mesh_sensor_model_api.h> Sensor Client Model set message union. Public Members esp_ble_mesh_sensor_cadence_set_t cadence_set For ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET & ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET_UNACK esp_ble_mesh_sensor_cadence_set_t cadence_set For ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET & ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET_UNACK esp_ble_mesh_sensor_setting_set_t setting_set For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_SET & ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_SET_UNACK esp_ble_mesh_sensor_setting_set_t setting_set For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_SET & ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_SET_UNACK esp_ble_mesh_sensor_cadence_set_t cadence_set union esp_ble_mesh_sensor_client_status_cb_t #include <esp_ble_mesh_sensor_model_api.h> Sensor Client Model received message union. Public Members esp_ble_mesh_sensor_descriptor_status_cb_t descriptor_status For ESP_BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_STATUS esp_ble_mesh_sensor_descriptor_status_cb_t descriptor_status For ESP_BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_STATUS esp_ble_mesh_sensor_cadence_status_cb_t cadence_status For ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_STATUS esp_ble_mesh_sensor_cadence_status_cb_t cadence_status For ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_STATUS esp_ble_mesh_sensor_settings_status_cb_t settings_status For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTINGS_STATUS esp_ble_mesh_sensor_settings_status_cb_t settings_status For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTINGS_STATUS esp_ble_mesh_sensor_setting_status_cb_t setting_status For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_STATUS esp_ble_mesh_sensor_setting_status_cb_t setting_status For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_STATUS esp_ble_mesh_sensor_status_cb_t sensor_status For ESP_BLE_MESH_MODEL_OP_SENSOR_STATUS esp_ble_mesh_sensor_status_cb_t sensor_status For ESP_BLE_MESH_MODEL_OP_SENSOR_STATUS esp_ble_mesh_sensor_column_status_cb_t column_status For ESP_BLE_MESH_MODEL_OP_SENSOR_COLUMN_STATUS esp_ble_mesh_sensor_column_status_cb_t column_status For ESP_BLE_MESH_MODEL_OP_SENSOR_COLUMN_STATUS esp_ble_mesh_sensor_series_status_cb_t series_status For ESP_BLE_MESH_MODEL_OP_SENSOR_SERIES_STATUS esp_ble_mesh_sensor_series_status_cb_t series_status For ESP_BLE_MESH_MODEL_OP_SENSOR_SERIES_STATUS esp_ble_mesh_sensor_descriptor_status_cb_t descriptor_status union esp_ble_mesh_sensor_server_state_change_t #include <esp_ble_mesh_sensor_model_api.h> Sensor Server Model state change value union. Public Members esp_ble_mesh_state_change_sensor_cadence_set_t sensor_cadence_set The recv_op in ctx can be used to decide which state is changed. Sensor Cadence Set esp_ble_mesh_state_change_sensor_cadence_set_t sensor_cadence_set The recv_op in ctx can be used to decide which state is changed. Sensor Cadence Set esp_ble_mesh_state_change_sensor_setting_set_t sensor_setting_set Sensor Setting Set esp_ble_mesh_state_change_sensor_setting_set_t sensor_setting_set Sensor Setting Set esp_ble_mesh_state_change_sensor_cadence_set_t sensor_cadence_set union esp_ble_mesh_sensor_server_recv_get_msg_t #include <esp_ble_mesh_sensor_model_api.h> Sensor Server Model received get message union. Public Members esp_ble_mesh_server_recv_sensor_descriptor_get_t sensor_descriptor Sensor Descriptor Get esp_ble_mesh_server_recv_sensor_descriptor_get_t sensor_descriptor Sensor Descriptor Get esp_ble_mesh_server_recv_sensor_cadence_get_t sensor_cadence Sensor Cadence Get esp_ble_mesh_server_recv_sensor_cadence_get_t sensor_cadence Sensor Cadence Get esp_ble_mesh_server_recv_sensor_settings_get_t sensor_settings Sensor Settings Get esp_ble_mesh_server_recv_sensor_settings_get_t sensor_settings Sensor Settings Get esp_ble_mesh_server_recv_sensor_setting_get_t sensor_setting Sensor Setting Get esp_ble_mesh_server_recv_sensor_setting_get_t sensor_setting Sensor Setting Get esp_ble_mesh_server_recv_sensor_get_t sensor_data Sensor Get esp_ble_mesh_server_recv_sensor_get_t sensor_data Sensor Get esp_ble_mesh_server_recv_sensor_column_get_t sensor_column Sensor Column Get esp_ble_mesh_server_recv_sensor_column_get_t sensor_column Sensor Column Get esp_ble_mesh_server_recv_sensor_series_get_t sensor_series Sensor Series Get esp_ble_mesh_server_recv_sensor_series_get_t sensor_series Sensor Series Get esp_ble_mesh_server_recv_sensor_descriptor_get_t sensor_descriptor union esp_ble_mesh_sensor_server_recv_set_msg_t #include <esp_ble_mesh_sensor_model_api.h> Sensor Server Model received set message union. Public Members esp_ble_mesh_server_recv_sensor_cadence_set_t sensor_cadence Sensor Cadence Set esp_ble_mesh_server_recv_sensor_cadence_set_t sensor_cadence Sensor Cadence Set esp_ble_mesh_server_recv_sensor_setting_set_t sensor_setting Sensor Setting Set esp_ble_mesh_server_recv_sensor_setting_set_t sensor_setting Sensor Setting Set esp_ble_mesh_server_recv_sensor_cadence_set_t sensor_cadence union esp_ble_mesh_sensor_server_cb_value_t #include <esp_ble_mesh_sensor_model_api.h> Sensor Server Model callback value union. Public Members esp_ble_mesh_sensor_server_state_change_t state_change ESP_BLE_MESH_SENSOR_SERVER_STATE_CHANGE_EVT esp_ble_mesh_sensor_server_state_change_t state_change ESP_BLE_MESH_SENSOR_SERVER_STATE_CHANGE_EVT esp_ble_mesh_sensor_server_recv_get_msg_t get ESP_BLE_MESH_SENSOR_SERVER_RECV_GET_MSG_EVT esp_ble_mesh_sensor_server_recv_get_msg_t get ESP_BLE_MESH_SENSOR_SERVER_RECV_GET_MSG_EVT esp_ble_mesh_sensor_server_recv_set_msg_t set ESP_BLE_MESH_SENSOR_SERVER_RECV_SET_MSG_EVT esp_ble_mesh_sensor_server_recv_set_msg_t set ESP_BLE_MESH_SENSOR_SERVER_RECV_SET_MSG_EVT esp_ble_mesh_sensor_server_state_change_t state_change Structures struct esp_ble_mesh_sensor_descriptor_get_t Bluetooth Mesh Sensor Client Model Get and Set parameters structure. Parameters of Sensor Descriptor Get struct esp_ble_mesh_sensor_cadence_get_t Parameter of Sensor Cadence Get struct esp_ble_mesh_sensor_cadence_set_t Parameters of Sensor Cadence Set Public Members uint16_t property_id Property ID for the sensor uint16_t property_id Property ID for the sensor uint8_t fast_cadence_period_divisor Divisor for the publish period uint8_t fast_cadence_period_divisor Divisor for the publish period uint8_t status_trigger_type The unit and format of the Status Trigger Delta fields uint8_t status_trigger_type The unit and format of the Status Trigger Delta fields struct net_buf_simple *status_trigger_delta_down Delta down value that triggers a status message struct net_buf_simple *status_trigger_delta_down Delta down value that triggers a status message struct net_buf_simple *status_trigger_delta_up Delta up value that triggers a status message struct net_buf_simple *status_trigger_delta_up Delta up value that triggers a status message uint8_t status_min_interval Minimum interval between two consecutive Status messages uint8_t status_min_interval Minimum interval between two consecutive Status messages struct net_buf_simple *fast_cadence_low Low value for the fast cadence range struct net_buf_simple *fast_cadence_low Low value for the fast cadence range struct net_buf_simple *fast_cadence_high Fast value for the fast cadence range struct net_buf_simple *fast_cadence_high Fast value for the fast cadence range uint16_t property_id struct esp_ble_mesh_sensor_settings_get_t Parameter of Sensor Settings Get Public Members uint16_t sensor_property_id Property ID of a sensor uint16_t sensor_property_id Property ID of a sensor uint16_t sensor_property_id struct esp_ble_mesh_sensor_setting_get_t Parameters of Sensor Setting Get struct esp_ble_mesh_sensor_setting_set_t Parameters of Sensor Setting Set struct esp_ble_mesh_sensor_get_t Parameters of Sensor Get struct esp_ble_mesh_sensor_column_get_t Parameters of Sensor Column Get struct esp_ble_mesh_sensor_series_get_t Parameters of Sensor Series Get struct esp_ble_mesh_sensor_descriptor_status_cb_t Bluetooth Mesh Sensor Client Model Get and Set callback parameters structure. Parameter of Sensor Descriptor Status Public Members struct net_buf_simple *descriptor Sequence of 8-octet sensor descriptors (optional) struct net_buf_simple *descriptor Sequence of 8-octet sensor descriptors (optional) struct net_buf_simple *descriptor struct esp_ble_mesh_sensor_cadence_status_cb_t Parameters of Sensor Cadence Status struct esp_ble_mesh_sensor_settings_status_cb_t Parameters of Sensor Settings Status struct esp_ble_mesh_sensor_setting_status_cb_t Parameters of Sensor Setting Status Public Members bool op_en Indicate id optional parameters are included bool op_en Indicate id optional parameters are included uint16_t sensor_property_id Property ID identifying a sensor uint16_t sensor_property_id Property ID identifying a sensor uint16_t sensor_setting_property_id Setting ID identifying a setting within a sensor uint16_t sensor_setting_property_id Setting ID identifying a setting within a sensor uint8_t sensor_setting_access Read/Write access rights for the setting (optional) uint8_t sensor_setting_access Read/Write access rights for the setting (optional) struct net_buf_simple *sensor_setting_raw Raw value for the setting struct net_buf_simple *sensor_setting_raw Raw value for the setting bool op_en struct esp_ble_mesh_sensor_status_cb_t Parameter of Sensor Status Public Members struct net_buf_simple *marshalled_sensor_data Value of sensor data state (optional) struct net_buf_simple *marshalled_sensor_data Value of sensor data state (optional) struct net_buf_simple *marshalled_sensor_data struct esp_ble_mesh_sensor_column_status_cb_t Parameters of Sensor Column Status struct esp_ble_mesh_sensor_series_status_cb_t Parameters of Sensor Series Status struct esp_ble_mesh_sensor_client_cb_param_t Sensor Client Model callback parameters Public Members int error_code 0: success, otherwise failure. For the error code values please refer to errno.h file. A negative sign is added to the standard error codes in errno.h. int error_code 0: success, otherwise failure. For the error code values please refer to errno.h file. A negative sign is added to the standard error codes in errno.h. esp_ble_mesh_client_common_param_t *params The client common parameters. esp_ble_mesh_client_common_param_t *params The client common parameters. esp_ble_mesh_sensor_client_status_cb_t status_cb The sensor status message callback values esp_ble_mesh_sensor_client_status_cb_t status_cb The sensor status message callback values int error_code struct esp_ble_mesh_sensor_descriptor_t Parameters of Sensor Descriptor state Public Members uint32_t positive_tolerance The value of Sensor Positive Tolerance field uint32_t positive_tolerance The value of Sensor Positive Tolerance field uint32_t negative_tolerance The value of Sensor Negative Tolerance field uint32_t negative_tolerance The value of Sensor Negative Tolerance field uint32_t sampling_function The value of Sensor Sampling Function field uint32_t sampling_function The value of Sensor Sampling Function field uint8_t measure_period The value of Sensor Measurement Period field uint8_t measure_period The value of Sensor Measurement Period field uint8_t update_interval The value of Sensor Update Interval field uint8_t update_interval The value of Sensor Update Interval field uint32_t positive_tolerance struct esp_ble_mesh_sensor_setting_t Parameters of Sensor Setting state struct esp_ble_mesh_sensor_cadence_t Parameters of Sensor Cadence state Public Members uint8_t period_divisor The value of Fast Cadence Period Divisor field uint8_t period_divisor The value of Fast Cadence Period Divisor field uint8_t trigger_type The value of Status Trigger Type field uint8_t trigger_type The value of Status Trigger Type field struct net_buf_simple *trigger_delta_down Note: The parameter "size" in trigger_delta_down, trigger_delta_up, fast_cadence_low & fast_cadence_high indicates the exact length of these four parameters, and they are associated with the Sensor Property ID. Users need to initialize the "size" precisely. The value of Status Trigger Delta Down field struct net_buf_simple *trigger_delta_down Note: The parameter "size" in trigger_delta_down, trigger_delta_up, fast_cadence_low & fast_cadence_high indicates the exact length of these four parameters, and they are associated with the Sensor Property ID. Users need to initialize the "size" precisely. The value of Status Trigger Delta Down field struct net_buf_simple *trigger_delta_up The value of Status Trigger Delta Up field struct net_buf_simple *trigger_delta_up The value of Status Trigger Delta Up field uint8_t min_interval The value of Status Min Interval field uint8_t min_interval The value of Status Min Interval field struct net_buf_simple *fast_cadence_low The value of Fast Cadence Low field struct net_buf_simple *fast_cadence_low The value of Fast Cadence Low field struct net_buf_simple *fast_cadence_high The value of Fast Cadence High field struct net_buf_simple *fast_cadence_high The value of Fast Cadence High field uint8_t period_divisor struct esp_ble_mesh_sensor_data_t Parameters of Sensor Data state Public Members uint8_t format Format A: The Length field is a 1-based uint4 value (valid range 0x0–0xF, representing range of 1 – 16). Format B: The Length field is a 1-based uint7 value (valid range 0x0–0x7F, representing range of 1 – 127). The value 0x7F represents a length of zero. The value of the Sensor Data format uint8_t format Format A: The Length field is a 1-based uint4 value (valid range 0x0–0xF, representing range of 1 – 16). Format B: The Length field is a 1-based uint7 value (valid range 0x0–0x7F, representing range of 1 – 127). The value 0x7F represents a length of zero. The value of the Sensor Data format uint8_t length The value of the Sensor Data length uint8_t length The value of the Sensor Data length struct net_buf_simple *raw_value The value of Sensor Data raw value struct net_buf_simple *raw_value The value of Sensor Data raw value uint8_t format struct esp_ble_mesh_sensor_series_column_t Parameters of Sensor Series Column state struct esp_ble_mesh_sensor_state_t Parameters of Sensor states Public Members uint16_t sensor_property_id The value of Sensor Property ID field uint16_t sensor_property_id The value of Sensor Property ID field esp_ble_mesh_sensor_descriptor_t descriptor Parameters of the Sensor Descriptor state esp_ble_mesh_sensor_descriptor_t descriptor Parameters of the Sensor Descriptor state const uint8_t setting_count Multiple Sensor Setting states may be present for each sensor. The Sensor Setting Property ID values shall be unique for each Sensor Property ID that identifies a sensor within an element. const uint8_t setting_count Multiple Sensor Setting states may be present for each sensor. The Sensor Setting Property ID values shall be unique for each Sensor Property ID that identifies a sensor within an element. esp_ble_mesh_sensor_setting_t *settings Parameters of the Sensor Setting state esp_ble_mesh_sensor_setting_t *settings Parameters of the Sensor Setting state esp_ble_mesh_sensor_cadence_t *cadence The Sensor Cadence state may be not supported by sensors based on device properties referencing "non-scalar characteristics" such as "histograms" or "composite characteristics". Parameters of the Sensor Cadence state esp_ble_mesh_sensor_cadence_t *cadence The Sensor Cadence state may be not supported by sensors based on device properties referencing "non-scalar characteristics" such as "histograms" or "composite characteristics". Parameters of the Sensor Cadence state esp_ble_mesh_sensor_data_t sensor_data Parameters of the Sensor Data state esp_ble_mesh_sensor_data_t sensor_data Parameters of the Sensor Data state esp_ble_mesh_sensor_series_column_t series_column Parameters of the Sensor Series Column state esp_ble_mesh_sensor_series_column_t series_column Parameters of the Sensor Series Column state uint16_t sensor_property_id struct esp_ble_mesh_sensor_srv_t User data of Sensor Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Sensor Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Sensor Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages const uint8_t state_count Sensor state count const uint8_t state_count Sensor state count esp_ble_mesh_sensor_state_t *states Parameters of the Sensor states esp_ble_mesh_sensor_state_t *states Parameters of the Sensor states esp_ble_mesh_model_t *model struct esp_ble_mesh_sensor_setup_srv_t User data of Sensor Setup Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Sensor Setup Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Sensor Setup Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages const uint8_t state_count Sensor state count const uint8_t state_count Sensor state count esp_ble_mesh_sensor_state_t *states Parameters of the Sensor states esp_ble_mesh_sensor_state_t *states Parameters of the Sensor states esp_ble_mesh_model_t *model struct esp_ble_mesh_state_change_sensor_cadence_set_t Parameters of Sensor Cadence Set state change event Public Members uint16_t property_id The value of Sensor Property ID state uint16_t property_id The value of Sensor Property ID state uint8_t period_divisor The value of Fast Cadence Period Divisor state uint8_t period_divisor The value of Fast Cadence Period Divisor state uint8_t trigger_type The value of Status Trigger Type state uint8_t trigger_type The value of Status Trigger Type state struct net_buf_simple *trigger_delta_down The value of Status Trigger Delta Down state struct net_buf_simple *trigger_delta_down The value of Status Trigger Delta Down state struct net_buf_simple *trigger_delta_up The value of Status Trigger Delta Up state struct net_buf_simple *trigger_delta_up The value of Status Trigger Delta Up state uint8_t min_interval The value of Status Min Interval state uint8_t min_interval The value of Status Min Interval state struct net_buf_simple *fast_cadence_low The value of Fast Cadence Low state struct net_buf_simple *fast_cadence_low The value of Fast Cadence Low state struct net_buf_simple *fast_cadence_high The value of Fast Cadence High state struct net_buf_simple *fast_cadence_high The value of Fast Cadence High state uint16_t property_id struct esp_ble_mesh_state_change_sensor_setting_set_t Parameters of Sensor Setting Set state change event struct esp_ble_mesh_server_recv_sensor_descriptor_get_t Context of the received Sensor Descriptor Get message struct esp_ble_mesh_server_recv_sensor_cadence_get_t Context of the received Sensor Cadence Get message struct esp_ble_mesh_server_recv_sensor_settings_get_t Context of the received Sensor Settings Get message struct esp_ble_mesh_server_recv_sensor_setting_get_t Context of the received Sensor Setting Get message struct esp_ble_mesh_server_recv_sensor_get_t Context of the received Sensor Get message struct esp_ble_mesh_server_recv_sensor_column_get_t Context of the received Sensor Column Get message struct esp_ble_mesh_server_recv_sensor_series_get_t Context of the received Sensor Series Get message struct esp_ble_mesh_server_recv_sensor_cadence_set_t Context of the received Sensor Cadence Set message struct esp_ble_mesh_server_recv_sensor_setting_set_t Context of the received Sensor Setting Set message struct esp_ble_mesh_sensor_server_cb_param_t Sensor Server Model callback parameters Public Members esp_ble_mesh_model_t *model Pointer to Sensor Server Models esp_ble_mesh_model_t *model Pointer to Sensor Server Models esp_ble_mesh_msg_ctx_t ctx Context of the received messages esp_ble_mesh_msg_ctx_t ctx Context of the received messages esp_ble_mesh_sensor_server_cb_value_t value Value of the received Sensor Messages esp_ble_mesh_sensor_server_cb_value_t value Value of the received Sensor Messages esp_ble_mesh_model_t *model Macros ESP_BLE_MESH_MODEL_SENSOR_CLI(cli_pub, cli_data) Define a new Sensor Client Model. Note This API needs to be called for each element on which the application needs to have a Sensor Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Sensor Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Sensor Client Model instance. ESP_BLE_MESH_MODEL_SENSOR_SRV(srv_pub, srv_data) Sensor Server Models related context. Define a new Sensor Server Model. Note 1. The Sensor Server model is a root model. When this model is present on an element, the corresponding Sensor Setup Server model shall also be present. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_sensor_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_sensor_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Sensor Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_sensor_srv_t. Returns New Sensor Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_SENSOR_SETUP_SRV(srv_pub, srv_data) Define a new Sensor Setup Server Model. Note 1. The Sensor Setup Server model extends the Sensor Server model. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_sensor_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_sensor_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Sensor Setup Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_sensor_setup_srv_t. Returns New Sensor Setup Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_INVALID_SENSOR_PROPERTY_ID Invalid Sensor Property ID ESP_BLE_MESH_SENSOR_PROPERTY_ID_LEN Length of Sensor Property ID ESP_BLE_MESH_SENSOR_DESCRIPTOR_LEN Length of Sensor Descriptor state ESP_BLE_MESH_SENSOR_UNSPECIFIED_POS_TOLERANCE Unspecified Sensor Positive Tolerance ESP_BLE_MESH_SENSOR_UNSPECIFIED_NEG_TOLERANCE Unspecified Sensor Negative Tolerance ESP_BLE_MESH_SENSOR_NOT_APPL_MEASURE_PERIOD Not applicable Sensor Measurement Period ESP_BLE_MESH_SENSOR_NOT_APPL_UPDATE_INTERVAL Not applicable Sensor Update Interval ESP_BLE_MESH_INVALID_SENSOR_SETTING_PROPERTY_ID Invalid Sensor Setting Property ID ESP_BLE_MESH_SENSOR_SETTING_PROPERTY_ID_LEN Length of Sensor Setting Property ID ESP_BLE_MESH_SENSOR_SETTING_ACCESS_LEN Length of Sensor Setting Access ESP_BLE_MESH_SENSOR_SETTING_ACCESS_READ Sensor Setting Access - Read ESP_BLE_MESH_SENSOR_SETTING_ACCESS_READ_WRITE Sensor Setting Access - Read & Write ESP_BLE_MESH_SENSOR_DIVISOR_TRIGGER_TYPE_LEN Length of Sensor Divisor Trigger Type ESP_BLE_MESH_SENSOR_STATUS_MIN_INTERVAL_LEN Length of Sensor Status Min Interval ESP_BLE_MESH_SENSOR_PERIOD_DIVISOR_MAX_VALUE Maximum value of Sensor Period Divisor ESP_BLE_MESH_SENSOR_STATUS_MIN_INTERVAL_MAX Maximum value of Sensor Status Min Interval ESP_BLE_MESH_SENSOR_STATUS_TRIGGER_TYPE_CHAR Sensor Status Trigger Type - Format Type of the characteristic that the Sensor Property ID state references ESP_BLE_MESH_SENSOR_STATUS_TRIGGER_TYPE_UINT16 Sensor Status Trigger Type - Format Type "uint16" ESP_BLE_MESH_SENSOR_DATA_FORMAT_A Sensor Data Format A ESP_BLE_MESH_SENSOR_DATA_FORMAT_B Sensor Data Format B ESP_BLE_MESH_SENSOR_DATA_FORMAT_A_MPID_LEN MPID length of Sensor Data Format A ESP_BLE_MESH_SENSOR_DATA_FORMAT_B_MPID_LEN MPID length of Sensor Data Format B ESP_BLE_MESH_SENSOR_DATA_ZERO_LEN Zero length of Sensor Data. Note: The Length field is a 1-based uint7 value (valid range 0x0–0x7F, representing range of 1–127). The value 0x7F represents a length of zero. ESP_BLE_MESH_GET_SENSOR_DATA_FORMAT(_data) Get format of the sensor data. Note Multiple sensor data may be concatenated. Make sure the _data pointer is updated before getting the format of the corresponding sensor data. Parameters _data -- Pointer to the start of the sensor data. _data -- Pointer to the start of the sensor data. _data -- Pointer to the start of the sensor data. Returns Format of the sensor data. Parameters _data -- Pointer to the start of the sensor data. Returns Format of the sensor data. ESP_BLE_MESH_GET_SENSOR_DATA_LENGTH(_data, _fmt) Get length of the sensor data. Note Multiple sensor data may be concatenated. Make sure the _data pointer is updated before getting the length of the corresponding sensor data. Parameters _data -- Pointer to the start of the sensor data. _fmt -- Format of the sensor data. _data -- Pointer to the start of the sensor data. _fmt -- Format of the sensor data. _data -- Pointer to the start of the sensor data. Returns Length (zero-based) of the sensor data. Parameters _data -- Pointer to the start of the sensor data. _fmt -- Format of the sensor data. Returns Length (zero-based) of the sensor data. ESP_BLE_MESH_GET_SENSOR_DATA_PROPERTY_ID(_data, _fmt) Get Sensor Property ID of the sensor data. Note Multiple sensor data may be concatenated. Make sure the _data pointer is updated before getting Sensor Property ID of the corresponding sensor data. Parameters _data -- Pointer to the start of the sensor data. _fmt -- Format of the sensor data. _data -- Pointer to the start of the sensor data. _fmt -- Format of the sensor data. _data -- Pointer to the start of the sensor data. Returns Sensor Property ID of the sensor data. Parameters _data -- Pointer to the start of the sensor data. _fmt -- Format of the sensor data. Returns Sensor Property ID of the sensor data. ESP_BLE_MESH_SENSOR_DATA_FORMAT_A_MPID(_len, _id) Generate a MPID value for sensor data with Format A. Note 1. The Format field is 0b0 and indicates that Format A is used. The Length field is a 1-based uint4 value (valid range 0x0–0xF, representing range of 1–16). The Property ID is an 11-bit bit field representing 11 LSb of a Property ID. This format may be used for Property Values that are not longer than 16 octets and for Property IDs less than 0x0800. The Length field is a 1-based uint4 value (valid range 0x0–0xF, representing range of 1–16). The Property ID is an 11-bit bit field representing 11 LSb of a Property ID. This format may be used for Property Values that are not longer than 16 octets and for Property IDs less than 0x0800. Parameters _len -- Length of Sensor Raw value. _id -- Sensor Property ID. _len -- Length of Sensor Raw value. _id -- Sensor Property ID. _len -- Length of Sensor Raw value. Returns 2-octet MPID value for sensor data with Format A. Parameters _len -- Length of Sensor Raw value. _id -- Sensor Property ID. Returns 2-octet MPID value for sensor data with Format A. The Length field is a 1-based uint4 value (valid range 0x0–0xF, representing range of 1–16). ESP_BLE_MESH_SENSOR_DATA_FORMAT_B_MPID(_len, _id) Generate a MPID value for sensor data with Format B. Note 1. The Format field is 0b1 and indicates Format B is used. The Length field is a 1-based uint7 value (valid range 0x0–0x7F, representing range of 1–127). The value 0x7F represents a length of zero. The Property ID is a 16-bit bit field representing a Property ID. This format may be used for Property Values not longer than 128 octets and for any Property IDs. Property values longer than 128 octets are not supported by the Sensor Status message. Exclude the generated 1-octet value, the 2-octet Sensor Property ID The Length field is a 1-based uint7 value (valid range 0x0–0x7F, representing range of 1–127). The value 0x7F represents a length of zero. The Property ID is a 16-bit bit field representing a Property ID. This format may be used for Property Values not longer than 128 octets and for any Property IDs. Property values longer than 128 octets are not supported by the Sensor Status message. Exclude the generated 1-octet value, the 2-octet Sensor Property ID Parameters _len -- Length of Sensor Raw value. _id -- Sensor Property ID. _len -- Length of Sensor Raw value. _id -- Sensor Property ID. _len -- Length of Sensor Raw value. Returns 3-octet MPID value for sensor data with Format B. Parameters _len -- Length of Sensor Raw value. _id -- Sensor Property ID. Returns 3-octet MPID value for sensor data with Format B. The Length field is a 1-based uint7 value (valid range 0x0–0x7F, representing range of 1–127). The value 0x7F represents a length of zero. Type Definitions typedef void (*esp_ble_mesh_sensor_client_cb_t)(esp_ble_mesh_sensor_client_cb_event_t event, esp_ble_mesh_sensor_client_cb_param_t *param) Bluetooth Mesh Sensor Client Model function. Sensor Client Model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter typedef void (*esp_ble_mesh_sensor_server_cb_t)(esp_ble_mesh_sensor_server_cb_event_t event, esp_ble_mesh_sensor_server_cb_param_t *param) Bluetooth Mesh Sensor Server Model function. Sensor Server Model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter Enumerations enum esp_ble_mesh_sensor_client_cb_event_t This enum value is the event of Sensor Client Model Values: enumerator ESP_BLE_MESH_SENSOR_CLIENT_GET_STATE_EVT enumerator ESP_BLE_MESH_SENSOR_CLIENT_GET_STATE_EVT enumerator ESP_BLE_MESH_SENSOR_CLIENT_SET_STATE_EVT enumerator ESP_BLE_MESH_SENSOR_CLIENT_SET_STATE_EVT enumerator ESP_BLE_MESH_SENSOR_CLIENT_PUBLISH_EVT enumerator ESP_BLE_MESH_SENSOR_CLIENT_PUBLISH_EVT enumerator ESP_BLE_MESH_SENSOR_CLIENT_TIMEOUT_EVT enumerator ESP_BLE_MESH_SENSOR_CLIENT_TIMEOUT_EVT enumerator ESP_BLE_MESH_SENSOR_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_SENSOR_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_SENSOR_CLIENT_GET_STATE_EVT enum esp_ble_mesh_sensor_sample_func This enum value is value of Sensor Sampling Function Values: enumerator ESP_BLE_MESH_SAMPLE_FUNC_UNSPECIFIED enumerator ESP_BLE_MESH_SAMPLE_FUNC_UNSPECIFIED enumerator ESP_BLE_MESH_SAMPLE_FUNC_INSTANTANEOUS enumerator ESP_BLE_MESH_SAMPLE_FUNC_INSTANTANEOUS enumerator ESP_BLE_MESH_SAMPLE_FUNC_ARITHMETIC_MEAN enumerator ESP_BLE_MESH_SAMPLE_FUNC_ARITHMETIC_MEAN enumerator ESP_BLE_MESH_SAMPLE_FUNC_RMS enumerator ESP_BLE_MESH_SAMPLE_FUNC_RMS enumerator ESP_BLE_MESH_SAMPLE_FUNC_MAXIMUM enumerator ESP_BLE_MESH_SAMPLE_FUNC_MAXIMUM enumerator ESP_BLE_MESH_SAMPLE_FUNC_MINIMUM enumerator ESP_BLE_MESH_SAMPLE_FUNC_MINIMUM enumerator ESP_BLE_MESH_SAMPLE_FUNC_ACCUMULATED enumerator ESP_BLE_MESH_SAMPLE_FUNC_ACCUMULATED enumerator ESP_BLE_MESH_SAMPLE_FUNC_COUNT enumerator ESP_BLE_MESH_SAMPLE_FUNC_COUNT enumerator ESP_BLE_MESH_SAMPLE_FUNC_UNSPECIFIED enum esp_ble_mesh_sensor_server_cb_event_t This enum value is the event of Sensor Server Model Values: enumerator ESP_BLE_MESH_SENSOR_SERVER_STATE_CHANGE_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Sensor Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Sensor Set/Set Unack messages are received. When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Sensor Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Sensor Set/Set Unack messages are received. When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Sensor Get messages are received. enumerator ESP_BLE_MESH_SENSOR_SERVER_STATE_CHANGE_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Sensor Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Sensor Set/Set Unack messages are received. enumerator ESP_BLE_MESH_SENSOR_SERVER_RECV_GET_MSG_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Sensor Get messages are received. enumerator ESP_BLE_MESH_SENSOR_SERVER_RECV_GET_MSG_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Sensor Get messages are received. enumerator ESP_BLE_MESH_SENSOR_SERVER_RECV_SET_MSG_EVT When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Sensor Set/Set Unack messages are received. enumerator ESP_BLE_MESH_SENSOR_SERVER_RECV_SET_MSG_EVT When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Sensor Set/Set Unack messages are received. enumerator ESP_BLE_MESH_SENSOR_SERVER_EVT_MAX enumerator ESP_BLE_MESH_SENSOR_SERVER_EVT_MAX enumerator ESP_BLE_MESH_SENSOR_SERVER_STATE_CHANGE_EVT Time and Scenes Client/Server Models Header File components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_time_scene_model_api.h This header file can be included with: #include "esp_ble_mesh_time_scene_model_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_time_scene_client_callback(esp_ble_mesh_time_scene_client_cb_t callback) Register BLE Mesh Time Scene Client Model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_time_scene_client_get_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_time_scene_client_get_state_t *get_state) Get the value of Time Scene Server Model states using the Time Scene Client Model get messages. Note If you want to know the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_time_scene_message_opcode_t in esp_ble_mesh_defs.h Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to time scene get message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to time scene get message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to time scene get message value. Shall not be set to NULL. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_time_scene_client_set_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_time_scene_client_set_state_t *set_state) Set the value of Time Scene Server Model states using the Time Scene Client Model set messages. Note If you want to know the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_time_scene_message_opcode_t in esp_ble_mesh_defs.h Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to time scene set message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to time scene set message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to time scene set message value. Shall not be set to NULL. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_register_time_scene_server_callback(esp_ble_mesh_time_scene_server_cb_t callback) Register BLE Mesh Time and Scenes Server Model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Unions union esp_ble_mesh_time_scene_client_get_state_t #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Client Model get message union. Public Members esp_ble_mesh_scheduler_act_get_t scheduler_act_get For ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_GET esp_ble_mesh_scheduler_act_get_t scheduler_act_get For ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_GET esp_ble_mesh_scheduler_act_get_t scheduler_act_get union esp_ble_mesh_time_scene_client_set_state_t #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Client Model set message union. Public Members esp_ble_mesh_time_set_t time_set For ESP_BLE_MESH_MODEL_OP_TIME_SET esp_ble_mesh_time_set_t time_set For ESP_BLE_MESH_MODEL_OP_TIME_SET esp_ble_mesh_time_zone_set_t time_zone_set For ESP_BLE_MESH_MODEL_OP_TIME_ZONE_SET esp_ble_mesh_time_zone_set_t time_zone_set For ESP_BLE_MESH_MODEL_OP_TIME_ZONE_SET esp_ble_mesh_tai_utc_delta_set_t tai_utc_delta_set For ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_SET esp_ble_mesh_tai_utc_delta_set_t tai_utc_delta_set For ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_SET esp_ble_mesh_time_role_set_t time_role_set For ESP_BLE_MESH_MODEL_OP_TIME_ROLE_SET esp_ble_mesh_time_role_set_t time_role_set For ESP_BLE_MESH_MODEL_OP_TIME_ROLE_SET esp_ble_mesh_scene_store_t scene_store For ESP_BLE_MESH_MODEL_OP_SCENE_STORE & ESP_BLE_MESH_MODEL_OP_SCENE_STORE_UNACK esp_ble_mesh_scene_store_t scene_store For ESP_BLE_MESH_MODEL_OP_SCENE_STORE & ESP_BLE_MESH_MODEL_OP_SCENE_STORE_UNACK esp_ble_mesh_scene_recall_t scene_recall For ESP_BLE_MESH_MODEL_OP_SCENE_RECALL & ESP_BLE_MESH_MODEL_OP_SCENE_RECALL_UNACK esp_ble_mesh_scene_recall_t scene_recall For ESP_BLE_MESH_MODEL_OP_SCENE_RECALL & ESP_BLE_MESH_MODEL_OP_SCENE_RECALL_UNACK esp_ble_mesh_scene_delete_t scene_delete For ESP_BLE_MESH_MODEL_OP_SCENE_DELETE & ESP_BLE_MESH_MODEL_OP_SCENE_DELETE_UNACK esp_ble_mesh_scene_delete_t scene_delete For ESP_BLE_MESH_MODEL_OP_SCENE_DELETE & ESP_BLE_MESH_MODEL_OP_SCENE_DELETE_UNACK esp_ble_mesh_scheduler_act_set_t scheduler_act_set For ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET & ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET_UNACK esp_ble_mesh_scheduler_act_set_t scheduler_act_set For ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET & ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET_UNACK esp_ble_mesh_time_set_t time_set union esp_ble_mesh_time_scene_client_status_cb_t #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Client Model received message union. Public Members esp_ble_mesh_time_status_cb_t time_status For ESP_BLE_MESH_MODEL_OP_TIME_STATUS esp_ble_mesh_time_status_cb_t time_status For ESP_BLE_MESH_MODEL_OP_TIME_STATUS esp_ble_mesh_time_zone_status_cb_t time_zone_status For ESP_BLE_MESH_MODEL_OP_TIME_ZONE_STATUS esp_ble_mesh_time_zone_status_cb_t time_zone_status For ESP_BLE_MESH_MODEL_OP_TIME_ZONE_STATUS esp_ble_mesh_tai_utc_delta_status_cb_t tai_utc_delta_status For ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_STATUS esp_ble_mesh_tai_utc_delta_status_cb_t tai_utc_delta_status For ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_STATUS esp_ble_mesh_time_role_status_cb_t time_role_status For ESP_BLE_MESH_MODEL_OP_TIME_ROLE_STATUS esp_ble_mesh_time_role_status_cb_t time_role_status For ESP_BLE_MESH_MODEL_OP_TIME_ROLE_STATUS esp_ble_mesh_scene_status_cb_t scene_status For ESP_BLE_MESH_MODEL_OP_SCENE_STATUS esp_ble_mesh_scene_status_cb_t scene_status For ESP_BLE_MESH_MODEL_OP_SCENE_STATUS esp_ble_mesh_scene_register_status_cb_t scene_register_status For ESP_BLE_MESH_MODEL_OP_SCENE_REGISTER_STATUS esp_ble_mesh_scene_register_status_cb_t scene_register_status For ESP_BLE_MESH_MODEL_OP_SCENE_REGISTER_STATUS esp_ble_mesh_scheduler_status_cb_t scheduler_status For ESP_BLE_MESH_MODEL_OP_SCHEDULER_STATUS esp_ble_mesh_scheduler_status_cb_t scheduler_status For ESP_BLE_MESH_MODEL_OP_SCHEDULER_STATUS esp_ble_mesh_scheduler_act_status_cb_t scheduler_act_status For ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_STATUS esp_ble_mesh_scheduler_act_status_cb_t scheduler_act_status For ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_STATUS esp_ble_mesh_time_status_cb_t time_status union esp_ble_mesh_time_scene_server_state_change_t #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Server Model state change value union. Public Members esp_ble_mesh_state_change_time_set_t time_set The recv_op in ctx can be used to decide which state is changed. Time Set esp_ble_mesh_state_change_time_set_t time_set The recv_op in ctx can be used to decide which state is changed. Time Set esp_ble_mesh_state_change_time_status_t time_status Time Status esp_ble_mesh_state_change_time_status_t time_status Time Status esp_ble_mesh_state_change_time_zone_set_t time_zone_set Time Zone Set esp_ble_mesh_state_change_time_zone_set_t time_zone_set Time Zone Set esp_ble_mesh_state_change_tai_utc_delta_set_t tai_utc_delta_set TAI UTC Delta Set esp_ble_mesh_state_change_tai_utc_delta_set_t tai_utc_delta_set TAI UTC Delta Set esp_ble_mesh_state_change_time_role_set_t time_role_set Time Role Set esp_ble_mesh_state_change_time_role_set_t time_role_set Time Role Set esp_ble_mesh_state_change_scene_store_t scene_store Scene Store esp_ble_mesh_state_change_scene_store_t scene_store Scene Store esp_ble_mesh_state_change_scene_recall_t scene_recall Scene Recall esp_ble_mesh_state_change_scene_recall_t scene_recall Scene Recall esp_ble_mesh_state_change_scene_delete_t scene_delete Scene Delete esp_ble_mesh_state_change_scene_delete_t scene_delete Scene Delete esp_ble_mesh_state_change_scheduler_act_set_t scheduler_act_set Scheduler Action Set esp_ble_mesh_state_change_scheduler_act_set_t scheduler_act_set Scheduler Action Set esp_ble_mesh_state_change_time_set_t time_set union esp_ble_mesh_time_scene_server_recv_get_msg_t #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Server Model received get message union. Public Members esp_ble_mesh_server_recv_scheduler_act_get_t scheduler_act Scheduler Action Get esp_ble_mesh_server_recv_scheduler_act_get_t scheduler_act Scheduler Action Get esp_ble_mesh_server_recv_scheduler_act_get_t scheduler_act union esp_ble_mesh_time_scene_server_recv_set_msg_t #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Server Model received set message union. Public Members esp_ble_mesh_server_recv_time_set_t time Time Set esp_ble_mesh_server_recv_time_set_t time Time Set esp_ble_mesh_server_recv_time_zone_set_t time_zone Time Zone Set esp_ble_mesh_server_recv_time_zone_set_t time_zone Time Zone Set esp_ble_mesh_server_recv_tai_utc_delta_set_t tai_utc_delta TAI-UTC Delta Set esp_ble_mesh_server_recv_tai_utc_delta_set_t tai_utc_delta TAI-UTC Delta Set esp_ble_mesh_server_recv_time_role_set_t time_role Time Role Set esp_ble_mesh_server_recv_time_role_set_t time_role Time Role Set esp_ble_mesh_server_recv_scene_store_t scene_store Scene Store/Scene Store Unack esp_ble_mesh_server_recv_scene_store_t scene_store Scene Store/Scene Store Unack esp_ble_mesh_server_recv_scene_recall_t scene_recall Scene Recall/Scene Recall Unack esp_ble_mesh_server_recv_scene_recall_t scene_recall Scene Recall/Scene Recall Unack esp_ble_mesh_server_recv_scene_delete_t scene_delete Scene Delete/Scene Delete Unack esp_ble_mesh_server_recv_scene_delete_t scene_delete Scene Delete/Scene Delete Unack esp_ble_mesh_server_recv_scheduler_act_set_t scheduler_act Scheduler Action Set/Scheduler Action Set Unack esp_ble_mesh_server_recv_scheduler_act_set_t scheduler_act Scheduler Action Set/Scheduler Action Set Unack esp_ble_mesh_server_recv_time_set_t time union esp_ble_mesh_time_scene_server_recv_status_msg_t #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Server Model received status message union. Public Members esp_ble_mesh_server_recv_time_status_t time_status Time Status esp_ble_mesh_server_recv_time_status_t time_status Time Status esp_ble_mesh_server_recv_time_status_t time_status union esp_ble_mesh_time_scene_server_cb_value_t #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Server Model callback value union. Public Members esp_ble_mesh_time_scene_server_state_change_t state_change ESP_BLE_MESH_TIME_SCENE_SERVER_STATE_CHANGE_EVT esp_ble_mesh_time_scene_server_state_change_t state_change ESP_BLE_MESH_TIME_SCENE_SERVER_STATE_CHANGE_EVT esp_ble_mesh_time_scene_server_recv_get_msg_t get ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_GET_MSG_EVT esp_ble_mesh_time_scene_server_recv_get_msg_t get ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_GET_MSG_EVT esp_ble_mesh_time_scene_server_recv_set_msg_t set ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_SET_MSG_EVT esp_ble_mesh_time_scene_server_recv_set_msg_t set ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_SET_MSG_EVT esp_ble_mesh_time_scene_server_recv_status_msg_t status ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_STATUS_MSG_EVT esp_ble_mesh_time_scene_server_recv_status_msg_t status ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_STATUS_MSG_EVT esp_ble_mesh_time_scene_server_state_change_t state_change Structures struct esp_ble_mesh_time_set_t Bluetooth Mesh Time Scene Client Model Get and Set parameters structure. Parameters of Time Set Public Members uint8_t tai_seconds[5] The current TAI time in seconds uint8_t tai_seconds[5] The current TAI time in seconds uint8_t sub_second The sub-second time in units of 1/256 second uint8_t sub_second The sub-second time in units of 1/256 second uint8_t uncertainty The estimated uncertainty in 10-millisecond steps uint8_t uncertainty The estimated uncertainty in 10-millisecond steps 0 = No Time Authority, 1 = Time Authority 0 = No Time Authority, 1 = Time Authority uint16_t tai_utc_delta Current difference between TAI and UTC in seconds uint16_t tai_utc_delta Current difference between TAI and UTC in seconds uint8_t time_zone_offset The local time zone offset in 15-minute increments uint8_t time_zone_offset The local time zone offset in 15-minute increments uint8_t tai_seconds[5] struct esp_ble_mesh_time_zone_set_t Parameters of Time Zone Set struct esp_ble_mesh_tai_utc_delta_set_t Parameters of TAI-UTC Delta Set struct esp_ble_mesh_time_role_set_t Parameter of Time Role Set struct esp_ble_mesh_scene_store_t Parameter of Scene Store struct esp_ble_mesh_scene_recall_t Parameters of Scene Recall struct esp_ble_mesh_scene_delete_t Parameter of Scene Delete struct esp_ble_mesh_scheduler_act_get_t Parameter of Scheduler Action Get Public Members uint8_t index Index of the Schedule Register entry to get uint8_t index Index of the Schedule Register entry to get uint8_t index struct esp_ble_mesh_scheduler_act_set_t Parameters of Scheduler Action Set Public Members uint64_t index Index of the Schedule Register entry to set uint64_t index Index of the Schedule Register entry to set uint64_t year Scheduled year for the action uint64_t year Scheduled year for the action uint64_t month Scheduled month for the action uint64_t month Scheduled month for the action uint64_t day Scheduled day of the month for the action uint64_t day Scheduled day of the month for the action uint64_t hour Scheduled hour for the action uint64_t hour Scheduled hour for the action uint64_t minute Scheduled minute for the action uint64_t minute Scheduled minute for the action uint64_t second Scheduled second for the action uint64_t second Scheduled second for the action uint64_t day_of_week Schedule days of the week for the action uint64_t day_of_week Schedule days of the week for the action uint64_t action Action to be performed at the scheduled time uint64_t action Action to be performed at the scheduled time uint64_t trans_time Transition time for this action uint64_t trans_time Transition time for this action uint16_t scene_number Transition time for this action uint16_t scene_number Transition time for this action uint64_t index struct esp_ble_mesh_time_status_cb_t Bluetooth Mesh Time Scene Client Model Get and Set callback parameters structure. Parameters of Time Status Public Members uint8_t tai_seconds[5] The current TAI time in seconds uint8_t tai_seconds[5] The current TAI time in seconds uint8_t sub_second The sub-second time in units of 1/256 second uint8_t sub_second The sub-second time in units of 1/256 second uint8_t uncertainty The estimated uncertainty in 10-millisecond steps uint8_t uncertainty The estimated uncertainty in 10-millisecond steps 0 = No Time Authority, 1 = Time Authority 0 = No Time Authority, 1 = Time Authority uint16_t tai_utc_delta Current difference between TAI and UTC in seconds uint16_t tai_utc_delta Current difference between TAI and UTC in seconds uint8_t time_zone_offset The local time zone offset in 15-minute increments uint8_t time_zone_offset The local time zone offset in 15-minute increments uint8_t tai_seconds[5] struct esp_ble_mesh_time_zone_status_cb_t Parameters of Time Zone Status struct esp_ble_mesh_tai_utc_delta_status_cb_t Parameters of TAI-UTC Delta Status Public Members uint16_t tai_utc_delta_curr Current difference between TAI and UTC in seconds uint16_t tai_utc_delta_curr Current difference between TAI and UTC in seconds uint16_t padding_1 Always 0b0. Other values are Prohibited. uint16_t padding_1 Always 0b0. Other values are Prohibited. uint16_t tai_utc_delta_new Upcoming difference between TAI and UTC in seconds uint16_t tai_utc_delta_new Upcoming difference between TAI and UTC in seconds uint16_t padding_2 Always 0b0. Other values are Prohibited. uint16_t padding_2 Always 0b0. Other values are Prohibited. uint8_t tai_delta_change[5] TAI Seconds time of the upcoming TAI-UTC Delta change uint8_t tai_delta_change[5] TAI Seconds time of the upcoming TAI-UTC Delta change uint16_t tai_utc_delta_curr struct esp_ble_mesh_time_role_status_cb_t Parameter of Time Role Status struct esp_ble_mesh_scene_status_cb_t Parameters of Scene Status Public Members bool op_en Indicate if optional parameters are included bool op_en Indicate if optional parameters are included uint8_t status_code Status code of the last operation uint8_t status_code Status code of the last operation uint16_t current_scene Scene Number of the current scene uint16_t current_scene Scene Number of the current scene uint16_t target_scene Scene Number of the target scene (optional) uint16_t target_scene Scene Number of the target scene (optional) uint8_t remain_time Time to complete state transition (C.1) uint8_t remain_time Time to complete state transition (C.1) bool op_en struct esp_ble_mesh_scene_register_status_cb_t Parameters of Scene Register Status struct esp_ble_mesh_scheduler_status_cb_t Parameter of Scheduler Status Public Members uint16_t schedules Bit field indicating defined Actions in the Schedule Register uint16_t schedules Bit field indicating defined Actions in the Schedule Register uint16_t schedules struct esp_ble_mesh_scheduler_act_status_cb_t Parameters of Scheduler Action Status Public Members uint64_t index Enumerates (selects) a Schedule Register entry uint64_t index Enumerates (selects) a Schedule Register entry uint64_t year Scheduled year for the action uint64_t year Scheduled year for the action uint64_t month Scheduled month for the action uint64_t month Scheduled month for the action uint64_t day Scheduled day of the month for the action uint64_t day Scheduled day of the month for the action uint64_t hour Scheduled hour for the action uint64_t hour Scheduled hour for the action uint64_t minute Scheduled minute for the action uint64_t minute Scheduled minute for the action uint64_t second Scheduled second for the action uint64_t second Scheduled second for the action uint64_t day_of_week Schedule days of the week for the action uint64_t day_of_week Schedule days of the week for the action uint64_t action Action to be performed at the scheduled time uint64_t action Action to be performed at the scheduled time uint64_t trans_time Transition time for this action uint64_t trans_time Transition time for this action uint16_t scene_number Transition time for this action uint16_t scene_number Transition time for this action uint64_t index struct esp_ble_mesh_time_scene_client_cb_param_t Time Scene Client Model callback parameters Public Members int error_code Appropriate error code int error_code Appropriate error code esp_ble_mesh_client_common_param_t *params The client common parameters. esp_ble_mesh_client_common_param_t *params The client common parameters. esp_ble_mesh_time_scene_client_status_cb_t status_cb The scene status message callback values esp_ble_mesh_time_scene_client_status_cb_t status_cb The scene status message callback values int error_code struct esp_ble_mesh_time_state_t Parameters of Time state Public Members uint8_t tai_seconds[5] The value of the TAI Seconds state uint8_t tai_seconds[5] The value of the TAI Seconds state uint8_t subsecond The value of the Subsecond field uint8_t subsecond The value of the Subsecond field uint8_t uncertainty The value of the Uncertainty field uint8_t uncertainty The value of the Uncertainty field uint8_t time_zone_offset_curr The value of the Time Zone Offset Current field uint8_t time_zone_offset_curr The value of the Time Zone Offset Current field uint8_t time_zone_offset_new The value of the Time Zone Offset New state uint8_t time_zone_offset_new The value of the Time Zone Offset New state uint8_t tai_zone_change[5] The value of the TAI of Zone Change field uint8_t tai_zone_change[5] The value of the TAI of Zone Change field The value of the Time Authority bit The value of the Time Authority bit uint16_t tai_utc_delta_curr The value of the TAI-UTC Delta Current state uint16_t tai_utc_delta_curr The value of the TAI-UTC Delta Current state uint16_t tai_utc_delta_new The value of the TAI-UTC Delta New state uint16_t tai_utc_delta_new The value of the TAI-UTC Delta New state uint8_t tai_delta_change[5] The value of the TAI of Delta Change field uint8_t tai_delta_change[5] The value of the TAI of Delta Change field struct esp_ble_mesh_time_state_t::[anonymous] time Parameters of the Time state struct esp_ble_mesh_time_state_t::[anonymous] time Parameters of the Time state uint8_t time_role The value of the Time Role state uint8_t time_role The value of the Time Role state uint8_t tai_seconds[5] struct esp_ble_mesh_time_srv_t User data of Time Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Time Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Time Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_time_state_t *state Parameters of the Time state esp_ble_mesh_time_state_t *state Parameters of the Time state esp_ble_mesh_model_t *model struct esp_ble_mesh_time_setup_srv_t User data of Time Setup Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Time Setup Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Time Setup Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_time_state_t *state Parameters of the Time state esp_ble_mesh_time_state_t *state Parameters of the Time state esp_ble_mesh_model_t *model struct esp_ble_mesh_scene_register_t Scene Store is an operation of storing values of a present state of an element. The structure and meaning of the stored state is determined by a model. States to be stored are specified by each model. The Scene Store operation shall persistently store all values of all states marked as Stored with Scene for all models present on all elements of a node. If a model is extending another model, the extending model shall determine the Stored with Scene behavior of that model. Parameters of Scene Register state Scene Store is an operation of storing values of a present state of an element. The structure and meaning of the stored state is determined by a model. States to be stored are specified by each model. The Scene Store operation shall persistently store all values of all states marked as Stored with Scene for all models present on all elements of a node. If a model is extending another model, the extending model shall determine the Stored with Scene behavior of that model. Parameters of Scene Register state Public Members uint16_t scene_number The value of the Scene Number uint16_t scene_number The value of the Scene Number uint8_t scene_type The value of the Scene Type uint8_t scene_type The value of the Scene Type struct net_buf_simple *scene_value Scene value may use a union to represent later, the union contains structures of all the model states which can be stored in a scene. The value of the Scene Value struct net_buf_simple *scene_value Scene value may use a union to represent later, the union contains structures of all the model states which can be stored in a scene. The value of the Scene Value Scene Store is an operation of storing values of a present state of an element. struct esp_ble_mesh_scenes_state_t Parameters of Scenes state. Scenes serve as memory banks for storage of states (e.g., a power level or a light level/color). Values of states of an element can be stored as a scene and can be recalled later from the scene memory. A scene is represented by a Scene Number, which is a 16-bit non-zero, mesh-wide value. (There can be a maximum of 65535 scenes in a mesh network.) The meaning of a scene, as well as the state storage container associated with it, are determined by a model. The Scenes state change may start numerous parallel model transitions. In that case, each individual model handles the transition internally. The scene transition is defined as a group of individual model transitions started by a Scene Recall operation. The scene transition is in progress when at least one transition from the group of individual model transitions is in progress. Public Members const uint16_t scene_count The Scenes state's scene count const uint16_t scene_count The Scenes state's scene count esp_ble_mesh_scene_register_t *scenes Parameters of the Scenes state esp_ble_mesh_scene_register_t *scenes Parameters of the Scenes state uint16_t current_scene The Current Scene state is a 16-bit value that contains either the Scene Number of the currently active scene or a value of 0x0000 when no scene is active. When a Scene Store operation or a Scene Recall operation completes with success, the Current Scene state value shall be to the Scene Number used during that operation. When the Current Scene Number is deleted from a Scene Register state as a result of Scene Delete operation, the Current Scene state shall be set to 0x0000. When any of the element's state that is marked as “Stored with Scene” has changed not as a result of a Scene Recall operation, the value of the Current Scene state shall be set to 0x0000. When a scene transition is in progress, the value of the Current Scene state shall be set to 0x0000. The value of the Current Scene state uint16_t current_scene The Current Scene state is a 16-bit value that contains either the Scene Number of the currently active scene or a value of 0x0000 when no scene is active. When a Scene Store operation or a Scene Recall operation completes with success, the Current Scene state value shall be to the Scene Number used during that operation. When the Current Scene Number is deleted from a Scene Register state as a result of Scene Delete operation, the Current Scene state shall be set to 0x0000. When any of the element's state that is marked as “Stored with Scene” has changed not as a result of a Scene Recall operation, the value of the Current Scene state shall be set to 0x0000. When a scene transition is in progress, the value of the Current Scene state shall be set to 0x0000. The value of the Current Scene state uint16_t target_scene The Target Scene state is a 16-bit value that contains the target Scene Number when a scene transition is in progress. When the scene transition is in progress and the target Scene Number is deleted from a Scene Register state as a result of Scene Delete operation, the Target Scene state shall be set to 0x0000. When the scene transition is in progress and a new Scene Number is stored in the Scene Register as a result of Scene Store operation, the Target Scene state shall be set to the new Scene Number. When the scene transition is not in progress, the value of the Target Scene state shall be set to 0x0000. The value of the Target Scene state uint16_t target_scene The Target Scene state is a 16-bit value that contains the target Scene Number when a scene transition is in progress. When the scene transition is in progress and the target Scene Number is deleted from a Scene Register state as a result of Scene Delete operation, the Target Scene state shall be set to 0x0000. When the scene transition is in progress and a new Scene Number is stored in the Scene Register as a result of Scene Store operation, the Target Scene state shall be set to the new Scene Number. When the scene transition is not in progress, the value of the Target Scene state shall be set to 0x0000. The value of the Target Scene state uint8_t status_code The status code of the last scene operation uint8_t status_code The status code of the last scene operation bool in_progress Indicate if the scene transition is in progress bool in_progress Indicate if the scene transition is in progress const uint16_t scene_count struct esp_ble_mesh_scene_srv_t User data of Scene Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Scene Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Scene Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_scenes_state_t *state Parameters of the Scenes state esp_ble_mesh_scenes_state_t *state Parameters of the Scenes state esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_state_transition_t transition Parameters of state transition esp_ble_mesh_state_transition_t transition Parameters of state transition esp_ble_mesh_model_t *model struct esp_ble_mesh_scene_setup_srv_t User data of Scene Setup Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Scene Setup Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Scene Setup Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_scenes_state_t *state Parameters of the Scenes state esp_ble_mesh_scenes_state_t *state Parameters of the Scenes state esp_ble_mesh_model_t *model struct esp_ble_mesh_schedule_register_t Parameters of Scheduler Register state Public Members bool in_use Indicate if the registered schedule is in use bool in_use Indicate if the registered schedule is in use uint64_t year The value of Scheduled year for the action uint64_t year The value of Scheduled year for the action uint64_t month The value of Scheduled month for the action uint64_t month The value of Scheduled month for the action uint64_t day The value of Scheduled day of the month for the action uint64_t day The value of Scheduled day of the month for the action uint64_t hour The value of Scheduled hour for the action uint64_t hour The value of Scheduled hour for the action uint64_t minute The value of Scheduled minute for the action uint64_t minute The value of Scheduled minute for the action uint64_t second The value of Scheduled second for the action uint64_t second The value of Scheduled second for the action uint64_t day_of_week The value of Schedule days of the week for the action uint64_t day_of_week The value of Schedule days of the week for the action uint64_t action The value of Action to be performed at the scheduled time uint64_t action The value of Action to be performed at the scheduled time uint64_t trans_time The value of Transition time for this action uint64_t trans_time The value of Transition time for this action uint16_t scene_number The value of Scene Number to be used for some actions uint16_t scene_number The value of Scene Number to be used for some actions bool in_use struct esp_ble_mesh_scheduler_state_t Parameters of Scheduler state Public Members const uint8_t schedule_count Scheduler count const uint8_t schedule_count Scheduler count esp_ble_mesh_schedule_register_t *schedules Up to 16 scheduled entries esp_ble_mesh_schedule_register_t *schedules Up to 16 scheduled entries const uint8_t schedule_count struct esp_ble_mesh_scheduler_srv_t User data of Scheduler Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Scheduler Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Scheduler Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_scheduler_state_t *state Parameters of the Scheduler state esp_ble_mesh_scheduler_state_t *state Parameters of the Scheduler state esp_ble_mesh_model_t *model struct esp_ble_mesh_scheduler_setup_srv_t User data of Scheduler Setup Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Scheduler Setup Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Scheduler Setup Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_scheduler_state_t *state Parameters of the Scheduler state esp_ble_mesh_scheduler_state_t *state Parameters of the Scheduler state esp_ble_mesh_model_t *model struct esp_ble_mesh_state_change_time_set_t Parameters of Time Set state change event Public Members uint8_t tai_seconds[5] The current TAI time in seconds uint8_t tai_seconds[5] The current TAI time in seconds uint8_t subsecond The sub-second time in units of 1/256 second uint8_t subsecond The sub-second time in units of 1/256 second uint8_t uncertainty The estimated uncertainty in 10-millisecond steps uint8_t uncertainty The estimated uncertainty in 10-millisecond steps 0 = No Time Authority, 1 = Time Authority 0 = No Time Authority, 1 = Time Authority uint16_t tai_utc_delta_curr Current difference between TAI and UTC in seconds uint16_t tai_utc_delta_curr Current difference between TAI and UTC in seconds uint8_t time_zone_offset_curr The local time zone offset in 15-minute increments uint8_t time_zone_offset_curr The local time zone offset in 15-minute increments uint8_t tai_seconds[5] struct esp_ble_mesh_state_change_time_status_t Parameters of Time Status state change event Public Members uint8_t tai_seconds[5] The current TAI time in seconds uint8_t tai_seconds[5] The current TAI time in seconds uint8_t subsecond The sub-second time in units of 1/256 second uint8_t subsecond The sub-second time in units of 1/256 second uint8_t uncertainty The estimated uncertainty in 10-millisecond steps uint8_t uncertainty The estimated uncertainty in 10-millisecond steps 0 = No Time Authority, 1 = Time Authority 0 = No Time Authority, 1 = Time Authority uint16_t tai_utc_delta_curr Current difference between TAI and UTC in seconds uint16_t tai_utc_delta_curr Current difference between TAI and UTC in seconds uint8_t time_zone_offset_curr The local time zone offset in 15-minute increments uint8_t time_zone_offset_curr The local time zone offset in 15-minute increments uint8_t tai_seconds[5] struct esp_ble_mesh_state_change_time_zone_set_t Parameters of Time Zone Set state change event struct esp_ble_mesh_state_change_tai_utc_delta_set_t Parameters of TAI UTC Delta Set state change event struct esp_ble_mesh_state_change_time_role_set_t Parameter of Time Role Set state change event struct esp_ble_mesh_state_change_scene_store_t Parameter of Scene Store state change event struct esp_ble_mesh_state_change_scene_recall_t Parameter of Scene Recall state change event Public Members uint16_t scene_number The number of scenes to be recalled uint16_t scene_number The number of scenes to be recalled uint16_t scene_number struct esp_ble_mesh_state_change_scene_delete_t Parameter of Scene Delete state change event struct esp_ble_mesh_state_change_scheduler_act_set_t Parameter of Scheduler Action Set state change event Public Members uint64_t index Index of the Schedule Register entry to set uint64_t index Index of the Schedule Register entry to set uint64_t year Scheduled year for the action uint64_t year Scheduled year for the action uint64_t month Scheduled month for the action uint64_t month Scheduled month for the action uint64_t day Scheduled day of the month for the action uint64_t day Scheduled day of the month for the action uint64_t hour Scheduled hour for the action uint64_t hour Scheduled hour for the action uint64_t minute Scheduled minute for the action uint64_t minute Scheduled minute for the action uint64_t second Scheduled second for the action uint64_t second Scheduled second for the action uint64_t day_of_week Schedule days of the week for the action uint64_t day_of_week Schedule days of the week for the action uint64_t action Action to be performed at the scheduled time uint64_t action Action to be performed at the scheduled time uint64_t trans_time Transition time for this action uint64_t trans_time Transition time for this action uint16_t scene_number Scene number to be used for some actions uint16_t scene_number Scene number to be used for some actions uint64_t index struct esp_ble_mesh_server_recv_scheduler_act_get_t Context of the received Scheduler Action Get message Public Members uint8_t index Index of the Schedule Register entry to get uint8_t index Index of the Schedule Register entry to get uint8_t index struct esp_ble_mesh_server_recv_time_set_t Context of the received Time Set message Public Members uint8_t tai_seconds[5] The current TAI time in seconds uint8_t tai_seconds[5] The current TAI time in seconds uint8_t subsecond The sub-second time in units of 1/256 second uint8_t subsecond The sub-second time in units of 1/256 second uint8_t uncertainty The estimated uncertainty in 10-millisecond steps uint8_t uncertainty The estimated uncertainty in 10-millisecond steps 0 = No Time Authority, 1 = Time Authority 0 = No Time Authority, 1 = Time Authority uint16_t tai_utc_delta Current difference between TAI and UTC in seconds uint16_t tai_utc_delta Current difference between TAI and UTC in seconds uint8_t time_zone_offset The local time zone offset in 15-minute increments uint8_t time_zone_offset The local time zone offset in 15-minute increments uint8_t tai_seconds[5] struct esp_ble_mesh_server_recv_time_zone_set_t Context of the received Time Zone Set message struct esp_ble_mesh_server_recv_tai_utc_delta_set_t Context of the received TAI UTC Delta Set message struct esp_ble_mesh_server_recv_time_role_set_t Context of the received Time Role Set message struct esp_ble_mesh_server_recv_scene_store_t Context of the received Scene Store message struct esp_ble_mesh_server_recv_scene_recall_t Context of the received Scene Recall message struct esp_ble_mesh_server_recv_scene_delete_t Context of the received Scene Delete message struct esp_ble_mesh_server_recv_scheduler_act_set_t Context of the received Scheduler Action Set message Public Members uint64_t index Index of the Schedule Register entry to set uint64_t index Index of the Schedule Register entry to set uint64_t year Scheduled year for the action uint64_t year Scheduled year for the action uint64_t month Scheduled month for the action uint64_t month Scheduled month for the action uint64_t day Scheduled day of the month for the action uint64_t day Scheduled day of the month for the action uint64_t hour Scheduled hour for the action uint64_t hour Scheduled hour for the action uint64_t minute Scheduled minute for the action uint64_t minute Scheduled minute for the action uint64_t second Scheduled second for the action uint64_t second Scheduled second for the action uint64_t day_of_week Schedule days of the week for the action uint64_t day_of_week Schedule days of the week for the action uint64_t action Action to be performed at the scheduled time uint64_t action Action to be performed at the scheduled time uint64_t trans_time Transition time for this action uint64_t trans_time Transition time for this action uint16_t scene_number Scene number to be used for some actions uint16_t scene_number Scene number to be used for some actions uint64_t index struct esp_ble_mesh_server_recv_time_status_t Context of the received Time Status message Public Members uint8_t tai_seconds[5] The current TAI time in seconds uint8_t tai_seconds[5] The current TAI time in seconds uint8_t subsecond The sub-second time in units of 1/256 second uint8_t subsecond The sub-second time in units of 1/256 second uint8_t uncertainty The estimated uncertainty in 10-millisecond steps uint8_t uncertainty The estimated uncertainty in 10-millisecond steps 0 = No Time Authority, 1 = Time Authority 0 = No Time Authority, 1 = Time Authority uint16_t tai_utc_delta Current difference between TAI and UTC in seconds uint16_t tai_utc_delta Current difference between TAI and UTC in seconds uint8_t time_zone_offset The local time zone offset in 15-minute increments uint8_t time_zone_offset The local time zone offset in 15-minute increments uint8_t tai_seconds[5] struct esp_ble_mesh_time_scene_server_cb_param_t Time Scene Server Model callback parameters Public Members esp_ble_mesh_model_t *model Pointer to Time and Scenes Server Models esp_ble_mesh_model_t *model Pointer to Time and Scenes Server Models esp_ble_mesh_msg_ctx_t ctx Context of the received messages esp_ble_mesh_msg_ctx_t ctx Context of the received messages esp_ble_mesh_time_scene_server_cb_value_t value Value of the received Time and Scenes Messages esp_ble_mesh_time_scene_server_cb_value_t value Value of the received Time and Scenes Messages esp_ble_mesh_model_t *model Macros ESP_BLE_MESH_MODEL_TIME_CLI(cli_pub, cli_data) Define a new Time Client Model. Note This API needs to be called for each element on which the application needs to have a Time Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Time Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Time Client Model instance. ESP_BLE_MESH_MODEL_SCENE_CLI(cli_pub, cli_data) Define a new Scene Client Model. Note This API needs to be called for each element on which the application needs to have a Scene Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Scene Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Scene Client Model instance. ESP_BLE_MESH_MODEL_SCHEDULER_CLI(cli_pub, cli_data) Define a new Scheduler Client Model. Note This API needs to be called for each element on which the application needs to have a Scheduler Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Scheduler Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Scheduler Client Model instance. ESP_BLE_MESH_MODEL_TIME_SRV(srv_pub, srv_data) Time Scene Server Models related context. Define a new Time Server Model. Note 1. The Time Server model is a root model. When this model is present on an Element, the corresponding Time Setup Server model shall also be present. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_time_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_time_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Time Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_time_srv_t. Returns New Time Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_TIME_SETUP_SRV(srv_data) Define a new Time Setup Server Model. Note 1. The Time Setup Server model extends the Time Server model. Time is sensitive information that is propagated across a mesh network. Only an authorized Time Client should be allowed to change the Time and Time Role states. A dedicated application key Bluetooth SIG Proprietary should be used on the Time Setup Server to restrict access to the server to only authorized Time Clients. This model does not support subscribing nor publishing. Only an authorized Time Client should be allowed to change the Time and Time Role states. A dedicated application key Bluetooth SIG Proprietary should be used on the Time Setup Server to restrict access to the server to only authorized Time Clients. This model does not support subscribing nor publishing. Parameters srv_data -- Pointer to the unique struct esp_ble_mesh_time_setup_srv_t. srv_data -- Pointer to the unique struct esp_ble_mesh_time_setup_srv_t. srv_data -- Pointer to the unique struct esp_ble_mesh_time_setup_srv_t. Returns New Time Setup Server Model instance. Parameters srv_data -- Pointer to the unique struct esp_ble_mesh_time_setup_srv_t. Returns New Time Setup Server Model instance. Only an authorized Time Client should be allowed to change the Time and Time Role states. A dedicated application key Bluetooth SIG Proprietary should be used on the Time Setup Server to restrict access to the server to only authorized Time Clients. ESP_BLE_MESH_MODEL_SCENE_SRV(srv_pub, srv_data) Define a new Scene Server Model. Note 1. The Scene Server model is a root model. When this model is present on an Element, the corresponding Scene Setup Server model shall also be present. This model shall support model publication and model subscription. The model may be present only on the Primary element of a node. This model shall support model publication and model subscription. The model may be present only on the Primary element of a node. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scene_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scene_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Scene Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scene_srv_t. Returns New Scene Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_SCENE_SETUP_SRV(srv_pub, srv_data) Define a new Scene Setup Server Model. Note 1. The Scene Setup Server model extends the Scene Server model and the Generic Default Transition Time Server model. This model shall support model subscription. The model may be present only on the Primary element of a node. This model shall support model subscription. The model may be present only on the Primary element of a node. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scene_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scene_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Scene Setup Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scene_setup_srv_t. Returns New Scene Setup Server Model instance. This model shall support model subscription. ESP_BLE_MESH_MODEL_SCHEDULER_SRV(srv_pub, srv_data) Define a new Scheduler Server Model. Note 1. The Scheduler Server model extends the Scene Server model. When this model is present on an Element, the corresponding Scheduler Setup Server model shall also be present. This model shall support model publication and model subscription. The model may be present only on the Primary element of a node. The model requires the Time Server model shall be present on the element. This model shall support model publication and model subscription. The model may be present only on the Primary element of a node. The model requires the Time Server model shall be present on the element. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scheduler_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scheduler_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Scheduler Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scheduler_srv_t. Returns New Scheduler Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_SCHEDULER_SETUP_SRV(srv_pub, srv_data) Define a new Scheduler Setup Server Model. Note 1. The Scheduler Setup Server model extends the Scheduler Server and the Scene Setup Server models. This model shall support model subscription. The model may be present only on the Primary element of a node. This model shall support model subscription. The model may be present only on the Primary element of a node. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scheduler_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scheduler_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Scheduler Setup Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scheduler_setup_srv_t. Returns New Scheduler Setup Server Model instance. This model shall support model subscription. ESP_BLE_MESH_UNKNOWN_TAI_SECONDS Unknown TAI Seconds ESP_BLE_MESH_UNKNOWN_TAI_ZONE_CHANGE Unknown TAI of Zone Change ESP_BLE_MESH_UNKNOWN_TAI_DELTA_CHANGE Unknown TAI of Delta Change ESP_BLE_MESH_TAI_UTC_DELTA_MAX_VALUE Maximum TAI-UTC Delta value ESP_BLE_MESH_TAI_SECONDS_LEN Length of TAI Seconds ESP_BLE_MESH_TAI_OF_ZONE_CHANGE_LEN Length of TAI of Zone Change ESP_BLE_MESH_TAI_OF_DELTA_CHANGE_LEN Length of TAI of Delta Change ESP_BLE_MESH_INVALID_SCENE_NUMBER Invalid Scene Number ESP_BLE_MESH_SCENE_NUMBER_LEN Length of the Scene Number ESP_BLE_MESH_SCHEDULE_YEAR_ANY_YEAR Any year of the Scheduled year ESP_BLE_MESH_SCHEDULE_DAY_ANY_DAY Any day of the Scheduled day ESP_BLE_MESH_SCHEDULE_HOUR_ANY_HOUR Any hour of the Scheduled hour ESP_BLE_MESH_SCHEDULE_HOUR_ONCE_A_DAY Any hour of the Scheduled Day ESP_BLE_MESH_SCHEDULE_SEC_ANY_OF_HOUR Any minute of the Scheduled hour ESP_BLE_MESH_SCHEDULE_SEC_EVERY_15_MIN Every 15 minutes of the Scheduled hour ESP_BLE_MESH_SCHEDULE_SEC_EVERY_20_MIN Every 20 minutes of the Scheduled hour ESP_BLE_MESH_SCHEDULE_SEC_ONCE_AN_HOUR Once of the Scheduled hour ESP_BLE_MESH_SCHEDULE_SEC_ANY_OF_MIN Any second of the Scheduled minute ESP_BLE_MESH_SCHEDULE_SEC_EVERY_15_SEC Every 15 seconds of the Scheduled minute ESP_BLE_MESH_SCHEDULE_SEC_EVERY_20_SEC Every 20 seconds of the Scheduled minute ESP_BLE_MESH_SCHEDULE_SEC_ONCE_AN_MIN Once of the Scheduled minute ESP_BLE_MESH_SCHEDULE_ACT_TURN_OFF Scheduled Action - Turn Off ESP_BLE_MESH_SCHEDULE_ACT_TURN_ON Scheduled Action - Turn On ESP_BLE_MESH_SCHEDULE_ACT_SCENE_RECALL Scheduled Action - Scene Recall ESP_BLE_MESH_SCHEDULE_ACT_NO_ACTION Scheduled Action - No Action ESP_BLE_MESH_SCHEDULE_SCENE_NO_SCENE Scheduled Scene - No Scene ESP_BLE_MESH_SCHEDULE_ENTRY_MAX_INDEX Maximum number of Scheduled entries ESP_BLE_MESH_TIME_NONE Time Role - None ESP_BLE_MESH_TIME_AUTHORITY Time Role - Mesh Time Authority ESP_BLE_MESH_TIME_RELAY Time Role - Mesh Time Relay ESP_BLE_MESH_TIME_CLIENT Time Role - Mesh Time Client ESP_BLE_MESH_SCENE_SUCCESS Scene operation - Success ESP_BLE_MESH_SCENE_REG_FULL Scene operation - Scene Register Full ESP_BLE_MESH_SCENE_NOT_FOUND Scene operation - Scene Not Found Type Definitions typedef void (*esp_ble_mesh_time_scene_client_cb_t)(esp_ble_mesh_time_scene_client_cb_event_t event, esp_ble_mesh_time_scene_client_cb_param_t *param) Bluetooth Mesh Time Scene Client Model function. Time Scene Client Model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter typedef void (*esp_ble_mesh_time_scene_server_cb_t)(esp_ble_mesh_time_scene_server_cb_event_t event, esp_ble_mesh_time_scene_server_cb_param_t *param) Bluetooth Mesh Time and Scenes Server Model function. Time Scene Server Model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter Enumerations enum esp_ble_mesh_time_scene_client_cb_event_t This enum value is the event of Time Scene Client Model Values: enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_GET_STATE_EVT enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_GET_STATE_EVT enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_SET_STATE_EVT enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_SET_STATE_EVT enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_PUBLISH_EVT enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_PUBLISH_EVT enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_TIMEOUT_EVT enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_TIMEOUT_EVT enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_GET_STATE_EVT enum esp_ble_mesh_time_scene_server_cb_event_t This enum value is the event of Time Scene Server Model Values: enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_STATE_CHANGE_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Time Scene Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Time Scene Set/Set Unack messages are received. When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Time Scene Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Time Scene Set/Set Unack messages are received. When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Time Scene Get messages are received. enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_STATE_CHANGE_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Time Scene Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Time Scene Set/Set Unack messages are received. enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_GET_MSG_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Time Scene Get messages are received. enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_GET_MSG_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Time Scene Get messages are received. enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_SET_MSG_EVT When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Time Scene Set/Set Unack messages are received. enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_SET_MSG_EVT When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Time Scene Set/Set Unack messages are received. enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_STATUS_MSG_EVT When status_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when TIme Status message is received. enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_STATUS_MSG_EVT When status_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when TIme Status message is received. enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_EVT_MAX enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_EVT_MAX enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_STATE_CHANGE_EVT Lighting Client/Server Models Header File components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_lighting_model_api.h This header file can be included with: #include "esp_ble_mesh_lighting_model_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_light_client_callback(esp_ble_mesh_light_client_cb_t callback) Register BLE Mesh Light Client Model callback. Parameters callback -- [in] pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_light_client_get_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_light_client_get_state_t *get_state) Get the value of Light Server Model states using the Light Client Model get messages. Note If you want to know the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_light_message_opcode_t in esp_ble_mesh_defs.h Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer of light get message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer of light get message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer of light get message value. Shall not be set to NULL. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_light_client_set_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_light_client_set_state_t *set_state) Set the value of Light Server Model states using the Light Client Model set messages. Note If you want to know the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_light_message_opcode_t in esp_ble_mesh_defs.h Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer of light set message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer of light set message value. Shall not be set to NULL. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer of light set message value. Shall not be set to NULL. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_register_lighting_server_callback(esp_ble_mesh_lighting_server_cb_t callback) Register BLE Mesh Lighting Server Model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Unions union esp_ble_mesh_light_client_get_state_t #include <esp_ble_mesh_lighting_model_api.h> Lighting Client Model get message union. Public Members esp_ble_mesh_light_lc_property_get_t lc_property_get For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_GET esp_ble_mesh_light_lc_property_get_t lc_property_get For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_GET esp_ble_mesh_light_lc_property_get_t lc_property_get union esp_ble_mesh_light_client_set_state_t #include <esp_ble_mesh_lighting_model_api.h> Lighting Client Model set message union. Public Members esp_ble_mesh_light_lightness_set_t lightness_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET_UNACK esp_ble_mesh_light_lightness_set_t lightness_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET_UNACK esp_ble_mesh_light_lightness_linear_set_t lightness_linear_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET_UNACK esp_ble_mesh_light_lightness_linear_set_t lightness_linear_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET_UNACK esp_ble_mesh_light_lightness_default_set_t lightness_default_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET_UNACK esp_ble_mesh_light_lightness_default_set_t lightness_default_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET_UNACK esp_ble_mesh_light_lightness_range_set_t lightness_range_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET_UNACK esp_ble_mesh_light_lightness_range_set_t lightness_range_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET_UNACK esp_ble_mesh_light_ctl_set_t ctl_set For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_SET_UNACK esp_ble_mesh_light_ctl_set_t ctl_set For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_SET_UNACK esp_ble_mesh_light_ctl_temperature_set_t ctl_temperature_set For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET_UNACK esp_ble_mesh_light_ctl_temperature_set_t ctl_temperature_set For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET_UNACK esp_ble_mesh_light_ctl_temperature_range_set_t ctl_temperature_range_set For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET_UNACK esp_ble_mesh_light_ctl_temperature_range_set_t ctl_temperature_range_set For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET_UNACK esp_ble_mesh_light_ctl_default_set_t ctl_default_set For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET_UNACK esp_ble_mesh_light_ctl_default_set_t ctl_default_set For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET_UNACK esp_ble_mesh_light_hsl_set_t hsl_set For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SET_UNACK esp_ble_mesh_light_hsl_set_t hsl_set For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SET_UNACK esp_ble_mesh_light_hsl_hue_set_t hsl_hue_set For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_SET_UNACK esp_ble_mesh_light_hsl_hue_set_t hsl_hue_set For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_SET_UNACK esp_ble_mesh_light_hsl_saturation_set_t hsl_saturation_set For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET_UNACK esp_ble_mesh_light_hsl_saturation_set_t hsl_saturation_set For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET_UNACK esp_ble_mesh_light_hsl_default_set_t hsl_default_set For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET_UNACK esp_ble_mesh_light_hsl_default_set_t hsl_default_set For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET_UNACK esp_ble_mesh_light_hsl_range_set_t hsl_range_set For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET_UNACK esp_ble_mesh_light_hsl_range_set_t hsl_range_set For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET_UNACK esp_ble_mesh_light_xyl_set_t xyl_set For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_SET_UNACK esp_ble_mesh_light_xyl_set_t xyl_set For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_SET_UNACK esp_ble_mesh_light_xyl_default_set_t xyl_default_set For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET_UNACK esp_ble_mesh_light_xyl_default_set_t xyl_default_set For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET_UNACK esp_ble_mesh_light_xyl_range_set_t xyl_range_set For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET_UNACK esp_ble_mesh_light_xyl_range_set_t xyl_range_set For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET_UNACK esp_ble_mesh_light_lc_mode_set_t lc_mode_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET_UNACK esp_ble_mesh_light_lc_mode_set_t lc_mode_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET_UNACK esp_ble_mesh_light_lc_om_set_t lc_om_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET_UNACK esp_ble_mesh_light_lc_om_set_t lc_om_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET_UNACK esp_ble_mesh_light_lc_light_onoff_set_t lc_light_onoff_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET_UNACK esp_ble_mesh_light_lc_light_onoff_set_t lc_light_onoff_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET_UNACK esp_ble_mesh_light_lc_property_set_t lc_property_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET_UNACK esp_ble_mesh_light_lc_property_set_t lc_property_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET_UNACK esp_ble_mesh_light_lightness_set_t lightness_set union esp_ble_mesh_light_client_status_cb_t #include <esp_ble_mesh_lighting_model_api.h> Lighting Client Model received message union. Public Members esp_ble_mesh_light_lightness_status_cb_t lightness_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_STATUS esp_ble_mesh_light_lightness_status_cb_t lightness_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_STATUS esp_ble_mesh_light_lightness_linear_status_cb_t lightness_linear_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_STATUS esp_ble_mesh_light_lightness_linear_status_cb_t lightness_linear_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_STATUS esp_ble_mesh_light_lightness_last_status_cb_t lightness_last_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LAST_STATUS esp_ble_mesh_light_lightness_last_status_cb_t lightness_last_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LAST_STATUS esp_ble_mesh_light_lightness_default_status_cb_t lightness_default_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_STATUS esp_ble_mesh_light_lightness_default_status_cb_t lightness_default_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_STATUS esp_ble_mesh_light_lightness_range_status_cb_t lightness_range_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_STATUS esp_ble_mesh_light_lightness_range_status_cb_t lightness_range_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_STATUS esp_ble_mesh_light_ctl_status_cb_t ctl_status For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_STATUS esp_ble_mesh_light_ctl_status_cb_t ctl_status For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_STATUS esp_ble_mesh_light_ctl_temperature_status_cb_t ctl_temperature_status For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_STATUS esp_ble_mesh_light_ctl_temperature_status_cb_t ctl_temperature_status For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_STATUS esp_ble_mesh_light_ctl_temperature_range_status_cb_t ctl_temperature_range_status For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_STATUS esp_ble_mesh_light_ctl_temperature_range_status_cb_t ctl_temperature_range_status For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_STATUS esp_ble_mesh_light_ctl_default_status_cb_t ctl_default_status For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_STATUS esp_ble_mesh_light_ctl_default_status_cb_t ctl_default_status For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_STATUS esp_ble_mesh_light_hsl_status_cb_t hsl_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_STATUS esp_ble_mesh_light_hsl_status_cb_t hsl_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_STATUS esp_ble_mesh_light_hsl_target_status_cb_t hsl_target_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_TARGET_STATUS esp_ble_mesh_light_hsl_target_status_cb_t hsl_target_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_TARGET_STATUS esp_ble_mesh_light_hsl_hue_status_cb_t hsl_hue_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_STATUS esp_ble_mesh_light_hsl_hue_status_cb_t hsl_hue_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_STATUS esp_ble_mesh_light_hsl_saturation_status_cb_t hsl_saturation_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_STATUS esp_ble_mesh_light_hsl_saturation_status_cb_t hsl_saturation_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_STATUS esp_ble_mesh_light_hsl_default_status_cb_t hsl_default_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_STATUS esp_ble_mesh_light_hsl_default_status_cb_t hsl_default_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_STATUS esp_ble_mesh_light_hsl_range_status_cb_t hsl_range_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_STATUS esp_ble_mesh_light_hsl_range_status_cb_t hsl_range_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_STATUS esp_ble_mesh_light_xyl_status_cb_t xyl_status For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_STATUS esp_ble_mesh_light_xyl_status_cb_t xyl_status For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_STATUS esp_ble_mesh_light_xyl_target_status_cb_t xyl_target_status For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_TARGET_STATUS esp_ble_mesh_light_xyl_target_status_cb_t xyl_target_status For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_TARGET_STATUS esp_ble_mesh_light_xyl_default_status_cb_t xyl_default_status For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_STATUS esp_ble_mesh_light_xyl_default_status_cb_t xyl_default_status For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_STATUS esp_ble_mesh_light_xyl_range_status_cb_t xyl_range_status For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_STATUS esp_ble_mesh_light_xyl_range_status_cb_t xyl_range_status For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_STATUS esp_ble_mesh_light_lc_mode_status_cb_t lc_mode_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_STATUS esp_ble_mesh_light_lc_mode_status_cb_t lc_mode_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_STATUS esp_ble_mesh_light_lc_om_status_cb_t lc_om_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_STATUS esp_ble_mesh_light_lc_om_status_cb_t lc_om_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_STATUS esp_ble_mesh_light_lc_light_onoff_status_cb_t lc_light_onoff_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_STATUS esp_ble_mesh_light_lc_light_onoff_status_cb_t lc_light_onoff_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_STATUS esp_ble_mesh_light_lc_property_status_cb_t lc_property_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_STATUS esp_ble_mesh_light_lc_property_status_cb_t lc_property_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_STATUS esp_ble_mesh_light_lightness_status_cb_t lightness_status union esp_ble_mesh_lighting_server_state_change_t #include <esp_ble_mesh_lighting_model_api.h> Lighting Server Model state change value union. Public Members esp_ble_mesh_state_change_light_lightness_set_t lightness_set The recv_op in ctx can be used to decide which state is changed. Light Lightness Set esp_ble_mesh_state_change_light_lightness_set_t lightness_set The recv_op in ctx can be used to decide which state is changed. Light Lightness Set esp_ble_mesh_state_change_light_lightness_linear_set_t lightness_linear_set Light Lightness Linear Set esp_ble_mesh_state_change_light_lightness_linear_set_t lightness_linear_set Light Lightness Linear Set esp_ble_mesh_state_change_light_lightness_default_set_t lightness_default_set Light Lightness Default Set esp_ble_mesh_state_change_light_lightness_default_set_t lightness_default_set Light Lightness Default Set esp_ble_mesh_state_change_light_lightness_range_set_t lightness_range_set Light Lightness Range Set esp_ble_mesh_state_change_light_lightness_range_set_t lightness_range_set Light Lightness Range Set esp_ble_mesh_state_change_light_ctl_set_t ctl_set Light CTL Set esp_ble_mesh_state_change_light_ctl_set_t ctl_set Light CTL Set esp_ble_mesh_state_change_light_ctl_temperature_set_t ctl_temp_set Light CTL Temperature Set esp_ble_mesh_state_change_light_ctl_temperature_set_t ctl_temp_set Light CTL Temperature Set esp_ble_mesh_state_change_light_ctl_temperature_range_set_t ctl_temp_range_set Light CTL Temperature Range Set esp_ble_mesh_state_change_light_ctl_temperature_range_set_t ctl_temp_range_set Light CTL Temperature Range Set esp_ble_mesh_state_change_light_ctl_default_set_t ctl_default_set Light CTL Default Set esp_ble_mesh_state_change_light_ctl_default_set_t ctl_default_set Light CTL Default Set esp_ble_mesh_state_change_light_hsl_set_t hsl_set Light HSL Set esp_ble_mesh_state_change_light_hsl_set_t hsl_set Light HSL Set esp_ble_mesh_state_change_light_hsl_hue_set_t hsl_hue_set Light HSL Hue Set esp_ble_mesh_state_change_light_hsl_hue_set_t hsl_hue_set Light HSL Hue Set esp_ble_mesh_state_change_light_hsl_saturation_set_t hsl_saturation_set Light HSL Saturation Set esp_ble_mesh_state_change_light_hsl_saturation_set_t hsl_saturation_set Light HSL Saturation Set esp_ble_mesh_state_change_light_hsl_default_set_t hsl_default_set Light HSL Default Set esp_ble_mesh_state_change_light_hsl_default_set_t hsl_default_set Light HSL Default Set esp_ble_mesh_state_change_light_hsl_range_set_t hsl_range_set Light HSL Range Set esp_ble_mesh_state_change_light_hsl_range_set_t hsl_range_set Light HSL Range Set esp_ble_mesh_state_change_light_xyl_set_t xyl_set Light xyL Set esp_ble_mesh_state_change_light_xyl_set_t xyl_set Light xyL Set esp_ble_mesh_state_change_light_xyl_default_set_t xyl_default_set Light xyL Default Set esp_ble_mesh_state_change_light_xyl_default_set_t xyl_default_set Light xyL Default Set esp_ble_mesh_state_change_light_xyl_range_set_t xyl_range_set Light xyL Range Set esp_ble_mesh_state_change_light_xyl_range_set_t xyl_range_set Light xyL Range Set esp_ble_mesh_state_change_light_lc_mode_set_t lc_mode_set Light LC Mode Set esp_ble_mesh_state_change_light_lc_mode_set_t lc_mode_set Light LC Mode Set esp_ble_mesh_state_change_light_lc_om_set_t lc_om_set Light LC Occupancy Mode Set esp_ble_mesh_state_change_light_lc_om_set_t lc_om_set Light LC Occupancy Mode Set esp_ble_mesh_state_change_light_lc_light_onoff_set_t lc_light_onoff_set Light LC Light OnOff Set esp_ble_mesh_state_change_light_lc_light_onoff_set_t lc_light_onoff_set Light LC Light OnOff Set esp_ble_mesh_state_change_light_lc_property_set_t lc_property_set Light LC Property Set esp_ble_mesh_state_change_light_lc_property_set_t lc_property_set Light LC Property Set esp_ble_mesh_state_change_sensor_status_t sensor_status Sensor Status esp_ble_mesh_state_change_sensor_status_t sensor_status Sensor Status esp_ble_mesh_state_change_light_lightness_set_t lightness_set union esp_ble_mesh_lighting_server_recv_get_msg_t #include <esp_ble_mesh_lighting_model_api.h> Lighting Server Model received get message union. Public Members esp_ble_mesh_server_recv_light_lc_property_get_t lc_property Light LC Property Get esp_ble_mesh_server_recv_light_lc_property_get_t lc_property Light LC Property Get esp_ble_mesh_server_recv_light_lc_property_get_t lc_property union esp_ble_mesh_lighting_server_recv_set_msg_t #include <esp_ble_mesh_lighting_model_api.h> Lighting Server Model received set message union. Public Members esp_ble_mesh_server_recv_light_lightness_set_t lightness Light Lightness Set/Light Lightness Set Unack esp_ble_mesh_server_recv_light_lightness_set_t lightness Light Lightness Set/Light Lightness Set Unack esp_ble_mesh_server_recv_light_lightness_linear_set_t lightness_linear Light Lightness Linear Set/Light Lightness Linear Set Unack esp_ble_mesh_server_recv_light_lightness_linear_set_t lightness_linear Light Lightness Linear Set/Light Lightness Linear Set Unack esp_ble_mesh_server_recv_light_lightness_default_set_t lightness_default Light Lightness Default Set/Light Lightness Default Set Unack esp_ble_mesh_server_recv_light_lightness_default_set_t lightness_default Light Lightness Default Set/Light Lightness Default Set Unack esp_ble_mesh_server_recv_light_lightness_range_set_t lightness_range Light Lightness Range Set/Light Lightness Range Set Unack esp_ble_mesh_server_recv_light_lightness_range_set_t lightness_range Light Lightness Range Set/Light Lightness Range Set Unack esp_ble_mesh_server_recv_light_ctl_set_t ctl Light CTL Set/Light CTL Set Unack esp_ble_mesh_server_recv_light_ctl_set_t ctl Light CTL Set/Light CTL Set Unack esp_ble_mesh_server_recv_light_ctl_temperature_set_t ctl_temp Light CTL Temperature Set/Light CTL Temperature Set Unack esp_ble_mesh_server_recv_light_ctl_temperature_set_t ctl_temp Light CTL Temperature Set/Light CTL Temperature Set Unack esp_ble_mesh_server_recv_light_ctl_temperature_range_set_t ctl_temp_range Light CTL Temperature Range Set/Light CTL Temperature Range Set Unack esp_ble_mesh_server_recv_light_ctl_temperature_range_set_t ctl_temp_range Light CTL Temperature Range Set/Light CTL Temperature Range Set Unack esp_ble_mesh_server_recv_light_ctl_default_set_t ctl_default Light CTL Default Set/Light CTL Default Set Unack esp_ble_mesh_server_recv_light_ctl_default_set_t ctl_default Light CTL Default Set/Light CTL Default Set Unack esp_ble_mesh_server_recv_light_hsl_set_t hsl Light HSL Set/Light HSL Set Unack esp_ble_mesh_server_recv_light_hsl_set_t hsl Light HSL Set/Light HSL Set Unack esp_ble_mesh_server_recv_light_hsl_hue_set_t hsl_hue Light HSL Hue Set/Light HSL Hue Set Unack esp_ble_mesh_server_recv_light_hsl_hue_set_t hsl_hue Light HSL Hue Set/Light HSL Hue Set Unack esp_ble_mesh_server_recv_light_hsl_saturation_set_t hsl_saturation Light HSL Saturation Set/Light HSL Saturation Set Unack esp_ble_mesh_server_recv_light_hsl_saturation_set_t hsl_saturation Light HSL Saturation Set/Light HSL Saturation Set Unack esp_ble_mesh_server_recv_light_hsl_default_set_t hsl_default Light HSL Default Set/Light HSL Default Set Unack esp_ble_mesh_server_recv_light_hsl_default_set_t hsl_default Light HSL Default Set/Light HSL Default Set Unack esp_ble_mesh_server_recv_light_hsl_range_set_t hsl_range Light HSL Range Set/Light HSL Range Set Unack esp_ble_mesh_server_recv_light_hsl_range_set_t hsl_range Light HSL Range Set/Light HSL Range Set Unack esp_ble_mesh_server_recv_light_xyl_set_t xyl Light xyL Set/Light xyL Set Unack esp_ble_mesh_server_recv_light_xyl_set_t xyl Light xyL Set/Light xyL Set Unack esp_ble_mesh_server_recv_light_xyl_default_set_t xyl_default Light xyL Default Set/Light xyL Default Set Unack esp_ble_mesh_server_recv_light_xyl_default_set_t xyl_default Light xyL Default Set/Light xyL Default Set Unack esp_ble_mesh_server_recv_light_xyl_range_set_t xyl_range Light xyL Range Set/Light xyL Range Set Unack esp_ble_mesh_server_recv_light_xyl_range_set_t xyl_range Light xyL Range Set/Light xyL Range Set Unack esp_ble_mesh_server_recv_light_lc_mode_set_t lc_mode Light LC Mode Set/Light LC Mode Set Unack esp_ble_mesh_server_recv_light_lc_mode_set_t lc_mode Light LC Mode Set/Light LC Mode Set Unack esp_ble_mesh_server_recv_light_lc_om_set_t lc_om Light LC OM Set/Light LC OM Set Unack esp_ble_mesh_server_recv_light_lc_om_set_t lc_om Light LC OM Set/Light LC OM Set Unack esp_ble_mesh_server_recv_light_lc_light_onoff_set_t lc_light_onoff Light LC Light OnOff Set/Light LC Light OnOff Set Unack esp_ble_mesh_server_recv_light_lc_light_onoff_set_t lc_light_onoff Light LC Light OnOff Set/Light LC Light OnOff Set Unack esp_ble_mesh_server_recv_light_lc_property_set_t lc_property Light LC Property Set/Light LC Property Set Unack esp_ble_mesh_server_recv_light_lc_property_set_t lc_property Light LC Property Set/Light LC Property Set Unack esp_ble_mesh_server_recv_light_lightness_set_t lightness union esp_ble_mesh_lighting_server_recv_status_msg_t #include <esp_ble_mesh_lighting_model_api.h> Lighting Server Model received status message union. Public Members esp_ble_mesh_server_recv_sensor_status_t sensor_status Sensor Status esp_ble_mesh_server_recv_sensor_status_t sensor_status Sensor Status esp_ble_mesh_server_recv_sensor_status_t sensor_status union esp_ble_mesh_lighting_server_cb_value_t #include <esp_ble_mesh_lighting_model_api.h> Lighting Server Model callback value union. Public Members esp_ble_mesh_lighting_server_state_change_t state_change ESP_BLE_MESH_LIGHTING_SERVER_STATE_CHANGE_EVT esp_ble_mesh_lighting_server_state_change_t state_change ESP_BLE_MESH_LIGHTING_SERVER_STATE_CHANGE_EVT esp_ble_mesh_lighting_server_recv_get_msg_t get ESP_BLE_MESH_LIGHTING_SERVER_RECV_GET_MSG_EVT esp_ble_mesh_lighting_server_recv_get_msg_t get ESP_BLE_MESH_LIGHTING_SERVER_RECV_GET_MSG_EVT esp_ble_mesh_lighting_server_recv_set_msg_t set ESP_BLE_MESH_LIGHTING_SERVER_RECV_SET_MSG_EVT esp_ble_mesh_lighting_server_recv_set_msg_t set ESP_BLE_MESH_LIGHTING_SERVER_RECV_SET_MSG_EVT esp_ble_mesh_lighting_server_recv_status_msg_t status ESP_BLE_MESH_LIGHTING_SERVER_RECV_STATUS_MSG_EVT esp_ble_mesh_lighting_server_recv_status_msg_t status ESP_BLE_MESH_LIGHTING_SERVER_RECV_STATUS_MSG_EVT esp_ble_mesh_lighting_server_state_change_t state_change Structures struct esp_ble_mesh_light_lightness_set_t Bluetooth Mesh Light Lightness Client Model Get and Set parameters structure. Parameters of Light Lightness Set struct esp_ble_mesh_light_lightness_linear_set_t Parameters of Light Lightness Linear Set struct esp_ble_mesh_light_lightness_default_set_t Parameter of Light Lightness Default Set Public Members uint16_t lightness The value of the Light Lightness Default state uint16_t lightness The value of the Light Lightness Default state uint16_t lightness struct esp_ble_mesh_light_lightness_range_set_t Parameters of Light Lightness Range Set struct esp_ble_mesh_light_ctl_set_t Parameters of Light CTL Set Public Members bool op_en Indicate if optional parameters are included bool op_en Indicate if optional parameters are included uint16_t ctl_lightness Target value of light ctl lightness state uint16_t ctl_lightness Target value of light ctl lightness state uint16_t ctl_temperature Target value of light ctl temperature state uint16_t ctl_temperature Target value of light ctl temperature state int16_t ctl_delta_uv Target value of light ctl delta UV state int16_t ctl_delta_uv Target value of light ctl delta UV state uint8_t tid Transaction ID uint8_t tid Transaction ID uint8_t trans_time Time to complete state transition (optional) uint8_t trans_time Time to complete state transition (optional) uint8_t delay Indicate message execution delay (C.1) uint8_t delay Indicate message execution delay (C.1) bool op_en struct esp_ble_mesh_light_ctl_temperature_set_t Parameters of Light CTL Temperature Set Public Members bool op_en Indicate if optional parameters are included bool op_en Indicate if optional parameters are included uint16_t ctl_temperature Target value of light ctl temperature state uint16_t ctl_temperature Target value of light ctl temperature state int16_t ctl_delta_uv Target value of light ctl delta UV state int16_t ctl_delta_uv Target value of light ctl delta UV state uint8_t tid Transaction ID uint8_t tid Transaction ID uint8_t trans_time Time to complete state transition (optional) uint8_t trans_time Time to complete state transition (optional) uint8_t delay Indicate message execution delay (C.1) uint8_t delay Indicate message execution delay (C.1) bool op_en struct esp_ble_mesh_light_ctl_temperature_range_set_t Parameters of Light CTL Temperature Range Set struct esp_ble_mesh_light_ctl_default_set_t Parameters of Light CTL Default Set struct esp_ble_mesh_light_hsl_set_t Parameters of Light HSL Set Public Members bool op_en Indicate if optional parameters are included bool op_en Indicate if optional parameters are included uint16_t hsl_lightness Target value of light hsl lightness state uint16_t hsl_lightness Target value of light hsl lightness state uint16_t hsl_hue Target value of light hsl hue state uint16_t hsl_hue Target value of light hsl hue state uint16_t hsl_saturation Target value of light hsl saturation state uint16_t hsl_saturation Target value of light hsl saturation state uint8_t tid Transaction ID uint8_t tid Transaction ID uint8_t trans_time Time to complete state transition (optional) uint8_t trans_time Time to complete state transition (optional) uint8_t delay Indicate message execution delay (C.1) uint8_t delay Indicate message execution delay (C.1) bool op_en struct esp_ble_mesh_light_hsl_hue_set_t Parameters of Light HSL Hue Set struct esp_ble_mesh_light_hsl_saturation_set_t Parameters of Light HSL Saturation Set struct esp_ble_mesh_light_hsl_default_set_t Parameters of Light HSL Default Set struct esp_ble_mesh_light_hsl_range_set_t Parameters of Light HSL Range Set Public Members uint16_t hue_range_min Value of hue range min field of light hsl hue range state uint16_t hue_range_min Value of hue range min field of light hsl hue range state uint16_t hue_range_max Value of hue range max field of light hsl hue range state uint16_t hue_range_max Value of hue range max field of light hsl hue range state uint16_t saturation_range_min Value of saturation range min field of light hsl saturation range state uint16_t saturation_range_min Value of saturation range min field of light hsl saturation range state uint16_t saturation_range_max Value of saturation range max field of light hsl saturation range state uint16_t saturation_range_max Value of saturation range max field of light hsl saturation range state uint16_t hue_range_min struct esp_ble_mesh_light_xyl_set_t Parameters of Light xyL Set Public Members bool op_en Indicate whether optional parameters included bool op_en Indicate whether optional parameters included uint16_t xyl_lightness The target value of the Light xyL Lightness state uint16_t xyl_lightness The target value of the Light xyL Lightness state uint16_t xyl_x The target value of the Light xyL x state uint16_t xyl_x The target value of the Light xyL x state uint16_t xyl_y The target value of the Light xyL y state uint16_t xyl_y The target value of the Light xyL y state uint8_t tid Transaction Identifier uint8_t tid Transaction Identifier uint8_t trans_time Time to complete state transition (optional) uint8_t trans_time Time to complete state transition (optional) uint8_t delay Indicate message execution delay (C.1) uint8_t delay Indicate message execution delay (C.1) bool op_en struct esp_ble_mesh_light_xyl_default_set_t Parameters of Light xyL Default Set struct esp_ble_mesh_light_xyl_range_set_t Parameters of Light xyL Range Set Public Members uint16_t xyl_x_range_min The value of the xyL x Range Min field of the Light xyL x Range state uint16_t xyl_x_range_min The value of the xyL x Range Min field of the Light xyL x Range state uint16_t xyl_x_range_max The value of the xyL x Range Max field of the Light xyL x Range state uint16_t xyl_x_range_max The value of the xyL x Range Max field of the Light xyL x Range state uint16_t xyl_y_range_min The value of the xyL y Range Min field of the Light xyL y Range state uint16_t xyl_y_range_min The value of the xyL y Range Min field of the Light xyL y Range state uint16_t xyl_y_range_max The value of the xyL y Range Max field of the Light xyL y Range state uint16_t xyl_y_range_max The value of the xyL y Range Max field of the Light xyL y Range state uint16_t xyl_x_range_min struct esp_ble_mesh_light_lc_mode_set_t Parameter of Light LC Mode Set Public Members uint8_t mode The target value of the Light LC Mode state uint8_t mode The target value of the Light LC Mode state uint8_t mode struct esp_ble_mesh_light_lc_om_set_t Parameter of Light LC OM Set Public Members uint8_t mode The target value of the Light LC Occupancy Mode state uint8_t mode The target value of the Light LC Occupancy Mode state uint8_t mode struct esp_ble_mesh_light_lc_light_onoff_set_t Parameters of Light LC Light OnOff Set struct esp_ble_mesh_light_lc_property_get_t Parameter of Light LC Property Get Public Members uint16_t property_id Property ID identifying a Light LC Property uint16_t property_id Property ID identifying a Light LC Property uint16_t property_id struct esp_ble_mesh_light_lc_property_set_t Parameters of Light LC Property Set struct esp_ble_mesh_light_lightness_status_cb_t Bluetooth Mesh Light Lightness Client Model Get and Set callback parameters structure. Parameters of Light Lightness Status struct esp_ble_mesh_light_lightness_linear_status_cb_t Parameters of Light Lightness Linear Status struct esp_ble_mesh_light_lightness_last_status_cb_t Parameter of Light Lightness Last Status Public Members uint16_t lightness The value of the Light Lightness Last state uint16_t lightness The value of the Light Lightness Last state uint16_t lightness struct esp_ble_mesh_light_lightness_default_status_cb_t Parameter of Light Lightness Default Status Public Members uint16_t lightness The value of the Light Lightness default State uint16_t lightness The value of the Light Lightness default State uint16_t lightness struct esp_ble_mesh_light_lightness_range_status_cb_t Parameters of Light Lightness Range Status struct esp_ble_mesh_light_ctl_status_cb_t Parameters of Light CTL Status Public Members bool op_en Indicate if optional parameters are included bool op_en Indicate if optional parameters are included uint16_t present_ctl_lightness Current value of light ctl lightness state uint16_t present_ctl_lightness Current value of light ctl lightness state uint16_t present_ctl_temperature Current value of light ctl temperature state uint16_t present_ctl_temperature Current value of light ctl temperature state uint16_t target_ctl_lightness Target value of light ctl lightness state (optional) uint16_t target_ctl_lightness Target value of light ctl lightness state (optional) uint16_t target_ctl_temperature Target value of light ctl temperature state (C.1) uint16_t target_ctl_temperature Target value of light ctl temperature state (C.1) uint8_t remain_time Time to complete state transition (C.1) uint8_t remain_time Time to complete state transition (C.1) bool op_en struct esp_ble_mesh_light_ctl_temperature_status_cb_t Parameters of Light CTL Temperature Status Public Members bool op_en Indicate if optional parameters are included bool op_en Indicate if optional parameters are included uint16_t present_ctl_temperature Current value of light ctl temperature state uint16_t present_ctl_temperature Current value of light ctl temperature state uint16_t present_ctl_delta_uv Current value of light ctl delta UV state uint16_t present_ctl_delta_uv Current value of light ctl delta UV state uint16_t target_ctl_temperature Target value of light ctl temperature state (optional) uint16_t target_ctl_temperature Target value of light ctl temperature state (optional) uint16_t target_ctl_delta_uv Target value of light ctl delta UV state (C.1) uint16_t target_ctl_delta_uv Target value of light ctl delta UV state (C.1) uint8_t remain_time Time to complete state transition (C.1) uint8_t remain_time Time to complete state transition (C.1) bool op_en struct esp_ble_mesh_light_ctl_temperature_range_status_cb_t Parameters of Light CTL Temperature Range Status struct esp_ble_mesh_light_ctl_default_status_cb_t Parameters of Light CTL Default Status struct esp_ble_mesh_light_hsl_status_cb_t Parameters of Light HSL Status Public Members bool op_en Indicate if optional parameters are included bool op_en Indicate if optional parameters are included uint16_t hsl_lightness Current value of light hsl lightness state uint16_t hsl_lightness Current value of light hsl lightness state uint16_t hsl_hue Current value of light hsl hue state uint16_t hsl_hue Current value of light hsl hue state uint16_t hsl_saturation Current value of light hsl saturation state uint16_t hsl_saturation Current value of light hsl saturation state uint8_t remain_time Time to complete state transition (optional) uint8_t remain_time Time to complete state transition (optional) bool op_en struct esp_ble_mesh_light_hsl_target_status_cb_t Parameters of Light HSL Target Status Public Members bool op_en Indicate if optional parameters are included bool op_en Indicate if optional parameters are included uint16_t hsl_lightness_target Target value of light hsl lightness state uint16_t hsl_lightness_target Target value of light hsl lightness state uint16_t hsl_hue_target Target value of light hsl hue state uint16_t hsl_hue_target Target value of light hsl hue state uint16_t hsl_saturation_target Target value of light hsl saturation state uint16_t hsl_saturation_target Target value of light hsl saturation state uint8_t remain_time Time to complete state transition (optional) uint8_t remain_time Time to complete state transition (optional) bool op_en struct esp_ble_mesh_light_hsl_hue_status_cb_t Parameters of Light HSL Hue Status struct esp_ble_mesh_light_hsl_saturation_status_cb_t Parameters of Light HSL Saturation Status struct esp_ble_mesh_light_hsl_default_status_cb_t Parameters of Light HSL Default Status struct esp_ble_mesh_light_hsl_range_status_cb_t Parameters of Light HSL Range Status Public Members uint8_t status_code Status code for the request message uint8_t status_code Status code for the request message uint16_t hue_range_min Value of hue range min field of light hsl hue range state uint16_t hue_range_min Value of hue range min field of light hsl hue range state uint16_t hue_range_max Value of hue range max field of light hsl hue range state uint16_t hue_range_max Value of hue range max field of light hsl hue range state uint16_t saturation_range_min Value of saturation range min field of light hsl saturation range state uint16_t saturation_range_min Value of saturation range min field of light hsl saturation range state uint16_t saturation_range_max Value of saturation range max field of light hsl saturation range state uint16_t saturation_range_max Value of saturation range max field of light hsl saturation range state uint8_t status_code struct esp_ble_mesh_light_xyl_status_cb_t Parameters of Light xyL Status Public Members bool op_en Indicate whether optional parameters included bool op_en Indicate whether optional parameters included uint16_t xyl_lightness The present value of the Light xyL Lightness state uint16_t xyl_lightness The present value of the Light xyL Lightness state uint16_t xyl_x The present value of the Light xyL x state uint16_t xyl_x The present value of the Light xyL x state uint16_t xyl_y The present value of the Light xyL y state uint16_t xyl_y The present value of the Light xyL y state uint8_t remain_time Time to complete state transition (optional) uint8_t remain_time Time to complete state transition (optional) bool op_en struct esp_ble_mesh_light_xyl_target_status_cb_t Parameters of Light xyL Target Status Public Members bool op_en Indicate whether optional parameters included bool op_en Indicate whether optional parameters included uint16_t target_xyl_lightness The target value of the Light xyL Lightness state uint16_t target_xyl_lightness The target value of the Light xyL Lightness state uint16_t target_xyl_x The target value of the Light xyL x state uint16_t target_xyl_x The target value of the Light xyL x state uint16_t target_xyl_y The target value of the Light xyL y state uint16_t target_xyl_y The target value of the Light xyL y state uint8_t remain_time Time to complete state transition (optional) uint8_t remain_time Time to complete state transition (optional) bool op_en struct esp_ble_mesh_light_xyl_default_status_cb_t Parameters of Light xyL Default Status struct esp_ble_mesh_light_xyl_range_status_cb_t Parameters of Light xyL Range Status Public Members uint8_t status_code Status Code for the requesting message uint8_t status_code Status Code for the requesting message uint16_t xyl_x_range_min The value of the xyL x Range Min field of the Light xyL x Range state uint16_t xyl_x_range_min The value of the xyL x Range Min field of the Light xyL x Range state uint16_t xyl_x_range_max The value of the xyL x Range Max field of the Light xyL x Range state uint16_t xyl_x_range_max The value of the xyL x Range Max field of the Light xyL x Range state uint16_t xyl_y_range_min The value of the xyL y Range Min field of the Light xyL y Range state uint16_t xyl_y_range_min The value of the xyL y Range Min field of the Light xyL y Range state uint16_t xyl_y_range_max The value of the xyL y Range Max field of the Light xyL y Range state uint16_t xyl_y_range_max The value of the xyL y Range Max field of the Light xyL y Range state uint8_t status_code struct esp_ble_mesh_light_lc_mode_status_cb_t Parameter of Light LC Mode Status Public Members uint8_t mode The present value of the Light LC Mode state uint8_t mode The present value of the Light LC Mode state uint8_t mode struct esp_ble_mesh_light_lc_om_status_cb_t Parameter of Light LC OM Status Public Members uint8_t mode The present value of the Light LC Occupancy Mode state uint8_t mode The present value of the Light LC Occupancy Mode state uint8_t mode struct esp_ble_mesh_light_lc_light_onoff_status_cb_t Parameters of Light LC Light OnOff Status Public Members bool op_en Indicate whether optional parameters included bool op_en Indicate whether optional parameters included uint8_t present_light_onoff The present value of the Light LC Light OnOff state uint8_t present_light_onoff The present value of the Light LC Light OnOff state uint8_t target_light_onoff The target value of the Light LC Light OnOff state (Optional) uint8_t target_light_onoff The target value of the Light LC Light OnOff state (Optional) uint8_t remain_time Time to complete state transition (C.1) uint8_t remain_time Time to complete state transition (C.1) bool op_en struct esp_ble_mesh_light_lc_property_status_cb_t Parameters of Light LC Property Status struct esp_ble_mesh_light_client_cb_param_t Lighting Client Model callback parameters Public Members int error_code Appropriate error code int error_code Appropriate error code esp_ble_mesh_client_common_param_t *params The client common parameters. esp_ble_mesh_client_common_param_t *params The client common parameters. esp_ble_mesh_light_client_status_cb_t status_cb The light status message callback values esp_ble_mesh_light_client_status_cb_t status_cb The light status message callback values int error_code struct esp_ble_mesh_light_lightness_state_t Parameters of Light Lightness state Public Members uint16_t lightness_linear The present value of Light Lightness Linear state uint16_t lightness_linear The present value of Light Lightness Linear state uint16_t target_lightness_linear The target value of Light Lightness Linear state uint16_t target_lightness_linear The target value of Light Lightness Linear state uint16_t lightness_actual The present value of Light Lightness Actual state uint16_t lightness_actual The present value of Light Lightness Actual state uint16_t target_lightness_actual The target value of Light Lightness Actual state uint16_t target_lightness_actual The target value of Light Lightness Actual state uint16_t lightness_last The value of Light Lightness Last state uint16_t lightness_last The value of Light Lightness Last state uint16_t lightness_default The value of Light Lightness Default state uint16_t lightness_default The value of Light Lightness Default state uint8_t status_code The status code of setting Light Lightness Range state uint8_t status_code The status code of setting Light Lightness Range state uint16_t lightness_range_min The minimum value of Light Lightness Range state uint16_t lightness_range_min The minimum value of Light Lightness Range state uint16_t lightness_range_max The maximum value of Light Lightness Range state uint16_t lightness_range_max The maximum value of Light Lightness Range state uint16_t lightness_linear struct esp_ble_mesh_light_lightness_srv_t User data of Light Lightness Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Lighting Lightness Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Lighting Lightness Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_light_lightness_state_t *state Parameters of the Light Lightness state esp_ble_mesh_light_lightness_state_t *state Parameters of the Light Lightness state esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_state_transition_t actual_transition Parameters of state transition esp_ble_mesh_state_transition_t actual_transition Parameters of state transition esp_ble_mesh_state_transition_t linear_transition Parameters of state transition esp_ble_mesh_state_transition_t linear_transition Parameters of state transition int32_t tt_delta_lightness_actual Delta change value of lightness actual state transition int32_t tt_delta_lightness_actual Delta change value of lightness actual state transition int32_t tt_delta_lightness_linear Delta change value of lightness linear state transition int32_t tt_delta_lightness_linear Delta change value of lightness linear state transition esp_ble_mesh_model_t *model struct esp_ble_mesh_light_lightness_setup_srv_t User data of Light Lightness Setup Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Lighting Lightness Setup Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Lighting Lightness Setup Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_light_lightness_state_t *state Parameters of the Light Lightness state esp_ble_mesh_light_lightness_state_t *state Parameters of the Light Lightness state esp_ble_mesh_model_t *model struct esp_ble_mesh_light_ctl_state_t Parameters of Light CTL state Public Members uint16_t lightness The present value of Light CTL Lightness state uint16_t lightness The present value of Light CTL Lightness state uint16_t target_lightness The target value of Light CTL Lightness state uint16_t target_lightness The target value of Light CTL Lightness state uint16_t temperature The present value of Light CTL Temperature state uint16_t temperature The present value of Light CTL Temperature state uint16_t target_temperature The target value of Light CTL Temperature state uint16_t target_temperature The target value of Light CTL Temperature state int16_t delta_uv The present value of Light CTL Delta UV state int16_t delta_uv The present value of Light CTL Delta UV state int16_t target_delta_uv The target value of Light CTL Delta UV state int16_t target_delta_uv The target value of Light CTL Delta UV state uint8_t status_code The statue code of setting Light CTL Temperature Range state uint8_t status_code The statue code of setting Light CTL Temperature Range state uint16_t temperature_range_min The minimum value of Light CTL Temperature Range state uint16_t temperature_range_min The minimum value of Light CTL Temperature Range state uint16_t temperature_range_max The maximum value of Light CTL Temperature Range state uint16_t temperature_range_max The maximum value of Light CTL Temperature Range state uint16_t lightness_default The value of Light Lightness Default state uint16_t lightness_default The value of Light Lightness Default state uint16_t temperature_default The value of Light CTL Temperature Default state uint16_t temperature_default The value of Light CTL Temperature Default state int16_t delta_uv_default The value of Light CTL Delta UV Default state int16_t delta_uv_default The value of Light CTL Delta UV Default state uint16_t lightness struct esp_ble_mesh_light_ctl_srv_t User data of Light CTL Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Lighting CTL Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Lighting CTL Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_light_ctl_state_t *state Parameters of the Light CTL state esp_ble_mesh_light_ctl_state_t *state Parameters of the Light CTL state esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_state_transition_t transition Parameters of state transition esp_ble_mesh_state_transition_t transition Parameters of state transition int32_t tt_delta_lightness Delta change value of lightness state transition int32_t tt_delta_lightness Delta change value of lightness state transition int32_t tt_delta_temperature Delta change value of temperature state transition int32_t tt_delta_temperature Delta change value of temperature state transition int32_t tt_delta_delta_uv Delta change value of delta uv state transition int32_t tt_delta_delta_uv Delta change value of delta uv state transition esp_ble_mesh_model_t *model struct esp_ble_mesh_light_ctl_setup_srv_t User data of Light CTL Setup Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Lighting CTL Setup Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Lighting CTL Setup Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_light_ctl_state_t *state Parameters of the Light CTL state esp_ble_mesh_light_ctl_state_t *state Parameters of the Light CTL state esp_ble_mesh_model_t *model struct esp_ble_mesh_light_ctl_temp_srv_t User data of Light CTL Temperature Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Lighting CTL Temperature Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Lighting CTL Temperature Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_light_ctl_state_t *state Parameters of the Light CTL state esp_ble_mesh_light_ctl_state_t *state Parameters of the Light CTL state esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_state_transition_t transition Parameters of state transition esp_ble_mesh_state_transition_t transition Parameters of state transition int32_t tt_delta_temperature Delta change value of temperature state transition int32_t tt_delta_temperature Delta change value of temperature state transition int32_t tt_delta_delta_uv Delta change value of delta uv state transition int32_t tt_delta_delta_uv Delta change value of delta uv state transition esp_ble_mesh_model_t *model struct esp_ble_mesh_light_hsl_state_t Parameters of Light HSL state Public Members uint16_t lightness The present value of Light HSL Lightness state uint16_t lightness The present value of Light HSL Lightness state uint16_t target_lightness The target value of Light HSL Lightness state uint16_t target_lightness The target value of Light HSL Lightness state uint16_t hue The present value of Light HSL Hue state uint16_t hue The present value of Light HSL Hue state uint16_t target_hue The target value of Light HSL Hue state uint16_t target_hue The target value of Light HSL Hue state uint16_t saturation The present value of Light HSL Saturation state uint16_t saturation The present value of Light HSL Saturation state uint16_t target_saturation The target value of Light HSL Saturation state uint16_t target_saturation The target value of Light HSL Saturation state uint16_t lightness_default The value of Light Lightness Default state uint16_t lightness_default The value of Light Lightness Default state uint16_t hue_default The value of Light HSL Hue Default state uint16_t hue_default The value of Light HSL Hue Default state uint16_t saturation_default The value of Light HSL Saturation Default state uint16_t saturation_default The value of Light HSL Saturation Default state uint8_t status_code The status code of setting Light HSL Hue & Saturation Range state uint8_t status_code The status code of setting Light HSL Hue & Saturation Range state uint16_t hue_range_min The minimum value of Light HSL Hue Range state uint16_t hue_range_min The minimum value of Light HSL Hue Range state uint16_t hue_range_max The maximum value of Light HSL Hue Range state uint16_t hue_range_max The maximum value of Light HSL Hue Range state uint16_t saturation_range_min The minimum value of Light HSL Saturation state uint16_t saturation_range_min The minimum value of Light HSL Saturation state uint16_t saturation_range_max The maximum value of Light HSL Saturation state uint16_t saturation_range_max The maximum value of Light HSL Saturation state uint16_t lightness struct esp_ble_mesh_light_hsl_srv_t User data of Light HSL Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Lighting HSL Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Lighting HSL Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_light_hsl_state_t *state Parameters of the Light HSL state esp_ble_mesh_light_hsl_state_t *state Parameters of the Light HSL state esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_state_transition_t transition Parameters of state transition esp_ble_mesh_state_transition_t transition Parameters of state transition int32_t tt_delta_lightness Delta change value of lightness state transition int32_t tt_delta_lightness Delta change value of lightness state transition int32_t tt_delta_hue Delta change value of hue state transition int32_t tt_delta_hue Delta change value of hue state transition int32_t tt_delta_saturation Delta change value of saturation state transition int32_t tt_delta_saturation Delta change value of saturation state transition esp_ble_mesh_model_t *model struct esp_ble_mesh_light_hsl_setup_srv_t User data of Light HSL Setup Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Lighting HSL Setup Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Lighting HSL Setup Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_light_hsl_state_t *state Parameters of the Light HSL state esp_ble_mesh_light_hsl_state_t *state Parameters of the Light HSL state esp_ble_mesh_model_t *model struct esp_ble_mesh_light_hsl_hue_srv_t User data of Light HSL Hue Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Lighting HSL Hue Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Lighting HSL Hue Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_light_hsl_state_t *state Parameters of the Light HSL state esp_ble_mesh_light_hsl_state_t *state Parameters of the Light HSL state esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_state_transition_t transition Parameters of state transition esp_ble_mesh_state_transition_t transition Parameters of state transition int32_t tt_delta_hue Delta change value of hue state transition int32_t tt_delta_hue Delta change value of hue state transition esp_ble_mesh_model_t *model struct esp_ble_mesh_light_hsl_sat_srv_t User data of Light HSL Saturation Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Lighting HSL Saturation Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Lighting HSL Saturation Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_light_hsl_state_t *state Parameters of the Light HSL state esp_ble_mesh_light_hsl_state_t *state Parameters of the Light HSL state esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_state_transition_t transition Parameters of state transition esp_ble_mesh_state_transition_t transition Parameters of state transition int32_t tt_delta_saturation Delta change value of saturation state transition int32_t tt_delta_saturation Delta change value of saturation state transition esp_ble_mesh_model_t *model struct esp_ble_mesh_light_xyl_state_t Parameters of Light xyL state Public Members uint16_t lightness The present value of Light xyL Lightness state uint16_t lightness The present value of Light xyL Lightness state uint16_t target_lightness The target value of Light xyL Lightness state uint16_t target_lightness The target value of Light xyL Lightness state uint16_t x The present value of Light xyL x state uint16_t x The present value of Light xyL x state uint16_t target_x The target value of Light xyL x state uint16_t target_x The target value of Light xyL x state uint16_t y The present value of Light xyL y state uint16_t y The present value of Light xyL y state uint16_t target_y The target value of Light xyL y state uint16_t target_y The target value of Light xyL y state uint16_t lightness_default The value of Light Lightness Default state uint16_t lightness_default The value of Light Lightness Default state uint16_t x_default The value of Light xyL x Default state uint16_t x_default The value of Light xyL x Default state uint16_t y_default The value of Light xyL y Default state uint16_t y_default The value of Light xyL y Default state uint8_t status_code The status code of setting Light xyL x & y Range state uint8_t status_code The status code of setting Light xyL x & y Range state uint16_t x_range_min The minimum value of Light xyL x Range state uint16_t x_range_min The minimum value of Light xyL x Range state uint16_t x_range_max The maximum value of Light xyL x Range state uint16_t x_range_max The maximum value of Light xyL x Range state uint16_t y_range_min The minimum value of Light xyL y Range state uint16_t y_range_min The minimum value of Light xyL y Range state uint16_t y_range_max The maximum value of Light xyL y Range state uint16_t y_range_max The maximum value of Light xyL y Range state uint16_t lightness struct esp_ble_mesh_light_xyl_srv_t User data of Light xyL Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Lighting xyL Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Lighting xyL Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_light_xyl_state_t *state Parameters of the Light xyL state esp_ble_mesh_light_xyl_state_t *state Parameters of the Light xyL state esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_state_transition_t transition Parameters of state transition esp_ble_mesh_state_transition_t transition Parameters of state transition int32_t tt_delta_lightness Delta change value of lightness state transition int32_t tt_delta_lightness Delta change value of lightness state transition int32_t tt_delta_x Delta change value of x state transition int32_t tt_delta_x Delta change value of x state transition int32_t tt_delta_y Delta change value of y state transition int32_t tt_delta_y Delta change value of y state transition esp_ble_mesh_model_t *model struct esp_ble_mesh_light_xyl_setup_srv_t User data of Light xyL Setup Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Lighting xyL Setup Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Lighting xyL Setup Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_light_xyl_state_t *state Parameters of the Light xyL state esp_ble_mesh_light_xyl_state_t *state Parameters of the Light xyL state esp_ble_mesh_model_t *model struct esp_ble_mesh_light_lc_state_t Parameters of Light LC states Public Members uint32_t mode 0b0 The controller is turned off. The binding with the Light Lightness state is disabled. 0b1 The controller is turned on. The binding with the Light Lightness state is enabled. The value of Light LC Mode state The binding with the Light Lightness state is disabled. 0b1 The controller is turned on. The binding with the Light Lightness state is enabled. The value of Light LC Mode state The binding with the Light Lightness state is disabled. 0b1 The controller is turned on. uint32_t mode 0b0 The controller is turned off. The binding with the Light Lightness state is disabled. 0b1 The controller is turned on. The binding with the Light Lightness state is enabled. The value of Light LC Mode state uint32_t occupancy_mode The value of Light LC Occupancy Mode state uint32_t occupancy_mode The value of Light LC Occupancy Mode state uint32_t light_onoff The present value of Light LC Light OnOff state uint32_t light_onoff The present value of Light LC Light OnOff state uint32_t target_light_onoff The target value of Light LC Light OnOff state uint32_t target_light_onoff The target value of Light LC Light OnOff state uint32_t occupancy The value of Light LC Occupancy state uint32_t occupancy The value of Light LC Occupancy state uint32_t ambient_luxlevel The value of Light LC Ambient LuxLevel state uint32_t ambient_luxlevel The value of Light LC Ambient LuxLevel state uint16_t linear_output Light LC Linear Output = max((Lightness Out)^2/65535, Regulator Output) If the Light LC Mode state is set to 0b1, the binding is enabled and upon a change of the Light LC Linear Output state, the following operation shall be performed: Light Lightness Linear = Light LC Linear Output If the Light LC Mode state is set to 0b0, the binding is disabled (i.e., upon a change of the Light LC Linear Output state, no operation on the Light Lightness Linear state is performed). The value of Light LC Linear Output state Light LC Linear Output = max((Lightness Out)^2/65535, Regulator Output) If the Light LC Mode state is set to 0b1, the binding is enabled and upon a change of the Light LC Linear Output state, the following operation shall be performed: Light Lightness Linear = Light LC Linear Output If the Light LC Mode state is set to 0b0, the binding is disabled (i.e., upon a change of the Light LC Linear Output state, no operation on the Light Lightness Linear state is performed). The value of Light LC Linear Output state Light LC Linear Output = max((Lightness Out)^2/65535, Regulator Output) uint16_t linear_output Light LC Linear Output = max((Lightness Out)^2/65535, Regulator Output) If the Light LC Mode state is set to 0b1, the binding is enabled and upon a change of the Light LC Linear Output state, the following operation shall be performed: Light Lightness Linear = Light LC Linear Output If the Light LC Mode state is set to 0b0, the binding is disabled (i.e., upon a change of the Light LC Linear Output state, no operation on the Light Lightness Linear state is performed). The value of Light LC Linear Output state uint32_t mode struct esp_ble_mesh_light_lc_property_state_t Parameters of Light Property states. The Light LC Property states are read / write states that determine the configuration of a Light Lightness Controller. Each state is represented by a device property and is controlled by Light LC Property messages. Public Members uint32_t time_occupancy_delay A timing state that determines the delay for changing the Light LC Occupancy state upon receiving a Sensor Status message from an occupancy sensor. The value of Light LC Time Occupancy Delay state uint32_t time_occupancy_delay A timing state that determines the delay for changing the Light LC Occupancy state upon receiving a Sensor Status message from an occupancy sensor. The value of Light LC Time Occupancy Delay state uint32_t time_fade_on A timing state that determines the time the controlled lights fade to the level determined by the Light LC Lightness On state. The value of Light LC Time Fade On state uint32_t time_fade_on A timing state that determines the time the controlled lights fade to the level determined by the Light LC Lightness On state. The value of Light LC Time Fade On state uint32_t time_run_on A timing state that determines the time the controlled lights stay at the level determined by the Light LC Lightness On state. The value of Light LC Time Run On state uint32_t time_run_on A timing state that determines the time the controlled lights stay at the level determined by the Light LC Lightness On state. The value of Light LC Time Run On state uint32_t time_fade A timing state that determines the time the controlled lights fade from the level determined by the Light LC Lightness On state to the level determined by the Light Lightness Prolong state. The value of Light LC Time Fade state uint32_t time_fade A timing state that determines the time the controlled lights fade from the level determined by the Light LC Lightness On state to the level determined by the Light Lightness Prolong state. The value of Light LC Time Fade state uint32_t time_prolong A timing state that determines the time the controlled lights stay at the level determined by the Light LC Lightness Prolong state. The value of Light LC Time Prolong state uint32_t time_prolong A timing state that determines the time the controlled lights stay at the level determined by the Light LC Lightness Prolong state. The value of Light LC Time Prolong state uint32_t time_fade_standby_auto A timing state that determines the time the controlled lights fade from the level determined by the Light LC Lightness Prolong state to the level determined by the Light LC Lightness Standby state when the transition is automatic. The value of Light LC Time Fade Standby Auto state uint32_t time_fade_standby_auto A timing state that determines the time the controlled lights fade from the level determined by the Light LC Lightness Prolong state to the level determined by the Light LC Lightness Standby state when the transition is automatic. The value of Light LC Time Fade Standby Auto state uint32_t time_fade_standby_manual A timing state that determines the time the controlled lights fade from the level determined by the Light LC Lightness Prolong state to the level determined by the Light LC Lightness Standby state when the transition is triggered by a change in the Light LC Light OnOff state. The value of Light LC Time Fade Standby Manual state uint32_t time_fade_standby_manual A timing state that determines the time the controlled lights fade from the level determined by the Light LC Lightness Prolong state to the level determined by the Light LC Lightness Standby state when the transition is triggered by a change in the Light LC Light OnOff state. The value of Light LC Time Fade Standby Manual state uint16_t lightness_on A lightness state that determines the perceptive light lightness at the Occupancy and Run internal controller states. The value of Light LC Lightness On state uint16_t lightness_on A lightness state that determines the perceptive light lightness at the Occupancy and Run internal controller states. The value of Light LC Lightness On state uint16_t lightness_prolong A lightness state that determines the light lightness at the Prolong internal controller state. The value of Light LC Lightness Prolong state uint16_t lightness_prolong A lightness state that determines the light lightness at the Prolong internal controller state. The value of Light LC Lightness Prolong state uint16_t lightness_standby A lightness state that determines the light lightness at the Standby internal controller state. The value of Light LC Lightness Standby state uint16_t lightness_standby A lightness state that determines the light lightness at the Standby internal controller state. The value of Light LC Lightness Standby state uint16_t ambient_luxlevel_on A uint16 state representing the Ambient LuxLevel level that determines if the controller transitions from the Light Control Standby state. The value of Light LC Ambient LuxLevel On state uint16_t ambient_luxlevel_on A uint16 state representing the Ambient LuxLevel level that determines if the controller transitions from the Light Control Standby state. The value of Light LC Ambient LuxLevel On state uint16_t ambient_luxlevel_prolong A uint16 state representing the required Ambient LuxLevel level in the Prolong state. The value of Light LC Ambient LuxLevel Prolong state uint16_t ambient_luxlevel_prolong A uint16 state representing the required Ambient LuxLevel level in the Prolong state. The value of Light LC Ambient LuxLevel Prolong state uint16_t ambient_luxlevel_standby A uint16 state representing the required Ambient LuxLevel level in the Standby state. The value of Light LC Ambient LuxLevel Standby state uint16_t ambient_luxlevel_standby A uint16 state representing the required Ambient LuxLevel level in the Standby state. The value of Light LC Ambient LuxLevel Standby state float regulator_kiu A float32 state representing the integral coefficient that determines the integral part of the equation defining the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is less than LuxLevel Out. Valid range: 0.0 ~ 1000.0. The default value is 250.0. The value of Light LC Regulator Kiu state float regulator_kiu A float32 state representing the integral coefficient that determines the integral part of the equation defining the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is less than LuxLevel Out. Valid range: 0.0 ~ 1000.0. The default value is 250.0. The value of Light LC Regulator Kiu state float regulator_kid A float32 state representing the integral coefficient that determines the integral part of the equation defining the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is greater than or equal to the value of the LuxLevel Out state. Valid range: 0.0 ~ 1000.0. The default value is 25.0. The value of Light LC Regulator Kid state float regulator_kid A float32 state representing the integral coefficient that determines the integral part of the equation defining the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is greater than or equal to the value of the LuxLevel Out state. Valid range: 0.0 ~ 1000.0. The default value is 25.0. The value of Light LC Regulator Kid state float regulator_kpu A float32 state representing the proportional coefficient that determines the proportional part of the equation defining the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is less than the value of the LuxLevel Out state. Valid range: 0.0 ~ 1000.0. The default value is 80.0. The value of Light LC Regulator Kpu state float regulator_kpu A float32 state representing the proportional coefficient that determines the proportional part of the equation defining the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is less than the value of the LuxLevel Out state. Valid range: 0.0 ~ 1000.0. The default value is 80.0. The value of Light LC Regulator Kpu state float regulator_kpd A float32 state representing the proportional coefficient that determines the proportional part of the equation defining the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is greater than or equal to the value of the LuxLevel Out state. Valid range: 0.0 ~ 1000.0. The default value is 80.0. The value of Light LC Regulator Kpd state float regulator_kpd A float32 state representing the proportional coefficient that determines the proportional part of the equation defining the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is greater than or equal to the value of the LuxLevel Out state. Valid range: 0.0 ~ 1000.0. The default value is 80.0. The value of Light LC Regulator Kpd state int8_t regulator_accuracy A int8 state representing the percentage accuracy of the Light LC PI Feedback Regulator. Valid range: 0.0 ~ 100.0. The default value is 2.0. The value of Light LC Regulator Accuracy state int8_t regulator_accuracy A int8 state representing the percentage accuracy of the Light LC PI Feedback Regulator. Valid range: 0.0 ~ 100.0. The default value is 2.0. The value of Light LC Regulator Accuracy state uint32_t set_occupancy_to_1_delay If the message Raw field contains a Raw Value for the Time Since Motion Sensed device property, which represents a value less than or equal to the value of the Light LC Occupancy Delay state, it shall delay setting the Light LC Occupancy state to 0b1 by the difference between the value of the Light LC Occupancy Delay state and the received Time Since Motion value. The value of the difference between value of the Light LC Occupancy Delay state and the received Time Since Motion value uint32_t set_occupancy_to_1_delay If the message Raw field contains a Raw Value for the Time Since Motion Sensed device property, which represents a value less than or equal to the value of the Light LC Occupancy Delay state, it shall delay setting the Light LC Occupancy state to 0b1 by the difference between the value of the Light LC Occupancy Delay state and the received Time Since Motion value. The value of the difference between value of the Light LC Occupancy Delay state and the received Time Since Motion value uint32_t time_occupancy_delay struct esp_ble_mesh_light_lc_state_machine_t Parameters of Light LC state machine Public Members uint8_t fade_on The value of transition time of Light LC Time Fade On uint8_t fade_on The value of transition time of Light LC Time Fade On uint8_t fade The value of transition time of Light LC Time Fade uint8_t fade The value of transition time of Light LC Time Fade uint8_t fade_standby_auto The value of transition time of Light LC Time Fade Standby Auto uint8_t fade_standby_auto The value of transition time of Light LC Time Fade Standby Auto uint8_t fade_standby_manual The value of transition time of Light LC Time Fade Standby Manual uint8_t fade_standby_manual The value of transition time of Light LC Time Fade Standby Manual struct esp_ble_mesh_light_lc_state_machine_t::[anonymous] trans_time The Fade On, Fade, Fade Standby Auto, and Fade Standby Manual states are transition states that define the transition of the Lightness Out and LuxLevel Out states. This transition can be started as a result of the Light LC State Machine change or as a result of receiving the Light LC Light OnOff Set or Light LC Light Set Unacknowledged message. The value of transition time struct esp_ble_mesh_light_lc_state_machine_t::[anonymous] trans_time The Fade On, Fade, Fade Standby Auto, and Fade Standby Manual states are transition states that define the transition of the Lightness Out and LuxLevel Out states. This transition can be started as a result of the Light LC State Machine change or as a result of receiving the Light LC Light OnOff Set or Light LC Light Set Unacknowledged message. The value of transition time esp_ble_mesh_lc_state_t state The value of Light LC state machine state esp_ble_mesh_lc_state_t state The value of Light LC state machine state struct k_delayed_work timer Timer of Light LC state machine struct k_delayed_work timer Timer of Light LC state machine uint8_t fade_on struct esp_ble_mesh_light_control_t Parameters of Light Lightness controller Public Members esp_ble_mesh_light_lc_state_t state Parameters of Light LC state esp_ble_mesh_light_lc_state_t state Parameters of Light LC state esp_ble_mesh_light_lc_property_state_t prop_state Parameters of Light LC Property state esp_ble_mesh_light_lc_property_state_t prop_state Parameters of Light LC Property state esp_ble_mesh_light_lc_state_machine_t state_machine Parameters of Light LC state machine esp_ble_mesh_light_lc_state_machine_t state_machine Parameters of Light LC state machine esp_ble_mesh_light_lc_state_t state struct esp_ble_mesh_light_lc_srv_t User data of Light LC Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Lighting LC Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Lighting LC Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_light_control_t *lc Parameters of the Light controller esp_ble_mesh_light_control_t *lc Parameters of the Light controller esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_last_msg_info_t last Parameters of the last received set message esp_ble_mesh_state_transition_t transition Parameters of state transition esp_ble_mesh_state_transition_t transition Parameters of state transition esp_ble_mesh_model_t *model struct esp_ble_mesh_light_lc_setup_srv_t User data of Light LC Setup Server Model Public Members esp_ble_mesh_model_t *model Pointer to the Lighting LC Setup Server Model. Initialized internally. esp_ble_mesh_model_t *model Pointer to the Lighting LC Setup Server Model. Initialized internally. esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages esp_ble_mesh_light_control_t *lc Parameters of the Light controller esp_ble_mesh_light_control_t *lc Parameters of the Light controller esp_ble_mesh_model_t *model struct esp_ble_mesh_state_change_light_lightness_set_t Parameter of Light Lightness Actual state change event Public Members uint16_t lightness The value of Light Lightness Actual state uint16_t lightness The value of Light Lightness Actual state uint16_t lightness struct esp_ble_mesh_state_change_light_lightness_linear_set_t Parameter of Light Lightness Linear state change event Public Members uint16_t lightness The value of Light Lightness Linear state uint16_t lightness The value of Light Lightness Linear state uint16_t lightness struct esp_ble_mesh_state_change_light_lightness_default_set_t Parameter of Light Lightness Default state change event Public Members uint16_t lightness The value of Light Lightness Default state uint16_t lightness The value of Light Lightness Default state uint16_t lightness struct esp_ble_mesh_state_change_light_lightness_range_set_t Parameters of Light Lightness Range state change event struct esp_ble_mesh_state_change_light_ctl_set_t Parameters of Light CTL state change event struct esp_ble_mesh_state_change_light_ctl_temperature_set_t Parameters of Light CTL Temperature state change event struct esp_ble_mesh_state_change_light_ctl_temperature_range_set_t Parameters of Light CTL Temperature Range state change event struct esp_ble_mesh_state_change_light_ctl_default_set_t Parameters of Light CTL Default state change event struct esp_ble_mesh_state_change_light_hsl_set_t Parameters of Light HSL state change event struct esp_ble_mesh_state_change_light_hsl_hue_set_t Parameter of Light HSL Hue state change event Public Members uint16_t hue The value of Light HSL Hue state uint16_t hue The value of Light HSL Hue state uint16_t hue struct esp_ble_mesh_state_change_light_hsl_saturation_set_t Parameter of Light HSL Saturation state change event Public Members uint16_t saturation The value of Light HSL Saturation state uint16_t saturation The value of Light HSL Saturation state uint16_t saturation struct esp_ble_mesh_state_change_light_hsl_default_set_t Parameters of Light HSL Default state change event struct esp_ble_mesh_state_change_light_hsl_range_set_t Parameters of Light HSL Range state change event Public Members uint16_t hue_range_min The minimum hue value of Light HSL Range state uint16_t hue_range_min The minimum hue value of Light HSL Range state uint16_t hue_range_max The maximum hue value of Light HSL Range state uint16_t hue_range_max The maximum hue value of Light HSL Range state uint16_t saturation_range_min The minimum saturation value of Light HSL Range state uint16_t saturation_range_min The minimum saturation value of Light HSL Range state uint16_t saturation_range_max The maximum saturation value of Light HSL Range state uint16_t saturation_range_max The maximum saturation value of Light HSL Range state uint16_t hue_range_min struct esp_ble_mesh_state_change_light_xyl_set_t Parameters of Light xyL state change event struct esp_ble_mesh_state_change_light_xyl_default_set_t Parameters of Light xyL Default state change event struct esp_ble_mesh_state_change_light_xyl_range_set_t Parameters of Light xyL Range state change event struct esp_ble_mesh_state_change_light_lc_mode_set_t Parameter of Light LC Mode state change event Public Members uint8_t mode The value of Light LC Mode state uint8_t mode The value of Light LC Mode state uint8_t mode struct esp_ble_mesh_state_change_light_lc_om_set_t Parameter of Light LC Occupancy Mode state change event Public Members uint8_t mode The value of Light LC Occupancy Mode state uint8_t mode The value of Light LC Occupancy Mode state uint8_t mode struct esp_ble_mesh_state_change_light_lc_light_onoff_set_t Parameter of Light LC Light OnOff state change event Public Members uint8_t onoff The value of Light LC Light OnOff state uint8_t onoff The value of Light LC Light OnOff state uint8_t onoff struct esp_ble_mesh_state_change_light_lc_property_set_t Parameters of Light LC Property state change event struct esp_ble_mesh_state_change_sensor_status_t Parameters of Sensor Status state change event Public Members uint16_t property_id The value of Sensor Property ID uint16_t property_id The value of Sensor Property ID uint8_t occupancy The value of Light LC Occupancy state uint8_t occupancy The value of Light LC Occupancy state uint32_t set_occupancy_to_1_delay The value of Light LC Set Occupancy to 1 Delay state uint32_t set_occupancy_to_1_delay The value of Light LC Set Occupancy to 1 Delay state uint32_t ambient_luxlevel The value of Light LC Ambient Luxlevel state uint32_t ambient_luxlevel The value of Light LC Ambient Luxlevel state union esp_ble_mesh_state_change_sensor_status_t::[anonymous] state Parameters of Sensor Status related state union esp_ble_mesh_state_change_sensor_status_t::[anonymous] state Parameters of Sensor Status related state uint16_t property_id struct esp_ble_mesh_server_recv_light_lc_property_get_t Context of the received Light LC Property Get message Public Members uint16_t property_id Property ID identifying a Light LC Property uint16_t property_id Property ID identifying a Light LC Property uint16_t property_id struct esp_ble_mesh_server_recv_light_lightness_set_t Context of the received Light Lightness Set message struct esp_ble_mesh_server_recv_light_lightness_linear_set_t Context of the received Light Lightness Linear Set message struct esp_ble_mesh_server_recv_light_lightness_default_set_t Context of the received Light Lightness Default Set message Public Members uint16_t lightness The value of the Light Lightness Default state uint16_t lightness The value of the Light Lightness Default state uint16_t lightness struct esp_ble_mesh_server_recv_light_lightness_range_set_t Context of the received Light Lightness Range Set message struct esp_ble_mesh_server_recv_light_ctl_set_t Context of the received Light CTL Set message Public Members bool op_en Indicate if optional parameters are included bool op_en Indicate if optional parameters are included uint16_t lightness Target value of light ctl lightness state uint16_t lightness Target value of light ctl lightness state uint16_t temperature Target value of light ctl temperature state uint16_t temperature Target value of light ctl temperature state int16_t delta_uv Target value of light ctl delta UV state int16_t delta_uv Target value of light ctl delta UV state uint8_t tid Transaction ID uint8_t tid Transaction ID uint8_t trans_time Time to complete state transition (optional) uint8_t trans_time Time to complete state transition (optional) uint8_t delay Indicate message execution delay (C.1) uint8_t delay Indicate message execution delay (C.1) bool op_en struct esp_ble_mesh_server_recv_light_ctl_temperature_set_t Context of the received Light CTL Temperature Set message Public Members bool op_en Indicate if optional parameters are included bool op_en Indicate if optional parameters are included uint16_t temperature Target value of light ctl temperature state uint16_t temperature Target value of light ctl temperature state int16_t delta_uv Target value of light ctl delta UV state int16_t delta_uv Target value of light ctl delta UV state uint8_t tid Transaction ID uint8_t tid Transaction ID uint8_t trans_time Time to complete state transition (optional) uint8_t trans_time Time to complete state transition (optional) uint8_t delay Indicate message execution delay (C.1) uint8_t delay Indicate message execution delay (C.1) bool op_en struct esp_ble_mesh_server_recv_light_ctl_temperature_range_set_t Context of the received Light CTL Temperature Range Set message struct esp_ble_mesh_server_recv_light_ctl_default_set_t Context of the received Light CTL Default Set message struct esp_ble_mesh_server_recv_light_hsl_set_t Context of the received Light HSL Set message Public Members bool op_en Indicate if optional parameters are included bool op_en Indicate if optional parameters are included uint16_t lightness Target value of light hsl lightness state uint16_t lightness Target value of light hsl lightness state uint16_t hue Target value of light hsl hue state uint16_t hue Target value of light hsl hue state uint16_t saturation Target value of light hsl saturation state uint16_t saturation Target value of light hsl saturation state uint8_t tid Transaction ID uint8_t tid Transaction ID uint8_t trans_time Time to complete state transition (optional) uint8_t trans_time Time to complete state transition (optional) uint8_t delay Indicate message execution delay (C.1) uint8_t delay Indicate message execution delay (C.1) bool op_en struct esp_ble_mesh_server_recv_light_hsl_hue_set_t Context of the received Light HSL Hue Set message struct esp_ble_mesh_server_recv_light_hsl_saturation_set_t Context of the received Light HSL Saturation Set message struct esp_ble_mesh_server_recv_light_hsl_default_set_t Context of the received Light HSL Default Set message struct esp_ble_mesh_server_recv_light_hsl_range_set_t Context of the received Light HSL Range Set message Public Members uint16_t hue_range_min Value of hue range min field of light hsl hue range state uint16_t hue_range_min Value of hue range min field of light hsl hue range state uint16_t hue_range_max Value of hue range max field of light hsl hue range state uint16_t hue_range_max Value of hue range max field of light hsl hue range state uint16_t saturation_range_min Value of saturation range min field of light hsl saturation range state uint16_t saturation_range_min Value of saturation range min field of light hsl saturation range state uint16_t saturation_range_max Value of saturation range max field of light hsl saturation range state uint16_t saturation_range_max Value of saturation range max field of light hsl saturation range state uint16_t hue_range_min struct esp_ble_mesh_server_recv_light_xyl_set_t Context of the received Light xyL Set message Public Members bool op_en Indicate whether optional parameters included bool op_en Indicate whether optional parameters included uint16_t lightness The target value of the Light xyL Lightness state uint16_t lightness The target value of the Light xyL Lightness state uint16_t x The target value of the Light xyL x state uint16_t x The target value of the Light xyL x state uint16_t y The target value of the Light xyL y state uint16_t y The target value of the Light xyL y state uint8_t tid Transaction Identifier uint8_t tid Transaction Identifier uint8_t trans_time Time to complete state transition (optional) uint8_t trans_time Time to complete state transition (optional) uint8_t delay Indicate message execution delay (C.1) uint8_t delay Indicate message execution delay (C.1) bool op_en struct esp_ble_mesh_server_recv_light_xyl_default_set_t Context of the received Light xyL Default Set message struct esp_ble_mesh_server_recv_light_xyl_range_set_t Context of the received Light xyl Range Set message Public Members uint16_t x_range_min The value of the xyL x Range Min field of the Light xyL x Range state uint16_t x_range_min The value of the xyL x Range Min field of the Light xyL x Range state uint16_t x_range_max The value of the xyL x Range Max field of the Light xyL x Range state uint16_t x_range_max The value of the xyL x Range Max field of the Light xyL x Range state uint16_t y_range_min The value of the xyL y Range Min field of the Light xyL y Range state uint16_t y_range_min The value of the xyL y Range Min field of the Light xyL y Range state uint16_t y_range_max The value of the xyL y Range Max field of the Light xyL y Range state uint16_t y_range_max The value of the xyL y Range Max field of the Light xyL y Range state uint16_t x_range_min struct esp_ble_mesh_server_recv_light_lc_mode_set_t Context of the received Light LC Mode Set message Public Members uint8_t mode The target value of the Light LC Mode state uint8_t mode The target value of the Light LC Mode state uint8_t mode struct esp_ble_mesh_server_recv_light_lc_om_set_t Context of the received Light OM Set message Public Members uint8_t mode The target value of the Light LC Occupancy Mode state uint8_t mode The target value of the Light LC Occupancy Mode state uint8_t mode struct esp_ble_mesh_server_recv_light_lc_light_onoff_set_t Context of the received Light LC Light OnOff Set message struct esp_ble_mesh_server_recv_light_lc_property_set_t Context of the received Light LC Property Set message struct esp_ble_mesh_server_recv_sensor_status_t Context of the received Sensor Status message Public Members struct net_buf_simple *data Value of sensor data state (optional) struct net_buf_simple *data Value of sensor data state (optional) struct net_buf_simple *data struct esp_ble_mesh_lighting_server_cb_param_t Lighting Server Model callback parameters Public Members esp_ble_mesh_model_t *model Pointer to Lighting Server Models esp_ble_mesh_model_t *model Pointer to Lighting Server Models esp_ble_mesh_msg_ctx_t ctx Context of the received messages esp_ble_mesh_msg_ctx_t ctx Context of the received messages esp_ble_mesh_lighting_server_cb_value_t value Value of the received Lighting Messages esp_ble_mesh_lighting_server_cb_value_t value Value of the received Lighting Messages esp_ble_mesh_model_t *model Macros ESP_BLE_MESH_MODEL_LIGHT_LIGHTNESS_CLI(cli_pub, cli_data) Define a new Light Lightness Client Model. Note This API needs to be called for each element on which the application needs to have a Light Lightness Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light Lightness Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Light Lightness Client Model instance. ESP_BLE_MESH_MODEL_LIGHT_CTL_CLI(cli_pub, cli_data) Define a new Light CTL Client Model. Note This API needs to be called for each element on which the application needs to have a Light CTL Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light CTL Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Light CTL Client Model instance. ESP_BLE_MESH_MODEL_LIGHT_HSL_CLI(cli_pub, cli_data) Define a new Light HSL Client Model. Note This API needs to be called for each element on which the application needs to have a Light HSL Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light HSL Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Light HSL Client Model instance. ESP_BLE_MESH_MODEL_LIGHT_XYL_CLI(cli_pub, cli_data) Define a new Light xyL Client Model. Note This API needs to be called for each element on which the application needs to have a Light xyL Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light xyL Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Light xyL Client Model instance. ESP_BLE_MESH_MODEL_LIGHT_LC_CLI(cli_pub, cli_data) Define a new Light LC Client Model. Note This API needs to be called for each element on which the application needs to have a Light LC Client Model. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light LC Client Model instance. Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. Returns New Light LC Client Model instance. ESP_BLE_MESH_MODEL_LIGHT_LIGHTNESS_SRV(srv_pub, srv_data) Lighting Server Models related context. Define a new Light Lightness Server Model. Note 1. The Light Lightness Server model extends the Generic Power OnOff Server model and the Generic Level Server model. When this model is present on an Element, the corresponding Light Lightness Setup Server model shall also be present. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lightness_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lightness_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light Lightness Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lightness_srv_t. Returns New Light Lightness Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_LIGHT_LIGHTNESS_SETUP_SRV(srv_pub, srv_data) Define a new Light Lightness Setup Server Model. Note 1. The Light Lightness Setup Server model extends the Light Lightness Server model and the Generic Power OnOff Setup Server model. This model shall support model subscription. This model shall support model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lightness_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lightness_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light Lightness Setup Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lightness_setup_srv_t. Returns New Light Lightness Setup Server Model instance. This model shall support model subscription. ESP_BLE_MESH_MODEL_LIGHT_CTL_SRV(srv_pub, srv_data) Define a new Light CTL Server Model. Note 1. The Light CTL Server model extends the Light Lightness Server model. When this model is present on an Element, the corresponding Light CTL Temperature Server model and the corresponding Light CTL Setup Server model shall also be present. This model shall support model publication and model subscription. The model requires two elements: the main element and the Temperature element. The Temperature element contains the corresponding Light CTL Temperature Server model and an instance of a Generic Level state bound to the Light CTL Temperature state on the Temperature element. The Light CTL Temperature state on the Temperature element is bound to the Light CTL state on the main element. This model shall support model publication and model subscription. The model requires two elements: the main element and the Temperature element. The Temperature element contains the corresponding Light CTL Temperature Server model and an instance of a Generic Level state bound to the Light CTL Temperature state on the Temperature element. The Light CTL Temperature state on the Temperature element is bound to the Light CTL state on the main element. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_ctl_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_ctl_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light CTL Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_ctl_srv_t. Returns New Light CTL Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_LIGHT_CTL_SETUP_SRV(srv_pub, srv_data) Define a new Light CTL Setup Server Model. Note 1. The Light CTL Setup Server model extends the Light CTL Server and the Light Lightness Setup Server. This model shall support model subscription. This model shall support model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_ctl_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_ctl_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light CTL Setup Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_ctl_setup_srv_t. Returns New Light CTL Setup Server Model instance. This model shall support model subscription. ESP_BLE_MESH_MODEL_LIGHT_CTL_TEMP_SRV(srv_pub, srv_data) Define a new Light CTL Temperature Server Model. Note 1. The Light CTL Temperature Server model extends the Generic Level Server model. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_ctl_temp_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_ctl_temp_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light CTL Temperature Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_ctl_temp_srv_t. Returns New Light CTL Temperature Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_LIGHT_HSL_SRV(srv_pub, srv_data) Define a new Light HSL Server Model. Note 1. The Light HSL Server model extends the Light Lightness Server model. When this model is present on an Element, the corresponding Light HSL Hue Server model and the corresponding Light HSL Saturation Server model and the corresponding Light HSL Setup Server model shall also be present. This model shall support model publication and model subscription. The model requires three elements: the main element and the Hue element and the Saturation element. The Hue element contains the corresponding Light HSL Hue Server model and an instance of a Generic Level state bound to the Light HSL Hue state on the Hue element. The Saturation element contains the corresponding Light HSL Saturation Server model and an instance of a Generic Level state bound to the Light HSL Saturation state on the Saturation element. The Light HSL Hue state on the Hue element is bound to the Light HSL state on the main element and the Light HSL Saturation state on the Saturation element is bound to the Light HSL state on the main element. This model shall support model publication and model subscription. The model requires three elements: the main element and the Hue element and the Saturation element. The Hue element contains the corresponding Light HSL Hue Server model and an instance of a Generic Level state bound to the Light HSL Hue state on the Hue element. The Saturation element contains the corresponding Light HSL Saturation Server model and an instance of a Generic Level state bound to the Light HSL Saturation state on the Saturation element. The Light HSL Hue state on the Hue element is bound to the Light HSL state on the main element and the Light HSL Saturation state on the Saturation element is bound to the Light HSL state on the main element. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light HSL Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_srv_t. Returns New Light HSL Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_LIGHT_HSL_SETUP_SRV(srv_pub, srv_data) Define a new Light HSL Setup Server Model. Note 1. The Light HSL Setup Server model extends the Light HSL Server and the Light Lightness Setup Server. This model shall support model subscription. This model shall support model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light HSL Setup Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_setup_srv_t. Returns New Light HSL Setup Server Model instance. This model shall support model subscription. ESP_BLE_MESH_MODEL_LIGHT_HSL_HUE_SRV(srv_pub, srv_data) Define a new Light HSL Hue Server Model. Note 1. The Light HSL Hue Server model extends the Generic Level Server model. This model is associated with the Light HSL Server model. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_hue_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_hue_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light HSL Hue Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_hue_srv_t. Returns New Light HSL Hue Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_LIGHT_HSL_SAT_SRV(srv_pub, srv_data) Define a new Light HSL Saturation Server Model. Note 1. The Light HSL Saturation Server model extends the Generic Level Server model. This model is associated with the Light HSL Server model. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_sat_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_sat_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light HSL Saturation Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_sat_srv_t. Returns New Light HSL Saturation Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_LIGHT_XYL_SRV(srv_pub, srv_data) Define a new Light xyL Server Model. Note 1. The Light xyL Server model extends the Light Lightness Server model. When this model is present on an Element, the corresponding Light xyL Setup Server model shall also be present. This model shall support model publication and model subscription. This model shall support model publication and model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_xyl_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_xyl_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light xyL Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_xyl_srv_t. Returns New Light xyL Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_LIGHT_XYL_SETUP_SRV(srv_pub, srv_data) Define a new Light xyL Setup Server Model. Note 1. The Light xyL Setup Server model extends the Light xyL Server and the Light Lightness Setup Server. This model shall support model subscription. This model shall support model subscription. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_xyl_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_xyl_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light xyL Setup Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_xyl_setup_srv_t. Returns New Light xyL Setup Server Model instance. This model shall support model subscription. ESP_BLE_MESH_MODEL_LIGHT_LC_SRV(srv_pub, srv_data) Define a new Light LC Server Model. Note 1. The Light LC (Lightness Control) Server model extends the Light Lightness Server model and the Generic OnOff Server model. When this model is present on an Element, the corresponding Light LC Setup Server model shall also be present. This model shall support model publication and model subscription. This model may be used to represent an element that is a client to a Sensor Server model and controls the Light Lightness Actual state via defined state bindings. This model shall support model publication and model subscription. This model may be used to represent an element that is a client to a Sensor Server model and controls the Light Lightness Actual state via defined state bindings. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lc_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lc_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light LC Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lc_srv_t. Returns New Light LC Server Model instance. This model shall support model publication and model subscription. ESP_BLE_MESH_MODEL_LIGHT_LC_SETUP_SRV(srv_pub, srv_data) Define a new Light LC Setup Server Model. Note 1. The Light LC (Lightness Control) Setup model extends the Light LC Server model. This model shall support model publication and model subscription. This model may be used to configure setup parameters for the Light LC Server model. This model shall support model publication and model subscription. This model may be used to configure setup parameters for the Light LC Server model. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lc_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lc_setup_srv_t. srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. Returns New Light LC Setup Server Model instance. Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lc_setup_srv_t. Returns New Light LC Setup Server Model instance. This model shall support model publication and model subscription. Type Definitions typedef void (*esp_ble_mesh_light_client_cb_t)(esp_ble_mesh_light_client_cb_event_t event, esp_ble_mesh_light_client_cb_param_t *param) Bluetooth Mesh Light Client Model function. Lighting Client Model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter typedef void (*esp_ble_mesh_lighting_server_cb_t)(esp_ble_mesh_lighting_server_cb_event_t event, esp_ble_mesh_lighting_server_cb_param_t *param) Bluetooth Mesh Lighting Server Model function. Lighting Server Model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter Enumerations enum esp_ble_mesh_light_client_cb_event_t This enum value is the event of Lighting Client Model Values: enumerator ESP_BLE_MESH_LIGHT_CLIENT_GET_STATE_EVT enumerator ESP_BLE_MESH_LIGHT_CLIENT_GET_STATE_EVT enumerator ESP_BLE_MESH_LIGHT_CLIENT_SET_STATE_EVT enumerator ESP_BLE_MESH_LIGHT_CLIENT_SET_STATE_EVT enumerator ESP_BLE_MESH_LIGHT_CLIENT_PUBLISH_EVT enumerator ESP_BLE_MESH_LIGHT_CLIENT_PUBLISH_EVT enumerator ESP_BLE_MESH_LIGHT_CLIENT_TIMEOUT_EVT enumerator ESP_BLE_MESH_LIGHT_CLIENT_TIMEOUT_EVT enumerator ESP_BLE_MESH_LIGHT_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_LIGHT_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_LIGHT_CLIENT_GET_STATE_EVT enum esp_ble_mesh_lc_state_t This enum value is the Light LC State Machine states Values: enumerator ESP_BLE_MESH_LC_OFF enumerator ESP_BLE_MESH_LC_OFF enumerator ESP_BLE_MESH_LC_STANDBY enumerator ESP_BLE_MESH_LC_STANDBY enumerator ESP_BLE_MESH_LC_FADE_ON enumerator ESP_BLE_MESH_LC_FADE_ON enumerator ESP_BLE_MESH_LC_RUN enumerator ESP_BLE_MESH_LC_RUN enumerator ESP_BLE_MESH_LC_FADE enumerator ESP_BLE_MESH_LC_FADE enumerator ESP_BLE_MESH_LC_PROLONG enumerator ESP_BLE_MESH_LC_PROLONG enumerator ESP_BLE_MESH_LC_FADE_STANDBY_AUTO enumerator ESP_BLE_MESH_LC_FADE_STANDBY_AUTO enumerator ESP_BLE_MESH_LC_FADE_STANDBY_MANUAL enumerator ESP_BLE_MESH_LC_FADE_STANDBY_MANUAL enumerator ESP_BLE_MESH_LC_OFF enum esp_ble_mesh_lighting_server_cb_event_t This enum value is the event of Lighting Server Model Values: enumerator ESP_BLE_MESH_LIGHTING_SERVER_STATE_CHANGE_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Lighting Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Lighting Set/Set Unack messages are received. When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Lighting Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Lighting Set/Set Unack messages are received. When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Lighting Get messages are received. enumerator ESP_BLE_MESH_LIGHTING_SERVER_STATE_CHANGE_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Lighting Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Lighting Set/Set Unack messages are received. enumerator ESP_BLE_MESH_LIGHTING_SERVER_RECV_GET_MSG_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Lighting Get messages are received. enumerator ESP_BLE_MESH_LIGHTING_SERVER_RECV_GET_MSG_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Lighting Get messages are received. enumerator ESP_BLE_MESH_LIGHTING_SERVER_RECV_SET_MSG_EVT When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Lighting Set/Set Unack messages are received. enumerator ESP_BLE_MESH_LIGHTING_SERVER_RECV_SET_MSG_EVT When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Lighting Set/Set Unack messages are received. enumerator ESP_BLE_MESH_LIGHTING_SERVER_RECV_STATUS_MSG_EVT When status_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Sensor Status message is received. enumerator ESP_BLE_MESH_LIGHTING_SERVER_RECV_STATUS_MSG_EVT When status_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Sensor Status message is received. enumerator ESP_BLE_MESH_LIGHTING_SERVER_EVT_MAX enumerator ESP_BLE_MESH_LIGHTING_SERVER_EVT_MAX enumerator ESP_BLE_MESH_LIGHTING_SERVER_STATE_CHANGE_EVT ESP-BLE-MESH (v1.1) Core API Reference Note This section is a preview version, so the related structures, macros, and APIs may be changed. This section contains ESP-BLE-MESH v1.1 Core related APIs, event types, event parameters, etc. This API reference covers 10 components: Remote Provisioning Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_rpr_model_api.h This header file can be included with: #include "esp_ble_mesh_rpr_model_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_rpr_client_callback(esp_ble_mesh_rpr_client_cb_t callback) Register BLE Mesh Remote Provisioning Client model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_rpr_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_rpr_client_msg_t *msg) Get the value of Remote Provisioning Server model state with the corresponding get message. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Remote Provisioning Client message. params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Remote Provisioning Client message. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Remote Provisioning Client message. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_rpr_client_action(esp_ble_mesh_rpr_client_act_type_t type, esp_ble_mesh_rpr_client_act_param_t *param) Remote Provisioning Client model perform related actions, e.g. start remote provisioning. Parameters type -- [in] Type of the action to be performed. param -- [in] Parameters of the action to be performed. type -- [in] Type of the action to be performed. param -- [in] Parameters of the action to be performed. type -- [in] Type of the action to be performed. Returns ESP_OK on success or error code otherwise. Parameters type -- [in] Type of the action to be performed. param -- [in] Parameters of the action to be performed. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_register_rpr_server_callback(esp_ble_mesh_rpr_server_cb_t callback) Register BLE Mesh Remote Provisioning Server model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Unions union esp_ble_mesh_rpr_client_msg_t #include <esp_ble_mesh_rpr_model_api.h> Remote Provisioning Client model message union. Public Members esp_ble_mesh_rpr_scan_start_t scan_start For ESP_BLE_MESH_MODEL_OP_RPR_SCAN_START esp_ble_mesh_rpr_scan_start_t scan_start For ESP_BLE_MESH_MODEL_OP_RPR_SCAN_START esp_ble_mesh_rpr_ext_scan_start_t ext_scan_start For ESP_BLE_MESH_MODEL_OP_RPR_EXT_SCAN_START esp_ble_mesh_rpr_ext_scan_start_t ext_scan_start For ESP_BLE_MESH_MODEL_OP_RPR_EXT_SCAN_START esp_ble_mesh_rpr_link_open_t link_open For ESP_BLE_MESH_MODEL_OP_RPR_LINK_OPEN esp_ble_mesh_rpr_link_open_t link_open For ESP_BLE_MESH_MODEL_OP_RPR_LINK_OPEN esp_ble_mesh_rpr_link_close_t link_close For ESP_BLE_MESH_MODEL_OP_RPR_LINK_CLOSE esp_ble_mesh_rpr_link_close_t link_close For ESP_BLE_MESH_MODEL_OP_RPR_LINK_CLOSE esp_ble_mesh_rpr_scan_start_t scan_start union esp_ble_mesh_rpr_client_act_param_t #include <esp_ble_mesh_rpr_model_api.h> Remote Provisioning Client model action union. Public Members esp_ble_mesh_rpr_client_start_rpr_t start_rpr Start remote provisioning esp_ble_mesh_rpr_client_start_rpr_t start_rpr Start remote provisioning esp_ble_mesh_rpr_client_start_rpr_t start_rpr union esp_ble_mesh_rpr_client_recv_cb_t #include <esp_ble_mesh_rpr_model_api.h> Remote Provisioning Client model received message union. Public Members esp_ble_mesh_rpr_scan_caps_status_t scan_caps_status For ESP_BLE_MESH_MODEL_OP_RPR_SCAN_CAPS_STATUS esp_ble_mesh_rpr_scan_caps_status_t scan_caps_status For ESP_BLE_MESH_MODEL_OP_RPR_SCAN_CAPS_STATUS esp_ble_mesh_rpr_scan_status_t scan_status For ESP_BLE_MESH_MODEL_OP_RPR_SCAN_STATUS esp_ble_mesh_rpr_scan_status_t scan_status For ESP_BLE_MESH_MODEL_OP_RPR_SCAN_STATUS esp_ble_mesh_rpr_scan_report_t scan_report For ESP_BLE_MESH_MODEL_OP_RPR_SCAN_REPORT esp_ble_mesh_rpr_scan_report_t scan_report For ESP_BLE_MESH_MODEL_OP_RPR_SCAN_REPORT esp_ble_mesh_rpr_ext_scan_report_t ext_scan_report For ESP_BLE_MESH_MODEL_OP_RPR_EXT_SCAN_REPORT esp_ble_mesh_rpr_ext_scan_report_t ext_scan_report For ESP_BLE_MESH_MODEL_OP_RPR_EXT_SCAN_REPORT esp_ble_mesh_rpr_link_status_t link_status For ESP_BLE_MESH_MODEL_OP_RPR_LINK_STATUS esp_ble_mesh_rpr_link_status_t link_status For ESP_BLE_MESH_MODEL_OP_RPR_LINK_STATUS esp_ble_mesh_rpr_link_report_t link_report For ESP_BLE_MESH_MODEL_OP_RPR_LINK_REPORT esp_ble_mesh_rpr_link_report_t link_report For ESP_BLE_MESH_MODEL_OP_RPR_LINK_REPORT esp_ble_mesh_rpr_scan_caps_status_t scan_caps_status union esp_ble_mesh_rpr_client_cb_param_t #include <esp_ble_mesh_rpr_model_api.h> Remote Provisioning Client model callback parameters Public Members int err_code Result of sending a message Result of starting remote provisioning int err_code Result of sending a message Result of starting remote provisioning esp_ble_mesh_client_common_param_t *params Client common parameters esp_ble_mesh_client_common_param_t *params Client common parameters struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] send Event parameters of sending messages Event parameters of sending messages struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] send Event parameters of sending messages Event parameters of sending messages esp_ble_mesh_rpr_client_recv_cb_t val Parameters of received status message esp_ble_mesh_rpr_client_recv_cb_t val Parameters of received status message struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] recv Event parameters of receiving messages Event parameters of receiving messages struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] recv Event parameters of receiving messages Event parameters of receiving messages esp_ble_mesh_rpr_client_act_evt_t sub_evt Event type of the performed action esp_ble_mesh_rpr_client_act_evt_t sub_evt Event type of the performed action esp_ble_mesh_model_t *model Pointer of Remote Provisioning Client esp_ble_mesh_model_t *model Pointer of Remote Provisioning Client uint16_t rpr_srv_addr Unicast address of Remote Provisioning Server uint16_t rpr_srv_addr Unicast address of Remote Provisioning Server struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous]::[anonymous] start_rpr_comp ESP_BLE_MESH_START_RPR_COMP_SUB_EVT. Event parameter of ESP_BLE_MESH_START_RPR_COMP_SUB_EVT struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous]::[anonymous] start_rpr_comp ESP_BLE_MESH_START_RPR_COMP_SUB_EVT. Event parameter of ESP_BLE_MESH_START_RPR_COMP_SUB_EVT struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] act Event parameters of performed actions Event parameters of performed actions struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] act Event parameters of performed actions Event parameters of performed actions struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] link_open ESP_BLE_MESH_RPR_CLIENT_LINK_OPEN_EVT. Event parameters of ESP_BLE_MESH_RPR_CLIENT_LINK_OPEN_EVT struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] link_open ESP_BLE_MESH_RPR_CLIENT_LINK_OPEN_EVT. Event parameters of ESP_BLE_MESH_RPR_CLIENT_LINK_OPEN_EVT uint8_t reason Reason of closing provisioning link uint8_t reason Reason of closing provisioning link struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] link_close ESP_BLE_MESH_RPR_CLIENT_LINK_CLOSE_EVT. Event parameters of ESP_BLE_MESH_RPR_CLIENT_LINK_CLOSE_EVT struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] link_close ESP_BLE_MESH_RPR_CLIENT_LINK_CLOSE_EVT. Event parameters of ESP_BLE_MESH_RPR_CLIENT_LINK_CLOSE_EVT uint8_t nppi NPPI Procedure uint8_t nppi NPPI Procedure uint16_t index Index of the provisioned node uint16_t index Index of the provisioned node uint8_t uuid[16] Device UUID uint8_t uuid[16] Device UUID uint16_t unicast_addr Primary element address uint16_t unicast_addr Primary element address uint8_t element_num Element number uint8_t element_num Element number uint16_t net_idx NetKey Index uint16_t net_idx NetKey Index struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] prov ESP_BLE_MESH_RPR_CLIENT_PROV_COMP_EVT. Event parameters of ESP_BLE_MESH_RPR_CLIENT_PROV_COMP_EVT struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] prov ESP_BLE_MESH_RPR_CLIENT_PROV_COMP_EVT. Event parameters of ESP_BLE_MESH_RPR_CLIENT_PROV_COMP_EVT int err_code union esp_ble_mesh_rpr_server_cb_param_t #include <esp_ble_mesh_rpr_model_api.h> Remote Provisioning Server model related context. Remote Provisioning Server model callback value union Public Members esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_model_t *model Pointer to the server model structure uint8_t scan_items_limit Maximum number of scanned items to be reported uint8_t scan_items_limit Maximum number of scanned items to be reported uint8_t timeout Time limit for a scan (in seconds) Time limit for extended scan (in seconds) Time limit for opening a link (in seconds) uint8_t timeout Time limit for a scan (in seconds) Time limit for extended scan (in seconds) Time limit for opening a link (in seconds) uint8_t uuid[16] Device UUID (All ZERO if not present) Device UUID (ZERO if not present) uint8_t uuid[16] Device UUID (All ZERO if not present) Device UUID (ZERO if not present) uint16_t net_idx NetKey Index used by Remote Provisioning Client uint16_t net_idx NetKey Index used by Remote Provisioning Client uint16_t rpr_cli_addr Unicast address of Remote Provisioning Client uint16_t rpr_cli_addr Unicast address of Remote Provisioning Client struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] scan_start ESP_BLE_MESH_RPR_SERVER_SCAN_START_EVT. struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] scan_start ESP_BLE_MESH_RPR_SERVER_SCAN_START_EVT. struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] scan_stop ESP_BLE_MESH_RPR_SERVER_SCAN_STOP_EVT. struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] scan_stop ESP_BLE_MESH_RPR_SERVER_SCAN_STOP_EVT. uint8_t ad_type_filter_count Number of AD Types in the ADTypeFilter field uint8_t ad_type_filter_count Number of AD Types in the ADTypeFilter field uint8_t *ad_type_filter List of AD Types to be reported uint8_t *ad_type_filter List of AD Types to be reported uint8_t index Index of the extended scan instance uint8_t index Index of the extended scan instance struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] ext_scan_start ESP_BLE_MESH_RPR_SERVER_EXT_SCAN_START_EVT. struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] ext_scan_start ESP_BLE_MESH_RPR_SERVER_EXT_SCAN_START_EVT. struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] ext_scan_stop ESP_BLE_MESH_RPR_SERVER_EXT_SCAN_STOP_EVT. struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] ext_scan_stop ESP_BLE_MESH_RPR_SERVER_EXT_SCAN_STOP_EVT. uint8_t status Status of Link Open procedure uint8_t status Status of Link Open procedure uint8_t nppi Node Provisioning Protocol Interface Provisioning bearer link close reason code uint8_t nppi Node Provisioning Protocol Interface Provisioning bearer link close reason code struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] link_open ESP_BLE_MESH_RPR_SERVER_LINK_OPEN_EVT. struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] link_open ESP_BLE_MESH_RPR_SERVER_LINK_OPEN_EVT. bool close_by_device Indicate if the link is closed by the Unprovisioned Device bool close_by_device Indicate if the link is closed by the Unprovisioned Device uint8_t reason Provisioning bearer link close reason code uint8_t reason Provisioning bearer link close reason code struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] link_close ESP_BLE_MESH_RPR_SERVER_LINK_CLOSE_EVT. struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] link_close ESP_BLE_MESH_RPR_SERVER_LINK_CLOSE_EVT. struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] prov_comp ESP_BLE_MESH_RPR_SERVER_PROV_COMP_EVT. TODO: Duplicate with Link Close event? struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] prov_comp ESP_BLE_MESH_RPR_SERVER_PROV_COMP_EVT. TODO: Duplicate with Link Close event? esp_ble_mesh_model_t *model Structures struct esp_ble_mesh_rpr_scan_start_t Remote Provisioning Server model context Parameters of Remote Provisioning Scan Start struct esp_ble_mesh_rpr_ext_scan_start_t Parameters of Remote Provisioning Extended Scan Start Public Members uint8_t ad_type_filter_count Number of AD Types in the ADTypeFilter field uint8_t ad_type_filter_count Number of AD Types in the ADTypeFilter field uint8_t ad_type_filter[16] List of AD Types to be reported. Minimum is 1, maximum is 16 uint8_t ad_type_filter[16] List of AD Types to be reported. Minimum is 1, maximum is 16 bool uuid_en Indicate if Device UUID is present bool uuid_en Indicate if Device UUID is present uint8_t uuid[16] Device UUID (Optional) uint8_t uuid[16] Device UUID (Optional) uint8_t timeout Time limit for a scan (in seconds) (C.1) uint8_t timeout Time limit for a scan (in seconds) (C.1) uint8_t ad_type_filter_count struct esp_ble_mesh_rpr_link_open_t Parameters of Remote Provisioning Link Open struct esp_ble_mesh_rpr_link_close_t Parameters of Remote Provisioning Link Close Public Members uint8_t reason Provisioning bearer link close reason code uint8_t reason Provisioning bearer link close reason code uint8_t reason struct esp_ble_mesh_rpr_client_start_rpr_t Parameters of starting remote provisioning Public Members esp_ble_mesh_model_t *model Pointer of Remote Provisioning Client esp_ble_mesh_model_t *model Pointer of Remote Provisioning Client uint16_t rpr_srv_addr Unicast address of Remote Provisioning Server uint16_t rpr_srv_addr Unicast address of Remote Provisioning Server esp_ble_mesh_model_t *model struct esp_ble_mesh_rpr_scan_caps_status_t Parameters of Remote Provisioning Scan Capabilities Status struct esp_ble_mesh_rpr_scan_status_t Parameters of Remote Provisioning Scan Status struct esp_ble_mesh_rpr_scan_report_t Parameters of Remote Provisioning Scan Report struct esp_ble_mesh_rpr_ext_scan_report_t Parameters of Remote Provisioning Extended Scan Report struct esp_ble_mesh_rpr_link_status_t Parameters of Remote Provisioning Link Status struct esp_ble_mesh_rpr_link_report_t Parameters of Remote Provisioning Link Report Macros ESP_BLE_MESH_MODEL_OP_RPR_SCAN_CAPS_GET ESP_BLE_MESH_MODEL_OP_RPR_SCAN_CAPS_STATUS ESP_BLE_MESH_MODEL_OP_RPR_SCAN_GET ESP_BLE_MESH_MODEL_OP_RPR_SCAN_START ESP_BLE_MESH_MODEL_OP_RPR_SCAN_STOP ESP_BLE_MESH_MODEL_OP_RPR_SCAN_STATUS ESP_BLE_MESH_MODEL_OP_RPR_SCAN_REPORT ESP_BLE_MESH_MODEL_OP_RPR_EXT_SCAN_START ESP_BLE_MESH_MODEL_OP_RPR_EXT_SCAN_REPORT ESP_BLE_MESH_MODEL_OP_RPR_LINK_GET ESP_BLE_MESH_MODEL_OP_RPR_LINK_OPEN ESP_BLE_MESH_MODEL_OP_RPR_LINK_CLOSE ESP_BLE_MESH_MODEL_OP_RPR_LINK_STATUS ESP_BLE_MESH_MODEL_OP_RPR_LINK_REPORT ESP_BLE_MESH_MODEL_OP_RPR_PDU_SEND ESP_BLE_MESH_MODEL_OP_RPR_PDU_OUTBOUND_REPORT ESP_BLE_MESH_MODEL_OP_RPR_PDU_REPORT ESP_BLE_MESH_RPR_SRV_MAX_SCANNED_ITEMS_MIN ESP_BLE_MESH_RPR_NOT_SUPPORT_ACTIVE_SCAN ESP_BLE_MESH_RPR_SUPPORT_ACTIVE_SCAN ESP_BLE_MESH_RPR_SCAN_IDLE ESP_BLE_MESH_RPR_SCAN_MULTIPLE_DEVICE ESP_BLE_MESH_RPR_SCAN_SINGLE_DEVICE ESP_BLE_MESH_RPR_SCAN_NOT_IN_PROGRESS ESP_BLE_MESH_RPR_PROHIBIT_SCAN_TIMEOUT ESP_BLE_MESH_RPR_EXT_SCAN_TIMEOUT_MIN ESP_BLE_MESH_RPR_EXT_SCAN_TIMEOUT_MAX ESP_BLE_MESH_RPR_AD_TYPE_FILTER_CNT_MIN ESP_BLE_MESH_RPR_AD_TYPE_FILTER_CNT_MAX ESP_BLE_MESH_RPR_LINK_OPEN_TIMEOUT_MIN ESP_BLE_MESH_RPR_LINK_OPEN_TIMEOUT_MAX ESP_BLE_MESH_RPR_LINK_TIMEOUT_DEFAULT ESP_BLE_MESH_RPR_REASON_SUCCESS ESP_BLE_MESH_RPR_REASON_FAIL ESP_BLE_MESH_RPR_LINK_IDLE ESP_BLE_MESH_RPR_LINK_OPENING ESP_BLE_MESH_RPR_LINK_ACTIVE ESP_BLE_MESH_RPR_OUTBOUND_PACKET_TRANSFER ESP_BLE_MESH_RPR_LINK_CLOSING ESP_BLE_MESH_RPR_STATUS_SUCCESS ESP_BLE_MESH_RPR_STATUS_SCANNING_CANNOT_START ESP_BLE_MESH_RPR_STATUS_INVALID_STATE ESP_BLE_MESH_RPR_STATUS_LIMITED_RESOURCES ESP_BLE_MESH_RPR_STATUS_LINK_CANNOT_OPEN ESP_BLE_MESH_RPR_STATUS_LINK_OPEN_FAILED ESP_BLE_MESH_RPR_STATUS_LINK_CLOSED_BY_DEVICE ESP_BLE_MESH_RPR_STATUS_LINK_CLOSED_BY_SERVER ESP_BLE_MESH_RPR_STATUS_LINK_CLOSED_BY_CLIENT ESP_BLE_MESH_RPR_STATUS_LINK_CLOSED_AS_CANNOT_RECEIVE_PDU ESP_BLE_MESH_RPR_STATUS_LINK_CLOSED_AS_CANNOT_SEND_PDU ESP_BLE_MESH_RPR_STATUS_LINK_CLOSED_AS_CANNOT_DELIVER_PDU_REPORT ESP_BLE_MESH_MODEL_RPR_SRV(srv_data) Define a new Remote Provisioning Server model. Note If supported, the model shall be supported by a primary element and may be supported by any secondary element. Parameters srv_data -- Pointer to a unique Remote Provisioning Server model user_data. srv_data -- Pointer to a unique Remote Provisioning Server model user_data. srv_data -- Pointer to a unique Remote Provisioning Server model user_data. Returns New Remote Provisioning Server model instance. Parameters srv_data -- Pointer to a unique Remote Provisioning Server model user_data. Returns New Remote Provisioning Server model instance. ESP_BLE_MESH_MODEL_RPR_CLI(cli_data) Define a new Remote Provisioning Client model. Note If supported, the model shall be supported by a primary element and may be supported by any secondary element. Parameters cli_data -- Pointer to a unique Remote Provisioning Client model user_data. cli_data -- Pointer to a unique Remote Provisioning Client model user_data. cli_data -- Pointer to a unique Remote Provisioning Client model user_data. Returns New Remote Provisioning Client model instance. Parameters cli_data -- Pointer to a unique Remote Provisioning Client model user_data. Returns New Remote Provisioning Client model instance. Type Definitions typedef void (*esp_ble_mesh_rpr_client_cb_t)(esp_ble_mesh_rpr_client_cb_event_t event, esp_ble_mesh_rpr_client_cb_param_t *param) Remote Provisioning client and server model functions. Remote Provisioning Client model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter typedef void (*esp_ble_mesh_rpr_server_cb_t)(esp_ble_mesh_rpr_server_cb_event_t event, esp_ble_mesh_rpr_server_cb_param_t *param) Remote Provisioning Server model callback function type. Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter Enumerations enum esp_ble_mesh_rpr_client_act_type_t This enum value is the action of Remote Provisioning Client model Values: enumerator ESP_BLE_MESH_RPR_CLIENT_ACT_START_RPR enumerator ESP_BLE_MESH_RPR_CLIENT_ACT_START_RPR enumerator ESP_BLE_MESH_RPR_CLIENT_ACT_MAX enumerator ESP_BLE_MESH_RPR_CLIENT_ACT_MAX enumerator ESP_BLE_MESH_RPR_CLIENT_ACT_START_RPR enum esp_ble_mesh_rpr_client_act_evt_t This enum value is the event type of the performed action Values: enumerator ESP_BLE_MESH_START_RPR_COMP_SUB_EVT enumerator ESP_BLE_MESH_START_RPR_COMP_SUB_EVT enumerator ESP_BLE_MESH_START_RPR_COMP_SUB_EVT enum esp_ble_mesh_rpr_client_cb_event_t This enum value is the event of Remote Provisioning Client model Values: enumerator ESP_BLE_MESH_RPR_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_ACT_COMP_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_ACT_COMP_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_LINK_OPEN_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_LINK_OPEN_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_LINK_CLOSE_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_LINK_CLOSE_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_PROV_COMP_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_PROV_COMP_EVT enumerator ESP_BLE_MESH_RPR_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_RPR_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_RPR_CLIENT_SEND_COMP_EVT enum esp_ble_mesh_rpr_server_cb_event_t This enum value is the event of Remote Provisioning Server model Values: enumerator ESP_BLE_MESH_RPR_SERVER_SCAN_START_EVT enumerator ESP_BLE_MESH_RPR_SERVER_SCAN_START_EVT enumerator ESP_BLE_MESH_RPR_SERVER_SCAN_STOP_EVT enumerator ESP_BLE_MESH_RPR_SERVER_SCAN_STOP_EVT enumerator ESP_BLE_MESH_RPR_SERVER_EXT_SCAN_START_EVT enumerator ESP_BLE_MESH_RPR_SERVER_EXT_SCAN_START_EVT enumerator ESP_BLE_MESH_RPR_SERVER_EXT_SCAN_STOP_EVT enumerator ESP_BLE_MESH_RPR_SERVER_EXT_SCAN_STOP_EVT enumerator ESP_BLE_MESH_RPR_SERVER_LINK_OPEN_EVT enumerator ESP_BLE_MESH_RPR_SERVER_LINK_OPEN_EVT enumerator ESP_BLE_MESH_RPR_SERVER_LINK_CLOSE_EVT enumerator ESP_BLE_MESH_RPR_SERVER_LINK_CLOSE_EVT enumerator ESP_BLE_MESH_RPR_SERVER_PROV_COMP_EVT enumerator ESP_BLE_MESH_RPR_SERVER_PROV_COMP_EVT enumerator ESP_BLE_MESH_RPR_SERVER_EVT_MAX enumerator ESP_BLE_MESH_RPR_SERVER_EVT_MAX enumerator ESP_BLE_MESH_RPR_SERVER_SCAN_START_EVT Directed Forwarding Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_df_model_api.h This header file can be included with: #include "esp_ble_mesh_df_model_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_df_client_callback(esp_ble_mesh_df_client_cb_t callback) Register BLE Mesh Directed Forwarding Configuration Client model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_register_df_server_callback(esp_ble_mesh_df_server_cb_t callback) Register BLE Mesh Directed Forwarding Configuration Server model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_df_client_get_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_df_client_get_t *get) Get the value of Directed Forwarding Configuration Server model state with the corresponding get message. Parameters params -- [in] Pointer to BLE Mesh common client parameters. get -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. params -- [in] Pointer to BLE Mesh common client parameters. get -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. get -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_df_client_set_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_df_client_set_t *set) Set the value of Directed Forwarding Configuration Server model state with the corresponding set message. Parameters params -- [in] Pointer to BLE Mesh common client parameters. set -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. params -- [in] Pointer to BLE Mesh common client parameters. set -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. set -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Returns ESP_OK on success or error code otherwise. Unions union esp_ble_mesh_df_client_get_t #include <esp_ble_mesh_df_model_api.h> Directed Forwarding Configuration Client model get message union. Public Members esp_ble_mesh_directed_control_get_t directed_control_get For ESP_BLE_MESH_MODEL_OP_DIRECTED_CONTROL_GET esp_ble_mesh_directed_control_get_t directed_control_get For ESP_BLE_MESH_MODEL_OP_DIRECTED_CONTROL_GET esp_ble_mesh_path_metric_get_t path_metric_get For ESP_BLE_MESH_MODEL_OP_PATH_METRIC_GET esp_ble_mesh_path_metric_get_t path_metric_get For ESP_BLE_MESH_MODEL_OP_PATH_METRIC_GET esp_ble_mesh_discovery_table_caps_get_t disc_table_caps_get For ESP_BLE_MESH_MODEL_OP_DISCOVERY_TABLE_CAPS_GET esp_ble_mesh_discovery_table_caps_get_t disc_table_caps_get For ESP_BLE_MESH_MODEL_OP_DISCOVERY_TABLE_CAPS_GET esp_ble_mesh_forwarding_table_entries_cnt_get_t forwarding_table_entries_cnt_get For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_CNT_GET esp_ble_mesh_forwarding_table_entries_cnt_get_t forwarding_table_entries_cnt_get For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_CNT_GET esp_ble_mesh_forwarding_table_entries_get_t forwarding_table_entries_get For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_GET esp_ble_mesh_forwarding_table_entries_get_t forwarding_table_entries_get For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_GET esp_ble_mesh_forwarding_table_deps_get_t forwarding_table_deps_get For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_GET esp_ble_mesh_forwarding_table_deps_get_t forwarding_table_deps_get For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_GET esp_ble_mesh_wanted_lanes_get_t wanted_lanes_get For ESP_BLE_MESH_MODEL_OP_WANTED_LANES_GET esp_ble_mesh_wanted_lanes_get_t wanted_lanes_get For ESP_BLE_MESH_MODEL_OP_WANTED_LANES_GET esp_ble_mesh_two_way_path_get_t two_way_path_get For ESP_BLE_MESH_MODEL_OP_TWO_WAY_PATH_GET esp_ble_mesh_two_way_path_get_t two_way_path_get For ESP_BLE_MESH_MODEL_OP_TWO_WAY_PATH_GET esp_ble_mesh_path_echo_interval_get_t path_echo_interval_get For ESP_BLE_MESH_MODEL_OP_PATH_ECHO_INTERVAL_GET esp_ble_mesh_path_echo_interval_get_t path_echo_interval_get For ESP_BLE_MESH_MODEL_OP_PATH_ECHO_INTERVAL_GET esp_ble_mesh_directed_publish_policy_get_t directed_pub_policy_get For ESP_BLE_MESH_MODEL_OP_DIRECTED_PUB_POLICY_GET esp_ble_mesh_directed_publish_policy_get_t directed_pub_policy_get For ESP_BLE_MESH_MODEL_OP_DIRECTED_PUB_POLICY_GET esp_ble_mesh_directed_control_get_t directed_control_get union esp_ble_mesh_df_client_set_t #include <esp_ble_mesh_df_model_api.h> Directed Forwarding Configuration Client model set message union. Public Members esp_ble_mesh_directed_control_set_t directed_control_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_CONTROL_SET esp_ble_mesh_directed_control_set_t directed_control_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_CONTROL_SET esp_ble_mesh_path_metric_set_t path_metric_set For ESP_BLE_MESH_MODEL_OP_PATH_METRIC_SET esp_ble_mesh_path_metric_set_t path_metric_set For ESP_BLE_MESH_MODEL_OP_PATH_METRIC_SET esp_ble_mesh_discovery_table_caps_set_t disc_table_caps_set For ESP_BLE_MESH_MODEL_OP_DISCOVERY_TABLE_CAPS_SET esp_ble_mesh_discovery_table_caps_set_t disc_table_caps_set For ESP_BLE_MESH_MODEL_OP_DISCOVERY_TABLE_CAPS_SET esp_ble_mesh_forwarding_table_add_t forwarding_table_add For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ADD esp_ble_mesh_forwarding_table_add_t forwarding_table_add For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ADD esp_ble_mesh_forwarding_table_delete_t forwarding_table_del For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEL esp_ble_mesh_forwarding_table_delete_t forwarding_table_del For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEL esp_ble_mesh_forwarding_table_deps_add_t forwarding_table_deps_add For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_ADD esp_ble_mesh_forwarding_table_deps_add_t forwarding_table_deps_add For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_ADD esp_ble_mesh_forwarding_table_deps_delete_t forwarding_table_deps_del For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_DEL esp_ble_mesh_forwarding_table_deps_delete_t forwarding_table_deps_del For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_DEL esp_ble_mesh_wanted_lanes_set_t wanted_lanes_set For ESP_BLE_MESH_MODEL_OP_WANTED_LANES_SET esp_ble_mesh_wanted_lanes_set_t wanted_lanes_set For ESP_BLE_MESH_MODEL_OP_WANTED_LANES_SET esp_ble_mesh_two_way_path_set_t two_way_path_set For ESP_BLE_MESH_MODEL_OP_TWO_WAY_PATH_SET esp_ble_mesh_two_way_path_set_t two_way_path_set For ESP_BLE_MESH_MODEL_OP_TWO_WAY_PATH_SET esp_ble_mesh_path_echo_interval_set_t path_echo_interval_set For ESP_BLE_MESH_MODEL_OP_PATH_ECHO_INTERVAL_SET esp_ble_mesh_path_echo_interval_set_t path_echo_interval_set For ESP_BLE_MESH_MODEL_OP_PATH_ECHO_INTERVAL_SET esp_ble_mesh_directed_net_transmit_set_t directed_net_transmit_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_NET_TRANSMIT_SET esp_ble_mesh_directed_net_transmit_set_t directed_net_transmit_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_NET_TRANSMIT_SET esp_ble_mesh_directed_relay_retransmit_set_t directed_relay_retransmit_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_RELAY_RETRANSMIT_SET esp_ble_mesh_directed_relay_retransmit_set_t directed_relay_retransmit_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_RELAY_RETRANSMIT_SET esp_ble_mesh_rssi_threshold_set_t rssi_threshold_set For ESP_BLE_MESH_MODEL_OP_RSSI_THRESHOLD_SET esp_ble_mesh_rssi_threshold_set_t rssi_threshold_set For ESP_BLE_MESH_MODEL_OP_RSSI_THRESHOLD_SET esp_ble_mesh_directed_publish_policy_set_t directed_pub_policy_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_PUB_POLICY_SET esp_ble_mesh_directed_publish_policy_set_t directed_pub_policy_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_PUB_POLICY_SET esp_ble_mesh_path_discovery_timing_ctl_set_t path_disc_timing_ctl_set For ESP_BLE_MESH_MODEL_OP_PATH_DISCOVERY_TIMING_CTL_SET esp_ble_mesh_path_discovery_timing_ctl_set_t path_disc_timing_ctl_set For ESP_BLE_MESH_MODEL_OP_PATH_DISCOVERY_TIMING_CTL_SET esp_ble_mesh_directed_ctl_net_transmit_set_t directed_ctl_net_transmit_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_NET_TRANSMIT_SET esp_ble_mesh_directed_ctl_net_transmit_set_t directed_ctl_net_transmit_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_NET_TRANSMIT_SET esp_ble_mesh_directed_ctl_relay_retransmit_set_t directed_ctl_relay_retransmit_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_RELAY_RETRANSMIT_SET esp_ble_mesh_directed_ctl_relay_retransmit_set_t directed_ctl_relay_retransmit_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_RELAY_RETRANSMIT_SET esp_ble_mesh_directed_control_set_t directed_control_set union esp_ble_mesh_df_client_recv_cb_t #include <esp_ble_mesh_df_model_api.h> Directed Forwarding Configuration Client model received message union. Public Members esp_ble_mesh_directed_control_status_t directed_control_status ESP_BLE_MESH_MODEL_OP_DIRECTED_CONTROL_STATUS esp_ble_mesh_directed_control_status_t directed_control_status ESP_BLE_MESH_MODEL_OP_DIRECTED_CONTROL_STATUS esp_ble_mesh_path_metric_status_t path_metric_status ESP_BLE_MESH_MODEL_OP_PATH_METRIC_STATUS esp_ble_mesh_path_metric_status_t path_metric_status ESP_BLE_MESH_MODEL_OP_PATH_METRIC_STATUS esp_ble_mesh_discovery_table_caps_status_t disc_table_caps_status ESP_BLE_MESH_MODEL_OP_DISCOVERY_TABLE_CAPS_STATUS esp_ble_mesh_discovery_table_caps_status_t disc_table_caps_status ESP_BLE_MESH_MODEL_OP_DISCOVERY_TABLE_CAPS_STATUS esp_ble_mesh_forwarding_table_status_t forwarding_table_status ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_STATUS esp_ble_mesh_forwarding_table_status_t forwarding_table_status ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_STATUS esp_ble_mesh_forwarding_table_deps_status_t forwarding_table_deps_status ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_STATUS esp_ble_mesh_forwarding_table_deps_status_t forwarding_table_deps_status ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_STATUS esp_ble_mesh_forwarding_table_entries_cnt_status_t forwarding_table_entries_cnt_status ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_CNT_STATUS esp_ble_mesh_forwarding_table_entries_cnt_status_t forwarding_table_entries_cnt_status ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_CNT_STATUS esp_ble_mesh_forwarding_table_entries_status_t forwarding_table_entries_status ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_STATUS esp_ble_mesh_forwarding_table_entries_status_t forwarding_table_entries_status ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_STATUS esp_ble_mesh_forwarding_table_deps_get_status_t forwarding_table_deps_get_status ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_GET_STATUS esp_ble_mesh_forwarding_table_deps_get_status_t forwarding_table_deps_get_status ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_GET_STATUS esp_ble_mesh_wanted_lanes_status_t wanted_lanes_status ESP_BLE_MESH_MODEL_OP_WANTED_LANES_STATUS esp_ble_mesh_wanted_lanes_status_t wanted_lanes_status ESP_BLE_MESH_MODEL_OP_WANTED_LANES_STATUS esp_ble_mesh_two_way_path_status_t two_way_path_status ESP_BLE_MESH_MODEL_OP_TWO_WAY_PATH_STATUS esp_ble_mesh_two_way_path_status_t two_way_path_status ESP_BLE_MESH_MODEL_OP_TWO_WAY_PATH_STATUS esp_ble_mesh_path_echo_interval_status_t path_echo_interval_status ESP_BLE_MESH_MODEL_OP_PATH_ECHO_INTERVAL_STATUS esp_ble_mesh_path_echo_interval_status_t path_echo_interval_status ESP_BLE_MESH_MODEL_OP_PATH_ECHO_INTERVAL_STATUS esp_ble_mesh_directed_net_transmit_status_t directed_net_transmit_status ESP_BLE_MESH_MODEL_OP_DIRECTED_NET_TRANSMIT_STATUS esp_ble_mesh_directed_net_transmit_status_t directed_net_transmit_status ESP_BLE_MESH_MODEL_OP_DIRECTED_NET_TRANSMIT_STATUS esp_ble_mesh_directed_relay_retransmit_status_t directed_relay_retransmit_status ESP_BLE_MESH_MODEL_OP_DIRECTED_RELAY_RETRANSMIT_STATUS esp_ble_mesh_directed_relay_retransmit_status_t directed_relay_retransmit_status ESP_BLE_MESH_MODEL_OP_DIRECTED_RELAY_RETRANSMIT_STATUS esp_ble_mesh_rssi_threshold_status_t rssi_threshold_status ESP_BLE_MESH_MODEL_OP_RSSI_THRESHOLD_STATUS esp_ble_mesh_rssi_threshold_status_t rssi_threshold_status ESP_BLE_MESH_MODEL_OP_RSSI_THRESHOLD_STATUS esp_ble_mesh_directed_paths_status_t directed_paths_status ESP_BLE_MESH_MODEL_OP_DIRECTED_PATHS_STATUS esp_ble_mesh_directed_paths_status_t directed_paths_status ESP_BLE_MESH_MODEL_OP_DIRECTED_PATHS_STATUS esp_ble_mesh_directed_pub_policy_status_t directed_pub_policy_status ESP_BLE_MESH_MODEL_OP_DIRECTED_PUB_POLICY_STATUS esp_ble_mesh_directed_pub_policy_status_t directed_pub_policy_status ESP_BLE_MESH_MODEL_OP_DIRECTED_PUB_POLICY_STATUS esp_ble_mesh_path_disc_timing_ctl_status_cb_t path_disc_timing_ctl_status ESP_BLE_MESH_MODEL_OP_PATH_DISCOVERY_TIMING_CTL_STATUS esp_ble_mesh_path_disc_timing_ctl_status_cb_t path_disc_timing_ctl_status ESP_BLE_MESH_MODEL_OP_PATH_DISCOVERY_TIMING_CTL_STATUS esp_ble_mesh_directed_ctl_net_transmit_status_t directed_ctl_net_transmit_status ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_NET_TRANSMIT_STATUS esp_ble_mesh_directed_ctl_net_transmit_status_t directed_ctl_net_transmit_status ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_NET_TRANSMIT_STATUS esp_ble_mesh_directed_ctl_relay_retransmit_status_t directed_ctl_relay_retransmit_status ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_RELAY_RETRANSMIT_STATUS esp_ble_mesh_directed_ctl_relay_retransmit_status_t directed_ctl_relay_retransmit_status ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_RELAY_RETRANSMIT_STATUS esp_ble_mesh_directed_control_status_t directed_control_status union esp_ble_mesh_df_server_state_change_t #include <esp_ble_mesh_df_model_api.h> Directed Forwarding Configuration Server model related context. Directed Forwarding Configuration Server model state change value union union esp_ble_mesh_df_server_cb_value_t #include <esp_ble_mesh_df_model_api.h> Directed Forwarding Configuration Server model callback value union. Public Members esp_ble_mesh_df_server_state_change_t state_change For ESP_BLE_MESH_DF_SERVER_STATE_CHANGE_EVT esp_ble_mesh_df_server_state_change_t state_change For ESP_BLE_MESH_DF_SERVER_STATE_CHANGE_EVT esp_ble_mesh_df_server_table_change_t table_change For ESP_BLE_MESH_DF_SERVER_TABLE_CHANGE_EVT esp_ble_mesh_df_server_table_change_t table_change For ESP_BLE_MESH_DF_SERVER_TABLE_CHANGE_EVT esp_ble_mesh_df_server_state_change_t state_change Structures struct esp_ble_mesh_df_srv_t Directed Forwarding Configuration Server model context Public Members esp_ble_mesh_model_t *model Pointer to Directed Forwarding Configuration Server model esp_ble_mesh_model_t *model Pointer to Directed Forwarding Configuration Server model uint8_t directed_net_transmit Directed Network Transmit state uint8_t directed_net_transmit Directed Network Transmit state uint8_t directed_relay_retransmit Directed Relay Retransmit state uint8_t directed_relay_retransmit Directed Relay Retransmit state int8_t default_rssi_threshold Default RSSI Threshold state int8_t default_rssi_threshold Default RSSI Threshold state uint8_t rssi_margin RSSI Margin state uint8_t rssi_margin RSSI Margin state uint16_t directed_node_paths Directed Node Paths state uint16_t directed_node_paths Directed Node Paths state uint16_t directed_relay_paths Directed Relay Paths state uint16_t directed_relay_paths Directed Relay Paths state uint16_t directed_proxy_paths Directed Proxy Paths state uint16_t directed_proxy_paths Directed Proxy Paths state uint16_t directed_friend_paths Directed Friend Paths state uint16_t directed_friend_paths Directed Friend Paths state uint16_t path_monitor_interval Path Monitoring Interval state uint16_t path_monitor_interval Path Monitoring Interval state uint16_t path_disc_retry_interval Path Discovery Retry Interval state uint16_t path_disc_retry_interval Path Discovery Retry Interval state uint8_t path_disc_interval Path Discovery Interval state uint8_t path_disc_interval Path Discovery Interval state uint8_t lane_disc_guard_interval Lane Discovery Guard Interval state uint8_t lane_disc_guard_interval Lane Discovery Guard Interval state uint8_t directed_ctl_net_transmit Directed Control Network Transmit state uint8_t directed_ctl_net_transmit Directed Control Network Transmit state uint8_t directed_ctl_relay_retransmit Directed Control Relay Retransmit state uint8_t directed_ctl_relay_retransmit Directed Control Relay Retransmit state esp_ble_mesh_model_t *model struct esp_ble_mesh_directed_control_get_t Parameters of Directed Control Get. struct esp_ble_mesh_directed_control_set_t Parameters of Directed Control Set. Public Members uint16_t net_idx NetKey Index uint16_t net_idx NetKey Index uint8_t directed_forwarding New Directed Forwarding state uint8_t directed_forwarding New Directed Forwarding state uint8_t directed_relay New Directed Relay state uint8_t directed_relay New Directed Relay state uint8_t directed_proxy New Directed Proxy state uint8_t directed_proxy New Directed Proxy state uint8_t directed_proxy_use_default New Directed Proxy Use Directed Default state or value to ignore uint8_t directed_proxy_use_default New Directed Proxy Use Directed Default state or value to ignore uint8_t directed_friend New Directed Friend state or value to ignore uint8_t directed_friend New Directed Friend state or value to ignore uint16_t net_idx struct esp_ble_mesh_path_metric_get_t Parameters of Path Metric Get. struct esp_ble_mesh_path_metric_set_t Parameters of Path Metric Set. struct esp_ble_mesh_discovery_table_caps_get_t Parameters of Discovery Table Capabilities Get. struct esp_ble_mesh_discovery_table_caps_set_t Parameters of Discovery Table Capabilities Set. struct esp_ble_mesh_forwarding_table_add_t Parameters of Forwarding Table Add. Public Members uint16_t net_idx NetKey Index uint16_t net_idx NetKey Index uint16_t unicast_dst Indicates whether or not the destination of the path is a unicast address uint16_t unicast_dst Indicates whether or not the destination of the path is a unicast address uint16_t bw_path_validated Indicates whether or not the backward path has been validated uint16_t bw_path_validated Indicates whether or not the backward path has been validated esp_ble_mesh_uar_t path_origin Unicast address range of the Path Origin esp_ble_mesh_uar_t path_origin Unicast address range of the Path Origin esp_ble_mesh_uar_t path_target Unicast address range of the Path Target esp_ble_mesh_uar_t path_target Unicast address range of the Path Target uint16_t multicast_dst Multicast destination address uint16_t multicast_dst Multicast destination address union esp_ble_mesh_forwarding_table_add_t::[anonymous] [anonymous] Path target address union esp_ble_mesh_forwarding_table_add_t::[anonymous] [anonymous] Path target address uint16_t bearer_twd_path_origin Index of the bearer toward the Path Origin uint16_t bearer_twd_path_origin Index of the bearer toward the Path Origin uint16_t bearer_twd_path_target Index of the bearer toward the Path Target uint16_t bearer_twd_path_target Index of the bearer toward the Path Target uint16_t net_idx struct esp_ble_mesh_forwarding_table_delete_t Parameters of Forwarding Table Delete. struct esp_ble_mesh_forwarding_table_deps_add_t Parameters of Forwarding Table Dependents Add. Public Members uint16_t net_idx NetKey Index uint16_t net_idx NetKey Index uint16_t path_origin Primary element address of the Path Origin uint16_t path_origin Primary element address of the Path Origin uint16_t dst Destination address uint16_t dst Destination address uint8_t dep_origin_uar_list_size Number of entries in the Dependent_Origin_Unicast_Addr_Range_List field uint8_t dep_origin_uar_list_size Number of entries in the Dependent_Origin_Unicast_Addr_Range_List field uint8_t dep_target_uar_list_size Number of entries in the Dependent_Target_Unicast_Addr_Range_List field uint8_t dep_target_uar_list_size Number of entries in the Dependent_Target_Unicast_Addr_Range_List field esp_ble_mesh_uar_t *dep_origin_uar_list List of the unicast address ranges of the dependent nodes of the Path Origin esp_ble_mesh_uar_t *dep_origin_uar_list List of the unicast address ranges of the dependent nodes of the Path Origin esp_ble_mesh_uar_t *dep_target_uar_list List of the unicast address ranges of the dependent nodes of the Path Target esp_ble_mesh_uar_t *dep_target_uar_list List of the unicast address ranges of the dependent nodes of the Path Target uint16_t net_idx struct esp_ble_mesh_forwarding_table_deps_delete_t Parameters of Forwarding Table Dependents Delete. Public Members uint16_t net_idx NetKey Index uint16_t net_idx NetKey Index uint16_t path_origin Primary element address of the Path Origin uint16_t path_origin Primary element address of the Path Origin uint16_t dst Destination address uint16_t dst Destination address uint8_t dep_origin_list_size Number of entries in the Dependent_Origin_List field uint8_t dep_origin_list_size Number of entries in the Dependent_Origin_List field uint8_t dep_target_list_size Number of entries in the Dependent_Target_List field uint8_t dep_target_list_size Number of entries in the Dependent_Target_List field uint16_t *dep_origin_list List of the primary element addresses of the dependent nodes of the Path Origin uint16_t *dep_origin_list List of the primary element addresses of the dependent nodes of the Path Origin uint16_t *dep_target_list List of the primary element addresses of the dependent nodes of the Path Target uint16_t *dep_target_list List of the primary element addresses of the dependent nodes of the Path Target uint16_t net_idx struct esp_ble_mesh_forwarding_table_entries_cnt_get_t Parameters of Forwarding Table Entries Count Get. struct esp_ble_mesh_forwarding_table_entries_get_t Parameters of Forwarding Table Entries Get. Public Members uint16_t net_idx NetKey Index uint16_t net_idx NetKey Index uint16_t filter_mask Filter to be applied to the Forwarding Table entries uint16_t filter_mask Filter to be applied to the Forwarding Table entries uint16_t start_index Start offset to read in units of Forwarding Table entries uint16_t start_index Start offset to read in units of Forwarding Table entries uint16_t path_origin Primary element address of the Path Origin uint16_t path_origin Primary element address of the Path Origin uint16_t dst Destination address uint16_t dst Destination address bool include_id Indicate whether or not the Forwarding Table Update Identifier is present bool include_id Indicate whether or not the Forwarding Table Update Identifier is present uint16_t update_id Last saved Forwarding Table Update Identifier (Optional) uint16_t update_id Last saved Forwarding Table Update Identifier (Optional) uint16_t net_idx struct esp_ble_mesh_forwarding_table_deps_get_t Parameters of Forwarding Table Dependents Get. Public Members uint16_t net_idx NetKey Index uint16_t net_idx NetKey Index uint16_t dep_list_mask Filter applied to the lists of unicast address ranges for dependent nodes uint16_t dep_list_mask Filter applied to the lists of unicast address ranges for dependent nodes uint16_t fixed_path_flag Indicate whether or not to return the unicast address ranges of dependent nodes in a fixed path entry uint16_t fixed_path_flag Indicate whether or not to return the unicast address ranges of dependent nodes in a fixed path entry uint16_t start_index Start offset in units of unicast address ranges uint16_t start_index Start offset in units of unicast address ranges uint16_t path_origin Primary element address of the Path Origin uint16_t path_origin Primary element address of the Path Origin uint16_t dst Destination address uint16_t dst Destination address bool include_id Indicate whether or not the Forwarding Table Update Identifier is present bool include_id Indicate whether or not the Forwarding Table Update Identifier is present uint16_t update_id Last saved Forwarding Table Update Identifier (Optional) uint16_t update_id Last saved Forwarding Table Update Identifier (Optional) uint16_t net_idx struct esp_ble_mesh_wanted_lanes_get_t Parameters of Wanted Lanes Get. struct esp_ble_mesh_wanted_lanes_set_t Parameters of Wanted Lanes Set. struct esp_ble_mesh_two_way_path_get_t Parameters of Two Way Path Get. struct esp_ble_mesh_two_way_path_set_t Parameters of Two Way Path Set. struct esp_ble_mesh_path_echo_interval_get_t Parameters of Path Echo Interval Get. struct esp_ble_mesh_path_echo_interval_set_t Parameters of Path Echo Interval Set. struct esp_ble_mesh_directed_net_transmit_set_t Parameters of Directed Network Transmit Set. Public Members uint8_t net_transmit New Directed Network Transmit state uint8_t net_transmit New Directed Network Transmit state uint8_t net_transmit struct esp_ble_mesh_directed_relay_retransmit_set_t Parameters of Directed Relay Retransmit Set. Public Members uint8_t relay_retransmit New Directed Relay Retransmit state uint8_t relay_retransmit New Directed Relay Retransmit state uint8_t relay_retransmit struct esp_ble_mesh_rssi_threshold_set_t Parameters of RSSI Threshold Set. Public Members uint8_t rssi_margin New RSSI Margin state uint8_t rssi_margin New RSSI Margin state uint8_t rssi_margin struct esp_ble_mesh_directed_publish_policy_get_t Parameters of Directed Publish Policy Get. struct esp_ble_mesh_directed_publish_policy_set_t Parameters of Directed Publish Policy Set. struct esp_ble_mesh_path_discovery_timing_ctl_set_t Parameters of Path Discovery Timing Control Set. struct esp_ble_mesh_directed_ctl_net_transmit_set_t Parameters of Directed Control Network Transmit Set. Public Members uint8_t net_transmit New Directed Control Network Transmit Count state uint8_t net_transmit New Directed Control Network Transmit Count state uint8_t net_transmit struct esp_ble_mesh_directed_ctl_relay_retransmit_set_t Parameters of Directed Control Relay Retransmit Set. Public Members uint8_t relay_retransmit New Directed Control Relay Retransmit Count state uint8_t relay_retransmit New Directed Control Relay Retransmit Count state uint8_t relay_retransmit struct esp_ble_mesh_directed_control_status_t Parameters of Directed Control Status. Public Members uint8_t status Status code for the requesting message uint8_t status Status code for the requesting message uint16_t net_idx NetKey Index uint16_t net_idx NetKey Index uint8_t directed_forwarding Current Directed Forwarding state uint8_t directed_forwarding Current Directed Forwarding state uint8_t directed_relay Current Directed Relay state uint8_t directed_relay Current Directed Relay state uint8_t directed_proxy Current Directed Proxy state uint8_t directed_proxy Current Directed Proxy state uint8_t directed_proxy_use_default Current Directed Proxy Use Directed Default state or 0xFF uint8_t directed_proxy_use_default Current Directed Proxy Use Directed Default state or 0xFF uint8_t directed_friend Current Directed Friend state uint8_t directed_friend Current Directed Friend state uint8_t status struct esp_ble_mesh_path_metric_status_t Parameters of Path Metric Status. struct esp_ble_mesh_discovery_table_caps_status_t Parameters of Discovery Table Capabilities Status. struct esp_ble_mesh_forwarding_table_status_t Parameters of Forwarding Table Status. struct esp_ble_mesh_forwarding_table_deps_status_t Parameters of Forwarding Table Dependent Status. struct esp_ble_mesh_forwarding_table_entries_cnt_status_t Parameters of Forwarding Table Entries Count Status. Public Members uint8_t status Status code for the requesting message uint8_t status Status code for the requesting message uint16_t net_idx NetKey Index uint16_t net_idx NetKey Index uint16_t update_id Current Forwarding Table Update Identifier state uint16_t update_id Current Forwarding Table Update Identifier state uint16_t fixed_entry_cnt Number of fixed path entries in the Forwarding Table uint16_t fixed_entry_cnt Number of fixed path entries in the Forwarding Table uint16_t non_fixed_entry_cnt Number of non-fixed path entries in the Forwarding Table uint16_t non_fixed_entry_cnt Number of non-fixed path entries in the Forwarding Table uint8_t status struct esp_ble_mesh_forwarding_table_entry_t Parameters of Forwarding Table Entry. Public Members uint16_t fixed_path_flag Indicates whether the table entry is a fixed path entry or a non-fixed path entry uint16_t fixed_path_flag Indicates whether the table entry is a fixed path entry or a non-fixed path entry uint16_t unicast_dst_flag Indicates whether or not the destination of the path is a unicast address uint16_t unicast_dst_flag Indicates whether or not the destination of the path is a unicast address uint16_t bw_path_validated_flag Indicates whether or not the backward path has been validated uint16_t bw_path_validated_flag Indicates whether or not the backward path has been validated uint16_t bearer_twd_path_origin_ind Indicates the presence or absence of the Bearer_Toward_Path_Origin field uint16_t bearer_twd_path_origin_ind Indicates the presence or absence of the Bearer_Toward_Path_Origin field uint16_t bearer_twd_path_target_ind Indicates the presence or absence of the Bearer_Toward_Path_Target field uint16_t bearer_twd_path_target_ind Indicates the presence or absence of the Bearer_Toward_Path_Target field uint16_t dep_origin_list_size_ind Indicates the size of the Dependent_Origin_List field uint16_t dep_origin_list_size_ind Indicates the size of the Dependent_Origin_List field uint16_t dep_target_list_size_ind Indicates the size of the Dependent_Target_List field uint16_t dep_target_list_size_ind Indicates the size of the Dependent_Target_List field uint8_t lane_counter Number of lanes in the path uint8_t lane_counter Number of lanes in the path uint16_t path_remaining_time Path lifetime remaining uint16_t path_remaining_time Path lifetime remaining uint8_t path_origin_forward_number Forwarding number of the Path Origin uint8_t path_origin_forward_number Forwarding number of the Path Origin esp_ble_mesh_uar_t path_origin Path Origin unicast address range esp_ble_mesh_uar_t path_origin Path Origin unicast address range uint16_t dep_origin_list_size Current number of entries in the list of dependent nodes of the Path Origin uint16_t dep_origin_list_size Current number of entries in the list of dependent nodes of the Path Origin uint16_t bearer_twd_path_origin Index of the bearer toward the Path Origin uint16_t bearer_twd_path_origin Index of the bearer toward the Path Origin esp_ble_mesh_uar_t path_target Path Target unicast address range esp_ble_mesh_uar_t path_target Path Target unicast address range uint16_t multicast_dst Multicast destination address uint16_t multicast_dst Multicast destination address uint16_t dep_target_list_size Current number of entries in the list of dependent nodes of the Path Target uint16_t dep_target_list_size Current number of entries in the list of dependent nodes of the Path Target uint16_t bearer_twd_path_target Index of the bearer toward the Path Target uint16_t bearer_twd_path_target Index of the bearer toward the Path Target uint16_t fixed_path_flag struct esp_ble_mesh_forwarding_table_entries_status_t Parameters of Forwarding Table Entries Status. Public Members uint8_t status Status code for the requesting message uint8_t status Status code for the requesting message uint16_t net_idx NetKey Index uint16_t net_idx NetKey Index uint16_t filter_mask Filter applied to the Forwarding Table entries uint16_t filter_mask Filter applied to the Forwarding Table entries uint16_t start_index Start offset in units of Forwarding Table entries uint16_t start_index Start offset in units of Forwarding Table entries uint16_t path_origin Primary element address of the Path Origin uint16_t path_origin Primary element address of the Path Origin uint16_t dst Destination address uint16_t dst Destination address bool include_id Indicate whether or not the Forwarding Table Update Identifier is present bool include_id Indicate whether or not the Forwarding Table Update Identifier is present uint16_t update_id Current Forwarding Table Update Identifier state uint16_t update_id Current Forwarding Table Update Identifier state uint8_t entry_list_size Current number of entries in the list of Forwarding Table entries uint8_t entry_list_size Current number of entries in the list of Forwarding Table entries esp_ble_mesh_forwarding_table_entry_t *entry_list List of Forwarding Table entries esp_ble_mesh_forwarding_table_entry_t *entry_list List of Forwarding Table entries uint8_t status struct esp_ble_mesh_forwarding_table_deps_get_status_t Parameters of Forwarding Table Dependents Get Status. Public Members uint8_t status Status code for the requesting message uint8_t status Status code for the requesting message uint16_t net_idx NetKey Index uint16_t net_idx NetKey Index uint16_t dep_list_mask Filter applied to the lists of unicast address ranges for dependent nodes uint16_t dep_list_mask Filter applied to the lists of unicast address ranges for dependent nodes uint16_t fixed_path_flag Flag indicating whether or not to return the unicast address ranges of dependent nodes in a fixed path entry uint16_t fixed_path_flag Flag indicating whether or not to return the unicast address ranges of dependent nodes in a fixed path entry uint16_t start_index Start offset in units of unicast address ranges uint16_t start_index Start offset in units of unicast address ranges uint16_t path_origin Primary element address of the Path Origin uint16_t path_origin Primary element address of the Path Origin uint16_t dst Destination address uint16_t dst Destination address bool include_id Indicate whether or not the Forwarding Table Update Identifier is present bool include_id Indicate whether or not the Forwarding Table Update Identifier is present uint16_t update_id Current Forwarding Table Update Identifier state uint16_t update_id Current Forwarding Table Update Identifier state uint8_t dep_origin_uar_list_size Number of unicast address ranges in the Dependent_Origin_Unicast_Addr_Range_List field uint8_t dep_origin_uar_list_size Number of unicast address ranges in the Dependent_Origin_Unicast_Addr_Range_List field uint8_t dep_target_uar_list_size Number of unicast address ranges in the Dependent_Target_Unicast_Addr_Range_List field uint8_t dep_target_uar_list_size Number of unicast address ranges in the Dependent_Target_Unicast_Addr_Range_List field esp_ble_mesh_uar_t *dep_origin_uar_list List of unicast address ranges of dependent nodes of the Path Origin esp_ble_mesh_uar_t *dep_origin_uar_list List of unicast address ranges of dependent nodes of the Path Origin esp_ble_mesh_uar_t *dep_target_uar_list List of unicast address ranges of dependent nodes of the Path Target esp_ble_mesh_uar_t *dep_target_uar_list List of unicast address ranges of dependent nodes of the Path Target uint8_t status struct esp_ble_mesh_wanted_lanes_status_t Parameters of Wanted Lanes Status. struct esp_ble_mesh_two_way_path_status_t Parameters of Two Way Path Status. struct esp_ble_mesh_path_echo_interval_status_t Parameters of Path Echo Interval Status. struct esp_ble_mesh_directed_net_transmit_status_t Parameters of Directed Network Transmit Status. Public Members uint8_t net_transmit Current Directed Network Transmit state uint8_t net_transmit Current Directed Network Transmit state uint8_t net_transmit struct esp_ble_mesh_directed_relay_retransmit_status_t Parameters of Directed Relay Retransmit Status. Public Members uint8_t relay_retransmit Current Directed Relay Retransmit state uint8_t relay_retransmit Current Directed Relay Retransmit state uint8_t relay_retransmit struct esp_ble_mesh_rssi_threshold_status_t Parameters of RSSI Threshold Status. struct esp_ble_mesh_directed_paths_status_t Parameters of Directed Paths Status. struct esp_ble_mesh_directed_pub_policy_status_t Parameters of Directed Publish Policy Status. struct esp_ble_mesh_path_disc_timing_ctl_status_cb_t Parameters of Path Discovery Timing Control Status. Public Members uint16_t path_monitor_interval Current Path Monitoring Interval state uint16_t path_monitor_interval Current Path Monitoring Interval state uint16_t path_disc_retry_interval Current Path Discovery Retry Interval state uint16_t path_disc_retry_interval Current Path Discovery Retry Interval state uint8_t path_disc_interval Current Path Discovery Interval state uint8_t path_disc_interval Current Path Discovery Interval state uint8_t lane_disc_guard_interval Current Lane Discovery Guard Interval state uint8_t lane_disc_guard_interval Current Lane Discovery Guard Interval state uint16_t path_monitor_interval struct esp_ble_mesh_directed_ctl_net_transmit_status_t Parameters of Directed Control Network Transmit Status. Public Members uint8_t net_transmit Current Directed Control Network Transmit state uint8_t net_transmit Current Directed Control Network Transmit state uint8_t net_transmit struct esp_ble_mesh_directed_ctl_relay_retransmit_status_t Parameters of Directed Control Relay Retransmit Status. Public Members uint8_t relay_retransmit Current Directed Control Relay Retransmit state uint8_t relay_retransmit Current Directed Control Relay Retransmit state uint8_t relay_retransmit struct esp_ble_mesh_df_client_send_cb_t Result of sending Directed Forwarding Configuration Client messages struct esp_ble_mesh_df_client_cb_param_t Directed Forwarding Configuration Client model callback parameters Public Members esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events. esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events. esp_ble_mesh_df_client_send_cb_t send Result of sending a message esp_ble_mesh_df_client_send_cb_t send Result of sending a message esp_ble_mesh_df_client_recv_cb_t recv Parameters of received status message esp_ble_mesh_df_client_recv_cb_t recv Parameters of received status message union esp_ble_mesh_df_client_cb_param_t::[anonymous] [anonymous] Union of DF Client callback union esp_ble_mesh_df_client_cb_param_t::[anonymous] [anonymous] Union of DF Client callback esp_ble_mesh_client_common_param_t *params struct esp_ble_mesh_df_server_table_change_t Parameters of directed forwarding table entry change Public Members esp_ble_mesh_df_table_action_t action Action of directed forwarding table esp_ble_mesh_df_table_action_t action Action of directed forwarding table esp_ble_mesh_uar_t path_origin Primary element address of the Path Origin esp_ble_mesh_uar_t path_origin Primary element address of the Path Origin esp_ble_mesh_uar_t path_target Primary element address of the Path Target esp_ble_mesh_uar_t path_target Primary element address of the Path Target esp_ble_mesh_uar_t *dep_origin_data List of the primary element addresses of the dependent nodes of the Path Origin esp_ble_mesh_uar_t *dep_origin_data List of the primary element addresses of the dependent nodes of the Path Origin uint32_t dep_origin_num Number of entries in the Dependent_Origin_List field of the message uint32_t dep_origin_num Number of entries in the Dependent_Origin_List field of the message esp_ble_mesh_uar_t *dep_target_data List of the primary element addresses of the dependent nodes of the Path Target esp_ble_mesh_uar_t *dep_target_data List of the primary element addresses of the dependent nodes of the Path Target uint32_t dep_target_num Number of entries in the Dependent_Target_List field of the message uint32_t dep_target_num Number of entries in the Dependent_Target_List field of the message uint8_t fixed_path Indicates whether the table entry is a fixed path entry or a non-fixed path entry uint8_t fixed_path Indicates whether the table entry is a fixed path entry or a non-fixed path entry uint8_t bw_path_validate Indicates whether or not the backward path has been validated uint8_t bw_path_validate Indicates whether or not the backward path has been validated uint8_t path_not_ready Flag indicating whether or not the path is ready for use uint8_t path_not_ready Flag indicating whether or not the path is ready for use uint8_t forward_number Forwarding number of the Path Origin; If the entry is associated with a fixed path, the value is 0 uint8_t forward_number Forwarding number of the Path Origin; If the entry is associated with a fixed path, the value is 0 uint8_t lane_counter Number of lanes discovered; if the entry is associated with a fixed path, the value is 1. uint8_t lane_counter Number of lanes discovered; if the entry is associated with a fixed path, the value is 1. struct esp_ble_mesh_df_server_table_change_t::[anonymous]::[anonymous] df_table_entry_add_remove Structure of directed forwarding table add and remove Structure of directed forwarding table add and remove struct esp_ble_mesh_df_server_table_change_t::[anonymous]::[anonymous] df_table_entry_add_remove Structure of directed forwarding table add and remove Structure of directed forwarding table add and remove uint8_t dummy Event not used currently uint8_t dummy Event not used currently struct esp_ble_mesh_df_server_table_change_t::[anonymous]::[anonymous] df_table_entry_change Structure of directed forwarding table entry change Directed forwarding table entry change struct esp_ble_mesh_df_server_table_change_t::[anonymous]::[anonymous] df_table_entry_change Structure of directed forwarding table entry change Directed forwarding table entry change union esp_ble_mesh_df_server_table_change_t::[anonymous] df_table_info Union of directed forwarding table information Directed forwarding table information union esp_ble_mesh_df_server_table_change_t::[anonymous] df_table_info Union of directed forwarding table information Directed forwarding table information esp_ble_mesh_df_table_action_t action struct esp_ble_mesh_df_server_cb_param_t Directed Forwarding Configuration Server model callback parameters Public Members esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_df_server_cb_value_t value Value of the received configuration messages esp_ble_mesh_df_server_cb_value_t value Value of the received configuration messages esp_ble_mesh_model_t *model Macros ESP_BLE_MESH_MODEL_OP_DIRECTED_CONTROL_GET ESP_BLE_MESH_MODEL_OP_DIRECTED_CONTROL_SET ESP_BLE_MESH_MODEL_OP_DIRECTED_CONTROL_STATUS ESP_BLE_MESH_MODEL_OP_PATH_METRIC_GET ESP_BLE_MESH_MODEL_OP_PATH_METRIC_SET ESP_BLE_MESH_MODEL_OP_PATH_METRIC_STATUS ESP_BLE_MESH_MODEL_OP_DISCOVERY_TABLE_CAPS_GET ESP_BLE_MESH_MODEL_OP_DISCOVERY_TABLE_CAPS_SET ESP_BLE_MESH_MODEL_OP_DISCOVERY_TABLE_CAPS_STATUS ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ADD ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEL ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_STATUS ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_ADD ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_DEL ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_STATUS ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_GET ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_GET_STATUS ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_CNT_GET ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_CNT_STATUS ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_GET ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_STATUS ESP_BLE_MESH_MODEL_OP_WANTED_LANES_GET ESP_BLE_MESH_MODEL_OP_WANTED_LANES_SET ESP_BLE_MESH_MODEL_OP_WANTED_LANES_STATUS ESP_BLE_MESH_MODEL_OP_TWO_WAY_PATH_GET ESP_BLE_MESH_MODEL_OP_TWO_WAY_PATH_SET ESP_BLE_MESH_MODEL_OP_TWO_WAY_PATH_STATUS ESP_BLE_MESH_MODEL_OP_PATH_ECHO_INTERVAL_GET ESP_BLE_MESH_MODEL_OP_PATH_ECHO_INTERVAL_SET ESP_BLE_MESH_MODEL_OP_PATH_ECHO_INTERVAL_STATUS ESP_BLE_MESH_MODEL_OP_DIRECTED_NET_TRANSMIT_GET ESP_BLE_MESH_MODEL_OP_DIRECTED_NET_TRANSMIT_SET ESP_BLE_MESH_MODEL_OP_DIRECTED_NET_TRANSMIT_STATUS ESP_BLE_MESH_MODEL_OP_DIRECTED_RELAY_RETRANSMIT_GET ESP_BLE_MESH_MODEL_OP_DIRECTED_RELAY_RETRANSMIT_SET ESP_BLE_MESH_MODEL_OP_DIRECTED_RELAY_RETRANSMIT_STATUS ESP_BLE_MESH_MODEL_OP_RSSI_THRESHOLD_GET ESP_BLE_MESH_MODEL_OP_RSSI_THRESHOLD_SET ESP_BLE_MESH_MODEL_OP_RSSI_THRESHOLD_STATUS ESP_BLE_MESH_MODEL_OP_DIRECTED_PATHS_GET ESP_BLE_MESH_MODEL_OP_DIRECTED_PATHS_STATUS ESP_BLE_MESH_MODEL_OP_DIRECTED_PUB_POLICY_GET ESP_BLE_MESH_MODEL_OP_DIRECTED_PUB_POLICY_SET ESP_BLE_MESH_MODEL_OP_DIRECTED_PUB_POLICY_STATUS ESP_BLE_MESH_MODEL_OP_PATH_DISCOVERY_TIMING_CTL_GET ESP_BLE_MESH_MODEL_OP_PATH_DISCOVERY_TIMING_CTL_SET ESP_BLE_MESH_MODEL_OP_PATH_DISCOVERY_TIMING_CTL_STATUS ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_NET_TRANSMIT_GET ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_NET_TRANSMIT_SET ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_NET_TRANSMIT_STATUS ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_RELAY_RETRANSMIT_GET ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_RELAY_RETRANSMIT_SET ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_RELAY_RETRANSMIT_STATUS ESP_BLE_MESH_PATH_DISC_INTERVAL_5_SEC ESP_BLE_MESH_PATH_DISC_INTERVAL_30_SEC ESP_BLE_MESH_LANE_DISC_GUARD_INTERVAL_2_SEC ESP_BLE_MESH_LANE_DISC_GUARD_INTERVAL_10_SEC ESP_BLE_MESH_DIRECTED_PUB_POLICY_MANAGED_FLOODING ESP_BLE_MESH_DIRECTED_PUB_POLICY_DIRECTED_FORWARDING ESP_BLE_MESH_GET_FILTER_MASK(fp, nfp, pom, dm) ESP_BLE_MESH_MODEL_DF_SRV(srv_data) Define a new Directed Forwarding Configuration Server model. Note If supported, the model shall be supported by a primary element and shall not be supported by any secondary elements. Parameters srv_data -- Pointer to a unique Directed Forwarding Configuration Server model user_data. srv_data -- Pointer to a unique Directed Forwarding Configuration Server model user_data. srv_data -- Pointer to a unique Directed Forwarding Configuration Server model user_data. Returns New Directed Forwarding Configuration Server model instance. Parameters srv_data -- Pointer to a unique Directed Forwarding Configuration Server model user_data. Returns New Directed Forwarding Configuration Server model instance. ESP_BLE_MESH_MODEL_DF_CLI(cli_data) Define a new Directed Forwarding Configuration Client model. Note If supported, the model shall be supported by a primary element and shall not be supported by any secondary elements. Parameters cli_data -- Pointer to a unique Directed Forwarding Configuration Client model user_data. cli_data -- Pointer to a unique Directed Forwarding Configuration Client model user_data. cli_data -- Pointer to a unique Directed Forwarding Configuration Client model user_data. Returns New Directed Forwarding Configuration Client model instance. Parameters cli_data -- Pointer to a unique Directed Forwarding Configuration Client model user_data. Returns New Directed Forwarding Configuration Client model instance. Type Definitions typedef void (*esp_ble_mesh_df_client_cb_t)(esp_ble_mesh_df_client_cb_event_t event, esp_ble_mesh_df_client_cb_param_t *param) Bluetooth Mesh Directed Forwarding Configuration client and server model functions. Directed Forwarding Configuration Client model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter typedef void (*esp_ble_mesh_df_server_cb_t)(esp_ble_mesh_df_server_cb_event_t event, esp_ble_mesh_df_server_cb_param_t *param) Directed Forwarding Configuration Server model callback function type. Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter Enumerations enum esp_ble_mesh_df_client_cb_event_t This enum value is the event of Directed Forwarding Configuration Client model Values: enumerator ESP_BLE_MESH_DF_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_DF_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_DF_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_DF_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_DF_CLIENT_RECV_GET_RSP_EVT enumerator ESP_BLE_MESH_DF_CLIENT_RECV_GET_RSP_EVT enumerator ESP_BLE_MESH_DF_CLIENT_RECV_SET_RSP_EVT enumerator ESP_BLE_MESH_DF_CLIENT_RECV_SET_RSP_EVT enumerator ESP_BLE_MESH_DF_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_DF_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_DF_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_DF_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_DF_CLIENT_SEND_COMP_EVT enum esp_ble_mesh_df_table_action_t Values: enumerator ESP_BLE_MESH_DF_TABLE_ACT_EMPTY enumerator ESP_BLE_MESH_DF_TABLE_ACT_EMPTY enumerator ESP_BLE_MESH_DF_TABLE_ADD enumerator ESP_BLE_MESH_DF_TABLE_ADD enumerator ESP_BLE_MESH_DF_TABLE_REMOVE enumerator ESP_BLE_MESH_DF_TABLE_REMOVE enumerator ESP_BLE_MESH_DF_TABLE_ENTRY_CHANGE enumerator ESP_BLE_MESH_DF_TABLE_ENTRY_CHANGE enumerator ESP_BLE_MESH_DF_TABLE_ACT_MAX_LIMIT enumerator ESP_BLE_MESH_DF_TABLE_ACT_MAX_LIMIT enumerator ESP_BLE_MESH_DF_TABLE_ACT_EMPTY Subnet Bridge Configuration Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_brc_model_api.h This header file can be included with: #include "esp_ble_mesh_brc_model_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_brc_client_callback(esp_ble_mesh_brc_client_cb_t callback) Register BLE Mesh Bridge Configuration Client model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_register_brc_server_callback(esp_ble_mesh_brc_server_cb_t callback) Register BLE Mesh Bridge Configuration Server model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_brc_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_brc_client_msg_t *msg) Get/Set the value of Bridge Configuration Server model state with the corresponding message. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Bridge Configuration Client message. params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Bridge Configuration Client message. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Bridge Configuration Client message. Returns ESP_OK on success or error code otherwise. Unions union esp_ble_mesh_brc_client_msg_t #include <esp_ble_mesh_brc_model_api.h> Bridge Configuration Client model message union. Public Members esp_ble_mesh_bridged_subnets_get_t bridged_subnets_get For ESP_BLE_MESH_MODEL_OP_BRIDGED_SUBNETS_GET esp_ble_mesh_bridged_subnets_get_t bridged_subnets_get For ESP_BLE_MESH_MODEL_OP_BRIDGED_SUBNETS_GET esp_ble_mesh_bridging_table_get_t bridging_table_get For ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_GET esp_ble_mesh_bridging_table_get_t bridging_table_get For ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_GET esp_ble_mesh_subnet_bridge_set_t subnet_bridge_set For ESP_BLE_MESH_MODEL_OP_SUBNET_BRIDGE_SET esp_ble_mesh_subnet_bridge_set_t subnet_bridge_set For ESP_BLE_MESH_MODEL_OP_SUBNET_BRIDGE_SET esp_ble_mesh_bridging_table_add_t bridging_table_add For ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_ADD esp_ble_mesh_bridging_table_add_t bridging_table_add For ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_ADD esp_ble_mesh_bridging_table_remove_t bridging_table_remove For ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_REMOVE esp_ble_mesh_bridging_table_remove_t bridging_table_remove For ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_REMOVE esp_ble_mesh_bridged_subnets_get_t bridged_subnets_get union esp_ble_mesh_brc_client_recv_cb_t #include <esp_ble_mesh_brc_model_api.h> Bridge Configuration Client model received message union. Public Members esp_ble_mesh_subnet_bridge_status_t subnet_bridge_status ESP_BLE_MESH_MODEL_OP_SUBNET_BRIDGE_STATUS esp_ble_mesh_subnet_bridge_status_t subnet_bridge_status ESP_BLE_MESH_MODEL_OP_SUBNET_BRIDGE_STATUS esp_ble_mesh_bridging_table_status_t bridging_table_status ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_STATUS esp_ble_mesh_bridging_table_status_t bridging_table_status ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_STATUS esp_ble_mesh_bridged_subnets_list_t bridged_subnets_list ESP_BLE_MESH_MODEL_OP_BRIDGED_SUBNETS_LIST esp_ble_mesh_bridged_subnets_list_t bridged_subnets_list ESP_BLE_MESH_MODEL_OP_BRIDGED_SUBNETS_LIST esp_ble_mesh_bridging_table_list_t bridging_table_list ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_LIST esp_ble_mesh_bridging_table_list_t bridging_table_list ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_LIST esp_ble_mesh_bridging_table_size_status_t bridging_table_size_status ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_SIZE_STATUS esp_ble_mesh_bridging_table_size_status_t bridging_table_size_status ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_SIZE_STATUS esp_ble_mesh_subnet_bridge_status_t subnet_bridge_status union esp_ble_mesh_brc_server_state_change_t #include <esp_ble_mesh_brc_model_api.h> Bridge Configuration Server model state change value union. Public Members esp_ble_mesh_state_change_bridging_table_add_t bridging_table_add The recv_op in ctx can be used to decide which state is changed. Bridging Table Add esp_ble_mesh_state_change_bridging_table_add_t bridging_table_add The recv_op in ctx can be used to decide which state is changed. Bridging Table Add esp_ble_mesh_state_change_bridging_table_remove_t bridging_table_remove Bridging Table Remove esp_ble_mesh_state_change_bridging_table_remove_t bridging_table_remove Bridging Table Remove esp_ble_mesh_state_change_bridging_table_add_t bridging_table_add union esp_ble_mesh_brc_server_cb_value_t #include <esp_ble_mesh_brc_model_api.h> Bridge Configuration Server model callback value union. Public Members esp_ble_mesh_brc_server_state_change_t state_change For ESP_BLE_MESH_BRC_SERVER_STATE_CHANGE_EVT esp_ble_mesh_brc_server_state_change_t state_change For ESP_BLE_MESH_BRC_SERVER_STATE_CHANGE_EVT esp_ble_mesh_brc_server_state_change_t state_change Structures struct esp_ble_mesh_subnet_bridge_table_t Parameters of subnet bridge table struct esp_ble_mesh_subnet_bridge_set_t Parameters of Subnet Bridge Set Public Members uint8_t subnet_bridge New Subnet Bridge state uint8_t subnet_bridge New Subnet Bridge state uint8_t subnet_bridge struct esp_ble_mesh_bridging_table_add_t Parameters of Bridging Table Add Public Members uint8_t bridge_direction Allowed directions for the bridged traffic uint8_t bridge_direction Allowed directions for the bridged traffic uint16_t bridge_net_idx_1 NetKey Index of the first subnet uint16_t bridge_net_idx_1 NetKey Index of the first subnet uint16_t bridge_net_idx_2 NetKey Index of the second subnet uint16_t bridge_net_idx_2 NetKey Index of the second subnet uint16_t bridge_addr_1 Address of the node in the first subnet uint16_t bridge_addr_1 Address of the node in the first subnet uint16_t bridge_addr_2 Address of the node in the second subnet uint16_t bridge_addr_2 Address of the node in the second subnet uint8_t bridge_direction struct esp_ble_mesh_bridging_table_remove_t Parameters of Bridging Table Remove struct esp_ble_mesh_bridged_subnets_get_t Parameters of Bridged Subnets Get struct esp_ble_mesh_bridging_table_get_t Parameters of Bridging Table Get struct esp_ble_mesh_subnet_bridge_status_t Parameters of Subnet Bridge Status Public Members uint8_t subnet_bridge Current Subnet Bridge state uint8_t subnet_bridge Current Subnet Bridge state uint8_t subnet_bridge struct esp_ble_mesh_bridging_table_status_t Parameters of Bridging Table Status Public Members uint8_t status Status Code for the requesting message uint8_t status Status Code for the requesting message uint8_t bridge_direction Allowed directions for the bridged traffic uint8_t bridge_direction Allowed directions for the bridged traffic uint16_t bridge_net_idx_1 NetKey Index of the first subnet uint16_t bridge_net_idx_1 NetKey Index of the first subnet uint16_t bridge_net_idx_2 NetKey Index of the second subnet uint16_t bridge_net_idx_2 NetKey Index of the second subnet uint16_t bridge_addr_1 Address of the node in the first subnet uint16_t bridge_addr_1 Address of the node in the first subnet uint16_t bridge_addr_2 Address of the node in the second subnet uint16_t bridge_addr_2 Address of the node in the second subnet uint8_t status struct esp_ble_mesh_bridge_net_idx_pair_entry_t Bridged_Subnets_List entry format struct esp_ble_mesh_bridged_subnets_list_t Parameters of Bridged Subnets List Public Members uint16_t bridge_filter Filter applied to the set of pairs of NetKey Indexes uint16_t bridge_filter Filter applied to the set of pairs of NetKey Indexes uint16_t bridge_net_idx NetKey Index used for filtering or ignored uint16_t bridge_net_idx NetKey Index used for filtering or ignored uint8_t bridge_start_idx Start offset in units of bridges uint8_t bridge_start_idx Start offset in units of bridges uint8_t bridged_entry_list_size Num of pairs of NetKey Indexes uint8_t bridged_entry_list_size Num of pairs of NetKey Indexes esp_ble_mesh_bridge_net_idx_pair_entry_t *net_idx_pair Filtered set of N pairs of NetKey Indexes esp_ble_mesh_bridge_net_idx_pair_entry_t *net_idx_pair Filtered set of N pairs of NetKey Indexes uint16_t bridge_filter struct esp_ble_mesh_bridged_addr_list_entry_t Bridged_Addresses_List entry format struct esp_ble_mesh_bridging_table_list_t Parameters of Bridging Table List Public Members uint8_t status Status Code for the requesting message uint8_t status Status Code for the requesting message uint16_t bridge_net_idx_1 NetKey Index of the first subnet uint16_t bridge_net_idx_1 NetKey Index of the first subnet uint16_t bridge_net_idx_2 NetKey Index of the second subnet uint16_t bridge_net_idx_2 NetKey Index of the second subnet uint16_t bridge_start_idx Start offset in units of Bridging Table state entries uint16_t bridge_start_idx Start offset in units of Bridging Table state entries uint16_t bridged_addr_list_size Num of pairs of entry uint16_t bridged_addr_list_size Num of pairs of entry esp_ble_mesh_bridged_addr_list_entry_t *bridged_addr_list List of bridged addresses and allowed traffic directions esp_ble_mesh_bridged_addr_list_entry_t *bridged_addr_list List of bridged addresses and allowed traffic directions uint8_t status struct esp_ble_mesh_bridging_table_size_status_t Parameters of Bridging Table Size Status Public Members uint16_t bridging_table_size Bridging Table Size state uint16_t bridging_table_size Bridging Table Size state uint16_t bridging_table_size struct esp_ble_mesh_brc_client_send_cb_t Result of sending Bridge Configuration Client messages struct esp_ble_mesh_brc_client_cb_param_t Bridge Configuration Client model callback parameters Public Members esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events. esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events. esp_ble_mesh_brc_client_send_cb_t send Result of sending a message esp_ble_mesh_brc_client_send_cb_t send Result of sending a message esp_ble_mesh_brc_client_recv_cb_t recv Parameters of received status message esp_ble_mesh_brc_client_recv_cb_t recv Parameters of received status message union esp_ble_mesh_brc_client_cb_param_t::[anonymous] [anonymous] Union of Bridge Configuration Client callback union esp_ble_mesh_brc_client_cb_param_t::[anonymous] [anonymous] Union of Bridge Configuration Client callback esp_ble_mesh_client_common_param_t *params struct esp_ble_mesh_state_change_bridging_table_add_t Bridge Configuration Server model related context. Parameters of Bridging Table Add Public Members uint8_t bridge_direction Allowed directions for the bridged traffic uint8_t bridge_direction Allowed directions for the bridged traffic uint16_t bridge_net_idx_1 NetKey Index of the first subnet uint16_t bridge_net_idx_1 NetKey Index of the first subnet uint16_t bridge_net_idx_2 NetKey Index of the second subnet uint16_t bridge_net_idx_2 NetKey Index of the second subnet uint16_t bridge_addr_1 Address of the node in the first subnet uint16_t bridge_addr_1 Address of the node in the first subnet uint16_t bridge_addr_2 Address of the node in the second subnet uint16_t bridge_addr_2 Address of the node in the second subnet uint8_t bridge_direction struct esp_ble_mesh_state_change_bridging_table_remove_t Parameters of Bridging Table Remove struct esp_ble_mesh_brc_server_cb_param_t Bridge Configuration Server model callback parameters Public Members esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_brc_server_cb_value_t value Value of the received configuration messages esp_ble_mesh_brc_server_cb_value_t value Value of the received configuration messages esp_ble_mesh_model_t *model Macros ESP_BLE_MESH_MODEL_OP_SUBNET_BRIDGE_GET ESP_BLE_MESH_MODEL_OP_SUBNET_BRIDGE_SET ESP_BLE_MESH_MODEL_OP_SUBNET_BRIDGE_STATUS ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_ADD ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_REMOVE ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_STATUS ESP_BLE_MESH_MODEL_OP_BRIDGED_SUBNETS_GET ESP_BLE_MESH_MODEL_OP_BRIDGED_SUBNETS_LIST ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_GET ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_LIST ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_SIZE_GET ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_SIZE_STATUS ESP_BLE_MESH_MODEL_BRC_SRV(srv_data) Define a new Bridge Configuration Server model. Note If supported, the model shall be supported by a primary element and shall not be supported by any secondary elements. Parameters srv_data -- Pointer to a unique Bridge Configuration Server model user_data. srv_data -- Pointer to a unique Bridge Configuration Server model user_data. srv_data -- Pointer to a unique Bridge Configuration Server model user_data. Returns New Bridge Configuration Server model instance. Parameters srv_data -- Pointer to a unique Bridge Configuration Server model user_data. Returns New Bridge Configuration Server model instance. ESP_BLE_MESH_MODEL_BRC_CLI(cli_data) Define a new Bridge Configuration Client model. Note If supported, the model shall be supported by a primary element and shall not be supported by any secondary elements. Parameters cli_data -- Pointer to a unique Bridge Configuration Client model user_data. cli_data -- Pointer to a unique Bridge Configuration Client model user_data. cli_data -- Pointer to a unique Bridge Configuration Client model user_data. Returns New Bridge Configuration Client model instance. Parameters cli_data -- Pointer to a unique Bridge Configuration Client model user_data. Returns New Bridge Configuration Client model instance. Type Definitions typedef void (*esp_ble_mesh_brc_client_cb_t)(esp_ble_mesh_brc_client_cb_event_t event, esp_ble_mesh_brc_client_cb_param_t *param) Bluetooth Mesh Bridge Configuration client and server model functions. Bridge Configuration Client model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter typedef void (*esp_ble_mesh_brc_server_cb_t)(esp_ble_mesh_brc_server_cb_event_t event, esp_ble_mesh_brc_server_cb_param_t *param) Bridge Configuration Server model callback function type. Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter Enumerations enum esp_ble_mesh_brc_client_cb_event_t This enum value is the event of Bridge Configuration Client model Values: enumerator ESP_BLE_MESH_BRC_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_BRC_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_BRC_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_BRC_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_BRC_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_BRC_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_BRC_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_BRC_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_BRC_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_BRC_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_BRC_CLIENT_SEND_COMP_EVT Mesh Private Beacon Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_prb_model_api.h This header file can be included with: #include "esp_ble_mesh_prb_model_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_prb_client_callback(esp_ble_mesh_prb_client_cb_t callback) Register BLE Mesh Private Beacon Client Model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_register_prb_server_callback(esp_ble_mesh_prb_server_cb_t callback) Register BLE Mesh Private Beacon Server Model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_prb_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_prb_client_msg_t *msg) Get/Set the value of Private Beacon Server Model states using the corresponding messages of Private Beacon Client Model. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Mesh Private Beacon Client message. params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Mesh Private Beacon Client message. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Mesh Private Beacon Client message. Returns ESP_OK on success or error code otherwise. Unions union esp_ble_mesh_prb_client_msg_t #include <esp_ble_mesh_prb_model_api.h> Mesh Private Beacon Client model message union. Public Members esp_ble_mesh_priv_beacon_set_t priv_beacon_set ESP_BLE_MESH_MODEL_OP_PRIV_BEACON_SET. esp_ble_mesh_priv_beacon_set_t priv_beacon_set ESP_BLE_MESH_MODEL_OP_PRIV_BEACON_SET. esp_ble_mesh_priv_gatt_proxy_set_t priv_gatt_proxy_set ESP_BLE_MESH_MODEL_OP_PRIV_GATT_PROXY_SET. esp_ble_mesh_priv_gatt_proxy_set_t priv_gatt_proxy_set ESP_BLE_MESH_MODEL_OP_PRIV_GATT_PROXY_SET. esp_ble_mesh_priv_node_id_get_t priv_node_id_get ESP_BLE_MESH_MODEL_OP_PRIV_NODE_IDENTITY_GET. esp_ble_mesh_priv_node_id_get_t priv_node_id_get ESP_BLE_MESH_MODEL_OP_PRIV_NODE_IDENTITY_GET. esp_ble_mesh_priv_node_id_set_t priv_node_id_set ESP_BLE_MESH_MODEL_OP_PRIV_NODE_IDENTITY_SET. esp_ble_mesh_priv_node_id_set_t priv_node_id_set ESP_BLE_MESH_MODEL_OP_PRIV_NODE_IDENTITY_SET. esp_ble_mesh_priv_beacon_set_t priv_beacon_set union esp_ble_mesh_prb_client_recv_cb_t #include <esp_ble_mesh_prb_model_api.h> Private Beacon Client Model received message union. Public Members esp_ble_mesh_priv_beacon_status_cb_t priv_beacon_status The private beacon status value esp_ble_mesh_priv_beacon_status_cb_t priv_beacon_status The private beacon status value esp_ble_mesh_priv_gatt_proxy_status_cb_t priv_gatt_proxy_status The private gatt proxy status value esp_ble_mesh_priv_gatt_proxy_status_cb_t priv_gatt_proxy_status The private gatt proxy status value esp_ble_mesh_priv_node_identity_status_cb_t priv_node_id_status The private node identity status value esp_ble_mesh_priv_node_identity_status_cb_t priv_node_id_status The private node identity status value esp_ble_mesh_priv_beacon_status_cb_t priv_beacon_status union esp_ble_mesh_prb_server_state_change_t #include <esp_ble_mesh_prb_model_api.h> Mesh Private Beacon Server model state change value union. Public Members esp_ble_mesh_state_change_priv_beacon_set_t priv_beacon_set The recv_op in ctx can be used to decide which state is changed. Private Beacon Set esp_ble_mesh_state_change_priv_beacon_set_t priv_beacon_set The recv_op in ctx can be used to decide which state is changed. Private Beacon Set esp_ble_mesh_state_change_priv_gatt_proxy_set_t priv_gatt_proxy_set Private GATT Proxy Set esp_ble_mesh_state_change_priv_gatt_proxy_set_t priv_gatt_proxy_set Private GATT Proxy Set esp_ble_mesh_state_change_priv_node_id_set_t priv_node_id_set Private Node Identity Set esp_ble_mesh_state_change_priv_node_id_set_t priv_node_id_set Private Node Identity Set esp_ble_mesh_state_change_priv_beacon_set_t priv_beacon_set union esp_ble_mesh_prb_server_cb_value_t #include <esp_ble_mesh_prb_model_api.h> Private Beacon Server model callback value union. Public Members esp_ble_mesh_prb_server_state_change_t state_change ESP_BLE_MESH_PRB_SERVER_STATE_CHANGE_EVT esp_ble_mesh_prb_server_state_change_t state_change ESP_BLE_MESH_PRB_SERVER_STATE_CHANGE_EVT esp_ble_mesh_prb_server_state_change_t state_change Structures struct esp_ble_mesh_prb_srv_t Private Beacon Server Model context Public Members esp_ble_mesh_model_t *model Pointer to Private Beacon Server Model esp_ble_mesh_model_t *model Pointer to Private Beacon Server Model uint8_t private_beacon Value of Private Beacon state uint8_t private_beacon Value of Private Beacon state uint8_t random_update_interval Value of Random Update Interval Steps state uint8_t random_update_interval Value of Random Update Interval Steps state uint8_t private_gatt_proxy Value of Private GATT Proxy state uint8_t private_gatt_proxy Value of Private GATT Proxy state struct k_delayed_work update_timer Timer for update the random field of private beacon struct k_delayed_work update_timer Timer for update the random field of private beacon esp_ble_mesh_model_t *model struct esp_ble_mesh_priv_beacon_set_t Parameter of private Beacon Set struct esp_ble_mesh_priv_gatt_proxy_set_t Parameter of Private GATT Proxy Set Public Members uint8_t private_gatt_proxy New Private GATT Proxy state uint8_t private_gatt_proxy New Private GATT Proxy state uint8_t private_gatt_proxy struct esp_ble_mesh_priv_node_id_get_t Parameter of Private node identity Get Public Members uint16_t net_idx Index of the NetKey uint16_t net_idx Index of the NetKey uint16_t net_idx struct esp_ble_mesh_priv_node_id_set_t Parameter of Private node identity Set struct esp_ble_mesh_priv_beacon_status_cb_t Parameter of Private Beacon Status struct esp_ble_mesh_priv_gatt_proxy_status_cb_t Parameter of Private GATT Proxy Status Public Members uint8_t private_gatt_proxy Private GATT Proxy state uint8_t private_gatt_proxy Private GATT Proxy state uint8_t private_gatt_proxy struct esp_ble_mesh_priv_node_identity_status_cb_t Parameters of Private Node Identity Status struct esp_ble_mesh_prb_client_send_cb_t Result of sending Bridge Configuration Client messages struct esp_ble_mesh_prb_client_cb_param_t Mesh Private Beacon Client Model callback parameters Public Members esp_ble_mesh_client_common_param_t *params The client common parameters. esp_ble_mesh_client_common_param_t *params The client common parameters. esp_ble_mesh_prb_client_send_cb_t send Result of sending a message esp_ble_mesh_prb_client_send_cb_t send Result of sending a message esp_ble_mesh_prb_client_recv_cb_t recv The private beacon message status callback values esp_ble_mesh_prb_client_recv_cb_t recv The private beacon message status callback values union esp_ble_mesh_prb_client_cb_param_t::[anonymous] [anonymous] Union of Private Beacon Client callback union esp_ble_mesh_prb_client_cb_param_t::[anonymous] [anonymous] Union of Private Beacon Client callback esp_ble_mesh_client_common_param_t *params struct esp_ble_mesh_state_change_priv_beacon_set_t Mesh Private Beacon Server model related context. Parameters of Private Beacon Set. struct esp_ble_mesh_state_change_priv_gatt_proxy_set_t Parameters of Private GATT Proxy Set. Public Members uint8_t private_gatt_proxy Private GATT Proxy state uint8_t private_gatt_proxy Private GATT Proxy state uint8_t private_gatt_proxy struct esp_ble_mesh_state_change_priv_node_id_set_t Parameters of Private Node Identity Set. struct esp_ble_mesh_prb_server_cb_param_t Private Beacon Server model callback parameters Public Members esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_prb_server_cb_value_t value Value of the received private beacon messages esp_ble_mesh_prb_server_cb_value_t value Value of the received private beacon messages esp_ble_mesh_model_t *model Macros ESP_BLE_MESH_MODEL_OP_PRIV_BEACON_GET ESP_BLE_MESH_MODEL_OP_PRIV_BEACON_SET ESP_BLE_MESH_MODEL_OP_PRIV_BEACON_STATUS ESP_BLE_MESH_MODEL_OP_PRIV_GATT_PROXY_GET ESP_BLE_MESH_MODEL_OP_PRIV_GATT_PROXY_SET ESP_BLE_MESH_MODEL_OP_PRIV_GATT_PROXY_STATUS ESP_BLE_MESH_MODEL_OP_PRIV_NODE_IDENTITY_GET ESP_BLE_MESH_MODEL_OP_PRIV_NODE_IDENTITY_SET ESP_BLE_MESH_MODEL_OP_PRIV_NODE_IDENTITY_STATUS ESP_BLE_MESH_MODEL_PRB_SRV(srv_data) Define a new Private Beacon Server Model. Note The Private Beacon Server Model can only be included by a Primary Element. Parameters srv_data -- Pointer to a unique Private Beacon Server Model user_data. srv_data -- Pointer to a unique Private Beacon Server Model user_data. srv_data -- Pointer to a unique Private Beacon Server Model user_data. Returns New Private Beacon Server Model instance. Parameters srv_data -- Pointer to a unique Private Beacon Server Model user_data. Returns New Private Beacon Server Model instance. ESP_BLE_MESH_MODEL_PRB_CLI(cli_data) Define a new Private Beacon Client Model. Note The Private Beacon Client Model can only be included by a Primary Element. Parameters cli_data -- Pointer to a unique struct esp_ble_mesh_client_t. cli_data -- Pointer to a unique struct esp_ble_mesh_client_t. cli_data -- Pointer to a unique struct esp_ble_mesh_client_t. Returns New Private Beacon Client Model instance. Parameters cli_data -- Pointer to a unique struct esp_ble_mesh_client_t. Returns New Private Beacon Client Model instance. Type Definitions typedef void (*esp_ble_mesh_prb_client_cb_t)(esp_ble_mesh_prb_client_cb_event_t event, esp_ble_mesh_prb_client_cb_param_t *param) Bluetooth Mesh Private Beacon Client and Server Model functions. Private Beacon Client Model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter typedef void (*esp_ble_mesh_prb_server_cb_t)(esp_ble_mesh_prb_server_cb_event_t event, esp_ble_mesh_prb_server_cb_param_t *param) Private Beacon Server Model callback function type. Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter Enumerations enum esp_ble_mesh_prb_client_cb_event_t This enum value is the event of Private Beacon Client Model Values: enumerator ESP_BLE_MESH_PRB_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_PRB_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_PRB_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_PRB_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_PRB_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_PRB_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_PRB_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_PRB_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_PRB_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_PRB_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_PRB_CLIENT_SEND_COMP_EVT On-Demand Private Proxy Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_odp_model_api.h This header file can be included with: #include "esp_ble_mesh_odp_model_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_odp_client_callback(esp_ble_mesh_odp_client_cb_t callback) Register BLE Mesh On-Demand Private Proxy Config Client model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_odp_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_odp_client_msg_t *msg) Get the value of On-Demand Private Proxy Config Server model state with the corresponding get message. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to On-Demand Private Proxy Config Client message. params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to On-Demand Private Proxy Config Client message. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to On-Demand Private Proxy Config Client message. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_register_odp_server_callback(esp_ble_mesh_odp_server_cb_t callback) Register BLE Mesh On-Demand Private Proxy Config Server model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Unions union esp_ble_mesh_odp_client_msg_t #include <esp_ble_mesh_odp_model_api.h> On-Demand Private Proxy Client model message union. Public Members esp_ble_mesh_od_priv_proxy_set_t od_priv_proxy_set For ESP_BLE_MESH_MODEL_OP_OD_PRIV_PROXY_SET esp_ble_mesh_od_priv_proxy_set_t od_priv_proxy_set For ESP_BLE_MESH_MODEL_OP_OD_PRIV_PROXY_SET esp_ble_mesh_od_priv_proxy_set_t od_priv_proxy_set union esp_ble_mesh_odp_client_recv_cb_t #include <esp_ble_mesh_odp_model_api.h> On-Demand Private Proxy Client model received message union. Public Members esp_ble_mesh_od_priv_proxy_status_t od_priv_proxy_status For ESP_BLE_MESH_MODEL_OP_OD_PRIV_PROXY_STATUS esp_ble_mesh_od_priv_proxy_status_t od_priv_proxy_status For ESP_BLE_MESH_MODEL_OP_OD_PRIV_PROXY_STATUS esp_ble_mesh_od_priv_proxy_status_t od_priv_proxy_status union esp_ble_mesh_odp_server_state_change_t #include <esp_ble_mesh_odp_model_api.h> On-Demand Private Proxy Config Server model related context. On-Demand Private Proxy Config Server model state change value union union esp_ble_mesh_odp_server_cb_value_t #include <esp_ble_mesh_odp_model_api.h> On-Demand Private Proxy Config Server model callback value union. Public Members esp_ble_mesh_odp_server_state_change_t state_change For ESP_BLE_MESH_ODP_SERVER_STATE_CHANGE_EVT esp_ble_mesh_odp_server_state_change_t state_change For ESP_BLE_MESH_ODP_SERVER_STATE_CHANGE_EVT esp_ble_mesh_odp_server_state_change_t state_change Structures struct esp_ble_mesh_odp_srv_t On-Demand Private Proxy Config Server model context Public Members esp_ble_mesh_model_t *model Pointer to On-Demand Private Proxy Config Server model esp_ble_mesh_model_t *model Pointer to On-Demand Private Proxy Config Server model uint8_t on_demand_private_gatt_proxy Duration in seconds of the interval during which advertising with Private Network Identity type is enabled after receiving a Solicitation PDU or after a client disconnect. Note: Binding with the Private GATT Proxy state. uint8_t on_demand_private_gatt_proxy Duration in seconds of the interval during which advertising with Private Network Identity type is enabled after receiving a Solicitation PDU or after a client disconnect. Note: Binding with the Private GATT Proxy state. esp_ble_mesh_model_t *model struct esp_ble_mesh_od_priv_proxy_set_t Parameter of On-Demand Private Proxy Set Public Members uint8_t gatt_proxy On-Demand Private GATT Proxy uint8_t gatt_proxy On-Demand Private GATT Proxy uint8_t gatt_proxy struct esp_ble_mesh_od_priv_proxy_status_t Parameter of On-Demand Private Proxy Status Public Members uint8_t gatt_proxy On-Demand Private GATT Proxy uint8_t gatt_proxy On-Demand Private GATT Proxy uint8_t gatt_proxy struct esp_ble_mesh_odp_client_send_cb_t Result of sending On-Demand Private Proxy Client messages struct esp_ble_mesh_odp_client_cb_param_t On-Demand Private Proxy Config Client model callback parameters Public Members esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events esp_ble_mesh_odp_client_send_cb_t send Result of sending a message esp_ble_mesh_odp_client_send_cb_t send Result of sending a message esp_ble_mesh_odp_client_recv_cb_t recv Parameters of received status message esp_ble_mesh_odp_client_recv_cb_t recv Parameters of received status message union esp_ble_mesh_odp_client_cb_param_t::[anonymous] [anonymous] Union of ODP Client callback union esp_ble_mesh_odp_client_cb_param_t::[anonymous] [anonymous] Union of ODP Client callback esp_ble_mesh_client_common_param_t *params struct esp_ble_mesh_odp_server_cb_param_t On-Demand Private Proxy Config Server model callback parameters Public Members esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_odp_server_cb_value_t value Value of the received configuration messages esp_ble_mesh_odp_server_cb_value_t value Value of the received configuration messages esp_ble_mesh_model_t *model Macros ESP_BLE_MESH_MODEL_OP_OD_PRIV_PROXY_GET ESP_BLE_MESH_MODEL_OP_OD_PRIV_PROXY_SET ESP_BLE_MESH_MODEL_OP_OD_PRIV_PROXY_STATUS ESP_BLE_MESH_MODEL_ODP_SRV(srv_data) Define a new On-Demand Private Proxy Config Server model. Note The On-Demand Private Proxy Server model is used to represent the ability to enable advertising with Private Network Identity type of a node. This model extends the Mesh Private Beacon Server model. When this model is present on an element, the corresponding Solicitation PDU RPL Configuration Server model shall also be present. The model shall be supported by a primary element and shall not be supported by any secondary elements. Parameters srv_data -- Pointer to a unique On-Demand Private Proxy Config Server model user_data. srv_data -- Pointer to a unique On-Demand Private Proxy Config Server model user_data. srv_data -- Pointer to a unique On-Demand Private Proxy Config Server model user_data. Returns New On-Demand Private Proxy Config Server model instance. Parameters srv_data -- Pointer to a unique On-Demand Private Proxy Config Server model user_data. Returns New On-Demand Private Proxy Config Server model instance. ESP_BLE_MESH_MODEL_ODP_CLI(cli_data) Define a new On-Demand Private Proxy Config Client model. Note The model shall be supported by a primary element and shall not be supported by any secondary elements. Parameters cli_data -- Pointer to a unique On-Demand Private Proxy Config Client model user_data. cli_data -- Pointer to a unique On-Demand Private Proxy Config Client model user_data. cli_data -- Pointer to a unique On-Demand Private Proxy Config Client model user_data. Returns New On-Demand Private Proxy Config Client model instance. Parameters cli_data -- Pointer to a unique On-Demand Private Proxy Config Client model user_data. Returns New On-Demand Private Proxy Config Client model instance. Type Definitions typedef void (*esp_ble_mesh_odp_client_cb_t)(esp_ble_mesh_odp_client_cb_event_t event, esp_ble_mesh_odp_client_cb_param_t *param) Bluetooth Mesh On-Demand Private Proxy Config client and server model functions. On-Demand Private Proxy Config Client model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter typedef void (*esp_ble_mesh_odp_server_cb_t)(esp_ble_mesh_odp_server_cb_event_t event, esp_ble_mesh_odp_server_cb_param_t *param) On-Demand Private Proxy Config Server model callback function type. Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter Enumerations enum esp_ble_mesh_odp_client_cb_event_t This enum value is the event of On-Demand Private Proxy Config Client model Values: enumerator ESP_BLE_MESH_ODP_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_ODP_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_ODP_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_ODP_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_ODP_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_ODP_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_ODP_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_ODP_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_ODP_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_ODP_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_ODP_CLIENT_SEND_COMP_EVT SAR Configuration Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_sar_model_api.h This header file can be included with: #include "esp_ble_mesh_sar_model_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_sar_client_callback(esp_ble_mesh_sar_client_cb_t callback) Register BLE Mesh SAR Configuration Client model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_sar_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_sar_client_msg_t *msg) Get the value of SAR Configuration Server model state with the corresponding get message. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to SAR Configuration Client message. params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to SAR Configuration Client message. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to SAR Configuration Client message. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_register_sar_server_callback(esp_ble_mesh_sar_server_cb_t callback) Register BLE Mesh SAR Configuration Server model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Unions union esp_ble_mesh_sar_client_msg_t #include <esp_ble_mesh_sar_model_api.h> SAR Configuration Client model message union. Public Members esp_ble_mesh_sar_transmitter_set_t sar_transmitter_set For ESP_BLE_MESH_MODEL_OP_SAR_TRANSMITTER_SET esp_ble_mesh_sar_transmitter_set_t sar_transmitter_set For ESP_BLE_MESH_MODEL_OP_SAR_TRANSMITTER_SET esp_ble_mesh_sar_receiver_set_t sar_receiver_set For ESP_BLE_MESH_MODEL_OP_SAR_RECEIVER_SET esp_ble_mesh_sar_receiver_set_t sar_receiver_set For ESP_BLE_MESH_MODEL_OP_SAR_RECEIVER_SET esp_ble_mesh_sar_transmitter_set_t sar_transmitter_set union esp_ble_mesh_sar_client_recv_cb_t #include <esp_ble_mesh_sar_model_api.h> SAR Configuration Client model received message union. Public Members esp_ble_mesh_sar_transmitter_status_t sar_transmitter_status For ESP_BLE_MESH_MODEL_OP_SAR_TRANSMITTER_STATUS esp_ble_mesh_sar_transmitter_status_t sar_transmitter_status For ESP_BLE_MESH_MODEL_OP_SAR_TRANSMITTER_STATUS esp_ble_mesh_sar_receiver_status_t sar_receiver_status For ESP_BLE_MESH_MODEL_OP_SAR_RECEIVE_STATUS esp_ble_mesh_sar_receiver_status_t sar_receiver_status For ESP_BLE_MESH_MODEL_OP_SAR_RECEIVE_STATUS esp_ble_mesh_sar_transmitter_status_t sar_transmitter_status union esp_ble_mesh_sar_server_state_change_t #include <esp_ble_mesh_sar_model_api.h> SAR Configuration Server model related context. SAR Configuration Server model state change value union union esp_ble_mesh_sar_server_cb_value_t #include <esp_ble_mesh_sar_model_api.h> SAR Configuration Server model callback value union. Public Members esp_ble_mesh_sar_server_state_change_t state_change For ESP_BLE_MESH_SAR_SERVER_STATE_CHANGE_EVT esp_ble_mesh_sar_server_state_change_t state_change For ESP_BLE_MESH_SAR_SERVER_STATE_CHANGE_EVT esp_ble_mesh_sar_server_state_change_t state_change Structures struct esp_ble_mesh_sar_srv_t SAR Configuration Server model context Public Members esp_ble_mesh_model_t *model Pointer to SAR Configuration Server model esp_ble_mesh_model_t *model Pointer to SAR Configuration Server model esp_ble_mesh_model_t *model struct esp_ble_mesh_sar_transmitter_set_t Parameters of SAR Transmitter Set Public Members uint8_t sar_segment_interval_step SAR Segment Interval Step state value uint8_t sar_segment_interval_step SAR Segment Interval Step state value uint8_t sar_unicast_retrans_count SAR Unicast Retransmissions Count state uint8_t sar_unicast_retrans_count SAR Unicast Retransmissions Count state uint8_t sar_unicast_retrans_without_progress_count SAR Unicast Retransmissions Without Progress Count state uint8_t sar_unicast_retrans_without_progress_count SAR Unicast Retransmissions Without Progress Count state uint8_t sar_unicast_retrans_interval_step SAR Unicast Retransmissions Interval Step state uint8_t sar_unicast_retrans_interval_step SAR Unicast Retransmissions Interval Step state uint8_t sar_unicast_retrans_interval_increment SAR Unicast Retransmissions Interval Increment state uint8_t sar_unicast_retrans_interval_increment SAR Unicast Retransmissions Interval Increment state uint8_t sar_multicast_retrans_count SAR Multicast Retransmissions Count state uint8_t sar_multicast_retrans_count SAR Multicast Retransmissions Count state uint8_t sar_multicast_retrans_interval_step SAR Multicast Retransmissions Interval state uint8_t sar_multicast_retrans_interval_step SAR Multicast Retransmissions Interval state uint8_t sar_segment_interval_step struct esp_ble_mesh_sar_receiver_set_t Parameters of SAR Receiver Set Public Members uint8_t sar_segments_threshold SAR Segments Threshold state uint8_t sar_segments_threshold SAR Segments Threshold state uint8_t sar_ack_delay_increment SAR Acknowledgment Delay Increment state uint8_t sar_ack_delay_increment SAR Acknowledgment Delay Increment state uint8_t sar_discard_timeout SAR Discard Timeout state uint8_t sar_discard_timeout SAR Discard Timeout state uint8_t sar_receiver_segment_interval_step SAR Receiver Segment Interval Step state uint8_t sar_receiver_segment_interval_step SAR Receiver Segment Interval Step state uint8_t sar_ack_retrans_count SAR Acknowledgment Retransmissions Count state uint8_t sar_ack_retrans_count SAR Acknowledgment Retransmissions Count state uint8_t sar_segments_threshold struct esp_ble_mesh_sar_transmitter_status_t Parameters of SAR Transmitter Status Public Members uint8_t sar_segment_interval_step SAR Segment Interval Step state value uint8_t sar_segment_interval_step SAR Segment Interval Step state value uint8_t sar_unicast_retrans_count SAR Unicast Retransmissions Count state uint8_t sar_unicast_retrans_count SAR Unicast Retransmissions Count state uint8_t sar_unicast_retrans_without_progress_count SAR Unicast Retransmissions Without Progress Count state uint8_t sar_unicast_retrans_without_progress_count SAR Unicast Retransmissions Without Progress Count state uint8_t sar_unicast_retrans_interval_step SAR Unicast Retransmissions Interval Step state uint8_t sar_unicast_retrans_interval_step SAR Unicast Retransmissions Interval Step state uint8_t sar_unicast_retrans_interval_increment SAR Unicast Retransmissions Interval Increment state uint8_t sar_unicast_retrans_interval_increment SAR Unicast Retransmissions Interval Increment state uint8_t sar_multicast_retrans_count SAR Multicast Retransmissions Count state uint8_t sar_multicast_retrans_count SAR Multicast Retransmissions Count state uint8_t sar_multicast_retrans_interval_step SAR Multicast Retransmissions Interval state uint8_t sar_multicast_retrans_interval_step SAR Multicast Retransmissions Interval state uint8_t sar_segment_interval_step struct esp_ble_mesh_sar_receiver_status_t Parameters of SAR Receiver Status Public Members uint8_t sar_segments_threshold SAR Segments Threshold state uint8_t sar_segments_threshold SAR Segments Threshold state uint8_t sar_ack_delay_increment SAR Acknowledgment Delay Increment state uint8_t sar_ack_delay_increment SAR Acknowledgment Delay Increment state uint8_t sar_discard_timeout SAR Discard Timeout state uint8_t sar_discard_timeout SAR Discard Timeout state uint8_t sar_receiver_segment_interval_step SAR Receiver Segment Interval Step state uint8_t sar_receiver_segment_interval_step SAR Receiver Segment Interval Step state uint8_t sar_ack_retrans_count SAR Acknowledgment Retransmissions Count state uint8_t sar_ack_retrans_count SAR Acknowledgment Retransmissions Count state uint8_t sar_segments_threshold struct esp_ble_mesh_sar_client_send_cb_t Result of sending SAR Configuration Client messages struct esp_ble_mesh_sar_client_cb_param_t SAR Configuration Client model callback parameters Public Members esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events. esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events. esp_ble_mesh_sar_client_send_cb_t send Result of sending a message esp_ble_mesh_sar_client_send_cb_t send Result of sending a message esp_ble_mesh_sar_client_recv_cb_t recv Parameters of received status message esp_ble_mesh_sar_client_recv_cb_t recv Parameters of received status message union esp_ble_mesh_sar_client_cb_param_t::[anonymous] [anonymous] Union of SAR Client callback union esp_ble_mesh_sar_client_cb_param_t::[anonymous] [anonymous] Union of SAR Client callback esp_ble_mesh_client_common_param_t *params struct esp_ble_mesh_sar_server_cb_param_t SAR Configuration Server model callback parameters Public Members esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_sar_server_cb_value_t value Value of the received configuration messages esp_ble_mesh_sar_server_cb_value_t value Value of the received configuration messages esp_ble_mesh_model_t *model Macros ESP_BLE_MESH_MODEL_OP_SAR_TRANSMITTER_GET ESP_BLE_MESH_MODEL_OP_SAR_TRANSMITTER_SET ESP_BLE_MESH_MODEL_OP_SAR_TRANSMITTER_STATUS ESP_BLE_MESH_MODEL_OP_SAR_RECEIVER_GET ESP_BLE_MESH_MODEL_OP_SAR_RECEIVER_SET ESP_BLE_MESH_MODEL_OP_SAR_RECEIVER_STATUS ESP_BLE_MESH_MODEL_SAR_SRV(srv_data) Define a new SAR Configuration Server model. Note If supported, the model shall be supported by a primary element and shall not be supported by any secondary elements. Parameters srv_data -- Pointer to a unique SAR Configuration Server model user_data. srv_data -- Pointer to a unique SAR Configuration Server model user_data. srv_data -- Pointer to a unique SAR Configuration Server model user_data. Returns New SAR Configuration Server model instance. Parameters srv_data -- Pointer to a unique SAR Configuration Server model user_data. Returns New SAR Configuration Server model instance. ESP_BLE_MESH_MODEL_SAR_CLI(cli_data) Define a new SAR Configuration Client model. Note If supported, the model shall be supported by the primary element and shall not be supported by any secondary elements. Parameters cli_data -- Pointer to a unique SAR Configuration Client model user_data. cli_data -- Pointer to a unique SAR Configuration Client model user_data. cli_data -- Pointer to a unique SAR Configuration Client model user_data. Returns New SAR Configuration Client model instance. Parameters cli_data -- Pointer to a unique SAR Configuration Client model user_data. Returns New SAR Configuration Client model instance. Type Definitions typedef void (*esp_ble_mesh_sar_client_cb_t)(esp_ble_mesh_sar_client_cb_event_t event, esp_ble_mesh_sar_client_cb_param_t *param) Bluetooth Mesh SAR Configuration client and server model functions. SAR Configuration Client model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter typedef void (*esp_ble_mesh_sar_server_cb_t)(esp_ble_mesh_sar_server_cb_event_t event, esp_ble_mesh_sar_server_cb_param_t *param) SAR Configuration Server model callback function type. Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter Enumerations enum esp_ble_mesh_sar_client_cb_event_t This enum value is the event of SAR Configuration Client model Values: enumerator ESP_BLE_MESH_SAR_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_SAR_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_SAR_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_SAR_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_SAR_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_SAR_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_SAR_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_SAR_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_SAR_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_SAR_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_SAR_CLIENT_SEND_COMP_EVT Solicitation PDU RPL Configuration Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_srpl_model_api.h This header file can be included with: #include "esp_ble_mesh_srpl_model_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_srpl_client_callback(esp_ble_mesh_srpl_client_cb_t callback) Register BLE Mesh Solicitation PDU RPL Configuration Client model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_srpl_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_srpl_client_msg_t *msg) Set the value of Solicitation PDU RPL Configuration Server model state with the corresponding set message. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Solicitation PDU RPL Configuration Client message. params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Solicitation PDU RPL Configuration Client message. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Solicitation PDU RPL Configuration Client message. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_register_srpl_server_callback(esp_ble_mesh_srpl_server_cb_t callback) Register BLE Mesh Solicitation PDU RPL Configuration Server model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Unions union esp_ble_mesh_srpl_client_msg_t #include <esp_ble_mesh_srpl_model_api.h> Solicitation PDU RPL Configuration Client model message union. Public Members esp_ble_mesh_srpl_items_clear_t srpl_items_clear For ESP_BLE_MESH_MODEL_OP_SRPL_ITEMS_CLEAR esp_ble_mesh_srpl_items_clear_t srpl_items_clear For ESP_BLE_MESH_MODEL_OP_SRPL_ITEMS_CLEAR esp_ble_mesh_srpl_items_clear_t srpl_items_clear union esp_ble_mesh_srpl_client_recv_cb_t #include <esp_ble_mesh_srpl_model_api.h> Solicitation PDU RPL Configuration Client model received message union. Public Members esp_ble_mesh_srpl_items_status_t srpl_items_status For ESP_BLE_MESH_MODEL_OP_SRPL_ITEMS_STATUS esp_ble_mesh_srpl_items_status_t srpl_items_status For ESP_BLE_MESH_MODEL_OP_SRPL_ITEMS_STATUS esp_ble_mesh_srpl_items_status_t srpl_items_status union esp_ble_mesh_srpl_server_state_change_t #include <esp_ble_mesh_srpl_model_api.h> Solicitation PDU RPL Configuration Server model related context. Solicitation PDU RPL Configuration Server model state change value union Public Members uint8_t dummy Currently this event is not used. uint8_t dummy Currently this event is not used. uint8_t dummy union esp_ble_mesh_srpl_server_cb_value_t #include <esp_ble_mesh_srpl_model_api.h> Solicitation PDU RPL Configuration Server model callback value union. Public Members esp_ble_mesh_srpl_server_state_change_t state_change ESP_BLE_MESH_SRPL_SERVER_STATE_CHANGE_EVT esp_ble_mesh_srpl_server_state_change_t state_change ESP_BLE_MESH_SRPL_SERVER_STATE_CHANGE_EVT esp_ble_mesh_srpl_server_state_change_t state_change Structures struct esp_ble_mesh_srpl_srv_t Solicitation PDU RPL Configuration Server model context Public Members esp_ble_mesh_model_t *model Pointer to Solicitation PDU RPL Configuration Server model esp_ble_mesh_model_t *model Pointer to Solicitation PDU RPL Configuration Server model esp_ble_mesh_model_t *model struct esp_ble_mesh_srpl_items_clear_t Parameter of Solicitation PDU RPL Items Clear Public Members esp_ble_mesh_uar_t addr_range Unicast address range esp_ble_mesh_uar_t addr_range Unicast address range esp_ble_mesh_uar_t addr_range struct esp_ble_mesh_srpl_items_status_t Parameter of Solicitation PDU RPL Items Clear Status Public Members esp_ble_mesh_uar_t addr_range Unicast address range esp_ble_mesh_uar_t addr_range Unicast address range esp_ble_mesh_uar_t addr_range struct esp_ble_mesh_srpl_client_send_cb_t Result of sending Solicitation PDU RPL Configuration Client messages struct esp_ble_mesh_srpl_client_cb_param_t Solicitation PDU RPL Configuration Client model callback parameters Public Members esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events. esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events. esp_ble_mesh_srpl_client_send_cb_t send Result of sending a message esp_ble_mesh_srpl_client_send_cb_t send Result of sending a message esp_ble_mesh_srpl_client_recv_cb_t recv Parameters of received status message esp_ble_mesh_srpl_client_recv_cb_t recv Parameters of received status message union esp_ble_mesh_srpl_client_cb_param_t::[anonymous] [anonymous] Union of SRPL Client callback union esp_ble_mesh_srpl_client_cb_param_t::[anonymous] [anonymous] Union of SRPL Client callback esp_ble_mesh_client_common_param_t *params struct esp_ble_mesh_srpl_server_cb_param_t Solicitation PDU RPL Configuration Server model callback parameters Public Members esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_srpl_server_cb_value_t value Value of the received configuration messages esp_ble_mesh_srpl_server_cb_value_t value Value of the received configuration messages esp_ble_mesh_model_t *model Macros ESP_BLE_MESH_MODEL_OP_SRPL_ITEMS_CLEAR ESP_BLE_MESH_MODEL_OP_SRPL_ITEMS_CLEAR_UNACK ESP_BLE_MESH_MODEL_OP_SRPL_ITEMS_STATUS ESP_BLE_MESH_MODEL_SRPL_SRV(srv_data) Define a new Solicitation PDU RPL Configuration Server model. Note The Solicitation PDU RPL Configuration Server model extends the On-Demand Private Proxy Server model. If the model is supported, the model shall be supported by a primary element and shall not be supported by any secondary elements. Parameters srv_data -- Pointer to a unique Solicitation PDU RPL Configuration Server model user_data. srv_data -- Pointer to a unique Solicitation PDU RPL Configuration Server model user_data. srv_data -- Pointer to a unique Solicitation PDU RPL Configuration Server model user_data. Returns New Solicitation PDU RPL Configuration Server model instance. Parameters srv_data -- Pointer to a unique Solicitation PDU RPL Configuration Server model user_data. Returns New Solicitation PDU RPL Configuration Server model instance. ESP_BLE_MESH_MODEL_SRPL_CLI(cli_data) Define a new Solicitation PDU RPL Configuration Client model. Note If supported, the model shall be supported by the primary element and shall not be supported by any secondary elements. Parameters cli_data -- Pointer to a unique Solicitation PDU RPL Configuration Client model user_data. cli_data -- Pointer to a unique Solicitation PDU RPL Configuration Client model user_data. cli_data -- Pointer to a unique Solicitation PDU RPL Configuration Client model user_data. Returns New Solicitation PDU RPL Configuration Client model instance. Parameters cli_data -- Pointer to a unique Solicitation PDU RPL Configuration Client model user_data. Returns New Solicitation PDU RPL Configuration Client model instance. Type Definitions typedef void (*esp_ble_mesh_srpl_client_cb_t)(esp_ble_mesh_srpl_client_cb_event_t event, esp_ble_mesh_srpl_client_cb_param_t *param) Bluetooth Mesh Solicitation PDU RPL Configuration client and server model functions. Solicitation PDU RPL Configuration Client model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter typedef void (*esp_ble_mesh_srpl_server_cb_t)(esp_ble_mesh_srpl_server_cb_event_t event, esp_ble_mesh_srpl_server_cb_param_t *param) Solicitation PDU RPL Configuration Server model callback function type. Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter Enumerations enum esp_ble_mesh_srpl_client_cb_event_t This enum value is the event of Solicitation PDU RPL Configuration Client model Values: enumerator ESP_BLE_MESH_SRPL_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_SRPL_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_SRPL_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_SRPL_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_SRPL_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_SRPL_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_SRPL_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_SRPL_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_SRPL_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_SRPL_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_SRPL_CLIENT_SEND_COMP_EVT Opcodes Aggregator Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_agg_model_api.h This header file can be included with: #include "esp_ble_mesh_agg_model_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_agg_client_callback(esp_ble_mesh_agg_client_cb_t callback) Register BLE Mesh Opcodes Aggregator Client model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_agg_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_agg_client_msg_t *msg) Set the value of Opcodes Aggregator Server model state with the corresponding set message. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Opcodes Aggregator Client message. params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Opcodes Aggregator Client message. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Opcodes Aggregator Client message. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_register_agg_server_callback(esp_ble_mesh_agg_server_cb_t callback) Register BLE Mesh Opcodes Aggregator Server model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Unions union esp_ble_mesh_agg_client_msg_t #include <esp_ble_mesh_agg_model_api.h> Opcodes Aggregator Client model message union. Public Members esp_ble_mesh_agg_sequence_t agg_sequence For ESP_BLE_MESH_MODEL_OP_AGG_SEQUENCE esp_ble_mesh_agg_sequence_t agg_sequence For ESP_BLE_MESH_MODEL_OP_AGG_SEQUENCE esp_ble_mesh_agg_sequence_t agg_sequence union esp_ble_mesh_agg_client_recv_cb_t #include <esp_ble_mesh_agg_model_api.h> Opcodes Aggregator Client model received message union. Public Members esp_ble_mesh_agg_status_t agg_status For ESP_BLE_MESH_MODEL_OP_AGG_STATUS esp_ble_mesh_agg_status_t agg_status For ESP_BLE_MESH_MODEL_OP_AGG_STATUS esp_ble_mesh_agg_status_t agg_status union esp_ble_mesh_agg_server_recv_msg_t #include <esp_ble_mesh_agg_model_api.h> Opcodes Aggregator Server model related context. Opcodes Aggregator Server model received message union Public Members esp_ble_mesh_agg_sequence_t agg_sequence For ESP_BLE_MESH_MODEL_OP_AGG_SEQUENCE esp_ble_mesh_agg_sequence_t agg_sequence For ESP_BLE_MESH_MODEL_OP_AGG_SEQUENCE esp_ble_mesh_agg_sequence_t agg_sequence Structures struct esp_ble_mesh_agg_srv_t Opcodes Aggregator Server model context Public Members esp_ble_mesh_model_t *model Pointer to Opcodes Aggregator Server model esp_ble_mesh_model_t *model Pointer to Opcodes Aggregator Server model esp_ble_mesh_model_t *model struct esp_ble_mesh_agg_item_t Parameters of Aggregator Item struct esp_ble_mesh_agg_sequence_t Parameters of Opcodes Aggregator Sequence struct esp_ble_mesh_agg_status_t Parameters of Opcodes Aggregator Status struct esp_ble_mesh_agg_client_send_cb_t Result of sending Opcodes Aggregator Client messages struct esp_ble_mesh_agg_client_cb_param_t Opcodes Aggregator Client model callback parameters Public Members esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events esp_ble_mesh_agg_client_send_cb_t send Result of sending a message esp_ble_mesh_agg_client_send_cb_t send Result of sending a message esp_ble_mesh_agg_client_recv_cb_t recv Parameters of received status message esp_ble_mesh_agg_client_recv_cb_t recv Parameters of received status message union esp_ble_mesh_agg_client_cb_param_t::[anonymous] [anonymous] Union of AGG Client callback union esp_ble_mesh_agg_client_cb_param_t::[anonymous] [anonymous] Union of AGG Client callback esp_ble_mesh_client_common_param_t *params struct esp_ble_mesh_agg_server_cb_param_t Opcodes Aggregator Server model callback parameters Public Members esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_agg_server_recv_msg_t recv Received message callback values esp_ble_mesh_agg_server_recv_msg_t recv Received message callback values union esp_ble_mesh_agg_server_cb_param_t::[anonymous] [anonymous] Union of AGG Server callback union esp_ble_mesh_agg_server_cb_param_t::[anonymous] [anonymous] Union of AGG Server callback esp_ble_mesh_model_t *model Macros ESP_BLE_MESH_MODEL_OP_AGG_SEQUENCE Defines the Opcodes Aggregator message opcode. ESP_BLE_MESH_MODEL_OP_AGG_STATUS ESP_BLE_MESH_AGG_STATUS_SUCCESS Defines the status codes for Opcodes Aggregator messages. ESP_BLE_MESH_AGG_STATUS_INVALID_ADDRESS ESP_BLE_MESH_AGG_STATUS_INVALID_MODEL ESP_BLE_MESH_AGG_STATUS_WRONG_ACCESS_KEY ESP_BLE_MESH_AGG_STATUS_WRONG_OPCODE ESP_BLE_MESH_AGG_STATUS_MSG_NOT_UNDERSTOOD ESP_BLE_MESH_AGG_ITEM_LENGTH_FORMAT_SHORT Values of the Length_Format ESP_BLE_MESH_AGG_ITEM_LENGTH_FORMAT_LONG ESP_BLE_MESH_MODEL_AGG_SRV(srv_data) Define a new Opcodes Aggregator Server model. Note If supported, the Opcodes Aggregator Server model shall be supported by a primary element. Parameters srv_data -- Pointer to a unique Opcodes Aggregator Server model user_data. srv_data -- Pointer to a unique Opcodes Aggregator Server model user_data. srv_data -- Pointer to a unique Opcodes Aggregator Server model user_data. Returns New Opcodes Aggregator Server model instance. Parameters srv_data -- Pointer to a unique Opcodes Aggregator Server model user_data. Returns New Opcodes Aggregator Server model instance. ESP_BLE_MESH_MODEL_AGG_CLI(cli_data) Define a new Opcodes Aggregator Client model. Note If supported, the model shall be supported by the primary element and shall not be supported by any secondary elements. Parameters cli_data -- Pointer to a unique Opcodes Aggregator Client model user_data. cli_data -- Pointer to a unique Opcodes Aggregator Client model user_data. cli_data -- Pointer to a unique Opcodes Aggregator Client model user_data. Returns New Opcodes Aggregator Client model instance. Parameters cli_data -- Pointer to a unique Opcodes Aggregator Client model user_data. Returns New Opcodes Aggregator Client model instance. Type Definitions typedef void (*esp_ble_mesh_agg_client_cb_t)(esp_ble_mesh_agg_client_cb_event_t event, esp_ble_mesh_agg_client_cb_param_t *param) Bluetooth Mesh Opcodes Aggregator client and server model functions. Opcodes Aggregator Client model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter typedef void (*esp_ble_mesh_agg_server_cb_t)(esp_ble_mesh_agg_server_cb_event_t event, esp_ble_mesh_agg_server_cb_param_t *param) Opcodes Aggregator Server model callback function type. Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter Enumerations enum esp_ble_mesh_agg_client_cb_event_t This enum value is the event of Opcodes Aggregator Client model Values: enumerator ESP_BLE_MESH_AGG_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_AGG_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_AGG_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_AGG_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_AGG_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_AGG_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_AGG_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_AGG_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_AGG_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_AGG_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_AGG_CLIENT_SEND_COMP_EVT Large Composition Data Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_lcd_model_api.h This header file can be included with: #include "esp_ble_mesh_lcd_model_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_register_lcd_client_callback(esp_ble_mesh_lcd_client_cb_t callback) Register BLE Mesh Large Composition Data Client model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_lcd_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_lcd_client_msg_t *msg) Get the value of Large Composition Data Server model state with the corresponding get message. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Large Composition Data Client message. params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Large Composition Data Client message. params -- [in] Pointer to BLE Mesh common client parameters. Returns ESP_OK on success or error code otherwise. Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Large Composition Data Client message. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_register_lcd_server_callback(esp_ble_mesh_lcd_server_cb_t callback) Register BLE Mesh Large Composition Data Server model callback. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Parameters callback -- [in] Pointer to the callback function. Returns ESP_OK on success or error code otherwise. Unions union esp_ble_mesh_lcd_client_msg_t #include <esp_ble_mesh_lcd_model_api.h> Large Composition Data Client model message union. Public Members esp_ble_mesh_large_comp_data_get_t large_comp_data_get For ESP_BLE_MESH_MODEL_OP_LARGE_COMP_DATA_GET esp_ble_mesh_large_comp_data_get_t large_comp_data_get For ESP_BLE_MESH_MODEL_OP_LARGE_COMP_DATA_GET esp_ble_mesh_models_metadata_get_t models_metadata_get For ESP_BLE_MESH_MODEL_OP_MODELS_METADATA_GET esp_ble_mesh_models_metadata_get_t models_metadata_get For ESP_BLE_MESH_MODEL_OP_MODELS_METADATA_GET esp_ble_mesh_large_comp_data_get_t large_comp_data_get union esp_ble_mesh_lcd_client_recv_cb_t #include <esp_ble_mesh_lcd_model_api.h> Large Composition Data Client model received message union. Public Members esp_ble_mesh_large_comp_data_status_t large_comp_data_status For ESP_BLE_MESH_MODEL_OP_LARGE_COMP_DATA_STATUS esp_ble_mesh_large_comp_data_status_t large_comp_data_status For ESP_BLE_MESH_MODEL_OP_LARGE_COMP_DATA_STATUS esp_ble_mesh_models_metadata_status_t models_metadata_status For ESP_BLE_MESH_MODEL_OP_MODELS_METADATA_STATUS esp_ble_mesh_models_metadata_status_t models_metadata_status For ESP_BLE_MESH_MODEL_OP_MODELS_METADATA_STATUS esp_ble_mesh_large_comp_data_status_t large_comp_data_status union esp_ble_mesh_lcd_server_state_change_t #include <esp_ble_mesh_lcd_model_api.h> Large Composition Data Server model related context. Large Composition Data Server model state change value union union esp_ble_mesh_lcd_server_cb_value_t #include <esp_ble_mesh_lcd_model_api.h> Large Composition Data Server model callback value union. Public Members esp_ble_mesh_lcd_server_state_change_t state_change For ESP_BLE_MESH_LCD_SERVER_STATE_CHANGE_EVT esp_ble_mesh_lcd_server_state_change_t state_change For ESP_BLE_MESH_LCD_SERVER_STATE_CHANGE_EVT esp_ble_mesh_lcd_server_state_change_t state_change Structures struct esp_ble_mesh_lcd_srv_t Large Composition Data Server model context Public Members esp_ble_mesh_model_t *model Pointer to Large Composition Data Server model esp_ble_mesh_model_t *model Pointer to Large Composition Data Server model esp_ble_mesh_model_t *model struct esp_ble_mesh_large_comp_data_get_t Parameters of Large Composition Data Get struct esp_ble_mesh_models_metadata_get_t Parameters of Models Metadata Get struct esp_ble_mesh_large_comp_data_status_t Parameters of Large Composition Data Status struct esp_ble_mesh_models_metadata_status_t Parameters of Models Metadata Data Status struct esp_ble_mesh_lcd_client_send_cb_t Result of sending Large Composition Data Client messages struct esp_ble_mesh_lcd_client_cb_param_t Large Composition Data Client model callback parameters Public Members esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events. esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events. esp_ble_mesh_lcd_client_send_cb_t send Result of sending a message esp_ble_mesh_lcd_client_send_cb_t send Result of sending a message esp_ble_mesh_lcd_client_recv_cb_t recv Parameters of received status message esp_ble_mesh_lcd_client_recv_cb_t recv Parameters of received status message union esp_ble_mesh_lcd_client_cb_param_t::[anonymous] [anonymous] Union of LCD Client callback union esp_ble_mesh_lcd_client_cb_param_t::[anonymous] [anonymous] Union of LCD Client callback esp_ble_mesh_client_common_param_t *params struct esp_ble_mesh_lcd_server_cb_param_t Large Composition Data Server model callback parameters Public Members esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_model_t *model Pointer to the server model structure esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_msg_ctx_t ctx Context of the received message esp_ble_mesh_lcd_server_cb_value_t value Value of the received configuration messages esp_ble_mesh_lcd_server_cb_value_t value Value of the received configuration messages esp_ble_mesh_model_t *model Macros ESP_BLE_MESH_MODEL_OP_LARGE_COMP_DATA_GET ESP_BLE_MESH_MODEL_OP_LARGE_COMP_DATA_STATUS ESP_BLE_MESH_MODEL_OP_MODELS_METADATA_GET ESP_BLE_MESH_MODEL_OP_MODELS_METADATA_STATUS ESP_BLE_MESH_MODEL_LCD_SRV(srv_data) Define a new Large Composition Data Server model. Note If supported, the model shall be supported by a primary element and shall not be supported by any secondary elements. Parameters srv_data -- Pointer to a unique Large Composition Data Server model user_data. srv_data -- Pointer to a unique Large Composition Data Server model user_data. srv_data -- Pointer to a unique Large Composition Data Server model user_data. Returns New Large Composition Data Server model instance. Parameters srv_data -- Pointer to a unique Large Composition Data Server model user_data. Returns New Large Composition Data Server model instance. ESP_BLE_MESH_MODEL_LCD_CLI(cli_data) Define a new Large Composition Data Client model. Note If supported, the model shall be supported by the primary element and shall not be supported by any secondary elements. Parameters cli_data -- Pointer to a unique Large Composition Data Client model user_data. cli_data -- Pointer to a unique Large Composition Data Client model user_data. cli_data -- Pointer to a unique Large Composition Data Client model user_data. Returns New Large Composition Data Client model instance. Parameters cli_data -- Pointer to a unique Large Composition Data Client model user_data. Returns New Large Composition Data Client model instance. Type Definitions typedef void (*esp_ble_mesh_lcd_client_cb_t)(esp_ble_mesh_lcd_client_cb_event_t event, esp_ble_mesh_lcd_client_cb_param_t *param) Large Composition Data client and server model functions. Large Composition Data Client model callback function type Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter typedef void (*esp_ble_mesh_lcd_server_cb_t)(esp_ble_mesh_lcd_server_cb_event_t event, esp_ble_mesh_lcd_server_cb_param_t *param) Large Composition Data Server model callback function type. Param event Event type Param param Pointer to callback parameter Param event Event type Param param Pointer to callback parameter Enumerations enum esp_ble_mesh_lcd_client_cb_event_t This enum value is the event of Large Composition Data Client model Values: enumerator ESP_BLE_MESH_LCD_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_LCD_CLIENT_SEND_COMP_EVT enumerator ESP_BLE_MESH_LCD_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_LCD_CLIENT_SEND_TIMEOUT_EVT enumerator ESP_BLE_MESH_LCD_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_LCD_CLIENT_RECV_RSP_EVT enumerator ESP_BLE_MESH_LCD_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_LCD_CLIENT_RECV_PUB_EVT enumerator ESP_BLE_MESH_LCD_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_LCD_CLIENT_EVT_MAX enumerator ESP_BLE_MESH_LCD_CLIENT_SEND_COMP_EVT Composition and Metadata Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_cm_data_api.h This header file can be included with: #include "esp_ble_mesh_cm_data_api.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_ble_mesh_comp_1_register(const esp_ble_mesh_comp_1_t *comp) Register Composition Data Page 1. Parameters comp -- [in] Pointer to Composition Data Page 1. Returns ESP_OK on success or error code otherwise. Parameters comp -- [in] Pointer to Composition Data Page 1. Returns ESP_OK on success or error code otherwise. esp_err_t esp_ble_mesh_models_metadata_register(const esp_ble_mesh_models_metadata_t *metadata, uint8_t metadata_page) Register Models Metadata Page 0 or 128. Parameters metadata -- [in] Pointer to Models Metadata Page 0 or 128. metadata_page -- [in] Models Metadata Page number, i.e. 0 or 128. metadata -- [in] Pointer to Models Metadata Page 0 or 128. metadata_page -- [in] Models Metadata Page number, i.e. 0 or 128. metadata -- [in] Pointer to Models Metadata Page 0 or 128. Returns ESP_OK on success or error code otherwise. Parameters metadata -- [in] Pointer to Models Metadata Page 0 or 128. metadata_page -- [in] Models Metadata Page number, i.e. 0 or 128. Returns ESP_OK on success or error code otherwise. Structures struct esp_ble_mesh_extended_model_item_t Format of Extended Model Item Public Members uint8_t element_offset Element address modifier, in the range -4 to 3. See above. uint8_t element_offset Element address modifier, in the range -4 to 3. See above. uint8_t model_item_idx Model Index, in the range 0 to 31 Model index, in the range 0 to 255 uint8_t model_item_idx Model Index, in the range 0 to 31 Model index, in the range 0 to 255 int8_t element_offset Element address modifier, in the range -128 to 127 int8_t element_offset Element address modifier, in the range -128 to 127 struct esp_ble_mesh_extended_model_item_t::[anonymous]::[anonymous] long_fmt Extended Model Item long format Extended Model Item long format struct esp_ble_mesh_extended_model_item_t::[anonymous]::[anonymous] long_fmt Extended Model Item long format Extended Model Item long format union esp_ble_mesh_extended_model_item_t::[anonymous] [anonymous] Union of Extended Model Item union esp_ble_mesh_extended_model_item_t::[anonymous] [anonymous] Union of Extended Model Item uint8_t element_offset struct esp_ble_mesh_model_item_t Format of Model Item Public Members uint8_t corresponding_present Corresponding_Group_ID field indicator uint8_t corresponding_present Corresponding_Group_ID field indicator uint8_t format Format of Extended_Model_Items indicator uint8_t format Format of Extended_Model_Items indicator uint8_t extended_items_count Number of Extended Model Items in the Extended_Model_Items field uint8_t extended_items_count Number of Extended Model Items in the Extended_Model_Items field uint8_t corresponding_group_id Corresponding group identifier uint8_t corresponding_group_id Corresponding group identifier esp_ble_mesh_extended_model_item_t *const extended_model_items List of Extended Model Items esp_ble_mesh_extended_model_item_t *const extended_model_items List of Extended Model Items uint8_t corresponding_present struct esp_ble_mesh_comp_1_elem_t Format of element of Composition Data Page 1 Public Members const uint8_t num_s A count of SIG Models Items in this element const uint8_t num_s A count of SIG Models Items in this element const uint8_t num_v A count of Vendor Models Items in this element const uint8_t num_v A count of Vendor Models Items in this element esp_ble_mesh_model_item_t *const model_items_s A sequence of "num_s" SIG Model Items esp_ble_mesh_model_item_t *const model_items_s A sequence of "num_s" SIG Model Items esp_ble_mesh_model_item_t *const model_items_v A sequence of "num_v" Vendor Model Items esp_ble_mesh_model_item_t *const model_items_v A sequence of "num_v" Vendor Model Items const uint8_t num_s struct esp_ble_mesh_comp_1_t Format of Composition Data Page 1 Public Members size_t element_count Element count size_t element_count Element count esp_ble_mesh_comp_1_elem_t *elements A sequence of element descriptions esp_ble_mesh_comp_1_elem_t *elements A sequence of element descriptions size_t element_count struct esp_ble_mesh_metadata_entry_t Format of Metadata entry struct esp_ble_mesh_metadata_item_t Format of Metadata item Public Members uint16_t model_id Model ID uint16_t model_id Model ID uint16_t company_id Company ID uint16_t company_id Company ID struct esp_ble_mesh_metadata_item_t::[anonymous]::[anonymous] vnd Vendor model identifier Vendor model identifier struct esp_ble_mesh_metadata_item_t::[anonymous]::[anonymous] vnd Vendor model identifier Vendor model identifier union esp_ble_mesh_metadata_item_t::[anonymous] [anonymous] Union of model ID union esp_ble_mesh_metadata_item_t::[anonymous] [anonymous] Union of model ID uint8_t metadata_entries_num Number of metadata entries uint8_t metadata_entries_num Number of metadata entries esp_ble_mesh_metadata_entry_t *const metadata_entries List of model’s metadata esp_ble_mesh_metadata_entry_t *const metadata_entries List of model’s metadata uint16_t model_id struct esp_ble_mesh_metadata_elem_t Format of Metadata element of Models Metadata Page 0/128 Public Members const uint8_t items_num_s Number of metadata items for SIG models in the element const uint8_t items_num_s Number of metadata items for SIG models in the element const uint8_t items_num_v Number of metadata items for Vendor models in the element const uint8_t items_num_v Number of metadata items for Vendor models in the element esp_ble_mesh_metadata_item_t *const metadata_items_s List of metadata items for SIG models in the element esp_ble_mesh_metadata_item_t *const metadata_items_s List of metadata items for SIG models in the element esp_ble_mesh_metadata_item_t *const metadata_items_v List of metadata items for Vendor models in the element esp_ble_mesh_metadata_item_t *const metadata_items_v List of metadata items for Vendor models in the element const uint8_t items_num_s struct esp_ble_mesh_models_metadata_t Format of the Models Metadata Page 0/128 Public Members size_t element_count Element count size_t element_count Element count esp_ble_mesh_metadata_elem_t *elements List of metadata for models for each element esp_ble_mesh_metadata_elem_t *elements List of metadata for models for each element size_t element_count Macros ESP_BLE_MESH_MODEL_ITEM_SHORT < Definitions of the format of Extended_Model_Items indicator ESP_BLE_MESH_MODEL_ITEM_LONG
ESP-BLE-MESH Note The current ESP-BLE-MESH v1.1 related code is a preview version, so the Mesh Protocol v1.1 related Structures, MACROs, and APIs involved in the code may be changed. With various features of ESP-BLE-MESH, users can create a managed flooding mesh network for several scenarios, such as lighting, sensor and etc. For an ESP32 to join and work on a ESP-BLE-MESH network, it must be provisioned firstly. By provisioning, the ESP32, as an unprovisioned device, will join the ESP-BLE-MESH network and become a ESP-BLE-MESH node, communicating with other nodes within or beyond the radio range. Apart from ESP-BLE-MESH nodes, inside ESP-BLE-MESH network, there is also ESP32 that works as ESP-BLE-MESH provisioner, which could provision unprovisioned devices into ESP-BLE-MESH nodes and configure the nodes with various features. For information how to start using ESP32 and ESP-BLE-MESH, please see the Section Getting Started with ESP-BLE-MESH. If you are interested in information on ESP-BLE-MESH architecture, including some details of software implementation, please see Section ESP-BLE-MESH Architecture. Application Examples and Demos Please refer to Sections ESP-BLE-MESH Examples and ESP-BLE-MESH Demo Videos. API Reference ESP-BLE-MESH APIs are divided into the following parts: ESP-BLE-MESH Definitions This section contains only one header file, which lists the following items of ESP-BLE-MESH. ID of all the models and related message opcodes Structs of model, element and Composition Data Structs of used by ESP-BLE-MESH Node/Provisioner for provisioning Structs used to transmit/receive messages Event types and related event parameters Header File This header file can be included with: #include "esp_ble_mesh_defs.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Unions - union esp_ble_mesh_prov_cb_param_t - #include <esp_ble_mesh_defs.h> BLE Mesh Node/Provisioner callback parameters union. Public Members - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_prov_register_comp_param prov_register_comp Event parameter of ESP_BLE_MESH_PROV_REGISTER_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_unprov_dev_name_comp_param node_set_unprov_dev_name_comp Event parameter of ESP_BLE_MESH_NODE_SET_UNPROV_DEV_NAME_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_prov_enable_comp_param node_prov_enable_comp Event parameter of ESP_BLE_MESH_NODE_PROV_ENABLE_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_prov_disable_comp_param node_prov_disable_comp Event parameter of ESP_BLE_MESH_NODE_PROV_DISABLE_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_link_open_evt_param node_prov_link_open Event parameter of ESP_BLE_MESH_NODE_PROV_LINK_OPEN_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_link_close_evt_param node_prov_link_close Event parameter of ESP_BLE_MESH_NODE_PROV_LINK_CLOSE_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_output_num_evt_param node_prov_output_num Event parameter of ESP_BLE_MESH_NODE_PROV_OUTPUT_NUMBER_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_output_str_evt_param node_prov_output_str Event parameter of ESP_BLE_MESH_NODE_PROV_OUTPUT_STRING_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_input_evt_param node_prov_input Event parameter of ESP_BLE_MESH_NODE_PROV_INPUT_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provision_complete_evt_param node_prov_complete Event parameter of ESP_BLE_MESH_NODE_PROV_COMPLETE_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provision_reset_param node_prov_reset Event parameter of ESP_BLE_MESH_NODE_PROV_RESET_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_oob_pub_key_comp_param node_prov_set_oob_pub_key_comp Event parameter of ESP_BLE_MESH_NODE_PROV_SET_OOB_PUB_KEY_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_input_number_comp_param node_prov_input_num_comp Event parameter of ESP_BLE_MESH_NODE_PROV_INPUT_NUM_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_input_string_comp_param node_prov_input_str_comp Event parameter of ESP_BLE_MESH_NODE_PROV_INPUT_STR_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_identity_enable_comp_param node_proxy_identity_enable_comp Event parameter of ESP_BLE_MESH_NODE_PROXY_IDENTITY_ENABLE_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_gatt_enable_comp_param node_proxy_gatt_enable_comp Event parameter of ESP_BLE_MESH_NODE_PROXY_GATT_ENABLE_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_gatt_disable_comp_param node_proxy_gatt_disable_comp Event parameter of ESP_BLE_MESH_NODE_PROXY_GATT_DISABLE_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_private_identity_enable_comp_param node_private_proxy_identity_enable_comp Event parameter of ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_ENABLE_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_private_identity_disable_comp_param node_private_proxy_identity_disable_comp Event parameter of ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_DISABLE_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_node_add_local_net_key_comp_param node_add_net_key_comp Event parameter of ESP_BLE_MESH_NODE_ADD_LOCAL_NET_KEY_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_node_add_local_app_key_comp_param node_add_app_key_comp Event parameter of ESP_BLE_MESH_NODE_ADD_LOCAL_APP_KEY_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_node_bind_local_mod_app_comp_param node_bind_app_key_to_model_comp Event parameter of ESP_BLE_MESH_NODE_BIND_APP_KEY_TO_MODEL_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_recv_unprov_adv_pkt_param provisioner_recv_unprov_adv_pkt Event parameter of ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_enable_comp_param provisioner_prov_enable_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_ENABLE_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_disable_comp_param provisioner_prov_disable_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_DISABLE_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_link_open_evt_param provisioner_prov_link_open Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_LINK_OPEN_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_read_oob_pub_key_evt_param provisioner_prov_read_oob_pub_key Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_input_evt_param provisioner_prov_input Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_INPUT_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_output_evt_param provisioner_prov_output Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_OUTPUT_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_link_close_evt_param provisioner_prov_link_close Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_LINK_CLOSE_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_comp_param provisioner_prov_complete Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_cert_based_prov_start_evt_param provisioner_cert_based_prov_start Event parameter of ESP_BLE_MESH_PROVISIONER_CERT_BASED_PROV_START_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_recv_prov_records_list_evt_param recv_provisioner_records_list Event parameter of ESP_BLE_MESH_PROVISIONER_RECV_PROV_RECORDS_LIST_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_record_recv_comp_evt_param provisioner_prov_record_recv_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_RECORD_RECV_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_send_prov_records_get_evt_param provisioner_send_records_get Event parameter of ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORDS_GET_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_send_prov_record_req_evt_param provisioner_send_record_req Event parameter of ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORD_REQUEST_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_send_prov_invite_evt_param provisioner_send_prov_invite Event parameter of ESP_BLE_MESH_PROVISIONER_SEND_PROV_INVITE_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_send_link_close_evt_param provisioner_send_link_close Event parameter of ESP_BLE_MESH_PROVISIONER_SEND_LINK_CLOSE_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_add_unprov_dev_comp_param provisioner_add_unprov_dev_comp Event parameter of ESP_BLE_MESH_PROVISIONER_ADD_UNPROV_DEV_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_dev_with_addr_comp_param provisioner_prov_dev_with_addr_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_DEV_WITH_ADDR_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_delete_dev_comp_param provisioner_delete_dev_comp Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_DEV_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_dev_uuid_match_comp_param provisioner_set_dev_uuid_match_comp Event parameter of ESP_BLE_MESH_PROVISIONER_SET_DEV_UUID_MATCH_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_prov_data_info_comp_param provisioner_set_prov_data_info_comp Event parameter of ESP_BLE_MESH_PROVISIONER_SET_PROV_DATA_INFO_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_static_oob_val_comp_param provisioner_set_static_oob_val_comp Event parameter of ESP_BLE_MESH_PROVISIONER_SET_STATIC_OOB_VALUE_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_primary_elem_addr_comp_param provisioner_set_primary_elem_addr_comp Event parameter of ESP_BLE_MESH_PROVISIONER_SET_PRIMARY_ELEM_ADDR_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_read_oob_pub_key_comp_param provisioner_prov_read_oob_pub_key_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_input_num_comp_param provisioner_prov_input_num_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_INPUT_NUMBER_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_input_str_comp_param provisioner_prov_input_str_comp Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_INPUT_STRING_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_node_name_comp_param provisioner_set_node_name_comp Event parameter of ESP_BLE_MESH_PROVISIONER_SET_NODE_NAME_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_add_local_app_key_comp_param provisioner_add_app_key_comp Event parameter of ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_APP_KEY_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_update_local_app_key_comp_param provisioner_update_app_key_comp Event parameter of ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_APP_KEY_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_bind_local_mod_app_comp_param provisioner_bind_app_key_to_model_comp Event parameter of ESP_BLE_MESH_PROVISIONER_BIND_APP_KEY_TO_MODEL_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_add_local_net_key_comp_param provisioner_add_net_key_comp Event parameter of ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_NET_KEY_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_update_local_net_key_comp_param provisioner_update_net_key_comp Event parameter of ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_NET_KEY_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_store_node_comp_data_comp_param provisioner_store_node_comp_data_comp Event parameter of ESP_BLE_MESH_PROVISIONER_STORE_NODE_COMP_DATA_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_delete_node_with_uuid_comp_param provisioner_delete_node_with_uuid_comp Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_UUID_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_delete_node_with_addr_comp_param provisioner_delete_node_with_addr_comp Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_ADDR_COMP_EVT - int err_code Indicate the result of enabling/disabling to receive heartbeat messages by the Provisioner Indicate the result of setting the heartbeat filter type by the Provisioner Indicate the result of setting the heartbeat filter address by the Provisioner Indicate the result of directly erasing settings by the Provisioner Indicate the result of opening settings with index by the Provisioner Indicate the result of opening settings with user id by the Provisioner Indicate the result of closing settings with index by the Provisioner Indicate the result of closing settings with user id by the Provisioner Indicate the result of deleting settings with index by the Provisioner Indicate the result of deleting settings with user id by the Provisioner Indicate the result of Proxy Client send Solicitation PDU - bool enable Indicate enabling or disabling receiving heartbeat messages - struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_enable_heartbeat_recv_comp ESP_BLE_MESH_PROVISIONER_ENABLE_HEARTBEAT_RECV_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_ENABLE_HEARTBEAT_RECV_COMP_EVT - uint8_t type Type of the filter used for receiving heartbeat messages - struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_set_heartbeat_filter_type_comp ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_TYPE_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_TYPE_COMP_EVT - uint8_t op Operation (add, remove, clean) - uint16_t hb_src Heartbeat source address - uint16_t hb_dst Heartbeat destination address - struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_set_heartbeat_filter_info_comp ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_INFO_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_INFO_COMP_EVT - uint8_t init_ttl Heartbeat InitTTL - uint8_t rx_ttl Heartbeat RxTTL - uint8_t hops Heartbeat hops (InitTTL - RxTTL + 1) - uint16_t feature Bit field of currently active features of the node - int8_t rssi RSSI of the heartbeat message - struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_recv_heartbeat ESP_BLE_MESH_PROVISIONER_RECV_HEARTBEAT_MESSAGE_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_RECV_HEARTBEAT_MESSAGE_EVT - struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_direct_erase_settings_comp ESP_BLE_MESH_PROVISIONER_DIRECT_ERASE_SETTINGS_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_DIRECT_ERASE_SETTINGS_COMP_EVT - uint8_t index Index of Provisioner settings - struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_open_settings_with_index_comp ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_INDEX_COMP_EVT. Event parameter of ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_INDEX_COMP_EVT - char uid[ESP_BLE_MESH_SETTINGS_UID_SIZE + 1] Provisioner settings user id - struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_open_settings_with_uid_comp ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_UID_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_UID_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_close_settings_with_index_comp ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_INDEX_COMP_EVT. Event parameter of ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_INDEX_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_close_settings_with_uid_comp ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_UID_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_UID_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_delete_settings_with_index_comp ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_INDEX_COMP_EVT. Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_INDEX_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::[anonymous] provisioner_delete_settings_with_uid_comp ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_UID_COMP_EVT. Event parameters of ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_UID_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_fast_prov_info_comp_param set_fast_prov_info_comp Event parameter of ESP_BLE_MESH_SET_FAST_PROV_INFO_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_fast_prov_action_comp_param set_fast_prov_action_comp Event parameter of ESP_BLE_MESH_SET_FAST_PROV_ACTION_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_heartbeat_msg_recv_param heartbeat_msg_recv Event parameter of ESP_BLE_MESH_HEARTBEAT_MESSAGE_RECV_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_enable_comp_param lpn_enable_comp Event parameter of ESP_BLE_MESH_LPN_ENABLE_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_disable_comp_param lpn_disable_comp Event parameter of ESP_BLE_MESH_LPN_DISABLE_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_poll_comp_param lpn_poll_comp Event parameter of ESP_BLE_MESH_LPN_POLL_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_friendship_establish_param lpn_friendship_establish Event parameter of ESP_BLE_MESH_LPN_FRIENDSHIP_ESTABLISH_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_friendship_terminate_param lpn_friendship_terminate Event parameter of ESP_BLE_MESH_LPN_FRIENDSHIP_TERMINATE_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_friend_friendship_establish_param frnd_friendship_establish Event parameter of ESP_BLE_MESH_FRIEND_FRIENDSHIP_ESTABLISH_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_friend_friendship_terminate_param frnd_friendship_terminate Event parameter of ESP_BLE_MESH_FRIEND_FRIENDSHIP_TERMINATE_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_recv_adv_pkt_param proxy_client_recv_adv_pkt Event parameter of ESP_BLE_MESH_PROXY_CLIENT_RECV_ADV_PKT_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_connected_param proxy_client_connected Event parameter of ESP_BLE_MESH_PROXY_CLIENT_CONNECTED_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_disconnected_param proxy_client_disconnected Event parameter of ESP_BLE_MESH_PROXY_CLIENT_DISCONNECTED_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_recv_filter_status_param proxy_client_recv_filter_status Event parameter of ESP_BLE_MESH_PROXY_CLIENT_RECV_FILTER_STATUS_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_connect_comp_param proxy_client_connect_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_CONNECT_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_disconnect_comp_param proxy_client_disconnect_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_DISCONNECT_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_set_filter_type_comp_param proxy_client_set_filter_type_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_SET_FILTER_TYPE_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_add_filter_addr_comp_param proxy_client_add_filter_addr_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_ADD_FILTER_ADDR_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_remove_filter_addr_comp_param proxy_client_remove_filter_addr_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_REMOVE_FILTER_ADDR_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_directed_proxy_set_param proxy_client_directed_proxy_set_comp Event parameter of ESP_BLE_MESH_PROXY_CLIENT_DIRECTED_PROXY_SET_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_server_connected_param proxy_server_connected Event parameter of ESP_BLE_MESH_PROXY_SERVER_CONNECTED_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_server_disconnected_param proxy_server_disconnected Event parameter of ESP_BLE_MESH_PROXY_SERVER_DISCONNECTED_EVT - uint16_t net_idx Corresponding NetKey Index - uint16_t ssrc Solicitation SRC - uint16_t dst Solicitation DST - struct esp_ble_mesh_prov_cb_param_t::[anonymous] proxy_client_send_solic_pdu_comp ESP_BLE_MESH_PROXY_CLIENT_SEND_SOLIC_PDU_COMP_EVT. Event parameter of ESP_BLE_MESH_PROXY_CLIENT_SEND_SOLIC_PDU_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_model_sub_group_addr_comp_param model_sub_group_addr_comp Event parameters of ESP_BLE_MESH_MODEL_SUBSCRIBE_GROUP_ADDR_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_model_unsub_group_addr_comp_param model_unsub_group_addr_comp Event parameters of ESP_BLE_MESH_MODEL_UNSUBSCRIBE_GROUP_ADDR_COMP_EVT - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_deinit_mesh_comp_param deinit_mesh_comp Event parameter of ESP_BLE_MESH_DEINIT_MESH_COMP_EVT - struct ble_mesh_deinit_mesh_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_DEINIT_MESH_COMP_EVT. Public Members - int err_code Indicate the result of BLE Mesh deinitialization - int err_code - struct ble_mesh_friend_friendship_establish_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_FRIEND_FRIENDSHIP_ESTABLISH_EVT. Public Members - uint16_t lpn_addr Low Power Node unicast address - uint16_t lpn_addr - struct ble_mesh_friend_friendship_terminate_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_FRIEND_FRIENDSHIP_TERMINATE_EVT. Public Types - enum [anonymous] This enum value is the reason of friendship termination on the friend node side Values: - enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_ESTABLISH_FAIL Friend Offer has been sent, but Friend Offer is not received within 1 second, friendship fails to be established - enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_POLL_TIMEOUT Friendship is established, PollTimeout timer expires and no Friend Poll/Sub Add/Sub Remove is received - enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_RECV_FRND_REQ Receive Friend Request from existing Low Power Node - enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_RECV_FRND_CLEAR Receive Friend Clear from other friend node - enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_DISABLE Friend feature disabled or corresponding NetKey is deleted - enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_ESTABLISH_FAIL Public Members - uint16_t lpn_addr Low Power Node unicast address - enum esp_ble_mesh_prov_cb_param_t::ble_mesh_friend_friendship_terminate_param::[anonymous] reason This enum value is the reason of friendship termination on the friend node side Friendship terminated reason - enum [anonymous] - struct ble_mesh_heartbeat_msg_recv_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_HEARTBEAT_MESSAGE_RECV_EVT. - struct ble_mesh_input_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_INPUT_EVT. Public Members - esp_ble_mesh_input_action_t action Action of Input OOB Authentication - uint8_t size Size of Input OOB Authentication - esp_ble_mesh_input_action_t action - struct ble_mesh_input_number_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_INPUT_NUM_COMP_EVT. Public Members - int err_code Indicate the result of inputting number - int err_code - struct ble_mesh_input_string_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_INPUT_STR_COMP_EVT. Public Members - int err_code Indicate the result of inputting string - int err_code - struct ble_mesh_link_close_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_LINK_CLOSE_EVT. Public Members - esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when device link is closed - uint8_t reason Reason of the closed provisioning link - esp_ble_mesh_prov_bearer_t bearer - struct ble_mesh_link_open_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_LINK_OPEN_EVT. Public Members - esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when device link is open - esp_ble_mesh_prov_bearer_t bearer - struct ble_mesh_lpn_disable_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_DISABLE_COMP_EVT. Public Members - int err_code Indicate the result of disabling LPN functionality - int err_code - struct ble_mesh_lpn_enable_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_ENABLE_COMP_EVT. Public Members - int err_code Indicate the result of enabling LPN functionality - int err_code - struct ble_mesh_lpn_friendship_establish_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_FRIENDSHIP_ESTABLISH_EVT. Public Members - uint16_t friend_addr Friend Node unicast address - uint16_t friend_addr - struct ble_mesh_lpn_friendship_terminate_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_FRIENDSHIP_TERMINATE_EVT. Public Members - uint16_t friend_addr Friend Node unicast address - uint16_t friend_addr - struct ble_mesh_lpn_poll_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_POLL_COMP_EVT. Public Members - int err_code Indicate the result of sending Friend Poll - int err_code - struct ble_mesh_model_sub_group_addr_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_SUBSCRIBE_GROUP_ADDR_COMP_EVT. - struct ble_mesh_model_unsub_group_addr_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_UNSUBSCRIBE_GROUP_ADDR_COMP_EVT. - struct ble_mesh_node_add_local_app_key_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_ADD_LOCAL_APP_KEY_COMP_EVT. - struct ble_mesh_node_add_local_net_key_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_ADD_LOCAL_NET_KEY_COMP_EVT. - struct ble_mesh_node_bind_local_mod_app_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_BIND_APP_KEY_TO_MODEL_COMP_EVT. - struct ble_mesh_output_num_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_OUTPUT_NUMBER_EVT. Public Members - esp_ble_mesh_output_action_t action Action of Output OOB Authentication - uint32_t number Number of Output OOB Authentication - esp_ble_mesh_output_action_t action - struct ble_mesh_output_str_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_OUTPUT_STRING_EVT. Public Members - char string[8] String of Output OOB Authentication - char string[8] - struct ble_mesh_prov_disable_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_DISABLE_COMP_EVT. Public Members - int err_code Indicate the result of disabling BLE Mesh device - int err_code - struct ble_mesh_prov_enable_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_ENABLE_COMP_EVT. Public Members - int err_code Indicate the result of enabling BLE Mesh device - int err_code - struct ble_mesh_prov_register_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROV_REGISTER_COMP_EVT. Public Members - int err_code Indicate the result of BLE Mesh initialization - int err_code - struct ble_mesh_provision_complete_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_COMPLETE_EVT. - struct ble_mesh_provision_reset_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_RESET_EVT. - struct ble_mesh_provisioner_add_local_app_key_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_APP_KEY_COMP_EVT. - struct ble_mesh_provisioner_add_local_net_key_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_NET_KEY_COMP_EVT. - struct ble_mesh_provisioner_add_unprov_dev_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_ADD_UNPROV_DEV_COMP_EVT. Public Members - int err_code Indicate the result of adding device into queue by the Provisioner - int err_code - struct ble_mesh_provisioner_bind_local_mod_app_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_BIND_APP_KEY_TO_MODEL_COMP_EVT. - struct ble_mesh_provisioner_cert_based_prov_start_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_CERT_BASED_PROV_START_EVT. Public Members - uint16_t link_idx Index of the provisioning link - uint16_t link_idx - struct ble_mesh_provisioner_delete_dev_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_DELETE_DEV_COMP_EVT. Public Members - int err_code Indicate the result of deleting device by the Provisioner - int err_code - struct ble_mesh_provisioner_delete_node_with_addr_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_ADDR_COMP_EVT. - struct ble_mesh_provisioner_delete_node_with_uuid_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_UUID_COMP_EVT. - struct ble_mesh_provisioner_link_close_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_LINK_CLOSE_EVT. Public Members - esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when Provisioner link is closed - uint8_t reason Reason of the closed provisioning link - esp_ble_mesh_prov_bearer_t bearer - struct ble_mesh_provisioner_link_open_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_LINK_OPEN_EVT. Public Members - esp_ble_mesh_prov_bearer_t bearer Type of the bearer used when Provisioner link is opened - esp_ble_mesh_prov_bearer_t bearer - struct ble_mesh_provisioner_prov_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT. Public Members - uint16_t node_idx Index of the provisioned device - esp_ble_mesh_octet16_t device_uuid Device UUID of the provisioned device - uint16_t unicast_addr Primary address of the provisioned device - uint8_t element_num Element count of the provisioned device - uint16_t netkey_idx NetKey Index of the provisioned device - uint16_t node_idx - struct ble_mesh_provisioner_prov_dev_with_addr_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_DEV_WITH_ADDR_COMP_EVT. Public Members - int err_code Indicate the result of Provisioner starting to provision a device - int err_code - struct ble_mesh_provisioner_prov_disable_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_DISABLE_COMP_EVT. Public Members - int err_code Indicate the result of disabling BLE Mesh Provisioner - int err_code - struct ble_mesh_provisioner_prov_enable_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_ENABLE_COMP_EVT. Public Members - int err_code Indicate the result of enabling BLE Mesh Provisioner - int err_code - struct ble_mesh_provisioner_prov_input_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_INPUT_EVT. Public Members - esp_ble_mesh_oob_method_t method Method of device Output OOB Authentication - esp_ble_mesh_output_action_t action Action of device Output OOB Authentication - uint8_t size Size of device Output OOB Authentication - uint8_t link_idx Index of the provisioning link - esp_ble_mesh_oob_method_t method - struct ble_mesh_provisioner_prov_input_num_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_INPUT_NUMBER_COMP_EVT. Public Members - int err_code Indicate the result of inputting number by the Provisioner - int err_code - struct ble_mesh_provisioner_prov_input_str_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_INPUT_STRING_COMP_EVT. Public Members - int err_code Indicate the result of inputting string by the Provisioner - int err_code - struct ble_mesh_provisioner_prov_output_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_OUTPUT_EVT. Public Members - esp_ble_mesh_oob_method_t method Method of device Input OOB Authentication - esp_ble_mesh_input_action_t action Action of device Input OOB Authentication - uint8_t size Size of device Input OOB Authentication - uint8_t link_idx Index of the provisioning link - char string[8] String output by the Provisioner - uint32_t number Number output by the Provisioner - union esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_output_evt_param::[anonymous] [anonymous] Union of output OOB - esp_ble_mesh_oob_method_t method - struct ble_mesh_provisioner_prov_read_oob_pub_key_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_COMP_EVT. Public Members - int err_code Indicate the result of setting OOB Public Key by the Provisioner - int err_code - struct ble_mesh_provisioner_prov_read_oob_pub_key_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_EVT. Public Members - uint8_t link_idx Index of the provisioning link - uint8_t link_idx - struct ble_mesh_provisioner_prov_record_recv_comp_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_RECORD_RECV_COMP_EVT. Public Members - uint8_t status Indicates whether or not the request was handled successfully - uint16_t link_idx Index of the provisioning link - uint16_t record_id Identifies the provisioning record for which the request is made - uint16_t frag_offset The starting offset of the requested fragment in the provisioning record data - uint16_t total_len Total length of the provisioning record data stored on the Provisionee - uint8_t *record Provisioning record data fragment - uint8_t status - struct ble_mesh_provisioner_recv_prov_records_list_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_RECV_PROV_RECORDS_LIST_EVT. - struct ble_mesh_provisioner_recv_unprov_adv_pkt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT. Public Members - uint8_t dev_uuid[16] Device UUID of the unprovisioned device - esp_ble_mesh_bd_addr_t addr Device address of the unprovisioned device - esp_ble_mesh_addr_type_t addr_type Device address type - uint16_t oob_info OOB Info of the unprovisioned device - uint8_t adv_type Advertising type of the unprovisioned device - esp_ble_mesh_prov_bearer_t bearer Bearer of the unprovisioned device - int8_t rssi RSSI of the received advertising packet - uint8_t dev_uuid[16] - struct ble_mesh_provisioner_send_link_close_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SEND_LINK_CLOSE_EVT. - struct ble_mesh_provisioner_send_prov_invite_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SEND_PROV_INVITE_EVT. - struct ble_mesh_provisioner_send_prov_record_req_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORD_REQUEST_EVT. Public Members - int err_code Indicate the result of send Provisioning Record Request message - uint16_t link_idx Index of the provisioning link - uint16_t record_id Identifies the provisioning record for which the request is made - uint16_t frag_offset The starting offset of the requested fragment in the provisioning record data - uint16_t max_size The maximum size of the provisioning record fragment that the Provisioner can receive - int err_code - struct ble_mesh_provisioner_send_prov_records_get_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORDS_GET_EVT. - struct ble_mesh_provisioner_set_dev_uuid_match_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_DEV_UUID_MATCH_COMP_EVT. Public Members - int err_code Indicate the result of setting Device UUID match value by the Provisioner - int err_code - struct ble_mesh_provisioner_set_node_name_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_NODE_NAME_COMP_EVT. - struct ble_mesh_provisioner_set_primary_elem_addr_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_PRIMARY_ELEM_ADDR_COMP_EVT. Public Members - int err_code Indicate the result of setting unicast address of primary element by the Provisioner - int err_code - struct ble_mesh_provisioner_set_prov_data_info_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_PROV_DATA_INFO_COMP_EVT. Public Members - int err_code Indicate the result of setting provisioning info by the Provisioner - int err_code - struct ble_mesh_provisioner_set_static_oob_val_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_STATIC_OOB_VALUE_COMP_EVT. Public Members - int err_code Indicate the result of setting static oob value by the Provisioner - int err_code - struct ble_mesh_provisioner_store_node_comp_data_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_STORE_NODE_COMP_DATA_COMP_EVT. - struct ble_mesh_provisioner_update_local_app_key_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_APP_KEY_COMP_EVT. - struct ble_mesh_provisioner_update_local_net_key_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_NET_KEY_COMP_EVT. - struct ble_mesh_proxy_client_add_filter_addr_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_ADD_FILTER_ADDR_COMP_EVT. - struct ble_mesh_proxy_client_connect_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_CONNECT_COMP_EVT. Public Members - int err_code Indicate the result of Proxy Client connect - esp_ble_mesh_bd_addr_t addr Device address of the Proxy Server - esp_ble_mesh_addr_type_t addr_type Device address type - uint16_t net_idx Corresponding NetKey Index - int err_code - struct ble_mesh_proxy_client_connected_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_CONNECTED_EVT. Public Members - esp_ble_mesh_bd_addr_t addr Device address of the Proxy Server - esp_ble_mesh_addr_type_t addr_type Device address type - uint8_t conn_handle Proxy connection handle - uint16_t net_idx Corresponding NetKey Index - esp_ble_mesh_bd_addr_t addr - struct ble_mesh_proxy_client_directed_proxy_set_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_DIRECTED_PROXY_CONTROL_COMP_EVT. - struct ble_mesh_proxy_client_disconnect_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_DISCONNECT_COMP_EVT. - struct ble_mesh_proxy_client_disconnected_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_DISCONNECTED_EVT. Public Members - esp_ble_mesh_bd_addr_t addr Device address of the Proxy Server - esp_ble_mesh_addr_type_t addr_type Device address type - uint8_t conn_handle Proxy connection handle - uint16_t net_idx Corresponding NetKey Index - uint8_t reason Proxy disconnect reason - esp_ble_mesh_bd_addr_t addr - struct ble_mesh_proxy_client_recv_adv_pkt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_RECV_ADV_PKT_EVT. Public Members - esp_ble_mesh_bd_addr_t addr Device address - esp_ble_mesh_addr_type_t addr_type Device address type - uint16_t net_idx Network ID related NetKey Index - uint8_t net_id[8] Network ID contained in the advertising packet - int8_t rssi RSSI of the received advertising packet - esp_ble_mesh_bd_addr_t addr - struct ble_mesh_proxy_client_recv_filter_status_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_RECV_FILTER_STATUS_EVT. Public Members - uint8_t conn_handle Proxy connection handle - uint16_t server_addr Proxy Server primary element address - uint16_t net_idx Corresponding NetKey Index - uint8_t filter_type Proxy Server filter type(whitelist or blacklist) - uint16_t list_size Number of addresses in the Proxy Server filter list - uint8_t conn_handle - struct ble_mesh_proxy_client_remove_filter_addr_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_REMOVE_FILTER_ADDR_COMP_EVT. - struct ble_mesh_proxy_client_set_filter_type_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_SET_FILTER_TYPE_COMP_EVT. - struct ble_mesh_proxy_gatt_disable_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROXY_GATT_DISABLE_COMP_EVT. Public Members - int err_code Indicate the result of disabling Mesh Proxy Service - int err_code - struct ble_mesh_proxy_gatt_enable_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROXY_GATT_ENABLE_COMP_EVT. Public Members - int err_code Indicate the result of enabling Mesh Proxy Service - int err_code - struct ble_mesh_proxy_identity_enable_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROXY_IDENTITY_ENABLE_COMP_EVT. Public Members - int err_code Indicate the result of enabling Mesh Proxy advertising - int err_code - struct ble_mesh_proxy_private_identity_disable_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_DISABLE_COMP_EVT. Public Members - int err_code Indicate the result of disabling Mesh Proxy private advertising - int err_code - struct ble_mesh_proxy_private_identity_enable_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_ENABLE_COMP_EVT. Public Members - int err_code Indicate the result of enabling Mesh Proxy private advertising - int err_code - struct ble_mesh_proxy_server_connected_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_SERVER_CONNECTED_EVT. Public Members - uint8_t conn_handle Proxy connection handle - uint8_t conn_handle - struct ble_mesh_proxy_server_disconnected_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_SERVER_DISCONNECTED_EVT. - struct ble_mesh_set_fast_prov_action_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_SET_FAST_PROV_ACTION_COMP_EVT. Public Members - uint8_t status_action Indicate the result of setting action of fast provisioning - uint8_t status_action - struct ble_mesh_set_fast_prov_info_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_SET_FAST_PROV_INFO_COMP_EVT. - struct ble_mesh_set_oob_pub_key_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_SET_OOB_PUB_KEY_COMP_EVT. Public Members - int err_code Indicate the result of setting OOB Public Key - int err_code - struct esp_ble_mesh_prov_cb_param_t::ble_mesh_prov_register_comp_param prov_register_comp - union esp_ble_mesh_server_state_value_t - #include <esp_ble_mesh_defs.h> Server model state value union. Public Members - uint8_t onoff The value of the Generic OnOff state The value of the Light LC Light OnOff state - struct esp_ble_mesh_server_state_value_t::[anonymous] gen_onoff The Generic OnOff state - int16_t level The value of the Generic Level state - struct esp_ble_mesh_server_state_value_t::[anonymous] gen_level The Generic Level state - uint8_t onpowerup The value of the Generic OnPowerUp state - struct esp_ble_mesh_server_state_value_t::[anonymous] gen_onpowerup The Generic OnPowerUp state - uint16_t power The value of the Generic Power Actual state - struct esp_ble_mesh_server_state_value_t::[anonymous] gen_power_actual The Generic Power Actual state - uint16_t lightness The value of the Light Lightness Actual state The value of the Light Lightness Linear state The value of the Light CTL Lightness state The value of the Light HSL Lightness state The value of the Light xyL Lightness state - struct esp_ble_mesh_server_state_value_t::[anonymous] light_lightness_actual The Light Lightness Actual state - struct esp_ble_mesh_server_state_value_t::[anonymous] light_lightness_linear The Light Lightness Linear state - struct esp_ble_mesh_server_state_value_t::[anonymous] light_ctl_lightness The Light CTL Lightness state - uint16_t temperature The value of the Light CTL Temperature state - int16_t delta_uv The value of the Light CTL Delta UV state - struct esp_ble_mesh_server_state_value_t::[anonymous] light_ctl_temp_delta_uv The Light CTL Temperature & Delta UV states - uint16_t hue The value of the Light HSL Hue state - uint16_t saturation The value of the Light HSL Saturation state - struct esp_ble_mesh_server_state_value_t::[anonymous] light_hsl The Light HSL composite state - struct esp_ble_mesh_server_state_value_t::[anonymous] light_hsl_lightness The Light HSL Lightness state - struct esp_ble_mesh_server_state_value_t::[anonymous] light_hsl_hue The Light HSL Hue state - struct esp_ble_mesh_server_state_value_t::[anonymous] light_hsl_saturation The Light HSL Saturation state - struct esp_ble_mesh_server_state_value_t::[anonymous] light_xyl_lightness The Light xyL Lightness state - struct esp_ble_mesh_server_state_value_t::[anonymous] light_lc_light_onoff The Light LC Light OnOff state - uint8_t onoff - union esp_ble_mesh_model_cb_param_t - #include <esp_ble_mesh_defs.h> BLE Mesh model callback parameters union. Public Members - struct esp_ble_mesh_model_cb_param_t::ble_mesh_model_operation_evt_param model_operation Event parameter of ESP_BLE_MESH_MODEL_OPERATION_EVT - struct esp_ble_mesh_model_cb_param_t::ble_mesh_model_send_comp_param model_send_comp Event parameter of ESP_BLE_MESH_MODEL_SEND_COMP_EVT - struct esp_ble_mesh_model_cb_param_t::ble_mesh_model_publish_comp_param model_publish_comp Event parameter of ESP_BLE_MESH_MODEL_PUBLISH_COMP_EVT - struct esp_ble_mesh_model_cb_param_t::ble_mesh_mod_recv_publish_msg_param client_recv_publish_msg Event parameter of ESP_BLE_MESH_CLIENT_MODEL_RECV_PUBLISH_MSG_EVT - struct esp_ble_mesh_model_cb_param_t::ble_mesh_client_model_send_timeout_param client_send_timeout Event parameter of ESP_BLE_MESH_CLIENT_MODEL_SEND_TIMEOUT_EVT - struct esp_ble_mesh_model_cb_param_t::ble_mesh_model_publish_update_evt_param model_publish_update Event parameter of ESP_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT - struct esp_ble_mesh_model_cb_param_t::ble_mesh_server_model_update_state_comp_param server_model_update_state Event parameter of ESP_BLE_MESH_SERVER_MODEL_UPDATE_STATE_COMP_EVT - struct ble_mesh_client_model_send_timeout_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_CLIENT_MODEL_SEND_TIMEOUT_EVT. Public Members - uint32_t opcode Opcode of the previously sent message - esp_ble_mesh_model_t *model Pointer to the model which sends the previous message - esp_ble_mesh_msg_ctx_t *ctx Pointer to the context of the previous message - uint32_t opcode - struct ble_mesh_mod_recv_publish_msg_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_CLIENT_MODEL_RECV_PUBLISH_MSG_EVT. Public Members - uint32_t opcode Opcode of the unsolicited received message - esp_ble_mesh_model_t *model Pointer to the model which receives the message - esp_ble_mesh_msg_ctx_t *ctx Pointer to the context of the message - uint16_t length Length of the received message - uint8_t *msg Value of the received message - uint32_t opcode - struct ble_mesh_model_operation_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_OPERATION_EVT. Public Members - uint32_t opcode Opcode of the received message - esp_ble_mesh_model_t *model Pointer to the model which receives the message - esp_ble_mesh_msg_ctx_t *ctx Pointer to the context of the received message - uint16_t length Length of the received message - uint8_t *msg Value of the received message - uint32_t opcode - struct ble_mesh_model_publish_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_PUBLISH_COMP_EVT. Public Members - int err_code Indicate the result of publishing a message - esp_ble_mesh_model_t *model Pointer to the model which publishes the message - int err_code - struct ble_mesh_model_publish_update_evt_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT. Public Members - esp_ble_mesh_model_t *model Pointer to the model which is going to update its publish message - esp_ble_mesh_model_t *model - struct ble_mesh_model_send_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_SEND_COMP_EVT. Public Members - int err_code Indicate the result of sending a message - uint32_t opcode Opcode of the message - esp_ble_mesh_model_t *model Pointer to the model which sends the message - esp_ble_mesh_msg_ctx_t *ctx Context of the message - int err_code - struct ble_mesh_server_model_update_state_comp_param - #include <esp_ble_mesh_defs.h> ESP_BLE_MESH_SERVER_MODEL_UPDATE_STATE_COMP_EVT. Public Members - int err_code Indicate the result of updating server model state - esp_ble_mesh_model_t *model Pointer to the server model which state value is updated - esp_ble_mesh_server_state_type_t type Type of the updated server state - int err_code - struct esp_ble_mesh_model_cb_param_t::ble_mesh_model_operation_evt_param model_operation Structures - struct esp_ble_mesh_deinit_param_t BLE Mesh deinit parameters Public Members - bool erase_flash Indicate if erasing flash when deinit mesh stack - bool erase_flash - struct esp_ble_mesh_uar_t Format of Unicast Address Range - struct esp_ble_mesh_elem_t Abstraction that describes a BLE Mesh Element. This structure is associated with struct bt_mesh_elem in mesh_access.h Public Members - uint16_t element_addr Element Address, assigned during provisioning. - const uint16_t location Location Descriptor (GATT Bluetooth Namespace Descriptors) - const uint8_t sig_model_count SIG Model count - const uint8_t vnd_model_count Vendor Model count - esp_ble_mesh_model_t *sig_models SIG Models - esp_ble_mesh_model_t *vnd_models Vendor Models - uint16_t element_addr - struct esp_ble_mesh_model_pub_t Abstraction that describes a model publication context. This structure is associated with struct bt_mesh_model_pub in mesh_access.h Public Members - esp_ble_mesh_model_t *model Pointer to the model to which the context belongs. Initialized by the stack. - uint16_t publish_addr Publish Address. - uint16_t app_idx Publish AppKey Index. - uint16_t cred Friendship Credentials Flag. - uint16_t send_rel Force reliable sending (segment acks) - uint16_t send_szmic Size of TransMIC when publishing a Segmented Access message - uint8_t ttl Publish Time to Live. - uint8_t retransmit Retransmit Count & Interval Steps. - uint8_t period Publish Period. - uint8_t period_div Divisor for the Period. - uint8_t fast_period Use FastPeriodDivisor - uint8_t count Retransmissions left. - uint32_t period_start Start of the current period. - struct net_buf_simple *msg Publication buffer, containing the publication message. This will get correctly created when the publication context has been defined using the ESP_BLE_MESH_MODEL_PUB_DEFINE macro. ESP_BLE_MESH_MODEL_PUB_DEFINE(name, size); - esp_ble_mesh_cb_t update Callback used to update publish message. Initialized by the stack. - struct k_delayed_work timer Publish Period Timer. Initialized by the stack. - uint8_t dev_role Role of the device that is going to publish messages - esp_ble_mesh_model_t *model - struct esp_ble_mesh_model_op_t Abstraction that describes a model operation context. This structure is associated with struct bt_mesh_model_op in mesh_access.h Public Members - const uint32_t opcode Message opcode - const size_t min_len Message minimum length - esp_ble_mesh_cb_t param_cb Callback used to handle message. Initialized by the stack. - const uint32_t opcode - struct esp_ble_mesh_model_cbs_t Abstraction that describes a model callback structure. This structure is associated with struct bt_mesh_model_cb in mesh_access.h. Public Members - esp_ble_mesh_cb_t init_cb Callback used during model initialization. Initialized by the stack. - esp_ble_mesh_cb_t init_cb - struct esp_ble_mesh_model Abstraction that describes a Mesh Model instance. This structure is associated with struct bt_mesh_model in mesh_access.h Public Members - const uint16_t model_id 16-bit model identifier - uint16_t company_id 16-bit company identifier - uint16_t model_id 16-bit model identifier - struct esp_ble_mesh_model::[anonymous]::[anonymous] vnd Structure encapsulating a model ID with a company ID - union esp_ble_mesh_model::[anonymous] [anonymous] Model ID - uint8_t element_idx Internal information, mainly for persistent storage Belongs to Nth element - uint8_t model_idx Is the Nth model in the element - uint16_t flags Information about what has changed - esp_ble_mesh_elem_t *element The Element to which this Model belongs - esp_ble_mesh_model_pub_t *const pub Model Publication - uint16_t keys[CONFIG_BLE_MESH_MODEL_KEY_COUNT] AppKey List - uint16_t groups[CONFIG_BLE_MESH_MODEL_GROUP_COUNT] Subscription List (group or virtual addresses) - esp_ble_mesh_model_op_t *op Model operation context - esp_ble_mesh_model_cbs_t *cb Model callback structure - void *user_data Model-specific user data - const uint16_t model_id - struct esp_ble_mesh_msg_ctx_t Message sending context. This structure is associated with struct bt_mesh_msg_ctx in mesh_access.h Public Members - uint16_t net_idx NetKey Index of the subnet through which to send the message. - uint16_t app_idx AppKey Index for message encryption. - uint16_t addr Remote address. - uint16_t recv_dst Destination address of a received message. Not used for sending. - int8_t recv_rssi RSSI of a received message. Not used for sending. - uint32_t recv_op Opcode of a received message. Not used for sending. - uint8_t recv_ttl Received TTL value. Not used for sending. - uint8_t recv_cred Security credentials of a received message. Not used for sending. - uint8_t recv_tag Tag of a received message. Not used for sending. - uint8_t send_rel Force sending reliably by using segment acknowledgement. - uint8_t send_szmic Size of TransMIC when sending a Segmented Access message. - uint8_t send_ttl TTL, or ESP_BLE_MESH_TTL_DEFAULT for default TTL. - uint8_t send_cred Security credentials used for sending the message - uint8_t send_tag Tag used for sending the message. - esp_ble_mesh_model_t *model Model corresponding to the message, no need to be initialized before sending message - bool srv_send Indicate if the message is sent by a node server model, no need to be initialized before sending message - uint16_t net_idx - struct esp_ble_mesh_prov_t Provisioning properties & capabilities. This structure is associated with struct bt_mesh_prov in mesh_access.h - struct esp_ble_mesh_comp_t Node Composition data context. This structure is associated with struct bt_mesh_comp in mesh_access.h - struct esp_ble_mesh_unprov_dev_add_t Information of the device which is going to be added for provisioning. Public Members - esp_ble_mesh_bd_addr_t addr Device address - esp_ble_mesh_addr_type_t addr_type Device address type - uint8_t uuid[16] Device UUID - uint16_t oob_info Device OOB Info ADD_DEV_START_PROV_NOW_FLAG shall not be set if the bearer has both PB-ADV and PB-GATT enabled - esp_ble_mesh_prov_bearer_t bearer Provisioning Bearer - esp_ble_mesh_bd_addr_t addr - struct esp_ble_mesh_device_delete_t Information of the device which is going to be deleted. Public Members - esp_ble_mesh_bd_addr_t addr Device address - esp_ble_mesh_addr_type_t addr_type Device address type - uint8_t uuid[16] Device UUID - union esp_ble_mesh_device_delete_t::[anonymous] [anonymous] Union of Device information - uint8_t flag BIT0: device address; BIT1: device UUID - esp_ble_mesh_bd_addr_t addr - struct esp_ble_mesh_prov_data_info_t Information of the provisioner which is going to be updated. - struct esp_ble_mesh_node_t Information of the provisioned node Public Members - esp_ble_mesh_bd_addr_t addr Node device address - esp_ble_mesh_addr_type_t addr_type Node device address type - uint8_t dev_uuid[16] Device UUID - uint16_t oob_info Node OOB information - uint16_t unicast_addr Node unicast address - uint8_t element_num Node element number - uint16_t net_idx Node NetKey Index - uint8_t flags Node key refresh flag and iv update flag - uint32_t iv_index Node IV Index - uint8_t dev_key[16] Node device key - char name[ESP_BLE_MESH_NODE_NAME_MAX_LEN + 1] Node name - uint16_t comp_length Length of Composition Data - uint8_t *comp_data Value of Composition Data - esp_ble_mesh_bd_addr_t addr - struct esp_ble_mesh_fast_prov_info_t Context of fast provisioning which need to be set. Public Members - uint16_t unicast_min Minimum unicast address used for fast provisioning - uint16_t unicast_max Maximum unicast address used for fast provisioning - uint16_t net_idx Netkey index used for fast provisioning - uint8_t flags Flags used for fast provisioning - uint32_t iv_index IV Index used for fast provisioning - uint8_t offset Offset of the UUID to be compared - uint8_t match_len Length of the UUID to be compared - uint8_t match_val[16] Value of UUID to be compared - uint16_t unicast_min - struct esp_ble_mesh_heartbeat_filter_info_t Context of Provisioner heartbeat filter information to be set - struct esp_ble_mesh_client_op_pair_t BLE Mesh client models related definitions. Client model Get/Set message opcode and corresponding Status message opcode - struct esp_ble_mesh_client_t Client Model user data context. Public Members - esp_ble_mesh_model_t *model Pointer to the client model. Initialized by the stack. - uint32_t op_pair_size Size of the op_pair - const esp_ble_mesh_client_op_pair_t *op_pair Table containing get/set message opcode and corresponding status message opcode - uint32_t publish_status Callback used to handle the received unsolicited message. Initialized by the stack. - void *internal_data Pointer to the internal data of client model - void *vendor_data Pointer to the vendor data of client model - uint8_t msg_role Role of the device (Node/Provisioner) that is going to send messages - esp_ble_mesh_model_t *model - struct esp_ble_mesh_client_common_param_t Common parameters of the messages sent by Client Model. Public Members - esp_ble_mesh_opcode_t opcode Message opcode - esp_ble_mesh_model_t *model Pointer to the client model structure - esp_ble_mesh_msg_ctx_t ctx The context used to send message - int32_t msg_timeout Timeout value (ms) to get response to the sent message Note: if using default timeout value in menuconfig, make sure to set this value to 0 - uint8_t msg_role Role of the device - Node/Provisioner - esp_ble_mesh_opcode_t opcode - struct esp_ble_mesh_state_transition_t Parameters of the server model state transition Public Functions - BLE_MESH_ATOMIC_DEFINE(flag, ESP_BLE_MESH_SERVER_FLAG_MAX) Flag used to indicate if the transition timer has been started internally. If the model which contains esp_ble_mesh_state_transition_t sets "set_auto_rsp" to ESP_BLE_MESH_SERVER_RSP_BY_APP, the handler of the timer shall be initialized by the users. And users can use this flag to indicate whether the timer is started or not. Public Members - bool just_started Indicate if the state transition has just started - uint8_t trans_time State transition time - uint8_t remain_time Remaining time of state transition - uint8_t delay Delay before starting state transition - uint32_t quo_tt Duration of each divided transition step - uint32_t counter Number of steps which the transition duration is divided - uint32_t total_duration State transition total duration - int64_t start_timestamp Time when the state transition is started - struct k_delayed_work timer Timer used for state transition - BLE_MESH_ATOMIC_DEFINE(flag, ESP_BLE_MESH_SERVER_FLAG_MAX) - struct esp_ble_mesh_last_msg_info_t Parameters of the server model received last same set message. - struct esp_ble_mesh_server_rsp_ctrl_t Parameters of the Server Model response control Public Members - uint8_t get_auto_rsp BLE Mesh Server Response Option. If get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, then the response of Client Get messages need to be replied by the application; If get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, then the response of Client Get messages will be replied by the server models; If set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, then the response of Client Set messages need to be replied by the application; If set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, then the response of Client Set messages will be replied by the server models; If status_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, then the response of Server Status messages need to be replied by the application; If status_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, then the response of Server Status messages will be replied by the server models; Response control for Client Get messages - - uint8_t set_auto_rsp Response control for Client Set messages - uint8_t status_auto_rsp Response control for Server Status messages - uint8_t get_auto_rsp Macros - ESP_BLE_MESH_SDU_MAX_LEN < The maximum length of a BLE Mesh message, including Opcode, Payload and TransMIC Length of a short Mesh MIC. - ESP_BLE_MESH_MIC_SHORT Length of a long Mesh MIC. - ESP_BLE_MESH_MIC_LONG The maximum length of a BLE Mesh provisioned node name - ESP_BLE_MESH_NODE_NAME_MAX_LEN The maximum length of a BLE Mesh unprovisioned device name - ESP_BLE_MESH_DEVICE_NAME_MAX_LEN The maximum length of settings user id - ESP_BLE_MESH_SETTINGS_UID_SIZE The default value of Random Update Interval Steps - ESP_BLE_MESH_RAND_UPDATE_INTERVAL_DEFAULT Invalid settings index - ESP_BLE_MESH_INVALID_SETTINGS_IDX Define the BLE Mesh octet 16 bytes size - ESP_BLE_MESH_OCTET16_LEN - ESP_BLE_MESH_OCTET8_LEN - ESP_BLE_MESH_CID_NVAL Special TTL value to request using configured default TTL - ESP_BLE_MESH_TTL_DEFAULT Maximum allowed TTL value - ESP_BLE_MESH_TTL_MAX - ESP_BLE_MESH_ADDR_UNASSIGNED - ESP_BLE_MESH_ADDR_ALL_NODES - ESP_BLE_MESH_ADDR_PROXIES - ESP_BLE_MESH_ADDR_FRIENDS - ESP_BLE_MESH_ADDR_RELAYS - ESP_BLE_MESH_KEY_UNUSED - ESP_BLE_MESH_KEY_DEV - ESP_BLE_MESH_KEY_PRIMARY - ESP_BLE_MESH_KEY_ANY Internal macros used to initialize array members - ESP_BLE_MESH_KEY_UNUSED_ELT_(IDX, _) - ESP_BLE_MESH_ADDR_UNASSIGNED_ELT_(IDX, _) - ESP_BLE_MESH_MODEL_KEYS_UNUSED - ESP_BLE_MESH_MODEL_GROUPS_UNASSIGNED Primary Network Key index - ESP_BLE_MESH_NET_PRIMARY Relay state value - ESP_BLE_MESH_RELAY_DISABLED - ESP_BLE_MESH_RELAY_ENABLED - ESP_BLE_MESH_RELAY_NOT_SUPPORTED Beacon state value - ESP_BLE_MESH_BEACON_DISABLED - ESP_BLE_MESH_BEACON_ENABLED - ESP_BLE_MESH_PRIVATE_BEACON_DISABLE - ESP_BLE_MESH_PRIVATE_BEACON_ENABLE GATT Proxy state value - ESP_BLE_MESH_GATT_PROXY_DISABLED - ESP_BLE_MESH_GATT_PROXY_ENABLED - ESP_BLE_MESH_GATT_PROXY_NOT_SUPPORTED - ESP_BLE_MESH_PRIVATE_GATT_PROXY_DISABLED - ESP_BLE_MESH_PRIVATE_GATT_PROXY_ENABLED - ESP_BLE_MESH_PRIVATE_GATT_PROXY_NOT_SUPPORTED - ESP_BLE_MESH_PRIVATE_NODE_IDENTITY_DISABLED - ESP_BLE_MESH_PRIVATE_NODE_IDENTITY_ENABLED - ESP_BLE_MESH_PRIVATE_NODE_IDENTITY_NOT_SUPPORTED Friend state value - ESP_BLE_MESH_FRIEND_DISABLED - ESP_BLE_MESH_FRIEND_ENABLED - ESP_BLE_MESH_FRIEND_NOT_SUPPORTED Node identity state value - ESP_BLE_MESH_NODE_IDENTITY_STOPPED - ESP_BLE_MESH_NODE_IDENTITY_RUNNING - ESP_BLE_MESH_NODE_IDENTITY_NOT_SUPPORTED Subnet Bridge state value - ESP_BLE_MESH_SUBNET_BRIDGE_DISABLED - ESP_BLE_MESH_SUBNET_BRIDGE_ENABLED Supported features - ESP_BLE_MESH_FEATURE_RELAY - ESP_BLE_MESH_FEATURE_PROXY - ESP_BLE_MESH_FEATURE_FRIEND - ESP_BLE_MESH_FEATURE_LOW_POWER - ESP_BLE_MESH_FEATURE_ALL_SUPPORTED - ESP_BLE_MESH_ADDR_IS_UNICAST(addr) - ESP_BLE_MESH_ADDR_IS_GROUP(addr) - ESP_BLE_MESH_ADDR_IS_VIRTUAL(addr) - ESP_BLE_MESH_ADDR_IS_RFU(addr) - ESP_BLE_MESH_INVALID_NODE_INDEX - ESP_BLE_MESH_PROV_RECORD_MAX_ID - ESP_BLE_MESH_TRANSMIT(count, int_ms) Encode transmission count & interval steps. Note For example, ESP_BLE_MESH_TRANSMIT(2, 20) means that the message will be sent about 90ms(count is 3, step is 1, interval is 30 ms which includes 10ms of advertising interval random delay). - Parameters count -- Number of retransmissions (first transmission is excluded). int_ms -- Interval steps in milliseconds. Must be greater than 0 and a multiple of 10. - - Returns BLE Mesh transmit value that can be used e.g. for the default values of the Configuration Model data. - ESP_BLE_MESH_GET_TRANSMIT_COUNT(transmit) Decode transmit count from a transmit value. - Parameters transmit -- Encoded transmit count & interval value. - - Returns Transmission count (actual transmissions equal to N + 1). - ESP_BLE_MESH_GET_TRANSMIT_INTERVAL(transmit) Decode transmit interval from a transmit value. - Parameters transmit -- Encoded transmit count & interval value. - - Returns Transmission interval in milliseconds. - ESP_BLE_MESH_PUBLISH_TRANSMIT(count, int_ms) Encode Publish Retransmit count & interval steps. - Parameters count -- Number of retransmissions (first transmission is excluded). int_ms -- Interval steps in milliseconds. Must be greater than 0 and a multiple of 50. - - Returns BLE Mesh transmit value that can be used e.g. for the default values of the Configuration Model data. - ESP_BLE_MESH_GET_PUBLISH_TRANSMIT_COUNT(transmit) Decode Publish Retransmit count from a given value. - Parameters transmit -- Encoded Publish Retransmit count & interval value. - - Returns Retransmission count (actual transmissions equal to N + 1). - ESP_BLE_MESH_GET_PUBLISH_TRANSMIT_INTERVAL(transmit) Decode Publish Retransmit interval from a given value. Callbacks which are not needed to be initialized by users (set with 0 and will be initialized internally) - Parameters transmit -- Encoded Publish Retransmit count & interval value. - - Returns Transmission interval in milliseconds. - ESP_BLE_MESH_PROV_STATIC_OOB_MAX_LEN Maximum length of string used by Output OOB authentication - ESP_BLE_MESH_PROV_OUTPUT_OOB_MAX_LEN Maximum length of string used by Output OOB authentication - ESP_BLE_MESH_PROV_INPUT_OOB_MAX_LEN Macros used to define message opcode - ESP_BLE_MESH_MODEL_OP_1(b0) - ESP_BLE_MESH_MODEL_OP_2(b0, b1) - ESP_BLE_MESH_MODEL_OP_3(b0, cid) This macro is associated with BLE_MESH_MODEL_CB in mesh_access.h - ESP_BLE_MESH_SIG_MODEL(_id, _op, _pub, _user_data) This macro is associated with BLE_MESH_MODEL_VND_CB in mesh_access.h - ESP_BLE_MESH_VENDOR_MODEL(_company, _id, _op, _pub, _user_data) - ESP_BLE_MESH_ELEMENT(_loc, _mods, _vnd_mods) Helper to define a BLE Mesh element within an array. In case the element has no SIG or Vendor models, the helper macro ESP_BLE_MESH_MODEL_NONE can be given instead. Note This macro is associated with BLE_MESH_ELEM in mesh_access.h - Parameters _loc -- Location Descriptor. _mods -- Array of SIG models. _vnd_mods -- Array of vendor models. - - ESP_BLE_MESH_PROV(uuid, sta_val, sta_val_len, out_size, out_act, in_size, in_act) - BT_OCTET32_LEN - BD_ADDR_LEN - ESP_BLE_MESH_ADDR_TYPE_PUBLIC - ESP_BLE_MESH_ADDR_TYPE_RANDOM - ESP_BLE_MESH_ADDR_TYPE_RPA_PUBLIC - ESP_BLE_MESH_ADDR_TYPE_RPA_RANDOM - ESP_BLE_MESH_DIRECTED_FORWARDING_DISABLED - ESP_BLE_MESH_DIRECTED_FORWARDING_ENABLED - ESP_BLE_MESH_DIRECTED_RELAY_DISABLED - ESP_BLE_MESH_DIRECTED_RELAY_ENABLED - ESP_BLE_MESH_DIRECTED_PROXY_IGNORE - ESP_BLE_MESH_DIRECTED_PROXY_USE_DEFAULT_IGNORE - ESP_BLE_MESH_DIRECTED_FRIEND_IGNORE - ESP_BLE_MESH_DIRECTED_PROXY_DISABLED - ESP_BLE_MESH_DIRECTED_PROXY_ENABLED - ESP_BLE_MESH_DIRECTED_PROXY_NOT_SUPPORTED - ESP_BLE_MESH_DIRECTED_PROXY_USE_DEF_DISABLED - ESP_BLE_MESH_DIRECTED_PROXY_USE_DEF_ENABLED - ESP_BLE_MESH_DIRECTED_PROXY_USE_DEF_NOT_SUPPORTED - ESP_BLE_MESH_DIRECTED_FRIEND_DISABLED - ESP_BLE_MESH_DIRECTED_FRIEND_ENABLED - ESP_BLE_MESH_DIRECTED_FRIEND_NOT_SUPPORTED - ESP_BLE_MESH_DIRECTED_PUB_POLICY_FLOODING - ESP_BLE_MESH_DIRECTED_PUB_POLICY_FORWARD - ESP_BLE_MESH_PROXY_USE_DIRECTED_DISABLED - ESP_BLE_MESH_PROXY_USE_DIRECTED_ENABLED - ESP_BLE_MESH_FLOODING_CRED - ESP_BLE_MESH_FRIENDSHIP_CRED - ESP_BLE_MESH_DIRECTED_CRED - ESP_BLE_MESH_TAG_SEND_SEGMENTED - ESP_BLE_MESH_TAG_IMMUTABLE_CRED - ESP_BLE_MESH_TAG_USE_DIRECTED - ESP_BLE_MESH_TAG_RELAY - ESP_BLE_MESH_TAG_FRIENDSHIP - ESP_BLE_MESH_SEG_SZMIC_SHORT - ESP_BLE_MESH_SEG_SZMIC_LONG - ESP_BLE_MESH_MODEL_PUB_DEFINE(_name, _msg_len, _role) Define a model publication context. - Parameters _name -- Variable name given to the context. _msg_len -- Length of the publication message. _role -- Role of the device which contains the model. - - ESP_BLE_MESH_MODEL_OP(_opcode, _min_len) Define a model operation context. - Parameters _opcode -- Message opcode. _min_len -- Message minimum length. - - ESP_BLE_MESH_MODEL_OP_END Define the terminator for the model operation table. Each model operation struct array must use this terminator as the end tag of the operation unit. - ESP_BLE_MESH_MODEL_NONE Helper to define an empty model array. This structure is associated with BLE_MESH_MODEL_NONE in mesh_access.h - ADD_DEV_RM_AFTER_PROV_FLAG Device will be removed from queue after provisioned successfully - ADD_DEV_START_PROV_NOW_FLAG Start provisioning device immediately - ADD_DEV_FLUSHABLE_DEV_FLAG Device can be remove when queue is full and new device is going to added - DEL_DEV_ADDR_FLAG - DEL_DEV_UUID_FLAG - PROV_DATA_NET_IDX_FLAG - PROV_DATA_FLAGS_FLAG - PROV_DATA_IV_INDEX_FLAG - ESP_BLE_MESH_HEARTBEAT_FILTER_ACCEPTLIST - ESP_BLE_MESH_HEARTBEAT_FILTER_REJECTLIST Provisioner heartbeat filter operation - ESP_BLE_MESH_HEARTBEAT_FILTER_ADD - ESP_BLE_MESH_HEARTBEAT_FILTER_REMOVE - ESP_BLE_MESH_MODEL_ID_CONFIG_SRV BLE Mesh models related Model ID and Opcode definitions. < Foundation Models - ESP_BLE_MESH_MODEL_ID_CONFIG_CLI - ESP_BLE_MESH_MODEL_ID_HEALTH_SRV - ESP_BLE_MESH_MODEL_ID_HEALTH_CLI - ESP_BLE_MESH_MODEL_ID_RPR_SRV - ESP_BLE_MESH_MODEL_ID_RPR_CLI - ESP_BLE_MESH_MODEL_ID_DF_SRV - ESP_BLE_MESH_MODEL_ID_DF_CLI - ESP_BLE_MESH_MODEL_ID_BRC_SRV - ESP_BLE_MESH_MODEL_ID_BRC_CLI - ESP_BLE_MESH_MODEL_ID_PRB_SRV - ESP_BLE_MESH_MODEL_ID_PRB_CLI - ESP_BLE_MESH_MODEL_ID_ODP_SRV - ESP_BLE_MESH_MODEL_ID_ODP_CLI - ESP_BLE_MESH_MODEL_ID_SAR_SRV - ESP_BLE_MESH_MODEL_ID_SAR_CLI - ESP_BLE_MESH_MODEL_ID_AGG_SRV - ESP_BLE_MESH_MODEL_ID_AGG_CLI - ESP_BLE_MESH_MODEL_ID_LCD_SRV - ESP_BLE_MESH_MODEL_ID_LCD_CLI - ESP_BLE_MESH_MODEL_ID_SRPL_SRV - ESP_BLE_MESH_MODEL_ID_SRPL_CLI Models from the Mesh Model Specification - ESP_BLE_MESH_MODEL_ID_GEN_ONOFF_SRV - ESP_BLE_MESH_MODEL_ID_GEN_ONOFF_CLI - ESP_BLE_MESH_MODEL_ID_GEN_LEVEL_SRV - ESP_BLE_MESH_MODEL_ID_GEN_LEVEL_CLI - ESP_BLE_MESH_MODEL_ID_GEN_DEF_TRANS_TIME_SRV - ESP_BLE_MESH_MODEL_ID_GEN_DEF_TRANS_TIME_CLI - ESP_BLE_MESH_MODEL_ID_GEN_POWER_ONOFF_SRV - ESP_BLE_MESH_MODEL_ID_GEN_POWER_ONOFF_SETUP_SRV - ESP_BLE_MESH_MODEL_ID_GEN_POWER_ONOFF_CLI - ESP_BLE_MESH_MODEL_ID_GEN_POWER_LEVEL_SRV - ESP_BLE_MESH_MODEL_ID_GEN_POWER_LEVEL_SETUP_SRV - ESP_BLE_MESH_MODEL_ID_GEN_POWER_LEVEL_CLI - ESP_BLE_MESH_MODEL_ID_GEN_BATTERY_SRV - ESP_BLE_MESH_MODEL_ID_GEN_BATTERY_CLI - ESP_BLE_MESH_MODEL_ID_GEN_LOCATION_SRV - ESP_BLE_MESH_MODEL_ID_GEN_LOCATION_SETUP_SRV - ESP_BLE_MESH_MODEL_ID_GEN_LOCATION_CLI - ESP_BLE_MESH_MODEL_ID_GEN_ADMIN_PROP_SRV - ESP_BLE_MESH_MODEL_ID_GEN_MANUFACTURER_PROP_SRV - ESP_BLE_MESH_MODEL_ID_GEN_USER_PROP_SRV - ESP_BLE_MESH_MODEL_ID_GEN_CLIENT_PROP_SRV - ESP_BLE_MESH_MODEL_ID_GEN_PROP_CLI - ESP_BLE_MESH_MODEL_ID_SENSOR_SRV - ESP_BLE_MESH_MODEL_ID_SENSOR_SETUP_SRV - ESP_BLE_MESH_MODEL_ID_SENSOR_CLI - ESP_BLE_MESH_MODEL_ID_TIME_SRV - ESP_BLE_MESH_MODEL_ID_TIME_SETUP_SRV - ESP_BLE_MESH_MODEL_ID_TIME_CLI - ESP_BLE_MESH_MODEL_ID_SCENE_SRV - ESP_BLE_MESH_MODEL_ID_SCENE_SETUP_SRV - ESP_BLE_MESH_MODEL_ID_SCENE_CLI - ESP_BLE_MESH_MODEL_ID_SCHEDULER_SRV - ESP_BLE_MESH_MODEL_ID_SCHEDULER_SETUP_SRV - ESP_BLE_MESH_MODEL_ID_SCHEDULER_CLI - ESP_BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_SRV - ESP_BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_SETUP_SRV - ESP_BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_CLI - ESP_BLE_MESH_MODEL_ID_LIGHT_CTL_SRV - ESP_BLE_MESH_MODEL_ID_LIGHT_CTL_SETUP_SRV - ESP_BLE_MESH_MODEL_ID_LIGHT_CTL_CLI - ESP_BLE_MESH_MODEL_ID_LIGHT_CTL_TEMP_SRV - ESP_BLE_MESH_MODEL_ID_LIGHT_HSL_SRV - ESP_BLE_MESH_MODEL_ID_LIGHT_HSL_SETUP_SRV - ESP_BLE_MESH_MODEL_ID_LIGHT_HSL_CLI - ESP_BLE_MESH_MODEL_ID_LIGHT_HSL_HUE_SRV - ESP_BLE_MESH_MODEL_ID_LIGHT_HSL_SAT_SRV - ESP_BLE_MESH_MODEL_ID_LIGHT_XYL_SRV - ESP_BLE_MESH_MODEL_ID_LIGHT_XYL_SETUP_SRV - ESP_BLE_MESH_MODEL_ID_LIGHT_XYL_CLI - ESP_BLE_MESH_MODEL_ID_LIGHT_LC_SRV - ESP_BLE_MESH_MODEL_ID_LIGHT_LC_SETUP_SRV - ESP_BLE_MESH_MODEL_ID_LIGHT_LC_CLI - ESP_BLE_MESH_MODEL_ID_MBT_SRV - ESP_BLE_MESH_MODEL_ID_MBT_CLI - ESP_BLE_MESH_MODEL_OP_BEACON_GET Config Beacon Get - ESP_BLE_MESH_MODEL_OP_COMPOSITION_DATA_GET Config Composition Data Get - ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_GET Config Default TTL Get - ESP_BLE_MESH_MODEL_OP_GATT_PROXY_GET Config GATT Proxy Get - ESP_BLE_MESH_MODEL_OP_RELAY_GET Config Relay Get - ESP_BLE_MESH_MODEL_OP_MODEL_PUB_GET Config Model Publication Get - ESP_BLE_MESH_MODEL_OP_FRIEND_GET Config Friend Get - ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_GET Config Heartbeat Publication Get - ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_GET Config Heartbeat Subscription Get - ESP_BLE_MESH_MODEL_OP_NET_KEY_GET Config NetKey Get - ESP_BLE_MESH_MODEL_OP_APP_KEY_GET Config AppKey Get - ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_GET Config Node Identity Get - ESP_BLE_MESH_MODEL_OP_SIG_MODEL_SUB_GET Config SIG Model Subscription Get - ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_SUB_GET Config Vendor Model Subscription Get - ESP_BLE_MESH_MODEL_OP_SIG_MODEL_APP_GET Config SIG Model App Get - ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_APP_GET Config Vendor Model App Get - ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_GET Config Key Refresh Phase Get - ESP_BLE_MESH_MODEL_OP_LPN_POLLTIMEOUT_GET Config Low Power Node PollTimeout Get - ESP_BLE_MESH_MODEL_OP_NETWORK_TRANSMIT_GET Config Network Transmit Get - ESP_BLE_MESH_MODEL_OP_BEACON_SET Config Beacon Set - ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_SET Config Default TTL Set - ESP_BLE_MESH_MODEL_OP_GATT_PROXY_SET Config GATT Proxy Set - ESP_BLE_MESH_MODEL_OP_RELAY_SET Config Relay Set - ESP_BLE_MESH_MODEL_OP_MODEL_PUB_SET Config Model Publication Set - ESP_BLE_MESH_MODEL_OP_MODEL_SUB_ADD Config Model Subscription Add - ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_ADD Config Model Subscription Virtual Address Add - ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE Config Model Subscription Delete - ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_DELETE Config Model Subscription Virtual Address Delete - ESP_BLE_MESH_MODEL_OP_MODEL_SUB_OVERWRITE Config Model Subscription Overwrite - ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_OVERWRITE Config Model Subscription Virtual Address Overwrite - ESP_BLE_MESH_MODEL_OP_NET_KEY_ADD Config NetKey Add - ESP_BLE_MESH_MODEL_OP_APP_KEY_ADD Config AppKey Add - ESP_BLE_MESH_MODEL_OP_MODEL_APP_BIND Config Model App Bind - ESP_BLE_MESH_MODEL_OP_NODE_RESET Config Node Reset - ESP_BLE_MESH_MODEL_OP_FRIEND_SET Config Friend Set - ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_SET Config Heartbeat Publication Set - ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_SET Config Heartbeat Subscription Set - ESP_BLE_MESH_MODEL_OP_NET_KEY_UPDATE Config NetKey Update - ESP_BLE_MESH_MODEL_OP_NET_KEY_DELETE Config NetKey Delete - ESP_BLE_MESH_MODEL_OP_APP_KEY_UPDATE Config AppKey Update - ESP_BLE_MESH_MODEL_OP_APP_KEY_DELETE Config AppKey Delete - ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_SET Config Node Identity Set - ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_SET Config Key Refresh Phase Set - ESP_BLE_MESH_MODEL_OP_MODEL_PUB_VIRTUAL_ADDR_SET Config Model Publication Virtual Address Set - ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE_ALL Config Model Subscription Delete All - ESP_BLE_MESH_MODEL_OP_MODEL_APP_UNBIND Config Model App Unbind - ESP_BLE_MESH_MODEL_OP_NETWORK_TRANSMIT_SET Config Network Transmit Set - ESP_BLE_MESH_MODEL_OP_BEACON_STATUS - ESP_BLE_MESH_MODEL_OP_COMPOSITION_DATA_STATUS - ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_STATUS - ESP_BLE_MESH_MODEL_OP_GATT_PROXY_STATUS - ESP_BLE_MESH_MODEL_OP_RELAY_STATUS - ESP_BLE_MESH_MODEL_OP_MODEL_PUB_STATUS - ESP_BLE_MESH_MODEL_OP_MODEL_SUB_STATUS - ESP_BLE_MESH_MODEL_OP_SIG_MODEL_SUB_LIST - ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_SUB_LIST - ESP_BLE_MESH_MODEL_OP_NET_KEY_STATUS - ESP_BLE_MESH_MODEL_OP_NET_KEY_LIST - ESP_BLE_MESH_MODEL_OP_APP_KEY_STATUS - ESP_BLE_MESH_MODEL_OP_APP_KEY_LIST - ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_STATUS - ESP_BLE_MESH_MODEL_OP_MODEL_APP_STATUS - ESP_BLE_MESH_MODEL_OP_SIG_MODEL_APP_LIST - ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_APP_LIST - ESP_BLE_MESH_MODEL_OP_NODE_RESET_STATUS - ESP_BLE_MESH_MODEL_OP_FRIEND_STATUS - ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_STATUS - ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_STATUS - ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_STATUS - ESP_BLE_MESH_MODEL_OP_LPN_POLLTIMEOUT_STATUS - ESP_BLE_MESH_MODEL_OP_NETWORK_TRANSMIT_STATUS - ESP_BLE_MESH_CFG_STATUS_SUCCESS - ESP_BLE_MESH_CFG_STATUS_INVALID_ADDRESS - ESP_BLE_MESH_CFG_STATUS_INVALID_MODEL - ESP_BLE_MESH_CFG_STATUS_INVALID_APPKEY - ESP_BLE_MESH_CFG_STATUS_INVALID_NETKEY - ESP_BLE_MESH_CFG_STATUS_INSUFFICIENT_RESOURCES - ESP_BLE_MESH_CFG_STATUS_KEY_INDEX_ALREADY_STORED - ESP_BLE_MESH_CFG_STATUS_INVALID_PUBLISH_PARAMETERS - ESP_BLE_MESH_CFG_STATUS_NOT_A_SUBSCRIBE_MODEL - ESP_BLE_MESH_CFG_STATUS_STORAGE_FAILURE - ESP_BLE_MESH_CFG_STATUS_FEATURE_NOT_SUPPORTED - ESP_BLE_MESH_CFG_STATUS_CANNOT_UPDATE - ESP_BLE_MESH_CFG_STATUS_CANNOT_REMOVE - ESP_BLE_MESH_CFG_STATUS_CANNOT_BIND - ESP_BLE_MESH_CFG_STATUS_TEMP_UNABLE_TO_CHANGE_STATE - ESP_BLE_MESH_CFG_STATUS_CANNOT_SET - ESP_BLE_MESH_CFG_STATUS_UNSPECIFIED_ERROR - ESP_BLE_MESH_CFG_STATUS_INVALID_BINDING - ESP_BLE_MESH_CFG_STATUS_INVALID_PATH_ENTRY - ESP_BLE_MESH_CFG_STATUS_CANNOT_GET - ESP_BLE_MESH_CFG_STATUS_OBSOLETE_INFO - ESP_BLE_MESH_CFG_STATUS_INVALID_BEARER - ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_GET Health Fault Get - ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_GET Health Period Get - ESP_BLE_MESH_MODEL_OP_ATTENTION_GET Health Attention Get - ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR Health Fault Clear - ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR_UNACK Health Fault Clear Unacknowledged - ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST Health Fault Test - ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST_UNACK Health Fault Test Unacknowledged - ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET Health Period Set - ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET_UNACK Health Period Set Unacknowledged - ESP_BLE_MESH_MODEL_OP_ATTENTION_SET Health Attention Set - ESP_BLE_MESH_MODEL_OP_ATTENTION_SET_UNACK Health Attention Set Unacknowledged - ESP_BLE_MESH_MODEL_OP_HEALTH_CURRENT_STATUS - ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_STATUS - ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_STATUS - ESP_BLE_MESH_MODEL_OP_ATTENTION_STATUS - ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_GET - ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_SET - ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_SET_UNACK - ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_STATUS Generic Level Message Opcode - ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_GET - ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_SET - ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_SET_UNACK - ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_STATUS - ESP_BLE_MESH_MODEL_OP_GEN_DELTA_SET - ESP_BLE_MESH_MODEL_OP_GEN_DELTA_SET_UNACK - ESP_BLE_MESH_MODEL_OP_GEN_MOVE_SET - ESP_BLE_MESH_MODEL_OP_GEN_MOVE_SET_UNACK Generic Default Transition Time Message Opcode - ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_GET - ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET - ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET_UNACK - ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_STATUS Generic Power OnOff Message Opcode - ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_GET - ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_STATUS Generic Power OnOff Setup Message Opcode - ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET - ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET_UNACK Generic Power Level Message Opcode - ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_GET - ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET - ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET_UNACK - ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_STATUS - ESP_BLE_MESH_MODEL_OP_GEN_POWER_LAST_GET - ESP_BLE_MESH_MODEL_OP_GEN_POWER_LAST_STATUS - ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_GET - ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_STATUS - ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_GET - ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_STATUS Generic Power Level Setup Message Opcode - ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET - ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET_UNACK - ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET - ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET_UNACK Generic Battery Message Opcode - ESP_BLE_MESH_MODEL_OP_GEN_BATTERY_GET - ESP_BLE_MESH_MODEL_OP_GEN_BATTERY_STATUS Generic Location Message Opcode - ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_GET - ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_STATUS - ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_GET - ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_STATUS Generic Location Setup Message Opcode - ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET - ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET_UNACK - ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET - ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET_UNACK Generic Manufacturer Property Message Opcode - ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTIES_GET - ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTIES_STATUS - ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_GET - ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET - ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET_UNACK - ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_STATUS Generic Admin Property Message Opcode - ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTIES_GET - ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTIES_STATUS - ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_GET - ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET - ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET_UNACK - ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_STATUS Generic User Property Message Opcode - ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTIES_GET - ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTIES_STATUS - ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_GET - ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET - ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET_UNACK - ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_STATUS Generic Client Property Message Opcode - ESP_BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_GET - ESP_BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_STATUS - ESP_BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_GET - ESP_BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_STATUS - ESP_BLE_MESH_MODEL_OP_SENSOR_GET - ESP_BLE_MESH_MODEL_OP_SENSOR_STATUS - ESP_BLE_MESH_MODEL_OP_SENSOR_COLUMN_GET - ESP_BLE_MESH_MODEL_OP_SENSOR_COLUMN_STATUS - ESP_BLE_MESH_MODEL_OP_SENSOR_SERIES_GET - ESP_BLE_MESH_MODEL_OP_SENSOR_SERIES_STATUS Sensor Setup Message Opcode - ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_GET - ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET - ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET_UNACK - ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_STATUS - ESP_BLE_MESH_MODEL_OP_SENSOR_SETTINGS_GET - ESP_BLE_MESH_MODEL_OP_SENSOR_SETTINGS_STATUS - ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_GET - ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_SET - ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_SET_UNACK - ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_STATUS - ESP_BLE_MESH_MODEL_OP_TIME_GET - ESP_BLE_MESH_MODEL_OP_TIME_SET - ESP_BLE_MESH_MODEL_OP_TIME_STATUS - ESP_BLE_MESH_MODEL_OP_TIME_ROLE_GET - ESP_BLE_MESH_MODEL_OP_TIME_ROLE_SET - ESP_BLE_MESH_MODEL_OP_TIME_ROLE_STATUS - ESP_BLE_MESH_MODEL_OP_TIME_ZONE_GET - ESP_BLE_MESH_MODEL_OP_TIME_ZONE_SET - ESP_BLE_MESH_MODEL_OP_TIME_ZONE_STATUS - ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_GET - ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_SET - ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_STATUS Scene Message Opcode - ESP_BLE_MESH_MODEL_OP_SCENE_GET - ESP_BLE_MESH_MODEL_OP_SCENE_RECALL - ESP_BLE_MESH_MODEL_OP_SCENE_RECALL_UNACK - ESP_BLE_MESH_MODEL_OP_SCENE_STATUS - ESP_BLE_MESH_MODEL_OP_SCENE_REGISTER_GET - ESP_BLE_MESH_MODEL_OP_SCENE_REGISTER_STATUS Scene Setup Message Opcode - ESP_BLE_MESH_MODEL_OP_SCENE_STORE - ESP_BLE_MESH_MODEL_OP_SCENE_STORE_UNACK - ESP_BLE_MESH_MODEL_OP_SCENE_DELETE - ESP_BLE_MESH_MODEL_OP_SCENE_DELETE_UNACK Scheduler Message Opcode - ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_GET - ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_STATUS - ESP_BLE_MESH_MODEL_OP_SCHEDULER_GET - ESP_BLE_MESH_MODEL_OP_SCHEDULER_STATUS Scheduler Setup Message Opcode - ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET - ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LAST_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LAST_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_STATUS Light Lightness Setup Message Opcode - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET_UNACK Light CTL Message Opcode - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_STATUS Light CTL Setup Message Opcode - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET_UNACK Light HSL Message Opcode - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_TARGET_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_TARGET_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_STATUS Light HSL Setup Message Opcode - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET_UNACK Light xyL Message Opcode - ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_TARGET_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_TARGET_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_STATUS Light xyL Setup Message Opcode - ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET_UNACK Light Control Message Opcode - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_STATUS - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_GET - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET_UNACK - ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_STATUS - ESP_BLE_MESH_MODEL_STATUS_SUCCESS - ESP_BLE_MESH_MODEL_STATUS_CANNOT_SET_RANGE_MIN - ESP_BLE_MESH_MODEL_STATUS_CANNOT_SET_RANGE_MAX - ESP_BLE_MESH_SERVER_RSP_BY_APP Response need to be sent in the application - ESP_BLE_MESH_SERVER_AUTO_RSP Response will be sent internally Type Definitions - typedef uint8_t esp_ble_mesh_octet16_t[ESP_BLE_MESH_OCTET16_LEN] Define the BLE Mesh octet 8 bytes size - typedef uint8_t esp_ble_mesh_octet8_t[ESP_BLE_MESH_OCTET8_LEN] Invalid Company ID - typedef uint32_t esp_ble_mesh_cb_t - typedef uint8_t UINT8 - typedef uint16_t UINT16 - typedef uint32_t UINT32 - typedef uint64_t UINT64 - typedef uint8_t BD_ADDR[BD_ADDR_LEN] - typedef uint8_t esp_ble_mesh_bd_addr_t[BD_ADDR_LEN] - typedef uint8_t esp_ble_mesh_addr_type_t BLE device address type. - typedef struct esp_ble_mesh_model esp_ble_mesh_model_t - typedef uint8_t esp_ble_mesh_dev_add_flag_t - typedef uint32_t esp_ble_mesh_opcode_config_client_get_t esp_ble_mesh_opcode_config_client_get_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by esp_ble_mesh_config_client_get_state. The following opcodes will only be used in the esp_ble_mesh_config_client_get_state function. - typedef uint32_t esp_ble_mesh_opcode_config_client_set_t esp_ble_mesh_opcode_config_client_set_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by esp_ble_mesh_config_client_set_state. The following opcodes will only be used in the esp_ble_mesh_config_client_set_state function. - typedef uint32_t esp_ble_mesh_opcode_config_status_t esp_ble_mesh_opcode_config_status_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by the Config Model messages The following opcodes are used by the BLE Mesh Config Server Model internally to respond to the Config Client Model's request messages. - typedef uint8_t esp_ble_mesh_cfg_status_t This typedef is only used to indicate the status code contained in some of the Configuration Server Model status message. - typedef uint32_t esp_ble_mesh_opcode_health_client_get_t esp_ble_mesh_opcode_health_client_get_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by esp_ble_mesh_health_client_get_state. The following opcodes will only be used in the esp_ble_mesh_health_client_get_state function. - typedef uint32_t esp_ble_mesh_opcode_health_client_set_t esp_ble_mesh_opcode_health_client_set_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by esp_ble_mesh_health_client_set_state. The following opcodes will only be used in the esp_ble_mesh_health_client_set_state function. - typedef uint32_t esp_ble_mesh_health_model_status_t esp_ble_mesh_health_model_status_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by the Health Model messages. The following opcodes are used by the BLE Mesh Health Server Model internally to respond to the Health Client Model's request messages. - typedef uint32_t esp_ble_mesh_generic_message_opcode_t esp_ble_mesh_generic_message_opcode_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by functions esp_ble_mesh_generic_client_get_state & esp_ble_mesh_generic_client_set_state. Generic OnOff Message Opcode - typedef uint32_t esp_ble_mesh_sensor_message_opcode_t esp_ble_mesh_sensor_message_opcode_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by functions esp_ble_mesh_sensor_client_get_state & esp_ble_mesh_sensor_client_set_state. Sensor Message Opcode - typedef uint32_t esp_ble_mesh_time_scene_message_opcode_t esp_ble_mesh_time_scene_message_opcode_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by functions esp_ble_mesh_time_scene_client_get_state & esp_ble_mesh_time_scene_client_set_state. Time Message Opcode - typedef uint32_t esp_ble_mesh_light_message_opcode_t esp_ble_mesh_light_message_opcode_t belongs to esp_ble_mesh_opcode_t, this typedef is only used to locate the opcodes used by functions esp_ble_mesh_light_client_get_state & esp_ble_mesh_light_client_set_state. Light Lightness Message Opcode - typedef uint32_t esp_ble_mesh_opcode_t End of defines of esp_ble_mesh_opcode_t - typedef uint8_t esp_ble_mesh_model_status_t This typedef is only used to indicate the status code contained in some of the server models (e.g. Generic Server Model) status message. Enumerations - enum esp_ble_mesh_cb_type_t Values: - enumerator ESP_BLE_MESH_TYPE_PROV_CB - enumerator ESP_BLE_MESH_TYPE_OUTPUT_NUM_CB - enumerator ESP_BLE_MESH_TYPE_OUTPUT_STR_CB - enumerator ESP_BLE_MESH_TYPE_INTPUT_CB - enumerator ESP_BLE_MESH_TYPE_LINK_OPEN_CB - enumerator ESP_BLE_MESH_TYPE_LINK_CLOSE_CB - enumerator ESP_BLE_MESH_TYPE_COMPLETE_CB - enumerator ESP_BLE_MESH_TYPE_RESET_CB - enumerator ESP_BLE_MESH_TYPE_PROV_CB - enum esp_ble_mesh_oob_method_t Values: - enumerator ESP_BLE_MESH_NO_OOB - enumerator ESP_BLE_MESH_STATIC_OOB - enumerator ESP_BLE_MESH_OUTPUT_OOB - enumerator ESP_BLE_MESH_INPUT_OOB - enumerator ESP_BLE_MESH_NO_OOB - enum esp_ble_mesh_output_action_t Values: - enumerator ESP_BLE_MESH_NO_OUTPUT - enumerator ESP_BLE_MESH_BLINK - enumerator ESP_BLE_MESH_BEEP - enumerator ESP_BLE_MESH_VIBRATE - enumerator ESP_BLE_MESH_DISPLAY_NUMBER - enumerator ESP_BLE_MESH_DISPLAY_STRING - enumerator ESP_BLE_MESH_NO_OUTPUT - enum esp_ble_mesh_input_action_t Values: - enumerator ESP_BLE_MESH_NO_INPUT - enumerator ESP_BLE_MESH_PUSH - enumerator ESP_BLE_MESH_TWIST - enumerator ESP_BLE_MESH_ENTER_NUMBER - enumerator ESP_BLE_MESH_ENTER_STRING - enumerator ESP_BLE_MESH_NO_INPUT - enum esp_ble_mesh_prov_bearer_t Values: - enumerator ESP_BLE_MESH_PROV_ADV - enumerator ESP_BLE_MESH_PROV_GATT - enumerator ESP_BLE_MESH_PROV_ADV - enum esp_ble_mesh_prov_oob_info_t Values: - enumerator ESP_BLE_MESH_PROV_OOB_OTHER - enumerator ESP_BLE_MESH_PROV_OOB_URI - enumerator ESP_BLE_MESH_PROV_OOB_2D_CODE - enumerator ESP_BLE_MESH_PROV_OOB_BAR_CODE - enumerator ESP_BLE_MESH_PROV_OOB_NFC - enumerator ESP_BLE_MESH_PROV_OOB_NUMBER - enumerator ESP_BLE_MESH_PROV_OOB_STRING - enumerator ESP_BLE_MESH_PROV_CERT_BASED - enumerator ESP_BLE_MESH_PROV_RECORDS - enumerator ESP_BLE_MESH_PROV_OOB_ON_BOX - enumerator ESP_BLE_MESH_PROV_OOB_IN_BOX - enumerator ESP_BLE_MESH_PROV_OOB_ON_PAPER - enumerator ESP_BLE_MESH_PROV_OOB_IN_MANUAL - enumerator ESP_BLE_MESH_PROV_OOB_ON_DEV - enumerator ESP_BLE_MESH_PROV_OOB_OTHER - enum esp_ble_mesh_dev_role_t Values: - enumerator ROLE_NODE - enumerator ROLE_PROVISIONER - enumerator ROLE_FAST_PROV - enumerator ROLE_NODE - enum esp_ble_mesh_fast_prov_action_t Values: - enumerator FAST_PROV_ACT_NONE - enumerator FAST_PROV_ACT_ENTER - enumerator FAST_PROV_ACT_SUSPEND - enumerator FAST_PROV_ACT_EXIT - enumerator FAST_PROV_ACT_MAX - enumerator FAST_PROV_ACT_NONE - enum esp_ble_mesh_proxy_filter_type_t Values: - enumerator PROXY_FILTER_WHITELIST - enumerator PROXY_FILTER_BLACKLIST - enumerator PROXY_FILTER_WHITELIST - enum esp_ble_mesh_prov_cb_event_t Values: - enumerator ESP_BLE_MESH_PROV_REGISTER_COMP_EVT Initialize BLE Mesh provisioning capabilities and internal data information completion event - enumerator ESP_BLE_MESH_NODE_SET_UNPROV_DEV_NAME_COMP_EVT Set the unprovisioned device name completion event - enumerator ESP_BLE_MESH_NODE_PROV_ENABLE_COMP_EVT Enable node provisioning functionality completion event - enumerator ESP_BLE_MESH_NODE_PROV_DISABLE_COMP_EVT Disable node provisioning functionality completion event - enumerator ESP_BLE_MESH_NODE_PROV_LINK_OPEN_EVT Establish a BLE Mesh link event - enumerator ESP_BLE_MESH_NODE_PROV_LINK_CLOSE_EVT Close a BLE Mesh link event - enumerator ESP_BLE_MESH_NODE_PROV_OOB_PUB_KEY_EVT Generate Node input OOB public key event - enumerator ESP_BLE_MESH_NODE_PROV_OUTPUT_NUMBER_EVT Generate Node Output Number event - enumerator ESP_BLE_MESH_NODE_PROV_OUTPUT_STRING_EVT Generate Node Output String event - enumerator ESP_BLE_MESH_NODE_PROV_INPUT_EVT Event requiring the user to input a number or string - enumerator ESP_BLE_MESH_NODE_PROV_COMPLETE_EVT Provisioning done event - enumerator ESP_BLE_MESH_NODE_PROV_RESET_EVT Provisioning reset event - enumerator ESP_BLE_MESH_NODE_PROV_SET_OOB_PUB_KEY_COMP_EVT Node set oob public key completion event - enumerator ESP_BLE_MESH_NODE_PROV_INPUT_NUMBER_COMP_EVT Node input number completion event - enumerator ESP_BLE_MESH_NODE_PROV_INPUT_STRING_COMP_EVT Node input string completion event - enumerator ESP_BLE_MESH_NODE_PROXY_IDENTITY_ENABLE_COMP_EVT Enable BLE Mesh Proxy Identity advertising completion event - enumerator ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_ENABLE_COMP_EVT Enable BLE Mesh Private Proxy Identity advertising completion event - enumerator ESP_BLE_MESH_NODE_PRIVATE_PROXY_IDENTITY_DISABLE_COMP_EVT Disable BLE Mesh Private Proxy Identity advertising completion event - enumerator ESP_BLE_MESH_NODE_PROXY_GATT_ENABLE_COMP_EVT Enable BLE Mesh GATT Proxy Service completion event - enumerator ESP_BLE_MESH_NODE_PROXY_GATT_DISABLE_COMP_EVT Disable BLE Mesh GATT Proxy Service completion event - enumerator ESP_BLE_MESH_NODE_ADD_LOCAL_NET_KEY_COMP_EVT Node add NetKey locally completion event - enumerator ESP_BLE_MESH_NODE_ADD_LOCAL_APP_KEY_COMP_EVT Node add AppKey locally completion event - enumerator ESP_BLE_MESH_NODE_BIND_APP_KEY_TO_MODEL_COMP_EVT Node bind AppKey to model locally completion event - enumerator ESP_BLE_MESH_PROVISIONER_PROV_ENABLE_COMP_EVT Provisioner enable provisioning functionality completion event - enumerator ESP_BLE_MESH_PROVISIONER_PROV_DISABLE_COMP_EVT Provisioner disable provisioning functionality completion event - enumerator ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT Provisioner receives unprovisioned device beacon event - enumerator ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_EVT Provisioner read unprovisioned device OOB public key event - enumerator ESP_BLE_MESH_PROVISIONER_PROV_INPUT_EVT Provisioner input value for provisioning procedure event - enumerator ESP_BLE_MESH_PROVISIONER_PROV_OUTPUT_EVT Provisioner output value for provisioning procedure event - enumerator ESP_BLE_MESH_PROVISIONER_PROV_LINK_OPEN_EVT Provisioner establish a BLE Mesh link event - enumerator ESP_BLE_MESH_PROVISIONER_PROV_LINK_CLOSE_EVT Provisioner close a BLE Mesh link event - enumerator ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT Provisioner provisioning done event - enumerator ESP_BLE_MESH_PROVISIONER_CERT_BASED_PROV_START_EVT Provisioner initiate a certificate based provisioning - enumerator ESP_BLE_MESH_PROVISIONER_RECV_PROV_RECORDS_LIST_EVT Provisioner receive provisioning records list event - enumerator ESP_BLE_MESH_PROVISIONER_PROV_RECORD_RECV_COMP_EVT Provisioner receive provisioning record complete event - enumerator ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORDS_GET_EVT Provisioner send provisioning records get to device event - enumerator ESP_BLE_MESH_PROVISIONER_SEND_PROV_RECORD_REQUEST_EVT Provisioner send provisioning record request to device event - enumerator ESP_BLE_MESH_PROVISIONER_SEND_PROV_INVITE_EVT Provisioner send provisioning invite to device event - enumerator ESP_BLE_MESH_PROVISIONER_SEND_LINK_CLOSE_EVT Provisioner send link close to device event - enumerator ESP_BLE_MESH_PROVISIONER_ADD_UNPROV_DEV_COMP_EVT Provisioner add a device to the list which contains devices that are waiting/going to be provisioned completion event - enumerator ESP_BLE_MESH_PROVISIONER_PROV_DEV_WITH_ADDR_COMP_EVT Provisioner start to provision an unprovisioned device completion event - enumerator ESP_BLE_MESH_PROVISIONER_DELETE_DEV_COMP_EVT Provisioner delete a device from the list, close provisioning link with the device completion event - enumerator ESP_BLE_MESH_PROVISIONER_SET_DEV_UUID_MATCH_COMP_EVT Provisioner set the value to be compared with part of the unprovisioned device UUID completion event - enumerator ESP_BLE_MESH_PROVISIONER_SET_PROV_DATA_INFO_COMP_EVT Provisioner set net_idx/flags/iv_index used for provisioning completion event - enumerator ESP_BLE_MESH_PROVISIONER_SET_STATIC_OOB_VALUE_COMP_EVT Provisioner set static oob value used for provisioning completion event - enumerator ESP_BLE_MESH_PROVISIONER_SET_PRIMARY_ELEM_ADDR_COMP_EVT Provisioner set unicast address of primary element completion event - enumerator ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_COMP_EVT Provisioner read unprovisioned device OOB public key completion event - enumerator ESP_BLE_MESH_PROVISIONER_PROV_INPUT_NUMBER_COMP_EVT Provisioner input number completion event - enumerator ESP_BLE_MESH_PROVISIONER_PROV_INPUT_STRING_COMP_EVT Provisioner input string completion event - enumerator ESP_BLE_MESH_PROVISIONER_SET_NODE_NAME_COMP_EVT Provisioner set node name completion event - enumerator ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_APP_KEY_COMP_EVT Provisioner add local app key completion event - enumerator ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_APP_KEY_COMP_EVT Provisioner update local app key completion event - enumerator ESP_BLE_MESH_PROVISIONER_BIND_APP_KEY_TO_MODEL_COMP_EVT Provisioner bind local model with local app key completion event - enumerator ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_NET_KEY_COMP_EVT Provisioner add local network key completion event - enumerator ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_NET_KEY_COMP_EVT Provisioner update local network key completion event - enumerator ESP_BLE_MESH_PROVISIONER_STORE_NODE_COMP_DATA_COMP_EVT Provisioner store node composition data completion event - enumerator ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_UUID_COMP_EVT Provisioner delete node with uuid completion event - enumerator ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_ADDR_COMP_EVT Provisioner delete node with unicast address completion event - enumerator ESP_BLE_MESH_PROVISIONER_ENABLE_HEARTBEAT_RECV_COMP_EVT Provisioner start to receive heartbeat message completion event - enumerator ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_TYPE_COMP_EVT Provisioner set the heartbeat filter type completion event - enumerator ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_INFO_COMP_EVT Provisioner set the heartbeat filter information completion event - enumerator ESP_BLE_MESH_PROVISIONER_RECV_HEARTBEAT_MESSAGE_EVT Provisioner receive heartbeat message event - enumerator ESP_BLE_MESH_PROVISIONER_DIRECT_ERASE_SETTINGS_COMP_EVT Provisioner directly erase settings completion event - enumerator ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_INDEX_COMP_EVT Provisioner open settings with index completion event - enumerator ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_UID_COMP_EVT Provisioner open settings with user id completion event - enumerator ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_INDEX_COMP_EVT Provisioner close settings with index completion event - enumerator ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_UID_COMP_EVT Provisioner close settings with user id completion event - enumerator ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_INDEX_COMP_EVT Provisioner delete settings with index completion event - enumerator ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_UID_COMP_EVT Provisioner delete settings with user id completion event - enumerator ESP_BLE_MESH_SET_FAST_PROV_INFO_COMP_EVT Set fast provisioning information (e.g. unicast address range, net_idx, etc.) completion event - enumerator ESP_BLE_MESH_SET_FAST_PROV_ACTION_COMP_EVT Set fast provisioning action completion event - enumerator ESP_BLE_MESH_HEARTBEAT_MESSAGE_RECV_EVT Receive Heartbeat message event - enumerator ESP_BLE_MESH_LPN_ENABLE_COMP_EVT Enable Low Power Node completion event - enumerator ESP_BLE_MESH_LPN_DISABLE_COMP_EVT Disable Low Power Node completion event - enumerator ESP_BLE_MESH_LPN_POLL_COMP_EVT Low Power Node send Friend Poll completion event - enumerator ESP_BLE_MESH_LPN_FRIENDSHIP_ESTABLISH_EVT Low Power Node establishes friendship event - enumerator ESP_BLE_MESH_LPN_FRIENDSHIP_TERMINATE_EVT Low Power Node terminates friendship event - enumerator ESP_BLE_MESH_FRIEND_FRIENDSHIP_ESTABLISH_EVT Friend Node establishes friendship event - enumerator ESP_BLE_MESH_FRIEND_FRIENDSHIP_TERMINATE_EVT Friend Node terminates friendship event - enumerator ESP_BLE_MESH_PROXY_CLIENT_RECV_ADV_PKT_EVT Proxy Client receives Network ID advertising packet event - enumerator ESP_BLE_MESH_PROXY_CLIENT_CONNECTED_EVT Proxy Client establishes connection successfully event - enumerator ESP_BLE_MESH_PROXY_CLIENT_DISCONNECTED_EVT Proxy Client terminates connection successfully event - enumerator ESP_BLE_MESH_PROXY_CLIENT_RECV_FILTER_STATUS_EVT Proxy Client receives Proxy Filter Status event - enumerator ESP_BLE_MESH_PROXY_CLIENT_CONNECT_COMP_EVT Proxy Client connect completion event - enumerator ESP_BLE_MESH_PROXY_CLIENT_DISCONNECT_COMP_EVT Proxy Client disconnect completion event - enumerator ESP_BLE_MESH_PROXY_CLIENT_SET_FILTER_TYPE_COMP_EVT Proxy Client set filter type completion event - enumerator ESP_BLE_MESH_PROXY_CLIENT_ADD_FILTER_ADDR_COMP_EVT Proxy Client add filter address completion event - enumerator ESP_BLE_MESH_PROXY_CLIENT_REMOVE_FILTER_ADDR_COMP_EVT Proxy Client remove filter address completion event - enumerator ESP_BLE_MESH_PROXY_CLIENT_DIRECTED_PROXY_SET_COMP_EVT Proxy Client directed proxy set completion event - enumerator ESP_BLE_MESH_PROXY_SERVER_CONNECTED_EVT Proxy Server establishes connection successfully event - enumerator ESP_BLE_MESH_PROXY_SERVER_DISCONNECTED_EVT Proxy Server terminates connection successfully event - enumerator ESP_BLE_MESH_PROXY_CLIENT_SEND_SOLIC_PDU_COMP_EVT Proxy Client send Solicitation PDU completion event - enumerator ESP_BLE_MESH_MODEL_SUBSCRIBE_GROUP_ADDR_COMP_EVT Local model subscribes group address completion event - enumerator ESP_BLE_MESH_MODEL_UNSUBSCRIBE_GROUP_ADDR_COMP_EVT Local model unsubscribes group address completion event - enumerator ESP_BLE_MESH_DEINIT_MESH_COMP_EVT De-initialize BLE Mesh stack completion event - enumerator ESP_BLE_MESH_PROV_EVT_MAX - enumerator ESP_BLE_MESH_PROV_REGISTER_COMP_EVT - enum [anonymous] BLE Mesh server models related definitions. This enum value is the flag of transition timer operation Values: - enumerator ESP_BLE_MESH_SERVER_TRANS_TIMER_START - enumerator ESP_BLE_MESH_SERVER_FLAG_MAX - enumerator ESP_BLE_MESH_SERVER_TRANS_TIMER_START - enum esp_ble_mesh_server_state_type_t This enum value is the type of server model states Values: - enumerator ESP_BLE_MESH_GENERIC_ONOFF_STATE - enumerator ESP_BLE_MESH_GENERIC_LEVEL_STATE - enumerator ESP_BLE_MESH_GENERIC_ONPOWERUP_STATE - enumerator ESP_BLE_MESH_GENERIC_POWER_ACTUAL_STATE - enumerator ESP_BLE_MESH_LIGHT_LIGHTNESS_ACTUAL_STATE - enumerator ESP_BLE_MESH_LIGHT_LIGHTNESS_LINEAR_STATE - enumerator ESP_BLE_MESH_LIGHT_CTL_LIGHTNESS_STATE - enumerator ESP_BLE_MESH_LIGHT_CTL_TEMP_DELTA_UV_STATE - enumerator ESP_BLE_MESH_LIGHT_HSL_STATE - enumerator ESP_BLE_MESH_LIGHT_HSL_LIGHTNESS_STATE - enumerator ESP_BLE_MESH_LIGHT_HSL_HUE_STATE - enumerator ESP_BLE_MESH_LIGHT_HSL_SATURATION_STATE - enumerator ESP_BLE_MESH_LIGHT_XYL_LIGHTNESS_STATE - enumerator ESP_BLE_MESH_LIGHT_LC_LIGHT_ONOFF_STATE - enumerator ESP_BLE_MESH_SERVER_MODEL_STATE_MAX - enumerator ESP_BLE_MESH_GENERIC_ONOFF_STATE - enum esp_ble_mesh_model_cb_event_t Values: - enumerator ESP_BLE_MESH_MODEL_OPERATION_EVT User-defined models receive messages from peer devices (e.g. get, set, status, etc) event - enumerator ESP_BLE_MESH_MODEL_SEND_COMP_EVT User-defined models send messages completion event - enumerator ESP_BLE_MESH_MODEL_PUBLISH_COMP_EVT User-defined models publish messages completion event - enumerator ESP_BLE_MESH_CLIENT_MODEL_RECV_PUBLISH_MSG_EVT User-defined client models receive publish messages event - enumerator ESP_BLE_MESH_CLIENT_MODEL_SEND_TIMEOUT_EVT Timeout event for the user-defined client models that failed to receive response from peer server models - enumerator ESP_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT When a model is configured to publish messages periodically, this event will occur during every publish period - enumerator ESP_BLE_MESH_SERVER_MODEL_UPDATE_STATE_COMP_EVT Server models update state value completion event - enumerator ESP_BLE_MESH_MODEL_EVT_MAX - enumerator ESP_BLE_MESH_MODEL_OPERATION_EVT ESP-BLE-MESH Core API Reference This section contains ESP-BLE-MESH Core related APIs, which can be used to initialize ESP-BLE-MESH stack, provision, send/publish messages, etc. This API reference covers six components: ESP-BLE-MESH Stack Initialization Header File components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_common_api.h This header file can be included with: #include "esp_ble_mesh_common_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_init(esp_ble_mesh_prov_t *prov, esp_ble_mesh_comp_t *comp) Initialize BLE Mesh module. This API initializes provisioning capabilities and composition data information. Note After calling this API, the device needs to call esp_ble_mesh_prov_enable() to enable provisioning functionality again. - Parameters prov -- [in] Pointer to the device provisioning capabilities. This pointer must remain valid during the lifetime of the BLE Mesh device. comp -- [in] Pointer to the device composition data information. This pointer must remain valid during the lifetime of the BLE Mesh device. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_deinit(esp_ble_mesh_deinit_param_t *param) De-initialize BLE Mesh module. Note This function shall be invoked after esp_ble_mesh_client_model_deinit(). - Parameters param -- [in] Pointer to the structure of BLE Mesh deinit parameters. - Returns ESP_OK on success or error code otherwise. Reading of Local Data Information Header File components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_local_data_operation_api.h This header file can be included with: #include "esp_ble_mesh_local_data_operation_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - int32_t esp_ble_mesh_get_model_publish_period(esp_ble_mesh_model_t *model) Get the model publish period, the unit is ms. - Parameters model -- [in] Model instance pointer. - Returns Publish period value on success, 0 or (negative) error code from errno.h on failure. - uint16_t esp_ble_mesh_get_primary_element_address(void) Get the address of the primary element. - Returns Address of the primary element on success, or ESP_BLE_MESH_ADDR_UNASSIGNED on failure which means the device has not been provisioned. - uint16_t *esp_ble_mesh_is_model_subscribed_to_group(esp_ble_mesh_model_t *model, uint16_t group_addr) Check if the model has subscribed to the given group address. Note: E.g., once a status message is received and the destination address is a group address, the model uses this API to check if it is successfully subscribed to the given group address. - Parameters model -- [in] Pointer to the model. group_addr -- [in] Group address. - - Returns Pointer to the group address within the Subscription List of the model on success, or NULL on failure which means the model has not subscribed to the given group address. Note: With the pointer to the group address returned, you can reset the group address to 0x0000 in order to unsubscribe the model from the group. - esp_ble_mesh_elem_t *esp_ble_mesh_find_element(uint16_t element_addr) Find the BLE Mesh element pointer via the element address. - Parameters element_addr -- [in] Element address. - Returns Pointer to the element on success, or NULL on failure. - uint8_t esp_ble_mesh_get_element_count(void) Get the number of elements that have been registered. - Returns Number of elements. - esp_ble_mesh_model_t *esp_ble_mesh_find_vendor_model(const esp_ble_mesh_elem_t *element, uint16_t company_id, uint16_t model_id) Find the Vendor specific model with the given element, the company ID and the Vendor Model ID. - Parameters element -- [in] Element to which the model belongs. company_id -- [in] A 16-bit company identifier assigned by the Bluetooth SIG. model_id -- [in] A 16-bit vendor-assigned model identifier. - - Returns Pointer to the Vendor Model on success, or NULL on failure which means the Vendor Model is not found. - esp_ble_mesh_model_t *esp_ble_mesh_find_sig_model(const esp_ble_mesh_elem_t *element, uint16_t model_id) Find the SIG model with the given element and Model id. - Parameters element -- [in] Element to which the model belongs. model_id -- [in] SIG model identifier. - - Returns Pointer to the SIG Model on success, or NULL on failure which means the SIG Model is not found. - const esp_ble_mesh_comp_t *esp_ble_mesh_get_composition_data(void) Get the Composition data which has been registered. - Returns Pointer to the Composition data on success, or NULL on failure which means the Composition data is not initialized. - esp_err_t esp_ble_mesh_model_subscribe_group_addr(uint16_t element_addr, uint16_t company_id, uint16_t model_id, uint16_t group_addr) A local model of node or Provisioner subscribes a group address. Note This function shall not be invoked before node is provisioned or Provisioner is enabled. - Parameters element_addr -- [in] Unicast address of the element to which the model belongs. company_id -- [in] A 16-bit company identifier. model_id -- [in] A 16-bit model identifier. group_addr -- [in] The group address to be subscribed. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_model_unsubscribe_group_addr(uint16_t element_addr, uint16_t company_id, uint16_t model_id, uint16_t group_addr) A local model of node or Provisioner unsubscribes a group address. Note This function shall not be invoked before node is provisioned or Provisioner is enabled. - Parameters element_addr -- [in] Unicast address of the element to which the model belongs. company_id -- [in] A 16-bit company identifier. model_id -- [in] A 16-bit model identifier. group_addr -- [in] The subscribed group address. - - Returns ESP_OK on success or error code otherwise. - const uint8_t *esp_ble_mesh_node_get_local_net_key(uint16_t net_idx) This function is called by Node to get the local NetKey. - Parameters net_idx -- [in] NetKey index. - Returns NetKey on success, or NULL on failure. - const uint8_t *esp_ble_mesh_node_get_local_app_key(uint16_t app_idx) This function is called by Node to get the local AppKey. - Parameters app_idx -- [in] AppKey index. - Returns AppKey on success, or NULL on failure. - esp_err_t esp_ble_mesh_node_add_local_net_key(const uint8_t net_key[16], uint16_t net_idx) This function is called by Node to add a local NetKey. Note This function can only be called after the device is provisioned. - Parameters net_key -- [in] NetKey to be added. net_idx -- [in] NetKey Index. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_node_add_local_app_key(const uint8_t app_key[16], uint16_t net_idx, uint16_t app_idx) This function is called by Node to add a local AppKey. Note The net_idx must be an existing one. This function can only be called after the device is provisioned. - Parameters app_key -- [in] AppKey to be added. net_idx -- [in] NetKey Index. app_idx -- [in] AppKey Index. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_node_bind_app_key_to_local_model(uint16_t element_addr, uint16_t company_id, uint16_t model_id, uint16_t app_idx) This function is called by Node to bind AppKey to model locally. Note If going to bind app_key with local vendor model, the company_id shall be set to 0xFFFF. This function can only be called after the device is provisioned. - Parameters element_addr -- [in] Node local element address company_id -- [in] Node local company id model_id -- [in] Node local model id app_idx -- [in] Node local appkey index - - Returns ESP_OK on success or error code otherwise. Low Power Operation (Updating) Header File components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_low_power_api.h This header file can be included with: #include "esp_ble_mesh_low_power_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_lpn_enable(void) Enable BLE Mesh device LPN functionality. Note This API enables LPN functionality. Once called, the proper Friend Request will be sent. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_lpn_disable(bool force) Disable BLE Mesh device LPN functionality. - Parameters force -- [in] when disabling LPN functionality, use this flag to indicate whether directly clear corresponding information or just send friend clear to disable it if friendship has already been established. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_lpn_poll(void) LPN tries to poll messages from the Friend Node. Note The Friend Poll message is sent by a Low Power node to ask the Friend node to send a message that it has stored for the Low Power node. Users can call this API to send Friend Poll message manually. If this API is not invoked, the bottom layer of the Low Power node will send Friend Poll before the PollTimeout timer expires. If the corresponding Friend Update is received and MD is set to 0, which means there are no messages for the Low Power node, then the Low Power node will stop scanning. - Returns ESP_OK on success or error code otherwise. Send/Publish Messages, Add Local AppKey, Etc. Header File components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_networking_api.h This header file can be included with: #include "esp_ble_mesh_networking_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_custom_model_callback(esp_ble_mesh_model_cb_t callback) Register BLE Mesh callback for user-defined models' operations. This callback can report the following events generated for the user-defined models: Call back the messages received by user-defined client and server models to the application layer; If users call esp_ble_mesh_server/client_model_send, this callback notifies the application layer of the send_complete event; If user-defined client model sends a message that requires response, and the response message is received after the timer expires, the response message will be reported to the application layer as published by a peer device; If the user-defined client model fails to receive the response message during a specified period of time, a timeout event will be reported to the application layer. Note The client models (i.e. Config Client model, Health Client model, Generic Client models, Sensor Client model, Scene Client model and Lighting Client models) that have been realized internally have their specific register functions. For example, esp_ble_mesh_register_config_client_callback is the register function for Config Client Model. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - - esp_err_t esp_ble_mesh_model_msg_opcode_init(uint8_t *data, uint32_t opcode) Add the message opcode to the beginning of the model message before sending or publishing the model message. Note This API is only used to set the opcode of the message. - Parameters data -- [in] Pointer to the message data. opcode -- [in] The message opcode. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_client_model_init(esp_ble_mesh_model_t *model) Initialize the user-defined client model. All user-defined client models shall call this function to initialize the client model internal data. Node: Before calling this API, the op_pair_size and op_pair variables within the user_data(defined using esp_ble_mesh_client_t_) of the client model need to be initialized. - Parameters model -- [in] BLE Mesh Client model to which the message belongs. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_client_model_deinit(esp_ble_mesh_model_t *model) De-initialize the user-defined client model. Note This function shall be invoked before esp_ble_mesh_deinit() is called. - Parameters model -- [in] Pointer of the Client model. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_server_model_send_msg(esp_ble_mesh_model_t *model, esp_ble_mesh_msg_ctx_t *ctx, uint32_t opcode, uint16_t length, uint8_t *data) Send server model messages(such as server model status messages). - Parameters model -- [in] BLE Mesh Server Model to which the message belongs. ctx -- [in] Message context, includes keys, TTL, etc. opcode -- [in] Message opcode. length -- [in] Message length (exclude the message opcode). data -- [in] Parameters of Access Payload (exclude the message opcode) to be sent. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_client_model_send_msg(esp_ble_mesh_model_t *model, esp_ble_mesh_msg_ctx_t *ctx, uint32_t opcode, uint16_t length, uint8_t *data, int32_t msg_timeout, bool need_rsp, esp_ble_mesh_dev_role_t device_role) Send client model message (such as model get, set, etc). - Parameters model -- [in] BLE Mesh Client Model to which the message belongs. ctx -- [in] Message context, includes keys, TTL, etc. opcode -- [in] Message opcode. length -- [in] Message length (exclude the message opcode). data -- [in] Parameters of the Access Payload (exclude the message opcode) to be sent. msg_timeout -- [in] Time to get response to the message (in milliseconds). need_rsp -- [in] TRUE if the opcode requires the peer device to reply, FALSE otherwise. device_role -- [in] Role of the device (Node/Provisioner) that sends the message. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_model_publish(esp_ble_mesh_model_t *model, uint32_t opcode, uint16_t length, uint8_t *data, esp_ble_mesh_dev_role_t device_role) Send a model publication message. Note Before calling this function, the user needs to ensure that the model publication message (esp_ble_mesh_model_pub_t::msg) contains a valid message to be sent. And if users want to update the publishing message, this API should be called in ESP_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT with the message updated. - Parameters model -- [in] Mesh (client) Model publishing the message. opcode -- [in] Message opcode. length -- [in] Message length (exclude the message opcode). data -- [in] Parameters of the Access Payload (exclude the message opcode) to be sent. device_role -- [in] Role of the device (node/provisioner) publishing the message of the type esp_ble_mesh_dev_role_t. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_server_model_update_state(esp_ble_mesh_model_t *model, esp_ble_mesh_server_state_type_t type, esp_ble_mesh_server_state_value_t *value) Update a server model state value. If the model publication state is set properly (e.g. publish address is set to a valid address), it will publish corresponding status message. Note Currently this API is used to update bound state value, not for all server model states. - Parameters model -- [in] Server model which is going to update the state. type -- [in] Server model state type. value -- [in] Server model state value. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_node_local_reset(void) Reset the provisioning procedure of the local BLE Mesh node. Note All provisioning information in this node will be deleted and the node needs to be re-provisioned. The API function esp_ble_mesh_node_prov_enable() needs to be called to start a new provisioning procedure. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_set_node_name(uint16_t index, const char *name) This function is called to set the node (provisioned device) name. Note index is obtained from the parameters of ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT. - Parameters index -- [in] Index of the node in the node queue. name -- [in] Name (end by '\0') to be set for the node. - - Returns ESP_OK on success or error code otherwise. - const char *esp_ble_mesh_provisioner_get_node_name(uint16_t index) This function is called to get the node (provisioned device) name. Note index is obtained from the parameters of ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT. - Parameters index -- [in] Index of the node in the node queue. - Returns Node name on success, or NULL on failure. - uint16_t esp_ble_mesh_provisioner_get_node_index(const char *name) This function is called to get the node (provisioned device) index. - Parameters name -- [in] Name of the node (end by '\0'). - Returns Node index on success, or an invalid value (0xFFFF) on failure. - esp_err_t esp_ble_mesh_provisioner_store_node_comp_data(uint16_t unicast_addr, uint8_t *data, uint16_t length) This function is called to store the Composition Data of the node. - Parameters unicast_addr -- [in] Element address of the node data -- [in] Pointer of Composition Data length -- [in] Length of Composition Data - - Returns ESP_OK on success or error code otherwise. - esp_ble_mesh_node_t *esp_ble_mesh_provisioner_get_node_with_uuid(const uint8_t uuid[16]) This function is called to get the provisioned node information with the node device uuid. - Parameters uuid -- [in] Device UUID of the node - Returns Pointer of the node info struct or NULL on failure. - esp_ble_mesh_node_t *esp_ble_mesh_provisioner_get_node_with_addr(uint16_t unicast_addr) This function is called to get the provisioned node information with the node unicast address. - Parameters unicast_addr -- [in] Unicast address of the node - Returns Pointer of the node info struct or NULL on failure. - esp_ble_mesh_node_t *esp_ble_mesh_provisioner_get_node_with_name(const char *name) This function is called to get the provisioned node information with the node name. - Parameters name -- [in] Name of the node (end by '\0'). - Returns Pointer of the node info struct or NULL on failure. - uint16_t esp_ble_mesh_provisioner_get_prov_node_count(void) This function is called by Provisioner to get provisioned node count. - Returns Number of the provisioned nodes. - const esp_ble_mesh_node_t **esp_ble_mesh_provisioner_get_node_table_entry(void) This function is called by Provisioner to get the entry of the node table. Note After invoking the function to get the entry of nodes, users can use the "for" loop combined with the macro CONFIG_BLE_MESH_MAX_PROV_NODES to get each node's information. Before trying to read the node's information, users need to check if the node exists, i.e. if the *(esp_ble_mesh_node_t **node) is NULL. For example: ``` const esp_ble_mesh_node_t **entry = esp_ble_mesh_provisioner_get_node_table_entry(); for (int i = 0; i < CONFIG_BLE_MESH_MAX_PROV_NODES; i++) { const esp_ble_mesh_node_t *node = entry[i]; if (node) { ...... } } ``` - Returns Pointer to the start of the node table. - esp_err_t esp_ble_mesh_provisioner_delete_node_with_uuid(const uint8_t uuid[16]) This function is called to delete the provisioned node information with the node device uuid. - Parameters uuid -- [in] Device UUID of the node - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_delete_node_with_addr(uint16_t unicast_addr) This function is called to delete the provisioned node information with the node unicast address. - Parameters unicast_addr -- [in] Unicast address of the node - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_add_local_app_key(const uint8_t app_key[16], uint16_t net_idx, uint16_t app_idx) This function is called to add a local AppKey for Provisioner. Note app_key: If set to NULL, app_key will be generated internally. net_idx: Should be an existing one. app_idx: If it is going to be generated internally, it should be set to 0xFFFF, and the new app_idx will be reported via an event. - Parameters app_key -- [in] The app key to be set for the local BLE Mesh stack. net_idx -- [in] The network key index. app_idx -- [in] The app key index. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_update_local_app_key(const uint8_t app_key[16], uint16_t net_idx, uint16_t app_idx) This function is used to update a local AppKey for Provisioner. - Parameters app_key -- [in] Value of the AppKey. net_idx -- [in] Corresponding NetKey Index. app_idx -- [in] The AppKey Index - - Returns ESP_OK on success or error code otherwise. - const uint8_t *esp_ble_mesh_provisioner_get_local_app_key(uint16_t net_idx, uint16_t app_idx) This function is called by Provisioner to get the local app key value. - Parameters net_idx -- [in] Network key index. app_idx -- [in] Application key index. - - Returns App key on success, or NULL on failure. - esp_err_t esp_ble_mesh_provisioner_bind_app_key_to_local_model(uint16_t element_addr, uint16_t app_idx, uint16_t model_id, uint16_t company_id) This function is called by Provisioner to bind own model with proper app key. Note company_id: If going to bind app_key with local vendor model, company_id should be set to 0xFFFF. - Parameters element_addr -- [in] Provisioner local element address app_idx -- [in] Provisioner local appkey index model_id -- [in] Provisioner local model id company_id -- [in] Provisioner local company id - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_add_local_net_key(const uint8_t net_key[16], uint16_t net_idx) This function is called by Provisioner to add local network key. Note net_key: If set to NULL, net_key will be generated internally. net_idx: If it is going to be generated internally, it should be set to 0xFFFF, and the new net_idx will be reported via an event. - Parameters net_key -- [in] The network key to be added to the Provisioner local BLE Mesh stack. net_idx -- [in] The network key index. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_update_local_net_key(const uint8_t net_key[16], uint16_t net_idx) This function is called by Provisioner to update a local network key. - Parameters net_key -- [in] Value of the NetKey. net_idx -- [in] The NetKey Index. - - Returns ESP_OK on success or error code otherwise. - const uint8_t *esp_ble_mesh_provisioner_get_local_net_key(uint16_t net_idx) This function is called by Provisioner to get the local network key value. - Parameters net_idx -- [in] Network key index. - Returns Network key on success, or NULL on failure. - esp_err_t esp_ble_mesh_provisioner_recv_heartbeat(bool enable) This function is called by Provisioner to enable or disable receiving heartbeat messages. Note If enabling receiving heartbeat message successfully, the filter will be an empty rejectlist by default, which means all heartbeat messages received by the Provisioner will be reported to the application layer. - Parameters enable -- [in] Enable or disable receiving heartbeat messages. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_set_heartbeat_filter_type(uint8_t type) This function is called by Provisioner to set the heartbeat filter type. Note 1. If the filter type is not the same with the current value, then all the filter entries will be cleaned. If the previous type is rejectlist, and changed to acceptlist, then the filter will be an empty acceptlist, which means no heartbeat messages will be reported. Users need to add SRC or DST into the filter entry, then heartbeat messages from the SRC or to the DST will be reported. - Parameters type -- [in] Heartbeat filter type (acceptlist or rejectlist). - Returns ESP_OK on success or error code otherwise. - - esp_err_t esp_ble_mesh_provisioner_set_heartbeat_filter_info(uint8_t op, esp_ble_mesh_heartbeat_filter_info_t *info) This function is called by Provisioner to add or remove a heartbeat filter entry. If the operation is "REMOVE", the "hb_src" can be set to the SRC (can only be a unicast address) of heartbeat messages, and the "hb_dst" can be set to the DST (unicast address or group address), at least one of them needs to be set. The filter entry with the same SRC or DST will be removed. - Note 1. If the operation is "ADD", the "hb_src" can be set to the SRC (can only be a unicast address) of heartbeat messages, and the "hb_dst" can be set to the DST (unicast address or group address), at least one of them needs to be set. If only one of them is set, the filter entry will only use the configured SRC or DST to filter heartbeat messages. If both of them are set, the SRC and DST will both be used to decide if a heartbeat message will be handled. If SRC or DST already exists in some filter entry, then the corresponding entry will be cleaned firstly, then a new entry will be allocated to store the information. - Parameters op -- [in] Add or REMOVE info -- [in] Heartbeat filter entry information, including: hb_src - Heartbeat source address; hb_dst - Heartbeat destination address; - - Returns ESP_OK on success or error code otherwise. - - esp_err_t esp_ble_mesh_provisioner_direct_erase_settings(void) This function is called by Provisioner to directly erase the mesh information from nvs namespace. Note This function can be invoked when the mesh stack is not initialized or has been de-initialized. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_open_settings_with_index(uint8_t index) This function is called by Provisioner to open a nvs namespace for storing mesh information. Note Before open another nvs namespace, the previously opened nvs namespace must be closed firstly. - Parameters index -- [in] Settings index. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_open_settings_with_uid(const char *uid) This function is called by Provisioner to open a nvs namespace for storing mesh information. Note Before open another nvs namespace, the previously opened nvs namespace must be closed firstly. - Parameters uid -- [in] Settings user id. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_close_settings_with_index(uint8_t index, bool erase) This function is called by Provisioner to close a nvs namespace which is opened previously for storing mesh information. Note 1. Before closing the nvs namespace, it must be open. When the function is invoked, the Provisioner functionality will be disabled firstly, and: a) If the "erase" flag is set to false, the mesh information will be cleaned (e.g. removing NetKey, AppKey, nodes, etc) from the mesh stack. b) If the "erase" flag is set to true, the mesh information stored in the nvs namespace will also be erased besides been cleaned from the mesh stack. If Provisioner tries to work properly again, we can invoke the open function to open a new nvs namespace or a previously added one, and restore the mesh information from it if not erased. The working process shall be as following: a) Open settings A b) Start to provision and control nodes c) Close settings A d) Open settings B e) Start to provision and control other nodes f) Close settings B g) ...... - Parameters index -- [in] Settings index. erase -- [in] Indicate if erasing mesh information. - - Returns ESP_OK on success or error code otherwise. - - esp_err_t esp_ble_mesh_provisioner_close_settings_with_uid(const char *uid, bool erase) This function is called by Provisioner to close a nvs namespace which is opened previously for storing mesh information. Note 1. Before closing the nvs namespace, it must be open. When the function is invoked, the Provisioner functionality will be disabled firstly, and: a) If the "erase" flag is set to false, the mesh information will be cleaned (e.g. removing NetKey, AppKey, nodes, etc) from the mesh stack. b) If the "erase" flag is set to true, the mesh information stored in the nvs namespace will also be erased besides been cleaned from the mesh stack. If Provisioner tries to work properly again, we can invoke the open function to open a new nvs namespace or a previously added one, and restore the mesh information from it if not erased. The working process shall be as following: a) Open settings A b) Start to provision and control nodes c) Close settings A d) Open settings B e) Start to provision and control other nodes f) Close settings B g) ...... - Parameters uid -- [in] Settings user id. erase -- [in] Indicate if erasing mesh information. - - Returns ESP_OK on success or error code otherwise. - - esp_err_t esp_ble_mesh_provisioner_delete_settings_with_index(uint8_t index) This function is called by Provisioner to erase the mesh information and settings user id from a nvs namespace. Note When this function is called, the nvs namespace must not be open. This function is used to erase the mesh information and settings user id which are not used currently. - Parameters index -- [in] Settings index. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_delete_settings_with_uid(const char *uid) This function is called by Provisioner to erase the mesh information and settings user id from a nvs namespace. Note When this function is called, the nvs namespace must not be open. This function is used to erase the mesh information and settings user id which are not used currently. - Parameters uid -- [in] Settings user id. - Returns ESP_OK on success or error code otherwise. - const char *esp_ble_mesh_provisioner_get_settings_uid(uint8_t index) This function is called by Provisioner to get settings user id. - Parameters index -- [in] Settings index. - Returns Setting user id on success or NULL on failure. - uint8_t esp_ble_mesh_provisioner_get_settings_index(const char *uid) This function is called by Provisioner to get settings index. - Parameters uid -- [in] Settings user id. - Returns Settings index. - uint8_t esp_ble_mesh_provisioner_get_free_settings_count(void) This function is called by Provisioner to get the number of free settings user id. - Returns Number of free settings user id. - const uint8_t *esp_ble_mesh_get_fast_prov_app_key(uint16_t net_idx, uint16_t app_idx) This function is called to get fast provisioning application key. - Parameters net_idx -- [in] Network key index. app_idx -- [in] Application key index. - - Returns Application key on success, or NULL on failure. Type Definitions - typedef void (*esp_ble_mesh_model_cb_t)(esp_ble_mesh_model_cb_event_t event, esp_ble_mesh_model_cb_param_t *param) : event, event code of user-defined model events; param, parameters of user-defined model events ESP-BLE-MESH Node/Provisioner Provisioning Header File components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_provisioning_api.h This header file can be included with: #include "esp_ble_mesh_provisioning_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_prov_callback(esp_ble_mesh_prov_cb_t callback) Register BLE Mesh provisioning callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - bool esp_ble_mesh_node_is_provisioned(void) Check if a device has been provisioned. - Returns TRUE if the device is provisioned, FALSE if the device is unprovisioned. - esp_err_t esp_ble_mesh_node_prov_enable(esp_ble_mesh_prov_bearer_t bearers) Enable specific provisioning bearers to get the device ready for provisioning. Note PB-ADV: send unprovisioned device beacon. PB-GATT: send connectable advertising packets. - Parameters bearers -- Bit-wise OR of provisioning bearers. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_node_prov_disable(esp_ble_mesh_prov_bearer_t bearers) Disable specific provisioning bearers to make a device inaccessible for provisioning. - Parameters bearers -- Bit-wise OR of provisioning bearers. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_node_set_oob_pub_key(uint8_t pub_key_x[32], uint8_t pub_key_y[32], uint8_t private_key[32]) Unprovisioned device set own oob public key & private key pair. Note In order to avoid suffering brute-forcing attack (CVE-2020-26559). The Bluetooth SIG recommends that potentially vulnerable mesh provisioners use an out-of-band mechanism to exchange the public keys. So as an unprovisioned device, it should use this function to input the Public Key exchanged through the out-of-band mechanism. - Parameters pub_key_x -- [in] Unprovisioned device's Public Key X pub_key_y -- [in] Unprovisioned device's Public Key Y private_key -- [in] Unprovisioned device's Private Key - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_node_input_number(uint32_t number) Provide provisioning input OOB number. Note This is intended to be called if the user has received ESP_BLE_MESH_NODE_PROV_INPUT_EVT with ESP_BLE_MESH_ENTER_NUMBER as the action. - Parameters number -- [in] Number input by device. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_node_input_string(const char *string) Provide provisioning input OOB string. Note This is intended to be called if the user has received ESP_BLE_MESH_NODE_PROV_INPUT_EVT with ESP_BLE_MESH_ENTER_STRING as the action. - Parameters string -- [in] String input by device. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_set_unprovisioned_device_name(const char *name) Using this function, an unprovisioned device can set its own device name, which will be broadcasted in its advertising data. Note This API applicable to PB-GATT mode only by setting the name to the scan response data, it doesn't apply to PB-ADV mode. - Parameters name -- [in] Unprovisioned device name - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_read_oob_pub_key(uint8_t link_idx, uint8_t pub_key_x[32], uint8_t pub_key_y[32]) Provisioner inputs unprovisioned device's oob public key. Note In order to avoid suffering brute-forcing attack (CVE-2020-26559). The Bluetooth SIG recommends that potentially vulnerable mesh provisioners use an out-of-band mechanism to exchange the public keys. - Parameters link_idx -- [in] The provisioning link index pub_key_x -- [in] Unprovisioned device's Public Key X pub_key_y -- [in] Unprovisioned device's Public Key Y - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_input_string(const char *string, uint8_t link_idx) Provide provisioning input OOB string. This is intended to be called after the esp_ble_mesh_prov_t prov_input_num callback has been called with ESP_BLE_MESH_ENTER_STRING as the action. - Parameters string -- [in] String input by Provisioner. link_idx -- [in] The provisioning link index. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_input_number(uint32_t number, uint8_t link_idx) Provide provisioning input OOB number. This is intended to be called after the esp_ble_mesh_prov_t prov_input_num callback has been called with ESP_BLE_MESH_ENTER_NUMBER as the action. - Parameters number -- [in] Number input by Provisioner. link_idx -- [in] The provisioning link index. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_prov_enable(esp_ble_mesh_prov_bearer_t bearers) Enable one or more provisioning bearers. Note PB-ADV: Enable BLE scan. PB-GATT: Initialize corresponding BLE Mesh Proxy info. - Parameters bearers -- [in] Bit-wise OR of provisioning bearers. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_prov_disable(esp_ble_mesh_prov_bearer_t bearers) Disable one or more provisioning bearers. Note PB-ADV: Disable BLE scan. PB-GATT: Break any existing BLE Mesh Provisioning connections. - Parameters bearers -- [in] Bit-wise OR of provisioning bearers. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_add_unprov_dev(esp_ble_mesh_unprov_dev_add_t *add_dev, esp_ble_mesh_dev_add_flag_t flags) Add unprovisioned device info to the unprov_dev queue. Note : 1. Currently address type only supports public address and static random address. If device UUID and/or device address as well as address type already exist in the device queue, but the bearer is different from the existing one, add operation will also be successful and it will update the provision bearer supported by the device. For example, if the Provisioner wants to add an unprovisioned device info before receiving its unprovisioned device beacon or Mesh Provisioning advertising packets, the Provisioner can use this API to add the device info with each one or both of device UUID and device address added. When the Provisioner gets the device's advertising packets, it will start provisioning the device internally. In this situation, the Provisioner can set bearers with each one or both of ESP_BLE_MESH_PROV_ADV and ESP_BLE_MESH_PROV_GATT enabled, and cannot set flags with ADD_DEV_START_PROV_NOW_FLAG enabled. - Another example is when the Provisioner receives the unprovisioned device's beacon or Mesh Provisioning advertising packets, the advertising packets will be reported on to the application layer using the callback registered by the function esp_ble_mesh_register_prov_callback. And in the callback, the Provisioner can call this API to start provisioning the device. If the Provisioner uses PB-ADV to provision, either one or both of device UUID and device address can be added, bearers shall be set with ESP_BLE_MESH_PROV_ADV enabled and the flags shall be set with ADD_DEV_START_PROV_NOW_FLAG enabled. If the Provisioner uses PB-GATT to provision, both the device UUID and device address need to be added, bearers shall be set with ESP_BLE_MESH_PROV_GATT enabled, and the flags shall be set with ADD_DEV_START_PROV_NOW_FLAG enabled. If the Provisioner just wants to store the unprovisioned device info when receiving its advertising packets and start to provision it the next time (e.g. after receiving its advertising packets again), then it can add the device info with either one or both of device UUID and device address included. Bearers can be set with either one or both of ESP_BLE_MESH_PROV_ADV and ESP_BLE_MESH_PROV_GATT enabled (recommend to enable the bearer which will receive its advertising packets, because if the other bearer is enabled, the Provisioner is not aware if the device supports the bearer), and flags cannot be set with ADD_DEV_START_PROV_NOW_FLAG enabled. Note: ESP_BLE_MESH_PROV_ADV, ESP_BLE_MESH_PROV_GATT and ADD_DEV_START_PROV_NOW_FLAG can not be enabled at the same time. - - Parameters add_dev -- [in] Pointer to a struct containing the device information flags -- [in] Flags indicate several operations on the device information Remove device information from queue after device has been provisioned (BIT0) Start provisioning immediately after device is added to queue (BIT1) Device can be removed if device queue is full (BIT2) - - - Returns ESP_OK on success or error code otherwise. - - esp_err_t esp_ble_mesh_provisioner_prov_device_with_addr(const uint8_t uuid[16], esp_ble_mesh_bd_addr_t addr, esp_ble_mesh_addr_type_t addr_type, esp_ble_mesh_prov_bearer_t bearer, uint16_t oob_info, uint16_t unicast_addr) Provision an unprovisioned device and assign a fixed unicast address for it in advance. Note : 1. Currently address type only supports public address and static random address. Bearer must be equal to ESP_BLE_MESH_PROV_ADV or ESP_BLE_MESH_PROV_GATT, since Provisioner will start to provision a device immediately once this function is invoked. And the input bearer must be identical with the one within the parameters of the ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT event. If this function is used by a Provisioner to provision devices, the application should take care of the assigned unicast address and avoid overlap of the unicast addresses of different nodes. Recommend to use only one of the functions "esp_ble_mesh_provisioner_add_unprov_dev" and "esp_ble_mesh_provisioner_prov_device_with_addr" by a Provisioner. - Parameters uuid -- [in] Device UUID of the unprovisioned device addr -- [in] Device address of the unprovisioned device addr_type -- [in] Device address type of the unprovisioned device bearer -- [in] Provisioning bearer going to be used by Provisioner oob_info -- [in] OOB info of the unprovisioned device unicast_addr -- [in] Unicast address going to be allocated for the unprovisioned device - - Returns Zero on success or (negative) error code otherwise. - - esp_err_t esp_ble_mesh_provisioner_delete_dev(esp_ble_mesh_device_delete_t *del_dev) Delete device from queue, and reset current provisioning link with the device. Note If the device is in the queue, remove it from the queue; if the device is being provisioned, terminate the provisioning procedure. Either one of the device address or device UUID can be used as input. - Parameters del_dev -- [in] Pointer to a struct containing the device information. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_set_dev_uuid_match(const uint8_t *match_val, uint8_t match_len, uint8_t offset, bool prov_after_match) This function is called by Provisioner to set the part of the device UUID to be compared before starting to provision. - Parameters match_val -- [in] Value to be compared with the part of the device UUID. match_len -- [in] Length of the compared match value. offset -- [in] Offset of the device UUID to be compared (based on zero). prov_after_match -- [in] Flag used to indicate whether provisioner should start to provision the device immediately if the part of the UUID matches. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_set_prov_data_info(esp_ble_mesh_prov_data_info_t *prov_data_info) This function is called by Provisioner to set provisioning data information before starting to provision. - Parameters prov_data_info -- [in] Pointer to a struct containing net_idx or flags or iv_index. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_set_static_oob_value(const uint8_t *value, uint8_t length) This function is called by Provisioner to set static oob value used for provisioning. AuthValues selected using a cryptographically secure random or pseudorandom number generator and having the maximum permitted entropy (128-bits) will be most difficult to brute-force. AuthValues with reduced entropy or generated in a predictable manner will not grant the same level of protection against this vulnerability. Selecting a new AuthValue with each provisioning attempt can also make it more difficult to launch a brute-force attack by requiring the attacker to restart the search with each provisioning attempt (CVE-2020-26556). Note The Bluetooth SIG recommends that mesh implementations enforce a randomly selected AuthValue using all of the available bits, where permitted by the implementation. A large entropy helps ensure that a brute-force of the AuthValue, even a static AuthValue, cannot normally be completed in a reasonable time (CVE-2020-26557). - Parameters value -- [in] Pointer to the static oob value. length -- [in] Length of the static oob value. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_provisioner_set_primary_elem_addr(uint16_t addr) This function is called by Provisioner to set own Primary element address. Note This API must be invoked when BLE Mesh initialization is completed successfully, and can be invoked before Provisioner functionality is enabled. Once this API is invoked successfully, the prov_unicast_addr value in the struct esp_ble_mesh_prov_t will be ignored, and Provisioner will use this address as its own primary element address. And if the unicast address going to assigned for the next unprovisioned device is smaller than the input address + element number of Provisioner, then the address for the next unprovisioned device will be recalculated internally. - Parameters addr -- [in] Unicast address of the Primary element of Provisioner. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_set_fast_prov_info(esp_ble_mesh_fast_prov_info_t *fast_prov_info) This function is called to set provisioning data information before starting fast provisioning. - Parameters fast_prov_info -- [in] Pointer to a struct containing unicast address range, net_idx, etc. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_set_fast_prov_action(esp_ble_mesh_fast_prov_action_t action) This function is called to start/suspend/exit fast provisioning. - Parameters action -- [in] fast provisioning action (i.e. enter, suspend, exit). - Returns ESP_OK on success or error code otherwise. Type Definitions - typedef void (*esp_ble_mesh_prov_cb_t)(esp_ble_mesh_prov_cb_event_t event, esp_ble_mesh_prov_cb_param_t *param) : event, event code of provisioning events; param, parameters of provisioning events - typedef void (*esp_ble_mesh_prov_adv_cb_t)(const esp_ble_mesh_bd_addr_t addr, const esp_ble_mesh_addr_type_t addr_type, const uint8_t adv_type, const uint8_t *dev_uuid, uint16_t oob_info, esp_ble_mesh_prov_bearer_t bearer) Callback for Provisioner that received advertising packets from unprovisioned devices which are not in the unprovisioned device queue. Report on the unprovisioned device beacon and mesh provisioning service adv data to application. - Param addr [in] Pointer to the unprovisioned device address. - Param addr_type [in] Unprovisioned device address type. - Param adv_type [in] Adv packet type(ADV_IND or ADV_NONCONN_IND). - Param dev_uuid [in] Unprovisioned device UUID pointer. - Param oob_info [in] OOB information of the unprovisioned device. - Param bearer [in] Adv packet received from PB-GATT or PB-ADV bearer. ESP-BLE-MESH GATT Proxy Server Header File components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_proxy_api.h This header file can be included with: #include "esp_ble_mesh_proxy_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_proxy_identity_enable(void) Enable advertising with Node Identity. Note This API requires that GATT Proxy support be enabled. Once called, each subnet starts advertising using Node Identity for the next 60 seconds, and after 60s Network ID will be advertised. Under normal conditions, the BLE Mesh Proxy Node Identity and Network ID advertising will be enabled automatically by BLE Mesh stack after the device is provisioned. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_proxy_gatt_enable(void) Enable BLE Mesh GATT Proxy Service. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_proxy_gatt_disable(void) Disconnect the BLE Mesh GATT Proxy connection if there is any, and disable the BLE Mesh GATT Proxy Service. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_private_proxy_identity_enable(void) Enable advertising with Private Node Identity. Note This API requires that GATT Proxy support be enabled. Once called, each subnet starts advertising using Private Node Identity for the next 60 seconds, and after 60s Private Network ID will be advertised. Under normal conditions, the BLE Mesh Proxy Node Identity, Network ID advertising, Proxy Private Node Identity and Private Network ID advertising will be enabled automatically by BLE Mesh stack after the device is provisioned. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_private_proxy_identity_disable(void) Disable advertising with Private Node Identity. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_proxy_client_connect(esp_ble_mesh_bd_addr_t addr, esp_ble_mesh_addr_type_t addr_type, uint16_t net_idx) Proxy Client creates a connection with the Proxy Server. - Parameters addr -- [in] Device address of the Proxy Server. addr_type -- [in] Device address type(public or static random). net_idx -- [in] NetKey Index related with Network ID in the Mesh Proxy advertising packet. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_proxy_client_disconnect(uint8_t conn_handle) Proxy Client terminates a connection with the Proxy Server. - Parameters conn_handle -- [in] Proxy connection handle. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_proxy_client_set_filter_type(uint8_t conn_handle, uint16_t net_idx, esp_ble_mesh_proxy_filter_type_t filter_type) Proxy Client sets the filter type of the Proxy Server. - Parameters conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. filter_type -- [in] whitelist or blacklist. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_proxy_client_add_filter_addr(uint8_t conn_handle, uint16_t net_idx, uint16_t *addr, uint16_t addr_num) Proxy Client adds address to the Proxy Server filter list. - Parameters conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. addr -- [in] Pointer to the filter address. addr_num -- [in] Number of the filter address. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_proxy_client_remove_filter_addr(uint8_t conn_handle, uint16_t net_idx, uint16_t *addr, uint16_t addr_num) Proxy Client removes address from the Proxy Server filter list. - Parameters conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. addr -- [in] Pointer to the filter address. addr_num -- [in] Number of the filter address. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_proxy_client_directed_proxy_set(uint8_t conn_handle, uint16_t net_idx, uint8_t use_directed) Proxy Client sets whether or not the Directed Proxy Server uses directed forwarding for Directed Proxy Client messages. - Parameters conn_handle -- [in] Proxy connection handle. net_idx -- [in] Corresponding NetKey Index. use_directed -- [in] Whether or not to send message by directed forwarding. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_proxy_client_send_solic_pdu(uint8_t net_idx, uint16_t ssrc, uint16_t dst) Proxy Client sends Solicitation PDU. - Parameters net_idx -- [in] Corresponding NetKey Index. ssrc -- [in] Solicitation SRC, shall be one of its element address. dst -- [in] Solicitation DST (TBD). - - Returns ESP_OK on success or error code otherwise. Macros - ESP_BLE_MESH_PROXY_CLI_DIRECTED_FORWARDING_ENABLE - ESP_BLE_MESH_PROXY_CLI_DIRECTED_FORWARDING_DISABLE ESP-BLE-MESH Models API Reference This section contains ESP-BLE-MESH Model related APIs, event types, event parameters, etc. There are six categories of models: Note Definitions related to Server Models are being updated, and will be released soon. Configuration Client/Server Models Header File components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_config_model_api.h This header file can be included with: #include "esp_ble_mesh_config_model_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_config_client_callback(esp_ble_mesh_cfg_client_cb_t callback) Register BLE Mesh Config Client Model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_register_config_server_callback(esp_ble_mesh_cfg_server_cb_t callback) Register BLE Mesh Config Server Model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_config_client_get_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_cfg_client_get_state_t *get_state) Get the value of Config Server Model states using the Config Client Model get messages. Note If you want to find the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_opcode_config_client_get_t in esp_ble_mesh_defs.h - Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_config_client_set_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_cfg_client_set_state_t *set_state) Set the value of the Configuration Server Model states using the Config Client Model set messages. Note If you want to find the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_opcode_config_client_set_t in esp_ble_mesh_defs.h - Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. - - Returns ESP_OK on success or error code otherwise. Unions - union esp_ble_mesh_cfg_client_get_state_t - #include <esp_ble_mesh_config_model_api.h> For ESP_BLE_MESH_MODEL_OP_BEACON_GET ESP_BLE_MESH_MODEL_OP_COMPOSITION_DATA_GET ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_GET ESP_BLE_MESH_MODEL_OP_GATT_PROXY_GET ESP_BLE_MESH_MODEL_OP_RELAY_GET ESP_BLE_MESH_MODEL_OP_MODEL_PUB_GET ESP_BLE_MESH_MODEL_OP_FRIEND_GET ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_GET ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_GET the get_state parameter in the esp_ble_mesh_config_client_get_state function should not be set to NULL. Public Members - esp_ble_mesh_cfg_model_pub_get_t model_pub_get For ESP_BLE_MESH_MODEL_OP_MODEL_PUB_GET. - esp_ble_mesh_cfg_composition_data_get_t comp_data_get For ESP_BLE_MESH_MODEL_OP_COMPOSITION_DATA_GET. - esp_ble_mesh_cfg_sig_model_sub_get_t sig_model_sub_get For ESP_BLE_MESH_MODEL_OP_SIG_MODEL_SUB_GET - esp_ble_mesh_cfg_vnd_model_sub_get_t vnd_model_sub_get For ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_SUB_GET - esp_ble_mesh_cfg_app_key_get_t app_key_get For ESP_BLE_MESH_MODEL_OP_APP_KEY_GET. - esp_ble_mesh_cfg_node_identity_get_t node_identity_get For ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_GET. - esp_ble_mesh_cfg_sig_model_app_get_t sig_model_app_get For ESP_BLE_MESH_MODEL_OP_SIG_MODEL_APP_GET - esp_ble_mesh_cfg_vnd_model_app_get_t vnd_model_app_get For ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_APP_GET - esp_ble_mesh_cfg_kr_phase_get_t kr_phase_get For ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_GET - esp_ble_mesh_cfg_lpn_polltimeout_get_t lpn_pollto_get For ESP_BLE_MESH_MODEL_OP_LPN_POLLTIMEOUT_GET - esp_ble_mesh_cfg_model_pub_get_t model_pub_get - union esp_ble_mesh_cfg_client_set_state_t - #include <esp_ble_mesh_config_model_api.h> For ESP_BLE_MESH_MODEL_OP_BEACON_SET ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_SET ESP_BLE_MESH_MODEL_OP_GATT_PROXY_SET ESP_BLE_MESH_MODEL_OP_RELAY_SET ESP_BLE_MESH_MODEL_OP_MODEL_PUB_SET ESP_BLE_MESH_MODEL_OP_MODEL_SUB_ADD ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_ADD ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_DELETE ESP_BLE_MESH_MODEL_OP_MODEL_SUB_OVERWRITE ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_OVERWRITE ESP_BLE_MESH_MODEL_OP_NET_KEY_ADD ESP_BLE_MESH_MODEL_OP_APP_KEY_ADD ESP_BLE_MESH_MODEL_OP_MODEL_APP_BIND ESP_BLE_MESH_MODEL_OP_NODE_RESET ESP_BLE_MESH_MODEL_OP_FRIEND_SET ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_SET ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_SET the set_state parameter in the esp_ble_mesh_config_client_set_state function should not be set to NULL. Public Members - esp_ble_mesh_cfg_beacon_set_t beacon_set For ESP_BLE_MESH_MODEL_OP_BEACON_SET - esp_ble_mesh_cfg_default_ttl_set_t default_ttl_set For ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_SET - esp_ble_mesh_cfg_friend_set_t friend_set For ESP_BLE_MESH_MODEL_OP_FRIEND_SET - esp_ble_mesh_cfg_gatt_proxy_set_t gatt_proxy_set For ESP_BLE_MESH_MODEL_OP_GATT_PROXY_SET - esp_ble_mesh_cfg_relay_set_t relay_set For ESP_BLE_MESH_MODEL_OP_RELAY_SET - esp_ble_mesh_cfg_net_key_add_t net_key_add For ESP_BLE_MESH_MODEL_OP_NET_KEY_ADD - esp_ble_mesh_cfg_app_key_add_t app_key_add For ESP_BLE_MESH_MODEL_OP_APP_KEY_ADD - esp_ble_mesh_cfg_model_app_bind_t model_app_bind For ESP_BLE_MESH_MODEL_OP_MODEL_APP_BIND - esp_ble_mesh_cfg_model_pub_set_t model_pub_set For ESP_BLE_MESH_MODEL_OP_MODEL_PUB_SET - esp_ble_mesh_cfg_model_sub_add_t model_sub_add For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_ADD - esp_ble_mesh_cfg_model_sub_delete_t model_sub_delete For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE - esp_ble_mesh_cfg_model_sub_overwrite_t model_sub_overwrite For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_OVERWRITE - esp_ble_mesh_cfg_model_sub_va_add_t model_sub_va_add For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_ADD - esp_ble_mesh_cfg_model_sub_va_delete_t model_sub_va_delete For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_DELETE - esp_ble_mesh_cfg_model_sub_va_overwrite_t model_sub_va_overwrite For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_OVERWRITE - esp_ble_mesh_cfg_heartbeat_pub_set_t heartbeat_pub_set For ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_SET - esp_ble_mesh_cfg_heartbeat_sub_set_t heartbeat_sub_set For ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_SET - esp_ble_mesh_cfg_model_pub_va_set_t model_pub_va_set For ESP_BLE_MESH_MODEL_OP_MODEL_PUB_VIRTUAL_ADDR_SET - esp_ble_mesh_cfg_model_sub_delete_all_t model_sub_delete_all For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE_ALL - esp_ble_mesh_cfg_net_key_update_t net_key_update For ESP_BLE_MESH_MODEL_OP_NET_KEY_UPDATE - esp_ble_mesh_cfg_net_key_delete_t net_key_delete For ESP_BLE_MESH_MODEL_OP_NET_KEY_DELETE - esp_ble_mesh_cfg_app_key_update_t app_key_update For ESP_BLE_MESH_MODEL_OP_APP_KEY_UPDATE - esp_ble_mesh_cfg_app_key_delete_t app_key_delete For ESP_BLE_MESH_MODEL_OP_APP_KEY_DELETE - esp_ble_mesh_cfg_node_identity_set_t node_identity_set For ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_SET - esp_ble_mesh_cfg_model_app_unbind_t model_app_unbind For ESP_BLE_MESH_MODEL_OP_MODEL_APP_UNBIND - esp_ble_mesh_cfg_kr_phase_set_t kr_phase_set For ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_SET - esp_ble_mesh_cfg_net_transmit_set_t net_transmit_set For ESP_BLE_MESH_MODEL_OP_NETWORK_TRANSMIT_SET - esp_ble_mesh_cfg_beacon_set_t beacon_set - union esp_ble_mesh_cfg_client_common_cb_param_t - #include <esp_ble_mesh_config_model_api.h> Configuration Client Model received message union. Public Members - esp_ble_mesh_cfg_beacon_status_cb_t beacon_status The beacon status value - esp_ble_mesh_cfg_comp_data_status_cb_t comp_data_status The composition data status value - esp_ble_mesh_cfg_default_ttl_status_cb_t default_ttl_status The default_ttl status value - esp_ble_mesh_cfg_gatt_proxy_status_cb_t gatt_proxy_status The gatt_proxy status value - esp_ble_mesh_cfg_relay_status_cb_t relay_status The relay status value - esp_ble_mesh_cfg_model_pub_status_cb_t model_pub_status The model publication status value - esp_ble_mesh_cfg_model_sub_status_cb_t model_sub_status The model subscription status value - esp_ble_mesh_cfg_net_key_status_cb_t netkey_status The netkey status value - esp_ble_mesh_cfg_app_key_status_cb_t appkey_status The appkey status value - esp_ble_mesh_cfg_mod_app_status_cb_t model_app_status The model app status value - esp_ble_mesh_cfg_friend_status_cb_t friend_status The friend status value - esp_ble_mesh_cfg_hb_pub_status_cb_t heartbeat_pub_status The heartbeat publication status value - esp_ble_mesh_cfg_hb_sub_status_cb_t heartbeat_sub_status The heartbeat subscription status value - esp_ble_mesh_cfg_net_trans_status_cb_t net_transmit_status The network transmit status value - esp_ble_mesh_cfg_model_sub_list_cb_t model_sub_list The model subscription list value - esp_ble_mesh_cfg_net_key_list_cb_t netkey_list The network key index list value - esp_ble_mesh_cfg_app_key_list_cb_t appkey_list The application key index list value - esp_ble_mesh_cfg_node_id_status_cb_t node_identity_status The node identity status value - esp_ble_mesh_cfg_model_app_list_cb_t model_app_list The model application key index list value - esp_ble_mesh_cfg_kr_phase_status_cb_t kr_phase_status The key refresh phase status value - esp_ble_mesh_cfg_lpn_pollto_status_cb_t lpn_timeout_status The low power node poll timeout status value - esp_ble_mesh_cfg_beacon_status_cb_t beacon_status - union esp_ble_mesh_cfg_server_state_change_t - #include <esp_ble_mesh_config_model_api.h> Configuration Server model state change value union. Public Members - esp_ble_mesh_state_change_cfg_mod_pub_set_t mod_pub_set The recv_op in ctx can be used to decide which state is changed. Config Model Publication Set - esp_ble_mesh_state_change_cfg_mod_pub_va_set_t mod_pub_va_set Config Model Publication Virtual Address Set - esp_ble_mesh_state_change_cfg_model_sub_add_t mod_sub_add Config Model Subscription Add - esp_ble_mesh_state_change_cfg_model_sub_delete_t mod_sub_delete Config Model Subscription Delete - esp_ble_mesh_state_change_cfg_netkey_add_t netkey_add Config NetKey Add - esp_ble_mesh_state_change_cfg_netkey_update_t netkey_update Config NetKey Update - esp_ble_mesh_state_change_cfg_netkey_delete_t netkey_delete Config NetKey Delete - esp_ble_mesh_state_change_cfg_appkey_add_t appkey_add Config AppKey Add - esp_ble_mesh_state_change_cfg_appkey_update_t appkey_update Config AppKey Update - esp_ble_mesh_state_change_cfg_appkey_delete_t appkey_delete Config AppKey Delete - esp_ble_mesh_state_change_cfg_model_app_bind_t mod_app_bind Config Model App Bind - esp_ble_mesh_state_change_cfg_model_app_unbind_t mod_app_unbind Config Model App Unbind - esp_ble_mesh_state_change_cfg_kr_phase_set_t kr_phase_set Config Key Refresh Phase Set - esp_ble_mesh_state_change_cfg_mod_pub_set_t mod_pub_set - union esp_ble_mesh_cfg_server_cb_value_t - #include <esp_ble_mesh_config_model_api.h> Configuration Server model callback value union. Public Members - esp_ble_mesh_cfg_server_state_change_t state_change ESP_BLE_MESH_CFG_SERVER_STATE_CHANGE_EVT - esp_ble_mesh_cfg_server_state_change_t state_change Structures - struct esp_ble_mesh_cfg_srv_t Configuration Server Model context Public Members - esp_ble_mesh_model_t *model Pointer to Configuration Server Model - uint8_t net_transmit Network Transmit state - uint8_t relay Relay Mode state - uint8_t relay_retransmit Relay Retransmit state - uint8_t beacon Secure Network Beacon state - uint8_t gatt_proxy GATT Proxy state - uint8_t friend_state Friend state - uint8_t default_ttl Default TTL - struct k_delayed_work timer Heartbeat Publication timer - uint16_t dst Destination address for Heartbeat messages - uint16_t count Number of Heartbeat messages to be sent Number of Heartbeat messages received - uint8_t period Period for sending Heartbeat messages - uint8_t ttl TTL to be used when sending Heartbeat messages - uint16_t feature Bit field indicating features that trigger Heartbeat messages when changed - uint16_t net_idx NetKey Index used by Heartbeat Publication - struct esp_ble_mesh_cfg_srv_t::[anonymous] heartbeat_pub Heartbeat Publication - int64_t expiry Timestamp when Heartbeat subscription period is expired - uint16_t src Source address for Heartbeat messages - uint8_t min_hops Minimum hops when receiving Heartbeat messages - uint8_t max_hops Maximum hops when receiving Heartbeat messages - esp_ble_mesh_cb_t heartbeat_recv_cb Optional heartbeat subscription tracking function - struct esp_ble_mesh_cfg_srv_t::[anonymous] heartbeat_sub Heartbeat Subscription - esp_ble_mesh_model_t *model - struct esp_ble_mesh_cfg_composition_data_get_t Parameters of Config Composition Data Get. Public Members - uint8_t page Page number of the Composition Data. - uint8_t page - struct esp_ble_mesh_cfg_model_pub_get_t Parameters of Config Model Publication Get. - struct esp_ble_mesh_cfg_sig_model_sub_get_t Parameters of Config SIG Model Subscription Get. - struct esp_ble_mesh_cfg_vnd_model_sub_get_t Parameters of Config Vendor Model Subscription Get. - struct esp_ble_mesh_cfg_app_key_get_t Parameters of Config AppKey Get. - struct esp_ble_mesh_cfg_node_identity_get_t Parameters of Config Node Identity Get. - struct esp_ble_mesh_cfg_sig_model_app_get_t Parameters of Config SIG Model App Get. - struct esp_ble_mesh_cfg_vnd_model_app_get_t Parameters of Config Vendor Model App Get. - struct esp_ble_mesh_cfg_kr_phase_get_t Parameters of Config Key Refresh Phase Get. - struct esp_ble_mesh_cfg_lpn_polltimeout_get_t Parameters of Config Low Power Node PollTimeout Get. Public Members - uint16_t lpn_addr The unicast address of the Low Power node - uint16_t lpn_addr - struct esp_ble_mesh_cfg_beacon_set_t Parameters of Config Beacon Set. Public Members - uint8_t beacon New Secure Network Beacon state - uint8_t beacon - struct esp_ble_mesh_cfg_default_ttl_set_t Parameters of Config Default TTL Set. Public Members - uint8_t ttl The default TTL state value - uint8_t ttl - struct esp_ble_mesh_cfg_friend_set_t Parameters of Config Friend Set. Public Members - uint8_t friend_state The friend state value - uint8_t friend_state - struct esp_ble_mesh_cfg_gatt_proxy_set_t Parameters of Config GATT Proxy Set. Public Members - uint8_t gatt_proxy The GATT Proxy state value - uint8_t gatt_proxy - struct esp_ble_mesh_cfg_relay_set_t Parameters of Config Relay Set. - struct esp_ble_mesh_cfg_net_key_add_t Parameters of Config NetKey Add. - struct esp_ble_mesh_cfg_app_key_add_t Parameters of Config AppKey Add. - struct esp_ble_mesh_cfg_model_app_bind_t Parameters of Config Model App Bind. - struct esp_ble_mesh_cfg_model_pub_set_t Parameters of Config Model Publication Set. Public Members - uint16_t element_addr The element address - uint16_t publish_addr Value of the publish address - uint16_t publish_app_idx Index of the application key - bool cred_flag Value of the Friendship Credential Flag - uint8_t publish_ttl Default TTL value for the publishing messages - uint8_t publish_period Period for periodic status publishing - uint8_t publish_retransmit Number of retransmissions and number of 50-millisecond steps between retransmissions - uint16_t model_id The model id - uint16_t company_id The company id, if not a vendor model, shall set to 0xFFFF - uint16_t element_addr - struct esp_ble_mesh_cfg_model_sub_add_t Parameters of Config Model Subscription Add. - struct esp_ble_mesh_cfg_model_sub_delete_t Parameters of Config Model Subscription Delete. - struct esp_ble_mesh_cfg_model_sub_overwrite_t Parameters of Config Model Subscription Overwrite. - struct esp_ble_mesh_cfg_model_sub_va_add_t Parameters of Config Model Subscription Virtual Address Add. - struct esp_ble_mesh_cfg_model_sub_va_delete_t Parameters of Config Model Subscription Virtual Address Delete. - struct esp_ble_mesh_cfg_model_sub_va_overwrite_t Parameters of Config Model Subscription Virtual Address Overwrite. - struct esp_ble_mesh_cfg_model_pub_va_set_t Parameters of Config Model Publication Virtual Address Set. Public Members - uint16_t element_addr The element address - uint8_t label_uuid[16] Value of the Label UUID publish address - uint16_t publish_app_idx Index of the application key - bool cred_flag Value of the Friendship Credential Flag - uint8_t publish_ttl Default TTL value for the publishing messages - uint8_t publish_period Period for periodic status publishing - uint8_t publish_retransmit Number of retransmissions and number of 50-millisecond steps between retransmissions - uint16_t model_id The model id - uint16_t company_id The company id, if not a vendor model, shall set to 0xFFFF - uint16_t element_addr - struct esp_ble_mesh_cfg_model_sub_delete_all_t Parameters of Config Model Subscription Delete All. - struct esp_ble_mesh_cfg_net_key_update_t Parameters of Config NetKey Update. - struct esp_ble_mesh_cfg_net_key_delete_t Parameters of Config NetKey Delete. - struct esp_ble_mesh_cfg_app_key_update_t Parameters of Config AppKey Update. - struct esp_ble_mesh_cfg_app_key_delete_t Parameters of Config AppKey Delete. - struct esp_ble_mesh_cfg_node_identity_set_t Parameters of Config Node Identity Set. - struct esp_ble_mesh_cfg_model_app_unbind_t Parameters of Config Model App Unbind. - struct esp_ble_mesh_cfg_kr_phase_set_t Parameters of Config Key Refresh Phase Set. - struct esp_ble_mesh_cfg_net_transmit_set_t Parameters of Config Network Transmit Set. Public Members - uint8_t net_transmit Network Transmit State - uint8_t net_transmit - struct esp_ble_mesh_cfg_heartbeat_pub_set_t Parameters of Config Model Heartbeat Publication Set. Public Members - uint16_t dst Destination address for Heartbeat messages - uint8_t count Number of Heartbeat messages to be sent - uint8_t period Period for sending Heartbeat messages - uint8_t ttl TTL to be used when sending Heartbeat messages - uint16_t feature Bit field indicating features that trigger Heartbeat messages when changed - uint16_t net_idx NetKey Index - uint16_t dst - struct esp_ble_mesh_cfg_heartbeat_sub_set_t Parameters of Config Model Heartbeat Subscription Set. - struct esp_ble_mesh_cfg_beacon_status_cb_t Parameter of Config Beacon Status Public Members - uint8_t beacon Secure Network Beacon state value - uint8_t beacon - struct esp_ble_mesh_cfg_comp_data_status_cb_t Parameters of Config Composition Data Status - struct esp_ble_mesh_cfg_default_ttl_status_cb_t Parameter of Config Default TTL Status Public Members - uint8_t default_ttl Default TTL state value - uint8_t default_ttl - struct esp_ble_mesh_cfg_gatt_proxy_status_cb_t Parameter of Config GATT Proxy Status Public Members - uint8_t gatt_proxy GATT Proxy state value - uint8_t gatt_proxy - struct esp_ble_mesh_cfg_relay_status_cb_t Parameters of Config Relay Status - struct esp_ble_mesh_cfg_model_pub_status_cb_t Parameters of Config Model Publication Status Public Members - uint8_t status Status Code for the request message - uint16_t element_addr Address of the element - uint16_t publish_addr Value of the publish address - uint16_t app_idx Index of the application key - bool cred_flag Value of the Friendship Credential Flag - uint8_t ttl Default TTL value for the outgoing messages - uint8_t period Period for periodic status publishing - uint8_t transmit Number of retransmissions and number of 50-millisecond steps between retransmissions - uint16_t company_id Company ID - uint16_t model_id Model ID - uint8_t status - struct esp_ble_mesh_cfg_model_sub_status_cb_t Parameters of Config Model Subscription Status - struct esp_ble_mesh_cfg_net_key_status_cb_t Parameters of Config NetKey Status - struct esp_ble_mesh_cfg_app_key_status_cb_t Parameters of Config AppKey Status - struct esp_ble_mesh_cfg_mod_app_status_cb_t Parameters of Config Model App Status - struct esp_ble_mesh_cfg_friend_status_cb_t Parameter of Config Friend Status Public Members - uint8_t friend_state Friend state value - uint8_t friend_state - struct esp_ble_mesh_cfg_hb_pub_status_cb_t Parameters of Config Heartbeat Publication Status Public Members - uint8_t status Status Code for the request message - uint16_t dst Destination address for Heartbeat messages - uint8_t count Number of Heartbeat messages remaining to be sent - uint8_t period Period for sending Heartbeat messages - uint8_t ttl TTL to be used when sending Heartbeat messages - uint16_t features Features that trigger Heartbeat messages when changed - uint16_t net_idx Index of the NetKey - uint8_t status - struct esp_ble_mesh_cfg_hb_sub_status_cb_t Parameters of Config Heartbeat Subscription Status Public Members - uint8_t status Status Code for the request message - uint16_t src Source address for Heartbeat messages - uint16_t dst Destination address for Heartbeat messages - uint8_t period Remaining Period for processing Heartbeat messages - uint8_t count Number of Heartbeat messages received - uint8_t min_hops Minimum hops when receiving Heartbeat messages - uint8_t max_hops Maximum hops when receiving Heartbeat messages - uint8_t status - struct esp_ble_mesh_cfg_net_trans_status_cb_t Parameters of Config Network Transmit Status - struct esp_ble_mesh_cfg_model_sub_list_cb_t Parameters of Config SIG/Vendor Subscription List - struct esp_ble_mesh_cfg_net_key_list_cb_t Parameter of Config NetKey List Public Members - struct net_buf_simple *net_idx A list of NetKey Indexes known to the node - struct net_buf_simple *net_idx - struct esp_ble_mesh_cfg_app_key_list_cb_t Parameters of Config AppKey List - struct esp_ble_mesh_cfg_node_id_status_cb_t Parameters of Config Node Identity Status - struct esp_ble_mesh_cfg_model_app_list_cb_t Parameters of Config SIG/Vendor Model App List - struct esp_ble_mesh_cfg_kr_phase_status_cb_t Parameters of Config Key Refresh Phase Status - struct esp_ble_mesh_cfg_lpn_pollto_status_cb_t Parameters of Config Low Power Node PollTimeout Status - struct esp_ble_mesh_cfg_client_cb_param_t Configuration Client Model callback parameters Public Members - int error_code Appropriate error code - esp_ble_mesh_client_common_param_t *params The client common parameters - esp_ble_mesh_cfg_client_common_cb_param_t status_cb The config status message callback values - int error_code - struct esp_ble_mesh_state_change_cfg_mod_pub_set_t Configuration Server model related context. Parameters of Config Model Publication Set Public Members - uint16_t element_addr Element Address - uint16_t pub_addr Publish Address - uint16_t app_idx AppKey Index - bool cred_flag Friendship Credential Flag - uint8_t pub_ttl Publish TTL - uint8_t pub_period Publish Period - uint8_t pub_retransmit Publish Retransmit - uint16_t company_id Company ID - uint16_t model_id Model ID - uint16_t element_addr - struct esp_ble_mesh_state_change_cfg_mod_pub_va_set_t Parameters of Config Model Publication Virtual Address Set Public Members - uint16_t element_addr Element Address - uint8_t label_uuid[16] Label UUID - uint16_t app_idx AppKey Index - bool cred_flag Friendship Credential Flag - uint8_t pub_ttl Publish TTL - uint8_t pub_period Publish Period - uint8_t pub_retransmit Publish Retransmit - uint16_t company_id Company ID - uint16_t model_id Model ID - uint16_t element_addr - struct esp_ble_mesh_state_change_cfg_model_sub_add_t Parameters of Config Model Subscription Add - struct esp_ble_mesh_state_change_cfg_model_sub_delete_t Parameters of Config Model Subscription Delete - struct esp_ble_mesh_state_change_cfg_netkey_add_t Parameters of Config NetKey Add - struct esp_ble_mesh_state_change_cfg_netkey_update_t Parameters of Config NetKey Update - struct esp_ble_mesh_state_change_cfg_netkey_delete_t Parameter of Config NetKey Delete - struct esp_ble_mesh_state_change_cfg_appkey_add_t Parameters of Config AppKey Add - struct esp_ble_mesh_state_change_cfg_appkey_update_t Parameters of Config AppKey Update - struct esp_ble_mesh_state_change_cfg_appkey_delete_t Parameters of Config AppKey Delete - struct esp_ble_mesh_state_change_cfg_model_app_bind_t Parameters of Config Model App Bind - struct esp_ble_mesh_state_change_cfg_model_app_unbind_t Parameters of Config Model App Unbind - struct esp_ble_mesh_state_change_cfg_kr_phase_set_t Parameters of Config Key Refresh Phase Set - struct esp_ble_mesh_cfg_server_cb_param_t Configuration Server model callback parameters Public Members - esp_ble_mesh_model_t *model Pointer to the server model structure - esp_ble_mesh_msg_ctx_t ctx Context of the received message - esp_ble_mesh_cfg_server_cb_value_t value Value of the received configuration messages - esp_ble_mesh_model_t *model Macros - ESP_BLE_MESH_MODEL_CFG_SRV(srv_data) Define a new Config Server Model. Note The Config Server Model can only be included by a Primary Element. - Parameters srv_data -- Pointer to a unique Config Server Model user_data. - - Returns New Config Server Model instance. - ESP_BLE_MESH_MODEL_CFG_CLI(cli_data) Define a new Config Client Model. Note The Config Client Model can only be included by a Primary Element. - Parameters cli_data -- Pointer to a unique struct esp_ble_mesh_client_t. - - Returns New Config Client Model instance. Type Definitions - typedef void (*esp_ble_mesh_cfg_client_cb_t)(esp_ble_mesh_cfg_client_cb_event_t event, esp_ble_mesh_cfg_client_cb_param_t *param) Bluetooth Mesh Config Client and Server Model functions. Configuration Client Model callback function type - Param event Event type - Param param Pointer to callback parameter - typedef void (*esp_ble_mesh_cfg_server_cb_t)(esp_ble_mesh_cfg_server_cb_event_t event, esp_ble_mesh_cfg_server_cb_param_t *param) Configuration Server Model callback function type. - Param event Event type - Param param Pointer to callback parameter Enumerations - enum esp_ble_mesh_cfg_client_cb_event_t This enum value is the event of Configuration Client Model Values: - enumerator ESP_BLE_MESH_CFG_CLIENT_GET_STATE_EVT - enumerator ESP_BLE_MESH_CFG_CLIENT_SET_STATE_EVT - enumerator ESP_BLE_MESH_CFG_CLIENT_PUBLISH_EVT - enumerator ESP_BLE_MESH_CFG_CLIENT_TIMEOUT_EVT - enumerator ESP_BLE_MESH_CFG_CLIENT_EVT_MAX - enumerator ESP_BLE_MESH_CFG_CLIENT_GET_STATE_EVT Health Client/Server Models Header File components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_health_model_api.h This header file can be included with: #include "esp_ble_mesh_health_model_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_health_client_callback(esp_ble_mesh_health_client_cb_t callback) Register BLE Mesh Health Model callback, the callback will report Health Client & Server Model events. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_register_health_server_callback(esp_ble_mesh_health_server_cb_t callback) Register BLE Mesh Health Server Model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_health_client_get_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_health_client_get_state_t *get_state) This function is called to get the Health Server states using the Health Client Model get messages. Note If you want to find the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_opcode_health_client_get_t in esp_ble_mesh_defs.h - Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_health_client_set_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_health_client_set_state_t *set_state) This function is called to set the Health Server states using the Health Client Model set messages. Note If you want to find the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_opcode_health_client_set_t in esp_ble_mesh_defs.h - Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. Shall not be set to NULL. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_health_server_fault_update(esp_ble_mesh_elem_t *element) This function is called by the Health Server Model to update the context of its Health Current status. - Parameters element -- [in] The element to which the Health Server Model belongs. - Returns ESP_OK on success or error code otherwise. Unions - union esp_ble_mesh_health_client_get_state_t - #include <esp_ble_mesh_health_model_api.h> For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_GET ESP_BLE_MESH_MODEL_OP_ATTENTION_GET ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_GET the get_state parameter in the esp_ble_mesh_health_client_get_state function should not be set to NULL. Public Members - esp_ble_mesh_health_fault_get_t fault_get For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_GET. - esp_ble_mesh_health_fault_get_t fault_get - union esp_ble_mesh_health_client_set_state_t - #include <esp_ble_mesh_health_model_api.h> For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR_UNACK ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST_UNACK ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET_UNACK ESP_BLE_MESH_MODEL_OP_ATTENTION_SET ESP_BLE_MESH_MODEL_OP_ATTENTION_SET_UNACK the set_state parameter in the esp_ble_mesh_health_client_set_state function should not be set to NULL. Public Members - esp_ble_mesh_health_attention_set_t attention_set For ESP_BLE_MESH_MODEL_OP_ATTENTION_SET or ESP_BLE_MESH_MODEL_OP_ATTENTION_SET_UNACK. - esp_ble_mesh_health_period_set_t period_set For ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET or ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET_UNACK. - esp_ble_mesh_health_fault_test_t fault_test For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST or ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST_UNACK. - esp_ble_mesh_health_fault_clear_t fault_clear For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR or ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR_UNACK. - esp_ble_mesh_health_attention_set_t attention_set - union esp_ble_mesh_health_client_common_cb_param_t - #include <esp_ble_mesh_health_model_api.h> Health Client Model received message union. Public Members - esp_ble_mesh_health_current_status_cb_t current_status The health current status value - esp_ble_mesh_health_fault_status_cb_t fault_status The health fault status value - esp_ble_mesh_health_period_status_cb_t period_status The health period status value - esp_ble_mesh_health_attention_status_cb_t attention_status The health attention status value - esp_ble_mesh_health_current_status_cb_t current_status - union esp_ble_mesh_health_server_cb_param_t - #include <esp_ble_mesh_health_model_api.h> Health Server Model callback parameters union. Public Members - esp_ble_mesh_health_fault_update_comp_cb_t fault_update_comp ESP_BLE_MESH_HEALTH_SERVER_FAULT_UPDATE_COMP_EVT - esp_ble_mesh_health_fault_clear_cb_t fault_clear ESP_BLE_MESH_HEALTH_SERVER_FAULT_CLEAR_EVT - esp_ble_mesh_health_fault_test_cb_t fault_test ESP_BLE_MESH_HEALTH_SERVER_FAULT_TEST_EVT - esp_ble_mesh_health_attention_on_cb_t attention_on ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_ON_EVT - esp_ble_mesh_health_attention_off_cb_t attention_off ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_OFF_EVT - esp_ble_mesh_health_fault_update_comp_cb_t fault_update_comp Structures - struct esp_ble_mesh_health_srv_cb_t ESP BLE Mesh Health Server callback Public Members - esp_ble_mesh_cb_t fault_clear Clear health registered faults. Initialized by the stack. - esp_ble_mesh_cb_t fault_test Run a specific health test. Initialized by the stack. - esp_ble_mesh_cb_t attention_on Health attention on callback. Initialized by the stack. - esp_ble_mesh_cb_t attention_off Health attention off callback. Initialized by the stack. - esp_ble_mesh_cb_t fault_clear - struct esp_ble_mesh_health_test_t ESP BLE Mesh Health Server test Context Public Members - uint8_t id_count Number of Health self-test ID - const uint8_t *test_ids Array of Health self-test IDs - uint16_t company_id Company ID used to identify the Health Fault state - uint8_t prev_test_id Current test ID of the health fault test - uint8_t current_faults[ESP_BLE_MESH_HEALTH_FAULT_ARRAY_SIZE] Array of current faults - uint8_t registered_faults[ESP_BLE_MESH_HEALTH_FAULT_ARRAY_SIZE] Array of registered faults - uint8_t id_count - struct esp_ble_mesh_health_srv_t ESP BLE Mesh Health Server Model Context Public Members - esp_ble_mesh_model_t *model Pointer to Health Server Model - esp_ble_mesh_health_srv_cb_t health_cb Health callback struct - struct k_delayed_work attention_timer Attention Timer state - bool attention_timer_start Attention Timer start flag - esp_ble_mesh_health_test_t health_test Health Server fault test - esp_ble_mesh_model_t *model - struct esp_ble_mesh_health_fault_get_t Parameter of Health Fault Get Public Members - uint16_t company_id Bluetooth assigned 16-bit Company ID - uint16_t company_id - struct esp_ble_mesh_health_attention_set_t Parameter of Health Attention Set Public Members - uint8_t attention Value of the Attention Timer state - uint8_t attention - struct esp_ble_mesh_health_period_set_t Parameter of Health Period Set Public Members - uint8_t fast_period_divisor Divider for the Publish Period - uint8_t fast_period_divisor - struct esp_ble_mesh_health_fault_test_t Parameter of Health Fault Test - struct esp_ble_mesh_health_fault_clear_t Parameter of Health Fault Clear Public Members - uint16_t company_id Bluetooth assigned 16-bit Company ID - uint16_t company_id - struct esp_ble_mesh_health_current_status_cb_t Parameters of Health Current Status - struct esp_ble_mesh_health_fault_status_cb_t Parameters of Health Fault Status - struct esp_ble_mesh_health_period_status_cb_t Parameter of Health Period Status Public Members - uint8_t fast_period_divisor Divider for the Publish Period - uint8_t fast_period_divisor - struct esp_ble_mesh_health_attention_status_cb_t Parameter of Health Attention Status Public Members - uint8_t attention Value of the Attention Timer state - uint8_t attention - struct esp_ble_mesh_health_client_cb_param_t Health Client Model callback parameters Public Members - int error_code Appropriate error code - esp_ble_mesh_client_common_param_t *params The client common parameters. - esp_ble_mesh_health_client_common_cb_param_t status_cb The health message status callback values - int error_code - struct esp_ble_mesh_health_fault_update_comp_cb_t Parameter of publishing Health Current Status completion event Public Members - int error_code The result of publishing Health Current Status - esp_ble_mesh_elem_t *element Pointer to the element which contains the Health Server Model - int error_code - struct esp_ble_mesh_health_fault_clear_cb_t Parameters of Health Fault Clear event Public Members - esp_ble_mesh_model_t *model Pointer to the Health Server Model - uint16_t company_id Bluetooth assigned 16-bit Company ID - esp_ble_mesh_model_t *model - struct esp_ble_mesh_health_fault_test_cb_t Parameters of Health Fault Test event Public Members - esp_ble_mesh_model_t *model Pointer to the Health Server Model - uint8_t test_id ID of a specific test to be performed - uint16_t company_id Bluetooth assigned 16-bit Company ID - esp_ble_mesh_model_t *model - struct esp_ble_mesh_health_attention_on_cb_t Parameter of Health Attention On event Public Members - esp_ble_mesh_model_t *model Pointer to the Health Server Model - uint8_t time Duration of attention timer on (in seconds) - esp_ble_mesh_model_t *model - struct esp_ble_mesh_health_attention_off_cb_t Parameter of Health Attention Off event Public Members - esp_ble_mesh_model_t *model Pointer to the Health Server Model - esp_ble_mesh_model_t *model Macros - ESP_BLE_MESH_MODEL_HEALTH_SRV(srv, pub) Define a new Health Server Model. Note The Health Server Model can only be included by a Primary Element. - Parameters srv -- Pointer to the unique struct esp_ble_mesh_health_srv_t. pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. - - Returns New Health Server Model instance. - ESP_BLE_MESH_MODEL_HEALTH_CLI(cli_data) Define a new Health Client Model. Note This API needs to be called for each element on which the application needs to have a Health Client Model. - Parameters cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Health Client Model instance. - ESP_BLE_MESH_HEALTH_PUB_DEFINE(_name, _max, _role) A helper to define a health publication context - Parameters _name -- Name given to the publication context variable. _max -- Maximum number of faults the element can have. _role -- Role of the device which contains the model. - - ESP_BLE_MESH_HEALTH_STANDARD_TEST SIG identifier of Health Fault Test. 0x01 ~ 0xFF: Vendor Specific Test. - ESP_BLE_MESH_NO_FAULT Fault values of Health Fault Test. 0x33 ~ 0x7F: Reserved for Future Use. 0x80 ~ 0xFF: Vendor Specific Warning/Error. - ESP_BLE_MESH_BATTERY_LOW_WARNING - ESP_BLE_MESH_BATTERY_LOW_ERROR - ESP_BLE_MESH_SUPPLY_VOLTAGE_TOO_LOW_WARNING - ESP_BLE_MESH_SUPPLY_VOLTAGE_TOO_LOW_ERROR - ESP_BLE_MESH_SUPPLY_VOLTAGE_TOO_HIGH_WARNING - ESP_BLE_MESH_SUPPLY_VOLTAGE_TOO_HIGH_ERROR - ESP_BLE_MESH_POWER_SUPPLY_INTERRUPTED_WARNING - ESP_BLE_MESH_POWER_SUPPLY_INTERRUPTED_ERROR - ESP_BLE_MESH_NO_LOAD_WARNING - ESP_BLE_MESH_NO_LOAD_ERROR - ESP_BLE_MESH_OVERLOAD_WARNING - ESP_BLE_MESH_OVERLOAD_ERROR - ESP_BLE_MESH_OVERHEAT_WARNING - ESP_BLE_MESH_OVERHEAT_ERROR - ESP_BLE_MESH_CONDENSATION_WARNING - ESP_BLE_MESH_CONDENSATION_ERROR - ESP_BLE_MESH_VIBRATION_WARNING - ESP_BLE_MESH_VIBRATION_ERROR - ESP_BLE_MESH_CONFIGURATION_WARNING - ESP_BLE_MESH_CONFIGURATION_ERROR - ESP_BLE_MESH_ELEMENT_NOT_CALIBRATED_WARNING - ESP_BLE_MESH_ELEMENT_NOT_CALIBRATED_ERROR - ESP_BLE_MESH_MEMORY_WARNING - ESP_BLE_MESH_MEMORY_ERROR - ESP_BLE_MESH_SELF_TEST_WARNING - ESP_BLE_MESH_SELF_TEST_ERROR - ESP_BLE_MESH_INPUT_TOO_LOW_WARNING - ESP_BLE_MESH_INPUT_TOO_LOW_ERROR - ESP_BLE_MESH_INPUT_TOO_HIGH_WARNING - ESP_BLE_MESH_INPUT_TOO_HIGH_ERROR - ESP_BLE_MESH_INPUT_NO_CHANGE_WARNING - ESP_BLE_MESH_INPUT_NO_CHANGE_ERROR - ESP_BLE_MESH_ACTUATOR_BLOCKED_WARNING - ESP_BLE_MESH_ACTUATOR_BLOCKED_ERROR - ESP_BLE_MESH_HOUSING_OPENED_WARNING - ESP_BLE_MESH_HOUSING_OPENED_ERROR - ESP_BLE_MESH_TAMPER_WARNING - ESP_BLE_MESH_TAMPER_ERROR - ESP_BLE_MESH_DEVICE_MOVED_WARNING - ESP_BLE_MESH_DEVICE_MOVED_ERROR - ESP_BLE_MESH_DEVICE_DROPPED_WARNING - ESP_BLE_MESH_DEVICE_DROPPED_ERROR - ESP_BLE_MESH_OVERFLOW_WARNING - ESP_BLE_MESH_OVERFLOW_ERROR - ESP_BLE_MESH_EMPTY_WARNING - ESP_BLE_MESH_EMPTY_ERROR - ESP_BLE_MESH_INTERNAL_BUS_WARNING - ESP_BLE_MESH_INTERNAL_BUS_ERROR - ESP_BLE_MESH_MECHANISM_JAMMED_WARNING - ESP_BLE_MESH_MECHANISM_JAMMED_ERROR - ESP_BLE_MESH_HEALTH_FAULT_ARRAY_SIZE Type Definitions - typedef void (*esp_ble_mesh_health_client_cb_t)(esp_ble_mesh_health_client_cb_event_t event, esp_ble_mesh_health_client_cb_param_t *param) Bluetooth Mesh Health Client and Server Model function. Health Client Model callback function type - Param event Event type - Param param Pointer to callback parameter - typedef void (*esp_ble_mesh_health_server_cb_t)(esp_ble_mesh_health_server_cb_event_t event, esp_ble_mesh_health_server_cb_param_t *param) Health Server Model callback function type. - Param event Event type - Param param Pointer to callback parameter Enumerations - enum esp_ble_mesh_health_client_cb_event_t This enum value is the event of Health Client Model Values: - enumerator ESP_BLE_MESH_HEALTH_CLIENT_GET_STATE_EVT - enumerator ESP_BLE_MESH_HEALTH_CLIENT_SET_STATE_EVT - enumerator ESP_BLE_MESH_HEALTH_CLIENT_PUBLISH_EVT - enumerator ESP_BLE_MESH_HEALTH_CLIENT_TIMEOUT_EVT - enumerator ESP_BLE_MESH_HEALTH_CLIENT_EVT_MAX - enumerator ESP_BLE_MESH_HEALTH_CLIENT_GET_STATE_EVT - enum esp_ble_mesh_health_server_cb_event_t This enum value is the event of Health Server Model Values: - enumerator ESP_BLE_MESH_HEALTH_SERVER_FAULT_UPDATE_COMP_EVT - enumerator ESP_BLE_MESH_HEALTH_SERVER_FAULT_CLEAR_EVT - enumerator ESP_BLE_MESH_HEALTH_SERVER_FAULT_TEST_EVT - enumerator ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_ON_EVT - enumerator ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_OFF_EVT - enumerator ESP_BLE_MESH_HEALTH_SERVER_EVT_MAX - enumerator ESP_BLE_MESH_HEALTH_SERVER_FAULT_UPDATE_COMP_EVT Generic Client/Server Models Header File components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_generic_model_api.h This header file can be included with: #include "esp_ble_mesh_generic_model_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_generic_client_callback(esp_ble_mesh_generic_client_cb_t callback) Register BLE Mesh Generic Client Model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_generic_client_get_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_generic_client_get_state_t *get_state) Get the value of Generic Server Model states using the Generic Client Model get messages. Note If you want to find the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_generic_message_opcode_t in esp_ble_mesh_defs.h - Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to generic get message value. Shall not be set to NULL. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_generic_client_set_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_generic_client_set_state_t *set_state) Set the value of Generic Server Model states using the Generic Client Model set messages. Note If you want to find the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_generic_message_opcode_t in esp_ble_mesh_defs.h - Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to generic set message value. Shall not be set to NULL. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_register_generic_server_callback(esp_ble_mesh_generic_server_cb_t callback) Register BLE Mesh Generic Server Model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. Unions - union esp_ble_mesh_generic_client_get_state_t - #include <esp_ble_mesh_generic_model_api.h> Generic Client Model get message union. Public Members - esp_ble_mesh_gen_user_property_get_t user_property_get For ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_GET - esp_ble_mesh_gen_admin_property_get_t admin_property_get For ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_GET - esp_ble_mesh_gen_manufacturer_property_get_t manufacturer_property_get For ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET - esp_ble_mesh_gen_client_properties_get_t client_properties_get For ESP_BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_GET - esp_ble_mesh_gen_user_property_get_t user_property_get - union esp_ble_mesh_generic_client_set_state_t - #include <esp_ble_mesh_generic_model_api.h> Generic Client Model set message union. Public Members - esp_ble_mesh_gen_onoff_set_t onoff_set For ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_SET & ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_SET_UNACK - esp_ble_mesh_gen_level_set_t level_set For ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_SET & ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_SET_UNACK - esp_ble_mesh_gen_delta_set_t delta_set For ESP_BLE_MESH_MODEL_OP_GEN_DELTA_SET & ESP_BLE_MESH_MODEL_OP_GEN_DELTA_SET_UNACK - esp_ble_mesh_gen_move_set_t move_set For ESP_BLE_MESH_MODEL_OP_GEN_MOVE_SET & ESP_BLE_MESH_MODEL_OP_GEN_MOVE_SET_UNACK - esp_ble_mesh_gen_def_trans_time_set_t def_trans_time_set For ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET & ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET_UNACK - esp_ble_mesh_gen_onpowerup_set_t power_set For ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET & ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET_UNACK - esp_ble_mesh_gen_power_level_set_t power_level_set For ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET & ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET_UNACK - esp_ble_mesh_gen_power_default_set_t power_default_set For ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET & ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET_UNACK - esp_ble_mesh_gen_power_range_set_t power_range_set For ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET & ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET_UNACK - esp_ble_mesh_gen_loc_global_set_t loc_global_set For ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET & ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET_UNACK - esp_ble_mesh_gen_loc_local_set_t loc_local_set For ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET & ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET_UNACK - esp_ble_mesh_gen_user_property_set_t user_property_set For ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET & ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET_UNACK - esp_ble_mesh_gen_admin_property_set_t admin_property_set For ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET & ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET_UNACK - esp_ble_mesh_gen_manufacturer_property_set_t manufacturer_property_set For ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET & ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET_UNACK - esp_ble_mesh_gen_onoff_set_t onoff_set - union esp_ble_mesh_gen_client_status_cb_t - #include <esp_ble_mesh_generic_model_api.h> Generic Client Model received message union. Public Members - esp_ble_mesh_gen_onoff_status_cb_t onoff_status For ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_STATUS - esp_ble_mesh_gen_level_status_cb_t level_status For ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_STATUS - esp_ble_mesh_gen_def_trans_time_status_cb_t def_trans_time_status For ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_STATUS - esp_ble_mesh_gen_onpowerup_status_cb_t onpowerup_status For ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_STATUS - esp_ble_mesh_gen_power_level_status_cb_t power_level_status For ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_STATUS - esp_ble_mesh_gen_power_last_status_cb_t power_last_status For ESP_BLE_MESH_MODEL_OP_GEN_POWER_LAST_STATUS - esp_ble_mesh_gen_power_default_status_cb_t power_default_status For ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_STATUS - esp_ble_mesh_gen_power_range_status_cb_t power_range_status For ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_STATUS - esp_ble_mesh_gen_battery_status_cb_t battery_status For ESP_BLE_MESH_MODEL_OP_GEN_BATTERY_STATUS - esp_ble_mesh_gen_loc_global_status_cb_t location_global_status For ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_STATUS - esp_ble_mesh_gen_loc_local_status_cb_t location_local_status ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_STATUS - esp_ble_mesh_gen_user_properties_status_cb_t user_properties_status ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTIES_STATUS - esp_ble_mesh_gen_user_property_status_cb_t user_property_status ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_STATUS - esp_ble_mesh_gen_admin_properties_status_cb_t admin_properties_status ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTIES_STATUS - esp_ble_mesh_gen_admin_property_status_cb_t admin_property_status ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_STATUS - esp_ble_mesh_gen_manufacturer_properties_status_cb_t manufacturer_properties_status ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTIES_STATUS - esp_ble_mesh_gen_manufacturer_property_status_cb_t manufacturer_property_status ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_STATUS - esp_ble_mesh_gen_client_properties_status_cb_t client_properties_status ESP_BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_STATUS - esp_ble_mesh_gen_onoff_status_cb_t onoff_status - union esp_ble_mesh_generic_server_state_change_t - #include <esp_ble_mesh_generic_model_api.h> Generic Server Model state change value union. Public Members - esp_ble_mesh_state_change_gen_onoff_set_t onoff_set The recv_op in ctx can be used to decide which state is changed. Generic OnOff Set - esp_ble_mesh_state_change_gen_level_set_t level_set Generic Level Set - esp_ble_mesh_state_change_gen_delta_set_t delta_set Generic Delta Set - esp_ble_mesh_state_change_gen_move_set_t move_set Generic Move Set - esp_ble_mesh_state_change_gen_def_trans_time_set_t def_trans_time_set Generic Default Transition Time Set - esp_ble_mesh_state_change_gen_onpowerup_set_t onpowerup_set Generic OnPowerUp Set - esp_ble_mesh_state_change_gen_power_level_set_t power_level_set Generic Power Level Set - esp_ble_mesh_state_change_gen_power_default_set_t power_default_set Generic Power Default Set - esp_ble_mesh_state_change_gen_power_range_set_t power_range_set Generic Power Range Set - esp_ble_mesh_state_change_gen_loc_global_set_t loc_global_set Generic Location Global Set - esp_ble_mesh_state_change_gen_loc_local_set_t loc_local_set Generic Location Local Set - esp_ble_mesh_state_change_gen_user_property_set_t user_property_set Generic User Property Set - esp_ble_mesh_state_change_gen_admin_property_set_t admin_property_set Generic Admin Property Set - esp_ble_mesh_state_change_gen_manu_property_set_t manu_property_set Generic Manufacturer Property Set - esp_ble_mesh_state_change_gen_onoff_set_t onoff_set - union esp_ble_mesh_generic_server_recv_get_msg_t - #include <esp_ble_mesh_generic_model_api.h> Generic Server Model received get message union. Public Members - esp_ble_mesh_server_recv_gen_user_property_get_t user_property Generic User Property Get - esp_ble_mesh_server_recv_gen_admin_property_get_t admin_property Generic Admin Property Get - esp_ble_mesh_server_recv_gen_manufacturer_property_get_t manu_property Generic Manufacturer Property Get - esp_ble_mesh_server_recv_gen_client_properties_get_t client_properties Generic Client Properties Get - esp_ble_mesh_server_recv_gen_user_property_get_t user_property - union esp_ble_mesh_generic_server_recv_set_msg_t - #include <esp_ble_mesh_generic_model_api.h> Generic Server Model received set message union. Public Members - esp_ble_mesh_server_recv_gen_onoff_set_t onoff Generic OnOff Set/Generic OnOff Set Unack - esp_ble_mesh_server_recv_gen_level_set_t level Generic Level Set/Generic Level Set Unack - esp_ble_mesh_server_recv_gen_delta_set_t delta Generic Delta Set/Generic Delta Set Unack - esp_ble_mesh_server_recv_gen_move_set_t move Generic Move Set/Generic Move Set Unack - esp_ble_mesh_server_recv_gen_def_trans_time_set_t def_trans_time Generic Default Transition Time Set/Generic Default Transition Time Set Unack - esp_ble_mesh_server_recv_gen_onpowerup_set_t onpowerup Generic OnPowerUp Set/Generic OnPowerUp Set Unack - esp_ble_mesh_server_recv_gen_power_level_set_t power_level Generic Power Level Set/Generic Power Level Set Unack - esp_ble_mesh_server_recv_gen_power_default_set_t power_default Generic Power Default Set/Generic Power Default Set Unack - esp_ble_mesh_server_recv_gen_power_range_set_t power_range Generic Power Range Set/Generic Power Range Set Unack - esp_ble_mesh_server_recv_gen_loc_global_set_t location_global Generic Location Global Set/Generic Location Global Set Unack - esp_ble_mesh_server_recv_gen_loc_local_set_t location_local Generic Location Local Set/Generic Location Local Set Unack - esp_ble_mesh_server_recv_gen_user_property_set_t user_property Generic User Property Set/Generic User Property Set Unack - esp_ble_mesh_server_recv_gen_admin_property_set_t admin_property Generic Admin Property Set/Generic Admin Property Set Unack - esp_ble_mesh_server_recv_gen_manufacturer_property_set_t manu_property Generic Manufacturer Property Set/Generic Manufacturer Property Set Unack - esp_ble_mesh_server_recv_gen_onoff_set_t onoff - union esp_ble_mesh_generic_server_cb_value_t - #include <esp_ble_mesh_generic_model_api.h> Generic Server Model callback value union. Public Members - esp_ble_mesh_generic_server_state_change_t state_change ESP_BLE_MESH_GENERIC_SERVER_STATE_CHANGE_EVT - esp_ble_mesh_generic_server_recv_get_msg_t get ESP_BLE_MESH_GENERIC_SERVER_RECV_GET_MSG_EVT - esp_ble_mesh_generic_server_recv_set_msg_t set ESP_BLE_MESH_GENERIC_SERVER_RECV_SET_MSG_EVT - esp_ble_mesh_generic_server_state_change_t state_change Structures - struct esp_ble_mesh_gen_onoff_set_t Bluetooth Mesh Generic Client Model Get and Set parameters structure. Parameters of Generic OnOff Set. - struct esp_ble_mesh_gen_level_set_t Parameters of Generic Level Set. - struct esp_ble_mesh_gen_delta_set_t Parameters of Generic Delta Set. - struct esp_ble_mesh_gen_move_set_t Parameters of Generic Move Set. Public Members - bool op_en Indicate if optional parameters are included - int16_t delta_level Delta Level step to calculate Move speed for Generic Level state - uint8_t tid Transaction ID - uint8_t trans_time Time to complete state transition (optional) - uint8_t delay Indicate message execution delay (C.1) - bool op_en - struct esp_ble_mesh_gen_def_trans_time_set_t Parameter of Generic Default Transition Time Set. - struct esp_ble_mesh_gen_onpowerup_set_t Parameter of Generic OnPowerUp Set. - struct esp_ble_mesh_gen_power_level_set_t Parameters of Generic Power Level Set. - struct esp_ble_mesh_gen_power_default_set_t Parameter of Generic Power Default Set. Public Members - uint16_t power The value of the Generic Power Default state - uint16_t power - struct esp_ble_mesh_gen_power_range_set_t Parameters of Generic Power Range Set. - struct esp_ble_mesh_gen_loc_global_set_t Parameters of Generic Location Global Set. - struct esp_ble_mesh_gen_loc_local_set_t Parameters of Generic Location Local Set. - struct esp_ble_mesh_gen_user_property_get_t Parameter of Generic User Property Get. Public Members - uint16_t property_id Property ID identifying a Generic User Property - uint16_t property_id - struct esp_ble_mesh_gen_user_property_set_t Parameters of Generic User Property Set. - struct esp_ble_mesh_gen_admin_property_get_t Parameter of Generic Admin Property Get. Public Members - uint16_t property_id Property ID identifying a Generic Admin Property - uint16_t property_id - struct esp_ble_mesh_gen_admin_property_set_t Parameters of Generic Admin Property Set. - struct esp_ble_mesh_gen_manufacturer_property_get_t Parameter of Generic Manufacturer Property Get. Public Members - uint16_t property_id Property ID identifying a Generic Manufacturer Property - uint16_t property_id - struct esp_ble_mesh_gen_manufacturer_property_set_t Parameters of Generic Manufacturer Property Set. - struct esp_ble_mesh_gen_client_properties_get_t Parameter of Generic Client Properties Get. Public Members - uint16_t property_id A starting Client Property ID present within an element - uint16_t property_id - struct esp_ble_mesh_gen_onoff_status_cb_t Bluetooth Mesh Generic Client Model Get and Set callback parameters structure. Parameters of Generic OnOff Status. - struct esp_ble_mesh_gen_level_status_cb_t Parameters of Generic Level Status. - struct esp_ble_mesh_gen_def_trans_time_status_cb_t Parameter of Generic Default Transition Time Status. - struct esp_ble_mesh_gen_onpowerup_status_cb_t Parameter of Generic OnPowerUp Status. - struct esp_ble_mesh_gen_power_level_status_cb_t Parameters of Generic Power Level Status. - struct esp_ble_mesh_gen_power_last_status_cb_t Parameter of Generic Power Last Status. Public Members - uint16_t power The value of the Generic Power Last state - uint16_t power - struct esp_ble_mesh_gen_power_default_status_cb_t Parameter of Generic Power Default Status. Public Members - uint16_t power The value of the Generic Default Last state - uint16_t power - struct esp_ble_mesh_gen_power_range_status_cb_t Parameters of Generic Power Range Status. - struct esp_ble_mesh_gen_battery_status_cb_t Parameters of Generic Battery Status. - struct esp_ble_mesh_gen_loc_global_status_cb_t Parameters of Generic Location Global Status. - struct esp_ble_mesh_gen_loc_local_status_cb_t Parameters of Generic Location Local Status. - struct esp_ble_mesh_gen_user_properties_status_cb_t Parameter of Generic User Properties Status. Public Members - struct net_buf_simple *property_ids Buffer contains a sequence of N User Property IDs - struct net_buf_simple *property_ids - struct esp_ble_mesh_gen_user_property_status_cb_t Parameters of Generic User Property Status. - struct esp_ble_mesh_gen_admin_properties_status_cb_t Parameter of Generic Admin Properties Status. Public Members - struct net_buf_simple *property_ids Buffer contains a sequence of N Admin Property IDs - struct net_buf_simple *property_ids - struct esp_ble_mesh_gen_admin_property_status_cb_t Parameters of Generic Admin Property Status. - struct esp_ble_mesh_gen_manufacturer_properties_status_cb_t Parameter of Generic Manufacturer Properties Status. Public Members - struct net_buf_simple *property_ids Buffer contains a sequence of N Manufacturer Property IDs - struct net_buf_simple *property_ids - struct esp_ble_mesh_gen_manufacturer_property_status_cb_t Parameters of Generic Manufacturer Property Status. Public Members - bool op_en Indicate if optional parameters are included - uint16_t property_id Property ID identifying a Generic Manufacturer Property - uint8_t user_access Enumeration indicating user access (optional) - struct net_buf_simple *property_value Raw value for the Manufacturer Property (C.1) - bool op_en - struct esp_ble_mesh_gen_client_properties_status_cb_t Parameter of Generic Client Properties Status. Public Members - struct net_buf_simple *property_ids Buffer contains a sequence of N Client Property IDs - struct net_buf_simple *property_ids - struct esp_ble_mesh_generic_client_cb_param_t Generic Client Model callback parameters Public Members - int error_code Appropriate error code - esp_ble_mesh_client_common_param_t *params The client common parameters. - esp_ble_mesh_gen_client_status_cb_t status_cb The generic status message callback values - int error_code - struct esp_ble_mesh_gen_onoff_state_t Parameters of Generic OnOff state - struct esp_ble_mesh_gen_onoff_srv_t User data of Generic OnOff Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Generic OnOff Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_gen_onoff_state_t state Parameters of the Generic OnOff state - esp_ble_mesh_last_msg_info_t last Parameters of the last received set message - esp_ble_mesh_state_transition_t transition Parameters of state transition - esp_ble_mesh_model_t *model - struct esp_ble_mesh_gen_level_state_t Parameters of Generic Level state Public Members - int16_t level The present value of the Generic Level state - int16_t target_level The target value of the Generic Level state - int16_t last_level When a new transaction starts, level should be set to last_last, and use "level + incoming delta" to calculate the target level. In another word, "last_level" is used to record "level" of the last transaction, and "last_delta" is used to record the previously received delta_level value. The last value of the Generic Level state - int32_t last_delta The last delta change of the Generic Level state - bool move_start Indicate if the transition of the Generic Level state has been started - bool positive Indicate if the transition is positive or negative - int16_t level - struct esp_ble_mesh_gen_level_srv_t User data of Generic Level Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Generic Level Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_gen_level_state_t state Parameters of the Generic Level state - esp_ble_mesh_last_msg_info_t last Parameters of the last received set message - esp_ble_mesh_state_transition_t transition Parameters of state transition - int32_t tt_delta_level Delta change value of level state transition - esp_ble_mesh_model_t *model - struct esp_ble_mesh_gen_def_trans_time_state_t Parameter of Generic Default Transition Time state - struct esp_ble_mesh_gen_def_trans_time_srv_t User data of Generic Default Transition Time Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Generic Default Transition Time Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_gen_def_trans_time_state_t state Parameters of the Generic Default Transition Time state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_gen_onpowerup_state_t Parameter of Generic OnPowerUp state - struct esp_ble_mesh_gen_power_onoff_srv_t User data of Generic Power OnOff Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Generic Power OnOff Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_gen_onpowerup_state_t *state Parameters of the Generic OnPowerUp state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_gen_power_onoff_setup_srv_t User data of Generic Power OnOff Setup Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Generic Power OnOff Setup Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_gen_onpowerup_state_t *state Parameters of the Generic OnPowerUp state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_gen_power_level_state_t Parameters of Generic Power Level state Public Members - uint16_t power_actual The present value of the Generic Power Actual state - uint16_t target_power_actual The target value of the Generic Power Actual state - uint16_t power_last The value of the Generic Power Last state - uint16_t power_default The value of the Generic Power Default state - uint8_t status_code The status code of setting Generic Power Range state - uint16_t power_range_min The minimum value of the Generic Power Range state - uint16_t power_range_max The maximum value of the Generic Power Range state - uint16_t power_actual - struct esp_ble_mesh_gen_power_level_srv_t User data of Generic Power Level Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Generic Power Level Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_gen_power_level_state_t *state Parameters of the Generic Power Level state - esp_ble_mesh_last_msg_info_t last Parameters of the last received set message - esp_ble_mesh_state_transition_t transition Parameters of state transition - int32_t tt_delta_level Delta change value of level state transition - esp_ble_mesh_model_t *model - struct esp_ble_mesh_gen_power_level_setup_srv_t User data of Generic Power Level Setup Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Generic Power Level Setup Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_gen_power_level_state_t *state Parameters of the Generic Power Level state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_gen_battery_state_t Parameters of Generic Battery state Public Members - uint32_t battery_level The value of the Generic Battery Level state - uint32_t time_to_discharge The value of the Generic Battery Time to Discharge state - uint32_t time_to_charge The value of the Generic Battery Time to Charge state - uint32_t battery_flags The value of the Generic Battery Flags state - uint32_t battery_level - struct esp_ble_mesh_gen_battery_srv_t User data of Generic Battery Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Generic Battery Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_gen_battery_state_t state Parameters of the Generic Battery state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_gen_location_state_t Parameters of Generic Location state Public Members - int32_t global_latitude The value of the Global Latitude field - int32_t global_longitude The value of the Global Longitude field - int16_t global_altitude The value of the Global Altitude field - int16_t local_north The value of the Local North field - int16_t local_east The value of the Local East field - int16_t local_altitude The value of the Local Altitude field - uint8_t floor_number The value of the Floor Number field - uint16_t uncertainty The value of the Uncertainty field - int32_t global_latitude - struct esp_ble_mesh_gen_location_srv_t User data of Generic Location Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Generic Location Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_gen_location_state_t *state Parameters of the Generic Location state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_gen_location_setup_srv_t User data of Generic Location Setup Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Generic Location Setup Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_gen_location_state_t *state Parameters of the Generic Location state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_generic_property_t Parameters of Generic Property states Public Members - uint16_t id The value of User/Admin/Manufacturer Property ID - uint8_t user_access The value of User Access field - uint8_t admin_access The value of Admin Access field - uint8_t manu_access The value of Manufacturer Access field - struct net_buf_simple *val The value of User/Admin/Manufacturer Property - uint16_t id - struct esp_ble_mesh_gen_user_prop_srv_t User data of Generic User Property Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Generic User Property Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - uint8_t property_count Generic User Property count - esp_ble_mesh_generic_property_t *properties Parameters of the Generic User Property state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_gen_admin_prop_srv_t User data of Generic Admin Property Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Generic Admin Property Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - uint8_t property_count Generic Admin Property count - esp_ble_mesh_generic_property_t *properties Parameters of the Generic Admin Property state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_gen_manu_prop_srv_t User data of Generic Manufacturer Property Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Generic Manufacturer Property Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - uint8_t property_count Generic Manufacturer Property count - esp_ble_mesh_generic_property_t *properties Parameters of the Generic Manufacturer Property state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_gen_client_prop_srv_t User data of Generic Client Property Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Generic Client Property Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - uint8_t id_count Generic Client Property ID count - uint16_t *property_ids Parameters of the Generic Client Property state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_state_change_gen_onoff_set_t Parameter of Generic OnOff Set state change event Public Members - uint8_t onoff The value of Generic OnOff state - uint8_t onoff - struct esp_ble_mesh_state_change_gen_level_set_t Parameter of Generic Level Set state change event - struct esp_ble_mesh_state_change_gen_delta_set_t Parameter of Generic Delta Set state change event - struct esp_ble_mesh_state_change_gen_move_set_t Parameter of Generic Move Set state change event - struct esp_ble_mesh_state_change_gen_def_trans_time_set_t Parameter of Generic Default Transition Time Set state change event Public Members - uint8_t trans_time The value of Generic Default Transition Time state - uint8_t trans_time - struct esp_ble_mesh_state_change_gen_onpowerup_set_t Parameter of Generic OnPowerUp Set state change event Public Members - uint8_t onpowerup The value of Generic OnPowerUp state - uint8_t onpowerup - struct esp_ble_mesh_state_change_gen_power_level_set_t Parameter of Generic Power Level Set state change event Public Members - uint16_t power The value of Generic Power Actual state - uint16_t power - struct esp_ble_mesh_state_change_gen_power_default_set_t Parameter of Generic Power Default Set state change event Public Members - uint16_t power The value of Generic Power Default state - uint16_t power - struct esp_ble_mesh_state_change_gen_power_range_set_t Parameters of Generic Power Range Set state change event - struct esp_ble_mesh_state_change_gen_loc_global_set_t Parameters of Generic Location Global Set state change event - struct esp_ble_mesh_state_change_gen_loc_local_set_t Parameters of Generic Location Local Set state change event Public Members - int16_t north The Local North value of Generic Location state - int16_t east The Local East value of Generic Location state - int16_t altitude The Local Altitude value of Generic Location state - uint8_t floor_number The Floor Number value of Generic Location state - uint16_t uncertainty The Uncertainty value of Generic Location state - int16_t north - struct esp_ble_mesh_state_change_gen_user_property_set_t Parameters of Generic User Property Set state change event - struct esp_ble_mesh_state_change_gen_admin_property_set_t Parameters of Generic Admin Property Set state change event - struct esp_ble_mesh_state_change_gen_manu_property_set_t Parameters of Generic Manufacturer Property Set state change event - struct esp_ble_mesh_server_recv_gen_user_property_get_t Context of the received Generic User Property Get message Public Members - uint16_t property_id Property ID identifying a Generic User Property - uint16_t property_id - struct esp_ble_mesh_server_recv_gen_admin_property_get_t Context of the received Generic Admin Property Get message Public Members - uint16_t property_id Property ID identifying a Generic Admin Property - uint16_t property_id - struct esp_ble_mesh_server_recv_gen_manufacturer_property_get_t Context of the received Generic Manufacturer Property message Public Members - uint16_t property_id Property ID identifying a Generic Manufacturer Property - uint16_t property_id - struct esp_ble_mesh_server_recv_gen_client_properties_get_t Context of the received Generic Client Properties Get message Public Members - uint16_t property_id A starting Client Property ID present within an element - uint16_t property_id - struct esp_ble_mesh_server_recv_gen_onoff_set_t Context of the received Generic OnOff Set message - struct esp_ble_mesh_server_recv_gen_level_set_t Context of the received Generic Level Set message - struct esp_ble_mesh_server_recv_gen_delta_set_t Context of the received Generic Delta Set message - struct esp_ble_mesh_server_recv_gen_move_set_t Context of the received Generic Move Set message Public Members - bool op_en Indicate if optional parameters are included - int16_t delta_level Delta Level step to calculate Move speed for Generic Level state - uint8_t tid Transaction ID - uint8_t trans_time Time to complete state transition (optional) - uint8_t delay Indicate message execution delay (C.1) - bool op_en - struct esp_ble_mesh_server_recv_gen_def_trans_time_set_t Context of the received Generic Default Transition Time Set message - struct esp_ble_mesh_server_recv_gen_onpowerup_set_t Context of the received Generic OnPowerUp Set message - struct esp_ble_mesh_server_recv_gen_power_level_set_t Context of the received Generic Power Level Set message - struct esp_ble_mesh_server_recv_gen_power_default_set_t Context of the received Generic Power Default Set message Public Members - uint16_t power The value of the Generic Power Default state - uint16_t power - struct esp_ble_mesh_server_recv_gen_power_range_set_t Context of the received Generic Power Range Set message - struct esp_ble_mesh_server_recv_gen_loc_global_set_t Context of the received Generic Location Global Set message - struct esp_ble_mesh_server_recv_gen_loc_local_set_t Context of the received Generic Location Local Set message - struct esp_ble_mesh_server_recv_gen_user_property_set_t Context of the received Generic User Property Set message - struct esp_ble_mesh_server_recv_gen_admin_property_set_t Context of the received Generic Admin Property Set message - struct esp_ble_mesh_server_recv_gen_manufacturer_property_set_t Context of the received Generic Manufacturer Property Set message - struct esp_ble_mesh_generic_server_cb_param_t Generic Server Model callback parameters Public Members - esp_ble_mesh_model_t *model Pointer to Generic Server Models - esp_ble_mesh_msg_ctx_t ctx Context of the received messages - esp_ble_mesh_generic_server_cb_value_t value Value of the received Generic Messages - esp_ble_mesh_model_t *model Macros - ESP_BLE_MESH_MODEL_GEN_ONOFF_CLI(cli_pub, cli_data) Define a new Generic OnOff Client Model. Note This API needs to be called for each element on which the application needs to have a Generic OnOff Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Generic OnOff Client Model instance. - ESP_BLE_MESH_MODEL_GEN_LEVEL_CLI(cli_pub, cli_data) Define a new Generic Level Client Model. Note This API needs to be called for each element on which the application needs to have a Generic Level Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Generic Level Client Model instance. - ESP_BLE_MESH_MODEL_GEN_DEF_TRANS_TIME_CLI(cli_pub, cli_data) Define a new Generic Default Transition Time Client Model. Note This API needs to be called for each element on which the application needs to have a Generic Default Transition Time Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Generic Default Transition Time Client Model instance. - ESP_BLE_MESH_MODEL_GEN_POWER_ONOFF_CLI(cli_pub, cli_data) Define a new Generic Power OnOff Client Model. Note This API needs to be called for each element on which the application needs to have a Generic Power OnOff Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Generic Power OnOff Client Model instance. - ESP_BLE_MESH_MODEL_GEN_POWER_LEVEL_CLI(cli_pub, cli_data) Define a new Generic Power Level Client Model. Note This API needs to be called for each element on which the application needs to have a Generic Power Level Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Generic Power Level Client Model instance. - ESP_BLE_MESH_MODEL_GEN_BATTERY_CLI(cli_pub, cli_data) Define a new Generic Battery Client Model. Note This API needs to be called for each element on which the application needs to have a Generic Battery Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Generic Battery Client Model instance. - ESP_BLE_MESH_MODEL_GEN_LOCATION_CLI(cli_pub, cli_data) Define a new Generic Location Client Model. Note This API needs to be called for each element on which the application needs to have a Generic Location Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Generic Location Client Model instance. - ESP_BLE_MESH_MODEL_GEN_PROPERTY_CLI(cli_pub, cli_data) Define a new Generic Property Client Model. Note This API needs to be called for each element on which the application needs to have a Generic Property Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Generic Location Client Model instance. - ESP_BLE_MESH_MODEL_GEN_ONOFF_SRV(srv_pub, srv_data) Generic Server Models related context. Define a new Generic OnOff Server Model. Note 1. The Generic OnOff Server Model is a root model. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_onoff_srv_t. - - Returns New Generic OnOff Server Model instance. - - ESP_BLE_MESH_MODEL_GEN_LEVEL_SRV(srv_pub, srv_data) Define a new Generic Level Server Model. Note 1. The Generic Level Server Model is a root model. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_level_srv_t. - - Returns New Generic Level Server Model instance. - - ESP_BLE_MESH_MODEL_GEN_DEF_TRANS_TIME_SRV(srv_pub, srv_data) Define a new Generic Default Transition Time Server Model. Note 1. The Generic Default Transition Time Server Model is a root model. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_def_trans_time_srv_t. - - Returns New Generic Default Transition Time Server Model instance. - - ESP_BLE_MESH_MODEL_GEN_POWER_ONOFF_SRV(srv_pub, srv_data) Define a new Generic Power OnOff Server Model. Note 1. The Generic Power OnOff Server model extends the Generic OnOff Server model. When this model is present on an element, the corresponding Generic Power OnOff Setup Server model shall also be present. This model may be used to represent a variety of devices that do not fit any of the model descriptions that have been defined but support the generic properties of On/Off. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_onoff_srv_t. - - Returns New Generic Power OnOff Server Model instance. - - ESP_BLE_MESH_MODEL_GEN_POWER_ONOFF_SETUP_SRV(srv_pub, srv_data) Define a new Generic Power OnOff Setup Server Model. Note 1. The Generic Power OnOff Setup Server model extends the Generic Power OnOff Server model and the Generic Default Transition Time Server model. This model shall support model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_onoff_setup_srv_t. - - Returns New Generic Power OnOff Setup Server Model instance. - - ESP_BLE_MESH_MODEL_GEN_POWER_LEVEL_SRV(srv_pub, srv_data) Define a new Generic Power Level Server Model. Note 1. The Generic Power Level Server model extends the Generic Power OnOff Server model and the Generic Level Server model. When this model is present on an Element, the corresponding Generic Power Level Setup Server model shall also be present. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_level_srv_t. - - Returns New Generic Power Level Server Model instance. - - ESP_BLE_MESH_MODEL_GEN_POWER_LEVEL_SETUP_SRV(srv_pub, srv_data) Define a new Generic Power Level Setup Server Model. Note 1. The Generic Power Level Setup Server model extends the Generic Power Level Server model and the Generic Power OnOff Setup Server model. This model shall support model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_power_level_setup_srv_t. - - Returns New Generic Power Level Setup Server Model instance. - - ESP_BLE_MESH_MODEL_GEN_BATTERY_SRV(srv_pub, srv_data) Define a new Generic Battery Server Model. Note 1. The Generic Battery Server Model is a root model. This model shall support model publication and model subscription. The model may be used to represent an element that is powered by a battery. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_battery_srv_t. - - Returns New Generic Battery Server Model instance. - - ESP_BLE_MESH_MODEL_GEN_LOCATION_SRV(srv_pub, srv_data) Define a new Generic Location Server Model. Note 1. The Generic Location Server model is a root model. When this model is present on an Element, the corresponding Generic Location Setup Server model shall also be present. This model shall support model publication and model subscription. The model may be used to represent an element that knows its location (global or local). - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_location_srv_t. - - Returns New Generic Location Server Model instance. - - ESP_BLE_MESH_MODEL_GEN_LOCATION_SETUP_SRV(srv_pub, srv_data) Define a new Generic Location Setup Server Model. Note 1. The Generic Location Setup Server model extends the Generic Location Server model. This model shall support model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_location_setup_srv_t. - - Returns New Generic Location Setup Server Model instance. - - ESP_BLE_MESH_MODEL_GEN_USER_PROP_SRV(srv_pub, srv_data) Define a new Generic User Property Server Model. Note 1. The Generic User Property Server model is a root model. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_user_prop_srv_t. - - Returns New Generic User Property Server Model instance. - - ESP_BLE_MESH_MODEL_GEN_ADMIN_PROP_SRV(srv_pub, srv_data) Define a new Generic Admin Property Server Model. Note 1. The Generic Admin Property Server model extends the Generic User Property Server model. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_admin_prop_srv_t. - - Returns New Generic Admin Property Server Model instance. - - ESP_BLE_MESH_MODEL_GEN_MANUFACTURER_PROP_SRV(srv_pub, srv_data) Define a new Generic Manufacturer Property Server Model. Note 1. The Generic Manufacturer Property Server model extends the Generic User Property Server model. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_manu_prop_srv_t. - - Returns New Generic Manufacturer Property Server Model instance. - - ESP_BLE_MESH_MODEL_GEN_CLIENT_PROP_SRV(srv_pub, srv_data) Define a new Generic User Property Server Model. Note 1. The Generic Client Property Server model is a root model. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_gen_client_prop_srv_t. - - Returns New Generic Client Property Server Model instance. - Type Definitions - typedef void (*esp_ble_mesh_generic_client_cb_t)(esp_ble_mesh_generic_client_cb_event_t event, esp_ble_mesh_generic_client_cb_param_t *param) Bluetooth Mesh Generic Client Model function. Generic Client Model callback function type - Param event Event type - Param param Pointer to callback parameter - typedef void (*esp_ble_mesh_generic_server_cb_t)(esp_ble_mesh_generic_server_cb_event_t event, esp_ble_mesh_generic_server_cb_param_t *param) Bluetooth Mesh Generic Server Model function. Generic Server Model callback function type - Param event Event type - Param param Pointer to callback parameter Enumerations - enum esp_ble_mesh_generic_client_cb_event_t This enum value is the event of Generic Client Model Values: - enumerator ESP_BLE_MESH_GENERIC_CLIENT_GET_STATE_EVT - enumerator ESP_BLE_MESH_GENERIC_CLIENT_SET_STATE_EVT - enumerator ESP_BLE_MESH_GENERIC_CLIENT_PUBLISH_EVT - enumerator ESP_BLE_MESH_GENERIC_CLIENT_TIMEOUT_EVT - enumerator ESP_BLE_MESH_GENERIC_CLIENT_EVT_MAX - enumerator ESP_BLE_MESH_GENERIC_CLIENT_GET_STATE_EVT - enum esp_ble_mesh_gen_user_prop_access_t This enum value is the access value of Generic User Property Values: - enumerator ESP_BLE_MESH_GEN_USER_ACCESS_PROHIBIT - enumerator ESP_BLE_MESH_GEN_USER_ACCESS_READ - enumerator ESP_BLE_MESH_GEN_USER_ACCESS_WRITE - enumerator ESP_BLE_MESH_GEN_USER_ACCESS_READ_WRITE - enumerator ESP_BLE_MESH_GEN_USER_ACCESS_PROHIBIT - enum esp_ble_mesh_gen_admin_prop_access_t This enum value is the access value of Generic Admin Property Values: - enumerator ESP_BLE_MESH_GEN_ADMIN_NOT_USER_PROP - enumerator ESP_BLE_MESH_GEN_ADMIN_ACCESS_READ - enumerator ESP_BLE_MESH_GEN_ADMIN_ACCESS_WRITE - enumerator ESP_BLE_MESH_GEN_ADMIN_ACCESS_READ_WRITE - enumerator ESP_BLE_MESH_GEN_ADMIN_NOT_USER_PROP - enum esp_ble_mesh_gen_manu_prop_access_t This enum value is the access value of Generic Manufacturer Property Values: - enumerator ESP_BLE_MESH_GEN_MANU_NOT_USER_PROP - enumerator ESP_BLE_MESH_GEN_MANU_ACCESS_READ - enumerator ESP_BLE_MESH_GEN_MANU_NOT_USER_PROP - enum esp_ble_mesh_generic_server_cb_event_t This enum value is the event of Generic Server Model Values: - enumerator ESP_BLE_MESH_GENERIC_SERVER_STATE_CHANGE_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Generic Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Generic Set/Set Unack messages are received. - - enumerator ESP_BLE_MESH_GENERIC_SERVER_RECV_GET_MSG_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Generic Get messages are received. - enumerator ESP_BLE_MESH_GENERIC_SERVER_RECV_SET_MSG_EVT When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Generic Set/Set Unack messages are received. - enumerator ESP_BLE_MESH_GENERIC_SERVER_EVT_MAX - enumerator ESP_BLE_MESH_GENERIC_SERVER_STATE_CHANGE_EVT Sensor Client/Server Models Header File components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_sensor_model_api.h This header file can be included with: #include "esp_ble_mesh_sensor_model_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_sensor_client_callback(esp_ble_mesh_sensor_client_cb_t callback) Register BLE Mesh Sensor Client Model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_sensor_client_get_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_sensor_client_get_state_t *get_state) Get the value of Sensor Server Model states using the Sensor Client Model get messages. Note If you want to know the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_sensor_message_opcode_t in esp_ble_mesh_defs.h - Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to sensor get message value. Shall not be set to NULL. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_sensor_client_set_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_sensor_client_set_state_t *set_state) Set the value of Sensor Server Model states using the Sensor Client Model set messages. Note If you want to know the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_sensor_message_opcode_t in esp_ble_mesh_defs.h - Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to sensor set message value. Shall not be set to NULL. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_register_sensor_server_callback(esp_ble_mesh_sensor_server_cb_t callback) Register BLE Mesh Sensor Server Model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. Unions - union esp_ble_mesh_sensor_client_get_state_t - #include <esp_ble_mesh_sensor_model_api.h> Sensor Client Model get message union. Public Members - esp_ble_mesh_sensor_descriptor_get_t descriptor_get For ESP_BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_GET - esp_ble_mesh_sensor_cadence_get_t cadence_get For ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_GET - esp_ble_mesh_sensor_settings_get_t settings_get For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTINGS_GET - esp_ble_mesh_sensor_setting_get_t setting_get For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_GET - esp_ble_mesh_sensor_get_t sensor_get For ESP_BLE_MESH_MODEL_OP_SENSOR_GET - esp_ble_mesh_sensor_column_get_t column_get For ESP_BLE_MESH_MODEL_OP_SENSOR_COLUMN_GET - esp_ble_mesh_sensor_series_get_t series_get For ESP_BLE_MESH_MODEL_OP_SENSOR_SERIES_GET - esp_ble_mesh_sensor_descriptor_get_t descriptor_get - union esp_ble_mesh_sensor_client_set_state_t - #include <esp_ble_mesh_sensor_model_api.h> Sensor Client Model set message union. Public Members - esp_ble_mesh_sensor_cadence_set_t cadence_set For ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET & ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET_UNACK - esp_ble_mesh_sensor_setting_set_t setting_set For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_SET & ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_SET_UNACK - esp_ble_mesh_sensor_cadence_set_t cadence_set - union esp_ble_mesh_sensor_client_status_cb_t - #include <esp_ble_mesh_sensor_model_api.h> Sensor Client Model received message union. Public Members - esp_ble_mesh_sensor_descriptor_status_cb_t descriptor_status For ESP_BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_STATUS - esp_ble_mesh_sensor_cadence_status_cb_t cadence_status For ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_STATUS - esp_ble_mesh_sensor_settings_status_cb_t settings_status For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTINGS_STATUS - esp_ble_mesh_sensor_setting_status_cb_t setting_status For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_STATUS - esp_ble_mesh_sensor_status_cb_t sensor_status For ESP_BLE_MESH_MODEL_OP_SENSOR_STATUS - esp_ble_mesh_sensor_column_status_cb_t column_status For ESP_BLE_MESH_MODEL_OP_SENSOR_COLUMN_STATUS - esp_ble_mesh_sensor_series_status_cb_t series_status For ESP_BLE_MESH_MODEL_OP_SENSOR_SERIES_STATUS - esp_ble_mesh_sensor_descriptor_status_cb_t descriptor_status - union esp_ble_mesh_sensor_server_state_change_t - #include <esp_ble_mesh_sensor_model_api.h> Sensor Server Model state change value union. Public Members - esp_ble_mesh_state_change_sensor_cadence_set_t sensor_cadence_set The recv_op in ctx can be used to decide which state is changed. Sensor Cadence Set - esp_ble_mesh_state_change_sensor_setting_set_t sensor_setting_set Sensor Setting Set - esp_ble_mesh_state_change_sensor_cadence_set_t sensor_cadence_set - union esp_ble_mesh_sensor_server_recv_get_msg_t - #include <esp_ble_mesh_sensor_model_api.h> Sensor Server Model received get message union. Public Members - esp_ble_mesh_server_recv_sensor_descriptor_get_t sensor_descriptor Sensor Descriptor Get - esp_ble_mesh_server_recv_sensor_cadence_get_t sensor_cadence Sensor Cadence Get - esp_ble_mesh_server_recv_sensor_settings_get_t sensor_settings Sensor Settings Get - esp_ble_mesh_server_recv_sensor_setting_get_t sensor_setting Sensor Setting Get - esp_ble_mesh_server_recv_sensor_get_t sensor_data Sensor Get - esp_ble_mesh_server_recv_sensor_column_get_t sensor_column Sensor Column Get - esp_ble_mesh_server_recv_sensor_series_get_t sensor_series Sensor Series Get - esp_ble_mesh_server_recv_sensor_descriptor_get_t sensor_descriptor - union esp_ble_mesh_sensor_server_recv_set_msg_t - #include <esp_ble_mesh_sensor_model_api.h> Sensor Server Model received set message union. Public Members - esp_ble_mesh_server_recv_sensor_cadence_set_t sensor_cadence Sensor Cadence Set - esp_ble_mesh_server_recv_sensor_setting_set_t sensor_setting Sensor Setting Set - esp_ble_mesh_server_recv_sensor_cadence_set_t sensor_cadence - union esp_ble_mesh_sensor_server_cb_value_t - #include <esp_ble_mesh_sensor_model_api.h> Sensor Server Model callback value union. Public Members - esp_ble_mesh_sensor_server_state_change_t state_change ESP_BLE_MESH_SENSOR_SERVER_STATE_CHANGE_EVT - esp_ble_mesh_sensor_server_recv_get_msg_t get ESP_BLE_MESH_SENSOR_SERVER_RECV_GET_MSG_EVT - esp_ble_mesh_sensor_server_recv_set_msg_t set ESP_BLE_MESH_SENSOR_SERVER_RECV_SET_MSG_EVT - esp_ble_mesh_sensor_server_state_change_t state_change Structures - struct esp_ble_mesh_sensor_descriptor_get_t Bluetooth Mesh Sensor Client Model Get and Set parameters structure. Parameters of Sensor Descriptor Get - struct esp_ble_mesh_sensor_cadence_get_t Parameter of Sensor Cadence Get - struct esp_ble_mesh_sensor_cadence_set_t Parameters of Sensor Cadence Set Public Members - uint16_t property_id Property ID for the sensor - uint8_t fast_cadence_period_divisor Divisor for the publish period - uint8_t status_trigger_type The unit and format of the Status Trigger Delta fields - struct net_buf_simple *status_trigger_delta_down Delta down value that triggers a status message - struct net_buf_simple *status_trigger_delta_up Delta up value that triggers a status message - uint8_t status_min_interval Minimum interval between two consecutive Status messages - struct net_buf_simple *fast_cadence_low Low value for the fast cadence range - struct net_buf_simple *fast_cadence_high Fast value for the fast cadence range - uint16_t property_id - struct esp_ble_mesh_sensor_settings_get_t Parameter of Sensor Settings Get Public Members - uint16_t sensor_property_id Property ID of a sensor - uint16_t sensor_property_id - struct esp_ble_mesh_sensor_setting_get_t Parameters of Sensor Setting Get - struct esp_ble_mesh_sensor_setting_set_t Parameters of Sensor Setting Set - struct esp_ble_mesh_sensor_get_t Parameters of Sensor Get - struct esp_ble_mesh_sensor_column_get_t Parameters of Sensor Column Get - struct esp_ble_mesh_sensor_series_get_t Parameters of Sensor Series Get - struct esp_ble_mesh_sensor_descriptor_status_cb_t Bluetooth Mesh Sensor Client Model Get and Set callback parameters structure. Parameter of Sensor Descriptor Status Public Members - struct net_buf_simple *descriptor Sequence of 8-octet sensor descriptors (optional) - struct net_buf_simple *descriptor - struct esp_ble_mesh_sensor_cadence_status_cb_t Parameters of Sensor Cadence Status - struct esp_ble_mesh_sensor_settings_status_cb_t Parameters of Sensor Settings Status - struct esp_ble_mesh_sensor_setting_status_cb_t Parameters of Sensor Setting Status Public Members - bool op_en Indicate id optional parameters are included - uint16_t sensor_property_id Property ID identifying a sensor - uint16_t sensor_setting_property_id Setting ID identifying a setting within a sensor - uint8_t sensor_setting_access Read/Write access rights for the setting (optional) - struct net_buf_simple *sensor_setting_raw Raw value for the setting - bool op_en - struct esp_ble_mesh_sensor_status_cb_t Parameter of Sensor Status Public Members - struct net_buf_simple *marshalled_sensor_data Value of sensor data state (optional) - struct net_buf_simple *marshalled_sensor_data - struct esp_ble_mesh_sensor_column_status_cb_t Parameters of Sensor Column Status - struct esp_ble_mesh_sensor_series_status_cb_t Parameters of Sensor Series Status - struct esp_ble_mesh_sensor_client_cb_param_t Sensor Client Model callback parameters Public Members - int error_code 0: success, otherwise failure. For the error code values please refer to errno.h file. A negative sign is added to the standard error codes in errno.h. - esp_ble_mesh_client_common_param_t *params The client common parameters. - esp_ble_mesh_sensor_client_status_cb_t status_cb The sensor status message callback values - int error_code - struct esp_ble_mesh_sensor_descriptor_t Parameters of Sensor Descriptor state Public Members - uint32_t positive_tolerance The value of Sensor Positive Tolerance field - uint32_t negative_tolerance The value of Sensor Negative Tolerance field - uint32_t sampling_function The value of Sensor Sampling Function field - uint8_t measure_period The value of Sensor Measurement Period field - uint8_t update_interval The value of Sensor Update Interval field - uint32_t positive_tolerance - struct esp_ble_mesh_sensor_setting_t Parameters of Sensor Setting state - struct esp_ble_mesh_sensor_cadence_t Parameters of Sensor Cadence state Public Members - uint8_t period_divisor The value of Fast Cadence Period Divisor field - uint8_t trigger_type The value of Status Trigger Type field - struct net_buf_simple *trigger_delta_down Note: The parameter "size" in trigger_delta_down, trigger_delta_up, fast_cadence_low & fast_cadence_high indicates the exact length of these four parameters, and they are associated with the Sensor Property ID. Users need to initialize the "size" precisely. The value of Status Trigger Delta Down field - struct net_buf_simple *trigger_delta_up The value of Status Trigger Delta Up field - uint8_t min_interval The value of Status Min Interval field - struct net_buf_simple *fast_cadence_low The value of Fast Cadence Low field - struct net_buf_simple *fast_cadence_high The value of Fast Cadence High field - uint8_t period_divisor - struct esp_ble_mesh_sensor_data_t Parameters of Sensor Data state Public Members - uint8_t format Format A: The Length field is a 1-based uint4 value (valid range 0x0–0xF, representing range of 1 – 16). Format B: The Length field is a 1-based uint7 value (valid range 0x0–0x7F, representing range of 1 – 127). The value 0x7F represents a length of zero. The value of the Sensor Data format - uint8_t length The value of the Sensor Data length - struct net_buf_simple *raw_value The value of Sensor Data raw value - uint8_t format - struct esp_ble_mesh_sensor_series_column_t Parameters of Sensor Series Column state - struct esp_ble_mesh_sensor_state_t Parameters of Sensor states Public Members - uint16_t sensor_property_id The value of Sensor Property ID field - esp_ble_mesh_sensor_descriptor_t descriptor Parameters of the Sensor Descriptor state - const uint8_t setting_count Multiple Sensor Setting states may be present for each sensor. The Sensor Setting Property ID values shall be unique for each Sensor Property ID that identifies a sensor within an element. - esp_ble_mesh_sensor_setting_t *settings Parameters of the Sensor Setting state - esp_ble_mesh_sensor_cadence_t *cadence The Sensor Cadence state may be not supported by sensors based on device properties referencing "non-scalar characteristics" such as "histograms" or "composite characteristics". Parameters of the Sensor Cadence state - esp_ble_mesh_sensor_data_t sensor_data Parameters of the Sensor Data state - esp_ble_mesh_sensor_series_column_t series_column Parameters of the Sensor Series Column state - uint16_t sensor_property_id - struct esp_ble_mesh_sensor_srv_t User data of Sensor Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Sensor Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - const uint8_t state_count Sensor state count - esp_ble_mesh_sensor_state_t *states Parameters of the Sensor states - esp_ble_mesh_model_t *model - struct esp_ble_mesh_sensor_setup_srv_t User data of Sensor Setup Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Sensor Setup Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - const uint8_t state_count Sensor state count - esp_ble_mesh_sensor_state_t *states Parameters of the Sensor states - esp_ble_mesh_model_t *model - struct esp_ble_mesh_state_change_sensor_cadence_set_t Parameters of Sensor Cadence Set state change event Public Members - uint16_t property_id The value of Sensor Property ID state - uint8_t period_divisor The value of Fast Cadence Period Divisor state - uint8_t trigger_type The value of Status Trigger Type state - struct net_buf_simple *trigger_delta_down The value of Status Trigger Delta Down state - struct net_buf_simple *trigger_delta_up The value of Status Trigger Delta Up state - uint8_t min_interval The value of Status Min Interval state - struct net_buf_simple *fast_cadence_low The value of Fast Cadence Low state - struct net_buf_simple *fast_cadence_high The value of Fast Cadence High state - uint16_t property_id - struct esp_ble_mesh_state_change_sensor_setting_set_t Parameters of Sensor Setting Set state change event - struct esp_ble_mesh_server_recv_sensor_descriptor_get_t Context of the received Sensor Descriptor Get message - struct esp_ble_mesh_server_recv_sensor_cadence_get_t Context of the received Sensor Cadence Get message - struct esp_ble_mesh_server_recv_sensor_settings_get_t Context of the received Sensor Settings Get message - struct esp_ble_mesh_server_recv_sensor_setting_get_t Context of the received Sensor Setting Get message - struct esp_ble_mesh_server_recv_sensor_get_t Context of the received Sensor Get message - struct esp_ble_mesh_server_recv_sensor_column_get_t Context of the received Sensor Column Get message - struct esp_ble_mesh_server_recv_sensor_series_get_t Context of the received Sensor Series Get message - struct esp_ble_mesh_server_recv_sensor_cadence_set_t Context of the received Sensor Cadence Set message - struct esp_ble_mesh_server_recv_sensor_setting_set_t Context of the received Sensor Setting Set message - struct esp_ble_mesh_sensor_server_cb_param_t Sensor Server Model callback parameters Public Members - esp_ble_mesh_model_t *model Pointer to Sensor Server Models - esp_ble_mesh_msg_ctx_t ctx Context of the received messages - esp_ble_mesh_sensor_server_cb_value_t value Value of the received Sensor Messages - esp_ble_mesh_model_t *model Macros - ESP_BLE_MESH_MODEL_SENSOR_CLI(cli_pub, cli_data) Define a new Sensor Client Model. Note This API needs to be called for each element on which the application needs to have a Sensor Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Sensor Client Model instance. - ESP_BLE_MESH_MODEL_SENSOR_SRV(srv_pub, srv_data) Sensor Server Models related context. Define a new Sensor Server Model. Note 1. The Sensor Server model is a root model. When this model is present on an element, the corresponding Sensor Setup Server model shall also be present. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_sensor_srv_t. - - Returns New Sensor Server Model instance. - - ESP_BLE_MESH_MODEL_SENSOR_SETUP_SRV(srv_pub, srv_data) Define a new Sensor Setup Server Model. Note 1. The Sensor Setup Server model extends the Sensor Server model. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_sensor_setup_srv_t. - - Returns New Sensor Setup Server Model instance. - - ESP_BLE_MESH_INVALID_SENSOR_PROPERTY_ID Invalid Sensor Property ID - ESP_BLE_MESH_SENSOR_PROPERTY_ID_LEN Length of Sensor Property ID - ESP_BLE_MESH_SENSOR_DESCRIPTOR_LEN Length of Sensor Descriptor state - ESP_BLE_MESH_SENSOR_UNSPECIFIED_POS_TOLERANCE Unspecified Sensor Positive Tolerance - ESP_BLE_MESH_SENSOR_UNSPECIFIED_NEG_TOLERANCE Unspecified Sensor Negative Tolerance - ESP_BLE_MESH_SENSOR_NOT_APPL_MEASURE_PERIOD Not applicable Sensor Measurement Period - ESP_BLE_MESH_SENSOR_NOT_APPL_UPDATE_INTERVAL Not applicable Sensor Update Interval - ESP_BLE_MESH_INVALID_SENSOR_SETTING_PROPERTY_ID Invalid Sensor Setting Property ID - ESP_BLE_MESH_SENSOR_SETTING_PROPERTY_ID_LEN Length of Sensor Setting Property ID - ESP_BLE_MESH_SENSOR_SETTING_ACCESS_LEN Length of Sensor Setting Access - ESP_BLE_MESH_SENSOR_SETTING_ACCESS_READ Sensor Setting Access - Read - ESP_BLE_MESH_SENSOR_SETTING_ACCESS_READ_WRITE Sensor Setting Access - Read & Write - ESP_BLE_MESH_SENSOR_DIVISOR_TRIGGER_TYPE_LEN Length of Sensor Divisor Trigger Type - ESP_BLE_MESH_SENSOR_STATUS_MIN_INTERVAL_LEN Length of Sensor Status Min Interval - ESP_BLE_MESH_SENSOR_PERIOD_DIVISOR_MAX_VALUE Maximum value of Sensor Period Divisor - ESP_BLE_MESH_SENSOR_STATUS_MIN_INTERVAL_MAX Maximum value of Sensor Status Min Interval - ESP_BLE_MESH_SENSOR_STATUS_TRIGGER_TYPE_CHAR Sensor Status Trigger Type - Format Type of the characteristic that the Sensor Property ID state references - ESP_BLE_MESH_SENSOR_STATUS_TRIGGER_TYPE_UINT16 Sensor Status Trigger Type - Format Type "uint16" - ESP_BLE_MESH_SENSOR_DATA_FORMAT_A Sensor Data Format A - ESP_BLE_MESH_SENSOR_DATA_FORMAT_B Sensor Data Format B - ESP_BLE_MESH_SENSOR_DATA_FORMAT_A_MPID_LEN MPID length of Sensor Data Format A - ESP_BLE_MESH_SENSOR_DATA_FORMAT_B_MPID_LEN MPID length of Sensor Data Format B - ESP_BLE_MESH_SENSOR_DATA_ZERO_LEN Zero length of Sensor Data. Note: The Length field is a 1-based uint7 value (valid range 0x0–0x7F, representing range of 1–127). The value 0x7F represents a length of zero. - ESP_BLE_MESH_GET_SENSOR_DATA_FORMAT(_data) Get format of the sensor data. Note Multiple sensor data may be concatenated. Make sure the _data pointer is updated before getting the format of the corresponding sensor data. - Parameters _data -- Pointer to the start of the sensor data. - - Returns Format of the sensor data. - ESP_BLE_MESH_GET_SENSOR_DATA_LENGTH(_data, _fmt) Get length of the sensor data. Note Multiple sensor data may be concatenated. Make sure the _data pointer is updated before getting the length of the corresponding sensor data. - Parameters _data -- Pointer to the start of the sensor data. _fmt -- Format of the sensor data. - - Returns Length (zero-based) of the sensor data. - ESP_BLE_MESH_GET_SENSOR_DATA_PROPERTY_ID(_data, _fmt) Get Sensor Property ID of the sensor data. Note Multiple sensor data may be concatenated. Make sure the _data pointer is updated before getting Sensor Property ID of the corresponding sensor data. - Parameters _data -- Pointer to the start of the sensor data. _fmt -- Format of the sensor data. - - Returns Sensor Property ID of the sensor data. - ESP_BLE_MESH_SENSOR_DATA_FORMAT_A_MPID(_len, _id) Generate a MPID value for sensor data with Format A. Note 1. The Format field is 0b0 and indicates that Format A is used. The Length field is a 1-based uint4 value (valid range 0x0–0xF, representing range of 1–16). The Property ID is an 11-bit bit field representing 11 LSb of a Property ID. This format may be used for Property Values that are not longer than 16 octets and for Property IDs less than 0x0800. - Parameters _len -- Length of Sensor Raw value. _id -- Sensor Property ID. - - Returns 2-octet MPID value for sensor data with Format A. - - ESP_BLE_MESH_SENSOR_DATA_FORMAT_B_MPID(_len, _id) Generate a MPID value for sensor data with Format B. Note 1. The Format field is 0b1 and indicates Format B is used. The Length field is a 1-based uint7 value (valid range 0x0–0x7F, representing range of 1–127). The value 0x7F represents a length of zero. The Property ID is a 16-bit bit field representing a Property ID. This format may be used for Property Values not longer than 128 octets and for any Property IDs. Property values longer than 128 octets are not supported by the Sensor Status message. Exclude the generated 1-octet value, the 2-octet Sensor Property ID - Parameters _len -- Length of Sensor Raw value. _id -- Sensor Property ID. - - Returns 3-octet MPID value for sensor data with Format B. - Type Definitions - typedef void (*esp_ble_mesh_sensor_client_cb_t)(esp_ble_mesh_sensor_client_cb_event_t event, esp_ble_mesh_sensor_client_cb_param_t *param) Bluetooth Mesh Sensor Client Model function. Sensor Client Model callback function type - Param event Event type - Param param Pointer to callback parameter - typedef void (*esp_ble_mesh_sensor_server_cb_t)(esp_ble_mesh_sensor_server_cb_event_t event, esp_ble_mesh_sensor_server_cb_param_t *param) Bluetooth Mesh Sensor Server Model function. Sensor Server Model callback function type - Param event Event type - Param param Pointer to callback parameter Enumerations - enum esp_ble_mesh_sensor_client_cb_event_t This enum value is the event of Sensor Client Model Values: - enumerator ESP_BLE_MESH_SENSOR_CLIENT_GET_STATE_EVT - enumerator ESP_BLE_MESH_SENSOR_CLIENT_SET_STATE_EVT - enumerator ESP_BLE_MESH_SENSOR_CLIENT_PUBLISH_EVT - enumerator ESP_BLE_MESH_SENSOR_CLIENT_TIMEOUT_EVT - enumerator ESP_BLE_MESH_SENSOR_CLIENT_EVT_MAX - enumerator ESP_BLE_MESH_SENSOR_CLIENT_GET_STATE_EVT - enum esp_ble_mesh_sensor_sample_func This enum value is value of Sensor Sampling Function Values: - enumerator ESP_BLE_MESH_SAMPLE_FUNC_UNSPECIFIED - enumerator ESP_BLE_MESH_SAMPLE_FUNC_INSTANTANEOUS - enumerator ESP_BLE_MESH_SAMPLE_FUNC_ARITHMETIC_MEAN - enumerator ESP_BLE_MESH_SAMPLE_FUNC_RMS - enumerator ESP_BLE_MESH_SAMPLE_FUNC_MAXIMUM - enumerator ESP_BLE_MESH_SAMPLE_FUNC_MINIMUM - enumerator ESP_BLE_MESH_SAMPLE_FUNC_ACCUMULATED - enumerator ESP_BLE_MESH_SAMPLE_FUNC_COUNT - enumerator ESP_BLE_MESH_SAMPLE_FUNC_UNSPECIFIED - enum esp_ble_mesh_sensor_server_cb_event_t This enum value is the event of Sensor Server Model Values: - enumerator ESP_BLE_MESH_SENSOR_SERVER_STATE_CHANGE_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Sensor Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Sensor Set/Set Unack messages are received. - - enumerator ESP_BLE_MESH_SENSOR_SERVER_RECV_GET_MSG_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Sensor Get messages are received. - enumerator ESP_BLE_MESH_SENSOR_SERVER_RECV_SET_MSG_EVT When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Sensor Set/Set Unack messages are received. - enumerator ESP_BLE_MESH_SENSOR_SERVER_EVT_MAX - enumerator ESP_BLE_MESH_SENSOR_SERVER_STATE_CHANGE_EVT Time and Scenes Client/Server Models Header File components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_time_scene_model_api.h This header file can be included with: #include "esp_ble_mesh_time_scene_model_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_time_scene_client_callback(esp_ble_mesh_time_scene_client_cb_t callback) Register BLE Mesh Time Scene Client Model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_time_scene_client_get_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_time_scene_client_get_state_t *get_state) Get the value of Time Scene Server Model states using the Time Scene Client Model get messages. Note If you want to know the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_time_scene_message_opcode_t in esp_ble_mesh_defs.h - Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer to time scene get message value. Shall not be set to NULL. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_time_scene_client_set_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_time_scene_client_set_state_t *set_state) Set the value of Time Scene Server Model states using the Time Scene Client Model set messages. Note If you want to know the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_time_scene_message_opcode_t in esp_ble_mesh_defs.h - Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer to time scene set message value. Shall not be set to NULL. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_register_time_scene_server_callback(esp_ble_mesh_time_scene_server_cb_t callback) Register BLE Mesh Time and Scenes Server Model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. Unions - union esp_ble_mesh_time_scene_client_get_state_t - #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Client Model get message union. Public Members - esp_ble_mesh_scheduler_act_get_t scheduler_act_get For ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_GET - esp_ble_mesh_scheduler_act_get_t scheduler_act_get - union esp_ble_mesh_time_scene_client_set_state_t - #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Client Model set message union. Public Members - esp_ble_mesh_time_set_t time_set For ESP_BLE_MESH_MODEL_OP_TIME_SET - esp_ble_mesh_time_zone_set_t time_zone_set For ESP_BLE_MESH_MODEL_OP_TIME_ZONE_SET - esp_ble_mesh_tai_utc_delta_set_t tai_utc_delta_set For ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_SET - esp_ble_mesh_time_role_set_t time_role_set For ESP_BLE_MESH_MODEL_OP_TIME_ROLE_SET - esp_ble_mesh_scene_store_t scene_store For ESP_BLE_MESH_MODEL_OP_SCENE_STORE & ESP_BLE_MESH_MODEL_OP_SCENE_STORE_UNACK - esp_ble_mesh_scene_recall_t scene_recall For ESP_BLE_MESH_MODEL_OP_SCENE_RECALL & ESP_BLE_MESH_MODEL_OP_SCENE_RECALL_UNACK - esp_ble_mesh_scene_delete_t scene_delete For ESP_BLE_MESH_MODEL_OP_SCENE_DELETE & ESP_BLE_MESH_MODEL_OP_SCENE_DELETE_UNACK - esp_ble_mesh_scheduler_act_set_t scheduler_act_set For ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET & ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET_UNACK - esp_ble_mesh_time_set_t time_set - union esp_ble_mesh_time_scene_client_status_cb_t - #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Client Model received message union. Public Members - esp_ble_mesh_time_status_cb_t time_status For ESP_BLE_MESH_MODEL_OP_TIME_STATUS - esp_ble_mesh_time_zone_status_cb_t time_zone_status For ESP_BLE_MESH_MODEL_OP_TIME_ZONE_STATUS - esp_ble_mesh_tai_utc_delta_status_cb_t tai_utc_delta_status For ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_STATUS - esp_ble_mesh_time_role_status_cb_t time_role_status For ESP_BLE_MESH_MODEL_OP_TIME_ROLE_STATUS - esp_ble_mesh_scene_status_cb_t scene_status For ESP_BLE_MESH_MODEL_OP_SCENE_STATUS - esp_ble_mesh_scene_register_status_cb_t scene_register_status For ESP_BLE_MESH_MODEL_OP_SCENE_REGISTER_STATUS - esp_ble_mesh_scheduler_status_cb_t scheduler_status For ESP_BLE_MESH_MODEL_OP_SCHEDULER_STATUS - esp_ble_mesh_scheduler_act_status_cb_t scheduler_act_status For ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_STATUS - esp_ble_mesh_time_status_cb_t time_status - union esp_ble_mesh_time_scene_server_state_change_t - #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Server Model state change value union. Public Members - esp_ble_mesh_state_change_time_set_t time_set The recv_op in ctx can be used to decide which state is changed. Time Set - esp_ble_mesh_state_change_time_status_t time_status Time Status - esp_ble_mesh_state_change_time_zone_set_t time_zone_set Time Zone Set - esp_ble_mesh_state_change_tai_utc_delta_set_t tai_utc_delta_set TAI UTC Delta Set - esp_ble_mesh_state_change_time_role_set_t time_role_set Time Role Set - esp_ble_mesh_state_change_scene_store_t scene_store Scene Store - esp_ble_mesh_state_change_scene_recall_t scene_recall Scene Recall - esp_ble_mesh_state_change_scene_delete_t scene_delete Scene Delete - esp_ble_mesh_state_change_scheduler_act_set_t scheduler_act_set Scheduler Action Set - esp_ble_mesh_state_change_time_set_t time_set - union esp_ble_mesh_time_scene_server_recv_get_msg_t - #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Server Model received get message union. Public Members - esp_ble_mesh_server_recv_scheduler_act_get_t scheduler_act Scheduler Action Get - esp_ble_mesh_server_recv_scheduler_act_get_t scheduler_act - union esp_ble_mesh_time_scene_server_recv_set_msg_t - #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Server Model received set message union. Public Members - esp_ble_mesh_server_recv_time_set_t time Time Set - esp_ble_mesh_server_recv_time_zone_set_t time_zone Time Zone Set - esp_ble_mesh_server_recv_tai_utc_delta_set_t tai_utc_delta TAI-UTC Delta Set - esp_ble_mesh_server_recv_time_role_set_t time_role Time Role Set - esp_ble_mesh_server_recv_scene_store_t scene_store Scene Store/Scene Store Unack - esp_ble_mesh_server_recv_scene_recall_t scene_recall Scene Recall/Scene Recall Unack - esp_ble_mesh_server_recv_scene_delete_t scene_delete Scene Delete/Scene Delete Unack - esp_ble_mesh_server_recv_scheduler_act_set_t scheduler_act Scheduler Action Set/Scheduler Action Set Unack - esp_ble_mesh_server_recv_time_set_t time - union esp_ble_mesh_time_scene_server_recv_status_msg_t - #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Server Model received status message union. Public Members - esp_ble_mesh_server_recv_time_status_t time_status Time Status - esp_ble_mesh_server_recv_time_status_t time_status - union esp_ble_mesh_time_scene_server_cb_value_t - #include <esp_ble_mesh_time_scene_model_api.h> Time Scene Server Model callback value union. Public Members - esp_ble_mesh_time_scene_server_state_change_t state_change ESP_BLE_MESH_TIME_SCENE_SERVER_STATE_CHANGE_EVT - esp_ble_mesh_time_scene_server_recv_get_msg_t get ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_GET_MSG_EVT - esp_ble_mesh_time_scene_server_recv_set_msg_t set ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_SET_MSG_EVT - esp_ble_mesh_time_scene_server_recv_status_msg_t status ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_STATUS_MSG_EVT - esp_ble_mesh_time_scene_server_state_change_t state_change Structures - struct esp_ble_mesh_time_set_t Bluetooth Mesh Time Scene Client Model Get and Set parameters structure. Parameters of Time Set Public Members - uint8_t tai_seconds[5] The current TAI time in seconds - uint8_t sub_second The sub-second time in units of 1/256 second - uint8_t uncertainty The estimated uncertainty in 10-millisecond steps 0 = No Time Authority, 1 = Time Authority - uint16_t tai_utc_delta Current difference between TAI and UTC in seconds - uint8_t time_zone_offset The local time zone offset in 15-minute increments - uint8_t tai_seconds[5] - struct esp_ble_mesh_time_zone_set_t Parameters of Time Zone Set - struct esp_ble_mesh_tai_utc_delta_set_t Parameters of TAI-UTC Delta Set - struct esp_ble_mesh_time_role_set_t Parameter of Time Role Set - struct esp_ble_mesh_scene_store_t Parameter of Scene Store - struct esp_ble_mesh_scene_recall_t Parameters of Scene Recall - struct esp_ble_mesh_scene_delete_t Parameter of Scene Delete - struct esp_ble_mesh_scheduler_act_get_t Parameter of Scheduler Action Get Public Members - uint8_t index Index of the Schedule Register entry to get - uint8_t index - struct esp_ble_mesh_scheduler_act_set_t Parameters of Scheduler Action Set Public Members - uint64_t index Index of the Schedule Register entry to set - uint64_t year Scheduled year for the action - uint64_t month Scheduled month for the action - uint64_t day Scheduled day of the month for the action - uint64_t hour Scheduled hour for the action - uint64_t minute Scheduled minute for the action - uint64_t second Scheduled second for the action - uint64_t day_of_week Schedule days of the week for the action - uint64_t action Action to be performed at the scheduled time - uint64_t trans_time Transition time for this action - uint16_t scene_number Transition time for this action - uint64_t index - struct esp_ble_mesh_time_status_cb_t Bluetooth Mesh Time Scene Client Model Get and Set callback parameters structure. Parameters of Time Status Public Members - uint8_t tai_seconds[5] The current TAI time in seconds - uint8_t sub_second The sub-second time in units of 1/256 second - uint8_t uncertainty The estimated uncertainty in 10-millisecond steps 0 = No Time Authority, 1 = Time Authority - uint16_t tai_utc_delta Current difference between TAI and UTC in seconds - uint8_t time_zone_offset The local time zone offset in 15-minute increments - uint8_t tai_seconds[5] - struct esp_ble_mesh_time_zone_status_cb_t Parameters of Time Zone Status - struct esp_ble_mesh_tai_utc_delta_status_cb_t Parameters of TAI-UTC Delta Status Public Members - uint16_t tai_utc_delta_curr Current difference between TAI and UTC in seconds - uint16_t padding_1 Always 0b0. Other values are Prohibited. - uint16_t tai_utc_delta_new Upcoming difference between TAI and UTC in seconds - uint16_t padding_2 Always 0b0. Other values are Prohibited. - uint8_t tai_delta_change[5] TAI Seconds time of the upcoming TAI-UTC Delta change - uint16_t tai_utc_delta_curr - struct esp_ble_mesh_time_role_status_cb_t Parameter of Time Role Status - struct esp_ble_mesh_scene_status_cb_t Parameters of Scene Status Public Members - bool op_en Indicate if optional parameters are included - uint8_t status_code Status code of the last operation - uint16_t current_scene Scene Number of the current scene - uint16_t target_scene Scene Number of the target scene (optional) - uint8_t remain_time Time to complete state transition (C.1) - bool op_en - struct esp_ble_mesh_scene_register_status_cb_t Parameters of Scene Register Status - struct esp_ble_mesh_scheduler_status_cb_t Parameter of Scheduler Status Public Members - uint16_t schedules Bit field indicating defined Actions in the Schedule Register - uint16_t schedules - struct esp_ble_mesh_scheduler_act_status_cb_t Parameters of Scheduler Action Status Public Members - uint64_t index Enumerates (selects) a Schedule Register entry - uint64_t year Scheduled year for the action - uint64_t month Scheduled month for the action - uint64_t day Scheduled day of the month for the action - uint64_t hour Scheduled hour for the action - uint64_t minute Scheduled minute for the action - uint64_t second Scheduled second for the action - uint64_t day_of_week Schedule days of the week for the action - uint64_t action Action to be performed at the scheduled time - uint64_t trans_time Transition time for this action - uint16_t scene_number Transition time for this action - uint64_t index - struct esp_ble_mesh_time_scene_client_cb_param_t Time Scene Client Model callback parameters Public Members - int error_code Appropriate error code - esp_ble_mesh_client_common_param_t *params The client common parameters. - esp_ble_mesh_time_scene_client_status_cb_t status_cb The scene status message callback values - int error_code - struct esp_ble_mesh_time_state_t Parameters of Time state Public Members - uint8_t tai_seconds[5] The value of the TAI Seconds state - uint8_t subsecond The value of the Subsecond field - uint8_t uncertainty The value of the Uncertainty field - uint8_t time_zone_offset_curr The value of the Time Zone Offset Current field - uint8_t time_zone_offset_new The value of the Time Zone Offset New state - uint8_t tai_zone_change[5] The value of the TAI of Zone Change field The value of the Time Authority bit - uint16_t tai_utc_delta_curr The value of the TAI-UTC Delta Current state - uint16_t tai_utc_delta_new The value of the TAI-UTC Delta New state - uint8_t tai_delta_change[5] The value of the TAI of Delta Change field - struct esp_ble_mesh_time_state_t::[anonymous] time Parameters of the Time state - uint8_t time_role The value of the Time Role state - uint8_t tai_seconds[5] - struct esp_ble_mesh_time_srv_t User data of Time Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Time Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_time_state_t *state Parameters of the Time state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_time_setup_srv_t User data of Time Setup Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Time Setup Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_time_state_t *state Parameters of the Time state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_scene_register_t Scene Store is an operation of storing values of a present state of an element. The structure and meaning of the stored state is determined by a model. States to be stored are specified by each model. The Scene Store operation shall persistently store all values of all states marked as Stored with Scene for all models present on all elements of a node. If a model is extending another model, the extending model shall determine the Stored with Scene behavior of that model. Parameters of Scene Register state Public Members - uint16_t scene_number The value of the Scene Number - uint8_t scene_type The value of the Scene Type - struct net_buf_simple *scene_value Scene value may use a union to represent later, the union contains structures of all the model states which can be stored in a scene. The value of the Scene Value - - struct esp_ble_mesh_scenes_state_t Parameters of Scenes state. Scenes serve as memory banks for storage of states (e.g., a power level or a light level/color). Values of states of an element can be stored as a scene and can be recalled later from the scene memory. A scene is represented by a Scene Number, which is a 16-bit non-zero, mesh-wide value. (There can be a maximum of 65535 scenes in a mesh network.) The meaning of a scene, as well as the state storage container associated with it, are determined by a model. The Scenes state change may start numerous parallel model transitions. In that case, each individual model handles the transition internally. The scene transition is defined as a group of individual model transitions started by a Scene Recall operation. The scene transition is in progress when at least one transition from the group of individual model transitions is in progress. Public Members - const uint16_t scene_count The Scenes state's scene count - esp_ble_mesh_scene_register_t *scenes Parameters of the Scenes state - uint16_t current_scene The Current Scene state is a 16-bit value that contains either the Scene Number of the currently active scene or a value of 0x0000 when no scene is active. When a Scene Store operation or a Scene Recall operation completes with success, the Current Scene state value shall be to the Scene Number used during that operation. When the Current Scene Number is deleted from a Scene Register state as a result of Scene Delete operation, the Current Scene state shall be set to 0x0000. When any of the element's state that is marked as “Stored with Scene” has changed not as a result of a Scene Recall operation, the value of the Current Scene state shall be set to 0x0000. When a scene transition is in progress, the value of the Current Scene state shall be set to 0x0000. The value of the Current Scene state - uint16_t target_scene The Target Scene state is a 16-bit value that contains the target Scene Number when a scene transition is in progress. When the scene transition is in progress and the target Scene Number is deleted from a Scene Register state as a result of Scene Delete operation, the Target Scene state shall be set to 0x0000. When the scene transition is in progress and a new Scene Number is stored in the Scene Register as a result of Scene Store operation, the Target Scene state shall be set to the new Scene Number. When the scene transition is not in progress, the value of the Target Scene state shall be set to 0x0000. The value of the Target Scene state - uint8_t status_code The status code of the last scene operation - bool in_progress Indicate if the scene transition is in progress - const uint16_t scene_count - struct esp_ble_mesh_scene_srv_t User data of Scene Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Scene Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_scenes_state_t *state Parameters of the Scenes state - esp_ble_mesh_last_msg_info_t last Parameters of the last received set message - esp_ble_mesh_state_transition_t transition Parameters of state transition - esp_ble_mesh_model_t *model - struct esp_ble_mesh_scene_setup_srv_t User data of Scene Setup Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Scene Setup Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_scenes_state_t *state Parameters of the Scenes state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_schedule_register_t Parameters of Scheduler Register state Public Members - bool in_use Indicate if the registered schedule is in use - uint64_t year The value of Scheduled year for the action - uint64_t month The value of Scheduled month for the action - uint64_t day The value of Scheduled day of the month for the action - uint64_t hour The value of Scheduled hour for the action - uint64_t minute The value of Scheduled minute for the action - uint64_t second The value of Scheduled second for the action - uint64_t day_of_week The value of Schedule days of the week for the action - uint64_t action The value of Action to be performed at the scheduled time - uint64_t trans_time The value of Transition time for this action - uint16_t scene_number The value of Scene Number to be used for some actions - bool in_use - struct esp_ble_mesh_scheduler_state_t Parameters of Scheduler state Public Members - const uint8_t schedule_count Scheduler count - esp_ble_mesh_schedule_register_t *schedules Up to 16 scheduled entries - const uint8_t schedule_count - struct esp_ble_mesh_scheduler_srv_t User data of Scheduler Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Scheduler Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_scheduler_state_t *state Parameters of the Scheduler state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_scheduler_setup_srv_t User data of Scheduler Setup Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Scheduler Setup Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_scheduler_state_t *state Parameters of the Scheduler state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_state_change_time_set_t Parameters of Time Set state change event Public Members - uint8_t tai_seconds[5] The current TAI time in seconds - uint8_t subsecond The sub-second time in units of 1/256 second - uint8_t uncertainty The estimated uncertainty in 10-millisecond steps 0 = No Time Authority, 1 = Time Authority - uint16_t tai_utc_delta_curr Current difference between TAI and UTC in seconds - uint8_t time_zone_offset_curr The local time zone offset in 15-minute increments - uint8_t tai_seconds[5] - struct esp_ble_mesh_state_change_time_status_t Parameters of Time Status state change event Public Members - uint8_t tai_seconds[5] The current TAI time in seconds - uint8_t subsecond The sub-second time in units of 1/256 second - uint8_t uncertainty The estimated uncertainty in 10-millisecond steps 0 = No Time Authority, 1 = Time Authority - uint16_t tai_utc_delta_curr Current difference between TAI and UTC in seconds - uint8_t time_zone_offset_curr The local time zone offset in 15-minute increments - uint8_t tai_seconds[5] - struct esp_ble_mesh_state_change_time_zone_set_t Parameters of Time Zone Set state change event - struct esp_ble_mesh_state_change_tai_utc_delta_set_t Parameters of TAI UTC Delta Set state change event - struct esp_ble_mesh_state_change_time_role_set_t Parameter of Time Role Set state change event - struct esp_ble_mesh_state_change_scene_store_t Parameter of Scene Store state change event - struct esp_ble_mesh_state_change_scene_recall_t Parameter of Scene Recall state change event Public Members - uint16_t scene_number The number of scenes to be recalled - uint16_t scene_number - struct esp_ble_mesh_state_change_scene_delete_t Parameter of Scene Delete state change event - struct esp_ble_mesh_state_change_scheduler_act_set_t Parameter of Scheduler Action Set state change event Public Members - uint64_t index Index of the Schedule Register entry to set - uint64_t year Scheduled year for the action - uint64_t month Scheduled month for the action - uint64_t day Scheduled day of the month for the action - uint64_t hour Scheduled hour for the action - uint64_t minute Scheduled minute for the action - uint64_t second Scheduled second for the action - uint64_t day_of_week Schedule days of the week for the action - uint64_t action Action to be performed at the scheduled time - uint64_t trans_time Transition time for this action - uint16_t scene_number Scene number to be used for some actions - uint64_t index - struct esp_ble_mesh_server_recv_scheduler_act_get_t Context of the received Scheduler Action Get message Public Members - uint8_t index Index of the Schedule Register entry to get - uint8_t index - struct esp_ble_mesh_server_recv_time_set_t Context of the received Time Set message Public Members - uint8_t tai_seconds[5] The current TAI time in seconds - uint8_t subsecond The sub-second time in units of 1/256 second - uint8_t uncertainty The estimated uncertainty in 10-millisecond steps 0 = No Time Authority, 1 = Time Authority - uint16_t tai_utc_delta Current difference between TAI and UTC in seconds - uint8_t time_zone_offset The local time zone offset in 15-minute increments - uint8_t tai_seconds[5] - struct esp_ble_mesh_server_recv_time_zone_set_t Context of the received Time Zone Set message - struct esp_ble_mesh_server_recv_tai_utc_delta_set_t Context of the received TAI UTC Delta Set message - struct esp_ble_mesh_server_recv_time_role_set_t Context of the received Time Role Set message - struct esp_ble_mesh_server_recv_scene_store_t Context of the received Scene Store message - struct esp_ble_mesh_server_recv_scene_recall_t Context of the received Scene Recall message - struct esp_ble_mesh_server_recv_scene_delete_t Context of the received Scene Delete message - struct esp_ble_mesh_server_recv_scheduler_act_set_t Context of the received Scheduler Action Set message Public Members - uint64_t index Index of the Schedule Register entry to set - uint64_t year Scheduled year for the action - uint64_t month Scheduled month for the action - uint64_t day Scheduled day of the month for the action - uint64_t hour Scheduled hour for the action - uint64_t minute Scheduled minute for the action - uint64_t second Scheduled second for the action - uint64_t day_of_week Schedule days of the week for the action - uint64_t action Action to be performed at the scheduled time - uint64_t trans_time Transition time for this action - uint16_t scene_number Scene number to be used for some actions - uint64_t index - struct esp_ble_mesh_server_recv_time_status_t Context of the received Time Status message Public Members - uint8_t tai_seconds[5] The current TAI time in seconds - uint8_t subsecond The sub-second time in units of 1/256 second - uint8_t uncertainty The estimated uncertainty in 10-millisecond steps 0 = No Time Authority, 1 = Time Authority - uint16_t tai_utc_delta Current difference between TAI and UTC in seconds - uint8_t time_zone_offset The local time zone offset in 15-minute increments - uint8_t tai_seconds[5] - struct esp_ble_mesh_time_scene_server_cb_param_t Time Scene Server Model callback parameters Public Members - esp_ble_mesh_model_t *model Pointer to Time and Scenes Server Models - esp_ble_mesh_msg_ctx_t ctx Context of the received messages - esp_ble_mesh_time_scene_server_cb_value_t value Value of the received Time and Scenes Messages - esp_ble_mesh_model_t *model Macros - ESP_BLE_MESH_MODEL_TIME_CLI(cli_pub, cli_data) Define a new Time Client Model. Note This API needs to be called for each element on which the application needs to have a Time Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Time Client Model instance. - ESP_BLE_MESH_MODEL_SCENE_CLI(cli_pub, cli_data) Define a new Scene Client Model. Note This API needs to be called for each element on which the application needs to have a Scene Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Scene Client Model instance. - ESP_BLE_MESH_MODEL_SCHEDULER_CLI(cli_pub, cli_data) Define a new Scheduler Client Model. Note This API needs to be called for each element on which the application needs to have a Scheduler Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Scheduler Client Model instance. - ESP_BLE_MESH_MODEL_TIME_SRV(srv_pub, srv_data) Time Scene Server Models related context. Define a new Time Server Model. Note 1. The Time Server model is a root model. When this model is present on an Element, the corresponding Time Setup Server model shall also be present. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_time_srv_t. - - Returns New Time Server Model instance. - - ESP_BLE_MESH_MODEL_TIME_SETUP_SRV(srv_data) Define a new Time Setup Server Model. Note 1. The Time Setup Server model extends the Time Server model. Time is sensitive information that is propagated across a mesh network. Only an authorized Time Client should be allowed to change the Time and Time Role states. A dedicated application key Bluetooth SIG Proprietary should be used on the Time Setup Server to restrict access to the server to only authorized Time Clients. This model does not support subscribing nor publishing. - Parameters srv_data -- Pointer to the unique struct esp_ble_mesh_time_setup_srv_t. - - Returns New Time Setup Server Model instance. - - ESP_BLE_MESH_MODEL_SCENE_SRV(srv_pub, srv_data) Define a new Scene Server Model. Note 1. The Scene Server model is a root model. When this model is present on an Element, the corresponding Scene Setup Server model shall also be present. This model shall support model publication and model subscription. The model may be present only on the Primary element of a node. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scene_srv_t. - - Returns New Scene Server Model instance. - - ESP_BLE_MESH_MODEL_SCENE_SETUP_SRV(srv_pub, srv_data) Define a new Scene Setup Server Model. Note 1. The Scene Setup Server model extends the Scene Server model and the Generic Default Transition Time Server model. This model shall support model subscription. The model may be present only on the Primary element of a node. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scene_setup_srv_t. - - Returns New Scene Setup Server Model instance. - - ESP_BLE_MESH_MODEL_SCHEDULER_SRV(srv_pub, srv_data) Define a new Scheduler Server Model. Note 1. The Scheduler Server model extends the Scene Server model. When this model is present on an Element, the corresponding Scheduler Setup Server model shall also be present. This model shall support model publication and model subscription. The model may be present only on the Primary element of a node. The model requires the Time Server model shall be present on the element. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scheduler_srv_t. - - Returns New Scheduler Server Model instance. - - ESP_BLE_MESH_MODEL_SCHEDULER_SETUP_SRV(srv_pub, srv_data) Define a new Scheduler Setup Server Model. Note 1. The Scheduler Setup Server model extends the Scheduler Server and the Scene Setup Server models. This model shall support model subscription. The model may be present only on the Primary element of a node. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_scheduler_setup_srv_t. - - Returns New Scheduler Setup Server Model instance. - - ESP_BLE_MESH_UNKNOWN_TAI_SECONDS Unknown TAI Seconds - ESP_BLE_MESH_UNKNOWN_TAI_ZONE_CHANGE Unknown TAI of Zone Change - ESP_BLE_MESH_UNKNOWN_TAI_DELTA_CHANGE Unknown TAI of Delta Change - ESP_BLE_MESH_TAI_UTC_DELTA_MAX_VALUE Maximum TAI-UTC Delta value - ESP_BLE_MESH_TAI_SECONDS_LEN Length of TAI Seconds - ESP_BLE_MESH_TAI_OF_ZONE_CHANGE_LEN Length of TAI of Zone Change - ESP_BLE_MESH_TAI_OF_DELTA_CHANGE_LEN Length of TAI of Delta Change - ESP_BLE_MESH_INVALID_SCENE_NUMBER Invalid Scene Number - ESP_BLE_MESH_SCENE_NUMBER_LEN Length of the Scene Number - ESP_BLE_MESH_SCHEDULE_YEAR_ANY_YEAR Any year of the Scheduled year - ESP_BLE_MESH_SCHEDULE_DAY_ANY_DAY Any day of the Scheduled day - ESP_BLE_MESH_SCHEDULE_HOUR_ANY_HOUR Any hour of the Scheduled hour - ESP_BLE_MESH_SCHEDULE_HOUR_ONCE_A_DAY Any hour of the Scheduled Day - ESP_BLE_MESH_SCHEDULE_SEC_ANY_OF_HOUR Any minute of the Scheduled hour - ESP_BLE_MESH_SCHEDULE_SEC_EVERY_15_MIN Every 15 minutes of the Scheduled hour - ESP_BLE_MESH_SCHEDULE_SEC_EVERY_20_MIN Every 20 minutes of the Scheduled hour - ESP_BLE_MESH_SCHEDULE_SEC_ONCE_AN_HOUR Once of the Scheduled hour - ESP_BLE_MESH_SCHEDULE_SEC_ANY_OF_MIN Any second of the Scheduled minute - ESP_BLE_MESH_SCHEDULE_SEC_EVERY_15_SEC Every 15 seconds of the Scheduled minute - ESP_BLE_MESH_SCHEDULE_SEC_EVERY_20_SEC Every 20 seconds of the Scheduled minute - ESP_BLE_MESH_SCHEDULE_SEC_ONCE_AN_MIN Once of the Scheduled minute - ESP_BLE_MESH_SCHEDULE_ACT_TURN_OFF Scheduled Action - Turn Off - ESP_BLE_MESH_SCHEDULE_ACT_TURN_ON Scheduled Action - Turn On - ESP_BLE_MESH_SCHEDULE_ACT_SCENE_RECALL Scheduled Action - Scene Recall - ESP_BLE_MESH_SCHEDULE_ACT_NO_ACTION Scheduled Action - No Action - ESP_BLE_MESH_SCHEDULE_SCENE_NO_SCENE Scheduled Scene - No Scene - ESP_BLE_MESH_SCHEDULE_ENTRY_MAX_INDEX Maximum number of Scheduled entries - ESP_BLE_MESH_TIME_NONE Time Role - None - ESP_BLE_MESH_TIME_AUTHORITY Time Role - Mesh Time Authority - ESP_BLE_MESH_TIME_RELAY Time Role - Mesh Time Relay - ESP_BLE_MESH_TIME_CLIENT Time Role - Mesh Time Client - ESP_BLE_MESH_SCENE_SUCCESS Scene operation - Success - ESP_BLE_MESH_SCENE_REG_FULL Scene operation - Scene Register Full - ESP_BLE_MESH_SCENE_NOT_FOUND Scene operation - Scene Not Found Type Definitions - typedef void (*esp_ble_mesh_time_scene_client_cb_t)(esp_ble_mesh_time_scene_client_cb_event_t event, esp_ble_mesh_time_scene_client_cb_param_t *param) Bluetooth Mesh Time Scene Client Model function. Time Scene Client Model callback function type - Param event Event type - Param param Pointer to callback parameter - typedef void (*esp_ble_mesh_time_scene_server_cb_t)(esp_ble_mesh_time_scene_server_cb_event_t event, esp_ble_mesh_time_scene_server_cb_param_t *param) Bluetooth Mesh Time and Scenes Server Model function. Time Scene Server Model callback function type - Param event Event type - Param param Pointer to callback parameter Enumerations - enum esp_ble_mesh_time_scene_client_cb_event_t This enum value is the event of Time Scene Client Model Values: - enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_GET_STATE_EVT - enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_SET_STATE_EVT - enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_PUBLISH_EVT - enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_TIMEOUT_EVT - enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_EVT_MAX - enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_GET_STATE_EVT - enum esp_ble_mesh_time_scene_server_cb_event_t This enum value is the event of Time Scene Server Model Values: - enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_STATE_CHANGE_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Time Scene Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Time Scene Set/Set Unack messages are received. - - enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_GET_MSG_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Time Scene Get messages are received. - enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_SET_MSG_EVT When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Time Scene Set/Set Unack messages are received. - enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_STATUS_MSG_EVT When status_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when TIme Status message is received. - enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_EVT_MAX - enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_STATE_CHANGE_EVT Lighting Client/Server Models Header File components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_lighting_model_api.h This header file can be included with: #include "esp_ble_mesh_lighting_model_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_light_client_callback(esp_ble_mesh_light_client_cb_t callback) Register BLE Mesh Light Client Model callback. - Parameters callback -- [in] pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_light_client_get_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_light_client_get_state_t *get_state) Get the value of Light Server Model states using the Light Client Model get messages. Note If you want to know the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_light_message_opcode_t in esp_ble_mesh_defs.h - Parameters params -- [in] Pointer to BLE Mesh common client parameters. get_state -- [in] Pointer of light get message value. Shall not be set to NULL. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_light_client_set_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_light_client_set_state_t *set_state) Set the value of Light Server Model states using the Light Client Model set messages. Note If you want to know the opcodes and corresponding meanings accepted by this API, please refer to esp_ble_mesh_light_message_opcode_t in esp_ble_mesh_defs.h - Parameters params -- [in] Pointer to BLE Mesh common client parameters. set_state -- [in] Pointer of light set message value. Shall not be set to NULL. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_register_lighting_server_callback(esp_ble_mesh_lighting_server_cb_t callback) Register BLE Mesh Lighting Server Model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. Unions - union esp_ble_mesh_light_client_get_state_t - #include <esp_ble_mesh_lighting_model_api.h> Lighting Client Model get message union. Public Members - esp_ble_mesh_light_lc_property_get_t lc_property_get For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_GET - esp_ble_mesh_light_lc_property_get_t lc_property_get - union esp_ble_mesh_light_client_set_state_t - #include <esp_ble_mesh_lighting_model_api.h> Lighting Client Model set message union. Public Members - esp_ble_mesh_light_lightness_set_t lightness_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET_UNACK - esp_ble_mesh_light_lightness_linear_set_t lightness_linear_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET_UNACK - esp_ble_mesh_light_lightness_default_set_t lightness_default_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET_UNACK - esp_ble_mesh_light_lightness_range_set_t lightness_range_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET_UNACK - esp_ble_mesh_light_ctl_set_t ctl_set For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_SET_UNACK - esp_ble_mesh_light_ctl_temperature_set_t ctl_temperature_set For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET_UNACK - esp_ble_mesh_light_ctl_temperature_range_set_t ctl_temperature_range_set For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET_UNACK - esp_ble_mesh_light_ctl_default_set_t ctl_default_set For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET_UNACK - esp_ble_mesh_light_hsl_set_t hsl_set For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SET_UNACK - esp_ble_mesh_light_hsl_hue_set_t hsl_hue_set For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_SET_UNACK - esp_ble_mesh_light_hsl_saturation_set_t hsl_saturation_set For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET_UNACK - esp_ble_mesh_light_hsl_default_set_t hsl_default_set For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET_UNACK - esp_ble_mesh_light_hsl_range_set_t hsl_range_set For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET_UNACK - esp_ble_mesh_light_xyl_set_t xyl_set For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_SET_UNACK - esp_ble_mesh_light_xyl_default_set_t xyl_default_set For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET_UNACK - esp_ble_mesh_light_xyl_range_set_t xyl_range_set For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET_UNACK - esp_ble_mesh_light_lc_mode_set_t lc_mode_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET_UNACK - esp_ble_mesh_light_lc_om_set_t lc_om_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET_UNACK - esp_ble_mesh_light_lc_light_onoff_set_t lc_light_onoff_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET_UNACK - esp_ble_mesh_light_lc_property_set_t lc_property_set For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET_UNACK - esp_ble_mesh_light_lightness_set_t lightness_set - union esp_ble_mesh_light_client_status_cb_t - #include <esp_ble_mesh_lighting_model_api.h> Lighting Client Model received message union. Public Members - esp_ble_mesh_light_lightness_status_cb_t lightness_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_STATUS - esp_ble_mesh_light_lightness_linear_status_cb_t lightness_linear_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_STATUS - esp_ble_mesh_light_lightness_last_status_cb_t lightness_last_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LAST_STATUS - esp_ble_mesh_light_lightness_default_status_cb_t lightness_default_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_STATUS - esp_ble_mesh_light_lightness_range_status_cb_t lightness_range_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_STATUS - esp_ble_mesh_light_ctl_status_cb_t ctl_status For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_STATUS - esp_ble_mesh_light_ctl_temperature_status_cb_t ctl_temperature_status For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_STATUS - esp_ble_mesh_light_ctl_temperature_range_status_cb_t ctl_temperature_range_status For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_STATUS - esp_ble_mesh_light_ctl_default_status_cb_t ctl_default_status For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_STATUS - esp_ble_mesh_light_hsl_status_cb_t hsl_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_STATUS - esp_ble_mesh_light_hsl_target_status_cb_t hsl_target_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_TARGET_STATUS - esp_ble_mesh_light_hsl_hue_status_cb_t hsl_hue_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_STATUS - esp_ble_mesh_light_hsl_saturation_status_cb_t hsl_saturation_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_STATUS - esp_ble_mesh_light_hsl_default_status_cb_t hsl_default_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_STATUS - esp_ble_mesh_light_hsl_range_status_cb_t hsl_range_status For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_STATUS - esp_ble_mesh_light_xyl_status_cb_t xyl_status For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_STATUS - esp_ble_mesh_light_xyl_target_status_cb_t xyl_target_status For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_TARGET_STATUS - esp_ble_mesh_light_xyl_default_status_cb_t xyl_default_status For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_STATUS - esp_ble_mesh_light_xyl_range_status_cb_t xyl_range_status For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_STATUS - esp_ble_mesh_light_lc_mode_status_cb_t lc_mode_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_STATUS - esp_ble_mesh_light_lc_om_status_cb_t lc_om_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_STATUS - esp_ble_mesh_light_lc_light_onoff_status_cb_t lc_light_onoff_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_STATUS - esp_ble_mesh_light_lc_property_status_cb_t lc_property_status For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_STATUS - esp_ble_mesh_light_lightness_status_cb_t lightness_status - union esp_ble_mesh_lighting_server_state_change_t - #include <esp_ble_mesh_lighting_model_api.h> Lighting Server Model state change value union. Public Members - esp_ble_mesh_state_change_light_lightness_set_t lightness_set The recv_op in ctx can be used to decide which state is changed. Light Lightness Set - esp_ble_mesh_state_change_light_lightness_linear_set_t lightness_linear_set Light Lightness Linear Set - esp_ble_mesh_state_change_light_lightness_default_set_t lightness_default_set Light Lightness Default Set - esp_ble_mesh_state_change_light_lightness_range_set_t lightness_range_set Light Lightness Range Set - esp_ble_mesh_state_change_light_ctl_set_t ctl_set Light CTL Set - esp_ble_mesh_state_change_light_ctl_temperature_set_t ctl_temp_set Light CTL Temperature Set - esp_ble_mesh_state_change_light_ctl_temperature_range_set_t ctl_temp_range_set Light CTL Temperature Range Set - esp_ble_mesh_state_change_light_ctl_default_set_t ctl_default_set Light CTL Default Set - esp_ble_mesh_state_change_light_hsl_set_t hsl_set Light HSL Set - esp_ble_mesh_state_change_light_hsl_hue_set_t hsl_hue_set Light HSL Hue Set - esp_ble_mesh_state_change_light_hsl_saturation_set_t hsl_saturation_set Light HSL Saturation Set - esp_ble_mesh_state_change_light_hsl_default_set_t hsl_default_set Light HSL Default Set - esp_ble_mesh_state_change_light_hsl_range_set_t hsl_range_set Light HSL Range Set - esp_ble_mesh_state_change_light_xyl_set_t xyl_set Light xyL Set - esp_ble_mesh_state_change_light_xyl_default_set_t xyl_default_set Light xyL Default Set - esp_ble_mesh_state_change_light_xyl_range_set_t xyl_range_set Light xyL Range Set - esp_ble_mesh_state_change_light_lc_mode_set_t lc_mode_set Light LC Mode Set - esp_ble_mesh_state_change_light_lc_om_set_t lc_om_set Light LC Occupancy Mode Set - esp_ble_mesh_state_change_light_lc_light_onoff_set_t lc_light_onoff_set Light LC Light OnOff Set - esp_ble_mesh_state_change_light_lc_property_set_t lc_property_set Light LC Property Set - esp_ble_mesh_state_change_sensor_status_t sensor_status Sensor Status - esp_ble_mesh_state_change_light_lightness_set_t lightness_set - union esp_ble_mesh_lighting_server_recv_get_msg_t - #include <esp_ble_mesh_lighting_model_api.h> Lighting Server Model received get message union. Public Members - esp_ble_mesh_server_recv_light_lc_property_get_t lc_property Light LC Property Get - esp_ble_mesh_server_recv_light_lc_property_get_t lc_property - union esp_ble_mesh_lighting_server_recv_set_msg_t - #include <esp_ble_mesh_lighting_model_api.h> Lighting Server Model received set message union. Public Members - esp_ble_mesh_server_recv_light_lightness_set_t lightness Light Lightness Set/Light Lightness Set Unack - esp_ble_mesh_server_recv_light_lightness_linear_set_t lightness_linear Light Lightness Linear Set/Light Lightness Linear Set Unack - esp_ble_mesh_server_recv_light_lightness_default_set_t lightness_default Light Lightness Default Set/Light Lightness Default Set Unack - esp_ble_mesh_server_recv_light_lightness_range_set_t lightness_range Light Lightness Range Set/Light Lightness Range Set Unack - esp_ble_mesh_server_recv_light_ctl_set_t ctl Light CTL Set/Light CTL Set Unack - esp_ble_mesh_server_recv_light_ctl_temperature_set_t ctl_temp Light CTL Temperature Set/Light CTL Temperature Set Unack - esp_ble_mesh_server_recv_light_ctl_temperature_range_set_t ctl_temp_range Light CTL Temperature Range Set/Light CTL Temperature Range Set Unack - esp_ble_mesh_server_recv_light_ctl_default_set_t ctl_default Light CTL Default Set/Light CTL Default Set Unack - esp_ble_mesh_server_recv_light_hsl_set_t hsl Light HSL Set/Light HSL Set Unack - esp_ble_mesh_server_recv_light_hsl_hue_set_t hsl_hue Light HSL Hue Set/Light HSL Hue Set Unack - esp_ble_mesh_server_recv_light_hsl_saturation_set_t hsl_saturation Light HSL Saturation Set/Light HSL Saturation Set Unack - esp_ble_mesh_server_recv_light_hsl_default_set_t hsl_default Light HSL Default Set/Light HSL Default Set Unack - esp_ble_mesh_server_recv_light_hsl_range_set_t hsl_range Light HSL Range Set/Light HSL Range Set Unack - esp_ble_mesh_server_recv_light_xyl_set_t xyl Light xyL Set/Light xyL Set Unack - esp_ble_mesh_server_recv_light_xyl_default_set_t xyl_default Light xyL Default Set/Light xyL Default Set Unack - esp_ble_mesh_server_recv_light_xyl_range_set_t xyl_range Light xyL Range Set/Light xyL Range Set Unack - esp_ble_mesh_server_recv_light_lc_mode_set_t lc_mode Light LC Mode Set/Light LC Mode Set Unack - esp_ble_mesh_server_recv_light_lc_om_set_t lc_om Light LC OM Set/Light LC OM Set Unack - esp_ble_mesh_server_recv_light_lc_light_onoff_set_t lc_light_onoff Light LC Light OnOff Set/Light LC Light OnOff Set Unack - esp_ble_mesh_server_recv_light_lc_property_set_t lc_property Light LC Property Set/Light LC Property Set Unack - esp_ble_mesh_server_recv_light_lightness_set_t lightness - union esp_ble_mesh_lighting_server_recv_status_msg_t - #include <esp_ble_mesh_lighting_model_api.h> Lighting Server Model received status message union. Public Members - esp_ble_mesh_server_recv_sensor_status_t sensor_status Sensor Status - esp_ble_mesh_server_recv_sensor_status_t sensor_status - union esp_ble_mesh_lighting_server_cb_value_t - #include <esp_ble_mesh_lighting_model_api.h> Lighting Server Model callback value union. Public Members - esp_ble_mesh_lighting_server_state_change_t state_change ESP_BLE_MESH_LIGHTING_SERVER_STATE_CHANGE_EVT - esp_ble_mesh_lighting_server_recv_get_msg_t get ESP_BLE_MESH_LIGHTING_SERVER_RECV_GET_MSG_EVT - esp_ble_mesh_lighting_server_recv_set_msg_t set ESP_BLE_MESH_LIGHTING_SERVER_RECV_SET_MSG_EVT - esp_ble_mesh_lighting_server_recv_status_msg_t status ESP_BLE_MESH_LIGHTING_SERVER_RECV_STATUS_MSG_EVT - esp_ble_mesh_lighting_server_state_change_t state_change Structures - struct esp_ble_mesh_light_lightness_set_t Bluetooth Mesh Light Lightness Client Model Get and Set parameters structure. Parameters of Light Lightness Set - struct esp_ble_mesh_light_lightness_linear_set_t Parameters of Light Lightness Linear Set - struct esp_ble_mesh_light_lightness_default_set_t Parameter of Light Lightness Default Set Public Members - uint16_t lightness The value of the Light Lightness Default state - uint16_t lightness - struct esp_ble_mesh_light_lightness_range_set_t Parameters of Light Lightness Range Set - struct esp_ble_mesh_light_ctl_set_t Parameters of Light CTL Set Public Members - bool op_en Indicate if optional parameters are included - uint16_t ctl_lightness Target value of light ctl lightness state - uint16_t ctl_temperature Target value of light ctl temperature state - int16_t ctl_delta_uv Target value of light ctl delta UV state - uint8_t tid Transaction ID - uint8_t trans_time Time to complete state transition (optional) - uint8_t delay Indicate message execution delay (C.1) - bool op_en - struct esp_ble_mesh_light_ctl_temperature_set_t Parameters of Light CTL Temperature Set Public Members - bool op_en Indicate if optional parameters are included - uint16_t ctl_temperature Target value of light ctl temperature state - int16_t ctl_delta_uv Target value of light ctl delta UV state - uint8_t tid Transaction ID - uint8_t trans_time Time to complete state transition (optional) - uint8_t delay Indicate message execution delay (C.1) - bool op_en - struct esp_ble_mesh_light_ctl_temperature_range_set_t Parameters of Light CTL Temperature Range Set - struct esp_ble_mesh_light_ctl_default_set_t Parameters of Light CTL Default Set - struct esp_ble_mesh_light_hsl_set_t Parameters of Light HSL Set Public Members - bool op_en Indicate if optional parameters are included - uint16_t hsl_lightness Target value of light hsl lightness state - uint16_t hsl_hue Target value of light hsl hue state - uint16_t hsl_saturation Target value of light hsl saturation state - uint8_t tid Transaction ID - uint8_t trans_time Time to complete state transition (optional) - uint8_t delay Indicate message execution delay (C.1) - bool op_en - struct esp_ble_mesh_light_hsl_hue_set_t Parameters of Light HSL Hue Set - struct esp_ble_mesh_light_hsl_saturation_set_t Parameters of Light HSL Saturation Set - struct esp_ble_mesh_light_hsl_default_set_t Parameters of Light HSL Default Set - struct esp_ble_mesh_light_hsl_range_set_t Parameters of Light HSL Range Set Public Members - uint16_t hue_range_min Value of hue range min field of light hsl hue range state - uint16_t hue_range_max Value of hue range max field of light hsl hue range state - uint16_t saturation_range_min Value of saturation range min field of light hsl saturation range state - uint16_t saturation_range_max Value of saturation range max field of light hsl saturation range state - uint16_t hue_range_min - struct esp_ble_mesh_light_xyl_set_t Parameters of Light xyL Set Public Members - bool op_en Indicate whether optional parameters included - uint16_t xyl_lightness The target value of the Light xyL Lightness state - uint16_t xyl_x The target value of the Light xyL x state - uint16_t xyl_y The target value of the Light xyL y state - uint8_t tid Transaction Identifier - uint8_t trans_time Time to complete state transition (optional) - uint8_t delay Indicate message execution delay (C.1) - bool op_en - struct esp_ble_mesh_light_xyl_default_set_t Parameters of Light xyL Default Set - struct esp_ble_mesh_light_xyl_range_set_t Parameters of Light xyL Range Set Public Members - uint16_t xyl_x_range_min The value of the xyL x Range Min field of the Light xyL x Range state - uint16_t xyl_x_range_max The value of the xyL x Range Max field of the Light xyL x Range state - uint16_t xyl_y_range_min The value of the xyL y Range Min field of the Light xyL y Range state - uint16_t xyl_y_range_max The value of the xyL y Range Max field of the Light xyL y Range state - uint16_t xyl_x_range_min - struct esp_ble_mesh_light_lc_mode_set_t Parameter of Light LC Mode Set Public Members - uint8_t mode The target value of the Light LC Mode state - uint8_t mode - struct esp_ble_mesh_light_lc_om_set_t Parameter of Light LC OM Set Public Members - uint8_t mode The target value of the Light LC Occupancy Mode state - uint8_t mode - struct esp_ble_mesh_light_lc_light_onoff_set_t Parameters of Light LC Light OnOff Set - struct esp_ble_mesh_light_lc_property_get_t Parameter of Light LC Property Get Public Members - uint16_t property_id Property ID identifying a Light LC Property - uint16_t property_id - struct esp_ble_mesh_light_lc_property_set_t Parameters of Light LC Property Set - struct esp_ble_mesh_light_lightness_status_cb_t Bluetooth Mesh Light Lightness Client Model Get and Set callback parameters structure. Parameters of Light Lightness Status - struct esp_ble_mesh_light_lightness_linear_status_cb_t Parameters of Light Lightness Linear Status - struct esp_ble_mesh_light_lightness_last_status_cb_t Parameter of Light Lightness Last Status Public Members - uint16_t lightness The value of the Light Lightness Last state - uint16_t lightness - struct esp_ble_mesh_light_lightness_default_status_cb_t Parameter of Light Lightness Default Status Public Members - uint16_t lightness The value of the Light Lightness default State - uint16_t lightness - struct esp_ble_mesh_light_lightness_range_status_cb_t Parameters of Light Lightness Range Status - struct esp_ble_mesh_light_ctl_status_cb_t Parameters of Light CTL Status Public Members - bool op_en Indicate if optional parameters are included - uint16_t present_ctl_lightness Current value of light ctl lightness state - uint16_t present_ctl_temperature Current value of light ctl temperature state - uint16_t target_ctl_lightness Target value of light ctl lightness state (optional) - uint16_t target_ctl_temperature Target value of light ctl temperature state (C.1) - uint8_t remain_time Time to complete state transition (C.1) - bool op_en - struct esp_ble_mesh_light_ctl_temperature_status_cb_t Parameters of Light CTL Temperature Status Public Members - bool op_en Indicate if optional parameters are included - uint16_t present_ctl_temperature Current value of light ctl temperature state - uint16_t present_ctl_delta_uv Current value of light ctl delta UV state - uint16_t target_ctl_temperature Target value of light ctl temperature state (optional) - uint16_t target_ctl_delta_uv Target value of light ctl delta UV state (C.1) - uint8_t remain_time Time to complete state transition (C.1) - bool op_en - struct esp_ble_mesh_light_ctl_temperature_range_status_cb_t Parameters of Light CTL Temperature Range Status - struct esp_ble_mesh_light_ctl_default_status_cb_t Parameters of Light CTL Default Status - struct esp_ble_mesh_light_hsl_status_cb_t Parameters of Light HSL Status Public Members - bool op_en Indicate if optional parameters are included - uint16_t hsl_lightness Current value of light hsl lightness state - uint16_t hsl_hue Current value of light hsl hue state - uint16_t hsl_saturation Current value of light hsl saturation state - uint8_t remain_time Time to complete state transition (optional) - bool op_en - struct esp_ble_mesh_light_hsl_target_status_cb_t Parameters of Light HSL Target Status Public Members - bool op_en Indicate if optional parameters are included - uint16_t hsl_lightness_target Target value of light hsl lightness state - uint16_t hsl_hue_target Target value of light hsl hue state - uint16_t hsl_saturation_target Target value of light hsl saturation state - uint8_t remain_time Time to complete state transition (optional) - bool op_en - struct esp_ble_mesh_light_hsl_hue_status_cb_t Parameters of Light HSL Hue Status - struct esp_ble_mesh_light_hsl_saturation_status_cb_t Parameters of Light HSL Saturation Status - struct esp_ble_mesh_light_hsl_default_status_cb_t Parameters of Light HSL Default Status - struct esp_ble_mesh_light_hsl_range_status_cb_t Parameters of Light HSL Range Status Public Members - uint8_t status_code Status code for the request message - uint16_t hue_range_min Value of hue range min field of light hsl hue range state - uint16_t hue_range_max Value of hue range max field of light hsl hue range state - uint16_t saturation_range_min Value of saturation range min field of light hsl saturation range state - uint16_t saturation_range_max Value of saturation range max field of light hsl saturation range state - uint8_t status_code - struct esp_ble_mesh_light_xyl_status_cb_t Parameters of Light xyL Status Public Members - bool op_en Indicate whether optional parameters included - uint16_t xyl_lightness The present value of the Light xyL Lightness state - uint16_t xyl_x The present value of the Light xyL x state - uint16_t xyl_y The present value of the Light xyL y state - uint8_t remain_time Time to complete state transition (optional) - bool op_en - struct esp_ble_mesh_light_xyl_target_status_cb_t Parameters of Light xyL Target Status Public Members - bool op_en Indicate whether optional parameters included - uint16_t target_xyl_lightness The target value of the Light xyL Lightness state - uint16_t target_xyl_x The target value of the Light xyL x state - uint16_t target_xyl_y The target value of the Light xyL y state - uint8_t remain_time Time to complete state transition (optional) - bool op_en - struct esp_ble_mesh_light_xyl_default_status_cb_t Parameters of Light xyL Default Status - struct esp_ble_mesh_light_xyl_range_status_cb_t Parameters of Light xyL Range Status Public Members - uint8_t status_code Status Code for the requesting message - uint16_t xyl_x_range_min The value of the xyL x Range Min field of the Light xyL x Range state - uint16_t xyl_x_range_max The value of the xyL x Range Max field of the Light xyL x Range state - uint16_t xyl_y_range_min The value of the xyL y Range Min field of the Light xyL y Range state - uint16_t xyl_y_range_max The value of the xyL y Range Max field of the Light xyL y Range state - uint8_t status_code - struct esp_ble_mesh_light_lc_mode_status_cb_t Parameter of Light LC Mode Status Public Members - uint8_t mode The present value of the Light LC Mode state - uint8_t mode - struct esp_ble_mesh_light_lc_om_status_cb_t Parameter of Light LC OM Status Public Members - uint8_t mode The present value of the Light LC Occupancy Mode state - uint8_t mode - struct esp_ble_mesh_light_lc_light_onoff_status_cb_t Parameters of Light LC Light OnOff Status Public Members - bool op_en Indicate whether optional parameters included - uint8_t present_light_onoff The present value of the Light LC Light OnOff state - uint8_t target_light_onoff The target value of the Light LC Light OnOff state (Optional) - uint8_t remain_time Time to complete state transition (C.1) - bool op_en - struct esp_ble_mesh_light_lc_property_status_cb_t Parameters of Light LC Property Status - struct esp_ble_mesh_light_client_cb_param_t Lighting Client Model callback parameters Public Members - int error_code Appropriate error code - esp_ble_mesh_client_common_param_t *params The client common parameters. - esp_ble_mesh_light_client_status_cb_t status_cb The light status message callback values - int error_code - struct esp_ble_mesh_light_lightness_state_t Parameters of Light Lightness state Public Members - uint16_t lightness_linear The present value of Light Lightness Linear state - uint16_t target_lightness_linear The target value of Light Lightness Linear state - uint16_t lightness_actual The present value of Light Lightness Actual state - uint16_t target_lightness_actual The target value of Light Lightness Actual state - uint16_t lightness_last The value of Light Lightness Last state - uint16_t lightness_default The value of Light Lightness Default state - uint8_t status_code The status code of setting Light Lightness Range state - uint16_t lightness_range_min The minimum value of Light Lightness Range state - uint16_t lightness_range_max The maximum value of Light Lightness Range state - uint16_t lightness_linear - struct esp_ble_mesh_light_lightness_srv_t User data of Light Lightness Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Lighting Lightness Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_light_lightness_state_t *state Parameters of the Light Lightness state - esp_ble_mesh_last_msg_info_t last Parameters of the last received set message - esp_ble_mesh_state_transition_t actual_transition Parameters of state transition - esp_ble_mesh_state_transition_t linear_transition Parameters of state transition - int32_t tt_delta_lightness_actual Delta change value of lightness actual state transition - int32_t tt_delta_lightness_linear Delta change value of lightness linear state transition - esp_ble_mesh_model_t *model - struct esp_ble_mesh_light_lightness_setup_srv_t User data of Light Lightness Setup Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Lighting Lightness Setup Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_light_lightness_state_t *state Parameters of the Light Lightness state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_light_ctl_state_t Parameters of Light CTL state Public Members - uint16_t lightness The present value of Light CTL Lightness state - uint16_t target_lightness The target value of Light CTL Lightness state - uint16_t temperature The present value of Light CTL Temperature state - uint16_t target_temperature The target value of Light CTL Temperature state - int16_t delta_uv The present value of Light CTL Delta UV state - int16_t target_delta_uv The target value of Light CTL Delta UV state - uint8_t status_code The statue code of setting Light CTL Temperature Range state - uint16_t temperature_range_min The minimum value of Light CTL Temperature Range state - uint16_t temperature_range_max The maximum value of Light CTL Temperature Range state - uint16_t lightness_default The value of Light Lightness Default state - uint16_t temperature_default The value of Light CTL Temperature Default state - int16_t delta_uv_default The value of Light CTL Delta UV Default state - uint16_t lightness - struct esp_ble_mesh_light_ctl_srv_t User data of Light CTL Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Lighting CTL Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_light_ctl_state_t *state Parameters of the Light CTL state - esp_ble_mesh_last_msg_info_t last Parameters of the last received set message - esp_ble_mesh_state_transition_t transition Parameters of state transition - int32_t tt_delta_lightness Delta change value of lightness state transition - int32_t tt_delta_temperature Delta change value of temperature state transition - int32_t tt_delta_delta_uv Delta change value of delta uv state transition - esp_ble_mesh_model_t *model - struct esp_ble_mesh_light_ctl_setup_srv_t User data of Light CTL Setup Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Lighting CTL Setup Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_light_ctl_state_t *state Parameters of the Light CTL state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_light_ctl_temp_srv_t User data of Light CTL Temperature Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Lighting CTL Temperature Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_light_ctl_state_t *state Parameters of the Light CTL state - esp_ble_mesh_last_msg_info_t last Parameters of the last received set message - esp_ble_mesh_state_transition_t transition Parameters of state transition - int32_t tt_delta_temperature Delta change value of temperature state transition - int32_t tt_delta_delta_uv Delta change value of delta uv state transition - esp_ble_mesh_model_t *model - struct esp_ble_mesh_light_hsl_state_t Parameters of Light HSL state Public Members - uint16_t lightness The present value of Light HSL Lightness state - uint16_t target_lightness The target value of Light HSL Lightness state - uint16_t hue The present value of Light HSL Hue state - uint16_t target_hue The target value of Light HSL Hue state - uint16_t saturation The present value of Light HSL Saturation state - uint16_t target_saturation The target value of Light HSL Saturation state - uint16_t lightness_default The value of Light Lightness Default state - uint16_t hue_default The value of Light HSL Hue Default state - uint16_t saturation_default The value of Light HSL Saturation Default state - uint8_t status_code The status code of setting Light HSL Hue & Saturation Range state - uint16_t hue_range_min The minimum value of Light HSL Hue Range state - uint16_t hue_range_max The maximum value of Light HSL Hue Range state - uint16_t saturation_range_min The minimum value of Light HSL Saturation state - uint16_t saturation_range_max The maximum value of Light HSL Saturation state - uint16_t lightness - struct esp_ble_mesh_light_hsl_srv_t User data of Light HSL Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Lighting HSL Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_light_hsl_state_t *state Parameters of the Light HSL state - esp_ble_mesh_last_msg_info_t last Parameters of the last received set message - esp_ble_mesh_state_transition_t transition Parameters of state transition - int32_t tt_delta_lightness Delta change value of lightness state transition - int32_t tt_delta_hue Delta change value of hue state transition - int32_t tt_delta_saturation Delta change value of saturation state transition - esp_ble_mesh_model_t *model - struct esp_ble_mesh_light_hsl_setup_srv_t User data of Light HSL Setup Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Lighting HSL Setup Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_light_hsl_state_t *state Parameters of the Light HSL state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_light_hsl_hue_srv_t User data of Light HSL Hue Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Lighting HSL Hue Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_light_hsl_state_t *state Parameters of the Light HSL state - esp_ble_mesh_last_msg_info_t last Parameters of the last received set message - esp_ble_mesh_state_transition_t transition Parameters of state transition - int32_t tt_delta_hue Delta change value of hue state transition - esp_ble_mesh_model_t *model - struct esp_ble_mesh_light_hsl_sat_srv_t User data of Light HSL Saturation Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Lighting HSL Saturation Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_light_hsl_state_t *state Parameters of the Light HSL state - esp_ble_mesh_last_msg_info_t last Parameters of the last received set message - esp_ble_mesh_state_transition_t transition Parameters of state transition - int32_t tt_delta_saturation Delta change value of saturation state transition - esp_ble_mesh_model_t *model - struct esp_ble_mesh_light_xyl_state_t Parameters of Light xyL state Public Members - uint16_t lightness The present value of Light xyL Lightness state - uint16_t target_lightness The target value of Light xyL Lightness state - uint16_t x The present value of Light xyL x state - uint16_t target_x The target value of Light xyL x state - uint16_t y The present value of Light xyL y state - uint16_t target_y The target value of Light xyL y state - uint16_t lightness_default The value of Light Lightness Default state - uint16_t x_default The value of Light xyL x Default state - uint16_t y_default The value of Light xyL y Default state - uint8_t status_code The status code of setting Light xyL x & y Range state - uint16_t x_range_min The minimum value of Light xyL x Range state - uint16_t x_range_max The maximum value of Light xyL x Range state - uint16_t y_range_min The minimum value of Light xyL y Range state - uint16_t y_range_max The maximum value of Light xyL y Range state - uint16_t lightness - struct esp_ble_mesh_light_xyl_srv_t User data of Light xyL Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Lighting xyL Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_light_xyl_state_t *state Parameters of the Light xyL state - esp_ble_mesh_last_msg_info_t last Parameters of the last received set message - esp_ble_mesh_state_transition_t transition Parameters of state transition - int32_t tt_delta_lightness Delta change value of lightness state transition - int32_t tt_delta_x Delta change value of x state transition - int32_t tt_delta_y Delta change value of y state transition - esp_ble_mesh_model_t *model - struct esp_ble_mesh_light_xyl_setup_srv_t User data of Light xyL Setup Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Lighting xyL Setup Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_light_xyl_state_t *state Parameters of the Light xyL state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_light_lc_state_t Parameters of Light LC states Public Members - uint32_t mode 0b0 The controller is turned off. The binding with the Light Lightness state is disabled. 0b1 The controller is turned on. The binding with the Light Lightness state is enabled. The value of Light LC Mode state - - uint32_t occupancy_mode The value of Light LC Occupancy Mode state - uint32_t light_onoff The present value of Light LC Light OnOff state - uint32_t target_light_onoff The target value of Light LC Light OnOff state - uint32_t occupancy The value of Light LC Occupancy state - uint32_t ambient_luxlevel The value of Light LC Ambient LuxLevel state - uint16_t linear_output Light LC Linear Output = max((Lightness Out)^2/65535, Regulator Output) If the Light LC Mode state is set to 0b1, the binding is enabled and upon a change of the Light LC Linear Output state, the following operation shall be performed: Light Lightness Linear = Light LC Linear Output If the Light LC Mode state is set to 0b0, the binding is disabled (i.e., upon a change of the Light LC Linear Output state, no operation on the Light Lightness Linear state is performed). The value of Light LC Linear Output state - - uint32_t mode - struct esp_ble_mesh_light_lc_property_state_t Parameters of Light Property states. The Light LC Property states are read / write states that determine the configuration of a Light Lightness Controller. Each state is represented by a device property and is controlled by Light LC Property messages. Public Members - uint32_t time_occupancy_delay A timing state that determines the delay for changing the Light LC Occupancy state upon receiving a Sensor Status message from an occupancy sensor. The value of Light LC Time Occupancy Delay state - uint32_t time_fade_on A timing state that determines the time the controlled lights fade to the level determined by the Light LC Lightness On state. The value of Light LC Time Fade On state - uint32_t time_run_on A timing state that determines the time the controlled lights stay at the level determined by the Light LC Lightness On state. The value of Light LC Time Run On state - uint32_t time_fade A timing state that determines the time the controlled lights fade from the level determined by the Light LC Lightness On state to the level determined by the Light Lightness Prolong state. The value of Light LC Time Fade state - uint32_t time_prolong A timing state that determines the time the controlled lights stay at the level determined by the Light LC Lightness Prolong state. The value of Light LC Time Prolong state - uint32_t time_fade_standby_auto A timing state that determines the time the controlled lights fade from the level determined by the Light LC Lightness Prolong state to the level determined by the Light LC Lightness Standby state when the transition is automatic. The value of Light LC Time Fade Standby Auto state - uint32_t time_fade_standby_manual A timing state that determines the time the controlled lights fade from the level determined by the Light LC Lightness Prolong state to the level determined by the Light LC Lightness Standby state when the transition is triggered by a change in the Light LC Light OnOff state. The value of Light LC Time Fade Standby Manual state - uint16_t lightness_on A lightness state that determines the perceptive light lightness at the Occupancy and Run internal controller states. The value of Light LC Lightness On state - uint16_t lightness_prolong A lightness state that determines the light lightness at the Prolong internal controller state. The value of Light LC Lightness Prolong state - uint16_t lightness_standby A lightness state that determines the light lightness at the Standby internal controller state. The value of Light LC Lightness Standby state - uint16_t ambient_luxlevel_on A uint16 state representing the Ambient LuxLevel level that determines if the controller transitions from the Light Control Standby state. The value of Light LC Ambient LuxLevel On state - uint16_t ambient_luxlevel_prolong A uint16 state representing the required Ambient LuxLevel level in the Prolong state. The value of Light LC Ambient LuxLevel Prolong state - uint16_t ambient_luxlevel_standby A uint16 state representing the required Ambient LuxLevel level in the Standby state. The value of Light LC Ambient LuxLevel Standby state - float regulator_kiu A float32 state representing the integral coefficient that determines the integral part of the equation defining the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is less than LuxLevel Out. Valid range: 0.0 ~ 1000.0. The default value is 250.0. The value of Light LC Regulator Kiu state - float regulator_kid A float32 state representing the integral coefficient that determines the integral part of the equation defining the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is greater than or equal to the value of the LuxLevel Out state. Valid range: 0.0 ~ 1000.0. The default value is 25.0. The value of Light LC Regulator Kid state - float regulator_kpu A float32 state representing the proportional coefficient that determines the proportional part of the equation defining the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is less than the value of the LuxLevel Out state. Valid range: 0.0 ~ 1000.0. The default value is 80.0. The value of Light LC Regulator Kpu state - float regulator_kpd A float32 state representing the proportional coefficient that determines the proportional part of the equation defining the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is greater than or equal to the value of the LuxLevel Out state. Valid range: 0.0 ~ 1000.0. The default value is 80.0. The value of Light LC Regulator Kpd state - int8_t regulator_accuracy A int8 state representing the percentage accuracy of the Light LC PI Feedback Regulator. Valid range: 0.0 ~ 100.0. The default value is 2.0. The value of Light LC Regulator Accuracy state - uint32_t set_occupancy_to_1_delay If the message Raw field contains a Raw Value for the Time Since Motion Sensed device property, which represents a value less than or equal to the value of the Light LC Occupancy Delay state, it shall delay setting the Light LC Occupancy state to 0b1 by the difference between the value of the Light LC Occupancy Delay state and the received Time Since Motion value. The value of the difference between value of the Light LC Occupancy Delay state and the received Time Since Motion value - uint32_t time_occupancy_delay - struct esp_ble_mesh_light_lc_state_machine_t Parameters of Light LC state machine Public Members - uint8_t fade_on The value of transition time of Light LC Time Fade On - uint8_t fade The value of transition time of Light LC Time Fade - uint8_t fade_standby_auto The value of transition time of Light LC Time Fade Standby Auto - uint8_t fade_standby_manual The value of transition time of Light LC Time Fade Standby Manual - struct esp_ble_mesh_light_lc_state_machine_t::[anonymous] trans_time The Fade On, Fade, Fade Standby Auto, and Fade Standby Manual states are transition states that define the transition of the Lightness Out and LuxLevel Out states. This transition can be started as a result of the Light LC State Machine change or as a result of receiving the Light LC Light OnOff Set or Light LC Light Set Unacknowledged message. The value of transition time - esp_ble_mesh_lc_state_t state The value of Light LC state machine state - struct k_delayed_work timer Timer of Light LC state machine - uint8_t fade_on - struct esp_ble_mesh_light_control_t Parameters of Light Lightness controller Public Members - esp_ble_mesh_light_lc_state_t state Parameters of Light LC state - esp_ble_mesh_light_lc_property_state_t prop_state Parameters of Light LC Property state - esp_ble_mesh_light_lc_state_machine_t state_machine Parameters of Light LC state machine - esp_ble_mesh_light_lc_state_t state - struct esp_ble_mesh_light_lc_srv_t User data of Light LC Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Lighting LC Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_light_control_t *lc Parameters of the Light controller - esp_ble_mesh_last_msg_info_t last Parameters of the last received set message - esp_ble_mesh_state_transition_t transition Parameters of state transition - esp_ble_mesh_model_t *model - struct esp_ble_mesh_light_lc_setup_srv_t User data of Light LC Setup Server Model Public Members - esp_ble_mesh_model_t *model Pointer to the Lighting LC Setup Server Model. Initialized internally. - esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl Response control of the server model received messages - esp_ble_mesh_light_control_t *lc Parameters of the Light controller - esp_ble_mesh_model_t *model - struct esp_ble_mesh_state_change_light_lightness_set_t Parameter of Light Lightness Actual state change event Public Members - uint16_t lightness The value of Light Lightness Actual state - uint16_t lightness - struct esp_ble_mesh_state_change_light_lightness_linear_set_t Parameter of Light Lightness Linear state change event Public Members - uint16_t lightness The value of Light Lightness Linear state - uint16_t lightness - struct esp_ble_mesh_state_change_light_lightness_default_set_t Parameter of Light Lightness Default state change event Public Members - uint16_t lightness The value of Light Lightness Default state - uint16_t lightness - struct esp_ble_mesh_state_change_light_lightness_range_set_t Parameters of Light Lightness Range state change event - struct esp_ble_mesh_state_change_light_ctl_set_t Parameters of Light CTL state change event - struct esp_ble_mesh_state_change_light_ctl_temperature_set_t Parameters of Light CTL Temperature state change event - struct esp_ble_mesh_state_change_light_ctl_temperature_range_set_t Parameters of Light CTL Temperature Range state change event - struct esp_ble_mesh_state_change_light_ctl_default_set_t Parameters of Light CTL Default state change event - struct esp_ble_mesh_state_change_light_hsl_set_t Parameters of Light HSL state change event - struct esp_ble_mesh_state_change_light_hsl_hue_set_t Parameter of Light HSL Hue state change event Public Members - uint16_t hue The value of Light HSL Hue state - uint16_t hue - struct esp_ble_mesh_state_change_light_hsl_saturation_set_t Parameter of Light HSL Saturation state change event Public Members - uint16_t saturation The value of Light HSL Saturation state - uint16_t saturation - struct esp_ble_mesh_state_change_light_hsl_default_set_t Parameters of Light HSL Default state change event - struct esp_ble_mesh_state_change_light_hsl_range_set_t Parameters of Light HSL Range state change event Public Members - uint16_t hue_range_min The minimum hue value of Light HSL Range state - uint16_t hue_range_max The maximum hue value of Light HSL Range state - uint16_t saturation_range_min The minimum saturation value of Light HSL Range state - uint16_t saturation_range_max The maximum saturation value of Light HSL Range state - uint16_t hue_range_min - struct esp_ble_mesh_state_change_light_xyl_set_t Parameters of Light xyL state change event - struct esp_ble_mesh_state_change_light_xyl_default_set_t Parameters of Light xyL Default state change event - struct esp_ble_mesh_state_change_light_xyl_range_set_t Parameters of Light xyL Range state change event - struct esp_ble_mesh_state_change_light_lc_mode_set_t Parameter of Light LC Mode state change event Public Members - uint8_t mode The value of Light LC Mode state - uint8_t mode - struct esp_ble_mesh_state_change_light_lc_om_set_t Parameter of Light LC Occupancy Mode state change event Public Members - uint8_t mode The value of Light LC Occupancy Mode state - uint8_t mode - struct esp_ble_mesh_state_change_light_lc_light_onoff_set_t Parameter of Light LC Light OnOff state change event Public Members - uint8_t onoff The value of Light LC Light OnOff state - uint8_t onoff - struct esp_ble_mesh_state_change_light_lc_property_set_t Parameters of Light LC Property state change event - struct esp_ble_mesh_state_change_sensor_status_t Parameters of Sensor Status state change event Public Members - uint16_t property_id The value of Sensor Property ID - uint8_t occupancy The value of Light LC Occupancy state - uint32_t set_occupancy_to_1_delay The value of Light LC Set Occupancy to 1 Delay state - uint32_t ambient_luxlevel The value of Light LC Ambient Luxlevel state - union esp_ble_mesh_state_change_sensor_status_t::[anonymous] state Parameters of Sensor Status related state - uint16_t property_id - struct esp_ble_mesh_server_recv_light_lc_property_get_t Context of the received Light LC Property Get message Public Members - uint16_t property_id Property ID identifying a Light LC Property - uint16_t property_id - struct esp_ble_mesh_server_recv_light_lightness_set_t Context of the received Light Lightness Set message - struct esp_ble_mesh_server_recv_light_lightness_linear_set_t Context of the received Light Lightness Linear Set message - struct esp_ble_mesh_server_recv_light_lightness_default_set_t Context of the received Light Lightness Default Set message Public Members - uint16_t lightness The value of the Light Lightness Default state - uint16_t lightness - struct esp_ble_mesh_server_recv_light_lightness_range_set_t Context of the received Light Lightness Range Set message - struct esp_ble_mesh_server_recv_light_ctl_set_t Context of the received Light CTL Set message Public Members - bool op_en Indicate if optional parameters are included - uint16_t lightness Target value of light ctl lightness state - uint16_t temperature Target value of light ctl temperature state - int16_t delta_uv Target value of light ctl delta UV state - uint8_t tid Transaction ID - uint8_t trans_time Time to complete state transition (optional) - uint8_t delay Indicate message execution delay (C.1) - bool op_en - struct esp_ble_mesh_server_recv_light_ctl_temperature_set_t Context of the received Light CTL Temperature Set message Public Members - bool op_en Indicate if optional parameters are included - uint16_t temperature Target value of light ctl temperature state - int16_t delta_uv Target value of light ctl delta UV state - uint8_t tid Transaction ID - uint8_t trans_time Time to complete state transition (optional) - uint8_t delay Indicate message execution delay (C.1) - bool op_en - struct esp_ble_mesh_server_recv_light_ctl_temperature_range_set_t Context of the received Light CTL Temperature Range Set message - struct esp_ble_mesh_server_recv_light_ctl_default_set_t Context of the received Light CTL Default Set message - struct esp_ble_mesh_server_recv_light_hsl_set_t Context of the received Light HSL Set message Public Members - bool op_en Indicate if optional parameters are included - uint16_t lightness Target value of light hsl lightness state - uint16_t hue Target value of light hsl hue state - uint16_t saturation Target value of light hsl saturation state - uint8_t tid Transaction ID - uint8_t trans_time Time to complete state transition (optional) - uint8_t delay Indicate message execution delay (C.1) - bool op_en - struct esp_ble_mesh_server_recv_light_hsl_hue_set_t Context of the received Light HSL Hue Set message - struct esp_ble_mesh_server_recv_light_hsl_saturation_set_t Context of the received Light HSL Saturation Set message - struct esp_ble_mesh_server_recv_light_hsl_default_set_t Context of the received Light HSL Default Set message - struct esp_ble_mesh_server_recv_light_hsl_range_set_t Context of the received Light HSL Range Set message Public Members - uint16_t hue_range_min Value of hue range min field of light hsl hue range state - uint16_t hue_range_max Value of hue range max field of light hsl hue range state - uint16_t saturation_range_min Value of saturation range min field of light hsl saturation range state - uint16_t saturation_range_max Value of saturation range max field of light hsl saturation range state - uint16_t hue_range_min - struct esp_ble_mesh_server_recv_light_xyl_set_t Context of the received Light xyL Set message Public Members - bool op_en Indicate whether optional parameters included - uint16_t lightness The target value of the Light xyL Lightness state - uint16_t x The target value of the Light xyL x state - uint16_t y The target value of the Light xyL y state - uint8_t tid Transaction Identifier - uint8_t trans_time Time to complete state transition (optional) - uint8_t delay Indicate message execution delay (C.1) - bool op_en - struct esp_ble_mesh_server_recv_light_xyl_default_set_t Context of the received Light xyL Default Set message - struct esp_ble_mesh_server_recv_light_xyl_range_set_t Context of the received Light xyl Range Set message Public Members - uint16_t x_range_min The value of the xyL x Range Min field of the Light xyL x Range state - uint16_t x_range_max The value of the xyL x Range Max field of the Light xyL x Range state - uint16_t y_range_min The value of the xyL y Range Min field of the Light xyL y Range state - uint16_t y_range_max The value of the xyL y Range Max field of the Light xyL y Range state - uint16_t x_range_min - struct esp_ble_mesh_server_recv_light_lc_mode_set_t Context of the received Light LC Mode Set message Public Members - uint8_t mode The target value of the Light LC Mode state - uint8_t mode - struct esp_ble_mesh_server_recv_light_lc_om_set_t Context of the received Light OM Set message Public Members - uint8_t mode The target value of the Light LC Occupancy Mode state - uint8_t mode - struct esp_ble_mesh_server_recv_light_lc_light_onoff_set_t Context of the received Light LC Light OnOff Set message - struct esp_ble_mesh_server_recv_light_lc_property_set_t Context of the received Light LC Property Set message - struct esp_ble_mesh_server_recv_sensor_status_t Context of the received Sensor Status message Public Members - struct net_buf_simple *data Value of sensor data state (optional) - struct net_buf_simple *data - struct esp_ble_mesh_lighting_server_cb_param_t Lighting Server Model callback parameters Public Members - esp_ble_mesh_model_t *model Pointer to Lighting Server Models - esp_ble_mesh_msg_ctx_t ctx Context of the received messages - esp_ble_mesh_lighting_server_cb_value_t value Value of the received Lighting Messages - esp_ble_mesh_model_t *model Macros - ESP_BLE_MESH_MODEL_LIGHT_LIGHTNESS_CLI(cli_pub, cli_data) Define a new Light Lightness Client Model. Note This API needs to be called for each element on which the application needs to have a Light Lightness Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Light Lightness Client Model instance. - ESP_BLE_MESH_MODEL_LIGHT_CTL_CLI(cli_pub, cli_data) Define a new Light CTL Client Model. Note This API needs to be called for each element on which the application needs to have a Light CTL Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Light CTL Client Model instance. - ESP_BLE_MESH_MODEL_LIGHT_HSL_CLI(cli_pub, cli_data) Define a new Light HSL Client Model. Note This API needs to be called for each element on which the application needs to have a Light HSL Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Light HSL Client Model instance. - ESP_BLE_MESH_MODEL_LIGHT_XYL_CLI(cli_pub, cli_data) Define a new Light xyL Client Model. Note This API needs to be called for each element on which the application needs to have a Light xyL Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Light xyL Client Model instance. - ESP_BLE_MESH_MODEL_LIGHT_LC_CLI(cli_pub, cli_data) Define a new Light LC Client Model. Note This API needs to be called for each element on which the application needs to have a Light LC Client Model. - Parameters cli_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. cli_data -- Pointer to the unique struct esp_ble_mesh_client_t. - - Returns New Light LC Client Model instance. - ESP_BLE_MESH_MODEL_LIGHT_LIGHTNESS_SRV(srv_pub, srv_data) Lighting Server Models related context. Define a new Light Lightness Server Model. Note 1. The Light Lightness Server model extends the Generic Power OnOff Server model and the Generic Level Server model. When this model is present on an Element, the corresponding Light Lightness Setup Server model shall also be present. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lightness_srv_t. - - Returns New Light Lightness Server Model instance. - - ESP_BLE_MESH_MODEL_LIGHT_LIGHTNESS_SETUP_SRV(srv_pub, srv_data) Define a new Light Lightness Setup Server Model. Note 1. The Light Lightness Setup Server model extends the Light Lightness Server model and the Generic Power OnOff Setup Server model. This model shall support model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lightness_setup_srv_t. - - Returns New Light Lightness Setup Server Model instance. - - ESP_BLE_MESH_MODEL_LIGHT_CTL_SRV(srv_pub, srv_data) Define a new Light CTL Server Model. Note 1. The Light CTL Server model extends the Light Lightness Server model. When this model is present on an Element, the corresponding Light CTL Temperature Server model and the corresponding Light CTL Setup Server model shall also be present. This model shall support model publication and model subscription. The model requires two elements: the main element and the Temperature element. The Temperature element contains the corresponding Light CTL Temperature Server model and an instance of a Generic Level state bound to the Light CTL Temperature state on the Temperature element. The Light CTL Temperature state on the Temperature element is bound to the Light CTL state on the main element. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_ctl_srv_t. - - Returns New Light CTL Server Model instance. - - ESP_BLE_MESH_MODEL_LIGHT_CTL_SETUP_SRV(srv_pub, srv_data) Define a new Light CTL Setup Server Model. Note 1. The Light CTL Setup Server model extends the Light CTL Server and the Light Lightness Setup Server. This model shall support model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_ctl_setup_srv_t. - - Returns New Light CTL Setup Server Model instance. - - ESP_BLE_MESH_MODEL_LIGHT_CTL_TEMP_SRV(srv_pub, srv_data) Define a new Light CTL Temperature Server Model. Note 1. The Light CTL Temperature Server model extends the Generic Level Server model. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_ctl_temp_srv_t. - - Returns New Light CTL Temperature Server Model instance. - - ESP_BLE_MESH_MODEL_LIGHT_HSL_SRV(srv_pub, srv_data) Define a new Light HSL Server Model. Note 1. The Light HSL Server model extends the Light Lightness Server model. When this model is present on an Element, the corresponding Light HSL Hue Server model and the corresponding Light HSL Saturation Server model and the corresponding Light HSL Setup Server model shall also be present. This model shall support model publication and model subscription. The model requires three elements: the main element and the Hue element and the Saturation element. The Hue element contains the corresponding Light HSL Hue Server model and an instance of a Generic Level state bound to the Light HSL Hue state on the Hue element. The Saturation element contains the corresponding Light HSL Saturation Server model and an instance of a Generic Level state bound to the Light HSL Saturation state on the Saturation element. The Light HSL Hue state on the Hue element is bound to the Light HSL state on the main element and the Light HSL Saturation state on the Saturation element is bound to the Light HSL state on the main element. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_srv_t. - - Returns New Light HSL Server Model instance. - - ESP_BLE_MESH_MODEL_LIGHT_HSL_SETUP_SRV(srv_pub, srv_data) Define a new Light HSL Setup Server Model. Note 1. The Light HSL Setup Server model extends the Light HSL Server and the Light Lightness Setup Server. This model shall support model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_setup_srv_t. - - Returns New Light HSL Setup Server Model instance. - - ESP_BLE_MESH_MODEL_LIGHT_HSL_HUE_SRV(srv_pub, srv_data) Define a new Light HSL Hue Server Model. Note 1. The Light HSL Hue Server model extends the Generic Level Server model. This model is associated with the Light HSL Server model. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_hue_srv_t. - - Returns New Light HSL Hue Server Model instance. - - ESP_BLE_MESH_MODEL_LIGHT_HSL_SAT_SRV(srv_pub, srv_data) Define a new Light HSL Saturation Server Model. Note 1. The Light HSL Saturation Server model extends the Generic Level Server model. This model is associated with the Light HSL Server model. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_hsl_sat_srv_t. - - Returns New Light HSL Saturation Server Model instance. - - ESP_BLE_MESH_MODEL_LIGHT_XYL_SRV(srv_pub, srv_data) Define a new Light xyL Server Model. Note 1. The Light xyL Server model extends the Light Lightness Server model. When this model is present on an Element, the corresponding Light xyL Setup Server model shall also be present. This model shall support model publication and model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_xyl_srv_t. - - Returns New Light xyL Server Model instance. - - ESP_BLE_MESH_MODEL_LIGHT_XYL_SETUP_SRV(srv_pub, srv_data) Define a new Light xyL Setup Server Model. Note 1. The Light xyL Setup Server model extends the Light xyL Server and the Light Lightness Setup Server. This model shall support model subscription. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_xyl_setup_srv_t. - - Returns New Light xyL Setup Server Model instance. - - ESP_BLE_MESH_MODEL_LIGHT_LC_SRV(srv_pub, srv_data) Define a new Light LC Server Model. Note 1. The Light LC (Lightness Control) Server model extends the Light Lightness Server model and the Generic OnOff Server model. When this model is present on an Element, the corresponding Light LC Setup Server model shall also be present. This model shall support model publication and model subscription. This model may be used to represent an element that is a client to a Sensor Server model and controls the Light Lightness Actual state via defined state bindings. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lc_srv_t. - - Returns New Light LC Server Model instance. - - ESP_BLE_MESH_MODEL_LIGHT_LC_SETUP_SRV(srv_pub, srv_data) Define a new Light LC Setup Server Model. Note 1. The Light LC (Lightness Control) Setup model extends the Light LC Server model. This model shall support model publication and model subscription. This model may be used to configure setup parameters for the Light LC Server model. - Parameters srv_pub -- Pointer to the unique struct esp_ble_mesh_model_pub_t. srv_data -- Pointer to the unique struct esp_ble_mesh_light_lc_setup_srv_t. - - Returns New Light LC Setup Server Model instance. - Type Definitions - typedef void (*esp_ble_mesh_light_client_cb_t)(esp_ble_mesh_light_client_cb_event_t event, esp_ble_mesh_light_client_cb_param_t *param) Bluetooth Mesh Light Client Model function. Lighting Client Model callback function type - Param event Event type - Param param Pointer to callback parameter - typedef void (*esp_ble_mesh_lighting_server_cb_t)(esp_ble_mesh_lighting_server_cb_event_t event, esp_ble_mesh_lighting_server_cb_param_t *param) Bluetooth Mesh Lighting Server Model function. Lighting Server Model callback function type - Param event Event type - Param param Pointer to callback parameter Enumerations - enum esp_ble_mesh_light_client_cb_event_t This enum value is the event of Lighting Client Model Values: - enumerator ESP_BLE_MESH_LIGHT_CLIENT_GET_STATE_EVT - enumerator ESP_BLE_MESH_LIGHT_CLIENT_SET_STATE_EVT - enumerator ESP_BLE_MESH_LIGHT_CLIENT_PUBLISH_EVT - enumerator ESP_BLE_MESH_LIGHT_CLIENT_TIMEOUT_EVT - enumerator ESP_BLE_MESH_LIGHT_CLIENT_EVT_MAX - enumerator ESP_BLE_MESH_LIGHT_CLIENT_GET_STATE_EVT - enum esp_ble_mesh_lc_state_t This enum value is the Light LC State Machine states Values: - enumerator ESP_BLE_MESH_LC_OFF - enumerator ESP_BLE_MESH_LC_STANDBY - enumerator ESP_BLE_MESH_LC_FADE_ON - enumerator ESP_BLE_MESH_LC_RUN - enumerator ESP_BLE_MESH_LC_FADE - enumerator ESP_BLE_MESH_LC_PROLONG - enumerator ESP_BLE_MESH_LC_FADE_STANDBY_AUTO - enumerator ESP_BLE_MESH_LC_FADE_STANDBY_MANUAL - enumerator ESP_BLE_MESH_LC_OFF - enum esp_ble_mesh_lighting_server_cb_event_t This enum value is the event of Lighting Server Model Values: - enumerator ESP_BLE_MESH_LIGHTING_SERVER_STATE_CHANGE_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, no event will be callback to the application layer when Lighting Get messages are received. When set_auto_rsp is set to ESP_BLE_MESH_SERVER_AUTO_RSP, this event will be callback to the application layer when Lighting Set/Set Unack messages are received. - - enumerator ESP_BLE_MESH_LIGHTING_SERVER_RECV_GET_MSG_EVT When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Lighting Get messages are received. - enumerator ESP_BLE_MESH_LIGHTING_SERVER_RECV_SET_MSG_EVT When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Lighting Set/Set Unack messages are received. - enumerator ESP_BLE_MESH_LIGHTING_SERVER_RECV_STATUS_MSG_EVT When status_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to the application layer when Sensor Status message is received. - enumerator ESP_BLE_MESH_LIGHTING_SERVER_EVT_MAX - enumerator ESP_BLE_MESH_LIGHTING_SERVER_STATE_CHANGE_EVT ESP-BLE-MESH (v1.1) Core API Reference Note This section is a preview version, so the related structures, macros, and APIs may be changed. This section contains ESP-BLE-MESH v1.1 Core related APIs, event types, event parameters, etc. This API reference covers 10 components: Remote Provisioning Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_rpr_model_api.h This header file can be included with: #include "esp_ble_mesh_rpr_model_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_rpr_client_callback(esp_ble_mesh_rpr_client_cb_t callback) Register BLE Mesh Remote Provisioning Client model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_rpr_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_rpr_client_msg_t *msg) Get the value of Remote Provisioning Server model state with the corresponding get message. - Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Remote Provisioning Client message. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_rpr_client_action(esp_ble_mesh_rpr_client_act_type_t type, esp_ble_mesh_rpr_client_act_param_t *param) Remote Provisioning Client model perform related actions, e.g. start remote provisioning. - Parameters type -- [in] Type of the action to be performed. param -- [in] Parameters of the action to be performed. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_register_rpr_server_callback(esp_ble_mesh_rpr_server_cb_t callback) Register BLE Mesh Remote Provisioning Server model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. Unions - union esp_ble_mesh_rpr_client_msg_t - #include <esp_ble_mesh_rpr_model_api.h> Remote Provisioning Client model message union. Public Members - esp_ble_mesh_rpr_scan_start_t scan_start For ESP_BLE_MESH_MODEL_OP_RPR_SCAN_START - esp_ble_mesh_rpr_ext_scan_start_t ext_scan_start For ESP_BLE_MESH_MODEL_OP_RPR_EXT_SCAN_START - esp_ble_mesh_rpr_link_open_t link_open For ESP_BLE_MESH_MODEL_OP_RPR_LINK_OPEN - esp_ble_mesh_rpr_link_close_t link_close For ESP_BLE_MESH_MODEL_OP_RPR_LINK_CLOSE - esp_ble_mesh_rpr_scan_start_t scan_start - union esp_ble_mesh_rpr_client_act_param_t - #include <esp_ble_mesh_rpr_model_api.h> Remote Provisioning Client model action union. Public Members - esp_ble_mesh_rpr_client_start_rpr_t start_rpr Start remote provisioning - esp_ble_mesh_rpr_client_start_rpr_t start_rpr - union esp_ble_mesh_rpr_client_recv_cb_t - #include <esp_ble_mesh_rpr_model_api.h> Remote Provisioning Client model received message union. Public Members - esp_ble_mesh_rpr_scan_caps_status_t scan_caps_status For ESP_BLE_MESH_MODEL_OP_RPR_SCAN_CAPS_STATUS - esp_ble_mesh_rpr_scan_status_t scan_status For ESP_BLE_MESH_MODEL_OP_RPR_SCAN_STATUS - esp_ble_mesh_rpr_scan_report_t scan_report For ESP_BLE_MESH_MODEL_OP_RPR_SCAN_REPORT - esp_ble_mesh_rpr_ext_scan_report_t ext_scan_report For ESP_BLE_MESH_MODEL_OP_RPR_EXT_SCAN_REPORT - esp_ble_mesh_rpr_link_status_t link_status For ESP_BLE_MESH_MODEL_OP_RPR_LINK_STATUS - esp_ble_mesh_rpr_link_report_t link_report For ESP_BLE_MESH_MODEL_OP_RPR_LINK_REPORT - esp_ble_mesh_rpr_scan_caps_status_t scan_caps_status - union esp_ble_mesh_rpr_client_cb_param_t - #include <esp_ble_mesh_rpr_model_api.h> Remote Provisioning Client model callback parameters Public Members - int err_code Result of sending a message Result of starting remote provisioning - esp_ble_mesh_client_common_param_t *params Client common parameters - struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] send Event parameters of sending messages Event parameters of sending messages - esp_ble_mesh_rpr_client_recv_cb_t val Parameters of received status message - struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] recv Event parameters of receiving messages Event parameters of receiving messages - esp_ble_mesh_rpr_client_act_evt_t sub_evt Event type of the performed action - esp_ble_mesh_model_t *model Pointer of Remote Provisioning Client - uint16_t rpr_srv_addr Unicast address of Remote Provisioning Server - struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous]::[anonymous] start_rpr_comp ESP_BLE_MESH_START_RPR_COMP_SUB_EVT. Event parameter of ESP_BLE_MESH_START_RPR_COMP_SUB_EVT - struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] act Event parameters of performed actions Event parameters of performed actions - struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] link_open ESP_BLE_MESH_RPR_CLIENT_LINK_OPEN_EVT. Event parameters of ESP_BLE_MESH_RPR_CLIENT_LINK_OPEN_EVT - uint8_t reason Reason of closing provisioning link - struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] link_close ESP_BLE_MESH_RPR_CLIENT_LINK_CLOSE_EVT. Event parameters of ESP_BLE_MESH_RPR_CLIENT_LINK_CLOSE_EVT - uint8_t nppi NPPI Procedure - uint16_t index Index of the provisioned node - uint8_t uuid[16] Device UUID - uint16_t unicast_addr Primary element address - uint8_t element_num Element number - uint16_t net_idx NetKey Index - struct esp_ble_mesh_rpr_client_cb_param_t::[anonymous] prov ESP_BLE_MESH_RPR_CLIENT_PROV_COMP_EVT. Event parameters of ESP_BLE_MESH_RPR_CLIENT_PROV_COMP_EVT - int err_code - union esp_ble_mesh_rpr_server_cb_param_t - #include <esp_ble_mesh_rpr_model_api.h> Remote Provisioning Server model related context. Remote Provisioning Server model callback value union Public Members - esp_ble_mesh_model_t *model Pointer to the server model structure - uint8_t scan_items_limit Maximum number of scanned items to be reported - uint8_t timeout Time limit for a scan (in seconds) Time limit for extended scan (in seconds) Time limit for opening a link (in seconds) - uint8_t uuid[16] Device UUID (All ZERO if not present) Device UUID (ZERO if not present) - uint16_t net_idx NetKey Index used by Remote Provisioning Client - uint16_t rpr_cli_addr Unicast address of Remote Provisioning Client - struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] scan_start ESP_BLE_MESH_RPR_SERVER_SCAN_START_EVT. - struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] scan_stop ESP_BLE_MESH_RPR_SERVER_SCAN_STOP_EVT. - uint8_t ad_type_filter_count Number of AD Types in the ADTypeFilter field - uint8_t *ad_type_filter List of AD Types to be reported - uint8_t index Index of the extended scan instance - struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] ext_scan_start ESP_BLE_MESH_RPR_SERVER_EXT_SCAN_START_EVT. - struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] ext_scan_stop ESP_BLE_MESH_RPR_SERVER_EXT_SCAN_STOP_EVT. - uint8_t status Status of Link Open procedure - uint8_t nppi Node Provisioning Protocol Interface Provisioning bearer link close reason code - struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] link_open ESP_BLE_MESH_RPR_SERVER_LINK_OPEN_EVT. - bool close_by_device Indicate if the link is closed by the Unprovisioned Device - uint8_t reason Provisioning bearer link close reason code - struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] link_close ESP_BLE_MESH_RPR_SERVER_LINK_CLOSE_EVT. - struct esp_ble_mesh_rpr_server_cb_param_t::[anonymous] prov_comp ESP_BLE_MESH_RPR_SERVER_PROV_COMP_EVT. TODO: Duplicate with Link Close event? - esp_ble_mesh_model_t *model Structures - struct esp_ble_mesh_rpr_scan_start_t Remote Provisioning Server model context Parameters of Remote Provisioning Scan Start - struct esp_ble_mesh_rpr_ext_scan_start_t Parameters of Remote Provisioning Extended Scan Start Public Members - uint8_t ad_type_filter_count Number of AD Types in the ADTypeFilter field - uint8_t ad_type_filter[16] List of AD Types to be reported. Minimum is 1, maximum is 16 - bool uuid_en Indicate if Device UUID is present - uint8_t uuid[16] Device UUID (Optional) - uint8_t timeout Time limit for a scan (in seconds) (C.1) - uint8_t ad_type_filter_count - struct esp_ble_mesh_rpr_link_open_t Parameters of Remote Provisioning Link Open - struct esp_ble_mesh_rpr_link_close_t Parameters of Remote Provisioning Link Close Public Members - uint8_t reason Provisioning bearer link close reason code - uint8_t reason - struct esp_ble_mesh_rpr_client_start_rpr_t Parameters of starting remote provisioning Public Members - esp_ble_mesh_model_t *model Pointer of Remote Provisioning Client - uint16_t rpr_srv_addr Unicast address of Remote Provisioning Server - esp_ble_mesh_model_t *model - struct esp_ble_mesh_rpr_scan_caps_status_t Parameters of Remote Provisioning Scan Capabilities Status - struct esp_ble_mesh_rpr_scan_status_t Parameters of Remote Provisioning Scan Status - struct esp_ble_mesh_rpr_scan_report_t Parameters of Remote Provisioning Scan Report - struct esp_ble_mesh_rpr_ext_scan_report_t Parameters of Remote Provisioning Extended Scan Report - struct esp_ble_mesh_rpr_link_status_t Parameters of Remote Provisioning Link Status - struct esp_ble_mesh_rpr_link_report_t Parameters of Remote Provisioning Link Report Macros - ESP_BLE_MESH_MODEL_OP_RPR_SCAN_CAPS_GET - ESP_BLE_MESH_MODEL_OP_RPR_SCAN_CAPS_STATUS - ESP_BLE_MESH_MODEL_OP_RPR_SCAN_GET - ESP_BLE_MESH_MODEL_OP_RPR_SCAN_START - ESP_BLE_MESH_MODEL_OP_RPR_SCAN_STOP - ESP_BLE_MESH_MODEL_OP_RPR_SCAN_STATUS - ESP_BLE_MESH_MODEL_OP_RPR_SCAN_REPORT - ESP_BLE_MESH_MODEL_OP_RPR_EXT_SCAN_START - ESP_BLE_MESH_MODEL_OP_RPR_EXT_SCAN_REPORT - ESP_BLE_MESH_MODEL_OP_RPR_LINK_GET - ESP_BLE_MESH_MODEL_OP_RPR_LINK_OPEN - ESP_BLE_MESH_MODEL_OP_RPR_LINK_CLOSE - ESP_BLE_MESH_MODEL_OP_RPR_LINK_STATUS - ESP_BLE_MESH_MODEL_OP_RPR_LINK_REPORT - ESP_BLE_MESH_MODEL_OP_RPR_PDU_SEND - ESP_BLE_MESH_MODEL_OP_RPR_PDU_OUTBOUND_REPORT - ESP_BLE_MESH_MODEL_OP_RPR_PDU_REPORT - ESP_BLE_MESH_RPR_SRV_MAX_SCANNED_ITEMS_MIN - ESP_BLE_MESH_RPR_NOT_SUPPORT_ACTIVE_SCAN - ESP_BLE_MESH_RPR_SUPPORT_ACTIVE_SCAN - ESP_BLE_MESH_RPR_SCAN_IDLE - ESP_BLE_MESH_RPR_SCAN_MULTIPLE_DEVICE - ESP_BLE_MESH_RPR_SCAN_SINGLE_DEVICE - ESP_BLE_MESH_RPR_SCAN_NOT_IN_PROGRESS - ESP_BLE_MESH_RPR_PROHIBIT_SCAN_TIMEOUT - ESP_BLE_MESH_RPR_EXT_SCAN_TIMEOUT_MIN - ESP_BLE_MESH_RPR_EXT_SCAN_TIMEOUT_MAX - ESP_BLE_MESH_RPR_AD_TYPE_FILTER_CNT_MIN - ESP_BLE_MESH_RPR_AD_TYPE_FILTER_CNT_MAX - ESP_BLE_MESH_RPR_LINK_OPEN_TIMEOUT_MIN - ESP_BLE_MESH_RPR_LINK_OPEN_TIMEOUT_MAX - ESP_BLE_MESH_RPR_LINK_TIMEOUT_DEFAULT - ESP_BLE_MESH_RPR_REASON_SUCCESS - ESP_BLE_MESH_RPR_REASON_FAIL - ESP_BLE_MESH_RPR_LINK_IDLE - ESP_BLE_MESH_RPR_LINK_OPENING - ESP_BLE_MESH_RPR_LINK_ACTIVE - ESP_BLE_MESH_RPR_OUTBOUND_PACKET_TRANSFER - ESP_BLE_MESH_RPR_LINK_CLOSING - ESP_BLE_MESH_RPR_STATUS_SUCCESS - ESP_BLE_MESH_RPR_STATUS_SCANNING_CANNOT_START - ESP_BLE_MESH_RPR_STATUS_INVALID_STATE - ESP_BLE_MESH_RPR_STATUS_LIMITED_RESOURCES - ESP_BLE_MESH_RPR_STATUS_LINK_CANNOT_OPEN - ESP_BLE_MESH_RPR_STATUS_LINK_OPEN_FAILED - ESP_BLE_MESH_RPR_STATUS_LINK_CLOSED_BY_DEVICE - ESP_BLE_MESH_RPR_STATUS_LINK_CLOSED_BY_SERVER - ESP_BLE_MESH_RPR_STATUS_LINK_CLOSED_BY_CLIENT - ESP_BLE_MESH_RPR_STATUS_LINK_CLOSED_AS_CANNOT_RECEIVE_PDU - ESP_BLE_MESH_RPR_STATUS_LINK_CLOSED_AS_CANNOT_SEND_PDU - ESP_BLE_MESH_RPR_STATUS_LINK_CLOSED_AS_CANNOT_DELIVER_PDU_REPORT - ESP_BLE_MESH_MODEL_RPR_SRV(srv_data) Define a new Remote Provisioning Server model. Note If supported, the model shall be supported by a primary element and may be supported by any secondary element. - Parameters srv_data -- Pointer to a unique Remote Provisioning Server model user_data. - - Returns New Remote Provisioning Server model instance. - ESP_BLE_MESH_MODEL_RPR_CLI(cli_data) Define a new Remote Provisioning Client model. Note If supported, the model shall be supported by a primary element and may be supported by any secondary element. - Parameters cli_data -- Pointer to a unique Remote Provisioning Client model user_data. - - Returns New Remote Provisioning Client model instance. Type Definitions - typedef void (*esp_ble_mesh_rpr_client_cb_t)(esp_ble_mesh_rpr_client_cb_event_t event, esp_ble_mesh_rpr_client_cb_param_t *param) Remote Provisioning client and server model functions. Remote Provisioning Client model callback function type - Param event Event type - Param param Pointer to callback parameter - typedef void (*esp_ble_mesh_rpr_server_cb_t)(esp_ble_mesh_rpr_server_cb_event_t event, esp_ble_mesh_rpr_server_cb_param_t *param) Remote Provisioning Server model callback function type. - Param event Event type - Param param Pointer to callback parameter Enumerations - enum esp_ble_mesh_rpr_client_act_type_t This enum value is the action of Remote Provisioning Client model Values: - enumerator ESP_BLE_MESH_RPR_CLIENT_ACT_START_RPR - enumerator ESP_BLE_MESH_RPR_CLIENT_ACT_MAX - enumerator ESP_BLE_MESH_RPR_CLIENT_ACT_START_RPR - enum esp_ble_mesh_rpr_client_act_evt_t This enum value is the event type of the performed action Values: - enumerator ESP_BLE_MESH_START_RPR_COMP_SUB_EVT - enumerator ESP_BLE_MESH_START_RPR_COMP_SUB_EVT - enum esp_ble_mesh_rpr_client_cb_event_t This enum value is the event of Remote Provisioning Client model Values: - enumerator ESP_BLE_MESH_RPR_CLIENT_SEND_COMP_EVT - enumerator ESP_BLE_MESH_RPR_CLIENT_SEND_TIMEOUT_EVT - enumerator ESP_BLE_MESH_RPR_CLIENT_RECV_RSP_EVT - enumerator ESP_BLE_MESH_RPR_CLIENT_RECV_PUB_EVT - enumerator ESP_BLE_MESH_RPR_CLIENT_ACT_COMP_EVT - enumerator ESP_BLE_MESH_RPR_CLIENT_LINK_OPEN_EVT - enumerator ESP_BLE_MESH_RPR_CLIENT_LINK_CLOSE_EVT - enumerator ESP_BLE_MESH_RPR_CLIENT_PROV_COMP_EVT - enumerator ESP_BLE_MESH_RPR_CLIENT_EVT_MAX - enumerator ESP_BLE_MESH_RPR_CLIENT_SEND_COMP_EVT - enum esp_ble_mesh_rpr_server_cb_event_t This enum value is the event of Remote Provisioning Server model Values: - enumerator ESP_BLE_MESH_RPR_SERVER_SCAN_START_EVT - enumerator ESP_BLE_MESH_RPR_SERVER_SCAN_STOP_EVT - enumerator ESP_BLE_MESH_RPR_SERVER_EXT_SCAN_START_EVT - enumerator ESP_BLE_MESH_RPR_SERVER_EXT_SCAN_STOP_EVT - enumerator ESP_BLE_MESH_RPR_SERVER_LINK_OPEN_EVT - enumerator ESP_BLE_MESH_RPR_SERVER_LINK_CLOSE_EVT - enumerator ESP_BLE_MESH_RPR_SERVER_PROV_COMP_EVT - enumerator ESP_BLE_MESH_RPR_SERVER_EVT_MAX - enumerator ESP_BLE_MESH_RPR_SERVER_SCAN_START_EVT Directed Forwarding Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_df_model_api.h This header file can be included with: #include "esp_ble_mesh_df_model_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_df_client_callback(esp_ble_mesh_df_client_cb_t callback) Register BLE Mesh Directed Forwarding Configuration Client model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_register_df_server_callback(esp_ble_mesh_df_server_cb_t callback) Register BLE Mesh Directed Forwarding Configuration Server model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_df_client_get_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_df_client_get_t *get) Get the value of Directed Forwarding Configuration Server model state with the corresponding get message. - Parameters params -- [in] Pointer to BLE Mesh common client parameters. get -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_df_client_set_state(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_df_client_set_t *set) Set the value of Directed Forwarding Configuration Server model state with the corresponding set message. - Parameters params -- [in] Pointer to BLE Mesh common client parameters. set -- [in] Pointer to a union, each kind of opcode corresponds to one structure inside. - - Returns ESP_OK on success or error code otherwise. Unions - union esp_ble_mesh_df_client_get_t - #include <esp_ble_mesh_df_model_api.h> Directed Forwarding Configuration Client model get message union. Public Members - esp_ble_mesh_directed_control_get_t directed_control_get For ESP_BLE_MESH_MODEL_OP_DIRECTED_CONTROL_GET - esp_ble_mesh_path_metric_get_t path_metric_get For ESP_BLE_MESH_MODEL_OP_PATH_METRIC_GET - esp_ble_mesh_discovery_table_caps_get_t disc_table_caps_get For ESP_BLE_MESH_MODEL_OP_DISCOVERY_TABLE_CAPS_GET - esp_ble_mesh_forwarding_table_entries_cnt_get_t forwarding_table_entries_cnt_get For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_CNT_GET - esp_ble_mesh_forwarding_table_entries_get_t forwarding_table_entries_get For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_GET - esp_ble_mesh_forwarding_table_deps_get_t forwarding_table_deps_get For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_GET - esp_ble_mesh_wanted_lanes_get_t wanted_lanes_get For ESP_BLE_MESH_MODEL_OP_WANTED_LANES_GET - esp_ble_mesh_two_way_path_get_t two_way_path_get For ESP_BLE_MESH_MODEL_OP_TWO_WAY_PATH_GET - esp_ble_mesh_path_echo_interval_get_t path_echo_interval_get For ESP_BLE_MESH_MODEL_OP_PATH_ECHO_INTERVAL_GET - esp_ble_mesh_directed_publish_policy_get_t directed_pub_policy_get For ESP_BLE_MESH_MODEL_OP_DIRECTED_PUB_POLICY_GET - esp_ble_mesh_directed_control_get_t directed_control_get - union esp_ble_mesh_df_client_set_t - #include <esp_ble_mesh_df_model_api.h> Directed Forwarding Configuration Client model set message union. Public Members - esp_ble_mesh_directed_control_set_t directed_control_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_CONTROL_SET - esp_ble_mesh_path_metric_set_t path_metric_set For ESP_BLE_MESH_MODEL_OP_PATH_METRIC_SET - esp_ble_mesh_discovery_table_caps_set_t disc_table_caps_set For ESP_BLE_MESH_MODEL_OP_DISCOVERY_TABLE_CAPS_SET - esp_ble_mesh_forwarding_table_add_t forwarding_table_add For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ADD - esp_ble_mesh_forwarding_table_delete_t forwarding_table_del For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEL - esp_ble_mesh_forwarding_table_deps_add_t forwarding_table_deps_add For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_ADD - esp_ble_mesh_forwarding_table_deps_delete_t forwarding_table_deps_del For ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_DEL - esp_ble_mesh_wanted_lanes_set_t wanted_lanes_set For ESP_BLE_MESH_MODEL_OP_WANTED_LANES_SET - esp_ble_mesh_two_way_path_set_t two_way_path_set For ESP_BLE_MESH_MODEL_OP_TWO_WAY_PATH_SET - esp_ble_mesh_path_echo_interval_set_t path_echo_interval_set For ESP_BLE_MESH_MODEL_OP_PATH_ECHO_INTERVAL_SET - esp_ble_mesh_directed_net_transmit_set_t directed_net_transmit_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_NET_TRANSMIT_SET - esp_ble_mesh_directed_relay_retransmit_set_t directed_relay_retransmit_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_RELAY_RETRANSMIT_SET - esp_ble_mesh_rssi_threshold_set_t rssi_threshold_set For ESP_BLE_MESH_MODEL_OP_RSSI_THRESHOLD_SET - esp_ble_mesh_directed_publish_policy_set_t directed_pub_policy_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_PUB_POLICY_SET - esp_ble_mesh_path_discovery_timing_ctl_set_t path_disc_timing_ctl_set For ESP_BLE_MESH_MODEL_OP_PATH_DISCOVERY_TIMING_CTL_SET - esp_ble_mesh_directed_ctl_net_transmit_set_t directed_ctl_net_transmit_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_NET_TRANSMIT_SET - esp_ble_mesh_directed_ctl_relay_retransmit_set_t directed_ctl_relay_retransmit_set For ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_RELAY_RETRANSMIT_SET - esp_ble_mesh_directed_control_set_t directed_control_set - union esp_ble_mesh_df_client_recv_cb_t - #include <esp_ble_mesh_df_model_api.h> Directed Forwarding Configuration Client model received message union. Public Members - esp_ble_mesh_directed_control_status_t directed_control_status ESP_BLE_MESH_MODEL_OP_DIRECTED_CONTROL_STATUS - esp_ble_mesh_path_metric_status_t path_metric_status ESP_BLE_MESH_MODEL_OP_PATH_METRIC_STATUS - esp_ble_mesh_discovery_table_caps_status_t disc_table_caps_status ESP_BLE_MESH_MODEL_OP_DISCOVERY_TABLE_CAPS_STATUS - esp_ble_mesh_forwarding_table_status_t forwarding_table_status ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_STATUS - esp_ble_mesh_forwarding_table_deps_status_t forwarding_table_deps_status ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_STATUS - esp_ble_mesh_forwarding_table_entries_cnt_status_t forwarding_table_entries_cnt_status ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_CNT_STATUS - esp_ble_mesh_forwarding_table_entries_status_t forwarding_table_entries_status ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_STATUS - esp_ble_mesh_forwarding_table_deps_get_status_t forwarding_table_deps_get_status ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_GET_STATUS - esp_ble_mesh_wanted_lanes_status_t wanted_lanes_status ESP_BLE_MESH_MODEL_OP_WANTED_LANES_STATUS - esp_ble_mesh_two_way_path_status_t two_way_path_status ESP_BLE_MESH_MODEL_OP_TWO_WAY_PATH_STATUS - esp_ble_mesh_path_echo_interval_status_t path_echo_interval_status ESP_BLE_MESH_MODEL_OP_PATH_ECHO_INTERVAL_STATUS - esp_ble_mesh_directed_net_transmit_status_t directed_net_transmit_status ESP_BLE_MESH_MODEL_OP_DIRECTED_NET_TRANSMIT_STATUS - esp_ble_mesh_directed_relay_retransmit_status_t directed_relay_retransmit_status ESP_BLE_MESH_MODEL_OP_DIRECTED_RELAY_RETRANSMIT_STATUS - esp_ble_mesh_rssi_threshold_status_t rssi_threshold_status ESP_BLE_MESH_MODEL_OP_RSSI_THRESHOLD_STATUS - esp_ble_mesh_directed_paths_status_t directed_paths_status ESP_BLE_MESH_MODEL_OP_DIRECTED_PATHS_STATUS - esp_ble_mesh_directed_pub_policy_status_t directed_pub_policy_status ESP_BLE_MESH_MODEL_OP_DIRECTED_PUB_POLICY_STATUS - esp_ble_mesh_path_disc_timing_ctl_status_cb_t path_disc_timing_ctl_status ESP_BLE_MESH_MODEL_OP_PATH_DISCOVERY_TIMING_CTL_STATUS - esp_ble_mesh_directed_ctl_net_transmit_status_t directed_ctl_net_transmit_status ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_NET_TRANSMIT_STATUS - esp_ble_mesh_directed_ctl_relay_retransmit_status_t directed_ctl_relay_retransmit_status ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_RELAY_RETRANSMIT_STATUS - esp_ble_mesh_directed_control_status_t directed_control_status - union esp_ble_mesh_df_server_state_change_t - #include <esp_ble_mesh_df_model_api.h> Directed Forwarding Configuration Server model related context. Directed Forwarding Configuration Server model state change value union - union esp_ble_mesh_df_server_cb_value_t - #include <esp_ble_mesh_df_model_api.h> Directed Forwarding Configuration Server model callback value union. Public Members - esp_ble_mesh_df_server_state_change_t state_change For ESP_BLE_MESH_DF_SERVER_STATE_CHANGE_EVT - esp_ble_mesh_df_server_table_change_t table_change For ESP_BLE_MESH_DF_SERVER_TABLE_CHANGE_EVT - esp_ble_mesh_df_server_state_change_t state_change Structures - struct esp_ble_mesh_df_srv_t Directed Forwarding Configuration Server model context Public Members - esp_ble_mesh_model_t *model Pointer to Directed Forwarding Configuration Server model - uint8_t directed_net_transmit Directed Network Transmit state - uint8_t directed_relay_retransmit Directed Relay Retransmit state - int8_t default_rssi_threshold Default RSSI Threshold state - uint8_t rssi_margin RSSI Margin state - uint16_t directed_node_paths Directed Node Paths state - uint16_t directed_relay_paths Directed Relay Paths state - uint16_t directed_proxy_paths Directed Proxy Paths state - uint16_t directed_friend_paths Directed Friend Paths state - uint16_t path_monitor_interval Path Monitoring Interval state - uint16_t path_disc_retry_interval Path Discovery Retry Interval state - uint8_t path_disc_interval Path Discovery Interval state - uint8_t lane_disc_guard_interval Lane Discovery Guard Interval state - uint8_t directed_ctl_net_transmit Directed Control Network Transmit state - uint8_t directed_ctl_relay_retransmit Directed Control Relay Retransmit state - esp_ble_mesh_model_t *model - struct esp_ble_mesh_directed_control_get_t Parameters of Directed Control Get. - struct esp_ble_mesh_directed_control_set_t Parameters of Directed Control Set. Public Members - uint16_t net_idx NetKey Index - uint8_t directed_forwarding New Directed Forwarding state - uint8_t directed_relay New Directed Relay state - uint8_t directed_proxy New Directed Proxy state - uint8_t directed_proxy_use_default New Directed Proxy Use Directed Default state or value to ignore - uint8_t directed_friend New Directed Friend state or value to ignore - uint16_t net_idx - struct esp_ble_mesh_path_metric_get_t Parameters of Path Metric Get. - struct esp_ble_mesh_path_metric_set_t Parameters of Path Metric Set. - struct esp_ble_mesh_discovery_table_caps_get_t Parameters of Discovery Table Capabilities Get. - struct esp_ble_mesh_discovery_table_caps_set_t Parameters of Discovery Table Capabilities Set. - struct esp_ble_mesh_forwarding_table_add_t Parameters of Forwarding Table Add. Public Members - uint16_t net_idx NetKey Index - uint16_t unicast_dst Indicates whether or not the destination of the path is a unicast address - uint16_t bw_path_validated Indicates whether or not the backward path has been validated - esp_ble_mesh_uar_t path_origin Unicast address range of the Path Origin - esp_ble_mesh_uar_t path_target Unicast address range of the Path Target - uint16_t multicast_dst Multicast destination address - union esp_ble_mesh_forwarding_table_add_t::[anonymous] [anonymous] Path target address - uint16_t bearer_twd_path_origin Index of the bearer toward the Path Origin - uint16_t bearer_twd_path_target Index of the bearer toward the Path Target - uint16_t net_idx - struct esp_ble_mesh_forwarding_table_delete_t Parameters of Forwarding Table Delete. - struct esp_ble_mesh_forwarding_table_deps_add_t Parameters of Forwarding Table Dependents Add. Public Members - uint16_t net_idx NetKey Index - uint16_t path_origin Primary element address of the Path Origin - uint16_t dst Destination address - uint8_t dep_origin_uar_list_size Number of entries in the Dependent_Origin_Unicast_Addr_Range_List field - uint8_t dep_target_uar_list_size Number of entries in the Dependent_Target_Unicast_Addr_Range_List field - esp_ble_mesh_uar_t *dep_origin_uar_list List of the unicast address ranges of the dependent nodes of the Path Origin - esp_ble_mesh_uar_t *dep_target_uar_list List of the unicast address ranges of the dependent nodes of the Path Target - uint16_t net_idx - struct esp_ble_mesh_forwarding_table_deps_delete_t Parameters of Forwarding Table Dependents Delete. Public Members - uint16_t net_idx NetKey Index - uint16_t path_origin Primary element address of the Path Origin - uint16_t dst Destination address - uint8_t dep_origin_list_size Number of entries in the Dependent_Origin_List field - uint8_t dep_target_list_size Number of entries in the Dependent_Target_List field - uint16_t *dep_origin_list List of the primary element addresses of the dependent nodes of the Path Origin - uint16_t *dep_target_list List of the primary element addresses of the dependent nodes of the Path Target - uint16_t net_idx - struct esp_ble_mesh_forwarding_table_entries_cnt_get_t Parameters of Forwarding Table Entries Count Get. - struct esp_ble_mesh_forwarding_table_entries_get_t Parameters of Forwarding Table Entries Get. Public Members - uint16_t net_idx NetKey Index - uint16_t filter_mask Filter to be applied to the Forwarding Table entries - uint16_t start_index Start offset to read in units of Forwarding Table entries - uint16_t path_origin Primary element address of the Path Origin - uint16_t dst Destination address - bool include_id Indicate whether or not the Forwarding Table Update Identifier is present - uint16_t update_id Last saved Forwarding Table Update Identifier (Optional) - uint16_t net_idx - struct esp_ble_mesh_forwarding_table_deps_get_t Parameters of Forwarding Table Dependents Get. Public Members - uint16_t net_idx NetKey Index - uint16_t dep_list_mask Filter applied to the lists of unicast address ranges for dependent nodes - uint16_t fixed_path_flag Indicate whether or not to return the unicast address ranges of dependent nodes in a fixed path entry - uint16_t start_index Start offset in units of unicast address ranges - uint16_t path_origin Primary element address of the Path Origin - uint16_t dst Destination address - bool include_id Indicate whether or not the Forwarding Table Update Identifier is present - uint16_t update_id Last saved Forwarding Table Update Identifier (Optional) - uint16_t net_idx - struct esp_ble_mesh_wanted_lanes_get_t Parameters of Wanted Lanes Get. - struct esp_ble_mesh_wanted_lanes_set_t Parameters of Wanted Lanes Set. - struct esp_ble_mesh_two_way_path_get_t Parameters of Two Way Path Get. - struct esp_ble_mesh_two_way_path_set_t Parameters of Two Way Path Set. - struct esp_ble_mesh_path_echo_interval_get_t Parameters of Path Echo Interval Get. - struct esp_ble_mesh_path_echo_interval_set_t Parameters of Path Echo Interval Set. - struct esp_ble_mesh_directed_net_transmit_set_t Parameters of Directed Network Transmit Set. Public Members - uint8_t net_transmit New Directed Network Transmit state - uint8_t net_transmit - struct esp_ble_mesh_directed_relay_retransmit_set_t Parameters of Directed Relay Retransmit Set. Public Members - uint8_t relay_retransmit New Directed Relay Retransmit state - uint8_t relay_retransmit - struct esp_ble_mesh_rssi_threshold_set_t Parameters of RSSI Threshold Set. Public Members - uint8_t rssi_margin New RSSI Margin state - uint8_t rssi_margin - struct esp_ble_mesh_directed_publish_policy_get_t Parameters of Directed Publish Policy Get. - struct esp_ble_mesh_directed_publish_policy_set_t Parameters of Directed Publish Policy Set. - struct esp_ble_mesh_path_discovery_timing_ctl_set_t Parameters of Path Discovery Timing Control Set. - struct esp_ble_mesh_directed_ctl_net_transmit_set_t Parameters of Directed Control Network Transmit Set. Public Members - uint8_t net_transmit New Directed Control Network Transmit Count state - uint8_t net_transmit - struct esp_ble_mesh_directed_ctl_relay_retransmit_set_t Parameters of Directed Control Relay Retransmit Set. Public Members - uint8_t relay_retransmit New Directed Control Relay Retransmit Count state - uint8_t relay_retransmit - struct esp_ble_mesh_directed_control_status_t Parameters of Directed Control Status. Public Members - uint8_t status Status code for the requesting message - uint16_t net_idx NetKey Index - uint8_t directed_forwarding Current Directed Forwarding state - uint8_t directed_relay Current Directed Relay state - uint8_t directed_proxy Current Directed Proxy state - uint8_t directed_proxy_use_default Current Directed Proxy Use Directed Default state or 0xFF - uint8_t directed_friend Current Directed Friend state - uint8_t status - struct esp_ble_mesh_path_metric_status_t Parameters of Path Metric Status. - struct esp_ble_mesh_discovery_table_caps_status_t Parameters of Discovery Table Capabilities Status. - struct esp_ble_mesh_forwarding_table_status_t Parameters of Forwarding Table Status. - struct esp_ble_mesh_forwarding_table_deps_status_t Parameters of Forwarding Table Dependent Status. - struct esp_ble_mesh_forwarding_table_entries_cnt_status_t Parameters of Forwarding Table Entries Count Status. Public Members - uint8_t status Status code for the requesting message - uint16_t net_idx NetKey Index - uint16_t update_id Current Forwarding Table Update Identifier state - uint16_t fixed_entry_cnt Number of fixed path entries in the Forwarding Table - uint16_t non_fixed_entry_cnt Number of non-fixed path entries in the Forwarding Table - uint8_t status - struct esp_ble_mesh_forwarding_table_entry_t Parameters of Forwarding Table Entry. Public Members - uint16_t fixed_path_flag Indicates whether the table entry is a fixed path entry or a non-fixed path entry - uint16_t unicast_dst_flag Indicates whether or not the destination of the path is a unicast address - uint16_t bw_path_validated_flag Indicates whether or not the backward path has been validated - uint16_t bearer_twd_path_origin_ind Indicates the presence or absence of the Bearer_Toward_Path_Origin field - uint16_t bearer_twd_path_target_ind Indicates the presence or absence of the Bearer_Toward_Path_Target field - uint16_t dep_origin_list_size_ind Indicates the size of the Dependent_Origin_List field - uint16_t dep_target_list_size_ind Indicates the size of the Dependent_Target_List field - uint8_t lane_counter Number of lanes in the path - uint16_t path_remaining_time Path lifetime remaining - uint8_t path_origin_forward_number Forwarding number of the Path Origin - esp_ble_mesh_uar_t path_origin Path Origin unicast address range - uint16_t dep_origin_list_size Current number of entries in the list of dependent nodes of the Path Origin - uint16_t bearer_twd_path_origin Index of the bearer toward the Path Origin - esp_ble_mesh_uar_t path_target Path Target unicast address range - uint16_t multicast_dst Multicast destination address - uint16_t dep_target_list_size Current number of entries in the list of dependent nodes of the Path Target - uint16_t bearer_twd_path_target Index of the bearer toward the Path Target - uint16_t fixed_path_flag - struct esp_ble_mesh_forwarding_table_entries_status_t Parameters of Forwarding Table Entries Status. Public Members - uint8_t status Status code for the requesting message - uint16_t net_idx NetKey Index - uint16_t filter_mask Filter applied to the Forwarding Table entries - uint16_t start_index Start offset in units of Forwarding Table entries - uint16_t path_origin Primary element address of the Path Origin - uint16_t dst Destination address - bool include_id Indicate whether or not the Forwarding Table Update Identifier is present - uint16_t update_id Current Forwarding Table Update Identifier state - uint8_t entry_list_size Current number of entries in the list of Forwarding Table entries - esp_ble_mesh_forwarding_table_entry_t *entry_list List of Forwarding Table entries - uint8_t status - struct esp_ble_mesh_forwarding_table_deps_get_status_t Parameters of Forwarding Table Dependents Get Status. Public Members - uint8_t status Status code for the requesting message - uint16_t net_idx NetKey Index - uint16_t dep_list_mask Filter applied to the lists of unicast address ranges for dependent nodes - uint16_t fixed_path_flag Flag indicating whether or not to return the unicast address ranges of dependent nodes in a fixed path entry - uint16_t start_index Start offset in units of unicast address ranges - uint16_t path_origin Primary element address of the Path Origin - uint16_t dst Destination address - bool include_id Indicate whether or not the Forwarding Table Update Identifier is present - uint16_t update_id Current Forwarding Table Update Identifier state - uint8_t dep_origin_uar_list_size Number of unicast address ranges in the Dependent_Origin_Unicast_Addr_Range_List field - uint8_t dep_target_uar_list_size Number of unicast address ranges in the Dependent_Target_Unicast_Addr_Range_List field - esp_ble_mesh_uar_t *dep_origin_uar_list List of unicast address ranges of dependent nodes of the Path Origin - esp_ble_mesh_uar_t *dep_target_uar_list List of unicast address ranges of dependent nodes of the Path Target - uint8_t status - struct esp_ble_mesh_wanted_lanes_status_t Parameters of Wanted Lanes Status. - struct esp_ble_mesh_two_way_path_status_t Parameters of Two Way Path Status. - struct esp_ble_mesh_path_echo_interval_status_t Parameters of Path Echo Interval Status. - struct esp_ble_mesh_directed_net_transmit_status_t Parameters of Directed Network Transmit Status. Public Members - uint8_t net_transmit Current Directed Network Transmit state - uint8_t net_transmit - struct esp_ble_mesh_directed_relay_retransmit_status_t Parameters of Directed Relay Retransmit Status. Public Members - uint8_t relay_retransmit Current Directed Relay Retransmit state - uint8_t relay_retransmit - struct esp_ble_mesh_rssi_threshold_status_t Parameters of RSSI Threshold Status. - struct esp_ble_mesh_directed_paths_status_t Parameters of Directed Paths Status. - struct esp_ble_mesh_directed_pub_policy_status_t Parameters of Directed Publish Policy Status. - struct esp_ble_mesh_path_disc_timing_ctl_status_cb_t Parameters of Path Discovery Timing Control Status. Public Members - uint16_t path_monitor_interval Current Path Monitoring Interval state - uint16_t path_disc_retry_interval Current Path Discovery Retry Interval state - uint8_t path_disc_interval Current Path Discovery Interval state - uint8_t lane_disc_guard_interval Current Lane Discovery Guard Interval state - uint16_t path_monitor_interval - struct esp_ble_mesh_directed_ctl_net_transmit_status_t Parameters of Directed Control Network Transmit Status. Public Members - uint8_t net_transmit Current Directed Control Network Transmit state - uint8_t net_transmit - struct esp_ble_mesh_directed_ctl_relay_retransmit_status_t Parameters of Directed Control Relay Retransmit Status. Public Members - uint8_t relay_retransmit Current Directed Control Relay Retransmit state - uint8_t relay_retransmit - struct esp_ble_mesh_df_client_send_cb_t Result of sending Directed Forwarding Configuration Client messages - struct esp_ble_mesh_df_client_cb_param_t Directed Forwarding Configuration Client model callback parameters Public Members - esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events. - esp_ble_mesh_df_client_send_cb_t send Result of sending a message - esp_ble_mesh_df_client_recv_cb_t recv Parameters of received status message - union esp_ble_mesh_df_client_cb_param_t::[anonymous] [anonymous] Union of DF Client callback - esp_ble_mesh_client_common_param_t *params - struct esp_ble_mesh_df_server_table_change_t Parameters of directed forwarding table entry change Public Members - esp_ble_mesh_df_table_action_t action Action of directed forwarding table - esp_ble_mesh_uar_t path_origin Primary element address of the Path Origin - esp_ble_mesh_uar_t path_target Primary element address of the Path Target - esp_ble_mesh_uar_t *dep_origin_data List of the primary element addresses of the dependent nodes of the Path Origin - uint32_t dep_origin_num Number of entries in the Dependent_Origin_List field of the message - esp_ble_mesh_uar_t *dep_target_data List of the primary element addresses of the dependent nodes of the Path Target - uint32_t dep_target_num Number of entries in the Dependent_Target_List field of the message - uint8_t fixed_path Indicates whether the table entry is a fixed path entry or a non-fixed path entry - uint8_t bw_path_validate Indicates whether or not the backward path has been validated - uint8_t path_not_ready Flag indicating whether or not the path is ready for use - uint8_t forward_number Forwarding number of the Path Origin; If the entry is associated with a fixed path, the value is 0 - uint8_t lane_counter Number of lanes discovered; if the entry is associated with a fixed path, the value is 1. - struct esp_ble_mesh_df_server_table_change_t::[anonymous]::[anonymous] df_table_entry_add_remove Structure of directed forwarding table add and remove Structure of directed forwarding table add and remove - uint8_t dummy Event not used currently - struct esp_ble_mesh_df_server_table_change_t::[anonymous]::[anonymous] df_table_entry_change Structure of directed forwarding table entry change Directed forwarding table entry change - union esp_ble_mesh_df_server_table_change_t::[anonymous] df_table_info Union of directed forwarding table information Directed forwarding table information - esp_ble_mesh_df_table_action_t action - struct esp_ble_mesh_df_server_cb_param_t Directed Forwarding Configuration Server model callback parameters Public Members - esp_ble_mesh_model_t *model Pointer to the server model structure - esp_ble_mesh_msg_ctx_t ctx Context of the received message - esp_ble_mesh_df_server_cb_value_t value Value of the received configuration messages - esp_ble_mesh_model_t *model Macros - ESP_BLE_MESH_MODEL_OP_DIRECTED_CONTROL_GET - ESP_BLE_MESH_MODEL_OP_DIRECTED_CONTROL_SET - ESP_BLE_MESH_MODEL_OP_DIRECTED_CONTROL_STATUS - ESP_BLE_MESH_MODEL_OP_PATH_METRIC_GET - ESP_BLE_MESH_MODEL_OP_PATH_METRIC_SET - ESP_BLE_MESH_MODEL_OP_PATH_METRIC_STATUS - ESP_BLE_MESH_MODEL_OP_DISCOVERY_TABLE_CAPS_GET - ESP_BLE_MESH_MODEL_OP_DISCOVERY_TABLE_CAPS_SET - ESP_BLE_MESH_MODEL_OP_DISCOVERY_TABLE_CAPS_STATUS - ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ADD - ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEL - ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_STATUS - ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_ADD - ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_DEL - ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_STATUS - ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_GET - ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_DEPS_GET_STATUS - ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_CNT_GET - ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_CNT_STATUS - ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_GET - ESP_BLE_MESH_MODEL_OP_FORWARDING_TABLE_ENTRIES_STATUS - ESP_BLE_MESH_MODEL_OP_WANTED_LANES_GET - ESP_BLE_MESH_MODEL_OP_WANTED_LANES_SET - ESP_BLE_MESH_MODEL_OP_WANTED_LANES_STATUS - ESP_BLE_MESH_MODEL_OP_TWO_WAY_PATH_GET - ESP_BLE_MESH_MODEL_OP_TWO_WAY_PATH_SET - ESP_BLE_MESH_MODEL_OP_TWO_WAY_PATH_STATUS - ESP_BLE_MESH_MODEL_OP_PATH_ECHO_INTERVAL_GET - ESP_BLE_MESH_MODEL_OP_PATH_ECHO_INTERVAL_SET - ESP_BLE_MESH_MODEL_OP_PATH_ECHO_INTERVAL_STATUS - ESP_BLE_MESH_MODEL_OP_DIRECTED_NET_TRANSMIT_GET - ESP_BLE_MESH_MODEL_OP_DIRECTED_NET_TRANSMIT_SET - ESP_BLE_MESH_MODEL_OP_DIRECTED_NET_TRANSMIT_STATUS - ESP_BLE_MESH_MODEL_OP_DIRECTED_RELAY_RETRANSMIT_GET - ESP_BLE_MESH_MODEL_OP_DIRECTED_RELAY_RETRANSMIT_SET - ESP_BLE_MESH_MODEL_OP_DIRECTED_RELAY_RETRANSMIT_STATUS - ESP_BLE_MESH_MODEL_OP_RSSI_THRESHOLD_GET - ESP_BLE_MESH_MODEL_OP_RSSI_THRESHOLD_SET - ESP_BLE_MESH_MODEL_OP_RSSI_THRESHOLD_STATUS - ESP_BLE_MESH_MODEL_OP_DIRECTED_PATHS_GET - ESP_BLE_MESH_MODEL_OP_DIRECTED_PATHS_STATUS - ESP_BLE_MESH_MODEL_OP_DIRECTED_PUB_POLICY_GET - ESP_BLE_MESH_MODEL_OP_DIRECTED_PUB_POLICY_SET - ESP_BLE_MESH_MODEL_OP_DIRECTED_PUB_POLICY_STATUS - ESP_BLE_MESH_MODEL_OP_PATH_DISCOVERY_TIMING_CTL_GET - ESP_BLE_MESH_MODEL_OP_PATH_DISCOVERY_TIMING_CTL_SET - ESP_BLE_MESH_MODEL_OP_PATH_DISCOVERY_TIMING_CTL_STATUS - ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_NET_TRANSMIT_GET - ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_NET_TRANSMIT_SET - ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_NET_TRANSMIT_STATUS - ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_RELAY_RETRANSMIT_GET - ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_RELAY_RETRANSMIT_SET - ESP_BLE_MESH_MODEL_OP_DIRECTED_CTL_RELAY_RETRANSMIT_STATUS - ESP_BLE_MESH_PATH_DISC_INTERVAL_5_SEC - ESP_BLE_MESH_PATH_DISC_INTERVAL_30_SEC - ESP_BLE_MESH_LANE_DISC_GUARD_INTERVAL_2_SEC - ESP_BLE_MESH_LANE_DISC_GUARD_INTERVAL_10_SEC - ESP_BLE_MESH_DIRECTED_PUB_POLICY_MANAGED_FLOODING - ESP_BLE_MESH_DIRECTED_PUB_POLICY_DIRECTED_FORWARDING - ESP_BLE_MESH_GET_FILTER_MASK(fp, nfp, pom, dm) - ESP_BLE_MESH_MODEL_DF_SRV(srv_data) Define a new Directed Forwarding Configuration Server model. Note If supported, the model shall be supported by a primary element and shall not be supported by any secondary elements. - Parameters srv_data -- Pointer to a unique Directed Forwarding Configuration Server model user_data. - - Returns New Directed Forwarding Configuration Server model instance. - ESP_BLE_MESH_MODEL_DF_CLI(cli_data) Define a new Directed Forwarding Configuration Client model. Note If supported, the model shall be supported by a primary element and shall not be supported by any secondary elements. - Parameters cli_data -- Pointer to a unique Directed Forwarding Configuration Client model user_data. - - Returns New Directed Forwarding Configuration Client model instance. Type Definitions - typedef void (*esp_ble_mesh_df_client_cb_t)(esp_ble_mesh_df_client_cb_event_t event, esp_ble_mesh_df_client_cb_param_t *param) Bluetooth Mesh Directed Forwarding Configuration client and server model functions. Directed Forwarding Configuration Client model callback function type - Param event Event type - Param param Pointer to callback parameter - typedef void (*esp_ble_mesh_df_server_cb_t)(esp_ble_mesh_df_server_cb_event_t event, esp_ble_mesh_df_server_cb_param_t *param) Directed Forwarding Configuration Server model callback function type. - Param event Event type - Param param Pointer to callback parameter Enumerations - enum esp_ble_mesh_df_client_cb_event_t This enum value is the event of Directed Forwarding Configuration Client model Values: - enumerator ESP_BLE_MESH_DF_CLIENT_SEND_COMP_EVT - enumerator ESP_BLE_MESH_DF_CLIENT_SEND_TIMEOUT_EVT - enumerator ESP_BLE_MESH_DF_CLIENT_RECV_GET_RSP_EVT - enumerator ESP_BLE_MESH_DF_CLIENT_RECV_SET_RSP_EVT - enumerator ESP_BLE_MESH_DF_CLIENT_RECV_PUB_EVT - enumerator ESP_BLE_MESH_DF_CLIENT_EVT_MAX - enumerator ESP_BLE_MESH_DF_CLIENT_SEND_COMP_EVT - enum esp_ble_mesh_df_table_action_t Values: - enumerator ESP_BLE_MESH_DF_TABLE_ACT_EMPTY - enumerator ESP_BLE_MESH_DF_TABLE_ADD - enumerator ESP_BLE_MESH_DF_TABLE_REMOVE - enumerator ESP_BLE_MESH_DF_TABLE_ENTRY_CHANGE - enumerator ESP_BLE_MESH_DF_TABLE_ACT_MAX_LIMIT - enumerator ESP_BLE_MESH_DF_TABLE_ACT_EMPTY Subnet Bridge Configuration Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_brc_model_api.h This header file can be included with: #include "esp_ble_mesh_brc_model_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_brc_client_callback(esp_ble_mesh_brc_client_cb_t callback) Register BLE Mesh Bridge Configuration Client model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_register_brc_server_callback(esp_ble_mesh_brc_server_cb_t callback) Register BLE Mesh Bridge Configuration Server model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_brc_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_brc_client_msg_t *msg) Get/Set the value of Bridge Configuration Server model state with the corresponding message. - Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Bridge Configuration Client message. - - Returns ESP_OK on success or error code otherwise. Unions - union esp_ble_mesh_brc_client_msg_t - #include <esp_ble_mesh_brc_model_api.h> Bridge Configuration Client model message union. Public Members - esp_ble_mesh_bridged_subnets_get_t bridged_subnets_get For ESP_BLE_MESH_MODEL_OP_BRIDGED_SUBNETS_GET - esp_ble_mesh_bridging_table_get_t bridging_table_get For ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_GET - esp_ble_mesh_subnet_bridge_set_t subnet_bridge_set For ESP_BLE_MESH_MODEL_OP_SUBNET_BRIDGE_SET - esp_ble_mesh_bridging_table_add_t bridging_table_add For ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_ADD - esp_ble_mesh_bridging_table_remove_t bridging_table_remove For ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_REMOVE - esp_ble_mesh_bridged_subnets_get_t bridged_subnets_get - union esp_ble_mesh_brc_client_recv_cb_t - #include <esp_ble_mesh_brc_model_api.h> Bridge Configuration Client model received message union. Public Members - esp_ble_mesh_subnet_bridge_status_t subnet_bridge_status ESP_BLE_MESH_MODEL_OP_SUBNET_BRIDGE_STATUS - esp_ble_mesh_bridging_table_status_t bridging_table_status ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_STATUS - esp_ble_mesh_bridged_subnets_list_t bridged_subnets_list ESP_BLE_MESH_MODEL_OP_BRIDGED_SUBNETS_LIST - esp_ble_mesh_bridging_table_list_t bridging_table_list ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_LIST - esp_ble_mesh_bridging_table_size_status_t bridging_table_size_status ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_SIZE_STATUS - esp_ble_mesh_subnet_bridge_status_t subnet_bridge_status - union esp_ble_mesh_brc_server_state_change_t - #include <esp_ble_mesh_brc_model_api.h> Bridge Configuration Server model state change value union. Public Members - esp_ble_mesh_state_change_bridging_table_add_t bridging_table_add The recv_op in ctx can be used to decide which state is changed. Bridging Table Add - esp_ble_mesh_state_change_bridging_table_remove_t bridging_table_remove Bridging Table Remove - esp_ble_mesh_state_change_bridging_table_add_t bridging_table_add - union esp_ble_mesh_brc_server_cb_value_t - #include <esp_ble_mesh_brc_model_api.h> Bridge Configuration Server model callback value union. Public Members - esp_ble_mesh_brc_server_state_change_t state_change For ESP_BLE_MESH_BRC_SERVER_STATE_CHANGE_EVT - esp_ble_mesh_brc_server_state_change_t state_change Structures - struct esp_ble_mesh_subnet_bridge_table_t Parameters of subnet bridge table - struct esp_ble_mesh_subnet_bridge_set_t Parameters of Subnet Bridge Set Public Members - uint8_t subnet_bridge New Subnet Bridge state - uint8_t subnet_bridge - struct esp_ble_mesh_bridging_table_add_t Parameters of Bridging Table Add Public Members - uint8_t bridge_direction Allowed directions for the bridged traffic - uint16_t bridge_net_idx_1 NetKey Index of the first subnet - uint16_t bridge_net_idx_2 NetKey Index of the second subnet - uint16_t bridge_addr_1 Address of the node in the first subnet - uint16_t bridge_addr_2 Address of the node in the second subnet - uint8_t bridge_direction - struct esp_ble_mesh_bridging_table_remove_t Parameters of Bridging Table Remove - struct esp_ble_mesh_bridged_subnets_get_t Parameters of Bridged Subnets Get - struct esp_ble_mesh_bridging_table_get_t Parameters of Bridging Table Get - struct esp_ble_mesh_subnet_bridge_status_t Parameters of Subnet Bridge Status Public Members - uint8_t subnet_bridge Current Subnet Bridge state - uint8_t subnet_bridge - struct esp_ble_mesh_bridging_table_status_t Parameters of Bridging Table Status Public Members - uint8_t status Status Code for the requesting message - uint8_t bridge_direction Allowed directions for the bridged traffic - uint16_t bridge_net_idx_1 NetKey Index of the first subnet - uint16_t bridge_net_idx_2 NetKey Index of the second subnet - uint16_t bridge_addr_1 Address of the node in the first subnet - uint16_t bridge_addr_2 Address of the node in the second subnet - uint8_t status - struct esp_ble_mesh_bridge_net_idx_pair_entry_t Bridged_Subnets_List entry format - struct esp_ble_mesh_bridged_subnets_list_t Parameters of Bridged Subnets List Public Members - uint16_t bridge_filter Filter applied to the set of pairs of NetKey Indexes - uint16_t bridge_net_idx NetKey Index used for filtering or ignored - uint8_t bridge_start_idx Start offset in units of bridges - uint8_t bridged_entry_list_size Num of pairs of NetKey Indexes - esp_ble_mesh_bridge_net_idx_pair_entry_t *net_idx_pair Filtered set of N pairs of NetKey Indexes - uint16_t bridge_filter - struct esp_ble_mesh_bridged_addr_list_entry_t Bridged_Addresses_List entry format - struct esp_ble_mesh_bridging_table_list_t Parameters of Bridging Table List Public Members - uint8_t status Status Code for the requesting message - uint16_t bridge_net_idx_1 NetKey Index of the first subnet - uint16_t bridge_net_idx_2 NetKey Index of the second subnet - uint16_t bridge_start_idx Start offset in units of Bridging Table state entries - uint16_t bridged_addr_list_size Num of pairs of entry - esp_ble_mesh_bridged_addr_list_entry_t *bridged_addr_list List of bridged addresses and allowed traffic directions - uint8_t status - struct esp_ble_mesh_bridging_table_size_status_t Parameters of Bridging Table Size Status Public Members - uint16_t bridging_table_size Bridging Table Size state - uint16_t bridging_table_size - struct esp_ble_mesh_brc_client_send_cb_t Result of sending Bridge Configuration Client messages - struct esp_ble_mesh_brc_client_cb_param_t Bridge Configuration Client model callback parameters Public Members - esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events. - esp_ble_mesh_brc_client_send_cb_t send Result of sending a message - esp_ble_mesh_brc_client_recv_cb_t recv Parameters of received status message - union esp_ble_mesh_brc_client_cb_param_t::[anonymous] [anonymous] Union of Bridge Configuration Client callback - esp_ble_mesh_client_common_param_t *params - struct esp_ble_mesh_state_change_bridging_table_add_t Bridge Configuration Server model related context. Parameters of Bridging Table Add Public Members - uint8_t bridge_direction Allowed directions for the bridged traffic - uint16_t bridge_net_idx_1 NetKey Index of the first subnet - uint16_t bridge_net_idx_2 NetKey Index of the second subnet - uint16_t bridge_addr_1 Address of the node in the first subnet - uint16_t bridge_addr_2 Address of the node in the second subnet - uint8_t bridge_direction - struct esp_ble_mesh_state_change_bridging_table_remove_t Parameters of Bridging Table Remove - struct esp_ble_mesh_brc_server_cb_param_t Bridge Configuration Server model callback parameters Public Members - esp_ble_mesh_model_t *model Pointer to the server model structure - esp_ble_mesh_msg_ctx_t ctx Context of the received message - esp_ble_mesh_brc_server_cb_value_t value Value of the received configuration messages - esp_ble_mesh_model_t *model Macros - ESP_BLE_MESH_MODEL_OP_SUBNET_BRIDGE_GET - ESP_BLE_MESH_MODEL_OP_SUBNET_BRIDGE_SET - ESP_BLE_MESH_MODEL_OP_SUBNET_BRIDGE_STATUS - ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_ADD - ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_REMOVE - ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_STATUS - ESP_BLE_MESH_MODEL_OP_BRIDGED_SUBNETS_GET - ESP_BLE_MESH_MODEL_OP_BRIDGED_SUBNETS_LIST - ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_GET - ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_LIST - ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_SIZE_GET - ESP_BLE_MESH_MODEL_OP_BRIDGING_TABLE_SIZE_STATUS - ESP_BLE_MESH_MODEL_BRC_SRV(srv_data) Define a new Bridge Configuration Server model. Note If supported, the model shall be supported by a primary element and shall not be supported by any secondary elements. - Parameters srv_data -- Pointer to a unique Bridge Configuration Server model user_data. - - Returns New Bridge Configuration Server model instance. - ESP_BLE_MESH_MODEL_BRC_CLI(cli_data) Define a new Bridge Configuration Client model. Note If supported, the model shall be supported by a primary element and shall not be supported by any secondary elements. - Parameters cli_data -- Pointer to a unique Bridge Configuration Client model user_data. - - Returns New Bridge Configuration Client model instance. Type Definitions - typedef void (*esp_ble_mesh_brc_client_cb_t)(esp_ble_mesh_brc_client_cb_event_t event, esp_ble_mesh_brc_client_cb_param_t *param) Bluetooth Mesh Bridge Configuration client and server model functions. Bridge Configuration Client model callback function type - Param event Event type - Param param Pointer to callback parameter - typedef void (*esp_ble_mesh_brc_server_cb_t)(esp_ble_mesh_brc_server_cb_event_t event, esp_ble_mesh_brc_server_cb_param_t *param) Bridge Configuration Server model callback function type. - Param event Event type - Param param Pointer to callback parameter Enumerations - enum esp_ble_mesh_brc_client_cb_event_t This enum value is the event of Bridge Configuration Client model Values: - enumerator ESP_BLE_MESH_BRC_CLIENT_SEND_COMP_EVT - enumerator ESP_BLE_MESH_BRC_CLIENT_SEND_TIMEOUT_EVT - enumerator ESP_BLE_MESH_BRC_CLIENT_RECV_RSP_EVT - enumerator ESP_BLE_MESH_BRC_CLIENT_RECV_PUB_EVT - enumerator ESP_BLE_MESH_BRC_CLIENT_EVT_MAX - enumerator ESP_BLE_MESH_BRC_CLIENT_SEND_COMP_EVT Mesh Private Beacon Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_prb_model_api.h This header file can be included with: #include "esp_ble_mesh_prb_model_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_prb_client_callback(esp_ble_mesh_prb_client_cb_t callback) Register BLE Mesh Private Beacon Client Model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_register_prb_server_callback(esp_ble_mesh_prb_server_cb_t callback) Register BLE Mesh Private Beacon Server Model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_prb_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_prb_client_msg_t *msg) Get/Set the value of Private Beacon Server Model states using the corresponding messages of Private Beacon Client Model. - Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Mesh Private Beacon Client message. - - Returns ESP_OK on success or error code otherwise. Unions - union esp_ble_mesh_prb_client_msg_t - #include <esp_ble_mesh_prb_model_api.h> Mesh Private Beacon Client model message union. Public Members - esp_ble_mesh_priv_beacon_set_t priv_beacon_set ESP_BLE_MESH_MODEL_OP_PRIV_BEACON_SET. - esp_ble_mesh_priv_gatt_proxy_set_t priv_gatt_proxy_set ESP_BLE_MESH_MODEL_OP_PRIV_GATT_PROXY_SET. - esp_ble_mesh_priv_node_id_get_t priv_node_id_get ESP_BLE_MESH_MODEL_OP_PRIV_NODE_IDENTITY_GET. - esp_ble_mesh_priv_node_id_set_t priv_node_id_set ESP_BLE_MESH_MODEL_OP_PRIV_NODE_IDENTITY_SET. - esp_ble_mesh_priv_beacon_set_t priv_beacon_set - union esp_ble_mesh_prb_client_recv_cb_t - #include <esp_ble_mesh_prb_model_api.h> Private Beacon Client Model received message union. Public Members - esp_ble_mesh_priv_beacon_status_cb_t priv_beacon_status The private beacon status value - esp_ble_mesh_priv_gatt_proxy_status_cb_t priv_gatt_proxy_status The private gatt proxy status value - esp_ble_mesh_priv_node_identity_status_cb_t priv_node_id_status The private node identity status value - esp_ble_mesh_priv_beacon_status_cb_t priv_beacon_status - union esp_ble_mesh_prb_server_state_change_t - #include <esp_ble_mesh_prb_model_api.h> Mesh Private Beacon Server model state change value union. Public Members - esp_ble_mesh_state_change_priv_beacon_set_t priv_beacon_set The recv_op in ctx can be used to decide which state is changed. Private Beacon Set - esp_ble_mesh_state_change_priv_gatt_proxy_set_t priv_gatt_proxy_set Private GATT Proxy Set - esp_ble_mesh_state_change_priv_node_id_set_t priv_node_id_set Private Node Identity Set - esp_ble_mesh_state_change_priv_beacon_set_t priv_beacon_set - union esp_ble_mesh_prb_server_cb_value_t - #include <esp_ble_mesh_prb_model_api.h> Private Beacon Server model callback value union. Public Members - esp_ble_mesh_prb_server_state_change_t state_change ESP_BLE_MESH_PRB_SERVER_STATE_CHANGE_EVT - esp_ble_mesh_prb_server_state_change_t state_change Structures - struct esp_ble_mesh_prb_srv_t Private Beacon Server Model context Public Members - esp_ble_mesh_model_t *model Pointer to Private Beacon Server Model - uint8_t private_beacon Value of Private Beacon state - uint8_t random_update_interval Value of Random Update Interval Steps state - uint8_t private_gatt_proxy Value of Private GATT Proxy state - struct k_delayed_work update_timer Timer for update the random field of private beacon - esp_ble_mesh_model_t *model - struct esp_ble_mesh_priv_beacon_set_t Parameter of private Beacon Set - struct esp_ble_mesh_priv_gatt_proxy_set_t Parameter of Private GATT Proxy Set Public Members - uint8_t private_gatt_proxy New Private GATT Proxy state - uint8_t private_gatt_proxy - struct esp_ble_mesh_priv_node_id_get_t Parameter of Private node identity Get Public Members - uint16_t net_idx Index of the NetKey - uint16_t net_idx - struct esp_ble_mesh_priv_node_id_set_t Parameter of Private node identity Set - struct esp_ble_mesh_priv_beacon_status_cb_t Parameter of Private Beacon Status - struct esp_ble_mesh_priv_gatt_proxy_status_cb_t Parameter of Private GATT Proxy Status Public Members - uint8_t private_gatt_proxy Private GATT Proxy state - uint8_t private_gatt_proxy - struct esp_ble_mesh_priv_node_identity_status_cb_t Parameters of Private Node Identity Status - struct esp_ble_mesh_prb_client_send_cb_t Result of sending Bridge Configuration Client messages - struct esp_ble_mesh_prb_client_cb_param_t Mesh Private Beacon Client Model callback parameters Public Members - esp_ble_mesh_client_common_param_t *params The client common parameters. - esp_ble_mesh_prb_client_send_cb_t send Result of sending a message - esp_ble_mesh_prb_client_recv_cb_t recv The private beacon message status callback values - union esp_ble_mesh_prb_client_cb_param_t::[anonymous] [anonymous] Union of Private Beacon Client callback - esp_ble_mesh_client_common_param_t *params - struct esp_ble_mesh_state_change_priv_beacon_set_t Mesh Private Beacon Server model related context. Parameters of Private Beacon Set. - struct esp_ble_mesh_state_change_priv_gatt_proxy_set_t Parameters of Private GATT Proxy Set. Public Members - uint8_t private_gatt_proxy Private GATT Proxy state - uint8_t private_gatt_proxy - struct esp_ble_mesh_state_change_priv_node_id_set_t Parameters of Private Node Identity Set. - struct esp_ble_mesh_prb_server_cb_param_t Private Beacon Server model callback parameters Public Members - esp_ble_mesh_model_t *model Pointer to the server model structure - esp_ble_mesh_msg_ctx_t ctx Context of the received message - esp_ble_mesh_prb_server_cb_value_t value Value of the received private beacon messages - esp_ble_mesh_model_t *model Macros - ESP_BLE_MESH_MODEL_OP_PRIV_BEACON_GET - ESP_BLE_MESH_MODEL_OP_PRIV_BEACON_SET - ESP_BLE_MESH_MODEL_OP_PRIV_BEACON_STATUS - ESP_BLE_MESH_MODEL_OP_PRIV_GATT_PROXY_GET - ESP_BLE_MESH_MODEL_OP_PRIV_GATT_PROXY_SET - ESP_BLE_MESH_MODEL_OP_PRIV_GATT_PROXY_STATUS - ESP_BLE_MESH_MODEL_OP_PRIV_NODE_IDENTITY_GET - ESP_BLE_MESH_MODEL_OP_PRIV_NODE_IDENTITY_SET - ESP_BLE_MESH_MODEL_OP_PRIV_NODE_IDENTITY_STATUS - ESP_BLE_MESH_MODEL_PRB_SRV(srv_data) Define a new Private Beacon Server Model. Note The Private Beacon Server Model can only be included by a Primary Element. - Parameters srv_data -- Pointer to a unique Private Beacon Server Model user_data. - - Returns New Private Beacon Server Model instance. - ESP_BLE_MESH_MODEL_PRB_CLI(cli_data) Define a new Private Beacon Client Model. Note The Private Beacon Client Model can only be included by a Primary Element. - Parameters cli_data -- Pointer to a unique struct esp_ble_mesh_client_t. - - Returns New Private Beacon Client Model instance. Type Definitions - typedef void (*esp_ble_mesh_prb_client_cb_t)(esp_ble_mesh_prb_client_cb_event_t event, esp_ble_mesh_prb_client_cb_param_t *param) Bluetooth Mesh Private Beacon Client and Server Model functions. Private Beacon Client Model callback function type - Param event Event type - Param param Pointer to callback parameter - typedef void (*esp_ble_mesh_prb_server_cb_t)(esp_ble_mesh_prb_server_cb_event_t event, esp_ble_mesh_prb_server_cb_param_t *param) Private Beacon Server Model callback function type. - Param event Event type - Param param Pointer to callback parameter Enumerations - enum esp_ble_mesh_prb_client_cb_event_t This enum value is the event of Private Beacon Client Model Values: - enumerator ESP_BLE_MESH_PRB_CLIENT_SEND_COMP_EVT - enumerator ESP_BLE_MESH_PRB_CLIENT_SEND_TIMEOUT_EVT - enumerator ESP_BLE_MESH_PRB_CLIENT_RECV_RSP_EVT - enumerator ESP_BLE_MESH_PRB_CLIENT_RECV_PUB_EVT - enumerator ESP_BLE_MESH_PRB_CLIENT_EVT_MAX - enumerator ESP_BLE_MESH_PRB_CLIENT_SEND_COMP_EVT On-Demand Private Proxy Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_odp_model_api.h This header file can be included with: #include "esp_ble_mesh_odp_model_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_odp_client_callback(esp_ble_mesh_odp_client_cb_t callback) Register BLE Mesh On-Demand Private Proxy Config Client model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_odp_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_odp_client_msg_t *msg) Get the value of On-Demand Private Proxy Config Server model state with the corresponding get message. - Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to On-Demand Private Proxy Config Client message. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_register_odp_server_callback(esp_ble_mesh_odp_server_cb_t callback) Register BLE Mesh On-Demand Private Proxy Config Server model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. Unions - union esp_ble_mesh_odp_client_msg_t - #include <esp_ble_mesh_odp_model_api.h> On-Demand Private Proxy Client model message union. Public Members - esp_ble_mesh_od_priv_proxy_set_t od_priv_proxy_set For ESP_BLE_MESH_MODEL_OP_OD_PRIV_PROXY_SET - esp_ble_mesh_od_priv_proxy_set_t od_priv_proxy_set - union esp_ble_mesh_odp_client_recv_cb_t - #include <esp_ble_mesh_odp_model_api.h> On-Demand Private Proxy Client model received message union. Public Members - esp_ble_mesh_od_priv_proxy_status_t od_priv_proxy_status For ESP_BLE_MESH_MODEL_OP_OD_PRIV_PROXY_STATUS - esp_ble_mesh_od_priv_proxy_status_t od_priv_proxy_status - union esp_ble_mesh_odp_server_state_change_t - #include <esp_ble_mesh_odp_model_api.h> On-Demand Private Proxy Config Server model related context. On-Demand Private Proxy Config Server model state change value union - union esp_ble_mesh_odp_server_cb_value_t - #include <esp_ble_mesh_odp_model_api.h> On-Demand Private Proxy Config Server model callback value union. Public Members - esp_ble_mesh_odp_server_state_change_t state_change For ESP_BLE_MESH_ODP_SERVER_STATE_CHANGE_EVT - esp_ble_mesh_odp_server_state_change_t state_change Structures - struct esp_ble_mesh_odp_srv_t On-Demand Private Proxy Config Server model context Public Members - esp_ble_mesh_model_t *model Pointer to On-Demand Private Proxy Config Server model - uint8_t on_demand_private_gatt_proxy Duration in seconds of the interval during which advertising with Private Network Identity type is enabled after receiving a Solicitation PDU or after a client disconnect. Note: Binding with the Private GATT Proxy state. - esp_ble_mesh_model_t *model - struct esp_ble_mesh_od_priv_proxy_set_t Parameter of On-Demand Private Proxy Set Public Members - uint8_t gatt_proxy On-Demand Private GATT Proxy - uint8_t gatt_proxy - struct esp_ble_mesh_od_priv_proxy_status_t Parameter of On-Demand Private Proxy Status Public Members - uint8_t gatt_proxy On-Demand Private GATT Proxy - uint8_t gatt_proxy - struct esp_ble_mesh_odp_client_send_cb_t Result of sending On-Demand Private Proxy Client messages - struct esp_ble_mesh_odp_client_cb_param_t On-Demand Private Proxy Config Client model callback parameters Public Members - esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events - esp_ble_mesh_odp_client_send_cb_t send Result of sending a message - esp_ble_mesh_odp_client_recv_cb_t recv Parameters of received status message - union esp_ble_mesh_odp_client_cb_param_t::[anonymous] [anonymous] Union of ODP Client callback - esp_ble_mesh_client_common_param_t *params - struct esp_ble_mesh_odp_server_cb_param_t On-Demand Private Proxy Config Server model callback parameters Public Members - esp_ble_mesh_model_t *model Pointer to the server model structure - esp_ble_mesh_msg_ctx_t ctx Context of the received message - esp_ble_mesh_odp_server_cb_value_t value Value of the received configuration messages - esp_ble_mesh_model_t *model Macros - ESP_BLE_MESH_MODEL_OP_OD_PRIV_PROXY_GET - ESP_BLE_MESH_MODEL_OP_OD_PRIV_PROXY_SET - ESP_BLE_MESH_MODEL_OP_OD_PRIV_PROXY_STATUS - ESP_BLE_MESH_MODEL_ODP_SRV(srv_data) Define a new On-Demand Private Proxy Config Server model. Note The On-Demand Private Proxy Server model is used to represent the ability to enable advertising with Private Network Identity type of a node. This model extends the Mesh Private Beacon Server model. When this model is present on an element, the corresponding Solicitation PDU RPL Configuration Server model shall also be present. The model shall be supported by a primary element and shall not be supported by any secondary elements. - Parameters srv_data -- Pointer to a unique On-Demand Private Proxy Config Server model user_data. - - Returns New On-Demand Private Proxy Config Server model instance. - ESP_BLE_MESH_MODEL_ODP_CLI(cli_data) Define a new On-Demand Private Proxy Config Client model. Note The model shall be supported by a primary element and shall not be supported by any secondary elements. - Parameters cli_data -- Pointer to a unique On-Demand Private Proxy Config Client model user_data. - - Returns New On-Demand Private Proxy Config Client model instance. Type Definitions - typedef void (*esp_ble_mesh_odp_client_cb_t)(esp_ble_mesh_odp_client_cb_event_t event, esp_ble_mesh_odp_client_cb_param_t *param) Bluetooth Mesh On-Demand Private Proxy Config client and server model functions. On-Demand Private Proxy Config Client model callback function type - Param event Event type - Param param Pointer to callback parameter - typedef void (*esp_ble_mesh_odp_server_cb_t)(esp_ble_mesh_odp_server_cb_event_t event, esp_ble_mesh_odp_server_cb_param_t *param) On-Demand Private Proxy Config Server model callback function type. - Param event Event type - Param param Pointer to callback parameter Enumerations - enum esp_ble_mesh_odp_client_cb_event_t This enum value is the event of On-Demand Private Proxy Config Client model Values: - enumerator ESP_BLE_MESH_ODP_CLIENT_SEND_COMP_EVT - enumerator ESP_BLE_MESH_ODP_CLIENT_SEND_TIMEOUT_EVT - enumerator ESP_BLE_MESH_ODP_CLIENT_RECV_RSP_EVT - enumerator ESP_BLE_MESH_ODP_CLIENT_RECV_PUB_EVT - enumerator ESP_BLE_MESH_ODP_CLIENT_EVT_MAX - enumerator ESP_BLE_MESH_ODP_CLIENT_SEND_COMP_EVT SAR Configuration Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_sar_model_api.h This header file can be included with: #include "esp_ble_mesh_sar_model_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_sar_client_callback(esp_ble_mesh_sar_client_cb_t callback) Register BLE Mesh SAR Configuration Client model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_sar_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_sar_client_msg_t *msg) Get the value of SAR Configuration Server model state with the corresponding get message. - Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to SAR Configuration Client message. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_register_sar_server_callback(esp_ble_mesh_sar_server_cb_t callback) Register BLE Mesh SAR Configuration Server model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. Unions - union esp_ble_mesh_sar_client_msg_t - #include <esp_ble_mesh_sar_model_api.h> SAR Configuration Client model message union. Public Members - esp_ble_mesh_sar_transmitter_set_t sar_transmitter_set For ESP_BLE_MESH_MODEL_OP_SAR_TRANSMITTER_SET - esp_ble_mesh_sar_receiver_set_t sar_receiver_set For ESP_BLE_MESH_MODEL_OP_SAR_RECEIVER_SET - esp_ble_mesh_sar_transmitter_set_t sar_transmitter_set - union esp_ble_mesh_sar_client_recv_cb_t - #include <esp_ble_mesh_sar_model_api.h> SAR Configuration Client model received message union. Public Members - esp_ble_mesh_sar_transmitter_status_t sar_transmitter_status For ESP_BLE_MESH_MODEL_OP_SAR_TRANSMITTER_STATUS - esp_ble_mesh_sar_receiver_status_t sar_receiver_status For ESP_BLE_MESH_MODEL_OP_SAR_RECEIVE_STATUS - esp_ble_mesh_sar_transmitter_status_t sar_transmitter_status - union esp_ble_mesh_sar_server_state_change_t - #include <esp_ble_mesh_sar_model_api.h> SAR Configuration Server model related context. SAR Configuration Server model state change value union - union esp_ble_mesh_sar_server_cb_value_t - #include <esp_ble_mesh_sar_model_api.h> SAR Configuration Server model callback value union. Public Members - esp_ble_mesh_sar_server_state_change_t state_change For ESP_BLE_MESH_SAR_SERVER_STATE_CHANGE_EVT - esp_ble_mesh_sar_server_state_change_t state_change Structures - struct esp_ble_mesh_sar_srv_t SAR Configuration Server model context Public Members - esp_ble_mesh_model_t *model Pointer to SAR Configuration Server model - esp_ble_mesh_model_t *model - struct esp_ble_mesh_sar_transmitter_set_t Parameters of SAR Transmitter Set Public Members - uint8_t sar_segment_interval_step SAR Segment Interval Step state value - uint8_t sar_unicast_retrans_count SAR Unicast Retransmissions Count state - uint8_t sar_unicast_retrans_without_progress_count SAR Unicast Retransmissions Without Progress Count state - uint8_t sar_unicast_retrans_interval_step SAR Unicast Retransmissions Interval Step state - uint8_t sar_unicast_retrans_interval_increment SAR Unicast Retransmissions Interval Increment state - uint8_t sar_multicast_retrans_count SAR Multicast Retransmissions Count state - uint8_t sar_multicast_retrans_interval_step SAR Multicast Retransmissions Interval state - uint8_t sar_segment_interval_step - struct esp_ble_mesh_sar_receiver_set_t Parameters of SAR Receiver Set Public Members - uint8_t sar_segments_threshold SAR Segments Threshold state - uint8_t sar_ack_delay_increment SAR Acknowledgment Delay Increment state - uint8_t sar_discard_timeout SAR Discard Timeout state - uint8_t sar_receiver_segment_interval_step SAR Receiver Segment Interval Step state - uint8_t sar_ack_retrans_count SAR Acknowledgment Retransmissions Count state - uint8_t sar_segments_threshold - struct esp_ble_mesh_sar_transmitter_status_t Parameters of SAR Transmitter Status Public Members - uint8_t sar_segment_interval_step SAR Segment Interval Step state value - uint8_t sar_unicast_retrans_count SAR Unicast Retransmissions Count state - uint8_t sar_unicast_retrans_without_progress_count SAR Unicast Retransmissions Without Progress Count state - uint8_t sar_unicast_retrans_interval_step SAR Unicast Retransmissions Interval Step state - uint8_t sar_unicast_retrans_interval_increment SAR Unicast Retransmissions Interval Increment state - uint8_t sar_multicast_retrans_count SAR Multicast Retransmissions Count state - uint8_t sar_multicast_retrans_interval_step SAR Multicast Retransmissions Interval state - uint8_t sar_segment_interval_step - struct esp_ble_mesh_sar_receiver_status_t Parameters of SAR Receiver Status Public Members - uint8_t sar_segments_threshold SAR Segments Threshold state - uint8_t sar_ack_delay_increment SAR Acknowledgment Delay Increment state - uint8_t sar_discard_timeout SAR Discard Timeout state - uint8_t sar_receiver_segment_interval_step SAR Receiver Segment Interval Step state - uint8_t sar_ack_retrans_count SAR Acknowledgment Retransmissions Count state - uint8_t sar_segments_threshold - struct esp_ble_mesh_sar_client_send_cb_t Result of sending SAR Configuration Client messages - struct esp_ble_mesh_sar_client_cb_param_t SAR Configuration Client model callback parameters Public Members - esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events. - esp_ble_mesh_sar_client_send_cb_t send Result of sending a message - esp_ble_mesh_sar_client_recv_cb_t recv Parameters of received status message - union esp_ble_mesh_sar_client_cb_param_t::[anonymous] [anonymous] Union of SAR Client callback - esp_ble_mesh_client_common_param_t *params - struct esp_ble_mesh_sar_server_cb_param_t SAR Configuration Server model callback parameters Public Members - esp_ble_mesh_model_t *model Pointer to the server model structure - esp_ble_mesh_msg_ctx_t ctx Context of the received message - esp_ble_mesh_sar_server_cb_value_t value Value of the received configuration messages - esp_ble_mesh_model_t *model Macros - ESP_BLE_MESH_MODEL_OP_SAR_TRANSMITTER_GET - ESP_BLE_MESH_MODEL_OP_SAR_TRANSMITTER_SET - ESP_BLE_MESH_MODEL_OP_SAR_TRANSMITTER_STATUS - ESP_BLE_MESH_MODEL_OP_SAR_RECEIVER_GET - ESP_BLE_MESH_MODEL_OP_SAR_RECEIVER_SET - ESP_BLE_MESH_MODEL_OP_SAR_RECEIVER_STATUS - ESP_BLE_MESH_MODEL_SAR_SRV(srv_data) Define a new SAR Configuration Server model. Note If supported, the model shall be supported by a primary element and shall not be supported by any secondary elements. - Parameters srv_data -- Pointer to a unique SAR Configuration Server model user_data. - - Returns New SAR Configuration Server model instance. - ESP_BLE_MESH_MODEL_SAR_CLI(cli_data) Define a new SAR Configuration Client model. Note If supported, the model shall be supported by the primary element and shall not be supported by any secondary elements. - Parameters cli_data -- Pointer to a unique SAR Configuration Client model user_data. - - Returns New SAR Configuration Client model instance. Type Definitions - typedef void (*esp_ble_mesh_sar_client_cb_t)(esp_ble_mesh_sar_client_cb_event_t event, esp_ble_mesh_sar_client_cb_param_t *param) Bluetooth Mesh SAR Configuration client and server model functions. SAR Configuration Client model callback function type - Param event Event type - Param param Pointer to callback parameter - typedef void (*esp_ble_mesh_sar_server_cb_t)(esp_ble_mesh_sar_server_cb_event_t event, esp_ble_mesh_sar_server_cb_param_t *param) SAR Configuration Server model callback function type. - Param event Event type - Param param Pointer to callback parameter Enumerations - enum esp_ble_mesh_sar_client_cb_event_t This enum value is the event of SAR Configuration Client model Values: - enumerator ESP_BLE_MESH_SAR_CLIENT_SEND_COMP_EVT - enumerator ESP_BLE_MESH_SAR_CLIENT_SEND_TIMEOUT_EVT - enumerator ESP_BLE_MESH_SAR_CLIENT_RECV_RSP_EVT - enumerator ESP_BLE_MESH_SAR_CLIENT_RECV_PUB_EVT - enumerator ESP_BLE_MESH_SAR_CLIENT_EVT_MAX - enumerator ESP_BLE_MESH_SAR_CLIENT_SEND_COMP_EVT Solicitation PDU RPL Configuration Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_srpl_model_api.h This header file can be included with: #include "esp_ble_mesh_srpl_model_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_srpl_client_callback(esp_ble_mesh_srpl_client_cb_t callback) Register BLE Mesh Solicitation PDU RPL Configuration Client model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_srpl_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_srpl_client_msg_t *msg) Set the value of Solicitation PDU RPL Configuration Server model state with the corresponding set message. - Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Solicitation PDU RPL Configuration Client message. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_register_srpl_server_callback(esp_ble_mesh_srpl_server_cb_t callback) Register BLE Mesh Solicitation PDU RPL Configuration Server model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. Unions - union esp_ble_mesh_srpl_client_msg_t - #include <esp_ble_mesh_srpl_model_api.h> Solicitation PDU RPL Configuration Client model message union. Public Members - esp_ble_mesh_srpl_items_clear_t srpl_items_clear For ESP_BLE_MESH_MODEL_OP_SRPL_ITEMS_CLEAR - esp_ble_mesh_srpl_items_clear_t srpl_items_clear - union esp_ble_mesh_srpl_client_recv_cb_t - #include <esp_ble_mesh_srpl_model_api.h> Solicitation PDU RPL Configuration Client model received message union. Public Members - esp_ble_mesh_srpl_items_status_t srpl_items_status For ESP_BLE_MESH_MODEL_OP_SRPL_ITEMS_STATUS - esp_ble_mesh_srpl_items_status_t srpl_items_status - union esp_ble_mesh_srpl_server_state_change_t - #include <esp_ble_mesh_srpl_model_api.h> Solicitation PDU RPL Configuration Server model related context. Solicitation PDU RPL Configuration Server model state change value union Public Members - uint8_t dummy Currently this event is not used. - uint8_t dummy - union esp_ble_mesh_srpl_server_cb_value_t - #include <esp_ble_mesh_srpl_model_api.h> Solicitation PDU RPL Configuration Server model callback value union. Public Members - esp_ble_mesh_srpl_server_state_change_t state_change ESP_BLE_MESH_SRPL_SERVER_STATE_CHANGE_EVT - esp_ble_mesh_srpl_server_state_change_t state_change Structures - struct esp_ble_mesh_srpl_srv_t Solicitation PDU RPL Configuration Server model context Public Members - esp_ble_mesh_model_t *model Pointer to Solicitation PDU RPL Configuration Server model - esp_ble_mesh_model_t *model - struct esp_ble_mesh_srpl_items_clear_t Parameter of Solicitation PDU RPL Items Clear Public Members - esp_ble_mesh_uar_t addr_range Unicast address range - esp_ble_mesh_uar_t addr_range - struct esp_ble_mesh_srpl_items_status_t Parameter of Solicitation PDU RPL Items Clear Status Public Members - esp_ble_mesh_uar_t addr_range Unicast address range - esp_ble_mesh_uar_t addr_range - struct esp_ble_mesh_srpl_client_send_cb_t Result of sending Solicitation PDU RPL Configuration Client messages - struct esp_ble_mesh_srpl_client_cb_param_t Solicitation PDU RPL Configuration Client model callback parameters Public Members - esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events. - esp_ble_mesh_srpl_client_send_cb_t send Result of sending a message - esp_ble_mesh_srpl_client_recv_cb_t recv Parameters of received status message - union esp_ble_mesh_srpl_client_cb_param_t::[anonymous] [anonymous] Union of SRPL Client callback - esp_ble_mesh_client_common_param_t *params - struct esp_ble_mesh_srpl_server_cb_param_t Solicitation PDU RPL Configuration Server model callback parameters Public Members - esp_ble_mesh_model_t *model Pointer to the server model structure - esp_ble_mesh_msg_ctx_t ctx Context of the received message - esp_ble_mesh_srpl_server_cb_value_t value Value of the received configuration messages - esp_ble_mesh_model_t *model Macros - ESP_BLE_MESH_MODEL_OP_SRPL_ITEMS_CLEAR - ESP_BLE_MESH_MODEL_OP_SRPL_ITEMS_CLEAR_UNACK - ESP_BLE_MESH_MODEL_OP_SRPL_ITEMS_STATUS - ESP_BLE_MESH_MODEL_SRPL_SRV(srv_data) Define a new Solicitation PDU RPL Configuration Server model. Note The Solicitation PDU RPL Configuration Server model extends the On-Demand Private Proxy Server model. If the model is supported, the model shall be supported by a primary element and shall not be supported by any secondary elements. - Parameters srv_data -- Pointer to a unique Solicitation PDU RPL Configuration Server model user_data. - - Returns New Solicitation PDU RPL Configuration Server model instance. - ESP_BLE_MESH_MODEL_SRPL_CLI(cli_data) Define a new Solicitation PDU RPL Configuration Client model. Note If supported, the model shall be supported by the primary element and shall not be supported by any secondary elements. - Parameters cli_data -- Pointer to a unique Solicitation PDU RPL Configuration Client model user_data. - - Returns New Solicitation PDU RPL Configuration Client model instance. Type Definitions - typedef void (*esp_ble_mesh_srpl_client_cb_t)(esp_ble_mesh_srpl_client_cb_event_t event, esp_ble_mesh_srpl_client_cb_param_t *param) Bluetooth Mesh Solicitation PDU RPL Configuration client and server model functions. Solicitation PDU RPL Configuration Client model callback function type - Param event Event type - Param param Pointer to callback parameter - typedef void (*esp_ble_mesh_srpl_server_cb_t)(esp_ble_mesh_srpl_server_cb_event_t event, esp_ble_mesh_srpl_server_cb_param_t *param) Solicitation PDU RPL Configuration Server model callback function type. - Param event Event type - Param param Pointer to callback parameter Enumerations - enum esp_ble_mesh_srpl_client_cb_event_t This enum value is the event of Solicitation PDU RPL Configuration Client model Values: - enumerator ESP_BLE_MESH_SRPL_CLIENT_SEND_COMP_EVT - enumerator ESP_BLE_MESH_SRPL_CLIENT_SEND_TIMEOUT_EVT - enumerator ESP_BLE_MESH_SRPL_CLIENT_RECV_RSP_EVT - enumerator ESP_BLE_MESH_SRPL_CLIENT_RECV_PUB_EVT - enumerator ESP_BLE_MESH_SRPL_CLIENT_EVT_MAX - enumerator ESP_BLE_MESH_SRPL_CLIENT_SEND_COMP_EVT Opcodes Aggregator Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_agg_model_api.h This header file can be included with: #include "esp_ble_mesh_agg_model_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_agg_client_callback(esp_ble_mesh_agg_client_cb_t callback) Register BLE Mesh Opcodes Aggregator Client model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_agg_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_agg_client_msg_t *msg) Set the value of Opcodes Aggregator Server model state with the corresponding set message. - Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Opcodes Aggregator Client message. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_register_agg_server_callback(esp_ble_mesh_agg_server_cb_t callback) Register BLE Mesh Opcodes Aggregator Server model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. Unions - union esp_ble_mesh_agg_client_msg_t - #include <esp_ble_mesh_agg_model_api.h> Opcodes Aggregator Client model message union. Public Members - esp_ble_mesh_agg_sequence_t agg_sequence For ESP_BLE_MESH_MODEL_OP_AGG_SEQUENCE - esp_ble_mesh_agg_sequence_t agg_sequence - union esp_ble_mesh_agg_client_recv_cb_t - #include <esp_ble_mesh_agg_model_api.h> Opcodes Aggregator Client model received message union. Public Members - esp_ble_mesh_agg_status_t agg_status For ESP_BLE_MESH_MODEL_OP_AGG_STATUS - esp_ble_mesh_agg_status_t agg_status - union esp_ble_mesh_agg_server_recv_msg_t - #include <esp_ble_mesh_agg_model_api.h> Opcodes Aggregator Server model related context. Opcodes Aggregator Server model received message union Public Members - esp_ble_mesh_agg_sequence_t agg_sequence For ESP_BLE_MESH_MODEL_OP_AGG_SEQUENCE - esp_ble_mesh_agg_sequence_t agg_sequence Structures - struct esp_ble_mesh_agg_srv_t Opcodes Aggregator Server model context Public Members - esp_ble_mesh_model_t *model Pointer to Opcodes Aggregator Server model - esp_ble_mesh_model_t *model - struct esp_ble_mesh_agg_item_t Parameters of Aggregator Item - struct esp_ble_mesh_agg_sequence_t Parameters of Opcodes Aggregator Sequence - struct esp_ble_mesh_agg_status_t Parameters of Opcodes Aggregator Status - struct esp_ble_mesh_agg_client_send_cb_t Result of sending Opcodes Aggregator Client messages - struct esp_ble_mesh_agg_client_cb_param_t Opcodes Aggregator Client model callback parameters Public Members - esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events - esp_ble_mesh_agg_client_send_cb_t send Result of sending a message - esp_ble_mesh_agg_client_recv_cb_t recv Parameters of received status message - union esp_ble_mesh_agg_client_cb_param_t::[anonymous] [anonymous] Union of AGG Client callback - esp_ble_mesh_client_common_param_t *params - struct esp_ble_mesh_agg_server_cb_param_t Opcodes Aggregator Server model callback parameters Public Members - esp_ble_mesh_model_t *model Pointer to the server model structure - esp_ble_mesh_msg_ctx_t ctx Context of the received message - esp_ble_mesh_agg_server_recv_msg_t recv Received message callback values - union esp_ble_mesh_agg_server_cb_param_t::[anonymous] [anonymous] Union of AGG Server callback - esp_ble_mesh_model_t *model Macros - ESP_BLE_MESH_MODEL_OP_AGG_SEQUENCE Defines the Opcodes Aggregator message opcode. - ESP_BLE_MESH_MODEL_OP_AGG_STATUS - ESP_BLE_MESH_AGG_STATUS_SUCCESS Defines the status codes for Opcodes Aggregator messages. - ESP_BLE_MESH_AGG_STATUS_INVALID_ADDRESS - ESP_BLE_MESH_AGG_STATUS_INVALID_MODEL - ESP_BLE_MESH_AGG_STATUS_WRONG_ACCESS_KEY - ESP_BLE_MESH_AGG_STATUS_WRONG_OPCODE - ESP_BLE_MESH_AGG_STATUS_MSG_NOT_UNDERSTOOD - ESP_BLE_MESH_AGG_ITEM_LENGTH_FORMAT_SHORT Values of the Length_Format - ESP_BLE_MESH_AGG_ITEM_LENGTH_FORMAT_LONG - ESP_BLE_MESH_MODEL_AGG_SRV(srv_data) Define a new Opcodes Aggregator Server model. Note If supported, the Opcodes Aggregator Server model shall be supported by a primary element. - Parameters srv_data -- Pointer to a unique Opcodes Aggregator Server model user_data. - - Returns New Opcodes Aggregator Server model instance. - ESP_BLE_MESH_MODEL_AGG_CLI(cli_data) Define a new Opcodes Aggregator Client model. Note If supported, the model shall be supported by the primary element and shall not be supported by any secondary elements. - Parameters cli_data -- Pointer to a unique Opcodes Aggregator Client model user_data. - - Returns New Opcodes Aggregator Client model instance. Type Definitions - typedef void (*esp_ble_mesh_agg_client_cb_t)(esp_ble_mesh_agg_client_cb_event_t event, esp_ble_mesh_agg_client_cb_param_t *param) Bluetooth Mesh Opcodes Aggregator client and server model functions. Opcodes Aggregator Client model callback function type - Param event Event type - Param param Pointer to callback parameter - typedef void (*esp_ble_mesh_agg_server_cb_t)(esp_ble_mesh_agg_server_cb_event_t event, esp_ble_mesh_agg_server_cb_param_t *param) Opcodes Aggregator Server model callback function type. - Param event Event type - Param param Pointer to callback parameter Enumerations - enum esp_ble_mesh_agg_client_cb_event_t This enum value is the event of Opcodes Aggregator Client model Values: - enumerator ESP_BLE_MESH_AGG_CLIENT_SEND_COMP_EVT - enumerator ESP_BLE_MESH_AGG_CLIENT_SEND_TIMEOUT_EVT - enumerator ESP_BLE_MESH_AGG_CLIENT_RECV_RSP_EVT - enumerator ESP_BLE_MESH_AGG_CLIENT_RECV_PUB_EVT - enumerator ESP_BLE_MESH_AGG_CLIENT_EVT_MAX - enumerator ESP_BLE_MESH_AGG_CLIENT_SEND_COMP_EVT Large Composition Data Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_lcd_model_api.h This header file can be included with: #include "esp_ble_mesh_lcd_model_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_register_lcd_client_callback(esp_ble_mesh_lcd_client_cb_t callback) Register BLE Mesh Large Composition Data Client model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_lcd_client_send(esp_ble_mesh_client_common_param_t *params, esp_ble_mesh_lcd_client_msg_t *msg) Get the value of Large Composition Data Server model state with the corresponding get message. - Parameters params -- [in] Pointer to BLE Mesh common client parameters. msg -- [in] Pointer to Large Composition Data Client message. - - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_register_lcd_server_callback(esp_ble_mesh_lcd_server_cb_t callback) Register BLE Mesh Large Composition Data Server model callback. - Parameters callback -- [in] Pointer to the callback function. - Returns ESP_OK on success or error code otherwise. Unions - union esp_ble_mesh_lcd_client_msg_t - #include <esp_ble_mesh_lcd_model_api.h> Large Composition Data Client model message union. Public Members - esp_ble_mesh_large_comp_data_get_t large_comp_data_get For ESP_BLE_MESH_MODEL_OP_LARGE_COMP_DATA_GET - esp_ble_mesh_models_metadata_get_t models_metadata_get For ESP_BLE_MESH_MODEL_OP_MODELS_METADATA_GET - esp_ble_mesh_large_comp_data_get_t large_comp_data_get - union esp_ble_mesh_lcd_client_recv_cb_t - #include <esp_ble_mesh_lcd_model_api.h> Large Composition Data Client model received message union. Public Members - esp_ble_mesh_large_comp_data_status_t large_comp_data_status For ESP_BLE_MESH_MODEL_OP_LARGE_COMP_DATA_STATUS - esp_ble_mesh_models_metadata_status_t models_metadata_status For ESP_BLE_MESH_MODEL_OP_MODELS_METADATA_STATUS - esp_ble_mesh_large_comp_data_status_t large_comp_data_status - union esp_ble_mesh_lcd_server_state_change_t - #include <esp_ble_mesh_lcd_model_api.h> Large Composition Data Server model related context. Large Composition Data Server model state change value union - union esp_ble_mesh_lcd_server_cb_value_t - #include <esp_ble_mesh_lcd_model_api.h> Large Composition Data Server model callback value union. Public Members - esp_ble_mesh_lcd_server_state_change_t state_change For ESP_BLE_MESH_LCD_SERVER_STATE_CHANGE_EVT - esp_ble_mesh_lcd_server_state_change_t state_change Structures - struct esp_ble_mesh_lcd_srv_t Large Composition Data Server model context Public Members - esp_ble_mesh_model_t *model Pointer to Large Composition Data Server model - esp_ble_mesh_model_t *model - struct esp_ble_mesh_large_comp_data_get_t Parameters of Large Composition Data Get - struct esp_ble_mesh_models_metadata_get_t Parameters of Models Metadata Get - struct esp_ble_mesh_large_comp_data_status_t Parameters of Large Composition Data Status - struct esp_ble_mesh_models_metadata_status_t Parameters of Models Metadata Data Status - struct esp_ble_mesh_lcd_client_send_cb_t Result of sending Large Composition Data Client messages - struct esp_ble_mesh_lcd_client_cb_param_t Large Composition Data Client model callback parameters Public Members - esp_ble_mesh_client_common_param_t *params Client common parameters, used by all events. - esp_ble_mesh_lcd_client_send_cb_t send Result of sending a message - esp_ble_mesh_lcd_client_recv_cb_t recv Parameters of received status message - union esp_ble_mesh_lcd_client_cb_param_t::[anonymous] [anonymous] Union of LCD Client callback - esp_ble_mesh_client_common_param_t *params - struct esp_ble_mesh_lcd_server_cb_param_t Large Composition Data Server model callback parameters Public Members - esp_ble_mesh_model_t *model Pointer to the server model structure - esp_ble_mesh_msg_ctx_t ctx Context of the received message - esp_ble_mesh_lcd_server_cb_value_t value Value of the received configuration messages - esp_ble_mesh_model_t *model Macros - ESP_BLE_MESH_MODEL_OP_LARGE_COMP_DATA_GET - ESP_BLE_MESH_MODEL_OP_LARGE_COMP_DATA_STATUS - ESP_BLE_MESH_MODEL_OP_MODELS_METADATA_GET - ESP_BLE_MESH_MODEL_OP_MODELS_METADATA_STATUS - ESP_BLE_MESH_MODEL_LCD_SRV(srv_data) Define a new Large Composition Data Server model. Note If supported, the model shall be supported by a primary element and shall not be supported by any secondary elements. - Parameters srv_data -- Pointer to a unique Large Composition Data Server model user_data. - - Returns New Large Composition Data Server model instance. - ESP_BLE_MESH_MODEL_LCD_CLI(cli_data) Define a new Large Composition Data Client model. Note If supported, the model shall be supported by the primary element and shall not be supported by any secondary elements. - Parameters cli_data -- Pointer to a unique Large Composition Data Client model user_data. - - Returns New Large Composition Data Client model instance. Type Definitions - typedef void (*esp_ble_mesh_lcd_client_cb_t)(esp_ble_mesh_lcd_client_cb_event_t event, esp_ble_mesh_lcd_client_cb_param_t *param) Large Composition Data client and server model functions. Large Composition Data Client model callback function type - Param event Event type - Param param Pointer to callback parameter - typedef void (*esp_ble_mesh_lcd_server_cb_t)(esp_ble_mesh_lcd_server_cb_event_t event, esp_ble_mesh_lcd_server_cb_param_t *param) Large Composition Data Server model callback function type. - Param event Event type - Param param Pointer to callback parameter Enumerations - enum esp_ble_mesh_lcd_client_cb_event_t This enum value is the event of Large Composition Data Client model Values: - enumerator ESP_BLE_MESH_LCD_CLIENT_SEND_COMP_EVT - enumerator ESP_BLE_MESH_LCD_CLIENT_SEND_TIMEOUT_EVT - enumerator ESP_BLE_MESH_LCD_CLIENT_RECV_RSP_EVT - enumerator ESP_BLE_MESH_LCD_CLIENT_RECV_PUB_EVT - enumerator ESP_BLE_MESH_LCD_CLIENT_EVT_MAX - enumerator ESP_BLE_MESH_LCD_CLIENT_SEND_COMP_EVT Composition and Metadata Header File components/bt/esp_ble_mesh/v1.1/api/core/include/esp_ble_mesh_cm_data_api.h This header file can be included with: #include "esp_ble_mesh_cm_data_api.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_ble_mesh_comp_1_register(const esp_ble_mesh_comp_1_t *comp) Register Composition Data Page 1. - Parameters comp -- [in] Pointer to Composition Data Page 1. - Returns ESP_OK on success or error code otherwise. - esp_err_t esp_ble_mesh_models_metadata_register(const esp_ble_mesh_models_metadata_t *metadata, uint8_t metadata_page) Register Models Metadata Page 0 or 128. - Parameters metadata -- [in] Pointer to Models Metadata Page 0 or 128. metadata_page -- [in] Models Metadata Page number, i.e. 0 or 128. - - Returns ESP_OK on success or error code otherwise. Structures - struct esp_ble_mesh_extended_model_item_t Format of Extended Model Item Public Members - uint8_t element_offset Element address modifier, in the range -4 to 3. See above. - uint8_t model_item_idx Model Index, in the range 0 to 31 Model index, in the range 0 to 255 - int8_t element_offset Element address modifier, in the range -128 to 127 - struct esp_ble_mesh_extended_model_item_t::[anonymous]::[anonymous] long_fmt Extended Model Item long format Extended Model Item long format - union esp_ble_mesh_extended_model_item_t::[anonymous] [anonymous] Union of Extended Model Item - uint8_t element_offset - struct esp_ble_mesh_model_item_t Format of Model Item Public Members - uint8_t corresponding_present Corresponding_Group_ID field indicator - uint8_t format Format of Extended_Model_Items indicator - uint8_t extended_items_count Number of Extended Model Items in the Extended_Model_Items field - uint8_t corresponding_group_id Corresponding group identifier - esp_ble_mesh_extended_model_item_t *const extended_model_items List of Extended Model Items - uint8_t corresponding_present - struct esp_ble_mesh_comp_1_elem_t Format of element of Composition Data Page 1 Public Members - const uint8_t num_s A count of SIG Models Items in this element - const uint8_t num_v A count of Vendor Models Items in this element - esp_ble_mesh_model_item_t *const model_items_s A sequence of "num_s" SIG Model Items - esp_ble_mesh_model_item_t *const model_items_v A sequence of "num_v" Vendor Model Items - const uint8_t num_s - struct esp_ble_mesh_comp_1_t Format of Composition Data Page 1 Public Members - size_t element_count Element count - esp_ble_mesh_comp_1_elem_t *elements A sequence of element descriptions - size_t element_count - struct esp_ble_mesh_metadata_entry_t Format of Metadata entry - struct esp_ble_mesh_metadata_item_t Format of Metadata item Public Members - uint16_t model_id Model ID - uint16_t company_id Company ID - struct esp_ble_mesh_metadata_item_t::[anonymous]::[anonymous] vnd Vendor model identifier Vendor model identifier - union esp_ble_mesh_metadata_item_t::[anonymous] [anonymous] Union of model ID - uint8_t metadata_entries_num Number of metadata entries - esp_ble_mesh_metadata_entry_t *const metadata_entries List of model’s metadata - uint16_t model_id - struct esp_ble_mesh_metadata_elem_t Format of Metadata element of Models Metadata Page 0/128 Public Members - const uint8_t items_num_s Number of metadata items for SIG models in the element - const uint8_t items_num_v Number of metadata items for Vendor models in the element - esp_ble_mesh_metadata_item_t *const metadata_items_s List of metadata items for SIG models in the element - esp_ble_mesh_metadata_item_t *const metadata_items_v List of metadata items for Vendor models in the element - const uint8_t items_num_s - struct esp_ble_mesh_models_metadata_t Format of the Models Metadata Page 0/128 Public Members - size_t element_count Element count - esp_ble_mesh_metadata_elem_t *elements List of metadata for models for each element - size_t element_count Macros - ESP_BLE_MESH_MODEL_ITEM_SHORT < Definitions of the format of Extended_Model_Items indicator - ESP_BLE_MESH_MODEL_ITEM_LONG
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/esp-ble-mesh.html
ESP-IDF Programming Guide v5.2.1 documentation
null
NimBLE-based Host APIs
null
espressif.com
2016-01-01
3a0cd604aef8f560
null
null
NimBLE-based Host APIs Overview Apache MyNewt NimBLE is a highly configurable and Bluetooth® SIG qualifiable Bluetooth Low Energy (Bluetooth LE) stack providing both host and controller functionalities. ESP-IDF supports NimBLE host stack which is specifically ported for ESP32 platform and FreeRTOS. The underlying controller is still the same (as in case of Bluedroid) providing VHCI interface. Refer to NimBLE user guide for a complete list of features and additional information on NimBLE stack. Most features of NimBLE including Bluetooth Low Energy Mesh are supported by ESP-IDF. The porting layer is kept cleaner by maintaining all the existing APIs of NimBLE along with a single ESP-NimBLE API for initialization, making it simpler for the application developers. Architecture Currently, NimBLE host and controller support different transports such as UART and RAM between them. However, RAM transport cannot be used as is in case of ESP as ESP controller supports VHCI interface and buffering schemes used by NimBLE host is incompatible with that used by ESP controller. Therefore, a new transport between NimBLE host and ESP controller has been added. This is depicted in the figure below. This layer is responsible for maintaining pool of transport buffers and formatting buffers exchanges between host and controller as per the requirements. Threading Model The NimBLE host can run inside the application thread or can have its own independent thread. This flexibility is inherently provided by NimBLE design. By default, a thread is spawned by the porting function nimble_port_freertos_init . This behavior can be changed by overriding the same function. For Bluetooth Low Energy Mesh, additional thread (advertising thread) is used which keeps on feeding advertisement events to the main thread. Programming Sequence To begin with, make sure that the NimBLE stack is enabled from menuconfig choose NimBLE for the Bluetooth host. Typical programming sequence with NimBLE stack consists of the following steps: Initialize NVS flash using nvs_flash_init() API. This is because ESP controller uses NVS during initialization. Initialize the host and controller stack using nimble_port_init . Initialize the required NimBLE host configuration parameters and callbacks Perform application specific tasks/initialization Run the thread for host stack using nimble_port_freertos_init Initialize NVS flash using nvs_flash_init() API. This is because ESP controller uses NVS during initialization. Initialize the host and controller stack using nimble_port_init . Initialize the required NimBLE host configuration parameters and callbacks Perform application specific tasks/initialization Run the thread for host stack using nimble_port_freertos_init Initialize NVS flash using nvs_flash_init() API. This is because ESP controller uses NVS during initialization. This documentation does not cover NimBLE APIs. Refer to NimBLE tutorial for more details on the programming sequence/NimBLE APIs for different scenarios. API Reference Header File This header file can be included with: #include "esp_nimble_hci.h" This header file is a part of the API provided by the bt component. To declare that your component depends on bt , add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions esp_err_t esp_nimble_hci_init(void) Initialize VHCI transport layer between NimBLE Host and ESP Bluetooth controller. This function initializes the transport buffers to be exchanged between NimBLE host and ESP controller. It also registers required host callbacks with the controller. Returns ESP_OK if the initialization is successful Appropriate error code from esp_err_t in case of an error ESP_OK if the initialization is successful Appropriate error code from esp_err_t in case of an error ESP_OK if the initialization is successful Returns ESP_OK if the initialization is successful Appropriate error code from esp_err_t in case of an error esp_err_t esp_nimble_hci_deinit(void) Deinitialize VHCI transport layer between NimBLE Host and ESP Bluetooth controller. Note This function should be called after the NimBLE host is deinitialized. Returns ESP_OK if the deinitialization is successful Appropriate error codes from esp_err_t in case of an error ESP_OK if the deinitialization is successful Appropriate error codes from esp_err_t in case of an error ESP_OK if the deinitialization is successful Returns ESP_OK if the deinitialization is successful Appropriate error codes from esp_err_t in case of an error Macros BLE_HCI_UART_H4_NONE BLE_HCI_UART_H4_CMD BLE_HCI_UART_H4_ACL BLE_HCI_UART_H4_SCO BLE_HCI_UART_H4_EVT
NimBLE-based Host APIs Overview Apache MyNewt NimBLE is a highly configurable and Bluetooth® SIG qualifiable Bluetooth Low Energy (Bluetooth LE) stack providing both host and controller functionalities. ESP-IDF supports NimBLE host stack which is specifically ported for ESP32 platform and FreeRTOS. The underlying controller is still the same (as in case of Bluedroid) providing VHCI interface. Refer to NimBLE user guide for a complete list of features and additional information on NimBLE stack. Most features of NimBLE including Bluetooth Low Energy Mesh are supported by ESP-IDF. The porting layer is kept cleaner by maintaining all the existing APIs of NimBLE along with a single ESP-NimBLE API for initialization, making it simpler for the application developers. Architecture Currently, NimBLE host and controller support different transports such as UART and RAM between them. However, RAM transport cannot be used as is in case of ESP as ESP controller supports VHCI interface and buffering schemes used by NimBLE host is incompatible with that used by ESP controller. Therefore, a new transport between NimBLE host and ESP controller has been added. This is depicted in the figure below. This layer is responsible for maintaining pool of transport buffers and formatting buffers exchanges between host and controller as per the requirements. Threading Model The NimBLE host can run inside the application thread or can have its own independent thread. This flexibility is inherently provided by NimBLE design. By default, a thread is spawned by the porting function nimble_port_freertos_init. This behavior can be changed by overriding the same function. For Bluetooth Low Energy Mesh, additional thread (advertising thread) is used which keeps on feeding advertisement events to the main thread. Programming Sequence To begin with, make sure that the NimBLE stack is enabled from menuconfig choose NimBLE for the Bluetooth host. - Typical programming sequence with NimBLE stack consists of the following steps: Initialize NVS flash using nvs_flash_init()API. This is because ESP controller uses NVS during initialization. Initialize the host and controller stack using nimble_port_init. Initialize the required NimBLE host configuration parameters and callbacks Perform application specific tasks/initialization Run the thread for host stack using nimble_port_freertos_init - This documentation does not cover NimBLE APIs. Refer to NimBLE tutorial for more details on the programming sequence/NimBLE APIs for different scenarios. API Reference Header File This header file can be included with: #include "esp_nimble_hci.h" This header file is a part of the API provided by the btcomponent. To declare that your component depends on bt, add the following to your CMakeLists.txt: REQUIRES bt or PRIV_REQUIRES bt Functions - esp_err_t esp_nimble_hci_init(void) Initialize VHCI transport layer between NimBLE Host and ESP Bluetooth controller. This function initializes the transport buffers to be exchanged between NimBLE host and ESP controller. It also registers required host callbacks with the controller. - Returns ESP_OK if the initialization is successful Appropriate error code from esp_err_t in case of an error - - esp_err_t esp_nimble_hci_deinit(void) Deinitialize VHCI transport layer between NimBLE Host and ESP Bluetooth controller. Note This function should be called after the NimBLE host is deinitialized. - Returns ESP_OK if the deinitialization is successful Appropriate error codes from esp_err_t in case of an error - Macros - BLE_HCI_UART_H4_NONE - BLE_HCI_UART_H4_CMD - BLE_HCI_UART_H4_ACL - BLE_HCI_UART_H4_SCO - BLE_HCI_UART_H4_EVT
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/bluetooth/nimble/index.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Error Codes Reference
null
espressif.com
2016-01-01
3c4eca5986848dcc
null
null
Error Codes Reference This section lists various error code constants defined in ESP-IDF. For general information about error codes in ESP-IDF, see Error Handling. ESP_FAIL (-1): Generic esp_err_t code indicating failure ESP_OK (0): esp_err_t value indicating success (no error) ESP_ERR_NO_MEM (0x101): Out of memory ESP_ERR_INVALID_ARG (0x102): Invalid argument ESP_ERR_INVALID_STATE (0x103): Invalid state ESP_ERR_INVALID_SIZE (0x104): Invalid size ESP_ERR_NOT_FOUND (0x105): Requested resource not found ESP_ERR_NOT_SUPPORTED (0x106): Operation or feature not supported ESP_ERR_TIMEOUT (0x107): Operation timed out ESP_ERR_INVALID_RESPONSE (0x108): Received response was invalid ESP_ERR_INVALID_CRC (0x109): CRC or checksum was invalid ESP_ERR_INVALID_VERSION (0x10a): Version was invalid ESP_ERR_INVALID_MAC (0x10b): MAC address was invalid ESP_ERR_NOT_FINISHED (0x10c): Operation has not fully completed ESP_ERR_NOT_ALLOWED (0x10d): Operation is not allowed ESP_ERR_NVS_BASE (0x1100): Starting number of error codes ESP_ERR_NVS_NOT_INITIALIZED (0x1101): The storage driver is not initialized ESP_ERR_NVS_NOT_FOUND (0x1102): A requested entry couldn't be found or namespace doesn’t exist yet and mode is NVS_READONLY ESP_ERR_NVS_TYPE_MISMATCH (0x1103): The type of set or get operation doesn't match the type of value stored in NVS ESP_ERR_NVS_READ_ONLY (0x1104): Storage handle was opened as read only ESP_ERR_NVS_NOT_ENOUGH_SPACE (0x1105): There is not enough space in the underlying storage to save the value ESP_ERR_NVS_INVALID_NAME (0x1106): Namespace name doesn’t satisfy constraints ESP_ERR_NVS_INVALID_HANDLE (0x1107): Handle has been closed or is NULL ESP_ERR_NVS_REMOVE_FAILED (0x1108): The value wasn’t updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn’t fail again. ESP_ERR_NVS_KEY_TOO_LONG (0x1109): Key name is too long ESP_ERR_NVS_PAGE_FULL (0x110a): Internal error; never returned by nvs API functions ESP_ERR_NVS_INVALID_STATE (0x110b): NVS is in an inconsistent state due to a previous error. Call nvs_flash_init and nvs_open again, then retry. ESP_ERR_NVS_INVALID_LENGTH (0x110c): String or blob length is not sufficient to store data ESP_ERR_NVS_NO_FREE_PAGES (0x110d): NVS partition doesn't contain any empty pages. This may happen if NVS partition was truncated. Erase the whole partition and call nvs_flash_init again. ESP_ERR_NVS_VALUE_TOO_LONG (0x110e): Value doesn't fit into the entry or string or blob length is longer than supported by the implementation ESP_ERR_NVS_PART_NOT_FOUND (0x110f): Partition with specified name is not found in the partition table ESP_ERR_NVS_NEW_VERSION_FOUND (0x1110): NVS partition contains data in new format and cannot be recognized by this version of code ESP_ERR_NVS_XTS_ENCR_FAILED (0x1111): XTS encryption failed while writing NVS entry ESP_ERR_NVS_XTS_DECR_FAILED (0x1112): XTS decryption failed while reading NVS entry ESP_ERR_NVS_XTS_CFG_FAILED (0x1113): XTS configuration setting failed ESP_ERR_NVS_XTS_CFG_NOT_FOUND (0x1114): XTS configuration not found ESP_ERR_NVS_ENCR_NOT_SUPPORTED (0x1115): NVS encryption is not supported in this version ESP_ERR_NVS_KEYS_NOT_INITIALIZED (0x1116): NVS key partition is uninitialized ESP_ERR_NVS_CORRUPT_KEY_PART (0x1117): NVS key partition is corrupt ESP_ERR_NVS_CONTENT_DIFFERS (0x1118): Internal error; never returned by nvs API functions. NVS key is different in comparison ESP_ERR_NVS_WRONG_ENCRYPTION (0x1119): NVS partition is marked as encrypted with generic flash encryption. This is forbidden since the NVS encryption works differently. ESP_ERR_ULP_BASE (0x1200): Offset for ULP-related error codes ESP_ERR_ULP_SIZE_TOO_BIG (0x1201): Program doesn't fit into RTC memory reserved for the ULP ESP_ERR_ULP_INVALID_LOAD_ADDR (0x1202): Load address is outside of RTC memory reserved for the ULP ESP_ERR_ULP_DUPLICATE_LABEL (0x1203): More than one label with the same number was defined ESP_ERR_ULP_UNDEFINED_LABEL (0x1204): Branch instructions references an undefined label ESP_ERR_ULP_BRANCH_OUT_OF_RANGE (0x1205): Branch target is out of range of B instruction (try replacing with BX) ESP_ERR_OTA_BASE (0x1500): Base error code for ota_ops api ESP_ERR_OTA_PARTITION_CONFLICT (0x1501): Error if request was to write or erase the current running partition ESP_ERR_OTA_SELECT_INFO_INVALID (0x1502): Error if OTA data partition contains invalid content ESP_ERR_OTA_VALIDATE_FAILED (0x1503): Error if OTA app image is invalid ESP_ERR_OTA_SMALL_SEC_VER (0x1504): Error if the firmware has a secure version less than the running firmware. ESP_ERR_OTA_ROLLBACK_FAILED (0x1505): Error if flash does not have valid firmware in passive partition and hence rollback is not possible ESP_ERR_OTA_ROLLBACK_INVALID_STATE (0x1506): Error if current active firmware is still marked in pending validation state (ESP_OTA_IMG_PENDING_VERIFY), essentially first boot of firmware image post upgrade and hence firmware upgrade is not possible ESP_ERR_EFUSE (0x1600): Base error code for efuse api. ESP_OK_EFUSE_CNT (0x1601): OK the required number of bits is set. ESP_ERR_EFUSE_CNT_IS_FULL (0x1602): Error field is full. ESP_ERR_EFUSE_REPEATED_PROG (0x1603): Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING (0x1604): Error while a encoding operation. ESP_ERR_NOT_ENOUGH_UNUSED_KEY_BLOCKS (0x1605): Error not enough unused key blocks available ESP_ERR_DAMAGED_READING (0x1606): Error. Burn or reset was done during a reading operation leads to damage read data. This error is internal to the efuse component and not returned by any public API. ESP_ERR_IMAGE_BASE (0x2000) ESP_ERR_IMAGE_FLASH_FAIL (0x2001) ESP_ERR_IMAGE_INVALID (0x2002) ESP_ERR_WIFI_BASE (0x3000): Starting number of WiFi error codes ESP_ERR_WIFI_NOT_INIT (0x3001): WiFi driver was not installed by esp_wifi_init ESP_ERR_WIFI_NOT_STARTED (0x3002): WiFi driver was not started by esp_wifi_start ESP_ERR_WIFI_NOT_STOPPED (0x3003): WiFi driver was not stopped by esp_wifi_stop ESP_ERR_WIFI_IF (0x3004): WiFi interface error ESP_ERR_WIFI_MODE (0x3005): WiFi mode error ESP_ERR_WIFI_STATE (0x3006): WiFi internal state error ESP_ERR_WIFI_CONN (0x3007): WiFi internal control block of station or soft-AP error ESP_ERR_WIFI_NVS (0x3008): WiFi internal NVS module error ESP_ERR_WIFI_MAC (0x3009): MAC address is invalid ESP_ERR_WIFI_SSID (0x300a): SSID is invalid ESP_ERR_WIFI_PASSWORD (0x300b): Password is invalid ESP_ERR_WIFI_TIMEOUT (0x300c): Timeout error ESP_ERR_WIFI_WAKE_FAIL (0x300d): WiFi is in sleep state(RF closed) and wakeup fail ESP_ERR_WIFI_WOULD_BLOCK (0x300e): The caller would block ESP_ERR_WIFI_NOT_CONNECT (0x300f): Station still in disconnect status ESP_ERR_WIFI_POST (0x3012): Failed to post the event to WiFi task ESP_ERR_WIFI_INIT_STATE (0x3013): Invalid WiFi state when init/deinit is called ESP_ERR_WIFI_STOP_STATE (0x3014): Returned when WiFi is stopping ESP_ERR_WIFI_NOT_ASSOC (0x3015): The WiFi connection is not associated ESP_ERR_WIFI_TX_DISALLOW (0x3016): The WiFi TX is disallowed ESP_ERR_WIFI_TWT_FULL (0x3017): no available flow id ESP_ERR_WIFI_TWT_SETUP_TIMEOUT (0x3018): Timeout of receiving twt setup response frame, timeout times can be set during twt setup ESP_ERR_WIFI_TWT_SETUP_TXFAIL (0x3019): TWT setup frame tx failed ESP_ERR_WIFI_TWT_SETUP_REJECT (0x301a): The twt setup request was rejected by the AP ESP_ERR_WIFI_DISCARD (0x301b): Discard frame ESP_ERR_WIFI_ROC_IN_PROGRESS (0x301c): ROC op is in progress ESP_ERR_WIFI_REGISTRAR (0x3033): WPS registrar is not supported ESP_ERR_WIFI_WPS_TYPE (0x3034): WPS type error ESP_ERR_WIFI_WPS_SM (0x3035): WPS state machine is not initialized ESP_ERR_ESPNOW_BASE (0x3064): ESPNOW error number base. ESP_ERR_ESPNOW_NOT_INIT (0x3065): ESPNOW is not initialized. ESP_ERR_ESPNOW_ARG (0x3066): Invalid argument ESP_ERR_ESPNOW_NO_MEM (0x3067): Out of memory ESP_ERR_ESPNOW_FULL (0x3068): ESPNOW peer list is full ESP_ERR_ESPNOW_NOT_FOUND (0x3069): ESPNOW peer is not found ESP_ERR_ESPNOW_INTERNAL (0x306a): Internal error ESP_ERR_ESPNOW_EXIST (0x306b): ESPNOW peer has existed ESP_ERR_ESPNOW_IF (0x306c): Interface error ESP_ERR_ESPNOW_CHAN (0x306d): Channel error ESP_ERR_DPP_FAILURE (0x3097): Generic failure during DPP Operation ESP_ERR_DPP_TX_FAILURE (0x3098): DPP Frame Tx failed OR not Acked ESP_ERR_DPP_INVALID_ATTR (0x3099): Encountered invalid DPP Attribute ESP_ERR_DPP_AUTH_TIMEOUT (0x309a): DPP Auth response was not recieved in time ESP_ERR_MESH_BASE (0x4000): Starting number of MESH error codes ESP_ERR_MESH_WIFI_NOT_START (0x4001) ESP_ERR_MESH_NOT_INIT (0x4002) ESP_ERR_MESH_NOT_CONFIG (0x4003) ESP_ERR_MESH_NOT_START (0x4004) ESP_ERR_MESH_NOT_SUPPORT (0x4005) ESP_ERR_MESH_NOT_ALLOWED (0x4006) ESP_ERR_MESH_NO_MEMORY (0x4007) ESP_ERR_MESH_ARGUMENT (0x4008) ESP_ERR_MESH_EXCEED_MTU (0x4009) ESP_ERR_MESH_TIMEOUT (0x400a) ESP_ERR_MESH_DISCONNECTED (0x400b) ESP_ERR_MESH_QUEUE_FAIL (0x400c) ESP_ERR_MESH_QUEUE_FULL (0x400d) ESP_ERR_MESH_NO_PARENT_FOUND (0x400e) ESP_ERR_MESH_NO_ROUTE_FOUND (0x400f) ESP_ERR_MESH_OPTION_NULL (0x4010) ESP_ERR_MESH_OPTION_UNKNOWN (0x4011) ESP_ERR_MESH_XON_NO_WINDOW (0x4012) ESP_ERR_MESH_INTERFACE (0x4013) ESP_ERR_MESH_DISCARD_DUPLICATE (0x4014) ESP_ERR_MESH_DISCARD (0x4015) ESP_ERR_MESH_VOTING (0x4016) ESP_ERR_MESH_XMIT (0x4017) ESP_ERR_MESH_QUEUE_READ (0x4018) ESP_ERR_MESH_PS (0x4019) ESP_ERR_MESH_RECV_RELEASE (0x401a) ESP_ERR_ESP_NETIF_BASE (0x5000) ESP_ERR_ESP_NETIF_INVALID_PARAMS (0x5001) ESP_ERR_ESP_NETIF_IF_NOT_READY (0x5002) ESP_ERR_ESP_NETIF_DHCPC_START_FAILED (0x5003) ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED (0x5004) ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED (0x5005) ESP_ERR_ESP_NETIF_NO_MEM (0x5006) ESP_ERR_ESP_NETIF_DHCP_NOT_STOPPED (0x5007) ESP_ERR_ESP_NETIF_DRIVER_ATTACH_FAILED (0x5008) ESP_ERR_ESP_NETIF_INIT_FAILED (0x5009) ESP_ERR_ESP_NETIF_DNS_NOT_CONFIGURED (0x500a) ESP_ERR_ESP_NETIF_MLD6_FAILED (0x500b) ESP_ERR_ESP_NETIF_IP6_ADDR_FAILED (0x500c) ESP_ERR_ESP_NETIF_DHCPS_START_FAILED (0x500d) ESP_ERR_FLASH_BASE (0x6000): Starting number of flash error codes ESP_ERR_FLASH_OP_FAIL (0x6001) ESP_ERR_FLASH_OP_TIMEOUT (0x6002) ESP_ERR_FLASH_NOT_INITIALISED (0x6003) ESP_ERR_FLASH_UNSUPPORTED_HOST (0x6004) ESP_ERR_FLASH_UNSUPPORTED_CHIP (0x6005) ESP_ERR_FLASH_PROTECTED (0x6006) ESP_ERR_HTTP_BASE (0x7000): Starting number of HTTP error codes ESP_ERR_HTTP_MAX_REDIRECT (0x7001): The error exceeds the number of HTTP redirects ESP_ERR_HTTP_CONNECT (0x7002): Error open the HTTP connection ESP_ERR_HTTP_WRITE_DATA (0x7003): Error write HTTP data ESP_ERR_HTTP_FETCH_HEADER (0x7004): Error read HTTP header from server ESP_ERR_HTTP_INVALID_TRANSPORT (0x7005): There are no transport support for the input scheme ESP_ERR_HTTP_CONNECTING (0x7006): HTTP connection hasn't been established yet ESP_ERR_HTTP_EAGAIN (0x7007): Mapping of errno EAGAIN to esp_err_t ESP_ERR_HTTP_CONNECTION_CLOSED (0x7008): Read FIN from peer and the connection closed ESP_ERR_ESP_TLS_BASE (0x8000): Starting number of ESP-TLS error codes ESP_ERR_ESP_TLS_CANNOT_RESOLVE_HOSTNAME (0x8001): Error if hostname couldn't be resolved upon tls connection ESP_ERR_ESP_TLS_CANNOT_CREATE_SOCKET (0x8002): Failed to create socket ESP_ERR_ESP_TLS_UNSUPPORTED_PROTOCOL_FAMILY (0x8003): Unsupported protocol family ESP_ERR_ESP_TLS_FAILED_CONNECT_TO_HOST (0x8004): Failed to connect to host ESP_ERR_ESP_TLS_SOCKET_SETOPT_FAILED (0x8005): failed to set/get socket option ESP_ERR_ESP_TLS_CONNECTION_TIMEOUT (0x8006): new connection in esp_tls_low_level_conn connection timeouted ESP_ERR_ESP_TLS_SE_FAILED (0x8007) ESP_ERR_ESP_TLS_TCP_CLOSED_FIN (0x8008) ESP_ERR_MBEDTLS_CERT_PARTLY_OK (0x8010): mbedtls parse certificates was partly successful ESP_ERR_MBEDTLS_CTR_DRBG_SEED_FAILED (0x8011): mbedtls api returned error ESP_ERR_MBEDTLS_SSL_SET_HOSTNAME_FAILED (0x8012): mbedtls api returned error ESP_ERR_MBEDTLS_SSL_CONFIG_DEFAULTS_FAILED (0x8013): mbedtls api returned error ESP_ERR_MBEDTLS_SSL_CONF_ALPN_PROTOCOLS_FAILED (0x8014): mbedtls api returned error ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED (0x8015): mbedtls api returned error ESP_ERR_MBEDTLS_SSL_CONF_OWN_CERT_FAILED (0x8016): mbedtls api returned error ESP_ERR_MBEDTLS_SSL_SETUP_FAILED (0x8017): mbedtls api returned error ESP_ERR_MBEDTLS_SSL_WRITE_FAILED (0x8018): mbedtls api returned error ESP_ERR_MBEDTLS_PK_PARSE_KEY_FAILED (0x8019): mbedtls api returned failed ESP_ERR_MBEDTLS_SSL_HANDSHAKE_FAILED (0x801a): mbedtls api returned failed ESP_ERR_MBEDTLS_SSL_CONF_PSK_FAILED (0x801b): mbedtls api returned failed ESP_ERR_MBEDTLS_SSL_TICKET_SETUP_FAILED (0x801c): mbedtls api returned failed ESP_ERR_WOLFSSL_SSL_SET_HOSTNAME_FAILED (0x8031): wolfSSL api returned error ESP_ERR_WOLFSSL_SSL_CONF_ALPN_PROTOCOLS_FAILED (0x8032): wolfSSL api returned error ESP_ERR_WOLFSSL_CERT_VERIFY_SETUP_FAILED (0x8033): wolfSSL api returned error ESP_ERR_WOLFSSL_KEY_VERIFY_SETUP_FAILED (0x8034): wolfSSL api returned error ESP_ERR_WOLFSSL_SSL_HANDSHAKE_FAILED (0x8035): wolfSSL api returned failed ESP_ERR_WOLFSSL_CTX_SETUP_FAILED (0x8036): wolfSSL api returned failed ESP_ERR_WOLFSSL_SSL_SETUP_FAILED (0x8037): wolfSSL api returned failed ESP_ERR_WOLFSSL_SSL_WRITE_FAILED (0x8038): wolfSSL api returned failed ESP_ERR_HTTPS_OTA_BASE (0x9000) ESP_ERR_HTTPS_OTA_IN_PROGRESS (0x9001) ESP_ERR_PING_BASE (0xa000) ESP_ERR_PING_INVALID_PARAMS (0xa001) ESP_ERR_PING_NO_MEM (0xa002) ESP_ERR_HTTPD_BASE (0xb000): Starting number of HTTPD error codes ESP_ERR_HTTPD_HANDLERS_FULL (0xb001): All slots for registering URI handlers have been consumed ESP_ERR_HTTPD_HANDLER_EXISTS (0xb002): URI handler with same method and target URI already registered ESP_ERR_HTTPD_INVALID_REQ (0xb003): Invalid request pointer ESP_ERR_HTTPD_RESULT_TRUNC (0xb004): Result string truncated ESP_ERR_HTTPD_RESP_HDR (0xb005): Response header field larger than supported ESP_ERR_HTTPD_RESP_SEND (0xb006): Error occured while sending response packet ESP_ERR_HTTPD_ALLOC_MEM (0xb007): Failed to dynamically allocate memory for resource ESP_ERR_HTTPD_TASK (0xb008): Failed to launch server task/thread ESP_ERR_HW_CRYPTO_BASE (0xc000): Starting number of HW cryptography module error codes ESP_ERR_HW_CRYPTO_DS_HMAC_FAIL (0xc001): HMAC peripheral problem ESP_ERR_HW_CRYPTO_DS_INVALID_KEY (0xc002) ESP_ERR_HW_CRYPTO_DS_INVALID_DIGEST (0xc004) ESP_ERR_HW_CRYPTO_DS_INVALID_PADDING (0xc005) ESP_ERR_MEMPROT_BASE (0xd000): Starting number of Memory Protection API error codes ESP_ERR_MEMPROT_MEMORY_TYPE_INVALID (0xd001) ESP_ERR_MEMPROT_SPLIT_ADDR_INVALID (0xd002) ESP_ERR_MEMPROT_SPLIT_ADDR_OUT_OF_RANGE (0xd003) ESP_ERR_MEMPROT_SPLIT_ADDR_UNALIGNED (0xd004) ESP_ERR_MEMPROT_UNIMGMT_BLOCK_INVALID (0xd005) ESP_ERR_MEMPROT_WORLD_INVALID (0xd006) ESP_ERR_MEMPROT_AREA_INVALID (0xd007) ESP_ERR_MEMPROT_CPUID_INVALID (0xd008) ESP_ERR_TCP_TRANSPORT_BASE (0xe000): Starting number of TCP Transport error codes ESP_ERR_TCP_TRANSPORT_CONNECTION_TIMEOUT (0xe001): Connection has timed out ESP_ERR_TCP_TRANSPORT_CONNECTION_CLOSED_BY_FIN (0xe002): Read FIN from peer and the connection has closed (in a clean way) ESP_ERR_TCP_TRANSPORT_CONNECTION_FAILED (0xe003): Failed to connect to the peer ESP_ERR_TCP_TRANSPORT_NO_MEM (0xe004): Memory allocation failed ESP_ERR_NVS_SEC_BASE (0xf000): Starting number of error codes ESP_ERR_NVS_SEC_HMAC_KEY_NOT_FOUND (0xf001): HMAC Key required to generate the NVS encryption keys not found ESP_ERR_NVS_SEC_HMAC_KEY_BLK_ALREADY_USED (0xf002): Provided eFuse block for HMAC key generation is already in use ESP_ERR_NVS_SEC_HMAC_KEY_GENERATION_FAILED (0xf003): Failed to generate/write the HMAC key to eFuse ESP_ERR_NVS_SEC_HMAC_XTS_KEYS_DERIV_FAILED (0xf004): Failed to derive the NVS encryption keys based on the HMAC-based scheme
Error Codes Reference This section lists various error code constants defined in ESP-IDF. For general information about error codes in ESP-IDF, see Error Handling. ESP_FAIL (-1): Generic esp_err_t code indicating failure ESP_OK (0): esp_err_t value indicating success (no error) ESP_ERR_NO_MEM (0x101): Out of memory ESP_ERR_INVALID_ARG (0x102): Invalid argument ESP_ERR_INVALID_STATE (0x103): Invalid state ESP_ERR_INVALID_SIZE (0x104): Invalid size ESP_ERR_NOT_FOUND (0x105): Requested resource not found ESP_ERR_NOT_SUPPORTED (0x106): Operation or feature not supported ESP_ERR_TIMEOUT (0x107): Operation timed out ESP_ERR_INVALID_RESPONSE (0x108): Received response was invalid ESP_ERR_INVALID_CRC (0x109): CRC or checksum was invalid ESP_ERR_INVALID_VERSION (0x10a): Version was invalid ESP_ERR_INVALID_MAC (0x10b): MAC address was invalid ESP_ERR_NOT_FINISHED (0x10c): Operation has not fully completed ESP_ERR_NOT_ALLOWED (0x10d): Operation is not allowed ESP_ERR_NVS_BASE (0x1100): Starting number of error codes ESP_ERR_NVS_NOT_INITIALIZED (0x1101): The storage driver is not initialized ESP_ERR_NVS_NOT_FOUND (0x1102): A requested entry couldn't be found or namespace doesn’t exist yet and mode is NVS_READONLY ESP_ERR_NVS_TYPE_MISMATCH (0x1103): The type of set or get operation doesn't match the type of value stored in NVS ESP_ERR_NVS_READ_ONLY (0x1104): Storage handle was opened as read only ESP_ERR_NVS_NOT_ENOUGH_SPACE (0x1105): There is not enough space in the underlying storage to save the value ESP_ERR_NVS_INVALID_NAME (0x1106): Namespace name doesn’t satisfy constraints ESP_ERR_NVS_INVALID_HANDLE (0x1107): Handle has been closed or is NULL ESP_ERR_NVS_REMOVE_FAILED (0x1108): The value wasn’t updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn’t fail again. ESP_ERR_NVS_KEY_TOO_LONG (0x1109): Key name is too long ESP_ERR_NVS_PAGE_FULL (0x110a): Internal error; never returned by nvs API functions ESP_ERR_NVS_INVALID_STATE (0x110b): NVS is in an inconsistent state due to a previous error. Call nvs_flash_init and nvs_open again, then retry. ESP_ERR_NVS_INVALID_LENGTH (0x110c): String or blob length is not sufficient to store data ESP_ERR_NVS_NO_FREE_PAGES (0x110d): NVS partition doesn't contain any empty pages. This may happen if NVS partition was truncated. Erase the whole partition and call nvs_flash_init again. ESP_ERR_NVS_VALUE_TOO_LONG (0x110e): Value doesn't fit into the entry or string or blob length is longer than supported by the implementation ESP_ERR_NVS_PART_NOT_FOUND (0x110f): Partition with specified name is not found in the partition table ESP_ERR_NVS_NEW_VERSION_FOUND (0x1110): NVS partition contains data in new format and cannot be recognized by this version of code ESP_ERR_NVS_XTS_ENCR_FAILED (0x1111): XTS encryption failed while writing NVS entry ESP_ERR_NVS_XTS_DECR_FAILED (0x1112): XTS decryption failed while reading NVS entry ESP_ERR_NVS_XTS_CFG_FAILED (0x1113): XTS configuration setting failed ESP_ERR_NVS_XTS_CFG_NOT_FOUND (0x1114): XTS configuration not found ESP_ERR_NVS_ENCR_NOT_SUPPORTED (0x1115): NVS encryption is not supported in this version ESP_ERR_NVS_KEYS_NOT_INITIALIZED (0x1116): NVS key partition is uninitialized ESP_ERR_NVS_CORRUPT_KEY_PART (0x1117): NVS key partition is corrupt ESP_ERR_NVS_CONTENT_DIFFERS (0x1118): Internal error; never returned by nvs API functions. NVS key is different in comparison ESP_ERR_NVS_WRONG_ENCRYPTION (0x1119): NVS partition is marked as encrypted with generic flash encryption. This is forbidden since the NVS encryption works differently. ESP_ERR_ULP_BASE (0x1200): Offset for ULP-related error codes ESP_ERR_ULP_SIZE_TOO_BIG (0x1201): Program doesn't fit into RTC memory reserved for the ULP ESP_ERR_ULP_INVALID_LOAD_ADDR (0x1202): Load address is outside of RTC memory reserved for the ULP ESP_ERR_ULP_DUPLICATE_LABEL (0x1203): More than one label with the same number was defined ESP_ERR_ULP_UNDEFINED_LABEL (0x1204): Branch instructions references an undefined label ESP_ERR_ULP_BRANCH_OUT_OF_RANGE (0x1205): Branch target is out of range of B instruction (try replacing with BX) ESP_ERR_OTA_BASE (0x1500): Base error code for ota_ops api ESP_ERR_OTA_PARTITION_CONFLICT (0x1501): Error if request was to write or erase the current running partition ESP_ERR_OTA_SELECT_INFO_INVALID (0x1502): Error if OTA data partition contains invalid content ESP_ERR_OTA_VALIDATE_FAILED (0x1503): Error if OTA app image is invalid ESP_ERR_OTA_SMALL_SEC_VER (0x1504): Error if the firmware has a secure version less than the running firmware. ESP_ERR_OTA_ROLLBACK_FAILED (0x1505): Error if flash does not have valid firmware in passive partition and hence rollback is not possible ESP_ERR_OTA_ROLLBACK_INVALID_STATE (0x1506): Error if current active firmware is still marked in pending validation state (ESP_OTA_IMG_PENDING_VERIFY), essentially first boot of firmware image post upgrade and hence firmware upgrade is not possible ESP_ERR_EFUSE (0x1600): Base error code for efuse api. ESP_OK_EFUSE_CNT (0x1601): OK the required number of bits is set. ESP_ERR_EFUSE_CNT_IS_FULL (0x1602): Error field is full. ESP_ERR_EFUSE_REPEATED_PROG (0x1603): Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING (0x1604): Error while a encoding operation. ESP_ERR_NOT_ENOUGH_UNUSED_KEY_BLOCKS (0x1605): Error not enough unused key blocks available ESP_ERR_DAMAGED_READING (0x1606): Error. Burn or reset was done during a reading operation leads to damage read data. This error is internal to the efuse component and not returned by any public API. ESP_ERR_IMAGE_BASE (0x2000) ESP_ERR_IMAGE_FLASH_FAIL (0x2001) ESP_ERR_IMAGE_INVALID (0x2002) ESP_ERR_WIFI_BASE (0x3000): Starting number of WiFi error codes ESP_ERR_WIFI_NOT_INIT (0x3001): WiFi driver was not installed by esp_wifi_init ESP_ERR_WIFI_NOT_STARTED (0x3002): WiFi driver was not started by esp_wifi_start ESP_ERR_WIFI_NOT_STOPPED (0x3003): WiFi driver was not stopped by esp_wifi_stop ESP_ERR_WIFI_IF (0x3004): WiFi interface error ESP_ERR_WIFI_MODE (0x3005): WiFi mode error ESP_ERR_WIFI_STATE (0x3006): WiFi internal state error ESP_ERR_WIFI_CONN (0x3007): WiFi internal control block of station or soft-AP error ESP_ERR_WIFI_NVS (0x3008): WiFi internal NVS module error ESP_ERR_WIFI_MAC (0x3009): MAC address is invalid ESP_ERR_WIFI_SSID (0x300a): SSID is invalid ESP_ERR_WIFI_PASSWORD (0x300b): Password is invalid ESP_ERR_WIFI_TIMEOUT (0x300c): Timeout error ESP_ERR_WIFI_WAKE_FAIL (0x300d): WiFi is in sleep state(RF closed) and wakeup fail ESP_ERR_WIFI_WOULD_BLOCK (0x300e): The caller would block ESP_ERR_WIFI_NOT_CONNECT (0x300f): Station still in disconnect status ESP_ERR_WIFI_POST (0x3012): Failed to post the event to WiFi task ESP_ERR_WIFI_INIT_STATE (0x3013): Invalid WiFi state when init/deinit is called ESP_ERR_WIFI_STOP_STATE (0x3014): Returned when WiFi is stopping ESP_ERR_WIFI_NOT_ASSOC (0x3015): The WiFi connection is not associated ESP_ERR_WIFI_TX_DISALLOW (0x3016): The WiFi TX is disallowed ESP_ERR_WIFI_TWT_FULL (0x3017): no available flow id ESP_ERR_WIFI_TWT_SETUP_TIMEOUT (0x3018): Timeout of receiving twt setup response frame, timeout times can be set during twt setup ESP_ERR_WIFI_TWT_SETUP_TXFAIL (0x3019): TWT setup frame tx failed ESP_ERR_WIFI_TWT_SETUP_REJECT (0x301a): The twt setup request was rejected by the AP ESP_ERR_WIFI_DISCARD (0x301b): Discard frame ESP_ERR_WIFI_ROC_IN_PROGRESS (0x301c): ROC op is in progress ESP_ERR_WIFI_REGISTRAR (0x3033): WPS registrar is not supported ESP_ERR_WIFI_WPS_TYPE (0x3034): WPS type error ESP_ERR_WIFI_WPS_SM (0x3035): WPS state machine is not initialized ESP_ERR_ESPNOW_BASE (0x3064): ESPNOW error number base. ESP_ERR_ESPNOW_NOT_INIT (0x3065): ESPNOW is not initialized. ESP_ERR_ESPNOW_ARG (0x3066): Invalid argument ESP_ERR_ESPNOW_NO_MEM (0x3067): Out of memory ESP_ERR_ESPNOW_FULL (0x3068): ESPNOW peer list is full ESP_ERR_ESPNOW_NOT_FOUND (0x3069): ESPNOW peer is not found ESP_ERR_ESPNOW_INTERNAL (0x306a): Internal error ESP_ERR_ESPNOW_EXIST (0x306b): ESPNOW peer has existed ESP_ERR_ESPNOW_IF (0x306c): Interface error ESP_ERR_ESPNOW_CHAN (0x306d): Channel error ESP_ERR_DPP_FAILURE (0x3097): Generic failure during DPP Operation ESP_ERR_DPP_TX_FAILURE (0x3098): DPP Frame Tx failed OR not Acked ESP_ERR_DPP_INVALID_ATTR (0x3099): Encountered invalid DPP Attribute ESP_ERR_DPP_AUTH_TIMEOUT (0x309a): DPP Auth response was not recieved in time ESP_ERR_MESH_BASE (0x4000): Starting number of MESH error codes ESP_ERR_MESH_WIFI_NOT_START (0x4001) ESP_ERR_MESH_NOT_INIT (0x4002) ESP_ERR_MESH_NOT_CONFIG (0x4003) ESP_ERR_MESH_NOT_START (0x4004) ESP_ERR_MESH_NOT_SUPPORT (0x4005) ESP_ERR_MESH_NOT_ALLOWED (0x4006) ESP_ERR_MESH_NO_MEMORY (0x4007) ESP_ERR_MESH_ARGUMENT (0x4008) ESP_ERR_MESH_EXCEED_MTU (0x4009) ESP_ERR_MESH_TIMEOUT (0x400a) ESP_ERR_MESH_DISCONNECTED (0x400b) ESP_ERR_MESH_QUEUE_FAIL (0x400c) ESP_ERR_MESH_QUEUE_FULL (0x400d) ESP_ERR_MESH_NO_PARENT_FOUND (0x400e) ESP_ERR_MESH_NO_ROUTE_FOUND (0x400f) ESP_ERR_MESH_OPTION_NULL (0x4010) ESP_ERR_MESH_OPTION_UNKNOWN (0x4011) ESP_ERR_MESH_XON_NO_WINDOW (0x4012) ESP_ERR_MESH_INTERFACE (0x4013) ESP_ERR_MESH_DISCARD_DUPLICATE (0x4014) ESP_ERR_MESH_DISCARD (0x4015) ESP_ERR_MESH_VOTING (0x4016) ESP_ERR_MESH_XMIT (0x4017) ESP_ERR_MESH_QUEUE_READ (0x4018) ESP_ERR_MESH_PS (0x4019) ESP_ERR_MESH_RECV_RELEASE (0x401a) ESP_ERR_ESP_NETIF_BASE (0x5000) ESP_ERR_ESP_NETIF_INVALID_PARAMS (0x5001) ESP_ERR_ESP_NETIF_IF_NOT_READY (0x5002) ESP_ERR_ESP_NETIF_DHCPC_START_FAILED (0x5003) ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED (0x5004) ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED (0x5005) ESP_ERR_ESP_NETIF_NO_MEM (0x5006) ESP_ERR_ESP_NETIF_DHCP_NOT_STOPPED (0x5007) ESP_ERR_ESP_NETIF_DRIVER_ATTACH_FAILED (0x5008) ESP_ERR_ESP_NETIF_INIT_FAILED (0x5009) ESP_ERR_ESP_NETIF_DNS_NOT_CONFIGURED (0x500a) ESP_ERR_ESP_NETIF_MLD6_FAILED (0x500b) ESP_ERR_ESP_NETIF_IP6_ADDR_FAILED (0x500c) ESP_ERR_ESP_NETIF_DHCPS_START_FAILED (0x500d) ESP_ERR_FLASH_BASE (0x6000): Starting number of flash error codes ESP_ERR_FLASH_OP_FAIL (0x6001) ESP_ERR_FLASH_OP_TIMEOUT (0x6002) ESP_ERR_FLASH_NOT_INITIALISED (0x6003) ESP_ERR_FLASH_UNSUPPORTED_HOST (0x6004) ESP_ERR_FLASH_UNSUPPORTED_CHIP (0x6005) ESP_ERR_FLASH_PROTECTED (0x6006) ESP_ERR_HTTP_BASE (0x7000): Starting number of HTTP error codes ESP_ERR_HTTP_MAX_REDIRECT (0x7001): The error exceeds the number of HTTP redirects ESP_ERR_HTTP_CONNECT (0x7002): Error open the HTTP connection ESP_ERR_HTTP_WRITE_DATA (0x7003): Error write HTTP data ESP_ERR_HTTP_FETCH_HEADER (0x7004): Error read HTTP header from server ESP_ERR_HTTP_INVALID_TRANSPORT (0x7005): There are no transport support for the input scheme ESP_ERR_HTTP_CONNECTING (0x7006): HTTP connection hasn't been established yet ESP_ERR_HTTP_EAGAIN (0x7007): Mapping of errno EAGAIN to esp_err_t ESP_ERR_HTTP_CONNECTION_CLOSED (0x7008): Read FIN from peer and the connection closed ESP_ERR_ESP_TLS_BASE (0x8000): Starting number of ESP-TLS error codes ESP_ERR_ESP_TLS_CANNOT_RESOLVE_HOSTNAME (0x8001): Error if hostname couldn't be resolved upon tls connection ESP_ERR_ESP_TLS_CANNOT_CREATE_SOCKET (0x8002): Failed to create socket ESP_ERR_ESP_TLS_UNSUPPORTED_PROTOCOL_FAMILY (0x8003): Unsupported protocol family ESP_ERR_ESP_TLS_FAILED_CONNECT_TO_HOST (0x8004): Failed to connect to host ESP_ERR_ESP_TLS_SOCKET_SETOPT_FAILED (0x8005): failed to set/get socket option ESP_ERR_ESP_TLS_CONNECTION_TIMEOUT (0x8006): new connection in esp_tls_low_level_conn connection timeouted ESP_ERR_ESP_TLS_SE_FAILED (0x8007) ESP_ERR_ESP_TLS_TCP_CLOSED_FIN (0x8008) ESP_ERR_MBEDTLS_CERT_PARTLY_OK (0x8010): mbedtls parse certificates was partly successful ESP_ERR_MBEDTLS_CTR_DRBG_SEED_FAILED (0x8011): mbedtls api returned error ESP_ERR_MBEDTLS_SSL_SET_HOSTNAME_FAILED (0x8012): mbedtls api returned error ESP_ERR_MBEDTLS_SSL_CONFIG_DEFAULTS_FAILED (0x8013): mbedtls api returned error ESP_ERR_MBEDTLS_SSL_CONF_ALPN_PROTOCOLS_FAILED (0x8014): mbedtls api returned error ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED (0x8015): mbedtls api returned error ESP_ERR_MBEDTLS_SSL_CONF_OWN_CERT_FAILED (0x8016): mbedtls api returned error ESP_ERR_MBEDTLS_SSL_SETUP_FAILED (0x8017): mbedtls api returned error ESP_ERR_MBEDTLS_SSL_WRITE_FAILED (0x8018): mbedtls api returned error ESP_ERR_MBEDTLS_PK_PARSE_KEY_FAILED (0x8019): mbedtls api returned failed ESP_ERR_MBEDTLS_SSL_HANDSHAKE_FAILED (0x801a): mbedtls api returned failed ESP_ERR_MBEDTLS_SSL_CONF_PSK_FAILED (0x801b): mbedtls api returned failed ESP_ERR_MBEDTLS_SSL_TICKET_SETUP_FAILED (0x801c): mbedtls api returned failed ESP_ERR_WOLFSSL_SSL_SET_HOSTNAME_FAILED (0x8031): wolfSSL api returned error ESP_ERR_WOLFSSL_SSL_CONF_ALPN_PROTOCOLS_FAILED (0x8032): wolfSSL api returned error ESP_ERR_WOLFSSL_CERT_VERIFY_SETUP_FAILED (0x8033): wolfSSL api returned error ESP_ERR_WOLFSSL_KEY_VERIFY_SETUP_FAILED (0x8034): wolfSSL api returned error ESP_ERR_WOLFSSL_SSL_HANDSHAKE_FAILED (0x8035): wolfSSL api returned failed ESP_ERR_WOLFSSL_CTX_SETUP_FAILED (0x8036): wolfSSL api returned failed ESP_ERR_WOLFSSL_SSL_SETUP_FAILED (0x8037): wolfSSL api returned failed ESP_ERR_WOLFSSL_SSL_WRITE_FAILED (0x8038): wolfSSL api returned failed ESP_ERR_HTTPS_OTA_BASE (0x9000) ESP_ERR_HTTPS_OTA_IN_PROGRESS (0x9001) ESP_ERR_PING_BASE (0xa000) ESP_ERR_PING_INVALID_PARAMS (0xa001) ESP_ERR_PING_NO_MEM (0xa002) ESP_ERR_HTTPD_BASE (0xb000): Starting number of HTTPD error codes ESP_ERR_HTTPD_HANDLERS_FULL (0xb001): All slots for registering URI handlers have been consumed ESP_ERR_HTTPD_HANDLER_EXISTS (0xb002): URI handler with same method and target URI already registered ESP_ERR_HTTPD_INVALID_REQ (0xb003): Invalid request pointer ESP_ERR_HTTPD_RESULT_TRUNC (0xb004): Result string truncated ESP_ERR_HTTPD_RESP_HDR (0xb005): Response header field larger than supported ESP_ERR_HTTPD_RESP_SEND (0xb006): Error occured while sending response packet ESP_ERR_HTTPD_ALLOC_MEM (0xb007): Failed to dynamically allocate memory for resource ESP_ERR_HTTPD_TASK (0xb008): Failed to launch server task/thread ESP_ERR_HW_CRYPTO_BASE (0xc000): Starting number of HW cryptography module error codes ESP_ERR_HW_CRYPTO_DS_HMAC_FAIL (0xc001): HMAC peripheral problem ESP_ERR_HW_CRYPTO_DS_INVALID_KEY (0xc002) ESP_ERR_HW_CRYPTO_DS_INVALID_DIGEST (0xc004) ESP_ERR_HW_CRYPTO_DS_INVALID_PADDING (0xc005) ESP_ERR_MEMPROT_BASE (0xd000): Starting number of Memory Protection API error codes ESP_ERR_MEMPROT_MEMORY_TYPE_INVALID (0xd001) ESP_ERR_MEMPROT_SPLIT_ADDR_INVALID (0xd002) ESP_ERR_MEMPROT_SPLIT_ADDR_OUT_OF_RANGE (0xd003) ESP_ERR_MEMPROT_SPLIT_ADDR_UNALIGNED (0xd004) ESP_ERR_MEMPROT_UNIMGMT_BLOCK_INVALID (0xd005) ESP_ERR_MEMPROT_WORLD_INVALID (0xd006) ESP_ERR_MEMPROT_AREA_INVALID (0xd007) ESP_ERR_MEMPROT_CPUID_INVALID (0xd008) ESP_ERR_TCP_TRANSPORT_BASE (0xe000): Starting number of TCP Transport error codes ESP_ERR_TCP_TRANSPORT_CONNECTION_TIMEOUT (0xe001): Connection has timed out ESP_ERR_TCP_TRANSPORT_CONNECTION_CLOSED_BY_FIN (0xe002): Read FIN from peer and the connection has closed (in a clean way) ESP_ERR_TCP_TRANSPORT_CONNECTION_FAILED (0xe003): Failed to connect to the peer ESP_ERR_TCP_TRANSPORT_NO_MEM (0xe004): Memory allocation failed ESP_ERR_NVS_SEC_BASE (0xf000): Starting number of error codes ESP_ERR_NVS_SEC_HMAC_KEY_NOT_FOUND (0xf001): HMAC Key required to generate the NVS encryption keys not found ESP_ERR_NVS_SEC_HMAC_KEY_BLK_ALREADY_USED (0xf002): Provided eFuse block for HMAC key generation is already in use ESP_ERR_NVS_SEC_HMAC_KEY_GENERATION_FAILED (0xf003): Failed to generate/write the HMAC key to eFuse ESP_ERR_NVS_SEC_HMAC_XTS_KEYS_DERIV_FAILED (0xf004): Failed to derive the NVS encryption keys based on the HMAC-based scheme
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/error-codes.html
ESP-IDF Programming Guide v5.2.1 documentation
null
ESP-NOW
null
espressif.com
2016-01-01
82a5fac4c32e935b
null
null
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: ------------------------------------------------------------------------------------------------------------ | 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. 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: ------------------------------------------------------------------------------- | 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. 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. PMK is used to encrypt LMK with the AES-128 algorithm. Call esp_now_set_pmk() to set PMK. If PMK is not set, a default PMK will be used. LMK of the paired device is used to encrypt the vendor-specific action frame with the CCMP method. The maximum number of different LMKs is six. If the LMK of the paired device is not set, the vendor-specific action frame will not be encrypted. Encrypting multicast vendor-specific action frame is not supported. Initialization and Deinitialization Call esp_now_init() to initialize ESP-NOW and 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 esp_now_deinit() is called, all of the information of paired devices are deleted. Add Paired Device Call 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. 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 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. 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 esp_now_send() to send ESP-NOW data and 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. If there is a lot of ESP-NOW data to send, call 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 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 Call 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 esp_wifi_start() . Config ESP-NOW Power-saving Parameter Sleep is supported only when ESP32 is configured as station. Call 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 esp_wifi_connectionless_module_set_wake_interval() to configure Interval as well. Please refer to connectionless module power save to get more detail. Application Examples Example of sending and receiving ESP-NOW data between two devices: wifi/espnow. For more application examples of how to use ESP-NOW, please visit ESP-NOW repository. API Reference Header File This header file can be included with: #include "esp_now.h" This header file is a part of the API provided by the esp_wifi component. To declare that your component depends on esp_wifi , add the following to your CMakeLists.txt: REQUIRES esp_wifi or PRIV_REQUIRES esp_wifi Functions esp_err_t esp_now_init(void) Initialize ESPNOW function. Returns ESP_OK : succeed ESP_ERR_ESPNOW_INTERNAL : Internal error ESP_OK : succeed ESP_ERR_ESPNOW_INTERNAL : Internal error ESP_OK : succeed Returns ESP_OK : succeed ESP_ERR_ESPNOW_INTERNAL : Internal error esp_err_t esp_now_get_version(uint32_t *version) Get the version of ESPNOW. Parameters version -- ESPNOW version Returns ESP_OK : succeed ESP_ERR_ESPNOW_ARG : invalid argument ESP_OK : succeed ESP_ERR_ESPNOW_ARG : invalid argument ESP_OK : succeed Parameters version -- ESPNOW version Returns ESP_OK : succeed ESP_ERR_ESPNOW_ARG : invalid argument esp_err_t esp_now_register_recv_cb(esp_now_recv_cb_t cb) Register callback function of receiving ESPNOW data. Parameters cb -- callback function of receiving ESPNOW data Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_INTERNAL : internal error ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_INTERNAL : internal error ESP_OK : succeed Parameters cb -- callback function of receiving ESPNOW data Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_INTERNAL : internal error esp_err_t esp_now_unregister_recv_cb(void) Unregister callback function of receiving ESPNOW data. Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_OK : succeed Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized esp_err_t esp_now_register_send_cb(esp_now_send_cb_t cb) Register callback function of sending ESPNOW data. Parameters cb -- callback function of sending ESPNOW data Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_INTERNAL : internal error ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_INTERNAL : internal error ESP_OK : succeed Parameters cb -- callback function of sending ESPNOW data Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_INTERNAL : internal error esp_err_t esp_now_unregister_send_cb(void) Unregister callback function of sending ESPNOW data. Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_OK : succeed Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized esp_err_t esp_now_send(const uint8_t *peer_addr, const uint8_t *data, size_t len) Send ESPNOW data. Attention 1. If peer_addr is not NULL, send data to the peer whose MAC address matches peer_addr Attention 2. If peer_addr is NULL, send data to all of the peers that are added to the peer list Attention 3. The maximum length of data must be less than ESP_NOW_MAX_DATA_LEN Attention 4. The buffer pointed to by data argument does not need to be valid after esp_now_send returns Attention 1. If peer_addr is not NULL, send data to the peer whose MAC address matches peer_addr Attention 2. If peer_addr is NULL, send data to all of the peers that are added to the peer list Attention 3. The maximum length of data must be less than ESP_NOW_MAX_DATA_LEN Attention 4. The buffer pointed to by data argument does not need to be valid after esp_now_send returns Parameters peer_addr -- peer MAC address data -- data to send len -- length of data peer_addr -- peer MAC address data -- data to send len -- length of data peer_addr -- peer MAC address Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_INTERNAL : internal error ESP_ERR_ESPNOW_NO_MEM : out of memory, when this happens, you can delay a while before sending the next data ESP_ERR_ESPNOW_NOT_FOUND : peer is not found ESP_ERR_ESPNOW_IF : current Wi-Fi interface doesn't match that of peer ESP_ERR_ESPNOW_CHAN: current Wi-Fi channel doesn't match that of peer ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_INTERNAL : internal error ESP_ERR_ESPNOW_NO_MEM : out of memory, when this happens, you can delay a while before sending the next data ESP_ERR_ESPNOW_NOT_FOUND : peer is not found ESP_ERR_ESPNOW_IF : current Wi-Fi interface doesn't match that of peer ESP_ERR_ESPNOW_CHAN: current Wi-Fi channel doesn't match that of peer ESP_OK : succeed Parameters peer_addr -- peer MAC address data -- data to send len -- length of data Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_INTERNAL : internal error ESP_ERR_ESPNOW_NO_MEM : out of memory, when this happens, you can delay a while before sending the next data ESP_ERR_ESPNOW_NOT_FOUND : peer is not found ESP_ERR_ESPNOW_IF : current Wi-Fi interface doesn't match that of peer ESP_ERR_ESPNOW_CHAN: current Wi-Fi channel doesn't match that of peer esp_err_t esp_now_add_peer(const esp_now_peer_info_t *peer) Add a peer to peer list. Parameters peer -- peer information Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_FULL : peer list is full ESP_ERR_ESPNOW_NO_MEM : out of memory ESP_ERR_ESPNOW_EXIST : peer has existed ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_FULL : peer list is full ESP_ERR_ESPNOW_NO_MEM : out of memory ESP_ERR_ESPNOW_EXIST : peer has existed ESP_OK : succeed Parameters peer -- peer information Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_FULL : peer list is full ESP_ERR_ESPNOW_NO_MEM : out of memory ESP_ERR_ESPNOW_EXIST : peer has existed esp_err_t esp_now_del_peer(const uint8_t *peer_addr) Delete a peer from peer list. Parameters peer_addr -- peer MAC address Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_NOT_FOUND : peer is not found ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_NOT_FOUND : peer is not found ESP_OK : succeed Parameters peer_addr -- peer MAC address Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_NOT_FOUND : peer is not found esp_err_t esp_now_mod_peer(const esp_now_peer_info_t *peer) Modify a peer. Parameters peer -- peer information Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_FULL : peer list is full ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_FULL : peer list is full ESP_OK : succeed Parameters peer -- peer information Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_FULL : peer list is full esp_err_t esp_wifi_config_espnow_rate(wifi_interface_t ifx, wifi_phy_rate_t rate) Config ESPNOW rate of specified interface. Deprecated: please use esp_now_set_peer_rate_config() instead. Deprecated: please use esp_now_set_peer_rate_config() instead. Attention 1. This API should be called after esp_wifi_start(). Attention 2. This API only work when not use Wi-Fi 6 and esp_now_set_peer_rate_config() not called. Attention 1. This API should be called after esp_wifi_start(). Attention 2. This API only work when not use Wi-Fi 6 and esp_now_set_peer_rate_config() not called. Parameters ifx -- Interface to be configured. rate -- Phy rate to be configured. ifx -- Interface to be configured. rate -- Phy rate to be configured. ifx -- Interface to be configured. Returns ESP_OK: succeed others: failed ESP_OK: succeed others: failed ESP_OK: succeed Parameters ifx -- Interface to be configured. rate -- Phy rate to be configured. Returns ESP_OK: succeed others: failed esp_err_t esp_now_set_peer_rate_config(const uint8_t *peer_addr, esp_now_rate_config_t *config) Set ESPNOW rate config for each peer. Attention 1. This API should be called after esp_wifi_start() and esp_now_init(). Attention 1. This API should be called after esp_wifi_start() and esp_now_init(). Parameters peer_addr -- peer MAC address config -- rate config to be configured. peer_addr -- peer MAC address config -- rate config to be configured. peer_addr -- peer MAC address Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_INTERNAL : internal error ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_INTERNAL : internal error ESP_OK : succeed Parameters peer_addr -- peer MAC address config -- rate config to be configured. Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_INTERNAL : internal error esp_err_t esp_now_get_peer(const uint8_t *peer_addr, esp_now_peer_info_t *peer) Get a peer whose MAC address matches peer_addr from peer list. Parameters peer_addr -- peer MAC address peer -- peer information peer_addr -- peer MAC address peer -- peer information peer_addr -- peer MAC address Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_NOT_FOUND : peer is not found ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_NOT_FOUND : peer is not found ESP_OK : succeed Parameters peer_addr -- peer MAC address peer -- peer information Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_NOT_FOUND : peer is not found esp_err_t esp_now_fetch_peer(bool from_head, esp_now_peer_info_t *peer) Fetch a peer from peer list. Only return the peer which address is unicast, for the multicast/broadcast address, the function will ignore and try to find the next in the peer list. Parameters from_head -- fetch from head of list or not peer -- peer information from_head -- fetch from head of list or not peer -- peer information from_head -- fetch from head of list or not Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_NOT_FOUND : peer is not found ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_NOT_FOUND : peer is not found ESP_OK : succeed Parameters from_head -- fetch from head of list or not peer -- peer information Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_NOT_FOUND : peer is not found bool esp_now_is_peer_exist(const uint8_t *peer_addr) Peer exists or not. Parameters peer_addr -- peer MAC address Returns true : peer exists false : peer not exists true : peer exists false : peer not exists true : peer exists Parameters peer_addr -- peer MAC address Returns true : peer exists false : peer not exists esp_err_t esp_now_get_peer_num(esp_now_peer_num_t *num) Get the number of peers. Parameters num -- number of peers Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_OK : succeed Parameters num -- number of peers Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument esp_err_t esp_now_set_pmk(const uint8_t *pmk) Set the primary master key. Attention 1. primary master key is used to encrypt local master key Attention 1. primary master key is used to encrypt local master key Parameters pmk -- primary master key Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_OK : succeed Parameters pmk -- primary master key Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument esp_err_t esp_now_set_wake_window(uint16_t window) Set wake window for esp_now to wake up in interval unit. Attention 1. This configuration could work at connected status. When ESP_WIFI_STA_DISCONNECTED_PM_ENABLE is enabled, this configuration could work at disconnected status. Attention 2. Default value is the maximum. Attention 1. This configuration could work at connected status. When ESP_WIFI_STA_DISCONNECTED_PM_ENABLE is enabled, this configuration could work at disconnected status. Attention 2. Default value is the maximum. Parameters window -- Milliseconds would the chip keep waked each interval, from 0 to 65535. Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_OK : succeed Parameters window -- Milliseconds would the chip keep waked each interval, from 0 to 65535. Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized Structures struct esp_now_peer_info ESPNOW peer information parameters. Public Members uint8_t peer_addr[ESP_NOW_ETH_ALEN] ESPNOW peer MAC address that is also the MAC address of station or softap uint8_t peer_addr[ESP_NOW_ETH_ALEN] ESPNOW peer MAC address that is also the MAC address of station or softap uint8_t lmk[ESP_NOW_KEY_LEN] ESPNOW peer local master key that is used to encrypt data uint8_t lmk[ESP_NOW_KEY_LEN] ESPNOW peer local master key that is used to encrypt data uint8_t channel Wi-Fi channel that peer uses to send/receive ESPNOW data. If the value is 0, use the current channel which station or softap is on. Otherwise, it must be set as the channel that station or softap is on. uint8_t channel Wi-Fi channel that peer uses to send/receive ESPNOW data. If the value is 0, use the current channel which station or softap is on. Otherwise, it must be set as the channel that station or softap is on. wifi_interface_t ifidx Wi-Fi interface that peer uses to send/receive ESPNOW data wifi_interface_t ifidx Wi-Fi interface that peer uses to send/receive ESPNOW data bool encrypt ESPNOW data that this peer sends/receives is encrypted or not bool encrypt ESPNOW data that this peer sends/receives is encrypted or not void *priv ESPNOW peer private data void *priv ESPNOW peer private data uint8_t peer_addr[ESP_NOW_ETH_ALEN] struct esp_now_peer_num Number of ESPNOW peers which exist currently. struct esp_now_recv_info ESPNOW packet information. Public Members uint8_t *src_addr Source address of ESPNOW packet uint8_t *src_addr Source address of ESPNOW packet uint8_t *des_addr Destination address of ESPNOW packet uint8_t *des_addr Destination address of ESPNOW packet wifi_pkt_rx_ctrl_t *rx_ctrl Rx control info of ESPNOW packet wifi_pkt_rx_ctrl_t *rx_ctrl Rx control info of ESPNOW packet uint8_t *src_addr struct esp_now_rate_config ESPNOW rate config. Public Members wifi_phy_mode_t phymode ESPNOW phymode of specified interface wifi_phy_mode_t phymode ESPNOW phymode of specified interface wifi_phy_rate_t rate ESPNOW rate of specified interface wifi_phy_rate_t rate ESPNOW rate of specified interface bool ersu ESPNOW using ersu send frame bool ersu ESPNOW using ersu send frame bool dcm ESPNOW using dcm rate to send frame bool dcm ESPNOW using dcm rate to send frame wifi_phy_mode_t phymode Macros ESP_ERR_ESPNOW_BASE ESPNOW error number base. ESP_ERR_ESPNOW_NOT_INIT ESPNOW is not initialized. ESP_ERR_ESPNOW_ARG Invalid argument ESP_ERR_ESPNOW_NO_MEM Out of memory ESP_ERR_ESPNOW_FULL ESPNOW peer list is full ESP_ERR_ESPNOW_NOT_FOUND ESPNOW peer is not found ESP_ERR_ESPNOW_INTERNAL Internal error ESP_ERR_ESPNOW_EXIST ESPNOW peer has existed ESP_ERR_ESPNOW_IF Interface error ESP_ERR_ESPNOW_CHAN Channel error ESP_NOW_ETH_ALEN Length of ESPNOW peer MAC address ESP_NOW_KEY_LEN Length of ESPNOW peer local master key ESP_NOW_MAX_TOTAL_PEER_NUM Maximum number of ESPNOW total peers ESP_NOW_MAX_ENCRYPT_PEER_NUM Maximum number of ESPNOW encrypted peers ESP_NOW_MAX_DATA_LEN Maximum length of ESPNOW data which is sent very time Type Definitions typedef struct esp_now_peer_info esp_now_peer_info_t ESPNOW peer information parameters. typedef struct esp_now_peer_num esp_now_peer_num_t Number of ESPNOW peers which exist currently. typedef struct esp_now_recv_info esp_now_recv_info_t ESPNOW packet information. typedef struct esp_now_rate_config esp_now_rate_config_t ESPNOW rate config. typedef void (*esp_now_recv_cb_t)(const esp_now_recv_info_t *esp_now_info, const uint8_t *data, int data_len) Callback function of receiving ESPNOW data. Attention esp_now_info is a local variable,it can only be used in the callback. Attention esp_now_info is a local variable,it can only be used in the callback. Param esp_now_info received ESPNOW packet information Param data received data Param data_len length of received data Param esp_now_info received ESPNOW packet information Param data received data Param data_len length of received data typedef void (*esp_now_send_cb_t)(const uint8_t *mac_addr, esp_now_send_status_t status) Callback function of sending ESPNOW data. Param mac_addr peer MAC address Param status status of sending ESPNOW data (succeed or fail) Param mac_addr peer MAC address Param status status of sending ESPNOW data (succeed or fail)
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: ------------------------------------------------------------------------------------------------------------ | 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. 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: ------------------------------------------------------------------------------- | 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. 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. - PMK is used to encrypt LMK with the AES-128 algorithm. Call esp_now_set_pmk()to set PMK. If PMK is not set, a default PMK will be used. - LMK of the paired device is used to encrypt the vendor-specific action frame with the CCMP method. The maximum number of different LMKs is six. If the LMK of the paired device is not set, the vendor-specific action frame will not be encrypted. Encrypting multicast vendor-specific action frame is not supported. Initialization and Deinitialization Call esp_now_init() to initialize ESP-NOW and 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 esp_now_deinit() is called, all of the information of paired devices are deleted. Add Paired Device Call 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. 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 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. 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 esp_now_send() to send ESP-NOW data and 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. If there is a lot of ESP-NOW data to send, call 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 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 Call 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 esp_wifi_start(). Config ESP-NOW Power-saving Parameter Sleep is supported only when ESP32 is configured as station. Call 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 esp_wifi_connectionless_module_set_wake_interval() to configure Interval as well. Please refer to connectionless module power save to get more detail. Application Examples Example of sending and receiving ESP-NOW data between two devices: wifi/espnow. For more application examples of how to use ESP-NOW, please visit ESP-NOW repository. API Reference Header File This header file can be included with: #include "esp_now.h" This header file is a part of the API provided by the esp_wificomponent. To declare that your component depends on esp_wifi, add the following to your CMakeLists.txt: REQUIRES esp_wifi or PRIV_REQUIRES esp_wifi Functions - esp_err_t esp_now_init(void) Initialize ESPNOW function. - Returns ESP_OK : succeed ESP_ERR_ESPNOW_INTERNAL : Internal error - - esp_err_t esp_now_get_version(uint32_t *version) Get the version of ESPNOW. - Parameters version -- ESPNOW version - Returns ESP_OK : succeed ESP_ERR_ESPNOW_ARG : invalid argument - - esp_err_t esp_now_register_recv_cb(esp_now_recv_cb_t cb) Register callback function of receiving ESPNOW data. - Parameters cb -- callback function of receiving ESPNOW data - Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_INTERNAL : internal error - - esp_err_t esp_now_unregister_recv_cb(void) Unregister callback function of receiving ESPNOW data. - Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized - - esp_err_t esp_now_register_send_cb(esp_now_send_cb_t cb) Register callback function of sending ESPNOW data. - Parameters cb -- callback function of sending ESPNOW data - Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_INTERNAL : internal error - - esp_err_t esp_now_unregister_send_cb(void) Unregister callback function of sending ESPNOW data. - Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized - - esp_err_t esp_now_send(const uint8_t *peer_addr, const uint8_t *data, size_t len) Send ESPNOW data. - Attention 1. If peer_addr is not NULL, send data to the peer whose MAC address matches peer_addr - Attention 2. If peer_addr is NULL, send data to all of the peers that are added to the peer list - Attention 3. The maximum length of data must be less than ESP_NOW_MAX_DATA_LEN - Attention 4. The buffer pointed to by data argument does not need to be valid after esp_now_send returns - Parameters peer_addr -- peer MAC address data -- data to send len -- length of data - - Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_INTERNAL : internal error ESP_ERR_ESPNOW_NO_MEM : out of memory, when this happens, you can delay a while before sending the next data ESP_ERR_ESPNOW_NOT_FOUND : peer is not found ESP_ERR_ESPNOW_IF : current Wi-Fi interface doesn't match that of peer ESP_ERR_ESPNOW_CHAN: current Wi-Fi channel doesn't match that of peer - - esp_err_t esp_now_add_peer(const esp_now_peer_info_t *peer) Add a peer to peer list. - Parameters peer -- peer information - Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_FULL : peer list is full ESP_ERR_ESPNOW_NO_MEM : out of memory ESP_ERR_ESPNOW_EXIST : peer has existed - - esp_err_t esp_now_del_peer(const uint8_t *peer_addr) Delete a peer from peer list. - Parameters peer_addr -- peer MAC address - Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_NOT_FOUND : peer is not found - - esp_err_t esp_now_mod_peer(const esp_now_peer_info_t *peer) Modify a peer. - Parameters peer -- peer information - Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_FULL : peer list is full - - esp_err_t esp_wifi_config_espnow_rate(wifi_interface_t ifx, wifi_phy_rate_t rate) Config ESPNOW rate of specified interface. - Deprecated: please use esp_now_set_peer_rate_config() instead. - Attention 1. This API should be called after esp_wifi_start(). - Attention 2. This API only work when not use Wi-Fi 6 and esp_now_set_peer_rate_config() not called. - Parameters ifx -- Interface to be configured. rate -- Phy rate to be configured. - - Returns ESP_OK: succeed others: failed - - esp_err_t esp_now_set_peer_rate_config(const uint8_t *peer_addr, esp_now_rate_config_t *config) Set ESPNOW rate config for each peer. - Attention 1. This API should be called after esp_wifi_start() and esp_now_init(). - Parameters peer_addr -- peer MAC address config -- rate config to be configured. - - Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_INTERNAL : internal error - - esp_err_t esp_now_get_peer(const uint8_t *peer_addr, esp_now_peer_info_t *peer) Get a peer whose MAC address matches peer_addr from peer list. - Parameters peer_addr -- peer MAC address peer -- peer information - - Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_NOT_FOUND : peer is not found - - esp_err_t esp_now_fetch_peer(bool from_head, esp_now_peer_info_t *peer) Fetch a peer from peer list. Only return the peer which address is unicast, for the multicast/broadcast address, the function will ignore and try to find the next in the peer list. - Parameters from_head -- fetch from head of list or not peer -- peer information - - Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument ESP_ERR_ESPNOW_NOT_FOUND : peer is not found - - bool esp_now_is_peer_exist(const uint8_t *peer_addr) Peer exists or not. - Parameters peer_addr -- peer MAC address - Returns true : peer exists false : peer not exists - - esp_err_t esp_now_get_peer_num(esp_now_peer_num_t *num) Get the number of peers. - Parameters num -- number of peers - Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument - - esp_err_t esp_now_set_pmk(const uint8_t *pmk) Set the primary master key. - Attention 1. primary master key is used to encrypt local master key - Parameters pmk -- primary master key - Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized ESP_ERR_ESPNOW_ARG : invalid argument - - esp_err_t esp_now_set_wake_window(uint16_t window) Set wake window for esp_now to wake up in interval unit. - Attention 1. This configuration could work at connected status. When ESP_WIFI_STA_DISCONNECTED_PM_ENABLE is enabled, this configuration could work at disconnected status. - Attention 2. Default value is the maximum. - Parameters window -- Milliseconds would the chip keep waked each interval, from 0 to 65535. - Returns ESP_OK : succeed ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized - Structures - struct esp_now_peer_info ESPNOW peer information parameters. Public Members - uint8_t peer_addr[ESP_NOW_ETH_ALEN] ESPNOW peer MAC address that is also the MAC address of station or softap - uint8_t lmk[ESP_NOW_KEY_LEN] ESPNOW peer local master key that is used to encrypt data - uint8_t channel Wi-Fi channel that peer uses to send/receive ESPNOW data. If the value is 0, use the current channel which station or softap is on. Otherwise, it must be set as the channel that station or softap is on. - wifi_interface_t ifidx Wi-Fi interface that peer uses to send/receive ESPNOW data - bool encrypt ESPNOW data that this peer sends/receives is encrypted or not - void *priv ESPNOW peer private data - uint8_t peer_addr[ESP_NOW_ETH_ALEN] - struct esp_now_peer_num Number of ESPNOW peers which exist currently. - struct esp_now_recv_info ESPNOW packet information. Public Members - uint8_t *src_addr Source address of ESPNOW packet - uint8_t *des_addr Destination address of ESPNOW packet - wifi_pkt_rx_ctrl_t *rx_ctrl Rx control info of ESPNOW packet - uint8_t *src_addr - struct esp_now_rate_config ESPNOW rate config. Public Members - wifi_phy_mode_t phymode ESPNOW phymode of specified interface - wifi_phy_rate_t rate ESPNOW rate of specified interface - bool ersu ESPNOW using ersu send frame - bool dcm ESPNOW using dcm rate to send frame - wifi_phy_mode_t phymode Macros - ESP_ERR_ESPNOW_BASE ESPNOW error number base. - ESP_ERR_ESPNOW_NOT_INIT ESPNOW is not initialized. - ESP_ERR_ESPNOW_ARG Invalid argument - ESP_ERR_ESPNOW_NO_MEM Out of memory - ESP_ERR_ESPNOW_FULL ESPNOW peer list is full - ESP_ERR_ESPNOW_NOT_FOUND ESPNOW peer is not found - ESP_ERR_ESPNOW_INTERNAL Internal error - ESP_ERR_ESPNOW_EXIST ESPNOW peer has existed - ESP_ERR_ESPNOW_IF Interface error - ESP_ERR_ESPNOW_CHAN Channel error - ESP_NOW_ETH_ALEN Length of ESPNOW peer MAC address - ESP_NOW_KEY_LEN Length of ESPNOW peer local master key - ESP_NOW_MAX_TOTAL_PEER_NUM Maximum number of ESPNOW total peers - ESP_NOW_MAX_ENCRYPT_PEER_NUM Maximum number of ESPNOW encrypted peers - ESP_NOW_MAX_DATA_LEN Maximum length of ESPNOW data which is sent very time Type Definitions - typedef struct esp_now_peer_info esp_now_peer_info_t ESPNOW peer information parameters. - typedef struct esp_now_peer_num esp_now_peer_num_t Number of ESPNOW peers which exist currently. - typedef struct esp_now_recv_info esp_now_recv_info_t ESPNOW packet information. - typedef struct esp_now_rate_config esp_now_rate_config_t ESPNOW rate config. - typedef void (*esp_now_recv_cb_t)(const esp_now_recv_info_t *esp_now_info, const uint8_t *data, int data_len) Callback function of receiving ESPNOW data. - Attention esp_now_info is a local variable,it can only be used in the callback. - Param esp_now_info received ESPNOW packet information - Param data received data - Param data_len length of received data - typedef void (*esp_now_send_cb_t)(const uint8_t *mac_addr, esp_now_send_status_t status) Callback function of sending ESPNOW data. - Param mac_addr peer MAC address - Param status status of sending ESPNOW data (succeed or fail)
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/network/esp_now.html
ESP-IDF Programming Guide v5.2.1 documentation
null
ESP-WIFI-MESH Programming Guide
null
espressif.com
2016-01-01
b641f911f429bbc3
null
null
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 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 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. System Events An application interfaces with ESP-WIFI-MESH via ESP-WIFI-MESH Events. 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. The 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 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 MESH_EVENT_PARENT_CONNECTED and MESH_EVENT_CHILD_CONNECTED to indicate when a node can begin transmitting data upstream and downstream respectively. Likewise, IP_EVENT_STA_GOT_IP and 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 esp_mesh_start() is called, and before 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. Each node that could become root is required to initialize LwIP by calling 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 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. 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: Initialize Mesh The following code snippet demonstrates how to initialize ESP-WIFI-MESH /* 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)); Configuring an ESP-WIFI-MESH Network ESP-WIFI-MESH is configured via esp_mesh_set_config() which receives its arguments using the mesh_cfg_t structure. The structure contains the following parameters used to configure ESP-WIFI-MESH: Parameter Description Channel Range from 1 to 14 Mesh ID ID of ESP-WIFI-MESH Network, see Router Router Configuration, see Mesh AP Mesh AP Configuration, see Crypto Functions Crypto Functions for Mesh IE, see The following code snippet demonstrates how to configure ESP-WIFI-MESH. /* 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)); Start Mesh The following code snippet demonstrates how to start ESP-WIFI-MESH. /* 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. After connecting, the application can start transmitting and receiving packets over the ESP-WIFI-MESH network using esp_mesh_send() and esp_mesh_recv() . 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 Building a Network) Selection of a preferred parent node (see Parent Node Selection in Building a Network) Automatic reconnection upon detecting a disconnection (see Intermediate Parent Node Failure in Managing a Network) When self-organized networking is enabled, the ESP-WIFI-MESH stack will internally make calls to Wi-Fi APIs. 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 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. //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. 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 Y Y N Y The following code snipping demonstrates how to enable self-organized networking. //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 esp_mesh_set_self_organized() which disable and enable self-organized networking. The following code snippet demonstrates how an application can safely call esp_wifi_scan_start() whilst using ESP-WIFI-MESH. //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 Application Examples ESP-IDF contains these ESP-WIFI-MESH example projects: 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. 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. API Reference Header File This header file can be included with: #include "esp_mesh.h" This header file is a part of the API provided by the esp_wifi component. To declare that your component depends on esp_wifi , add the following to your CMakeLists.txt: REQUIRES esp_wifi or PRIV_REQUIRES esp_wifi Functions esp_err_t esp_mesh_init(void) Mesh initialization. Check whether Wi-Fi is started. Initialize mesh global variables with default values. Check whether Wi-Fi is started. Initialize mesh global variables with default values. Attention This API shall be called after Wi-Fi is started. Attention This API shall be called after Wi-Fi is started. Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Returns ESP_OK ESP_FAIL Check whether Wi-Fi is started. esp_err_t esp_mesh_deinit(void) Mesh de-initialization. - Release resources and stop the mesh Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Returns ESP_OK ESP_FAIL esp_err_t esp_mesh_start(void) Start mesh. Initialize mesh IE. Start mesh network management service. Create TX and RX queues according to the configuration. Register mesh packets receive callback. Initialize mesh IE. Start mesh network management service. Create TX and RX queues according to the configuration. Register mesh packets receive callback. Attention This API shall be called after mesh initialization and configuration. Attention This API shall be called after mesh initialization and configuration. Returns ESP_OK ESP_FAIL ESP_ERR_MESH_NOT_INIT ESP_ERR_MESH_NOT_CONFIG ESP_ERR_MESH_NO_MEMORY ESP_OK ESP_FAIL ESP_ERR_MESH_NOT_INIT ESP_ERR_MESH_NOT_CONFIG ESP_ERR_MESH_NO_MEMORY ESP_OK Returns ESP_OK ESP_FAIL ESP_ERR_MESH_NOT_INIT ESP_ERR_MESH_NOT_CONFIG ESP_ERR_MESH_NO_MEMORY Initialize mesh IE. esp_err_t esp_mesh_stop(void) Stop mesh. Deinitialize mesh IE. Disconnect with current parent. Disassociate all currently associated children. Stop mesh network management service. Unregister mesh packets receive callback. Delete TX and RX queues. Release resources. Restore Wi-Fi softAP to default settings if Wi-Fi dual mode is enabled. Set Wi-Fi Power Save type to WIFI_PS_NONE. Deinitialize mesh IE. Disconnect with current parent. Disassociate all currently associated children. Stop mesh network management service. Unregister mesh packets receive callback. Delete TX and RX queues. Release resources. Restore Wi-Fi softAP to default settings if Wi-Fi dual mode is enabled. Set Wi-Fi Power Save type to WIFI_PS_NONE. Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Returns ESP_OK ESP_FAIL Deinitialize mesh IE. esp_err_t esp_mesh_send(const mesh_addr_t *to, const mesh_data_t *data, int flag, const mesh_opt_t opt[], int opt_count) Send a packet over the mesh network. Send a packet to any device in the mesh network. Send a packet to external IP network. Send a packet to any device in the mesh network. Send a packet to external IP network. Attention This API is not reentrant. Attention This API is not reentrant. Parameters to -- [in] the address of the final destination of the packet If the packet is to the root, set this parameter to NULL. If the packet is to an external IP network, set this parameter to the IPv4:PORT combination. This packet will be delivered to the root firstly, then the root will forward this packet to the final IP server address. If the packet is to the root, set this parameter to NULL. If the packet is to an external IP network, set this parameter to the IPv4:PORT combination. This packet will be delivered to the root firstly, then the root will forward this packet to the final IP server address. If the packet is to the root, set this parameter to NULL. data -- [in] pointer to a sending mesh packet Field size should not exceed MESH_MPS. Note that the size of one mesh packet should not exceed MESH_MTU. Field proto should be set to data protocol in use (default is MESH_PROTO_BIN for binary). Field tos should be set to transmission tos (type of service) in use (default is MESH_TOS_P2P for point-to-point reliable). Field size should not exceed MESH_MPS. Note that the size of one mesh packet should not exceed MESH_MTU. Field proto should be set to data protocol in use (default is MESH_PROTO_BIN for binary). Field tos should be set to transmission tos (type of service) in use (default is MESH_TOS_P2P for point-to-point reliable). Field size should not exceed MESH_MPS. Note that the size of one mesh packet should not exceed MESH_MTU. flag -- [in] bitmap for data sent Speed up the route search If the packet is to the root and "to" parameter is NULL, set this parameter to 0. If the packet is to an internal device, MESH_DATA_P2P should be set. If the packet is to the root ("to" parameter isn't NULL) or to external IP network, MESH_DATA_TODS should be set. If the packet is from the root to an internal device, MESH_DATA_FROMDS should be set. If the packet is to the root and "to" parameter is NULL, set this parameter to 0. If the packet is to an internal device, MESH_DATA_P2P should be set. If the packet is to the root ("to" parameter isn't NULL) or to external IP network, MESH_DATA_TODS should be set. If the packet is from the root to an internal device, MESH_DATA_FROMDS should be set. If the packet is to the root and "to" parameter is NULL, set this parameter to 0. Specify whether this API is block or non-block, block by default If needs non-blocking, MESH_DATA_NONBLOCK should be set. Otherwise, may use esp_mesh_send_block_time() to specify a blocking time. If needs non-blocking, MESH_DATA_NONBLOCK should be set. Otherwise, may use esp_mesh_send_block_time() to specify a blocking time. If needs non-blocking, MESH_DATA_NONBLOCK should be set. Otherwise, may use esp_mesh_send_block_time() to specify a blocking time. In the situation of the root change, MESH_DATA_DROP identifies this packet can be dropped by the new root for upstream data to external IP network, we try our best to avoid data loss caused by the root change, but there is a risk that the new root is running out of memory because most of memory is occupied by the pending data which isn't read out in time by esp_mesh_recv_toDS(). Generally, we suggest esp_mesh_recv_toDS() is called after a connection with IP network is created. Thus data outgoing to external IP network via socket is just from reading esp_mesh_recv_toDS() which avoids unnecessary memory copy. Speed up the route search If the packet is to the root and "to" parameter is NULL, set this parameter to 0. If the packet is to an internal device, MESH_DATA_P2P should be set. If the packet is to the root ("to" parameter isn't NULL) or to external IP network, MESH_DATA_TODS should be set. If the packet is from the root to an internal device, MESH_DATA_FROMDS should be set. Specify whether this API is block or non-block, block by default If needs non-blocking, MESH_DATA_NONBLOCK should be set. Otherwise, may use esp_mesh_send_block_time() to specify a blocking time. In the situation of the root change, MESH_DATA_DROP identifies this packet can be dropped by the new root for upstream data to external IP network, we try our best to avoid data loss caused by the root change, but there is a risk that the new root is running out of memory because most of memory is occupied by the pending data which isn't read out in time by esp_mesh_recv_toDS(). Generally, we suggest esp_mesh_recv_toDS() is called after a connection with IP network is created. Thus data outgoing to external IP network via socket is just from reading esp_mesh_recv_toDS() which avoids unnecessary memory copy. Speed up the route search If the packet is to the root and "to" parameter is NULL, set this parameter to 0. If the packet is to an internal device, MESH_DATA_P2P should be set. If the packet is to the root ("to" parameter isn't NULL) or to external IP network, MESH_DATA_TODS should be set. If the packet is from the root to an internal device, MESH_DATA_FROMDS should be set. opt -- [in] options In case of sending a packet to a certain group, MESH_OPT_SEND_GROUP is a good choice. In this option, the value field should be set to the target receiver addresses in this group. Root sends a packet to an internal device, this packet is from external IP network in case the receiver device responds this packet, MESH_OPT_RECV_DS_ADDR is required to attach the target DS address. In case of sending a packet to a certain group, MESH_OPT_SEND_GROUP is a good choice. In this option, the value field should be set to the target receiver addresses in this group. Root sends a packet to an internal device, this packet is from external IP network in case the receiver device responds this packet, MESH_OPT_RECV_DS_ADDR is required to attach the target DS address. In case of sending a packet to a certain group, MESH_OPT_SEND_GROUP is a good choice. In this option, the value field should be set to the target receiver addresses in this group. opt_count -- [in] option count Currently, this API only takes one option, so opt_count is only supported to be 1. Currently, this API only takes one option, so opt_count is only supported to be 1. Currently, this API only takes one option, so opt_count is only supported to be 1. to -- [in] the address of the final destination of the packet If the packet is to the root, set this parameter to NULL. If the packet is to an external IP network, set this parameter to the IPv4:PORT combination. This packet will be delivered to the root firstly, then the root will forward this packet to the final IP server address. data -- [in] pointer to a sending mesh packet Field size should not exceed MESH_MPS. Note that the size of one mesh packet should not exceed MESH_MTU. Field proto should be set to data protocol in use (default is MESH_PROTO_BIN for binary). Field tos should be set to transmission tos (type of service) in use (default is MESH_TOS_P2P for point-to-point reliable). flag -- [in] bitmap for data sent Speed up the route search If the packet is to the root and "to" parameter is NULL, set this parameter to 0. If the packet is to an internal device, MESH_DATA_P2P should be set. If the packet is to the root ("to" parameter isn't NULL) or to external IP network, MESH_DATA_TODS should be set. If the packet is from the root to an internal device, MESH_DATA_FROMDS should be set. Specify whether this API is block or non-block, block by default If needs non-blocking, MESH_DATA_NONBLOCK should be set. Otherwise, may use esp_mesh_send_block_time() to specify a blocking time. In the situation of the root change, MESH_DATA_DROP identifies this packet can be dropped by the new root for upstream data to external IP network, we try our best to avoid data loss caused by the root change, but there is a risk that the new root is running out of memory because most of memory is occupied by the pending data which isn't read out in time by esp_mesh_recv_toDS(). Generally, we suggest esp_mesh_recv_toDS() is called after a connection with IP network is created. Thus data outgoing to external IP network via socket is just from reading esp_mesh_recv_toDS() which avoids unnecessary memory copy. opt -- [in] options In case of sending a packet to a certain group, MESH_OPT_SEND_GROUP is a good choice. In this option, the value field should be set to the target receiver addresses in this group. Root sends a packet to an internal device, this packet is from external IP network in case the receiver device responds this packet, MESH_OPT_RECV_DS_ADDR is required to attach the target DS address. opt_count -- [in] option count Currently, this API only takes one option, so opt_count is only supported to be 1. to -- [in] the address of the final destination of the packet If the packet is to the root, set this parameter to NULL. If the packet is to an external IP network, set this parameter to the IPv4:PORT combination. This packet will be delivered to the root firstly, then the root will forward this packet to the final IP server address. Returns ESP_OK ESP_FAIL ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_START ESP_ERR_MESH_DISCONNECTED ESP_ERR_MESH_OPT_UNKNOWN ESP_ERR_MESH_EXCEED_MTU ESP_ERR_MESH_NO_MEMORY ESP_ERR_MESH_TIMEOUT ESP_ERR_MESH_QUEUE_FULL ESP_ERR_MESH_NO_ROUTE_FOUND ESP_ERR_MESH_DISCARD ESP_OK ESP_FAIL ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_START ESP_ERR_MESH_DISCONNECTED ESP_ERR_MESH_OPT_UNKNOWN ESP_ERR_MESH_EXCEED_MTU ESP_ERR_MESH_NO_MEMORY ESP_ERR_MESH_TIMEOUT ESP_ERR_MESH_QUEUE_FULL ESP_ERR_MESH_NO_ROUTE_FOUND ESP_ERR_MESH_DISCARD ESP_OK Parameters to -- [in] the address of the final destination of the packet If the packet is to the root, set this parameter to NULL. If the packet is to an external IP network, set this parameter to the IPv4:PORT combination. This packet will be delivered to the root firstly, then the root will forward this packet to the final IP server address. data -- [in] pointer to a sending mesh packet Field size should not exceed MESH_MPS. Note that the size of one mesh packet should not exceed MESH_MTU. Field proto should be set to data protocol in use (default is MESH_PROTO_BIN for binary). Field tos should be set to transmission tos (type of service) in use (default is MESH_TOS_P2P for point-to-point reliable). flag -- [in] bitmap for data sent Speed up the route search If the packet is to the root and "to" parameter is NULL, set this parameter to 0. If the packet is to an internal device, MESH_DATA_P2P should be set. If the packet is to the root ("to" parameter isn't NULL) or to external IP network, MESH_DATA_TODS should be set. If the packet is from the root to an internal device, MESH_DATA_FROMDS should be set. Specify whether this API is block or non-block, block by default If needs non-blocking, MESH_DATA_NONBLOCK should be set. Otherwise, may use esp_mesh_send_block_time() to specify a blocking time. In the situation of the root change, MESH_DATA_DROP identifies this packet can be dropped by the new root for upstream data to external IP network, we try our best to avoid data loss caused by the root change, but there is a risk that the new root is running out of memory because most of memory is occupied by the pending data which isn't read out in time by esp_mesh_recv_toDS(). Generally, we suggest esp_mesh_recv_toDS() is called after a connection with IP network is created. Thus data outgoing to external IP network via socket is just from reading esp_mesh_recv_toDS() which avoids unnecessary memory copy. opt -- [in] options In case of sending a packet to a certain group, MESH_OPT_SEND_GROUP is a good choice. In this option, the value field should be set to the target receiver addresses in this group. Root sends a packet to an internal device, this packet is from external IP network in case the receiver device responds this packet, MESH_OPT_RECV_DS_ADDR is required to attach the target DS address. opt_count -- [in] option count Currently, this API only takes one option, so opt_count is only supported to be 1. Returns ESP_OK ESP_FAIL ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_START ESP_ERR_MESH_DISCONNECTED ESP_ERR_MESH_OPT_UNKNOWN ESP_ERR_MESH_EXCEED_MTU ESP_ERR_MESH_NO_MEMORY ESP_ERR_MESH_TIMEOUT ESP_ERR_MESH_QUEUE_FULL ESP_ERR_MESH_NO_ROUTE_FOUND ESP_ERR_MESH_DISCARD Send a packet to any device in the mesh network. esp_err_t esp_mesh_send_block_time(uint32_t time_ms) Set blocking time of esp_mesh_send() Attention This API shall be called before mesh is started. Attention This API shall be called before mesh is started. Parameters time_ms -- [in] blocking time of esp_mesh_send(), unit:ms Returns ESP_OK ESP_OK ESP_OK Parameters time_ms -- [in] blocking time of esp_mesh_send(), unit:ms Returns ESP_OK esp_err_t esp_mesh_recv(mesh_addr_t *from, mesh_data_t *data, int timeout_ms, int *flag, mesh_opt_t opt[], int opt_count) Receive a packet targeted to self over the mesh network. flag could be MESH_DATA_FROMDS or MESH_DATA_TODS. Attention Mesh RX queue should be checked regularly to avoid running out of memory. Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting to be received by applications. Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting to be received by applications. Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting to be received by applications. Attention Mesh RX queue should be checked regularly to avoid running out of memory. Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting to be received by applications. Parameters from -- [out] the address of the original source of the packet data -- [out] pointer to the received mesh packet Field proto is the data protocol in use. Should follow it to parse the received data. Field tos is the transmission tos (type of service) in use. Field proto is the data protocol in use. Should follow it to parse the received data. Field tos is the transmission tos (type of service) in use. Field proto is the data protocol in use. Should follow it to parse the received data. timeout_ms -- [in] wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever) flag -- [out] bitmap for data received MESH_DATA_FROMDS represents data from external IP network MESH_DATA_TODS represents data directed upward within the mesh network MESH_DATA_FROMDS represents data from external IP network MESH_DATA_TODS represents data directed upward within the mesh network MESH_DATA_FROMDS represents data from external IP network opt -- [out] options desired to receive MESH_OPT_RECV_DS_ADDR attaches the DS address MESH_OPT_RECV_DS_ADDR attaches the DS address MESH_OPT_RECV_DS_ADDR attaches the DS address opt_count -- [in] option count desired to receive Currently, this API only takes one option, so opt_count is only supported to be 1. Currently, this API only takes one option, so opt_count is only supported to be 1. Currently, this API only takes one option, so opt_count is only supported to be 1. from -- [out] the address of the original source of the packet data -- [out] pointer to the received mesh packet Field proto is the data protocol in use. Should follow it to parse the received data. Field tos is the transmission tos (type of service) in use. timeout_ms -- [in] wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever) flag -- [out] bitmap for data received MESH_DATA_FROMDS represents data from external IP network MESH_DATA_TODS represents data directed upward within the mesh network opt -- [out] options desired to receive MESH_OPT_RECV_DS_ADDR attaches the DS address opt_count -- [in] option count desired to receive Currently, this API only takes one option, so opt_count is only supported to be 1. from -- [out] the address of the original source of the packet Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_START ESP_ERR_MESH_TIMEOUT ESP_ERR_MESH_DISCARD ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_START ESP_ERR_MESH_TIMEOUT ESP_ERR_MESH_DISCARD ESP_OK Parameters from -- [out] the address of the original source of the packet data -- [out] pointer to the received mesh packet Field proto is the data protocol in use. Should follow it to parse the received data. Field tos is the transmission tos (type of service) in use. timeout_ms -- [in] wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever) flag -- [out] bitmap for data received MESH_DATA_FROMDS represents data from external IP network MESH_DATA_TODS represents data directed upward within the mesh network opt -- [out] options desired to receive MESH_OPT_RECV_DS_ADDR attaches the DS address opt_count -- [in] option count desired to receive Currently, this API only takes one option, so opt_count is only supported to be 1. Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_START ESP_ERR_MESH_TIMEOUT ESP_ERR_MESH_DISCARD esp_err_t esp_mesh_recv_toDS(mesh_addr_t *from, mesh_addr_t *to, mesh_data_t *data, int timeout_ms, int *flag, mesh_opt_t opt[], int opt_count) Receive a packet targeted to external IP network. Root uses this API to receive packets destined to external IP network Root forwards the received packets to the final destination via socket. If no socket connection is ready to send out the received packets and this esp_mesh_recv_toDS() hasn't been called by applications, packets from the whole mesh network will be pending in toDS queue. Root uses this API to receive packets destined to external IP network Root forwards the received packets to the final destination via socket. If no socket connection is ready to send out the received packets and this esp_mesh_recv_toDS() hasn't been called by applications, packets from the whole mesh network will be pending in toDS queue. Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting to be received by applications in case of running out of memory in the root. Using esp_mesh_set_xon_qsize() users may configure the RX queue size, default:32. If this size is too large, and esp_mesh_recv_toDS() isn't called in time, there is a risk that a great deal of memory is occupied by the pending packets. If this size is too small, it will impact the efficiency on upstream. How to decide this value depends on the specific application scenarios. flag could be MESH_DATA_TODS. Attention This API is only called by the root. Attention This API is only called by the root. Parameters from -- [out] the address of the original source of the packet to -- [out] the address contains remote IP address and port (IPv4:PORT) data -- [out] pointer to the received packet Contain the protocol and applications should follow it to parse the data. Contain the protocol and applications should follow it to parse the data. Contain the protocol and applications should follow it to parse the data. timeout_ms -- [in] wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever) flag -- [out] bitmap for data received MESH_DATA_TODS represents the received data target to external IP network. Root shall forward this data to external IP network via the association with router. MESH_DATA_TODS represents the received data target to external IP network. Root shall forward this data to external IP network via the association with router. MESH_DATA_TODS represents the received data target to external IP network. Root shall forward this data to external IP network via the association with router. opt -- [out] options desired to receive opt_count -- [in] option count desired to receive from -- [out] the address of the original source of the packet to -- [out] the address contains remote IP address and port (IPv4:PORT) data -- [out] pointer to the received packet Contain the protocol and applications should follow it to parse the data. timeout_ms -- [in] wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever) flag -- [out] bitmap for data received MESH_DATA_TODS represents the received data target to external IP network. Root shall forward this data to external IP network via the association with router. opt -- [out] options desired to receive opt_count -- [in] option count desired to receive from -- [out] the address of the original source of the packet Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_START ESP_ERR_MESH_TIMEOUT ESP_ERR_MESH_DISCARD ESP_ERR_MESH_RECV_RELEASE ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_START ESP_ERR_MESH_TIMEOUT ESP_ERR_MESH_DISCARD ESP_ERR_MESH_RECV_RELEASE ESP_OK Parameters from -- [out] the address of the original source of the packet to -- [out] the address contains remote IP address and port (IPv4:PORT) data -- [out] pointer to the received packet Contain the protocol and applications should follow it to parse the data. timeout_ms -- [in] wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever) flag -- [out] bitmap for data received MESH_DATA_TODS represents the received data target to external IP network. Root shall forward this data to external IP network via the association with router. opt -- [out] options desired to receive opt_count -- [in] option count desired to receive Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_START ESP_ERR_MESH_TIMEOUT ESP_ERR_MESH_DISCARD ESP_ERR_MESH_RECV_RELEASE Root uses this API to receive packets destined to external IP network esp_err_t esp_mesh_set_config(const mesh_cfg_t *config) Set mesh stack configuration. Use MESH_INIT_CONFIG_DEFAULT() to initialize the default values, mesh IE is encrypted by default. Mesh network is established on a fixed channel (1-14). Mesh event callback is mandatory. Mesh ID is an identifier of an MBSS. Nodes with the same mesh ID can communicate with each other. Regarding to the router configuration, if the router is hidden, BSSID field is mandatory. Use MESH_INIT_CONFIG_DEFAULT() to initialize the default values, mesh IE is encrypted by default. Mesh network is established on a fixed channel (1-14). Mesh event callback is mandatory. Mesh ID is an identifier of an MBSS. Nodes with the same mesh ID can communicate with each other. Regarding to the router configuration, if the router is hidden, BSSID field is mandatory. If BSSID field isn't set and there exists more than one router with same SSID, there is a risk that more roots than one connected with different BSSID will appear. It means more than one mesh network is established with the same mesh ID. Root conflict function could eliminate redundant roots connected with the same BSSID, but couldn't handle roots connected with different BSSID. Because users might have such requirements of setting up routers with same SSID for the future replacement. But in that case, if the above situations happen, please make sure applications implement forward functions on the root to guarantee devices in different mesh networks can communicate with each other. max_connection of mesh softAP is limited by the max number of Wi-Fi softAP supported (max:10). Attention This API shall be called before mesh is started after mesh is initialized. Attention This API shall be called before mesh is started after mesh is initialized. Parameters config -- [in] pointer to mesh stack configuration Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED ESP_OK Parameters config -- [in] pointer to mesh stack configuration Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED Use MESH_INIT_CONFIG_DEFAULT() to initialize the default values, mesh IE is encrypted by default. esp_err_t esp_mesh_get_config(mesh_cfg_t *config) Get mesh stack configuration. Parameters config -- [out] pointer to mesh stack configuration Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_OK ESP_ERR_MESH_ARGUMENT ESP_OK Parameters config -- [out] pointer to mesh stack configuration Returns ESP_OK ESP_ERR_MESH_ARGUMENT esp_err_t esp_mesh_set_router(const mesh_router_t *router) Get router configuration. Attention This API is used to dynamically modify the router configuration after mesh is configured. Attention This API is used to dynamically modify the router configuration after mesh is configured. Parameters router -- [in] pointer to router configuration Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_OK ESP_ERR_MESH_ARGUMENT ESP_OK Parameters router -- [in] pointer to router configuration Returns ESP_OK ESP_ERR_MESH_ARGUMENT esp_err_t esp_mesh_get_router(mesh_router_t *router) Get router configuration. Parameters router -- [out] pointer to router configuration Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_OK ESP_ERR_MESH_ARGUMENT ESP_OK Parameters router -- [out] pointer to router configuration Returns ESP_OK ESP_ERR_MESH_ARGUMENT esp_err_t esp_mesh_set_id(const mesh_addr_t *id) Set mesh network ID. Attention This API is used to dynamically modify the mesh network ID. Attention This API is used to dynamically modify the mesh network ID. Parameters id -- [in] pointer to mesh network ID Returns ESP_OK ESP_ERR_MESH_ARGUMENT: invalid argument ESP_OK ESP_ERR_MESH_ARGUMENT: invalid argument ESP_OK Parameters id -- [in] pointer to mesh network ID Returns ESP_OK ESP_ERR_MESH_ARGUMENT: invalid argument esp_err_t esp_mesh_get_id(mesh_addr_t *id) Get mesh network ID. Parameters id -- [out] pointer to mesh network ID Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_OK ESP_ERR_MESH_ARGUMENT ESP_OK Parameters id -- [out] pointer to mesh network ID Returns ESP_OK ESP_ERR_MESH_ARGUMENT esp_err_t esp_mesh_set_type(mesh_type_t type) Designate device type over the mesh network. MESH_IDLE: designates a device as a self-organized node for a mesh network MESH_ROOT: designates the root node for a mesh network MESH_LEAF: designates a device as a standalone Wi-Fi station that connects to a parent MESH_STA: designates a device as a standalone Wi-Fi station that connects to a router MESH_IDLE: designates a device as a self-organized node for a mesh network MESH_ROOT: designates the root node for a mesh network MESH_LEAF: designates a device as a standalone Wi-Fi station that connects to a parent MESH_STA: designates a device as a standalone Wi-Fi station that connects to a router Parameters type -- [in] device type Returns ESP_OK ESP_ERR_MESH_NOT_ALLOWED ESP_OK ESP_ERR_MESH_NOT_ALLOWED ESP_OK Parameters type -- [in] device type Returns ESP_OK ESP_ERR_MESH_NOT_ALLOWED MESH_IDLE: designates a device as a self-organized node for a mesh network mesh_type_t esp_mesh_get_type(void) Get device type over mesh network. Attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. Attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. Returns mesh type Returns mesh type esp_err_t esp_mesh_set_max_layer(int max_layer) Set network max layer value. for tree topology, the max is 25. for chain topology, the max is 1000. Network max layer limits the max hop count. for tree topology, the max is 25. for chain topology, the max is 1000. Network max layer limits the max hop count. Attention This API shall be called before mesh is started. Attention This API shall be called before mesh is started. Parameters max_layer -- [in] max layer value Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED ESP_OK Parameters max_layer -- [in] max layer value Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED for tree topology, the max is 25. int esp_mesh_get_max_layer(void) Get max layer value. Returns max layer value Returns max layer value esp_err_t esp_mesh_set_ap_password(const uint8_t *pwd, int len) Set mesh softAP password. Attention This API shall be called before mesh is started. Attention This API shall be called before mesh is started. Parameters pwd -- [in] pointer to the password len -- [in] password length pwd -- [in] pointer to the password len -- [in] password length pwd -- [in] pointer to the password Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED ESP_OK Parameters pwd -- [in] pointer to the password len -- [in] password length Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED esp_err_t esp_mesh_set_ap_authmode(wifi_auth_mode_t authmode) Set mesh softAP authentication mode. Attention This API shall be called before mesh is started. Attention This API shall be called before mesh is started. Parameters authmode -- [in] authentication mode Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED ESP_OK Parameters authmode -- [in] authentication mode Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED wifi_auth_mode_t esp_mesh_get_ap_authmode(void) Get mesh softAP authentication mode. Returns authentication mode Returns authentication mode esp_err_t esp_mesh_set_ap_connections(int connections) Set mesh max connection value. Set mesh softAP max connection = mesh max connection + non-mesh max connection Set mesh softAP max connection = mesh max connection + non-mesh max connection Attention This API shall be called before mesh is started. Attention This API shall be called before mesh is started. Parameters connections -- [in] the number of max connections Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_OK ESP_ERR_MESH_ARGUMENT ESP_OK Parameters connections -- [in] the number of max connections Returns ESP_OK ESP_ERR_MESH_ARGUMENT Set mesh softAP max connection = mesh max connection + non-mesh max connection int esp_mesh_get_ap_connections(void) Get mesh max connection configuration. Returns the number of mesh max connections Returns the number of mesh max connections int esp_mesh_get_non_mesh_connections(void) Get non-mesh max connection configuration. Returns the number of non-mesh max connections Returns the number of non-mesh max connections int esp_mesh_get_layer(void) Get current layer value over the mesh network. Attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. Attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. Returns layer value Returns layer value esp_err_t esp_mesh_get_parent_bssid(mesh_addr_t *bssid) Get the parent BSSID. Attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. Attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. Parameters bssid -- [out] pointer to parent BSSID Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters bssid -- [out] pointer to parent BSSID Returns ESP_OK ESP_FAIL bool esp_mesh_is_root(void) Return whether the device is the root node of the network. Returns true/false Returns true/false esp_err_t esp_mesh_set_self_organized(bool enable, bool select_parent) Enable/disable self-organized networking. Self-organized networking has three main functions: select the root node; find a preferred parent; initiate reconnection if a disconnection is detected. Self-organized networking is enabled by default. If self-organized is disabled, users should set a parent for the device via esp_mesh_set_parent(). Self-organized networking has three main functions: select the root node; find a preferred parent; initiate reconnection if a disconnection is detected. Self-organized networking is enabled by default. If self-organized is disabled, users should set a parent for the device via esp_mesh_set_parent(). Attention This API is used to dynamically modify whether to enable the self organizing. Attention This API is used to dynamically modify whether to enable the self organizing. Parameters enable -- [in] enable or disable self-organized networking select_parent -- [in] Only valid when self-organized networking is enabled. if select_parent is set to true, the root will give up its mesh root status and search for a new parent like other non-root devices. if select_parent is set to true, the root will give up its mesh root status and search for a new parent like other non-root devices. if select_parent is set to true, the root will give up its mesh root status and search for a new parent like other non-root devices. enable -- [in] enable or disable self-organized networking select_parent -- [in] Only valid when self-organized networking is enabled. if select_parent is set to true, the root will give up its mesh root status and search for a new parent like other non-root devices. enable -- [in] enable or disable self-organized networking Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters enable -- [in] enable or disable self-organized networking select_parent -- [in] Only valid when self-organized networking is enabled. if select_parent is set to true, the root will give up its mesh root status and search for a new parent like other non-root devices. Returns ESP_OK ESP_FAIL Self-organized networking has three main functions: select the root node; find a preferred parent; initiate reconnection if a disconnection is detected. bool esp_mesh_get_self_organized(void) Return whether enable self-organized networking or not. Returns true/false Returns true/false esp_err_t esp_mesh_waive_root(const mesh_vote_t *vote, int reason) Cause the root device to give up (waive) its mesh root status. A device is elected root primarily based on RSSI from the external router. If external router conditions change, users can call this API to perform a root switch. In this API, users could specify a desired root address to replace itself or specify an attempts value to ask current root to initiate a new round of voting. During the voting, a better root candidate would be expected to find to replace the current one. If no desired root candidate, the vote will try a specified number of attempts (at least 15). If no better root candidate is found, keep the current one. If a better candidate is found, the new better one will send a root switch request to the current root, current root will respond with a root switch acknowledgment. After that, the new candidate will connect to the router to be a new root, the previous root will disconnect with the router and choose another parent instead. A device is elected root primarily based on RSSI from the external router. If external router conditions change, users can call this API to perform a root switch. In this API, users could specify a desired root address to replace itself or specify an attempts value to ask current root to initiate a new round of voting. During the voting, a better root candidate would be expected to find to replace the current one. If no desired root candidate, the vote will try a specified number of attempts (at least 15). If no better root candidate is found, keep the current one. If a better candidate is found, the new better one will send a root switch request to the current root, current root will respond with a root switch acknowledgment. After that, the new candidate will connect to the router to be a new root, the previous root will disconnect with the router and choose another parent instead. Root switch is completed with minimal disruption to the whole mesh network. Attention This API is only called by the root. Attention This API is only called by the root. Parameters vote -- [in] vote configuration If this parameter is set NULL, the vote will perform the default 15 times. Field percentage threshold is 0.9 by default. Field is_rc_specified shall be false. Field attempts shall be at least 15 times. If this parameter is set NULL, the vote will perform the default 15 times. Field percentage threshold is 0.9 by default. Field is_rc_specified shall be false. Field attempts shall be at least 15 times. If this parameter is set NULL, the vote will perform the default 15 times. reason -- [in] only accept MESH_VOTE_REASON_ROOT_INITIATED for now vote -- [in] vote configuration If this parameter is set NULL, the vote will perform the default 15 times. Field percentage threshold is 0.9 by default. Field is_rc_specified shall be false. Field attempts shall be at least 15 times. reason -- [in] only accept MESH_VOTE_REASON_ROOT_INITIATED for now vote -- [in] vote configuration If this parameter is set NULL, the vote will perform the default 15 times. Field percentage threshold is 0.9 by default. Field is_rc_specified shall be false. Field attempts shall be at least 15 times. Returns ESP_OK ESP_ERR_MESH_QUEUE_FULL ESP_ERR_MESH_DISCARD ESP_FAIL ESP_OK ESP_ERR_MESH_QUEUE_FULL ESP_ERR_MESH_DISCARD ESP_FAIL ESP_OK Parameters vote -- [in] vote configuration If this parameter is set NULL, the vote will perform the default 15 times. Field percentage threshold is 0.9 by default. Field is_rc_specified shall be false. Field attempts shall be at least 15 times. reason -- [in] only accept MESH_VOTE_REASON_ROOT_INITIATED for now Returns ESP_OK ESP_ERR_MESH_QUEUE_FULL ESP_ERR_MESH_DISCARD ESP_FAIL A device is elected root primarily based on RSSI from the external router. esp_err_t esp_mesh_set_vote_percentage(float percentage) Set vote percentage threshold for approval of being a root (default:0.9) During the networking, only obtaining vote percentage reaches this threshold, the device could be a root. During the networking, only obtaining vote percentage reaches this threshold, the device could be a root. Attention This API shall be called before mesh is started. Attention This API shall be called before mesh is started. Parameters percentage -- [in] vote percentage threshold Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters percentage -- [in] vote percentage threshold Returns ESP_OK ESP_FAIL During the networking, only obtaining vote percentage reaches this threshold, the device could be a root. float esp_mesh_get_vote_percentage(void) Get vote percentage threshold for approval of being a root. Returns percentage threshold Returns percentage threshold esp_err_t esp_mesh_set_ap_assoc_expire(int seconds) Set mesh softAP associate expired time (default:10 seconds) If mesh softAP hasn't received any data from an associated child within this time, mesh softAP will take this child inactive and disassociate it. If mesh softAP is encrypted, this value should be set a greater value, such as 30 seconds. If mesh softAP hasn't received any data from an associated child within this time, mesh softAP will take this child inactive and disassociate it. If mesh softAP is encrypted, this value should be set a greater value, such as 30 seconds. Parameters seconds -- [in] the expired time Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters seconds -- [in] the expired time Returns ESP_OK ESP_FAIL If mesh softAP hasn't received any data from an associated child within this time, mesh softAP will take this child inactive and disassociate it. int esp_mesh_get_ap_assoc_expire(void) Get mesh softAP associate expired time. Returns seconds Returns seconds int esp_mesh_get_total_node_num(void) Get total number of devices in current network (including the root) Attention The returned value might be incorrect when the network is changing. Attention The returned value might be incorrect when the network is changing. Returns total number of devices (including the root) Returns total number of devices (including the root) int esp_mesh_get_routing_table_size(void) Get the number of devices in this device's sub-network (including self) Returns the number of devices over this device's sub-network (including self) Returns the number of devices over this device's sub-network (including self) esp_err_t esp_mesh_get_routing_table(mesh_addr_t *mac, int len, int *size) Get routing table of this device's sub-network (including itself) Parameters mac -- [out] pointer to routing table len -- [in] routing table size(in bytes) size -- [out] pointer to the number of devices in routing table (including itself) mac -- [out] pointer to routing table len -- [in] routing table size(in bytes) size -- [out] pointer to the number of devices in routing table (including itself) mac -- [out] pointer to routing table Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_OK ESP_ERR_MESH_ARGUMENT ESP_OK Parameters mac -- [out] pointer to routing table len -- [in] routing table size(in bytes) size -- [out] pointer to the number of devices in routing table (including itself) Returns ESP_OK ESP_ERR_MESH_ARGUMENT esp_err_t esp_mesh_post_toDS_state(bool reachable) Post the toDS state to the mesh stack. Attention This API is only for the root. Attention This API is only for the root. Parameters reachable -- [in] this state represents whether the root is able to access external IP network Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters reachable -- [in] this state represents whether the root is able to access external IP network Returns ESP_OK ESP_FAIL esp_err_t esp_mesh_get_tx_pending(mesh_tx_pending_t *pending) Return the number of packets pending in the queue waiting to be sent by the mesh stack. Parameters pending -- [out] pointer to the TX pending Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters pending -- [out] pointer to the TX pending Returns ESP_OK ESP_FAIL esp_err_t esp_mesh_get_rx_pending(mesh_rx_pending_t *pending) Return the number of packets available in the queue waiting to be received by applications. Parameters pending -- [out] pointer to the RX pending Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters pending -- [out] pointer to the RX pending Returns ESP_OK ESP_FAIL int esp_mesh_available_txupQ_num(const mesh_addr_t *addr, uint32_t *xseqno_in) Return the number of packets could be accepted from the specified address. Parameters addr -- [in] self address or an associate children address xseqno_in -- [out] sequence number of the last received packet from the specified address addr -- [in] self address or an associate children address xseqno_in -- [out] sequence number of the last received packet from the specified address addr -- [in] self address or an associate children address Returns the number of upQ for a certain address Parameters addr -- [in] self address or an associate children address xseqno_in -- [out] sequence number of the last received packet from the specified address Returns the number of upQ for a certain address esp_err_t esp_mesh_set_xon_qsize(int qsize) Set the number of RX queue for the node, the average number of window allocated to one of its child node is: wnd = xon_qsize / (2 * max_connection + 1). However, the window of each child node is not strictly equal to the average value, it is affected by the traffic also. Attention This API shall be called before mesh is started. Attention This API shall be called before mesh is started. Parameters qsize -- [in] default:32 (min:16) Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters qsize -- [in] default:32 (min:16) Returns ESP_OK ESP_FAIL int esp_mesh_get_xon_qsize(void) Get queue size. Returns the number of queue Returns the number of queue esp_err_t esp_mesh_allow_root_conflicts(bool allowed) Set whether allow more than one root existing in one network. Parameters allowed -- [in] allow or not Returns ESP_OK ESP_WIFI_ERR_NOT_INIT ESP_WIFI_ERR_NOT_START ESP_OK ESP_WIFI_ERR_NOT_INIT ESP_WIFI_ERR_NOT_START ESP_OK Parameters allowed -- [in] allow or not Returns ESP_OK ESP_WIFI_ERR_NOT_INIT ESP_WIFI_ERR_NOT_START bool esp_mesh_is_root_conflicts_allowed(void) Check whether allow more than one root to exist in one network. Returns true/false Returns true/false esp_err_t esp_mesh_set_group_id(const mesh_addr_t *addr, int num) Set group ID addresses. Parameters addr -- [in] pointer to new group ID addresses num -- [in] the number of group ID addresses addr -- [in] pointer to new group ID addresses num -- [in] the number of group ID addresses addr -- [in] pointer to new group ID addresses Returns ESP_OK ESP_MESH_ERR_ARGUMENT ESP_OK ESP_MESH_ERR_ARGUMENT ESP_OK Parameters addr -- [in] pointer to new group ID addresses num -- [in] the number of group ID addresses Returns ESP_OK ESP_MESH_ERR_ARGUMENT esp_err_t esp_mesh_delete_group_id(const mesh_addr_t *addr, int num) Delete group ID addresses. Parameters addr -- [in] pointer to deleted group ID address num -- [in] the number of group ID addresses addr -- [in] pointer to deleted group ID address num -- [in] the number of group ID addresses addr -- [in] pointer to deleted group ID address Returns ESP_OK ESP_MESH_ERR_ARGUMENT ESP_OK ESP_MESH_ERR_ARGUMENT ESP_OK Parameters addr -- [in] pointer to deleted group ID address num -- [in] the number of group ID addresses Returns ESP_OK ESP_MESH_ERR_ARGUMENT int esp_mesh_get_group_num(void) Get the number of group ID addresses. Returns the number of group ID addresses Returns the number of group ID addresses esp_err_t esp_mesh_get_group_list(mesh_addr_t *addr, int num) Get group ID addresses. Parameters addr -- [out] pointer to group ID addresses num -- [in] the number of group ID addresses addr -- [out] pointer to group ID addresses num -- [in] the number of group ID addresses addr -- [out] pointer to group ID addresses Returns ESP_OK ESP_MESH_ERR_ARGUMENT ESP_OK ESP_MESH_ERR_ARGUMENT ESP_OK Parameters addr -- [out] pointer to group ID addresses num -- [in] the number of group ID addresses Returns ESP_OK ESP_MESH_ERR_ARGUMENT bool esp_mesh_is_my_group(const mesh_addr_t *addr) Check whether the specified group address is my group. Returns true/false Returns true/false esp_err_t esp_mesh_set_capacity_num(int num) Set mesh network capacity (max:1000, default:300) Attention This API shall be called before mesh is started. Attention This API shall be called before mesh is started. Parameters num -- [in] mesh network capacity Returns ESP_OK ESP_ERR_MESH_NOT_ALLOWED ESP_MESH_ERR_ARGUMENT ESP_OK ESP_ERR_MESH_NOT_ALLOWED ESP_MESH_ERR_ARGUMENT ESP_OK Parameters num -- [in] mesh network capacity Returns ESP_OK ESP_ERR_MESH_NOT_ALLOWED ESP_MESH_ERR_ARGUMENT int esp_mesh_get_capacity_num(void) Get mesh network capacity. Returns mesh network capacity Returns mesh network capacity esp_err_t esp_mesh_set_ie_crypto_funcs(const mesh_crypto_funcs_t *crypto_funcs) Set mesh IE crypto functions. Attention This API can be called at any time after mesh is configured. Attention This API can be called at any time after mesh is configured. Parameters crypto_funcs -- [in] crypto functions for mesh IE If crypto_funcs is set to NULL, mesh IE is no longer encrypted. If crypto_funcs is set to NULL, mesh IE is no longer encrypted. If crypto_funcs is set to NULL, mesh IE is no longer encrypted. Returns ESP_OK ESP_OK ESP_OK Parameters crypto_funcs -- [in] crypto functions for mesh IE If crypto_funcs is set to NULL, mesh IE is no longer encrypted. Returns ESP_OK esp_err_t esp_mesh_set_ie_crypto_key(const char *key, int len) Set mesh IE crypto key. Attention This API can be called at any time after mesh is configured. Attention This API can be called at any time after mesh is configured. Parameters key -- [in] ASCII crypto key len -- [in] length in bytes, range:8~64 key -- [in] ASCII crypto key len -- [in] length in bytes, range:8~64 key -- [in] ASCII crypto key Returns ESP_OK ESP_MESH_ERR_ARGUMENT ESP_OK ESP_MESH_ERR_ARGUMENT ESP_OK Parameters key -- [in] ASCII crypto key len -- [in] length in bytes, range:8~64 Returns ESP_OK ESP_MESH_ERR_ARGUMENT esp_err_t esp_mesh_get_ie_crypto_key(char *key, int len) Get mesh IE crypto key. Parameters key -- [out] ASCII crypto key len -- [in] length in bytes, range:8~64 key -- [out] ASCII crypto key len -- [in] length in bytes, range:8~64 key -- [out] ASCII crypto key Returns ESP_OK ESP_MESH_ERR_ARGUMENT ESP_OK ESP_MESH_ERR_ARGUMENT ESP_OK Parameters key -- [out] ASCII crypto key len -- [in] length in bytes, range:8~64 Returns ESP_OK ESP_MESH_ERR_ARGUMENT esp_err_t esp_mesh_set_root_healing_delay(int delay_ms) Set delay time before starting root healing. Parameters delay_ms -- [in] delay time in milliseconds Returns ESP_OK ESP_OK ESP_OK Parameters delay_ms -- [in] delay time in milliseconds Returns ESP_OK int esp_mesh_get_root_healing_delay(void) Get delay time before network starts root healing. Returns delay time in milliseconds Returns delay time in milliseconds esp_err_t esp_mesh_fix_root(bool enable) Enable network Fixed Root Setting. Enabling fixed root disables automatic election of the root node via voting. All devices in the network shall use the same Fixed Root Setting (enabled or disabled). If Fixed Root is enabled, users should make sure a root node is designated for the network. Enabling fixed root disables automatic election of the root node via voting. All devices in the network shall use the same Fixed Root Setting (enabled or disabled). If Fixed Root is enabled, users should make sure a root node is designated for the network. Parameters enable -- [in] enable or not Returns ESP_OK ESP_OK ESP_OK Parameters enable -- [in] enable or not Returns ESP_OK Enabling fixed root disables automatic election of the root node via voting. bool esp_mesh_is_root_fixed(void) Check whether network Fixed Root Setting is enabled. Enable/disable network Fixed Root Setting by API esp_mesh_fix_root(). Network Fixed Root Setting also changes with the "flag" value in parent networking IE. Enable/disable network Fixed Root Setting by API esp_mesh_fix_root(). Network Fixed Root Setting also changes with the "flag" value in parent networking IE. Returns true/false Returns true/false Enable/disable network Fixed Root Setting by API esp_mesh_fix_root(). esp_err_t esp_mesh_set_parent(const wifi_config_t *parent, const mesh_addr_t *parent_mesh_id, mesh_type_t my_type, int my_layer) Set a specified parent for the device. Attention This API can be called at any time after mesh is configured. Attention This API can be called at any time after mesh is configured. Parameters parent -- [in] parent configuration, the SSID and the channel of the parent are mandatory. If the BSSID is set, make sure that the SSID and BSSID represent the same parent, otherwise the device will never find this specified parent. If the BSSID is set, make sure that the SSID and BSSID represent the same parent, otherwise the device will never find this specified parent. If the BSSID is set, make sure that the SSID and BSSID represent the same parent, otherwise the device will never find this specified parent. parent_mesh_id -- [in] parent mesh ID, If this value is not set, the original mesh ID is used. If this value is not set, the original mesh ID is used. If this value is not set, the original mesh ID is used. my_type -- [in] mesh type MESH_STA is not supported. If the parent set for the device is the same as the router in the network configuration, then my_type shall set MESH_ROOT and my_layer shall set MESH_ROOT_LAYER. MESH_STA is not supported. If the parent set for the device is the same as the router in the network configuration, then my_type shall set MESH_ROOT and my_layer shall set MESH_ROOT_LAYER. MESH_STA is not supported. my_layer -- [in] mesh layer my_layer of the device may change after joining the network. If my_type is set MESH_NODE, my_layer shall be greater than MESH_ROOT_LAYER. If my_type is set MESH_LEAF, the device becomes a standalone Wi-Fi station and no longer has the ability to extend the network. my_layer of the device may change after joining the network. If my_type is set MESH_NODE, my_layer shall be greater than MESH_ROOT_LAYER. If my_type is set MESH_LEAF, the device becomes a standalone Wi-Fi station and no longer has the ability to extend the network. my_layer of the device may change after joining the network. parent -- [in] parent configuration, the SSID and the channel of the parent are mandatory. If the BSSID is set, make sure that the SSID and BSSID represent the same parent, otherwise the device will never find this specified parent. parent_mesh_id -- [in] parent mesh ID, If this value is not set, the original mesh ID is used. my_type -- [in] mesh type MESH_STA is not supported. If the parent set for the device is the same as the router in the network configuration, then my_type shall set MESH_ROOT and my_layer shall set MESH_ROOT_LAYER. my_layer -- [in] mesh layer my_layer of the device may change after joining the network. If my_type is set MESH_NODE, my_layer shall be greater than MESH_ROOT_LAYER. If my_type is set MESH_LEAF, the device becomes a standalone Wi-Fi station and no longer has the ability to extend the network. parent -- [in] parent configuration, the SSID and the channel of the parent are mandatory. If the BSSID is set, make sure that the SSID and BSSID represent the same parent, otherwise the device will never find this specified parent. Returns ESP_OK ESP_ERR_ARGUMENT ESP_ERR_MESH_NOT_CONFIG ESP_OK ESP_ERR_ARGUMENT ESP_ERR_MESH_NOT_CONFIG ESP_OK Parameters parent -- [in] parent configuration, the SSID and the channel of the parent are mandatory. If the BSSID is set, make sure that the SSID and BSSID represent the same parent, otherwise the device will never find this specified parent. parent_mesh_id -- [in] parent mesh ID, If this value is not set, the original mesh ID is used. my_type -- [in] mesh type MESH_STA is not supported. If the parent set for the device is the same as the router in the network configuration, then my_type shall set MESH_ROOT and my_layer shall set MESH_ROOT_LAYER. my_layer -- [in] mesh layer my_layer of the device may change after joining the network. If my_type is set MESH_NODE, my_layer shall be greater than MESH_ROOT_LAYER. If my_type is set MESH_LEAF, the device becomes a standalone Wi-Fi station and no longer has the ability to extend the network. Returns ESP_OK ESP_ERR_ARGUMENT ESP_ERR_MESH_NOT_CONFIG esp_err_t esp_mesh_scan_get_ap_ie_len(int *len) Get mesh networking IE length of one AP. Parameters len -- [out] mesh networking IE length Returns ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_INVALID_ARG ESP_ERR_WIFI_FAIL ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_INVALID_ARG ESP_ERR_WIFI_FAIL ESP_OK Parameters len -- [out] mesh networking IE length Returns ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_INVALID_ARG ESP_ERR_WIFI_FAIL esp_err_t esp_mesh_scan_get_ap_record(wifi_ap_record_t *ap_record, void *buffer) Get AP record. Attention Different from esp_wifi_scan_get_ap_records(), this API only gets one of APs scanned each time. See "manual_networking" example. Attention Different from esp_wifi_scan_get_ap_records(), this API only gets one of APs scanned each time. See "manual_networking" example. Parameters ap_record -- [out] pointer to one AP record buffer -- [out] pointer to the mesh networking IE of this AP ap_record -- [out] pointer to one AP record buffer -- [out] pointer to the mesh networking IE of this AP ap_record -- [out] pointer to one AP record Returns ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_INVALID_ARG ESP_ERR_WIFI_FAIL ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_INVALID_ARG ESP_ERR_WIFI_FAIL ESP_OK Parameters ap_record -- [out] pointer to one AP record buffer -- [out] pointer to the mesh networking IE of this AP Returns ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_INVALID_ARG ESP_ERR_WIFI_FAIL esp_err_t esp_mesh_flush_upstream_packets(void) Flush upstream packets pending in to_parent queue and to_parent_p2p queue. Returns ESP_OK ESP_OK ESP_OK Returns ESP_OK esp_err_t esp_mesh_get_subnet_nodes_num(const mesh_addr_t *child_mac, int *nodes_num) Get the number of nodes in the subnet of a specific child. Parameters child_mac -- [in] an associated child address of this device nodes_num -- [out] pointer to the number of nodes in the subnet of a specific child child_mac -- [in] an associated child address of this device nodes_num -- [out] pointer to the number of nodes in the subnet of a specific child child_mac -- [in] an associated child address of this device Returns ESP_OK ESP_ERR_MESH_NOT_START ESP_ERR_MESH_ARGUMENT ESP_OK ESP_ERR_MESH_NOT_START ESP_ERR_MESH_ARGUMENT ESP_OK Parameters child_mac -- [in] an associated child address of this device nodes_num -- [out] pointer to the number of nodes in the subnet of a specific child Returns ESP_OK ESP_ERR_MESH_NOT_START ESP_ERR_MESH_ARGUMENT esp_err_t esp_mesh_get_subnet_nodes_list(const mesh_addr_t *child_mac, mesh_addr_t *nodes, int nodes_num) Get nodes in the subnet of a specific child. Parameters child_mac -- [in] an associated child address of this device nodes -- [out] pointer to nodes in the subnet of a specific child nodes_num -- [in] the number of nodes in the subnet of a specific child child_mac -- [in] an associated child address of this device nodes -- [out] pointer to nodes in the subnet of a specific child nodes_num -- [in] the number of nodes in the subnet of a specific child child_mac -- [in] an associated child address of this device Returns ESP_OK ESP_ERR_MESH_NOT_START ESP_ERR_MESH_ARGUMENT ESP_OK ESP_ERR_MESH_NOT_START ESP_ERR_MESH_ARGUMENT ESP_OK Parameters child_mac -- [in] an associated child address of this device nodes -- [out] pointer to nodes in the subnet of a specific child nodes_num -- [in] the number of nodes in the subnet of a specific child Returns ESP_OK ESP_ERR_MESH_NOT_START ESP_ERR_MESH_ARGUMENT esp_err_t esp_mesh_switch_channel(const uint8_t *new_bssid, int csa_newchan, int csa_count) Cause the root device to add Channel Switch Announcement Element (CSA IE) to beacon. Set the new channel Set how many beacons with CSA IE will be sent before changing a new channel Enable the channel switch function Set the new channel Set how many beacons with CSA IE will be sent before changing a new channel Enable the channel switch function Attention This API is only called by the root. Attention This API is only called by the root. Parameters new_bssid -- [in] the new router BSSID if the router changes csa_newchan -- [in] the new channel number to which the whole network is moving csa_count -- [in] channel switch period(beacon count), unit is based on beacon interval of its softAP, the default value is 15. new_bssid -- [in] the new router BSSID if the router changes csa_newchan -- [in] the new channel number to which the whole network is moving csa_count -- [in] channel switch period(beacon count), unit is based on beacon interval of its softAP, the default value is 15. new_bssid -- [in] the new router BSSID if the router changes Returns ESP_OK ESP_OK ESP_OK Parameters new_bssid -- [in] the new router BSSID if the router changes csa_newchan -- [in] the new channel number to which the whole network is moving csa_count -- [in] channel switch period(beacon count), unit is based on beacon interval of its softAP, the default value is 15. Returns ESP_OK Set the new channel esp_err_t esp_mesh_get_router_bssid(uint8_t *router_bssid) Get the router BSSID. Parameters router_bssid -- [out] pointer to the router BSSID Returns ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_INVALID_ARG ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_INVALID_ARG ESP_OK Parameters router_bssid -- [out] pointer to the router BSSID Returns ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_INVALID_ARG int64_t esp_mesh_get_tsf_time(void) Get the TSF time. Returns the TSF time Returns the TSF time esp_err_t esp_mesh_set_topology(esp_mesh_topology_t topo) Set mesh topology. The default value is MESH_TOPO_TREE. MESH_TOPO_CHAIN supports up to 1000 layers MESH_TOPO_CHAIN supports up to 1000 layers Attention This API shall be called before mesh is started. Attention This API shall be called before mesh is started. Parameters topo -- [in] MESH_TOPO_TREE or MESH_TOPO_CHAIN Returns ESP_OK ESP_MESH_ERR_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED ESP_OK ESP_MESH_ERR_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED ESP_OK Parameters topo -- [in] MESH_TOPO_TREE or MESH_TOPO_CHAIN Returns ESP_OK ESP_MESH_ERR_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED MESH_TOPO_CHAIN supports up to 1000 layers esp_mesh_topology_t esp_mesh_get_topology(void) Get mesh topology. Returns MESH_TOPO_TREE or MESH_TOPO_CHAIN Returns MESH_TOPO_TREE or MESH_TOPO_CHAIN esp_err_t esp_mesh_enable_ps(void) Enable mesh Power Save function. Attention This API shall be called before mesh is started. Attention This API shall be called before mesh is started. Returns ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_MESH_NOT_ALLOWED ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_MESH_NOT_ALLOWED ESP_OK Returns ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_MESH_NOT_ALLOWED esp_err_t esp_mesh_disable_ps(void) Disable mesh Power Save function. Attention This API shall be called before mesh is started. Attention This API shall be called before mesh is started. Returns ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_MESH_NOT_ALLOWED ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_MESH_NOT_ALLOWED ESP_OK Returns ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_MESH_NOT_ALLOWED bool esp_mesh_is_ps_enabled(void) Check whether the mesh Power Save function is enabled. Returns true/false Returns true/false bool esp_mesh_is_device_active(void) Check whether the device is in active state. If the device is not in active state, it will neither transmit nor receive frames. If the device is not in active state, it will neither transmit nor receive frames. Returns true/false Returns true/false If the device is not in active state, it will neither transmit nor receive frames. esp_err_t esp_mesh_set_active_duty_cycle(int dev_duty, int dev_duty_type) Set the device duty cycle and type. The range of dev_duty values is 1 to 100. The default value is 10. dev_duty = 100, the PS will be stopped. dev_duty is better to not less than 5. dev_duty_type could be MESH_PS_DEVICE_DUTY_REQUEST or MESH_PS_DEVICE_DUTY_DEMAND. If dev_duty_type is set to MESH_PS_DEVICE_DUTY_REQUEST, the device will use a nwk_duty provided by the network. If dev_duty_type is set to MESH_PS_DEVICE_DUTY_DEMAND, the device will use the specified dev_duty. The range of dev_duty values is 1 to 100. The default value is 10. dev_duty = 100, the PS will be stopped. dev_duty is better to not less than 5. dev_duty_type could be MESH_PS_DEVICE_DUTY_REQUEST or MESH_PS_DEVICE_DUTY_DEMAND. If dev_duty_type is set to MESH_PS_DEVICE_DUTY_REQUEST, the device will use a nwk_duty provided by the network. If dev_duty_type is set to MESH_PS_DEVICE_DUTY_DEMAND, the device will use the specified dev_duty. Attention This API can be called at any time after mesh is started. Attention This API can be called at any time after mesh is started. Parameters dev_duty -- [in] device duty cycle dev_duty_type -- [in] device PS duty cycle type, not accept MESH_PS_NETWORK_DUTY_MASTER dev_duty -- [in] device duty cycle dev_duty_type -- [in] device PS duty cycle type, not accept MESH_PS_NETWORK_DUTY_MASTER dev_duty -- [in] device duty cycle Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters dev_duty -- [in] device duty cycle dev_duty_type -- [in] device PS duty cycle type, not accept MESH_PS_NETWORK_DUTY_MASTER Returns ESP_OK ESP_FAIL The range of dev_duty values is 1 to 100. The default value is 10. esp_err_t esp_mesh_get_active_duty_cycle(int *dev_duty, int *dev_duty_type) Get device duty cycle and type. Parameters dev_duty -- [out] device duty cycle dev_duty_type -- [out] device PS duty cycle type dev_duty -- [out] device duty cycle dev_duty_type -- [out] device PS duty cycle type dev_duty -- [out] device duty cycle Returns ESP_OK ESP_OK ESP_OK Parameters dev_duty -- [out] device duty cycle dev_duty_type -- [out] device PS duty cycle type Returns ESP_OK esp_err_t esp_mesh_set_network_duty_cycle(int nwk_duty, int duration_mins, int applied_rule) Set the network duty cycle, duration and rule. The range of nwk_duty values is 1 to 100. The default value is 10. nwk_duty is the network duty cycle the entire network or the up-link path will use. A device that successfully sets the nwk_duty is known as a NWK-DUTY-MASTER. duration_mins specifies how long the specified nwk_duty will be used. Once duration_mins expires, the root will take over as the NWK-DUTY-MASTER. If an existing NWK-DUTY-MASTER leaves the network, the root will take over as the NWK-DUTY-MASTER again. duration_mins = (-1) represents nwk_duty will be used until a new NWK-DUTY-MASTER with a different nwk_duty appears. Only the root can set duration_mins to (-1). If applied_rule is set to MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE, the nwk_duty will be used by the entire network. If applied_rule is set to MESH_PS_NETWORK_DUTY_APPLIED_UPLINK, the nwk_duty will only be used by the up-link path nodes. The root does not accept MESH_PS_NETWORK_DUTY_APPLIED_UPLINK. A nwk_duty with duration_mins(-1) set by the root is the default network duty cycle used by the entire network. The range of nwk_duty values is 1 to 100. The default value is 10. nwk_duty is the network duty cycle the entire network or the up-link path will use. A device that successfully sets the nwk_duty is known as a NWK-DUTY-MASTER. duration_mins specifies how long the specified nwk_duty will be used. Once duration_mins expires, the root will take over as the NWK-DUTY-MASTER. If an existing NWK-DUTY-MASTER leaves the network, the root will take over as the NWK-DUTY-MASTER again. duration_mins = (-1) represents nwk_duty will be used until a new NWK-DUTY-MASTER with a different nwk_duty appears. Only the root can set duration_mins to (-1). If applied_rule is set to MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE, the nwk_duty will be used by the entire network. If applied_rule is set to MESH_PS_NETWORK_DUTY_APPLIED_UPLINK, the nwk_duty will only be used by the up-link path nodes. The root does not accept MESH_PS_NETWORK_DUTY_APPLIED_UPLINK. A nwk_duty with duration_mins(-1) set by the root is the default network duty cycle used by the entire network. Attention This API can be called at any time after mesh is started. In self-organized network, if this API is called before mesh is started in all devices, (1)nwk_duty shall be set to the same value for all devices; (2)duration_mins shall be set to (-1); (3)applied_rule shall be set to MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE; after the voted root appears, the root will become the NWK-DUTY-MASTER and broadcast the nwk_duty and its identity of NWK-DUTY-MASTER. If the root is specified (FIXED-ROOT), call this API in the root to provide a default nwk_duty for the entire network. After joins the network, any device can call this API to change the nwk_duty, duration_mins or applied_rule. In self-organized network, if this API is called before mesh is started in all devices, (1)nwk_duty shall be set to the same value for all devices; (2)duration_mins shall be set to (-1); (3)applied_rule shall be set to MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE; after the voted root appears, the root will become the NWK-DUTY-MASTER and broadcast the nwk_duty and its identity of NWK-DUTY-MASTER. If the root is specified (FIXED-ROOT), call this API in the root to provide a default nwk_duty for the entire network. After joins the network, any device can call this API to change the nwk_duty, duration_mins or applied_rule. In self-organized network, if this API is called before mesh is started in all devices, (1)nwk_duty shall be set to the same value for all devices; (2)duration_mins shall be set to (-1); (3)applied_rule shall be set to MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE; after the voted root appears, the root will become the NWK-DUTY-MASTER and broadcast the nwk_duty and its identity of NWK-DUTY-MASTER. Attention This API can be called at any time after mesh is started. In self-organized network, if this API is called before mesh is started in all devices, (1)nwk_duty shall be set to the same value for all devices; (2)duration_mins shall be set to (-1); (3)applied_rule shall be set to MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE; after the voted root appears, the root will become the NWK-DUTY-MASTER and broadcast the nwk_duty and its identity of NWK-DUTY-MASTER. If the root is specified (FIXED-ROOT), call this API in the root to provide a default nwk_duty for the entire network. After joins the network, any device can call this API to change the nwk_duty, duration_mins or applied_rule. Parameters nwk_duty -- [in] network duty cycle duration_mins -- [in] duration (unit: minutes) applied_rule -- [in] only support MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE nwk_duty -- [in] network duty cycle duration_mins -- [in] duration (unit: minutes) applied_rule -- [in] only support MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE nwk_duty -- [in] network duty cycle Returns ESP_OK ESP_FAIL ESP_OK ESP_FAIL ESP_OK Parameters nwk_duty -- [in] network duty cycle duration_mins -- [in] duration (unit: minutes) applied_rule -- [in] only support MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE Returns ESP_OK ESP_FAIL The range of nwk_duty values is 1 to 100. The default value is 10. esp_err_t esp_mesh_get_network_duty_cycle(int *nwk_duty, int *duration_mins, int *dev_duty_type, int *applied_rule) Get the network duty cycle, duration, type and rule. Parameters nwk_duty -- [out] current network duty cycle duration_mins -- [out] the duration of current nwk_duty dev_duty_type -- [out] if it includes MESH_PS_DEVICE_DUTY_MASTER, this device is the current NWK-DUTY-MASTER. applied_rule -- [out] MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE nwk_duty -- [out] current network duty cycle duration_mins -- [out] the duration of current nwk_duty dev_duty_type -- [out] if it includes MESH_PS_DEVICE_DUTY_MASTER, this device is the current NWK-DUTY-MASTER. applied_rule -- [out] MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE nwk_duty -- [out] current network duty cycle Returns ESP_OK ESP_OK ESP_OK Parameters nwk_duty -- [out] current network duty cycle duration_mins -- [out] the duration of current nwk_duty dev_duty_type -- [out] if it includes MESH_PS_DEVICE_DUTY_MASTER, this device is the current NWK-DUTY-MASTER. applied_rule -- [out] MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE Returns ESP_OK int esp_mesh_get_running_active_duty_cycle(void) Get the running active duty cycle. The running active duty cycle of the root is 100. If duty type is set to MESH_PS_DEVICE_DUTY_REQUEST, the running active duty cycle is nwk_duty provided by the network. If duty type is set to MESH_PS_DEVICE_DUTY_DEMAND, the running active duty cycle is dev_duty specified by the users. In a mesh network, devices are typically working with a certain duty-cycle (transmitting, receiving and sleep) to reduce the power consumption. The running active duty cycle decides the amount of awake time within a beacon interval. At each start of beacon interval, all devices wake up, broadcast beacons, and transmit packets if they do have pending packets for their parents or for their children. Note that Low-duty-cycle means devices may not be active in most of the time, the latency of data transmission might be greater. The running active duty cycle of the root is 100. If duty type is set to MESH_PS_DEVICE_DUTY_REQUEST, the running active duty cycle is nwk_duty provided by the network. If duty type is set to MESH_PS_DEVICE_DUTY_DEMAND, the running active duty cycle is dev_duty specified by the users. In a mesh network, devices are typically working with a certain duty-cycle (transmitting, receiving and sleep) to reduce the power consumption. The running active duty cycle decides the amount of awake time within a beacon interval. At each start of beacon interval, all devices wake up, broadcast beacons, and transmit packets if they do have pending packets for their parents or for their children. Note that Low-duty-cycle means devices may not be active in most of the time, the latency of data transmission might be greater. Returns the running active duty cycle Returns the running active duty cycle The running active duty cycle of the root is 100. Unions union mesh_addr_t #include <esp_mesh.h> Mesh address. union mesh_event_info_t #include <esp_mesh.h> Mesh event information. Public Members mesh_event_channel_switch_t channel_switch channel switch mesh_event_channel_switch_t channel_switch channel switch mesh_event_child_connected_t child_connected child connected mesh_event_child_connected_t child_connected child connected mesh_event_child_disconnected_t child_disconnected child disconnected mesh_event_child_disconnected_t child_disconnected child disconnected mesh_event_routing_table_change_t routing_table routing table change mesh_event_routing_table_change_t routing_table routing table change mesh_event_connected_t connected parent connected mesh_event_connected_t connected parent connected mesh_event_disconnected_t disconnected parent disconnected mesh_event_disconnected_t disconnected parent disconnected mesh_event_no_parent_found_t no_parent no parent found mesh_event_no_parent_found_t no_parent no parent found mesh_event_layer_change_t layer_change layer change mesh_event_layer_change_t layer_change layer change mesh_event_toDS_state_t toDS_state toDS state, devices shall check this state firstly before trying to send packets to external IP network. This state indicates right now whether the root is capable of sending packets out. If not, devices had better to wait until this state changes to be MESH_TODS_REACHABLE. mesh_event_toDS_state_t toDS_state toDS state, devices shall check this state firstly before trying to send packets to external IP network. This state indicates right now whether the root is capable of sending packets out. If not, devices had better to wait until this state changes to be MESH_TODS_REACHABLE. mesh_event_vote_started_t vote_started vote started mesh_event_vote_started_t vote_started vote started mesh_event_root_address_t root_addr root address mesh_event_root_address_t root_addr root address mesh_event_root_switch_req_t switch_req root switch request mesh_event_root_switch_req_t switch_req root switch request mesh_event_root_conflict_t root_conflict other powerful root mesh_event_root_conflict_t root_conflict other powerful root mesh_event_root_fixed_t root_fixed fixed root mesh_event_root_fixed_t root_fixed fixed root mesh_event_scan_done_t scan_done scan done mesh_event_scan_done_t scan_done scan done mesh_event_network_state_t network_state network state, such as whether current mesh network has a root. mesh_event_network_state_t network_state network state, such as whether current mesh network has a root. mesh_event_find_network_t find_network network found that can join mesh_event_find_network_t find_network network found that can join mesh_event_router_switch_t router_switch new router information mesh_event_router_switch_t router_switch new router information mesh_event_ps_duty_t ps_duty PS duty information mesh_event_ps_duty_t ps_duty PS duty information mesh_event_channel_switch_t channel_switch union mesh_rc_config_t #include <esp_mesh.h> Vote address configuration. Public Members int attempts max vote attempts before a new root is elected automatically by mesh network. (min:15, 15 by default) int attempts max vote attempts before a new root is elected automatically by mesh network. (min:15, 15 by default) mesh_addr_t rc_addr a new root address specified by users for API esp_mesh_waive_root() mesh_addr_t rc_addr a new root address specified by users for API esp_mesh_waive_root() int attempts Structures struct mip_t IP address and port. Public Members esp_ip4_addr_t ip4 IP address esp_ip4_addr_t ip4 IP address uint16_t port port uint16_t port port esp_ip4_addr_t ip4 struct mesh_event_channel_switch_t Channel switch information. Public Members uint8_t channel new channel uint8_t channel new channel uint8_t channel struct mesh_event_connected_t Parent connected information. Public Members wifi_event_sta_connected_t connected parent information, same as Wi-Fi event SYSTEM_EVENT_STA_CONNECTED does wifi_event_sta_connected_t connected parent information, same as Wi-Fi event SYSTEM_EVENT_STA_CONNECTED does uint16_t self_layer layer uint16_t self_layer layer uint8_t duty parent duty uint8_t duty parent duty wifi_event_sta_connected_t connected struct mesh_event_no_parent_found_t No parent found information. Public Members int scan_times scan times being through int scan_times scan times being through int scan_times struct mesh_event_layer_change_t Layer change information. Public Members uint16_t new_layer new layer uint16_t new_layer new layer uint16_t new_layer struct mesh_event_vote_started_t vote started information Public Members int reason vote reason, vote could be initiated by children or by the root itself int reason vote reason, vote could be initiated by children or by the root itself int attempts max vote attempts before stopped int attempts max vote attempts before stopped mesh_addr_t rc_addr root address specified by users via API esp_mesh_waive_root() mesh_addr_t rc_addr root address specified by users via API esp_mesh_waive_root() int reason struct mesh_event_find_network_t find a mesh network that this device can join struct mesh_event_root_switch_req_t Root switch request information. Public Members int reason root switch reason, generally root switch is initialized by users via API esp_mesh_waive_root() int reason root switch reason, generally root switch is initialized by users via API esp_mesh_waive_root() mesh_addr_t rc_addr the address of root switch requester mesh_addr_t rc_addr the address of root switch requester int reason struct mesh_event_root_conflict_t Other powerful root address. struct mesh_event_routing_table_change_t Routing table change. struct mesh_event_scan_done_t Scan done event information. Public Members uint8_t number the number of APs scanned uint8_t number the number of APs scanned uint8_t number struct mesh_event_network_state_t Network state information. Public Members bool is_rootless whether current mesh network has a root bool is_rootless whether current mesh network has a root bool is_rootless struct mesh_event_ps_duty_t PS duty information. Public Members uint8_t duty parent or child duty uint8_t duty parent or child duty mesh_event_child_connected_t child_connected child info mesh_event_child_connected_t child_connected child info uint8_t duty struct mesh_opt_t Mesh option. struct mesh_data_t Mesh data for esp_mesh_send() and esp_mesh_recv() Public Members uint8_t *data data uint8_t *data data uint16_t size data size uint16_t size data size mesh_proto_t proto data protocol mesh_proto_t proto data protocol mesh_tos_t tos data type of service mesh_tos_t tos data type of service uint8_t *data struct mesh_router_t Router configuration. Public Members uint8_t ssid[32] SSID uint8_t ssid[32] SSID uint8_t ssid_len length of SSID uint8_t ssid_len length of SSID uint8_t bssid[6] BSSID, if this value is specified, users should also specify "allow_router_switch". uint8_t bssid[6] BSSID, if this value is specified, users should also specify "allow_router_switch". uint8_t password[64] password uint8_t password[64] password bool allow_router_switch if the BSSID is specified and this value is also set, when the router of this specified BSSID fails to be found after "fail" (mesh_attempts_t) times, the whole network is allowed to switch to another router with the same SSID. The new router might also be on a different channel. The default value is false. There is a risk that if the password is different between the new switched router and the previous one, the mesh network could be established but the root will never connect to the new switched router. bool allow_router_switch if the BSSID is specified and this value is also set, when the router of this specified BSSID fails to be found after "fail" (mesh_attempts_t) times, the whole network is allowed to switch to another router with the same SSID. The new router might also be on a different channel. The default value is false. There is a risk that if the password is different between the new switched router and the previous one, the mesh network could be established but the root will never connect to the new switched router. uint8_t ssid[32] struct mesh_ap_cfg_t Mesh softAP configuration. struct mesh_cfg_t Mesh initialization configuration. Public Members uint8_t channel channel, the mesh network on uint8_t channel channel, the mesh network on bool allow_channel_switch if this value is set, when "fail" (mesh_attempts_t) times is reached, device will change to a full channel scan for a network that could join. The default value is false. bool allow_channel_switch if this value is set, when "fail" (mesh_attempts_t) times is reached, device will change to a full channel scan for a network that could join. The default value is false. mesh_addr_t mesh_id mesh network identification mesh_addr_t mesh_id mesh network identification mesh_router_t router router configuration mesh_router_t router router configuration mesh_ap_cfg_t mesh_ap mesh softAP configuration mesh_ap_cfg_t mesh_ap mesh softAP configuration const mesh_crypto_funcs_t *crypto_funcs crypto functions const mesh_crypto_funcs_t *crypto_funcs crypto functions uint8_t channel struct mesh_vote_t Vote. Public Members float percentage vote percentage threshold for approval of being a root float percentage vote percentage threshold for approval of being a root bool is_rc_specified if true, rc_addr shall be specified (Unimplemented). if false, attempts value shall be specified to make network start root election. bool is_rc_specified if true, rc_addr shall be specified (Unimplemented). if false, attempts value shall be specified to make network start root election. mesh_rc_config_t config vote address configuration mesh_rc_config_t config vote address configuration float percentage struct mesh_tx_pending_t The number of packets pending in the queue waiting to be sent by the mesh stack. struct mesh_rx_pending_t The number of packets available in the queue waiting to be received by applications. Macros MESH_ROOT_LAYER root layer value MESH_MTU max transmit unit(in bytes) MESH_MPS max payload size(in bytes) ESP_ERR_MESH_WIFI_NOT_START Mesh error code definition. Wi-Fi isn't started ESP_ERR_MESH_NOT_INIT mesh isn't initialized ESP_ERR_MESH_NOT_CONFIG mesh isn't configured ESP_ERR_MESH_NOT_START mesh isn't started ESP_ERR_MESH_NOT_SUPPORT not supported yet ESP_ERR_MESH_NOT_ALLOWED operation is not allowed ESP_ERR_MESH_NO_MEMORY out of memory ESP_ERR_MESH_ARGUMENT illegal argument ESP_ERR_MESH_EXCEED_MTU packet size exceeds MTU ESP_ERR_MESH_TIMEOUT timeout ESP_ERR_MESH_DISCONNECTED disconnected with parent on station interface ESP_ERR_MESH_QUEUE_FAIL queue fail ESP_ERR_MESH_QUEUE_FULL queue full ESP_ERR_MESH_NO_PARENT_FOUND no parent found to join the mesh network ESP_ERR_MESH_NO_ROUTE_FOUND no route found to forward the packet ESP_ERR_MESH_OPTION_NULL no option found ESP_ERR_MESH_OPTION_UNKNOWN unknown option ESP_ERR_MESH_XON_NO_WINDOW no window for software flow control on upstream ESP_ERR_MESH_INTERFACE low-level Wi-Fi interface error ESP_ERR_MESH_DISCARD_DUPLICATE discard the packet due to the duplicate sequence number ESP_ERR_MESH_DISCARD discard the packet ESP_ERR_MESH_VOTING vote in progress ESP_ERR_MESH_XMIT XMIT ESP_ERR_MESH_QUEUE_READ error in reading queue ESP_ERR_MESH_PS mesh PS is not specified as enable or disable ESP_ERR_MESH_RECV_RELEASE release esp_mesh_recv_toDS MESH_DATA_ENC Flags bitmap for esp_mesh_send() and esp_mesh_recv() data encrypted (Unimplemented) MESH_DATA_P2P point-to-point delivery over the mesh network MESH_DATA_FROMDS receive from external IP network MESH_DATA_TODS identify this packet is target to external IP network MESH_DATA_NONBLOCK esp_mesh_send() non-block MESH_DATA_DROP in the situation of the root having been changed, identify this packet can be dropped by new root MESH_DATA_GROUP identify this packet is target to a group address MESH_OPT_SEND_GROUP Option definitions for esp_mesh_send() and esp_mesh_recv() data transmission by group; used with esp_mesh_send() and shall have payload MESH_OPT_RECV_DS_ADDR return a remote IP address; used with esp_mesh_send() and esp_mesh_recv() MESH_ASSOC_FLAG_MAP_ASSOC Flag of mesh networking IE. Mesh AP doesn't detect children leave yet MESH_ASSOC_FLAG_VOTE_IN_PROGRESS station in vote, set when root vote start, clear when connect to router or when root switch MESH_ASSOC_FLAG_STA_VOTED station vote done, set when connect to router MESH_ASSOC_FLAG_NETWORK_FREE no root in current network MESH_ASSOC_FLAG_STA_VOTE_EXPIRE the voted address is expired, means the voted device lose the chance to be root MESH_ASSOC_FLAG_ROOTS_FOUND roots conflict is found, means that thre are at least two roots in the mesh network MESH_ASSOC_FLAG_ROOT_FIXED the root is fixed in the mesh network MESH_PS_DEVICE_DUTY_REQUEST Mesh PS (Power Save) duty cycle type. requests to join a network PS without specifying a device duty cycle. After the device joins the network, a network duty cycle will be provided by the network MESH_PS_DEVICE_DUTY_DEMAND requests to join a network PS and specifies a demanded device duty cycle MESH_PS_NETWORK_DUTY_MASTER indicates the device is the NWK-DUTY-MASTER (network duty cycle master) MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE Mesh PS (Power Save) duty cycle applied rule. MESH_PS_NETWORK_DUTY_APPLIED_UPLINK MESH_INIT_CONFIG_DEFAULT() Type Definitions typedef mesh_addr_t mesh_event_root_address_t Root address. typedef wifi_event_sta_disconnected_t mesh_event_disconnected_t Parent disconnected information. typedef wifi_event_ap_staconnected_t mesh_event_child_connected_t Child connected information. typedef wifi_event_ap_stadisconnected_t mesh_event_child_disconnected_t Child disconnected information. typedef wifi_event_sta_connected_t mesh_event_router_switch_t New router information. Enumerations enum mesh_event_id_t Enumerated list of mesh event id. Values: enumerator MESH_EVENT_STARTED mesh is started enumerator MESH_EVENT_STARTED mesh is started enumerator MESH_EVENT_STOPPED mesh is stopped enumerator MESH_EVENT_STOPPED mesh is stopped enumerator MESH_EVENT_CHANNEL_SWITCH channel switch enumerator MESH_EVENT_CHANNEL_SWITCH channel switch enumerator MESH_EVENT_CHILD_CONNECTED a child is connected on softAP interface enumerator MESH_EVENT_CHILD_CONNECTED a child is connected on softAP interface enumerator MESH_EVENT_CHILD_DISCONNECTED a child is disconnected on softAP interface enumerator MESH_EVENT_CHILD_DISCONNECTED a child is disconnected on softAP interface enumerator MESH_EVENT_ROUTING_TABLE_ADD routing table is changed by adding newly joined children enumerator MESH_EVENT_ROUTING_TABLE_ADD routing table is changed by adding newly joined children enumerator MESH_EVENT_ROUTING_TABLE_REMOVE routing table is changed by removing leave children enumerator MESH_EVENT_ROUTING_TABLE_REMOVE routing table is changed by removing leave children enumerator MESH_EVENT_PARENT_CONNECTED parent is connected on station interface enumerator MESH_EVENT_PARENT_CONNECTED parent is connected on station interface enumerator MESH_EVENT_PARENT_DISCONNECTED parent is disconnected on station interface enumerator MESH_EVENT_PARENT_DISCONNECTED parent is disconnected on station interface enumerator MESH_EVENT_NO_PARENT_FOUND no parent found enumerator MESH_EVENT_NO_PARENT_FOUND no parent found enumerator MESH_EVENT_LAYER_CHANGE layer changes over the mesh network enumerator MESH_EVENT_LAYER_CHANGE layer changes over the mesh network enumerator MESH_EVENT_TODS_STATE state represents whether the root is able to access external IP network. This state is a manual event that needs to be triggered with esp_mesh_post_toDS_state(). enumerator MESH_EVENT_TODS_STATE state represents whether the root is able to access external IP network. This state is a manual event that needs to be triggered with esp_mesh_post_toDS_state(). enumerator MESH_EVENT_VOTE_STARTED the process of voting a new root is started either by children or by the root enumerator MESH_EVENT_VOTE_STARTED the process of voting a new root is started either by children or by the root enumerator MESH_EVENT_VOTE_STOPPED the process of voting a new root is stopped enumerator MESH_EVENT_VOTE_STOPPED the process of voting a new root is stopped enumerator MESH_EVENT_ROOT_ADDRESS the root address is obtained. It is posted by mesh stack automatically. enumerator MESH_EVENT_ROOT_ADDRESS the root address is obtained. It is posted by mesh stack automatically. enumerator MESH_EVENT_ROOT_SWITCH_REQ root switch request sent from a new voted root candidate enumerator MESH_EVENT_ROOT_SWITCH_REQ root switch request sent from a new voted root candidate enumerator MESH_EVENT_ROOT_SWITCH_ACK root switch acknowledgment responds the above request sent from current root enumerator MESH_EVENT_ROOT_SWITCH_ACK root switch acknowledgment responds the above request sent from current root enumerator MESH_EVENT_ROOT_ASKED_YIELD the root is asked yield by a more powerful existing root. If self organized is disabled and this device is specified to be a root by users, users should set a new parent for this device. if self organized is enabled, this device will find a new parent by itself, users could ignore this event. enumerator MESH_EVENT_ROOT_ASKED_YIELD the root is asked yield by a more powerful existing root. If self organized is disabled and this device is specified to be a root by users, users should set a new parent for this device. if self organized is enabled, this device will find a new parent by itself, users could ignore this event. enumerator MESH_EVENT_ROOT_FIXED when devices join a network, if the setting of Fixed Root for one device is different from that of its parent, the device will update the setting the same as its parent's. Fixed Root Setting of each device is variable as that setting changes of the root. enumerator MESH_EVENT_ROOT_FIXED when devices join a network, if the setting of Fixed Root for one device is different from that of its parent, the device will update the setting the same as its parent's. Fixed Root Setting of each device is variable as that setting changes of the root. enumerator MESH_EVENT_SCAN_DONE if self-organized networking is disabled, user can call esp_wifi_scan_start() to trigger this event, and add the corresponding scan done handler in this event. enumerator MESH_EVENT_SCAN_DONE if self-organized networking is disabled, user can call esp_wifi_scan_start() to trigger this event, and add the corresponding scan done handler in this event. enumerator MESH_EVENT_NETWORK_STATE network state, such as whether current mesh network has a root. enumerator MESH_EVENT_NETWORK_STATE network state, such as whether current mesh network has a root. enumerator MESH_EVENT_STOP_RECONNECTION the root stops reconnecting to the router and non-root devices stop reconnecting to their parents. enumerator MESH_EVENT_STOP_RECONNECTION the root stops reconnecting to the router and non-root devices stop reconnecting to their parents. enumerator MESH_EVENT_FIND_NETWORK when the channel field in mesh configuration is set to zero, mesh stack will perform a full channel scan to find a mesh network that can join, and return the channel value after finding it. enumerator MESH_EVENT_FIND_NETWORK when the channel field in mesh configuration is set to zero, mesh stack will perform a full channel scan to find a mesh network that can join, and return the channel value after finding it. enumerator MESH_EVENT_ROUTER_SWITCH if users specify BSSID of the router in mesh configuration, when the root connects to another router with the same SSID, this event will be posted and the new router information is attached. enumerator MESH_EVENT_ROUTER_SWITCH if users specify BSSID of the router in mesh configuration, when the root connects to another router with the same SSID, this event will be posted and the new router information is attached. enumerator MESH_EVENT_PS_PARENT_DUTY parent duty enumerator MESH_EVENT_PS_PARENT_DUTY parent duty enumerator MESH_EVENT_PS_CHILD_DUTY child duty enumerator MESH_EVENT_PS_CHILD_DUTY child duty enumerator MESH_EVENT_PS_DEVICE_DUTY device duty enumerator MESH_EVENT_PS_DEVICE_DUTY device duty enumerator MESH_EVENT_MAX enumerator MESH_EVENT_MAX enumerator MESH_EVENT_STARTED enum mesh_type_t Device type. Values: enumerator MESH_IDLE hasn't joined the mesh network yet enumerator MESH_IDLE hasn't joined the mesh network yet enumerator MESH_ROOT the only sink of the mesh network. Has the ability to access external IP network enumerator MESH_ROOT the only sink of the mesh network. Has the ability to access external IP network enumerator MESH_NODE intermediate device. Has the ability to forward packets over the mesh network enumerator MESH_NODE intermediate device. Has the ability to forward packets over the mesh network enumerator MESH_LEAF has no forwarding ability enumerator MESH_LEAF has no forwarding ability enumerator MESH_STA connect to router with a standlone Wi-Fi station mode, no network expansion capability enumerator MESH_STA connect to router with a standlone Wi-Fi station mode, no network expansion capability enumerator MESH_IDLE enum mesh_proto_t Protocol of transmitted application data. Values: enumerator MESH_PROTO_BIN binary enumerator MESH_PROTO_BIN binary enumerator MESH_PROTO_HTTP HTTP protocol enumerator MESH_PROTO_HTTP HTTP protocol enumerator MESH_PROTO_JSON JSON format enumerator MESH_PROTO_JSON JSON format enumerator MESH_PROTO_MQTT MQTT protocol enumerator MESH_PROTO_MQTT MQTT protocol enumerator MESH_PROTO_AP IP network mesh communication of node's AP interface enumerator MESH_PROTO_AP IP network mesh communication of node's AP interface enumerator MESH_PROTO_STA IP network mesh communication of node's STA interface enumerator MESH_PROTO_STA IP network mesh communication of node's STA interface enumerator MESH_PROTO_BIN enum mesh_tos_t For reliable transmission, mesh stack provides three type of services. Values: enumerator MESH_TOS_P2P provide P2P (point-to-point) retransmission on mesh stack by default enumerator MESH_TOS_P2P provide P2P (point-to-point) retransmission on mesh stack by default enumerator MESH_TOS_E2E provide E2E (end-to-end) retransmission on mesh stack (Unimplemented) enumerator MESH_TOS_E2E provide E2E (end-to-end) retransmission on mesh stack (Unimplemented) enumerator MESH_TOS_DEF no retransmission on mesh stack enumerator MESH_TOS_DEF no retransmission on mesh stack enumerator MESH_TOS_P2P enum mesh_vote_reason_t Vote reason. Values: enumerator MESH_VOTE_REASON_ROOT_INITIATED vote is initiated by the root enumerator MESH_VOTE_REASON_ROOT_INITIATED vote is initiated by the root enumerator MESH_VOTE_REASON_CHILD_INITIATED vote is initiated by children enumerator MESH_VOTE_REASON_CHILD_INITIATED vote is initiated by children enumerator MESH_VOTE_REASON_ROOT_INITIATED enum mesh_disconnect_reason_t Mesh disconnect reason code. Values: enumerator MESH_REASON_CYCLIC cyclic is detected enumerator MESH_REASON_CYCLIC cyclic is detected enumerator MESH_REASON_PARENT_IDLE parent is idle enumerator MESH_REASON_PARENT_IDLE parent is idle enumerator MESH_REASON_LEAF the connected device is changed to a leaf enumerator MESH_REASON_LEAF the connected device is changed to a leaf enumerator MESH_REASON_DIFF_ID in different mesh ID enumerator MESH_REASON_DIFF_ID in different mesh ID enumerator MESH_REASON_ROOTS root conflict is detected enumerator MESH_REASON_ROOTS root conflict is detected enumerator MESH_REASON_PARENT_STOPPED parent has stopped the mesh enumerator MESH_REASON_PARENT_STOPPED parent has stopped the mesh enumerator MESH_REASON_SCAN_FAIL scan fail enumerator MESH_REASON_SCAN_FAIL scan fail enumerator MESH_REASON_IE_UNKNOWN unknown IE enumerator MESH_REASON_IE_UNKNOWN unknown IE enumerator MESH_REASON_WAIVE_ROOT waive root enumerator MESH_REASON_WAIVE_ROOT waive root enumerator MESH_REASON_PARENT_WORSE parent with very poor RSSI enumerator MESH_REASON_PARENT_WORSE parent with very poor RSSI enumerator MESH_REASON_EMPTY_PASSWORD use an empty password to connect to an encrypted parent enumerator MESH_REASON_EMPTY_PASSWORD use an empty password to connect to an encrypted parent enumerator MESH_REASON_PARENT_UNENCRYPTED connect to an unencrypted parent/router enumerator MESH_REASON_PARENT_UNENCRYPTED connect to an unencrypted parent/router enumerator MESH_REASON_CYCLIC enum esp_mesh_topology_t Mesh topology. Values: enumerator MESH_TOPO_TREE tree topology enumerator MESH_TOPO_TREE tree topology enumerator MESH_TOPO_CHAIN chain topology enumerator MESH_TOPO_CHAIN chain topology enumerator MESH_TOPO_TREE
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 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 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. System Events An application interfaces with ESP-WIFI-MESH via ESP-WIFI-MESH Events. 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. The 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 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 MESH_EVENT_PARENT_CONNECTED and MESH_EVENT_CHILD_CONNECTED to indicate when a node can begin transmitting data upstream and downstream respectively. Likewise, IP_EVENT_STA_GOT_IP and 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 esp_mesh_start() is called, and before 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. Each node that could become root is required to initialize LwIP by calling 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 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. 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: Initialize Mesh The following code snippet demonstrates how to initialize ESP-WIFI-MESH /* 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)); Configuring an ESP-WIFI-MESH Network ESP-WIFI-MESH is configured via esp_mesh_set_config() which receives its arguments using the mesh_cfg_t structure. The structure contains the following parameters used to configure ESP-WIFI-MESH: | Parameter | Description | Channel | Range from 1 to 14 | Mesh ID | ID of ESP-WIFI-MESH Network, see | Router | Router Configuration, see | Mesh AP | Mesh AP Configuration, see | Crypto Functions | Crypto Functions for Mesh IE, see The following code snippet demonstrates how to configure ESP-WIFI-MESH. /* 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)); Start Mesh The following code snippet demonstrates how to start ESP-WIFI-MESH. /* 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. After connecting, the application can start transmitting and receiving packets over the ESP-WIFI-MESH network using esp_mesh_send() and esp_mesh_recv(). 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 Building a Network) Selection of a preferred parent node (see Parent Node Selection in Building a Network) Automatic reconnection upon detecting a disconnection (see Intermediate Parent Node Failure in Managing a Network) When self-organized networking is enabled, the ESP-WIFI-MESH stack will internally make calls to Wi-Fi APIs. 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 esp_mesh_set_self_organized() function. The function has the two following parameters: bool enablespecifies whether to enable or disable self-organized networking. bool select_parentspecifies 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. //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. 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 | | Y | | Y | N | | Y | The following code snipping demonstrates how to enable self-organized networking. //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 esp_mesh_set_self_organized() which disable and enable self-organized networking. The following code snippet demonstrates how an application can safely call esp_wifi_scan_start() whilst using ESP-WIFI-MESH. //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 Application Examples ESP-IDF contains these ESP-WIFI-MESH example projects: 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. 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. API Reference Header File This header file can be included with: #include "esp_mesh.h" This header file is a part of the API provided by the esp_wificomponent. To declare that your component depends on esp_wifi, add the following to your CMakeLists.txt: REQUIRES esp_wifi or PRIV_REQUIRES esp_wifi Functions - esp_err_t esp_mesh_init(void) Mesh initialization. Check whether Wi-Fi is started. Initialize mesh global variables with default values. - Attention This API shall be called after Wi-Fi is started. - Returns ESP_OK ESP_FAIL - - - esp_err_t esp_mesh_deinit(void) Mesh de-initialization. - Release resources and stop the mesh - Returns ESP_OK ESP_FAIL - - esp_err_t esp_mesh_start(void) Start mesh. Initialize mesh IE. Start mesh network management service. Create TX and RX queues according to the configuration. Register mesh packets receive callback. - Attention This API shall be called after mesh initialization and configuration. - Returns ESP_OK ESP_FAIL ESP_ERR_MESH_NOT_INIT ESP_ERR_MESH_NOT_CONFIG ESP_ERR_MESH_NO_MEMORY - - - esp_err_t esp_mesh_stop(void) Stop mesh. Deinitialize mesh IE. Disconnect with current parent. Disassociate all currently associated children. Stop mesh network management service. Unregister mesh packets receive callback. Delete TX and RX queues. Release resources. Restore Wi-Fi softAP to default settings if Wi-Fi dual mode is enabled. Set Wi-Fi Power Save type to WIFI_PS_NONE. - Returns ESP_OK ESP_FAIL - - - esp_err_t esp_mesh_send(const mesh_addr_t *to, const mesh_data_t *data, int flag, const mesh_opt_t opt[], int opt_count) Send a packet over the mesh network. Send a packet to any device in the mesh network. Send a packet to external IP network. - Attention This API is not reentrant. - Parameters to -- [in] the address of the final destination of the packet If the packet is to the root, set this parameter to NULL. If the packet is to an external IP network, set this parameter to the IPv4:PORT combination. This packet will be delivered to the root firstly, then the root will forward this packet to the final IP server address. - data -- [in] pointer to a sending mesh packet Field size should not exceed MESH_MPS. Note that the size of one mesh packet should not exceed MESH_MTU. Field proto should be set to data protocol in use (default is MESH_PROTO_BIN for binary). Field tos should be set to transmission tos (type of service) in use (default is MESH_TOS_P2P for point-to-point reliable). - flag -- [in] bitmap for data sent Speed up the route search If the packet is to the root and "to" parameter is NULL, set this parameter to 0. If the packet is to an internal device, MESH_DATA_P2P should be set. If the packet is to the root ("to" parameter isn't NULL) or to external IP network, MESH_DATA_TODS should be set. If the packet is from the root to an internal device, MESH_DATA_FROMDS should be set. - Specify whether this API is block or non-block, block by default If needs non-blocking, MESH_DATA_NONBLOCK should be set. Otherwise, may use esp_mesh_send_block_time() to specify a blocking time. - In the situation of the root change, MESH_DATA_DROP identifies this packet can be dropped by the new root for upstream data to external IP network, we try our best to avoid data loss caused by the root change, but there is a risk that the new root is running out of memory because most of memory is occupied by the pending data which isn't read out in time by esp_mesh_recv_toDS(). Generally, we suggest esp_mesh_recv_toDS() is called after a connection with IP network is created. Thus data outgoing to external IP network via socket is just from reading esp_mesh_recv_toDS() which avoids unnecessary memory copy. - opt -- [in] options In case of sending a packet to a certain group, MESH_OPT_SEND_GROUP is a good choice. In this option, the value field should be set to the target receiver addresses in this group. Root sends a packet to an internal device, this packet is from external IP network in case the receiver device responds this packet, MESH_OPT_RECV_DS_ADDR is required to attach the target DS address. - opt_count -- [in] option count Currently, this API only takes one option, so opt_count is only supported to be 1. - - - Returns ESP_OK ESP_FAIL ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_START ESP_ERR_MESH_DISCONNECTED ESP_ERR_MESH_OPT_UNKNOWN ESP_ERR_MESH_EXCEED_MTU ESP_ERR_MESH_NO_MEMORY ESP_ERR_MESH_TIMEOUT ESP_ERR_MESH_QUEUE_FULL ESP_ERR_MESH_NO_ROUTE_FOUND ESP_ERR_MESH_DISCARD - - - esp_err_t esp_mesh_send_block_time(uint32_t time_ms) Set blocking time of esp_mesh_send() - Attention This API shall be called before mesh is started. - Parameters time_ms -- [in] blocking time of esp_mesh_send(), unit:ms - Returns ESP_OK - - esp_err_t esp_mesh_recv(mesh_addr_t *from, mesh_data_t *data, int timeout_ms, int *flag, mesh_opt_t opt[], int opt_count) Receive a packet targeted to self over the mesh network. flag could be MESH_DATA_FROMDS or MESH_DATA_TODS. - Attention Mesh RX queue should be checked regularly to avoid running out of memory. Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting to be received by applications. - - Parameters from -- [out] the address of the original source of the packet data -- [out] pointer to the received mesh packet Field proto is the data protocol in use. Should follow it to parse the received data. Field tos is the transmission tos (type of service) in use. - timeout_ms -- [in] wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever) flag -- [out] bitmap for data received MESH_DATA_FROMDS represents data from external IP network MESH_DATA_TODS represents data directed upward within the mesh network - opt -- [out] options desired to receive MESH_OPT_RECV_DS_ADDR attaches the DS address - opt_count -- [in] option count desired to receive Currently, this API only takes one option, so opt_count is only supported to be 1. - - - Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_START ESP_ERR_MESH_TIMEOUT ESP_ERR_MESH_DISCARD - - esp_err_t esp_mesh_recv_toDS(mesh_addr_t *from, mesh_addr_t *to, mesh_data_t *data, int timeout_ms, int *flag, mesh_opt_t opt[], int opt_count) Receive a packet targeted to external IP network. Root uses this API to receive packets destined to external IP network Root forwards the received packets to the final destination via socket. If no socket connection is ready to send out the received packets and this esp_mesh_recv_toDS() hasn't been called by applications, packets from the whole mesh network will be pending in toDS queue. Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting to be received by applications in case of running out of memory in the root. Using esp_mesh_set_xon_qsize() users may configure the RX queue size, default:32. If this size is too large, and esp_mesh_recv_toDS() isn't called in time, there is a risk that a great deal of memory is occupied by the pending packets. If this size is too small, it will impact the efficiency on upstream. How to decide this value depends on the specific application scenarios. flag could be MESH_DATA_TODS. - Attention This API is only called by the root. - Parameters from -- [out] the address of the original source of the packet to -- [out] the address contains remote IP address and port (IPv4:PORT) data -- [out] pointer to the received packet Contain the protocol and applications should follow it to parse the data. - timeout_ms -- [in] wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever) flag -- [out] bitmap for data received MESH_DATA_TODS represents the received data target to external IP network. Root shall forward this data to external IP network via the association with router. - opt -- [out] options desired to receive opt_count -- [in] option count desired to receive - - Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_START ESP_ERR_MESH_TIMEOUT ESP_ERR_MESH_DISCARD ESP_ERR_MESH_RECV_RELEASE - - - esp_err_t esp_mesh_set_config(const mesh_cfg_t *config) Set mesh stack configuration. Use MESH_INIT_CONFIG_DEFAULT() to initialize the default values, mesh IE is encrypted by default. Mesh network is established on a fixed channel (1-14). Mesh event callback is mandatory. Mesh ID is an identifier of an MBSS. Nodes with the same mesh ID can communicate with each other. Regarding to the router configuration, if the router is hidden, BSSID field is mandatory. If BSSID field isn't set and there exists more than one router with same SSID, there is a risk that more roots than one connected with different BSSID will appear. It means more than one mesh network is established with the same mesh ID. Root conflict function could eliminate redundant roots connected with the same BSSID, but couldn't handle roots connected with different BSSID. Because users might have such requirements of setting up routers with same SSID for the future replacement. But in that case, if the above situations happen, please make sure applications implement forward functions on the root to guarantee devices in different mesh networks can communicate with each other. max_connection of mesh softAP is limited by the max number of Wi-Fi softAP supported (max:10). - Attention This API shall be called before mesh is started after mesh is initialized. - Parameters config -- [in] pointer to mesh stack configuration - Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED - - - esp_err_t esp_mesh_get_config(mesh_cfg_t *config) Get mesh stack configuration. - Parameters config -- [out] pointer to mesh stack configuration - Returns ESP_OK ESP_ERR_MESH_ARGUMENT - - esp_err_t esp_mesh_set_router(const mesh_router_t *router) Get router configuration. - Attention This API is used to dynamically modify the router configuration after mesh is configured. - Parameters router -- [in] pointer to router configuration - Returns ESP_OK ESP_ERR_MESH_ARGUMENT - - esp_err_t esp_mesh_get_router(mesh_router_t *router) Get router configuration. - Parameters router -- [out] pointer to router configuration - Returns ESP_OK ESP_ERR_MESH_ARGUMENT - - esp_err_t esp_mesh_set_id(const mesh_addr_t *id) Set mesh network ID. - Attention This API is used to dynamically modify the mesh network ID. - Parameters id -- [in] pointer to mesh network ID - Returns ESP_OK ESP_ERR_MESH_ARGUMENT: invalid argument - - esp_err_t esp_mesh_get_id(mesh_addr_t *id) Get mesh network ID. - Parameters id -- [out] pointer to mesh network ID - Returns ESP_OK ESP_ERR_MESH_ARGUMENT - - esp_err_t esp_mesh_set_type(mesh_type_t type) Designate device type over the mesh network. MESH_IDLE: designates a device as a self-organized node for a mesh network MESH_ROOT: designates the root node for a mesh network MESH_LEAF: designates a device as a standalone Wi-Fi station that connects to a parent MESH_STA: designates a device as a standalone Wi-Fi station that connects to a router - Parameters type -- [in] device type - Returns ESP_OK ESP_ERR_MESH_NOT_ALLOWED - - - mesh_type_t esp_mesh_get_type(void) Get device type over mesh network. - Attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. - Returns mesh type - esp_err_t esp_mesh_set_max_layer(int max_layer) Set network max layer value. for tree topology, the max is 25. for chain topology, the max is 1000. Network max layer limits the max hop count. - Attention This API shall be called before mesh is started. - Parameters max_layer -- [in] max layer value - Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED - - - int esp_mesh_get_max_layer(void) Get max layer value. - Returns max layer value - esp_err_t esp_mesh_set_ap_password(const uint8_t *pwd, int len) Set mesh softAP password. - Attention This API shall be called before mesh is started. - Parameters pwd -- [in] pointer to the password len -- [in] password length - - Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED - - esp_err_t esp_mesh_set_ap_authmode(wifi_auth_mode_t authmode) Set mesh softAP authentication mode. - Attention This API shall be called before mesh is started. - Parameters authmode -- [in] authentication mode - Returns ESP_OK ESP_ERR_MESH_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED - - wifi_auth_mode_t esp_mesh_get_ap_authmode(void) Get mesh softAP authentication mode. - Returns authentication mode - esp_err_t esp_mesh_set_ap_connections(int connections) Set mesh max connection value. Set mesh softAP max connection = mesh max connection + non-mesh max connection - Attention This API shall be called before mesh is started. - Parameters connections -- [in] the number of max connections - Returns ESP_OK ESP_ERR_MESH_ARGUMENT - - - int esp_mesh_get_ap_connections(void) Get mesh max connection configuration. - Returns the number of mesh max connections - int esp_mesh_get_non_mesh_connections(void) Get non-mesh max connection configuration. - Returns the number of non-mesh max connections - int esp_mesh_get_layer(void) Get current layer value over the mesh network. - Attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. - Returns layer value - esp_err_t esp_mesh_get_parent_bssid(mesh_addr_t *bssid) Get the parent BSSID. - Attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. - Parameters bssid -- [out] pointer to parent BSSID - Returns ESP_OK ESP_FAIL - - bool esp_mesh_is_root(void) Return whether the device is the root node of the network. - Returns true/false - esp_err_t esp_mesh_set_self_organized(bool enable, bool select_parent) Enable/disable self-organized networking. Self-organized networking has three main functions: select the root node; find a preferred parent; initiate reconnection if a disconnection is detected. Self-organized networking is enabled by default. If self-organized is disabled, users should set a parent for the device via esp_mesh_set_parent(). - Attention This API is used to dynamically modify whether to enable the self organizing. - Parameters enable -- [in] enable or disable self-organized networking select_parent -- [in] Only valid when self-organized networking is enabled. if select_parent is set to true, the root will give up its mesh root status and search for a new parent like other non-root devices. - - - Returns ESP_OK ESP_FAIL - - - bool esp_mesh_get_self_organized(void) Return whether enable self-organized networking or not. - Returns true/false - esp_err_t esp_mesh_waive_root(const mesh_vote_t *vote, int reason) Cause the root device to give up (waive) its mesh root status. A device is elected root primarily based on RSSI from the external router. If external router conditions change, users can call this API to perform a root switch. In this API, users could specify a desired root address to replace itself or specify an attempts value to ask current root to initiate a new round of voting. During the voting, a better root candidate would be expected to find to replace the current one. If no desired root candidate, the vote will try a specified number of attempts (at least 15). If no better root candidate is found, keep the current one. If a better candidate is found, the new better one will send a root switch request to the current root, current root will respond with a root switch acknowledgment. After that, the new candidate will connect to the router to be a new root, the previous root will disconnect with the router and choose another parent instead. Root switch is completed with minimal disruption to the whole mesh network. - Attention This API is only called by the root. - Parameters vote -- [in] vote configuration If this parameter is set NULL, the vote will perform the default 15 times. Field percentage threshold is 0.9 by default. Field is_rc_specified shall be false. Field attempts shall be at least 15 times. - reason -- [in] only accept MESH_VOTE_REASON_ROOT_INITIATED for now - - Returns ESP_OK ESP_ERR_MESH_QUEUE_FULL ESP_ERR_MESH_DISCARD ESP_FAIL - - - esp_err_t esp_mesh_set_vote_percentage(float percentage) Set vote percentage threshold for approval of being a root (default:0.9) During the networking, only obtaining vote percentage reaches this threshold, the device could be a root. - Attention This API shall be called before mesh is started. - Parameters percentage -- [in] vote percentage threshold - Returns ESP_OK ESP_FAIL - - - float esp_mesh_get_vote_percentage(void) Get vote percentage threshold for approval of being a root. - Returns percentage threshold - esp_err_t esp_mesh_set_ap_assoc_expire(int seconds) Set mesh softAP associate expired time (default:10 seconds) If mesh softAP hasn't received any data from an associated child within this time, mesh softAP will take this child inactive and disassociate it. If mesh softAP is encrypted, this value should be set a greater value, such as 30 seconds. - Parameters seconds -- [in] the expired time - Returns ESP_OK ESP_FAIL - - - int esp_mesh_get_ap_assoc_expire(void) Get mesh softAP associate expired time. - Returns seconds - int esp_mesh_get_total_node_num(void) Get total number of devices in current network (including the root) - Attention The returned value might be incorrect when the network is changing. - Returns total number of devices (including the root) - int esp_mesh_get_routing_table_size(void) Get the number of devices in this device's sub-network (including self) - Returns the number of devices over this device's sub-network (including self) - esp_err_t esp_mesh_get_routing_table(mesh_addr_t *mac, int len, int *size) Get routing table of this device's sub-network (including itself) - Parameters mac -- [out] pointer to routing table len -- [in] routing table size(in bytes) size -- [out] pointer to the number of devices in routing table (including itself) - - Returns ESP_OK ESP_ERR_MESH_ARGUMENT - - esp_err_t esp_mesh_post_toDS_state(bool reachable) Post the toDS state to the mesh stack. - Attention This API is only for the root. - Parameters reachable -- [in] this state represents whether the root is able to access external IP network - Returns ESP_OK ESP_FAIL - - esp_err_t esp_mesh_get_tx_pending(mesh_tx_pending_t *pending) Return the number of packets pending in the queue waiting to be sent by the mesh stack. - Parameters pending -- [out] pointer to the TX pending - Returns ESP_OK ESP_FAIL - - esp_err_t esp_mesh_get_rx_pending(mesh_rx_pending_t *pending) Return the number of packets available in the queue waiting to be received by applications. - Parameters pending -- [out] pointer to the RX pending - Returns ESP_OK ESP_FAIL - - int esp_mesh_available_txupQ_num(const mesh_addr_t *addr, uint32_t *xseqno_in) Return the number of packets could be accepted from the specified address. - Parameters addr -- [in] self address or an associate children address xseqno_in -- [out] sequence number of the last received packet from the specified address - - Returns the number of upQ for a certain address - esp_err_t esp_mesh_set_xon_qsize(int qsize) Set the number of RX queue for the node, the average number of window allocated to one of its child node is: wnd = xon_qsize / (2 * max_connection + 1). However, the window of each child node is not strictly equal to the average value, it is affected by the traffic also. - Attention This API shall be called before mesh is started. - Parameters qsize -- [in] default:32 (min:16) - Returns ESP_OK ESP_FAIL - - int esp_mesh_get_xon_qsize(void) Get queue size. - Returns the number of queue - esp_err_t esp_mesh_allow_root_conflicts(bool allowed) Set whether allow more than one root existing in one network. - Parameters allowed -- [in] allow or not - Returns ESP_OK ESP_WIFI_ERR_NOT_INIT ESP_WIFI_ERR_NOT_START - - bool esp_mesh_is_root_conflicts_allowed(void) Check whether allow more than one root to exist in one network. - Returns true/false - esp_err_t esp_mesh_set_group_id(const mesh_addr_t *addr, int num) Set group ID addresses. - Parameters addr -- [in] pointer to new group ID addresses num -- [in] the number of group ID addresses - - Returns ESP_OK ESP_MESH_ERR_ARGUMENT - - esp_err_t esp_mesh_delete_group_id(const mesh_addr_t *addr, int num) Delete group ID addresses. - Parameters addr -- [in] pointer to deleted group ID address num -- [in] the number of group ID addresses - - Returns ESP_OK ESP_MESH_ERR_ARGUMENT - - int esp_mesh_get_group_num(void) Get the number of group ID addresses. - Returns the number of group ID addresses - esp_err_t esp_mesh_get_group_list(mesh_addr_t *addr, int num) Get group ID addresses. - Parameters addr -- [out] pointer to group ID addresses num -- [in] the number of group ID addresses - - Returns ESP_OK ESP_MESH_ERR_ARGUMENT - - bool esp_mesh_is_my_group(const mesh_addr_t *addr) Check whether the specified group address is my group. - Returns true/false - esp_err_t esp_mesh_set_capacity_num(int num) Set mesh network capacity (max:1000, default:300) - Attention This API shall be called before mesh is started. - Parameters num -- [in] mesh network capacity - Returns ESP_OK ESP_ERR_MESH_NOT_ALLOWED ESP_MESH_ERR_ARGUMENT - - int esp_mesh_get_capacity_num(void) Get mesh network capacity. - Returns mesh network capacity - esp_err_t esp_mesh_set_ie_crypto_funcs(const mesh_crypto_funcs_t *crypto_funcs) Set mesh IE crypto functions. - Attention This API can be called at any time after mesh is configured. - Parameters crypto_funcs -- [in] crypto functions for mesh IE If crypto_funcs is set to NULL, mesh IE is no longer encrypted. - - Returns ESP_OK - - esp_err_t esp_mesh_set_ie_crypto_key(const char *key, int len) Set mesh IE crypto key. - Attention This API can be called at any time after mesh is configured. - Parameters key -- [in] ASCII crypto key len -- [in] length in bytes, range:8~64 - - Returns ESP_OK ESP_MESH_ERR_ARGUMENT - - esp_err_t esp_mesh_get_ie_crypto_key(char *key, int len) Get mesh IE crypto key. - Parameters key -- [out] ASCII crypto key len -- [in] length in bytes, range:8~64 - - Returns ESP_OK ESP_MESH_ERR_ARGUMENT - - esp_err_t esp_mesh_set_root_healing_delay(int delay_ms) Set delay time before starting root healing. - Parameters delay_ms -- [in] delay time in milliseconds - Returns ESP_OK - - int esp_mesh_get_root_healing_delay(void) Get delay time before network starts root healing. - Returns delay time in milliseconds - esp_err_t esp_mesh_fix_root(bool enable) Enable network Fixed Root Setting. Enabling fixed root disables automatic election of the root node via voting. All devices in the network shall use the same Fixed Root Setting (enabled or disabled). If Fixed Root is enabled, users should make sure a root node is designated for the network. - Parameters enable -- [in] enable or not - Returns ESP_OK - - - bool esp_mesh_is_root_fixed(void) Check whether network Fixed Root Setting is enabled. Enable/disable network Fixed Root Setting by API esp_mesh_fix_root(). Network Fixed Root Setting also changes with the "flag" value in parent networking IE. - Returns true/false - - esp_err_t esp_mesh_set_parent(const wifi_config_t *parent, const mesh_addr_t *parent_mesh_id, mesh_type_t my_type, int my_layer) Set a specified parent for the device. - Attention This API can be called at any time after mesh is configured. - Parameters parent -- [in] parent configuration, the SSID and the channel of the parent are mandatory. If the BSSID is set, make sure that the SSID and BSSID represent the same parent, otherwise the device will never find this specified parent. - parent_mesh_id -- [in] parent mesh ID, If this value is not set, the original mesh ID is used. - my_type -- [in] mesh type MESH_STA is not supported. If the parent set for the device is the same as the router in the network configuration, then my_type shall set MESH_ROOT and my_layer shall set MESH_ROOT_LAYER. - my_layer -- [in] mesh layer my_layer of the device may change after joining the network. If my_type is set MESH_NODE, my_layer shall be greater than MESH_ROOT_LAYER. If my_type is set MESH_LEAF, the device becomes a standalone Wi-Fi station and no longer has the ability to extend the network. - - - Returns ESP_OK ESP_ERR_ARGUMENT ESP_ERR_MESH_NOT_CONFIG - - esp_err_t esp_mesh_scan_get_ap_ie_len(int *len) Get mesh networking IE length of one AP. - Parameters len -- [out] mesh networking IE length - Returns ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_INVALID_ARG ESP_ERR_WIFI_FAIL - - esp_err_t esp_mesh_scan_get_ap_record(wifi_ap_record_t *ap_record, void *buffer) Get AP record. - Attention Different from esp_wifi_scan_get_ap_records(), this API only gets one of APs scanned each time. See "manual_networking" example. - Parameters ap_record -- [out] pointer to one AP record buffer -- [out] pointer to the mesh networking IE of this AP - - Returns ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_INVALID_ARG ESP_ERR_WIFI_FAIL - - esp_err_t esp_mesh_flush_upstream_packets(void) Flush upstream packets pending in to_parent queue and to_parent_p2p queue. - Returns ESP_OK - - esp_err_t esp_mesh_get_subnet_nodes_num(const mesh_addr_t *child_mac, int *nodes_num) Get the number of nodes in the subnet of a specific child. - Parameters child_mac -- [in] an associated child address of this device nodes_num -- [out] pointer to the number of nodes in the subnet of a specific child - - Returns ESP_OK ESP_ERR_MESH_NOT_START ESP_ERR_MESH_ARGUMENT - - esp_err_t esp_mesh_get_subnet_nodes_list(const mesh_addr_t *child_mac, mesh_addr_t *nodes, int nodes_num) Get nodes in the subnet of a specific child. - Parameters child_mac -- [in] an associated child address of this device nodes -- [out] pointer to nodes in the subnet of a specific child nodes_num -- [in] the number of nodes in the subnet of a specific child - - Returns ESP_OK ESP_ERR_MESH_NOT_START ESP_ERR_MESH_ARGUMENT - - esp_err_t esp_mesh_switch_channel(const uint8_t *new_bssid, int csa_newchan, int csa_count) Cause the root device to add Channel Switch Announcement Element (CSA IE) to beacon. Set the new channel Set how many beacons with CSA IE will be sent before changing a new channel Enable the channel switch function - Attention This API is only called by the root. - Parameters new_bssid -- [in] the new router BSSID if the router changes csa_newchan -- [in] the new channel number to which the whole network is moving csa_count -- [in] channel switch period(beacon count), unit is based on beacon interval of its softAP, the default value is 15. - - Returns ESP_OK - - - esp_err_t esp_mesh_get_router_bssid(uint8_t *router_bssid) Get the router BSSID. - Parameters router_bssid -- [out] pointer to the router BSSID - Returns ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_INVALID_ARG - - int64_t esp_mesh_get_tsf_time(void) Get the TSF time. - Returns the TSF time - esp_err_t esp_mesh_set_topology(esp_mesh_topology_t topo) Set mesh topology. The default value is MESH_TOPO_TREE. MESH_TOPO_CHAIN supports up to 1000 layers - Attention This API shall be called before mesh is started. - Parameters topo -- [in] MESH_TOPO_TREE or MESH_TOPO_CHAIN - Returns ESP_OK ESP_MESH_ERR_ARGUMENT ESP_ERR_MESH_NOT_ALLOWED - - - esp_mesh_topology_t esp_mesh_get_topology(void) Get mesh topology. - Returns MESH_TOPO_TREE or MESH_TOPO_CHAIN - esp_err_t esp_mesh_enable_ps(void) Enable mesh Power Save function. - Attention This API shall be called before mesh is started. - Returns ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_MESH_NOT_ALLOWED - - esp_err_t esp_mesh_disable_ps(void) Disable mesh Power Save function. - Attention This API shall be called before mesh is started. - Returns ESP_OK ESP_ERR_WIFI_NOT_INIT ESP_ERR_MESH_NOT_ALLOWED - - bool esp_mesh_is_ps_enabled(void) Check whether the mesh Power Save function is enabled. - Returns true/false - bool esp_mesh_is_device_active(void) Check whether the device is in active state. If the device is not in active state, it will neither transmit nor receive frames. - Returns true/false - - esp_err_t esp_mesh_set_active_duty_cycle(int dev_duty, int dev_duty_type) Set the device duty cycle and type. The range of dev_duty values is 1 to 100. The default value is 10. dev_duty = 100, the PS will be stopped. dev_duty is better to not less than 5. dev_duty_type could be MESH_PS_DEVICE_DUTY_REQUEST or MESH_PS_DEVICE_DUTY_DEMAND. If dev_duty_type is set to MESH_PS_DEVICE_DUTY_REQUEST, the device will use a nwk_duty provided by the network. If dev_duty_type is set to MESH_PS_DEVICE_DUTY_DEMAND, the device will use the specified dev_duty. - Attention This API can be called at any time after mesh is started. - Parameters dev_duty -- [in] device duty cycle dev_duty_type -- [in] device PS duty cycle type, not accept MESH_PS_NETWORK_DUTY_MASTER - - Returns ESP_OK ESP_FAIL - - - esp_err_t esp_mesh_get_active_duty_cycle(int *dev_duty, int *dev_duty_type) Get device duty cycle and type. - Parameters dev_duty -- [out] device duty cycle dev_duty_type -- [out] device PS duty cycle type - - Returns ESP_OK - - esp_err_t esp_mesh_set_network_duty_cycle(int nwk_duty, int duration_mins, int applied_rule) Set the network duty cycle, duration and rule. The range of nwk_duty values is 1 to 100. The default value is 10. nwk_duty is the network duty cycle the entire network or the up-link path will use. A device that successfully sets the nwk_duty is known as a NWK-DUTY-MASTER. duration_mins specifies how long the specified nwk_duty will be used. Once duration_mins expires, the root will take over as the NWK-DUTY-MASTER. If an existing NWK-DUTY-MASTER leaves the network, the root will take over as the NWK-DUTY-MASTER again. duration_mins = (-1) represents nwk_duty will be used until a new NWK-DUTY-MASTER with a different nwk_duty appears. Only the root can set duration_mins to (-1). If applied_rule is set to MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE, the nwk_duty will be used by the entire network. If applied_rule is set to MESH_PS_NETWORK_DUTY_APPLIED_UPLINK, the nwk_duty will only be used by the up-link path nodes. The root does not accept MESH_PS_NETWORK_DUTY_APPLIED_UPLINK. A nwk_duty with duration_mins(-1) set by the root is the default network duty cycle used by the entire network. - Attention This API can be called at any time after mesh is started. In self-organized network, if this API is called before mesh is started in all devices, (1)nwk_duty shall be set to the same value for all devices; (2)duration_mins shall be set to (-1); (3)applied_rule shall be set to MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE; after the voted root appears, the root will become the NWK-DUTY-MASTER and broadcast the nwk_duty and its identity of NWK-DUTY-MASTER. If the root is specified (FIXED-ROOT), call this API in the root to provide a default nwk_duty for the entire network. After joins the network, any device can call this API to change the nwk_duty, duration_mins or applied_rule. - - Parameters nwk_duty -- [in] network duty cycle duration_mins -- [in] duration (unit: minutes) applied_rule -- [in] only support MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE - - Returns ESP_OK ESP_FAIL - - - esp_err_t esp_mesh_get_network_duty_cycle(int *nwk_duty, int *duration_mins, int *dev_duty_type, int *applied_rule) Get the network duty cycle, duration, type and rule. - Parameters nwk_duty -- [out] current network duty cycle duration_mins -- [out] the duration of current nwk_duty dev_duty_type -- [out] if it includes MESH_PS_DEVICE_DUTY_MASTER, this device is the current NWK-DUTY-MASTER. applied_rule -- [out] MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE - - Returns ESP_OK - - int esp_mesh_get_running_active_duty_cycle(void) Get the running active duty cycle. The running active duty cycle of the root is 100. If duty type is set to MESH_PS_DEVICE_DUTY_REQUEST, the running active duty cycle is nwk_duty provided by the network. If duty type is set to MESH_PS_DEVICE_DUTY_DEMAND, the running active duty cycle is dev_duty specified by the users. In a mesh network, devices are typically working with a certain duty-cycle (transmitting, receiving and sleep) to reduce the power consumption. The running active duty cycle decides the amount of awake time within a beacon interval. At each start of beacon interval, all devices wake up, broadcast beacons, and transmit packets if they do have pending packets for their parents or for their children. Note that Low-duty-cycle means devices may not be active in most of the time, the latency of data transmission might be greater. - Returns the running active duty cycle - Unions - union mesh_addr_t - #include <esp_mesh.h> Mesh address. - union mesh_event_info_t - #include <esp_mesh.h> Mesh event information. Public Members - mesh_event_channel_switch_t channel_switch channel switch - mesh_event_child_connected_t child_connected child connected - mesh_event_child_disconnected_t child_disconnected child disconnected - mesh_event_routing_table_change_t routing_table routing table change - mesh_event_connected_t connected parent connected - mesh_event_disconnected_t disconnected parent disconnected - mesh_event_no_parent_found_t no_parent no parent found - mesh_event_layer_change_t layer_change layer change - mesh_event_toDS_state_t toDS_state toDS state, devices shall check this state firstly before trying to send packets to external IP network. This state indicates right now whether the root is capable of sending packets out. If not, devices had better to wait until this state changes to be MESH_TODS_REACHABLE. - mesh_event_vote_started_t vote_started vote started - mesh_event_root_address_t root_addr root address - mesh_event_root_switch_req_t switch_req root switch request - mesh_event_root_conflict_t root_conflict other powerful root - mesh_event_root_fixed_t root_fixed fixed root - mesh_event_scan_done_t scan_done scan done - mesh_event_network_state_t network_state network state, such as whether current mesh network has a root. - mesh_event_find_network_t find_network network found that can join - mesh_event_router_switch_t router_switch new router information - mesh_event_ps_duty_t ps_duty PS duty information - mesh_event_channel_switch_t channel_switch - union mesh_rc_config_t - #include <esp_mesh.h> Vote address configuration. Public Members - int attempts max vote attempts before a new root is elected automatically by mesh network. (min:15, 15 by default) - mesh_addr_t rc_addr a new root address specified by users for API esp_mesh_waive_root() - int attempts Structures - struct mip_t IP address and port. Public Members - esp_ip4_addr_t ip4 IP address - uint16_t port port - esp_ip4_addr_t ip4 - struct mesh_event_channel_switch_t Channel switch information. Public Members - uint8_t channel new channel - uint8_t channel - struct mesh_event_connected_t Parent connected information. Public Members - wifi_event_sta_connected_t connected parent information, same as Wi-Fi event SYSTEM_EVENT_STA_CONNECTED does - uint16_t self_layer layer - uint8_t duty parent duty - wifi_event_sta_connected_t connected - struct mesh_event_no_parent_found_t No parent found information. Public Members - int scan_times scan times being through - int scan_times - struct mesh_event_layer_change_t Layer change information. Public Members - uint16_t new_layer new layer - uint16_t new_layer - struct mesh_event_vote_started_t vote started information Public Members - int reason vote reason, vote could be initiated by children or by the root itself - int attempts max vote attempts before stopped - mesh_addr_t rc_addr root address specified by users via API esp_mesh_waive_root() - int reason - struct mesh_event_find_network_t find a mesh network that this device can join - struct mesh_event_root_switch_req_t Root switch request information. Public Members - int reason root switch reason, generally root switch is initialized by users via API esp_mesh_waive_root() - mesh_addr_t rc_addr the address of root switch requester - int reason - struct mesh_event_root_conflict_t Other powerful root address. - struct mesh_event_routing_table_change_t Routing table change. - struct mesh_event_scan_done_t Scan done event information. Public Members - uint8_t number the number of APs scanned - uint8_t number - struct mesh_event_network_state_t Network state information. Public Members - bool is_rootless whether current mesh network has a root - bool is_rootless - struct mesh_event_ps_duty_t PS duty information. Public Members - uint8_t duty parent or child duty - mesh_event_child_connected_t child_connected child info - uint8_t duty - struct mesh_opt_t Mesh option. - struct mesh_data_t Mesh data for esp_mesh_send() and esp_mesh_recv() Public Members - uint8_t *data data - uint16_t size data size - mesh_proto_t proto data protocol - mesh_tos_t tos data type of service - uint8_t *data - struct mesh_router_t Router configuration. Public Members - uint8_t ssid[32] SSID - uint8_t ssid_len length of SSID - uint8_t bssid[6] BSSID, if this value is specified, users should also specify "allow_router_switch". - uint8_t password[64] password - bool allow_router_switch if the BSSID is specified and this value is also set, when the router of this specified BSSID fails to be found after "fail" (mesh_attempts_t) times, the whole network is allowed to switch to another router with the same SSID. The new router might also be on a different channel. The default value is false. There is a risk that if the password is different between the new switched router and the previous one, the mesh network could be established but the root will never connect to the new switched router. - uint8_t ssid[32] - struct mesh_ap_cfg_t Mesh softAP configuration. - struct mesh_cfg_t Mesh initialization configuration. Public Members - uint8_t channel channel, the mesh network on - bool allow_channel_switch if this value is set, when "fail" (mesh_attempts_t) times is reached, device will change to a full channel scan for a network that could join. The default value is false. - mesh_addr_t mesh_id mesh network identification - mesh_router_t router router configuration - mesh_ap_cfg_t mesh_ap mesh softAP configuration - const mesh_crypto_funcs_t *crypto_funcs crypto functions - uint8_t channel - struct mesh_vote_t Vote. Public Members - float percentage vote percentage threshold for approval of being a root - bool is_rc_specified if true, rc_addr shall be specified (Unimplemented). if false, attempts value shall be specified to make network start root election. - mesh_rc_config_t config vote address configuration - float percentage - struct mesh_tx_pending_t The number of packets pending in the queue waiting to be sent by the mesh stack. - struct mesh_rx_pending_t The number of packets available in the queue waiting to be received by applications. Macros - MESH_ROOT_LAYER root layer value - MESH_MTU max transmit unit(in bytes) - MESH_MPS max payload size(in bytes) - ESP_ERR_MESH_WIFI_NOT_START Mesh error code definition. Wi-Fi isn't started - ESP_ERR_MESH_NOT_INIT mesh isn't initialized - ESP_ERR_MESH_NOT_CONFIG mesh isn't configured - ESP_ERR_MESH_NOT_START mesh isn't started - ESP_ERR_MESH_NOT_SUPPORT not supported yet - ESP_ERR_MESH_NOT_ALLOWED operation is not allowed - ESP_ERR_MESH_NO_MEMORY out of memory - ESP_ERR_MESH_ARGUMENT illegal argument - ESP_ERR_MESH_EXCEED_MTU packet size exceeds MTU - ESP_ERR_MESH_TIMEOUT timeout - ESP_ERR_MESH_DISCONNECTED disconnected with parent on station interface - ESP_ERR_MESH_QUEUE_FAIL queue fail - ESP_ERR_MESH_QUEUE_FULL queue full - ESP_ERR_MESH_NO_PARENT_FOUND no parent found to join the mesh network - ESP_ERR_MESH_NO_ROUTE_FOUND no route found to forward the packet - ESP_ERR_MESH_OPTION_NULL no option found - ESP_ERR_MESH_OPTION_UNKNOWN unknown option - ESP_ERR_MESH_XON_NO_WINDOW no window for software flow control on upstream - ESP_ERR_MESH_INTERFACE low-level Wi-Fi interface error - ESP_ERR_MESH_DISCARD_DUPLICATE discard the packet due to the duplicate sequence number - ESP_ERR_MESH_DISCARD discard the packet - ESP_ERR_MESH_VOTING vote in progress - ESP_ERR_MESH_XMIT XMIT - ESP_ERR_MESH_QUEUE_READ error in reading queue - ESP_ERR_MESH_PS mesh PS is not specified as enable or disable - ESP_ERR_MESH_RECV_RELEASE release esp_mesh_recv_toDS - MESH_DATA_ENC Flags bitmap for esp_mesh_send() and esp_mesh_recv() data encrypted (Unimplemented) - MESH_DATA_P2P point-to-point delivery over the mesh network - MESH_DATA_FROMDS receive from external IP network - MESH_DATA_TODS identify this packet is target to external IP network - MESH_DATA_NONBLOCK esp_mesh_send() non-block - MESH_DATA_DROP in the situation of the root having been changed, identify this packet can be dropped by new root - MESH_DATA_GROUP identify this packet is target to a group address - MESH_OPT_SEND_GROUP Option definitions for esp_mesh_send() and esp_mesh_recv() data transmission by group; used with esp_mesh_send() and shall have payload - MESH_OPT_RECV_DS_ADDR return a remote IP address; used with esp_mesh_send() and esp_mesh_recv() - MESH_ASSOC_FLAG_MAP_ASSOC Flag of mesh networking IE. Mesh AP doesn't detect children leave yet - MESH_ASSOC_FLAG_VOTE_IN_PROGRESS station in vote, set when root vote start, clear when connect to router or when root switch - MESH_ASSOC_FLAG_STA_VOTED station vote done, set when connect to router - MESH_ASSOC_FLAG_NETWORK_FREE no root in current network - MESH_ASSOC_FLAG_STA_VOTE_EXPIRE the voted address is expired, means the voted device lose the chance to be root - MESH_ASSOC_FLAG_ROOTS_FOUND roots conflict is found, means that thre are at least two roots in the mesh network - MESH_ASSOC_FLAG_ROOT_FIXED the root is fixed in the mesh network - MESH_PS_DEVICE_DUTY_REQUEST Mesh PS (Power Save) duty cycle type. requests to join a network PS without specifying a device duty cycle. After the device joins the network, a network duty cycle will be provided by the network - MESH_PS_DEVICE_DUTY_DEMAND requests to join a network PS and specifies a demanded device duty cycle - MESH_PS_NETWORK_DUTY_MASTER indicates the device is the NWK-DUTY-MASTER (network duty cycle master) - MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE Mesh PS (Power Save) duty cycle applied rule. - MESH_PS_NETWORK_DUTY_APPLIED_UPLINK - MESH_INIT_CONFIG_DEFAULT() Type Definitions - typedef mesh_addr_t mesh_event_root_address_t Root address. - typedef wifi_event_sta_disconnected_t mesh_event_disconnected_t Parent disconnected information. - typedef wifi_event_ap_staconnected_t mesh_event_child_connected_t Child connected information. - typedef wifi_event_ap_stadisconnected_t mesh_event_child_disconnected_t Child disconnected information. - typedef wifi_event_sta_connected_t mesh_event_router_switch_t New router information. Enumerations - enum mesh_event_id_t Enumerated list of mesh event id. Values: - enumerator MESH_EVENT_STARTED mesh is started - enumerator MESH_EVENT_STOPPED mesh is stopped - enumerator MESH_EVENT_CHANNEL_SWITCH channel switch - enumerator MESH_EVENT_CHILD_CONNECTED a child is connected on softAP interface - enumerator MESH_EVENT_CHILD_DISCONNECTED a child is disconnected on softAP interface - enumerator MESH_EVENT_ROUTING_TABLE_ADD routing table is changed by adding newly joined children - enumerator MESH_EVENT_ROUTING_TABLE_REMOVE routing table is changed by removing leave children - enumerator MESH_EVENT_PARENT_CONNECTED parent is connected on station interface - enumerator MESH_EVENT_PARENT_DISCONNECTED parent is disconnected on station interface - enumerator MESH_EVENT_NO_PARENT_FOUND no parent found - enumerator MESH_EVENT_LAYER_CHANGE layer changes over the mesh network - enumerator MESH_EVENT_TODS_STATE state represents whether the root is able to access external IP network. This state is a manual event that needs to be triggered with esp_mesh_post_toDS_state(). - enumerator MESH_EVENT_VOTE_STARTED the process of voting a new root is started either by children or by the root - enumerator MESH_EVENT_VOTE_STOPPED the process of voting a new root is stopped - enumerator MESH_EVENT_ROOT_ADDRESS the root address is obtained. It is posted by mesh stack automatically. - enumerator MESH_EVENT_ROOT_SWITCH_REQ root switch request sent from a new voted root candidate - enumerator MESH_EVENT_ROOT_SWITCH_ACK root switch acknowledgment responds the above request sent from current root - enumerator MESH_EVENT_ROOT_ASKED_YIELD the root is asked yield by a more powerful existing root. If self organized is disabled and this device is specified to be a root by users, users should set a new parent for this device. if self organized is enabled, this device will find a new parent by itself, users could ignore this event. - enumerator MESH_EVENT_ROOT_FIXED when devices join a network, if the setting of Fixed Root for one device is different from that of its parent, the device will update the setting the same as its parent's. Fixed Root Setting of each device is variable as that setting changes of the root. - enumerator MESH_EVENT_SCAN_DONE if self-organized networking is disabled, user can call esp_wifi_scan_start() to trigger this event, and add the corresponding scan done handler in this event. - enumerator MESH_EVENT_NETWORK_STATE network state, such as whether current mesh network has a root. - enumerator MESH_EVENT_STOP_RECONNECTION the root stops reconnecting to the router and non-root devices stop reconnecting to their parents. - enumerator MESH_EVENT_FIND_NETWORK when the channel field in mesh configuration is set to zero, mesh stack will perform a full channel scan to find a mesh network that can join, and return the channel value after finding it. - enumerator MESH_EVENT_ROUTER_SWITCH if users specify BSSID of the router in mesh configuration, when the root connects to another router with the same SSID, this event will be posted and the new router information is attached. - enumerator MESH_EVENT_PS_PARENT_DUTY parent duty - enumerator MESH_EVENT_PS_CHILD_DUTY child duty - enumerator MESH_EVENT_PS_DEVICE_DUTY device duty - enumerator MESH_EVENT_MAX - enumerator MESH_EVENT_STARTED - enum mesh_type_t Device type. Values: - enumerator MESH_IDLE hasn't joined the mesh network yet - enumerator MESH_ROOT the only sink of the mesh network. Has the ability to access external IP network - enumerator MESH_NODE intermediate device. Has the ability to forward packets over the mesh network - enumerator MESH_LEAF has no forwarding ability - enumerator MESH_STA connect to router with a standlone Wi-Fi station mode, no network expansion capability - enumerator MESH_IDLE - enum mesh_proto_t Protocol of transmitted application data. Values: - enumerator MESH_PROTO_BIN binary - enumerator MESH_PROTO_HTTP HTTP protocol - enumerator MESH_PROTO_JSON JSON format - enumerator MESH_PROTO_MQTT MQTT protocol - enumerator MESH_PROTO_AP IP network mesh communication of node's AP interface - enumerator MESH_PROTO_STA IP network mesh communication of node's STA interface - enumerator MESH_PROTO_BIN - enum mesh_tos_t For reliable transmission, mesh stack provides three type of services. Values: - enumerator MESH_TOS_P2P provide P2P (point-to-point) retransmission on mesh stack by default - enumerator MESH_TOS_E2E provide E2E (end-to-end) retransmission on mesh stack (Unimplemented) - enumerator MESH_TOS_DEF no retransmission on mesh stack - enumerator MESH_TOS_P2P - enum mesh_vote_reason_t Vote reason. Values: - enumerator MESH_VOTE_REASON_ROOT_INITIATED vote is initiated by the root - enumerator MESH_VOTE_REASON_CHILD_INITIATED vote is initiated by children - enumerator MESH_VOTE_REASON_ROOT_INITIATED - enum mesh_disconnect_reason_t Mesh disconnect reason code. Values: - enumerator MESH_REASON_CYCLIC cyclic is detected - enumerator MESH_REASON_PARENT_IDLE parent is idle - enumerator MESH_REASON_LEAF the connected device is changed to a leaf - enumerator MESH_REASON_DIFF_ID in different mesh ID - enumerator MESH_REASON_ROOTS root conflict is detected - enumerator MESH_REASON_PARENT_STOPPED parent has stopped the mesh - enumerator MESH_REASON_SCAN_FAIL scan fail - enumerator MESH_REASON_IE_UNKNOWN unknown IE - enumerator MESH_REASON_WAIVE_ROOT waive root - enumerator MESH_REASON_PARENT_WORSE parent with very poor RSSI - enumerator MESH_REASON_EMPTY_PASSWORD use an empty password to connect to an encrypted parent - enumerator MESH_REASON_PARENT_UNENCRYPTED connect to an unencrypted parent/router - enumerator MESH_REASON_CYCLIC - enum esp_mesh_topology_t Mesh topology. Values: - enumerator MESH_TOPO_TREE tree topology - enumerator MESH_TOPO_CHAIN chain topology - enumerator MESH_TOPO_TREE
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/network/esp-wifi-mesh.html
ESP-IDF Programming Guide v5.2.1 documentation
null
SmartConfig
null
espressif.com
2016-01-01
168055ceee2c6296
null
null
SmartConfig The SmartConfigTM 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 ESP32 devices, check Provisioning API. Application Example Connect ESP32 to the target AP using SmartConfig: wifi/smart_config. API Reference Header File This header file can be included with: #include "esp_smartconfig.h" This header file is a part of the API provided by the esp_wifi component. To declare that your component depends on esp_wifi , add the following to your CMakeLists.txt: REQUIRES esp_wifi or PRIV_REQUIRES esp_wifi Functions const char *esp_smartconfig_get_version(void) Get the version of SmartConfig. Returns SmartConfig version const char. SmartConfig version const char. SmartConfig version const char. Returns SmartConfig version const char. esp_err_t esp_smartconfig_start(const smartconfig_start_config_t *config) Start SmartConfig, config ESP device to connect AP. You need to broadcast information by phone APP. Device sniffer special packets from the air that containing SSID and password of target AP. Attention 1. This API can be called in station or softAP-station mode. Attention 2. Can not call esp_smartconfig_start twice before it finish, please call esp_smartconfig_stop first. Attention 1. This API can be called in station or softAP-station mode. Attention 2. Can not call esp_smartconfig_start twice before it finish, please call esp_smartconfig_stop first. Parameters config -- pointer to smartconfig start configure structure Returns ESP_OK: succeed others: fail ESP_OK: succeed others: fail ESP_OK: succeed Parameters config -- pointer to smartconfig start configure structure Returns ESP_OK: succeed others: fail esp_err_t esp_smartconfig_stop(void) Stop SmartConfig, free the buffer taken by esp_smartconfig_start. Attention Whether connect to AP succeed or not, this API should be called to free memory taken by smartconfig_start. Attention Whether connect to AP succeed or not, this API should be called to free memory taken by smartconfig_start. Returns ESP_OK: succeed others: fail ESP_OK: succeed others: fail ESP_OK: succeed Returns ESP_OK: succeed others: fail esp_err_t esp_esptouch_set_timeout(uint8_t time_s) Set timeout of SmartConfig process. Attention Timing starts from SC_STATUS_FIND_CHANNEL status. SmartConfig will restart if timeout. Attention Timing starts from SC_STATUS_FIND_CHANNEL status. SmartConfig will restart if timeout. Parameters time_s -- range 15s~255s, offset:45s. Returns ESP_OK: succeed others: fail ESP_OK: succeed others: fail ESP_OK: succeed Parameters time_s -- range 15s~255s, offset:45s. Returns ESP_OK: succeed others: fail esp_err_t esp_smartconfig_set_type(smartconfig_type_t type) Set protocol type of SmartConfig. Attention If users need to set the SmartConfig type, please set it before calling esp_smartconfig_start. Attention If users need to set the SmartConfig type, please set it before calling esp_smartconfig_start. Parameters type -- Choose from the smartconfig_type_t. Returns ESP_OK: succeed others: fail ESP_OK: succeed others: fail ESP_OK: succeed Parameters type -- Choose from the smartconfig_type_t. Returns ESP_OK: succeed others: fail esp_err_t esp_smartconfig_fast_mode(bool enable) Set mode of SmartConfig. default normal mode. Attention 1. Please call it before API esp_smartconfig_start. Attention 2. Fast mode have corresponding APP(phone). Attention 3. Two mode is compatible. Attention 1. Please call it before API esp_smartconfig_start. Attention 2. Fast mode have corresponding APP(phone). Attention 3. Two mode is compatible. Parameters enable -- false-disable(default); true-enable; Returns ESP_OK: succeed others: fail ESP_OK: succeed others: fail ESP_OK: succeed Parameters enable -- false-disable(default); true-enable; Returns ESP_OK: succeed others: fail Structures struct smartconfig_event_got_ssid_pswd_t Argument structure for SC_EVENT_GOT_SSID_PSWD event Public Members uint8_t ssid[32] SSID of the AP. Null terminated string. uint8_t ssid[32] SSID of the AP. Null terminated string. uint8_t password[64] Password of the AP. Null terminated string. uint8_t password[64] Password of the AP. Null terminated string. bool bssid_set whether set MAC address of target AP or not. bool bssid_set whether set MAC address of target AP or not. uint8_t bssid[6] MAC address of target AP. uint8_t bssid[6] MAC address of target AP. smartconfig_type_t type Type of smartconfig(ESPTouch or AirKiss). smartconfig_type_t type Type of smartconfig(ESPTouch or AirKiss). uint8_t token Token from cellphone which is used to send ACK to cellphone. uint8_t token Token from cellphone which is used to send ACK to cellphone. uint8_t cellphone_ip[4] IP address of cellphone. uint8_t cellphone_ip[4] IP address of cellphone. uint8_t ssid[32] struct smartconfig_start_config_t Configure structure for esp_smartconfig_start Macros SMARTCONFIG_START_CONFIG_DEFAULT() Enumerations enum smartconfig_type_t Values: enumerator SC_TYPE_ESPTOUCH protocol: ESPTouch enumerator SC_TYPE_ESPTOUCH protocol: ESPTouch enumerator SC_TYPE_AIRKISS protocol: AirKiss enumerator SC_TYPE_AIRKISS protocol: AirKiss enumerator SC_TYPE_ESPTOUCH_AIRKISS protocol: ESPTouch and AirKiss enumerator SC_TYPE_ESPTOUCH_AIRKISS protocol: ESPTouch and AirKiss enumerator SC_TYPE_ESPTOUCH_V2 protocol: ESPTouch v2 enumerator SC_TYPE_ESPTOUCH_V2 protocol: ESPTouch v2 enumerator SC_TYPE_ESPTOUCH enum smartconfig_event_t Smartconfig event declarations Values: enumerator SC_EVENT_SCAN_DONE Station smartconfig has finished to scan for APs enumerator SC_EVENT_SCAN_DONE Station smartconfig has finished to scan for APs enumerator SC_EVENT_FOUND_CHANNEL Station smartconfig has found the channel of the target AP enumerator SC_EVENT_FOUND_CHANNEL Station smartconfig has found the channel of the target AP enumerator SC_EVENT_GOT_SSID_PSWD Station smartconfig got the SSID and password enumerator SC_EVENT_GOT_SSID_PSWD Station smartconfig got the SSID and password enumerator SC_EVENT_SEND_ACK_DONE Station smartconfig has sent ACK to cellphone enumerator SC_EVENT_SEND_ACK_DONE Station smartconfig has sent ACK to cellphone enumerator SC_EVENT_SCAN_DONE
SmartConfig The SmartConfigTM 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 ESP32 devices, check Provisioning API. Application Example Connect ESP32 to the target AP using SmartConfig: wifi/smart_config. API Reference Header File This header file can be included with: #include "esp_smartconfig.h" This header file is a part of the API provided by the esp_wificomponent. To declare that your component depends on esp_wifi, add the following to your CMakeLists.txt: REQUIRES esp_wifi or PRIV_REQUIRES esp_wifi Functions - const char *esp_smartconfig_get_version(void) Get the version of SmartConfig. - Returns SmartConfig version const char. - - esp_err_t esp_smartconfig_start(const smartconfig_start_config_t *config) Start SmartConfig, config ESP device to connect AP. You need to broadcast information by phone APP. Device sniffer special packets from the air that containing SSID and password of target AP. - Attention 1. This API can be called in station or softAP-station mode. - Attention 2. Can not call esp_smartconfig_start twice before it finish, please call esp_smartconfig_stop first. - Parameters config -- pointer to smartconfig start configure structure - Returns ESP_OK: succeed others: fail - - esp_err_t esp_smartconfig_stop(void) Stop SmartConfig, free the buffer taken by esp_smartconfig_start. - Attention Whether connect to AP succeed or not, this API should be called to free memory taken by smartconfig_start. - Returns ESP_OK: succeed others: fail - - esp_err_t esp_esptouch_set_timeout(uint8_t time_s) Set timeout of SmartConfig process. - Attention Timing starts from SC_STATUS_FIND_CHANNEL status. SmartConfig will restart if timeout. - Parameters time_s -- range 15s~255s, offset:45s. - Returns ESP_OK: succeed others: fail - - esp_err_t esp_smartconfig_set_type(smartconfig_type_t type) Set protocol type of SmartConfig. - Attention If users need to set the SmartConfig type, please set it before calling esp_smartconfig_start. - Parameters type -- Choose from the smartconfig_type_t. - Returns ESP_OK: succeed others: fail - - esp_err_t esp_smartconfig_fast_mode(bool enable) Set mode of SmartConfig. default normal mode. - Attention 1. Please call it before API esp_smartconfig_start. - Attention 2. Fast mode have corresponding APP(phone). - Attention 3. Two mode is compatible. - Parameters enable -- false-disable(default); true-enable; - Returns ESP_OK: succeed others: fail - Structures - struct smartconfig_event_got_ssid_pswd_t Argument structure for SC_EVENT_GOT_SSID_PSWD event Public Members - uint8_t ssid[32] SSID of the AP. Null terminated string. - uint8_t password[64] Password of the AP. Null terminated string. - bool bssid_set whether set MAC address of target AP or not. - uint8_t bssid[6] MAC address of target AP. - smartconfig_type_t type Type of smartconfig(ESPTouch or AirKiss). - uint8_t token Token from cellphone which is used to send ACK to cellphone. - uint8_t cellphone_ip[4] IP address of cellphone. - uint8_t ssid[32] - struct smartconfig_start_config_t Configure structure for esp_smartconfig_start Macros - SMARTCONFIG_START_CONFIG_DEFAULT() Enumerations - enum smartconfig_type_t Values: - enumerator SC_TYPE_ESPTOUCH protocol: ESPTouch - enumerator SC_TYPE_AIRKISS protocol: AirKiss - enumerator SC_TYPE_ESPTOUCH_AIRKISS protocol: ESPTouch and AirKiss - enumerator SC_TYPE_ESPTOUCH_V2 protocol: ESPTouch v2 - enumerator SC_TYPE_ESPTOUCH - enum smartconfig_event_t Smartconfig event declarations Values: - enumerator SC_EVENT_SCAN_DONE Station smartconfig has finished to scan for APs - enumerator SC_EVENT_FOUND_CHANNEL Station smartconfig has found the channel of the target AP - enumerator SC_EVENT_GOT_SSID_PSWD Station smartconfig got the SSID and password - enumerator SC_EVENT_SEND_ACK_DONE Station smartconfig has sent ACK to cellphone - enumerator SC_EVENT_SCAN_DONE
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/network/esp_smartconfig.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Wi-Fi Easy ConnectTM (DPP)
null
espressif.com
2016-01-01
a78e8b4fab29eb48
null
null
Wi-Fi Easy ConnectTM (DPP) Wi-Fi Easy ConnectTM, 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. ESP32 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 ESP32 to their Wi-Fi network. The provisioning device needs to be connected to the AP which need not support Wi-Fi Easy ConnectTM. 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 ESP32 using a supported smartphone: wifi/wifi_easy_connect/dpp-enrollee. API Reference Header File This header file can be included with: #include "esp_dpp.h" This header file is a part of the API provided by the wpa_supplicant component. To declare that your component depends on wpa_supplicant , add the following to your CMakeLists.txt: REQUIRES wpa_supplicant or PRIV_REQUIRES wpa_supplicant Functions esp_err_t esp_supp_dpp_init(esp_supp_dpp_event_cb_t evt_cb) Initialize DPP Supplicant. Starts DPP Supplicant and initializes related Data Structures. return ESP_OK: Success ESP_FAIL: Failure ESP_OK: Success ESP_FAIL: Failure Parameters evt_cb -- Callback function to receive DPP related events Parameters evt_cb -- Callback function to receive DPP related events ESP_OK: Success void esp_supp_dpp_deinit(void) De-initalize DPP Supplicant. Frees memory from DPP Supplicant Data Structures. esp_err_t esp_supp_dpp_bootstrap_gen(const char *chan_list, esp_supp_dpp_bootstrap_t type, const char *key, const char *info) Generates Bootstrap Information as an Enrollee. Generates Out Of Band Bootstrap information as an Enrollee which can be used by a DPP Configurator to provision the Enrollee. Parameters chan_list -- List of channels device will be available on for listening type -- Bootstrap method type, only QR Code method is supported for now. key -- (Optional) 32 byte Raw Private Key for generating a Bootstrapping Public Key info -- (Optional) Ancilliary Device Information like Serial Number chan_list -- List of channels device will be available on for listening type -- Bootstrap method type, only QR Code method is supported for now. key -- (Optional) 32 byte Raw Private Key for generating a Bootstrapping Public Key info -- (Optional) Ancilliary Device Information like Serial Number chan_list -- List of channels device will be available on for listening Returns ESP_OK: Success ESP_FAIL: Failure ESP_OK: Success ESP_FAIL: Failure ESP_OK: Success Parameters chan_list -- List of channels device will be available on for listening type -- Bootstrap method type, only QR Code method is supported for now. key -- (Optional) 32 byte Raw Private Key for generating a Bootstrapping Public Key info -- (Optional) Ancilliary Device Information like Serial Number Returns ESP_OK: Success ESP_FAIL: Failure esp_err_t esp_supp_dpp_start_listen(void) Start listening on Channels provided during esp_supp_dpp_bootstrap_gen. Listens on every Channel from Channel List for a pre-defined wait time. Returns ESP_OK: Success ESP_FAIL: Generic Failure ESP_ERR_INVALID_STATE: ROC attempted before WiFi is started ESP_ERR_NO_MEM: Memory allocation failed while posting ROC request ESP_OK: Success ESP_FAIL: Generic Failure ESP_ERR_INVALID_STATE: ROC attempted before WiFi is started ESP_ERR_NO_MEM: Memory allocation failed while posting ROC request ESP_OK: Success Returns ESP_OK: Success ESP_FAIL: Generic Failure ESP_ERR_INVALID_STATE: ROC attempted before WiFi is started ESP_ERR_NO_MEM: Memory allocation failed while posting ROC request void esp_supp_dpp_stop_listen(void) Stop listening on Channels. Stops listening on Channels and cancels ongoing listen operation. Macros ESP_DPP_AUTH_TIMEOUT_SECS ESP_ERR_DPP_FAILURE Generic failure during DPP Operation ESP_ERR_DPP_TX_FAILURE DPP Frame Tx failed OR not Acked ESP_ERR_DPP_INVALID_ATTR Encountered invalid DPP Attribute ESP_ERR_DPP_AUTH_TIMEOUT DPP Auth response was not recieved in time Type Definitions typedef enum dpp_bootstrap_type esp_supp_dpp_bootstrap_t Types of Bootstrap Methods for DPP. typedef void (*esp_supp_dpp_event_cb_t)(esp_supp_dpp_event_t evt, void *data) Callback function for receiving DPP Events from Supplicant. Callback function will be called with DPP related information. Param evt DPP event ID Param data Event data payload Param evt DPP event ID Param data Event data payload Enumerations enum dpp_bootstrap_type Types of Bootstrap Methods for DPP. Values: enumerator DPP_BOOTSTRAP_QR_CODE QR Code Method enumerator DPP_BOOTSTRAP_QR_CODE QR Code Method enumerator DPP_BOOTSTRAP_PKEX Proof of Knowledge Method enumerator DPP_BOOTSTRAP_PKEX Proof of Knowledge Method enumerator DPP_BOOTSTRAP_NFC_URI NFC URI record Method enumerator DPP_BOOTSTRAP_NFC_URI NFC URI record Method enumerator DPP_BOOTSTRAP_QR_CODE
Wi-Fi Easy ConnectTM (DPP) Wi-Fi Easy ConnectTM, 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. ESP32 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 ESP32 to their Wi-Fi network. The provisioning device needs to be connected to the AP which need not support Wi-Fi Easy ConnectTM. 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 ESP32 using a supported smartphone: wifi/wifi_easy_connect/dpp-enrollee. API Reference Header File This header file can be included with: #include "esp_dpp.h" This header file is a part of the API provided by the wpa_supplicantcomponent. To declare that your component depends on wpa_supplicant, add the following to your CMakeLists.txt: REQUIRES wpa_supplicant or PRIV_REQUIRES wpa_supplicant Functions - esp_err_t esp_supp_dpp_init(esp_supp_dpp_event_cb_t evt_cb) Initialize DPP Supplicant. Starts DPP Supplicant and initializes related Data Structures. return ESP_OK: Success ESP_FAIL: Failure - Parameters evt_cb -- Callback function to receive DPP related events - - void esp_supp_dpp_deinit(void) De-initalize DPP Supplicant. Frees memory from DPP Supplicant Data Structures. - esp_err_t esp_supp_dpp_bootstrap_gen(const char *chan_list, esp_supp_dpp_bootstrap_t type, const char *key, const char *info) Generates Bootstrap Information as an Enrollee. Generates Out Of Band Bootstrap information as an Enrollee which can be used by a DPP Configurator to provision the Enrollee. - Parameters chan_list -- List of channels device will be available on for listening type -- Bootstrap method type, only QR Code method is supported for now. key -- (Optional) 32 byte Raw Private Key for generating a Bootstrapping Public Key info -- (Optional) Ancilliary Device Information like Serial Number - - Returns ESP_OK: Success ESP_FAIL: Failure - - esp_err_t esp_supp_dpp_start_listen(void) Start listening on Channels provided during esp_supp_dpp_bootstrap_gen. Listens on every Channel from Channel List for a pre-defined wait time. - Returns ESP_OK: Success ESP_FAIL: Generic Failure ESP_ERR_INVALID_STATE: ROC attempted before WiFi is started ESP_ERR_NO_MEM: Memory allocation failed while posting ROC request - - void esp_supp_dpp_stop_listen(void) Stop listening on Channels. Stops listening on Channels and cancels ongoing listen operation. Macros - ESP_DPP_AUTH_TIMEOUT_SECS - ESP_ERR_DPP_FAILURE Generic failure during DPP Operation - ESP_ERR_DPP_TX_FAILURE DPP Frame Tx failed OR not Acked - ESP_ERR_DPP_INVALID_ATTR Encountered invalid DPP Attribute - ESP_ERR_DPP_AUTH_TIMEOUT DPP Auth response was not recieved in time Type Definitions - typedef enum dpp_bootstrap_type esp_supp_dpp_bootstrap_t Types of Bootstrap Methods for DPP. - typedef void (*esp_supp_dpp_event_cb_t)(esp_supp_dpp_event_t evt, void *data) Callback function for receiving DPP Events from Supplicant. Callback function will be called with DPP related information. - Param evt DPP event ID - Param data Event data payload Enumerations - enum dpp_bootstrap_type Types of Bootstrap Methods for DPP. Values: - enumerator DPP_BOOTSTRAP_QR_CODE QR Code Method - enumerator DPP_BOOTSTRAP_PKEX Proof of Knowledge Method - enumerator DPP_BOOTSTRAP_NFC_URI NFC URI record Method - enumerator DPP_BOOTSTRAP_QR_CODE
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/network/esp_dpp.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Wi-Fi AwareTM (NAN)
null
espressif.com
2016-01-01
86a4f9cde544c3e7
null
null
Wi-Fi AwareTM (NAN) Wi-Fi AwareTM 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. ESP32 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: wifi/wifi_aware/nan_publisher and wifi/wifi_aware/nan_subscriber. A user interactive console example to explore full functionality of Wi-Fi Aware: wifi/wifi_aware/nan_console. Please check the README for more details in respective example directories. API Reference Header File This header file can be included with: #include "esp_nan.h" This header file is a part of the API provided by the esp_wifi component. To declare that your component depends on esp_wifi , add the following to your CMakeLists.txt: REQUIRES esp_wifi or PRIV_REQUIRES esp_wifi Functions esp_err_t esp_wifi_nan_start(const wifi_nan_config_t *nan_cfg) Start NAN Discovery with provided configuration. Attention This API should be called after esp_wifi_init(). Attention This API should be called after esp_wifi_init(). Parameters nan_cfg -- NAN related parameters to be configured. Returns ESP_OK: succeed others: failed ESP_OK: succeed others: failed ESP_OK: succeed Parameters nan_cfg -- NAN related parameters to be configured. Returns ESP_OK: succeed others: failed esp_err_t esp_wifi_nan_stop(void) Stop NAN Discovery, end NAN Services and Datapaths. Returns ESP_OK: succeed others: failed ESP_OK: succeed others: failed ESP_OK: succeed Returns ESP_OK: succeed others: failed uint8_t esp_wifi_nan_publish_service(const wifi_nan_publish_cfg_t *publish_cfg, bool ndp_resp_needed) Start Publishing a service to the NAN Peers in vicinity. Attention This API should be called after esp_wifi_nan_start(). Attention This API should be called after esp_wifi_nan_start(). Parameters publish_cfg -- Configuration parameters for publishing a service. ndp_resp_needed -- Setting this true will require user response for every NDP Req using esp_wifi_nan_datapath_resp API. publish_cfg -- Configuration parameters for publishing a service. ndp_resp_needed -- Setting this true will require user response for every NDP Req using esp_wifi_nan_datapath_resp API. publish_cfg -- Configuration parameters for publishing a service. Returns non-zero: Publish service identifier zero: failed non-zero: Publish service identifier zero: failed non-zero: Publish service identifier Parameters publish_cfg -- Configuration parameters for publishing a service. ndp_resp_needed -- Setting this true will require user response for every NDP Req using esp_wifi_nan_datapath_resp API. Returns non-zero: Publish service identifier zero: failed uint8_t esp_wifi_nan_subscribe_service(const wifi_nan_subscribe_cfg_t *subscribe_cfg) Subscribe for a service within the NAN cluster. Attention This API should be called after esp_wifi_nan_start(). Attention This API should be called after esp_wifi_nan_start(). Parameters subscribe_cfg -- Configuration parameters for subscribing for a service. Returns non-zero: Subscribe service identifier zero: failed non-zero: Subscribe service identifier zero: failed non-zero: Subscribe service identifier Parameters subscribe_cfg -- Configuration parameters for subscribing for a service. Returns non-zero: Subscribe service identifier zero: failed esp_err_t esp_wifi_nan_send_message(wifi_nan_followup_params_t *fup_params) Send a follow-up message to the NAN Peer with matched service. Attention This API should be called after a NAN service is discovered due to a match. Attention This API should be called after a NAN service is discovered due to a match. Parameters fup_params -- Configuration parameters for sending a Follow-up message. Returns ESP_OK: succeed others: failed ESP_OK: succeed others: failed ESP_OK: succeed Parameters fup_params -- Configuration parameters for sending a Follow-up message. Returns ESP_OK: succeed others: failed esp_err_t esp_wifi_nan_cancel_service(uint8_t service_id) Cancel a NAN service. Parameters service_id -- Publish/Subscribe service id to be cancelled. Returns ESP_OK: succeed others: failed ESP_OK: succeed others: failed ESP_OK: succeed Parameters service_id -- Publish/Subscribe service id to be cancelled. Returns ESP_OK: succeed others: failed uint8_t esp_wifi_nan_datapath_req(wifi_nan_datapath_req_t *req) Send NAN Datapath Request to a NAN Publisher with matched service. Attention This API should be called by the Subscriber after a match occurs with a Publisher. Attention This API should be called by the Subscriber after a match occurs with a Publisher. Parameters req -- NAN Datapath Request parameters. Returns non-zero NAN Datapath identifier: If NAN datapath req was accepted by publisher zero: If NAN datapath req was rejected by publisher or a timeout occurs non-zero NAN Datapath identifier: If NAN datapath req was accepted by publisher zero: If NAN datapath req was rejected by publisher or a timeout occurs non-zero NAN Datapath identifier: If NAN datapath req was accepted by publisher Parameters req -- NAN Datapath Request parameters. Returns non-zero NAN Datapath identifier: If NAN datapath req was accepted by publisher zero: If NAN datapath req was rejected by publisher or a timeout occurs esp_err_t esp_wifi_nan_datapath_resp(wifi_nan_datapath_resp_t *resp) Respond to a NAN Datapath request with Accept or Reject. Attention This API should be called if ndp_resp_needed is set True by the Publisher and a WIFI_EVENT_NDP_INDICATION event is received due to an incoming NDP request. Attention This API should be called if ndp_resp_needed is set True by the Publisher and a WIFI_EVENT_NDP_INDICATION event is received due to an incoming NDP request. Parameters resp -- NAN Datapath Response parameters. Returns ESP_OK: succeed others: failed ESP_OK: succeed others: failed ESP_OK: succeed Parameters resp -- NAN Datapath Response parameters. Returns ESP_OK: succeed others: failed esp_err_t esp_wifi_nan_datapath_end(wifi_nan_datapath_end_req_t *req) Terminate a NAN Datapath. Parameters req -- NAN Datapath end request parameters. Returns ESP_OK: succeed others: failed ESP_OK: succeed others: failed ESP_OK: succeed Parameters req -- NAN Datapath end request parameters. Returns ESP_OK: succeed others: failed void esp_wifi_nan_get_ipv6_linklocal_from_mac(ip6_addr_t *ip6, uint8_t *mac_addr) Get IPv6 Link Local address using MAC address. Parameters ip6 -- [out] Derived IPv6 Link Local address. mac_addr -- [in] Input MAC Address. ip6 -- [out] Derived IPv6 Link Local address. mac_addr -- [in] Input MAC Address. ip6 -- [out] Derived IPv6 Link Local address. Parameters ip6 -- [out] Derived IPv6 Link Local address. mac_addr -- [in] Input MAC Address. esp_err_t esp_wifi_nan_get_own_svc_info(uint8_t *own_svc_id, char *svc_name, int *num_peer_records) brief Get own Service information from Service ID OR Name. Attention If service information is to be fetched from service name, set own_svc_id as zero. Attention If service information is to be fetched from service name, set own_svc_id as zero. Parameters own_svc_id -- [inout] As input, it indicates Service ID to search for. As output, it indicates Service ID of the service found using Service Name. svc_name -- [inout] As input, it indicates Service Name to search for. As output, it indicates Service Name of the service found using Service ID. num_peer_records -- [out] Number of peers discovered by corresponding service. own_svc_id -- [inout] As input, it indicates Service ID to search for. As output, it indicates Service ID of the service found using Service Name. svc_name -- [inout] As input, it indicates Service Name to search for. As output, it indicates Service Name of the service found using Service ID. num_peer_records -- [out] Number of peers discovered by corresponding service. own_svc_id -- [inout] As input, it indicates Service ID to search for. As output, it indicates Service ID of the service found using Service Name. Returns ESP_OK: succeed ESP_FAIL: failed ESP_OK: succeed ESP_FAIL: failed ESP_OK: succeed Parameters own_svc_id -- [inout] As input, it indicates Service ID to search for. As output, it indicates Service ID of the service found using Service Name. svc_name -- [inout] As input, it indicates Service Name to search for. As output, it indicates Service Name of the service found using Service ID. num_peer_records -- [out] Number of peers discovered by corresponding service. Returns ESP_OK: succeed ESP_FAIL: failed esp_err_t esp_wifi_nan_get_peer_records(int *num_peer_records, uint8_t own_svc_id, struct nan_peer_record *peer_record) brief Get a list of Peers discovered by the given Service. Parameters num_peer_records -- [inout] As input param, it stores max peers peer_record can hold. As output param, it specifies the actual number of peers this API returns. own_svc_id -- Service ID of own service. peer_record -- [out] Pointer to first peer record. num_peer_records -- [inout] As input param, it stores max peers peer_record can hold. As output param, it specifies the actual number of peers this API returns. own_svc_id -- Service ID of own service. peer_record -- [out] Pointer to first peer record. num_peer_records -- [inout] As input param, it stores max peers peer_record can hold. As output param, it specifies the actual number of peers this API returns. Returns ESP_OK: succeed ESP_FAIL: failed ESP_OK: succeed ESP_FAIL: failed ESP_OK: succeed Parameters num_peer_records -- [inout] As input param, it stores max peers peer_record can hold. As output param, it specifies the actual number of peers this API returns. own_svc_id -- Service ID of own service. peer_record -- [out] Pointer to first peer record. Returns ESP_OK: succeed ESP_FAIL: failed esp_err_t esp_wifi_nan_get_peer_info(char *svc_name, uint8_t *peer_mac, struct nan_peer_record *peer_info) brief Find Peer's Service information using Peer MAC and optionally Service Name. Parameters svc_name -- Service Name of the published/subscribed service. peer_mac -- Peer's NAN Management Interface MAC address. peer_info -- [out] Peer's service information structure. svc_name -- Service Name of the published/subscribed service. peer_mac -- Peer's NAN Management Interface MAC address. peer_info -- [out] Peer's service information structure. svc_name -- Service Name of the published/subscribed service. Returns ESP_OK: succeed ESP_FAIL: failed ESP_OK: succeed ESP_FAIL: failed ESP_OK: succeed Parameters svc_name -- Service Name of the published/subscribed service. peer_mac -- Peer's NAN Management Interface MAC address. peer_info -- [out] Peer's service information structure. Returns ESP_OK: succeed ESP_FAIL: failed Structures struct nan_peer_record Parameters of a peer service record Public Members uint8_t peer_svc_id Identifier of Peer's service uint8_t peer_svc_id Identifier of Peer's service uint8_t own_svc_id Identifier of own service associated with Peer uint8_t own_svc_id Identifier of own service associated with Peer uint8_t peer_nmi[6] Peer's NAN Management Interface address uint8_t peer_nmi[6] Peer's NAN Management Interface address uint8_t peer_svc_type Peer's service type (Publish/Subscribe) uint8_t peer_svc_type Peer's service type (Publish/Subscribe) uint8_t ndp_id Specifies if the peer has any active datapath uint8_t ndp_id Specifies if the peer has any active datapath uint8_t peer_ndi[6] Peer's NAN Data Interface address, only valid when ndp_id is non-zero uint8_t peer_ndi[6] Peer's NAN Data Interface address, only valid when ndp_id is non-zero uint8_t peer_svc_id Macros WIFI_NAN_CONFIG_DEFAULT() NDP_STATUS_ACCEPTED NDP_STATUS_REJECTED NAN_MAX_PEERS_RECORD ESP_NAN_PUBLISH ESP_NAN_SUBSCRIBE
Wi-Fi AwareTM (NAN) Wi-Fi AwareTM 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. ESP32 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: wifi/wifi_aware/nan_publisher and wifi/wifi_aware/nan_subscriber. A user interactive console example to explore full functionality of Wi-Fi Aware: wifi/wifi_aware/nan_console. Please check the README for more details in respective example directories. API Reference Header File This header file can be included with: #include "esp_nan.h" This header file is a part of the API provided by the esp_wificomponent. To declare that your component depends on esp_wifi, add the following to your CMakeLists.txt: REQUIRES esp_wifi or PRIV_REQUIRES esp_wifi Functions - esp_err_t esp_wifi_nan_start(const wifi_nan_config_t *nan_cfg) Start NAN Discovery with provided configuration. - Attention This API should be called after esp_wifi_init(). - Parameters nan_cfg -- NAN related parameters to be configured. - Returns ESP_OK: succeed others: failed - - esp_err_t esp_wifi_nan_stop(void) Stop NAN Discovery, end NAN Services and Datapaths. - Returns ESP_OK: succeed others: failed - - uint8_t esp_wifi_nan_publish_service(const wifi_nan_publish_cfg_t *publish_cfg, bool ndp_resp_needed) Start Publishing a service to the NAN Peers in vicinity. - Attention This API should be called after esp_wifi_nan_start(). - Parameters publish_cfg -- Configuration parameters for publishing a service. ndp_resp_needed -- Setting this true will require user response for every NDP Req using esp_wifi_nan_datapath_resp API. - - Returns non-zero: Publish service identifier zero: failed - - uint8_t esp_wifi_nan_subscribe_service(const wifi_nan_subscribe_cfg_t *subscribe_cfg) Subscribe for a service within the NAN cluster. - Attention This API should be called after esp_wifi_nan_start(). - Parameters subscribe_cfg -- Configuration parameters for subscribing for a service. - Returns non-zero: Subscribe service identifier zero: failed - - esp_err_t esp_wifi_nan_send_message(wifi_nan_followup_params_t *fup_params) Send a follow-up message to the NAN Peer with matched service. - Attention This API should be called after a NAN service is discovered due to a match. - Parameters fup_params -- Configuration parameters for sending a Follow-up message. - Returns ESP_OK: succeed others: failed - - esp_err_t esp_wifi_nan_cancel_service(uint8_t service_id) Cancel a NAN service. - Parameters service_id -- Publish/Subscribe service id to be cancelled. - Returns ESP_OK: succeed others: failed - - uint8_t esp_wifi_nan_datapath_req(wifi_nan_datapath_req_t *req) Send NAN Datapath Request to a NAN Publisher with matched service. - Attention This API should be called by the Subscriber after a match occurs with a Publisher. - Parameters req -- NAN Datapath Request parameters. - Returns non-zero NAN Datapath identifier: If NAN datapath req was accepted by publisher zero: If NAN datapath req was rejected by publisher or a timeout occurs - - esp_err_t esp_wifi_nan_datapath_resp(wifi_nan_datapath_resp_t *resp) Respond to a NAN Datapath request with Accept or Reject. - Attention This API should be called if ndp_resp_needed is set True by the Publisher and a WIFI_EVENT_NDP_INDICATION event is received due to an incoming NDP request. - Parameters resp -- NAN Datapath Response parameters. - Returns ESP_OK: succeed others: failed - - esp_err_t esp_wifi_nan_datapath_end(wifi_nan_datapath_end_req_t *req) Terminate a NAN Datapath. - Parameters req -- NAN Datapath end request parameters. - Returns ESP_OK: succeed others: failed - - void esp_wifi_nan_get_ipv6_linklocal_from_mac(ip6_addr_t *ip6, uint8_t *mac_addr) Get IPv6 Link Local address using MAC address. - Parameters ip6 -- [out] Derived IPv6 Link Local address. mac_addr -- [in] Input MAC Address. - - esp_err_t esp_wifi_nan_get_own_svc_info(uint8_t *own_svc_id, char *svc_name, int *num_peer_records) brief Get own Service information from Service ID OR Name. - Attention If service information is to be fetched from service name, set own_svc_id as zero. - Parameters own_svc_id -- [inout] As input, it indicates Service ID to search for. As output, it indicates Service ID of the service found using Service Name. svc_name -- [inout] As input, it indicates Service Name to search for. As output, it indicates Service Name of the service found using Service ID. num_peer_records -- [out] Number of peers discovered by corresponding service. - - Returns ESP_OK: succeed ESP_FAIL: failed - - esp_err_t esp_wifi_nan_get_peer_records(int *num_peer_records, uint8_t own_svc_id, struct nan_peer_record *peer_record) brief Get a list of Peers discovered by the given Service. - Parameters num_peer_records -- [inout] As input param, it stores max peers peer_record can hold. As output param, it specifies the actual number of peers this API returns. own_svc_id -- Service ID of own service. peer_record -- [out] Pointer to first peer record. - - Returns ESP_OK: succeed ESP_FAIL: failed - - esp_err_t esp_wifi_nan_get_peer_info(char *svc_name, uint8_t *peer_mac, struct nan_peer_record *peer_info) brief Find Peer's Service information using Peer MAC and optionally Service Name. - Parameters svc_name -- Service Name of the published/subscribed service. peer_mac -- Peer's NAN Management Interface MAC address. peer_info -- [out] Peer's service information structure. - - Returns ESP_OK: succeed ESP_FAIL: failed - Structures - struct nan_peer_record Parameters of a peer service record Public Members - uint8_t peer_svc_id Identifier of Peer's service - uint8_t own_svc_id Identifier of own service associated with Peer - uint8_t peer_nmi[6] Peer's NAN Management Interface address - uint8_t peer_svc_type Peer's service type (Publish/Subscribe) - uint8_t ndp_id Specifies if the peer has any active datapath - uint8_t peer_ndi[6] Peer's NAN Data Interface address, only valid when ndp_id is non-zero - uint8_t peer_svc_id Macros - WIFI_NAN_CONFIG_DEFAULT() - NDP_STATUS_ACCEPTED - NDP_STATUS_REJECTED - NAN_MAX_PEERS_RECORD - ESP_NAN_PUBLISH - ESP_NAN_SUBSCRIBE
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/network/esp_nan.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Ethernet
null
espressif.com
2016-01-01
ee7cda19a526db94
null
null
Ethernet Overview ESP-IDF provides a set of consistent and flexible APIs to support both internal Ethernet MAC (EMAC) controller and external SPI-Ethernet modules. This programming guide is split into the following sections: Basic Ethernet Concepts Ethernet is an asynchronous Carrier Sense Multiple Access with Collision Detect (CSMA/CD) protocol/interface. It is generally not well suited for low-power applications. However, with ubiquitous deployment, internet connectivity, high data rates, and limitless-range expandability, Ethernet can accommodate nearly all wired communications. Normal IEEE 802.3 compliant Ethernet frames are between 64 and 1518 bytes in length. They are made up of five or six different fields: a destination MAC address (DA), a source MAC address (SA), a type/length field, a data payload, an optional padding field and a Cyclic Redundancy Check (CRC). Additionally, when transmitted on the Ethernet medium, a 7-byte preamble field and Start-of-Frame (SOF) delimiter byte are appended to the beginning of the Ethernet packet. Thus the traffic on the twist-pair cabling appears as shown below: Preamble and Start-of-Frame Delimiter The preamble contains seven bytes of 55H . It allows the receiver to lock onto the stream of data before the actual frame arrives. The Start-of-Frame Delimiter (SFD) is a binary sequence 10101011 (as seen on the physical medium). It is sometimes considered to be part of the preamble. When transmitting and receiving data, the preamble and SFD bytes will be automatically generated or stripped from the packets. Destination Address The destination address field contains a 6-byte length MAC address of the device that the packet is directed to. If the Least Significant bit in the first byte of the MAC address is set, the address is a multicast destination. For example, 01-00-00-00-F0-00 and 33-45-67-89-AB-CD are multi-cast addresses, while 00-00-00-00-F0-00 and 32-45-67-89-AB-CD are not. Packets with multi-cast destination addresses are designed to arrive and be important to a selected group of Ethernet nodes. If the destination address field is the reserved multicast address, i.e., FF-FF-FF-FF-FF-FF, the packet is a broadcast packet and it will be directed to everyone sharing the network. If the Least Significant bit in the first byte of the MAC address is clear, the address is a unicast address and will be designed for usage by only the addressed node. Normally the EMAC controller incorporates receive filters which can be used to discard or accept packets with multi-cast, broadcast and/or unicast destination addresses. When transmitting packets, the host controller is responsible for writing the desired destination address into the transmit buffer. Source Address The source address field contains a 6-byte length MAC address of the node which created the Ethernet packet. Users of Ethernet must generate a unique MAC address for each controller used. MAC addresses consist of two portions. The first three bytes are known as the Organizationally Unique Identifier (OUI). OUIs are distributed by the IEEE. The last three bytes are address bytes at the discretion of the company that purchased the OUI. For more information about MAC Address used in ESP-IDF, please see MAC Address Allocation. When transmitting packets, the assigned source MAC address must be written into the transmit buffer by the host controller. Type/Length The type/length field is a 2-byte field. If the value in this field is <= 1500 (decimal), it is considered a length field and it specifies the amount of non-padding data which follows in the data field. If the value is >= 1536, it represents the protocol the following packet data belongs to. The followings are the most common type values: IPv4 = 0800H IPv6 = 86DDH ARP = 0806H Users implementing proprietary networks may choose to treat this field as a length field, while applications implementing protocols such as the Internet Protocol (IP) or Address Resolution Protocol (ARP), should program this field with the appropriate type defined by the protocol's specification when transmitting packets. Payload The payload field is a variable length field, anywhere from 0 to 1500 bytes. Larger data packets violates Ethernet standards and will be dropped by most Ethernet nodes. This field contains the client data, such as an IP datagram. Padding and FCS The padding field is a variable length field added to meet the IEEE 802.3 specification requirements when small data payloads are used. The DA, SA, type, payload, and padding of an Ethernet packet must be no smaller than 60 bytes in total. If the required 4-byte FCS field is added, packets must be no smaller than 64 bytes. If the payload field is less than 46-byte long, a padding field is required. The FCS field is a 4-byte field that contains an industry-standard 32-bit CRC calculated with the data from the DA, SA, type, payload, and padding fields. Given the complexity of calculating a CRC, the hardware normally automatically generates a valid CRC and transmit it. Otherwise, the host controller must generate the CRC and place it in the transmit buffer. Normally, the host controller does not need to concern itself with padding and the CRC which the hardware EMAC will also be able to automatically generate when transmitting and verify when receiving. However, the padding and CRC fields will be written into the receive buffer when packets arrive, so they may be evaluated by the host controller if needed. Note Besides the basic data frame described above, there are two other common frame types in 10/100 Mbps Ethernet: control frames and VLAN-tagged frames. They are not supported in ESP-IDF. Configure MAC and PHY The Ethernet driver is composed of two parts: MAC and PHY. The communication between MAC and PHY can have diverse choices: MII (Media Independent Interface), RMII (Reduced Media Independent Interface), etc. One of the obvious differences between MII and RMII is signal consumption. MII usually costs up to 18 signals, while the RMII interface can reduce the consumption to 9. In RMII mode, both the receiver and transmitter signals are referenced to the REF_CLK . REF_CLK must be stable during any access to PHY and MAC. Generally, there are three ways to generate the REF_CLK depending on the PHY device in your design: Some PHY chips can derive the REF_CLK from its externally connected 25 MHz crystal oscillator (as seen the option a in the picture). In this case, you should select CONFIG_ETH_RMII_CLK_INPUT in CONFIG_ETH_RMII_CLK_MODE. Some PHY chip uses an externally connected 50MHz crystal oscillator or other clock sources, which can also be used as the REF_CLK for the MAC side (as seen the option b in the picture). In this case, you still need to select CONFIG_ETH_RMII_CLK_INPUT in CONFIG_ETH_RMII_CLK_MODE. Some EMAC controllers can generate the REF_CLK using an internal high-precision PLL (as seen the option c in the picture). In this case, you should select CONFIG_ETH_RMII_CLK_OUTPUT in CONFIG_ETH_RMII_CLK_MODE. Note REF_CLK is configured via Project Configuration as described above by default. However, it can be overwritten from user application code by appropriately setting eth_esp32_emac_config_t::interface and eth_esp32_emac_config_t::clock_config members. See emac_rmii_clock_mode_t and emac_rmii_clock_gpio_t for more details. Warning If the RMII clock mode is selected to CONFIG_ETH_RMII_CLK_OUTPUT , then GPIO0 can be used to output the REF_CLK signal. See CONFIG_ETH_RMII_CLK_OUTPUT_GPIO0 for more information. What is more, if you are not using PSRAM in your design, GPIO16 and GPIO17 are also available to output the reference clock. See CONFIG_ETH_RMII_CLK_OUT_GPIO for more information. If the RMII clock mode is selected to CONFIG_ETH_RMII_CLK_INPUT , then GPIO0 is the only choice to input the REF_CLK signal. Please note that GPIO0 is also an important strapping GPIO on ESP32. If GPIO0 samples a low level during power-up, ESP32 will go into download mode. The system will get halted until a manually reset. The workaround for this issue is disabling the REF_CLK in hardware by default so that the strapping pin is not interfered by other signals in the boot stage. Then, re-enable the REF_CLK in the Ethernet driver installation stage. The ways to disable the REF_CLK signal can be: Disable or power down the crystal oscillator (as the case b in the picture). Force the PHY device to reset status (as the case a in the picture). This could fail for some PHY device (i.e., it still outputs signals to GPIO0 even in reset state). No matter which RMII clock mode you select, you really need to take care of the signal integrity of REF_CLK in your hardware design! Keep the trace as short as possible. Keep it away from RF devices and inductor elements. Note ESP-IDF only supports the RMII interface (i.e., always select CONFIG_ETH_PHY_INTERFACE_RMII in the Kconfig option CONFIG_ETH_PHY_INTERFACE). Signals used in the data plane are fixed to specific GPIOs via MUX, they can not be modified to other GPIOs. Signals used in the control plane can be routed to any free GPIOs via Matrix. Please refer to ESP32-Ethernet-Kit for hardware design example. You need to set up the necessary parameters for MAC and PHY respectively based on your Ethernet board design, and then combine the two together to complete the driver installation. Configuration for MAC is described in eth_mac_config_t , including: eth_mac_config_t::sw_reset_timeout_ms : software reset timeout value, in milliseconds. Typically, MAC reset should be finished within 100 ms. eth_mac_config_t::rx_task_stack_size and eth_mac_config_t::rx_task_prio : the MAC driver creates a dedicated task to process incoming packets. These two parameters are used to set the stack size and priority of the task. eth_mac_config_t::flags : specifying extra features that the MAC driver should have, it could be useful in some special situations. The value of this field can be OR'd with macros prefixed with ETH_MAC_FLAG_ . For example, if the MAC driver should work when the cache is disabled, then you should configure this field with ETH_MAC_FLAG_WORK_WITH_CACHE_DISABLE . eth_esp32_emac_config_t::smi_mdc_gpio_num and eth_esp32_emac_config_t::smi_mdio_gpio_num : the GPIO number used to connect the SMI signals. eth_esp32_emac_config_t::interface : configuration of MAC Data interface to PHY (MII/RMII). eth_esp32_emac_config_t::clock_config : configuration of EMAC Interface clock ( REF_CLK mode and GPIO number in case of RMII). Configuration for PHY is described in eth_phy_config_t , including: eth_phy_config_t::phy_addr : multiple PHY devices can share the same SMI bus, so each PHY needs a unique address. Usually, this address is configured during hardware design by pulling up/down some PHY strapping pins. You can set the value from 0 to 15 based on your Ethernet board. Especially, if the SMI bus is shared by only one PHY device, setting this value to -1 can enable the driver to detect the PHY address automatically. eth_phy_config_t::reset_timeout_ms : reset timeout value, in milliseconds. Typically, PHY reset should be finished within 100 ms. eth_phy_config_t::autonego_timeout_ms : auto-negotiation timeout value, in milliseconds. The Ethernet driver starts negotiation with the peer Ethernet node automatically, to determine to duplex and speed mode. This value usually depends on the ability of the PHY device on your board. eth_phy_config_t::reset_gpio_num : if your board also connects the PHY reset pin to one of the GPIO, then set it here. Otherwise, set this field to -1 . ESP-IDF provides a default configuration for MAC and PHY in macro ETH_MAC_DEFAULT_CONFIG and ETH_PHY_DEFAULT_CONFIG . Create MAC and PHY Instance The Ethernet driver is implemented in an Object-Oriented style. Any operation on MAC and PHY should be based on the instance of the two. Internal EMAC + External PHY eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG(); // apply default common MAC configuration eth_esp32_emac_config_t esp32_emac_config = ETH_ESP32_EMAC_DEFAULT_CONFIG(); // apply default vendor-specific MAC configuration esp32_emac_config.smi_mdc_gpio_num = CONFIG_EXAMPLE_ETH_MDC_GPIO; // alter the GPIO used for MDC signal esp32_emac_config.smi_mdio_gpio_num = CONFIG_EXAMPLE_ETH_MDIO_GPIO; // alter the GPIO used for MDIO signal esp_eth_mac_t *mac = esp_eth_mac_new_esp32(&esp32_emac_config, &mac_config); // create MAC instance eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG(); // apply default PHY configuration phy_config.phy_addr = CONFIG_EXAMPLE_ETH_PHY_ADDR; // alter the PHY address according to your board design phy_config.reset_gpio_num = CONFIG_EXAMPLE_ETH_PHY_RST_GPIO; // alter the GPIO used for PHY reset esp_eth_phy_t *phy = esp_eth_phy_new_ip101(&phy_config); // create PHY instance // ESP-IDF officially supports several different Ethernet PHY chip driver // esp_eth_phy_t *phy = esp_eth_phy_new_rtl8201(&phy_config); // esp_eth_phy_t *phy = esp_eth_phy_new_lan8720(&phy_config); // esp_eth_phy_t *phy = esp_eth_phy_new_dp83848(&phy_config); Optional Runtime MAC Clock Configuration EMAC REF_CLK can be optionally configured from the user application code. eth_esp32_emac_config_t esp32_emac_config = ETH_ESP32_EMAC_DEFAULT_CONFIG(); // apply default vendor-specific MAC configuration // ... esp32_emac_config.interface = EMAC_DATA_INTERFACE_RMII; // alter EMAC Data Interface esp32_emac_config.clock_config.rmii.clock_mode = EMAC_CLK_OUT; // select EMAC REF_CLK mode esp32_emac_config.clock_config.rmii.clock_gpio = EMAC_CLK_OUT_GPIO; // select GPIO number used to input/output EMAC REF_CLK esp_eth_mac_t *mac = esp_eth_mac_new_esp32(&esp32_emac_config, &mac_config); // create MAC instance SPI-Ethernet Module eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG(); // apply default common MAC configuration eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG(); // apply default PHY configuration phy_config.phy_addr = CONFIG_EXAMPLE_ETH_PHY_ADDR; // alter the PHY address according to your board design phy_config.reset_gpio_num = CONFIG_EXAMPLE_ETH_PHY_RST_GPIO; // alter the GPIO used for PHY reset // Install GPIO interrupt service (as the SPI-Ethernet module is interrupt-driven) gpio_install_isr_service(0); // SPI bus configuration spi_device_handle_t spi_handle = NULL; spi_bus_config_t buscfg = { .miso_io_num = CONFIG_EXAMPLE_ETH_SPI_MISO_GPIO, .mosi_io_num = CONFIG_EXAMPLE_ETH_SPI_MOSI_GPIO, .sclk_io_num = CONFIG_EXAMPLE_ETH_SPI_SCLK_GPIO, .quadwp_io_num = -1, .quadhd_io_num = -1, }; ESP_ERROR_CHECK(spi_bus_initialize(CONFIG_EXAMPLE_ETH_SPI_HOST, &buscfg, 1)); // Configure SPI device spi_device_interface_config_t spi_devcfg = { .mode = 0, .clock_speed_hz = CONFIG_EXAMPLE_ETH_SPI_CLOCK_MHZ * 1000 * 1000, .spics_io_num = CONFIG_EXAMPLE_ETH_SPI_CS_GPIO, .queue_size = 20 }; /* dm9051 ethernet driver is based on spi driver */ eth_dm9051_config_t dm9051_config = ETH_DM9051_DEFAULT_CONFIG(CONFIG_EXAMPLE_ETH_SPI_HOST, &spi_devcfg); dm9051_config.int_gpio_num = CONFIG_EXAMPLE_ETH_SPI_INT_GPIO; esp_eth_mac_t *mac = esp_eth_mac_new_dm9051(&dm9051_config, &mac_config); esp_eth_phy_t *phy = esp_eth_phy_new_dm9051(&phy_config); Note When creating MAC and PHY instances for SPI-Ethernet modules (e.g., DM9051), the constructor function must have the same suffix (e.g., esp_eth_mac_new_dm9051 and esp_eth_phy_new_dm9051). This is because we don not have other choices but the integrated PHY. The SPI device configuration (i.e., spi_device_interface_config_t) may slightly differ for other Ethernet modules or to meet SPI timing on specific PCB. Please check out your module's specs and the examples in ESP-IDF. Install Driver To install the Ethernet driver, we need to combine the instance of MAC and PHY and set some additional high-level configurations (i.e., not specific to either MAC or PHY) in esp_eth_config_t : esp_eth_config_t::mac : instance that created from MAC generator (e.g., esp_eth_mac_new_esp32() ). esp_eth_config_t::phy : instance that created from PHY generator (e.g., esp_eth_phy_new_ip101() ). esp_eth_config_t::check_link_period_ms : Ethernet driver starts an OS timer to check the link status periodically, this field is used to set the interval, in milliseconds. esp_eth_config_t::stack_input : In most Ethernet IoT applications, any Ethernet frame received by a driver should be passed to the upper layer (e.g., TCP/IP stack). This field is set to a function that is responsible to deal with the incoming frames. You can even update this field at runtime via function esp_eth_update_input_path() after driver installation. esp_eth_config_t::on_lowlevel_init_done and esp_eth_config_t::on_lowlevel_deinit_done : These two fields are used to specify the hooks which get invoked when low-level hardware has been initialized or de-initialized. ESP-IDF provides a default configuration for driver installation in macro ETH_DEFAULT_CONFIG . esp_eth_config_t config = ETH_DEFAULT_CONFIG(mac, phy); // apply default driver configuration esp_eth_handle_t eth_handle = NULL; // after the driver is installed, we will get the handle of the driver esp_eth_driver_install(&config, &eth_handle); // install driver The Ethernet driver also includes an event-driven model, which sends useful and important events to user space. We need to initialize the event loop before installing the Ethernet driver. For more information about event-driven programming, please refer to ESP Event. /** Event handler for Ethernet events */ static void eth_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { uint8_t mac_addr[6] = {0}; /* we can get the ethernet driver handle from event data */ esp_eth_handle_t eth_handle = *(esp_eth_handle_t *)event_data; switch (event_id) { case ETHERNET_EVENT_CONNECTED: esp_eth_ioctl(eth_handle, ETH_CMD_G_MAC_ADDR, mac_addr); ESP_LOGI(TAG, "Ethernet Link Up"); ESP_LOGI(TAG, "Ethernet HW Addr %02x:%02x:%02x:%02x:%02x:%02x", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); break; case ETHERNET_EVENT_DISCONNECTED: ESP_LOGI(TAG, "Ethernet Link Down"); break; case ETHERNET_EVENT_START: ESP_LOGI(TAG, "Ethernet Started"); break; case ETHERNET_EVENT_STOP: ESP_LOGI(TAG, "Ethernet Stopped"); break; default: break; } } esp_event_loop_create_default(); // create a default event loop that runs in the background esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, &eth_event_handler, NULL); // register Ethernet event handler (to deal with user-specific stuff when events like link up/down happened) Start Ethernet Driver After driver installation, we can start Ethernet immediately. esp_eth_start(eth_handle); // start Ethernet driver state machine Connect Driver to TCP/IP Stack Up until now, we have installed the Ethernet driver. From the view of OSI (Open System Interconnection), we are still on level 2 (i.e., Data Link Layer). While we can detect link up and down events and gain MAC address in user space, it is infeasible to obtain the IP address, let alone send an HTTP request. The TCP/IP stack used in ESP-IDF is called LwIP. For more information about it, please refer to LwIP. To connect the Ethernet driver to TCP/IP stack, follow these three steps: Create a network interface for the Ethernet driver Attach the network interface to the Ethernet driver Register IP event handlers For more information about the network interface, please refer to Network Interface. /** Event handler for IP_EVENT_ETH_GOT_IP */ static void got_ip_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { ip_event_got_ip_t *event = (ip_event_got_ip_t *) event_data; const esp_netif_ip_info_t *ip_info = &event->ip_info; ESP_LOGI(TAG, "Ethernet Got IP Address"); ESP_LOGI(TAG, "~~~~~~~~~~~"); ESP_LOGI(TAG, "ETHIP:" IPSTR, IP2STR(&ip_info->ip)); ESP_LOGI(TAG, "ETHMASK:" IPSTR, IP2STR(&ip_info->netmask)); ESP_LOGI(TAG, "ETHGW:" IPSTR, IP2STR(&ip_info->gw)); ESP_LOGI(TAG, "~~~~~~~~~~~"); } esp_netif_init()); // Initialize TCP/IP network interface (should be called only once in application) esp_netif_config_t cfg = ESP_NETIF_DEFAULT_ETH(); // apply default network interface configuration for Ethernet esp_netif_t *eth_netif = esp_netif_new(&cfg); // create network interface for Ethernet driver esp_netif_attach(eth_netif, esp_eth_new_netif_glue(eth_handle)); // attach Ethernet driver to TCP/IP stack esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &got_ip_event_handler, NULL); // register user defined IP event handlers esp_eth_start(eth_handle); // start Ethernet driver state machine Warning It is recommended to fully initialize the Ethernet driver and network interface before registering the user's Ethernet/IP event handlers, i.e., register the event handlers as the last thing prior to starting the Ethernet driver. Such an approach ensures that Ethernet/IP events get executed first by the Ethernet driver or network interface so the system is in the expected state when executing the user's handlers. Misc Control of Ethernet Driver The following functions should only be invoked after the Ethernet driver has been installed. Stop Ethernet driver: esp_eth_stop() Update Ethernet data input path: esp_eth_update_input_path() Misc get/set of Ethernet driver attributes: esp_eth_ioctl() /* get MAC address */ uint8_t mac_addr[6]; memset(mac_addr, 0, sizeof(mac_addr)); esp_eth_ioctl(eth_handle, ETH_CMD_G_MAC_ADDR, mac_addr); ESP_LOGI(TAG, "Ethernet MAC Address: %02x:%02x:%02x:%02x:%02x:%02x", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); /* get PHY address */ int phy_addr = -1; esp_eth_ioctl(eth_handle, ETH_CMD_G_PHY_ADDR, &phy_addr); ESP_LOGI(TAG, "Ethernet PHY Address: %d", phy_addr); Flow Control Ethernet on MCU usually has a limitation in the number of frames it can handle during network congestion, because of the limitation in RAM size. A sending station might be transmitting data faster than the peer end can accept it. The ethernet flow control mechanism allows the receiving node to signal the sender requesting the suspension of transmissions until the receiver catches up. The magic behind that is the pause frame, which was defined in IEEE 802.3x. Pause frame is a special Ethernet frame used to carry the pause command, whose EtherType field is 0x8808 , with the Control opcode set to 0x0001 . Only stations configured for full-duplex operation may send pause frames. When a station wishes to pause the other end of a link, it sends a pause frame to the 48-bit reserved multicast address of 01-80-C2-00-00-01 . The pause frame also includes the period of pause time being requested, in the form of a two-byte integer, ranging from 0 to 65535 . After the Ethernet driver installation, the flow control feature is disabled by default. You can enable it by: 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. Application Examples Ethernet basic example: ethernet/basic Ethernet iperf example: ethernet/iperf Ethernet to Wi-Fi AP "router": network/eth2ap Wi-Fi station to Ethernet "bridge": network/sta2eth Most protocol examples should also work for Ethernet: protocols 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. A set of management registers is defined to control chip behavior, link properties, auto-negotiation configuration, etc. This basic management functionality is addressed by 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 esp_eth/src/esp_eth_phy_802_3.c. However, the following may require developing chip-specific management functions: Link status which is almost always chip-specific Chip initialization, even though not strictly required, should be customized to at least ensure that the expected chip is used Chip-specific features configuration Steps to create a custom PHY driver: Define vendor-specific registry layout based on the PHY datasheet. See esp_eth/src/esp_eth_phy_ip101.c as an example. Prepare derived PHY management object info structure which: must contain at least parent IEEE 802.3 phy_802_3_t object optionally contain additional variables needed to support non-IEEE 802.3 or customized functionality. See esp_eth/src/esp_eth_phy_ksz80xx.c as an example. must contain at least parent IEEE 802.3 phy_802_3_t object optionally contain additional variables needed to support non-IEEE 802.3 or customized functionality. See esp_eth/src/esp_eth_phy_ksz80xx.c as an example. must contain at least parent IEEE 802.3 phy_802_3_t object Define chip-specific management call-back functions. Initialize parent IEEE 802.3 object and re-assign chip-specific management call-back functions. Once you finish the new custom PHY driver implementation, consider sharing it among other users via IDF Component Registry. API Reference Header File This header file can be included with: #include "esp_eth.h" This header file is a part of the API provided by the esp_eth component. To declare that your component depends on esp_eth , add the following to your CMakeLists.txt: REQUIRES esp_eth or PRIV_REQUIRES esp_eth Header File This header file can be included with: #include "esp_eth_driver.h" This header file is a part of the API provided by the esp_eth component. To declare that your component depends on esp_eth , add the following to your CMakeLists.txt: REQUIRES esp_eth or PRIV_REQUIRES esp_eth Functions esp_err_t esp_eth_driver_install(const esp_eth_config_t *config, esp_eth_handle_t *out_hdl) Install Ethernet driver. Parameters config -- [in] configuration of the Ethernet driver out_hdl -- [out] handle of Ethernet driver config -- [in] configuration of the Ethernet driver out_hdl -- [out] handle of Ethernet driver config -- [in] configuration of the Ethernet driver Returns ESP_OK: install esp_eth driver successfully ESP_ERR_INVALID_ARG: install esp_eth driver failed because of some invalid argument ESP_ERR_NO_MEM: install esp_eth driver failed because there's no memory for driver ESP_FAIL: install esp_eth driver failed because some other error occurred ESP_OK: install esp_eth driver successfully ESP_ERR_INVALID_ARG: install esp_eth driver failed because of some invalid argument ESP_ERR_NO_MEM: install esp_eth driver failed because there's no memory for driver ESP_FAIL: install esp_eth driver failed because some other error occurred ESP_OK: install esp_eth driver successfully Parameters config -- [in] configuration of the Ethernet driver out_hdl -- [out] handle of Ethernet driver Returns ESP_OK: install esp_eth driver successfully ESP_ERR_INVALID_ARG: install esp_eth driver failed because of some invalid argument ESP_ERR_NO_MEM: install esp_eth driver failed because there's no memory for driver ESP_FAIL: install esp_eth driver failed because some other error occurred esp_err_t esp_eth_driver_uninstall(esp_eth_handle_t hdl) Uninstall Ethernet driver. Note It's not recommended to uninstall Ethernet driver unless it won't get used any more in application code. To uninstall Ethernet driver, you have to make sure, all references to the driver are released. Ethernet driver can only be uninstalled successfully when reference counter equals to one. Parameters hdl -- [in] handle of Ethernet driver Returns ESP_OK: uninstall esp_eth driver successfully ESP_ERR_INVALID_ARG: uninstall esp_eth driver failed because of some invalid argument ESP_ERR_INVALID_STATE: uninstall esp_eth driver failed because it has more than one reference ESP_FAIL: uninstall esp_eth driver failed because some other error occurred ESP_OK: uninstall esp_eth driver successfully ESP_ERR_INVALID_ARG: uninstall esp_eth driver failed because of some invalid argument ESP_ERR_INVALID_STATE: uninstall esp_eth driver failed because it has more than one reference ESP_FAIL: uninstall esp_eth driver failed because some other error occurred ESP_OK: uninstall esp_eth driver successfully Parameters hdl -- [in] handle of Ethernet driver Returns ESP_OK: uninstall esp_eth driver successfully ESP_ERR_INVALID_ARG: uninstall esp_eth driver failed because of some invalid argument ESP_ERR_INVALID_STATE: uninstall esp_eth driver failed because it has more than one reference ESP_FAIL: uninstall esp_eth driver failed because some other error occurred esp_err_t esp_eth_start(esp_eth_handle_t hdl) Start Ethernet driver ONLY in standalone mode (i.e. without TCP/IP stack) Note This API will start driver state machine and internal software timer (for checking link status). Parameters hdl -- [in] handle of Ethernet driver Returns ESP_OK: start esp_eth driver successfully ESP_ERR_INVALID_ARG: start esp_eth driver failed because of some invalid argument ESP_ERR_INVALID_STATE: start esp_eth driver failed because driver has started already ESP_FAIL: start esp_eth driver failed because some other error occurred ESP_OK: start esp_eth driver successfully ESP_ERR_INVALID_ARG: start esp_eth driver failed because of some invalid argument ESP_ERR_INVALID_STATE: start esp_eth driver failed because driver has started already ESP_FAIL: start esp_eth driver failed because some other error occurred ESP_OK: start esp_eth driver successfully Parameters hdl -- [in] handle of Ethernet driver Returns ESP_OK: start esp_eth driver successfully ESP_ERR_INVALID_ARG: start esp_eth driver failed because of some invalid argument ESP_ERR_INVALID_STATE: start esp_eth driver failed because driver has started already ESP_FAIL: start esp_eth driver failed because some other error occurred esp_err_t esp_eth_stop(esp_eth_handle_t hdl) Stop Ethernet driver. Note This function does the oppsite operation of esp_eth_start . Parameters hdl -- [in] handle of Ethernet driver Returns ESP_OK: stop esp_eth driver successfully ESP_ERR_INVALID_ARG: stop esp_eth driver failed because of some invalid argument ESP_ERR_INVALID_STATE: stop esp_eth driver failed because driver has not started yet ESP_FAIL: stop esp_eth driver failed because some other error occurred ESP_OK: stop esp_eth driver successfully ESP_ERR_INVALID_ARG: stop esp_eth driver failed because of some invalid argument ESP_ERR_INVALID_STATE: stop esp_eth driver failed because driver has not started yet ESP_FAIL: stop esp_eth driver failed because some other error occurred ESP_OK: stop esp_eth driver successfully Parameters hdl -- [in] handle of Ethernet driver Returns ESP_OK: stop esp_eth driver successfully ESP_ERR_INVALID_ARG: stop esp_eth driver failed because of some invalid argument ESP_ERR_INVALID_STATE: stop esp_eth driver failed because driver has not started yet ESP_FAIL: stop esp_eth driver failed because some other error occurred esp_err_t esp_eth_update_input_path(esp_eth_handle_t hdl, esp_err_t (*stack_input)(esp_eth_handle_t hdl, uint8_t *buffer, uint32_t length, void *priv), void *priv) Update Ethernet data input path (i.e. specify where to pass the input buffer) Note After install driver, Ethernet still don't know where to deliver the input buffer. In fact, this API registers a callback function which get invoked when Ethernet received new packets. Parameters hdl -- [in] handle of Ethernet driver stack_input -- [in] function pointer, which does the actual process on incoming packets priv -- [in] private resource, which gets passed to stack_input callback without any modification hdl -- [in] handle of Ethernet driver stack_input -- [in] function pointer, which does the actual process on incoming packets priv -- [in] private resource, which gets passed to stack_input callback without any modification hdl -- [in] handle of Ethernet driver Returns ESP_OK: update input path successfully ESP_ERR_INVALID_ARG: update input path failed because of some invalid argument ESP_FAIL: update input path failed because some other error occurred ESP_OK: update input path successfully ESP_ERR_INVALID_ARG: update input path failed because of some invalid argument ESP_FAIL: update input path failed because some other error occurred ESP_OK: update input path successfully Parameters hdl -- [in] handle of Ethernet driver stack_input -- [in] function pointer, which does the actual process on incoming packets priv -- [in] private resource, which gets passed to stack_input callback without any modification Returns ESP_OK: update input path successfully ESP_ERR_INVALID_ARG: update input path failed because of some invalid argument ESP_FAIL: update input path failed because some other error occurred esp_err_t esp_eth_transmit(esp_eth_handle_t hdl, void *buf, size_t length) General Transmit. Parameters hdl -- [in] handle of Ethernet driver buf -- [in] buffer of the packet to transfer length -- [in] length of the buffer to transfer hdl -- [in] handle of Ethernet driver buf -- [in] buffer of the packet to transfer length -- [in] length of the buffer to transfer hdl -- [in] handle of Ethernet driver Returns ESP_OK: transmit frame buffer successfully ESP_ERR_INVALID_ARG: transmit frame buffer failed because of some invalid argument ESP_ERR_INVALID_STATE: invalid driver state (e.i. driver is not started) ESP_ERR_TIMEOUT: transmit frame buffer failed because HW was not get available in predefined period ESP_FAIL: transmit frame buffer failed because some other error occurred ESP_OK: transmit frame buffer successfully ESP_ERR_INVALID_ARG: transmit frame buffer failed because of some invalid argument ESP_ERR_INVALID_STATE: invalid driver state (e.i. driver is not started) ESP_ERR_TIMEOUT: transmit frame buffer failed because HW was not get available in predefined period ESP_FAIL: transmit frame buffer failed because some other error occurred ESP_OK: transmit frame buffer successfully Parameters hdl -- [in] handle of Ethernet driver buf -- [in] buffer of the packet to transfer length -- [in] length of the buffer to transfer Returns ESP_OK: transmit frame buffer successfully ESP_ERR_INVALID_ARG: transmit frame buffer failed because of some invalid argument ESP_ERR_INVALID_STATE: invalid driver state (e.i. driver is not started) ESP_ERR_TIMEOUT: transmit frame buffer failed because HW was not get available in predefined period ESP_FAIL: transmit frame buffer failed because some other error occurred esp_err_t esp_eth_transmit_vargs(esp_eth_handle_t hdl, uint32_t argc, ...) Special Transmit with variable number of arguments. Parameters hdl -- [in] handle of Ethernet driver argc -- [in] number variable arguments ... -- variable arguments hdl -- [in] handle of Ethernet driver argc -- [in] number variable arguments ... -- variable arguments hdl -- [in] handle of Ethernet driver Returns ESP_OK: transmit successfull ESP_ERR_INVALID_STATE: invalid driver state (e.i. driver is not started) ESP_ERR_TIMEOUT: transmit frame buffer failed because HW was not get available in predefined period ESP_FAIL: transmit frame buffer failed because some other error occurred ESP_OK: transmit successfull ESP_ERR_INVALID_STATE: invalid driver state (e.i. driver is not started) ESP_ERR_TIMEOUT: transmit frame buffer failed because HW was not get available in predefined period ESP_FAIL: transmit frame buffer failed because some other error occurred ESP_OK: transmit successfull Parameters hdl -- [in] handle of Ethernet driver argc -- [in] number variable arguments ... -- variable arguments Returns ESP_OK: transmit successfull ESP_ERR_INVALID_STATE: invalid driver state (e.i. driver is not started) ESP_ERR_TIMEOUT: transmit frame buffer failed because HW was not get available in predefined period ESP_FAIL: transmit frame buffer failed because some other error occurred esp_err_t esp_eth_ioctl(esp_eth_handle_t hdl, esp_eth_io_cmd_t cmd, void *data) Misc IO function of Etherent driver. The following common IO control commands are supported: ETH_CMD_S_MAC_ADDR sets Ethernet interface MAC address. data argument is pointer to MAC address buffer with expected size of 6 bytes. ETH_CMD_G_MAC_ADDR gets Ethernet interface MAC address. data argument is pointer to a buffer to which MAC address is to be copied. The buffer size must be at least 6 bytes. ETH_CMD_S_PHY_ADDR sets PHY address in range of <0-31>. data argument is pointer to memory of uint32_t datatype from where the configuration option is read. ETH_CMD_G_PHY_ADDR gets PHY address. data argument is pointer to memory of uint32_t datatype to which the PHY address is to be stored. ETH_CMD_S_AUTONEGO enables or disables Ethernet link speed and duplex mode autonegotiation. data argument is pointer to memory of bool datatype from which the configuration option is read. Preconditions: Ethernet driver needs to be stopped. ETH_CMD_G_AUTONEGO gets current configuration of the Ethernet link speed and duplex mode autonegotiation. data argument is pointer to memory of bool datatype to which the current configuration is to be stored. ETH_CMD_S_SPEED sets the Ethernet link speed. data argument is pointer to memory of eth_speed_t datatype from which the configuration option is read. Preconditions: Ethernet driver needs to be stopped and auto-negotiation disabled. ETH_CMD_G_SPEED gets current Ethernet link speed. data argument is pointer to memory of eth_speed_t datatype to which the speed is to be stored. ETH_CMD_S_PROMISCUOUS sets/resets Ethernet interface promiscuous mode. data argument is pointer to memory of bool datatype from which the configuration option is read. ETH_CMD_S_FLOW_CTRL sets/resets Ethernet interface flow control. data argument is pointer to memory of bool datatype from which the configuration option is read. ETH_CMD_S_DUPLEX_MODE sets the Ethernet duplex mode. data argument is pointer to memory of eth_duplex_t datatype from which the configuration option is read. Preconditions: Ethernet driver needs to be stopped and auto-negotiation disabled. ETH_CMD_G_DUPLEX_MODE gets current Ethernet link duplex mode. data argument is pointer to memory of eth_duplex_t datatype to which the duplex mode is to be stored. ETH_CMD_S_PHY_LOOPBACK sets/resets PHY to/from loopback mode. data argument is pointer to memory of bool datatype from which the configuration option is read. ETH_CMD_S_MAC_ADDR sets Ethernet interface MAC address. data argument is pointer to MAC address buffer with expected size of 6 bytes. ETH_CMD_G_MAC_ADDR gets Ethernet interface MAC address. data argument is pointer to a buffer to which MAC address is to be copied. The buffer size must be at least 6 bytes. ETH_CMD_S_PHY_ADDR sets PHY address in range of <0-31>. data argument is pointer to memory of uint32_t datatype from where the configuration option is read. ETH_CMD_G_PHY_ADDR gets PHY address. data argument is pointer to memory of uint32_t datatype to which the PHY address is to be stored. ETH_CMD_S_AUTONEGO enables or disables Ethernet link speed and duplex mode autonegotiation. data argument is pointer to memory of bool datatype from which the configuration option is read. Preconditions: Ethernet driver needs to be stopped. ETH_CMD_G_AUTONEGO gets current configuration of the Ethernet link speed and duplex mode autonegotiation. data argument is pointer to memory of bool datatype to which the current configuration is to be stored. ETH_CMD_S_SPEED sets the Ethernet link speed. data argument is pointer to memory of eth_speed_t datatype from which the configuration option is read. Preconditions: Ethernet driver needs to be stopped and auto-negotiation disabled. ETH_CMD_G_SPEED gets current Ethernet link speed. data argument is pointer to memory of eth_speed_t datatype to which the speed is to be stored. ETH_CMD_S_PROMISCUOUS sets/resets Ethernet interface promiscuous mode. data argument is pointer to memory of bool datatype from which the configuration option is read. ETH_CMD_S_FLOW_CTRL sets/resets Ethernet interface flow control. data argument is pointer to memory of bool datatype from which the configuration option is read. ETH_CMD_S_DUPLEX_MODE sets the Ethernet duplex mode. data argument is pointer to memory of eth_duplex_t datatype from which the configuration option is read. Preconditions: Ethernet driver needs to be stopped and auto-negotiation disabled. ETH_CMD_G_DUPLEX_MODE gets current Ethernet link duplex mode. data argument is pointer to memory of eth_duplex_t datatype to which the duplex mode is to be stored. ETH_CMD_S_PHY_LOOPBACK sets/resets PHY to/from loopback mode. data argument is pointer to memory of bool datatype from which the configuration option is read. Note that additional control commands may be available for specific MAC or PHY chips. Please consult specific MAC or PHY documentation or driver code. Note that additional control commands may be available for specific MAC or PHY chips. Please consult specific MAC or PHY documentation or driver code. Parameters hdl -- [in] handle of Ethernet driver cmd -- [in] IO control command data -- [inout] address of data for set command or address where to store the data when used with get command hdl -- [in] handle of Ethernet driver cmd -- [in] IO control command data -- [inout] address of data for set command or address where to store the data when used with get command hdl -- [in] handle of Ethernet driver Returns ESP_OK: process io command successfully ESP_ERR_INVALID_ARG: process io command failed because of some invalid argument ESP_FAIL: process io command failed because some other error occurred ESP_ERR_NOT_SUPPORTED: requested feature is not supported ESP_OK: process io command successfully ESP_ERR_INVALID_ARG: process io command failed because of some invalid argument ESP_FAIL: process io command failed because some other error occurred ESP_ERR_NOT_SUPPORTED: requested feature is not supported ESP_OK: process io command successfully Parameters hdl -- [in] handle of Ethernet driver cmd -- [in] IO control command data -- [inout] address of data for set command or address where to store the data when used with get command Returns ESP_OK: process io command successfully ESP_ERR_INVALID_ARG: process io command failed because of some invalid argument ESP_FAIL: process io command failed because some other error occurred ESP_ERR_NOT_SUPPORTED: requested feature is not supported ETH_CMD_S_MAC_ADDR sets Ethernet interface MAC address. data argument is pointer to MAC address buffer with expected size of 6 bytes. esp_err_t esp_eth_increase_reference(esp_eth_handle_t hdl) Increase Ethernet driver reference. Note Ethernet driver handle can be obtained by os timer, netif, etc. It's dangerous when thread A is using Ethernet but thread B uninstall the driver. Using reference counter can prevent such risk, but care should be taken, when you obtain Ethernet driver, this API must be invoked so that the driver won't be uninstalled during your using time. Parameters hdl -- [in] handle of Ethernet driver Returns ESP_OK: increase reference successfully ESP_ERR_INVALID_ARG: increase reference failed because of some invalid argument ESP_OK: increase reference successfully ESP_ERR_INVALID_ARG: increase reference failed because of some invalid argument ESP_OK: increase reference successfully Parameters hdl -- [in] handle of Ethernet driver Returns ESP_OK: increase reference successfully ESP_ERR_INVALID_ARG: increase reference failed because of some invalid argument esp_err_t esp_eth_decrease_reference(esp_eth_handle_t hdl) Decrease Ethernet driver reference. Parameters hdl -- [in] handle of Ethernet driver Returns ESP_OK: increase reference successfully ESP_ERR_INVALID_ARG: increase reference failed because of some invalid argument ESP_OK: increase reference successfully ESP_ERR_INVALID_ARG: increase reference failed because of some invalid argument ESP_OK: increase reference successfully Parameters hdl -- [in] handle of Ethernet driver Returns ESP_OK: increase reference successfully ESP_ERR_INVALID_ARG: increase reference failed because of some invalid argument Structures struct esp_eth_config_t Configuration of Ethernet driver. Public Members esp_eth_mac_t *mac Ethernet MAC object. esp_eth_mac_t *mac Ethernet MAC object. esp_eth_phy_t *phy Ethernet PHY object. esp_eth_phy_t *phy Ethernet PHY object. uint32_t check_link_period_ms Period time of checking Ethernet link status. uint32_t check_link_period_ms Period time of checking Ethernet link status. esp_err_t (*stack_input)(esp_eth_handle_t eth_handle, uint8_t *buffer, uint32_t length, void *priv) Input frame buffer to user's stack. Param eth_handle [in] handle of Ethernet driver Param buffer [in] frame buffer that will get input to upper stack Param length [in] length of the frame buffer Return ESP_OK: input frame buffer to upper stack successfully ESP_FAIL: error occurred when inputting buffer to upper stack ESP_OK: input frame buffer to upper stack successfully ESP_FAIL: error occurred when inputting buffer to upper stack ESP_OK: input frame buffer to upper stack successfully Param eth_handle [in] handle of Ethernet driver Param buffer [in] frame buffer that will get input to upper stack Param length [in] length of the frame buffer Return ESP_OK: input frame buffer to upper stack successfully ESP_FAIL: error occurred when inputting buffer to upper stack esp_err_t (*stack_input)(esp_eth_handle_t eth_handle, uint8_t *buffer, uint32_t length, void *priv) Input frame buffer to user's stack. Param eth_handle [in] handle of Ethernet driver Param buffer [in] frame buffer that will get input to upper stack Param length [in] length of the frame buffer Return ESP_OK: input frame buffer to upper stack successfully ESP_FAIL: error occurred when inputting buffer to upper stack esp_err_t (*on_lowlevel_init_done)(esp_eth_handle_t eth_handle) Callback function invoked when lowlevel initialization is finished. Param eth_handle [in] handle of Ethernet driver Return ESP_OK: process extra lowlevel initialization successfully ESP_FAIL: error occurred when processing extra lowlevel initialization ESP_OK: process extra lowlevel initialization successfully ESP_FAIL: error occurred when processing extra lowlevel initialization ESP_OK: process extra lowlevel initialization successfully Param eth_handle [in] handle of Ethernet driver Return ESP_OK: process extra lowlevel initialization successfully ESP_FAIL: error occurred when processing extra lowlevel initialization esp_err_t (*on_lowlevel_init_done)(esp_eth_handle_t eth_handle) Callback function invoked when lowlevel initialization is finished. Param eth_handle [in] handle of Ethernet driver Return ESP_OK: process extra lowlevel initialization successfully ESP_FAIL: error occurred when processing extra lowlevel initialization esp_err_t (*on_lowlevel_deinit_done)(esp_eth_handle_t eth_handle) Callback function invoked when lowlevel deinitialization is finished. Param eth_handle [in] handle of Ethernet driver Return ESP_OK: process extra lowlevel deinitialization successfully ESP_FAIL: error occurred when processing extra lowlevel deinitialization ESP_OK: process extra lowlevel deinitialization successfully ESP_FAIL: error occurred when processing extra lowlevel deinitialization ESP_OK: process extra lowlevel deinitialization successfully Param eth_handle [in] handle of Ethernet driver Return ESP_OK: process extra lowlevel deinitialization successfully ESP_FAIL: error occurred when processing extra lowlevel deinitialization esp_err_t (*on_lowlevel_deinit_done)(esp_eth_handle_t eth_handle) Callback function invoked when lowlevel deinitialization is finished. Param eth_handle [in] handle of Ethernet driver Return ESP_OK: process extra lowlevel deinitialization successfully ESP_FAIL: error occurred when processing extra lowlevel deinitialization esp_err_t (*read_phy_reg)(esp_eth_handle_t eth_handle, uint32_t phy_addr, uint32_t phy_reg, uint32_t *reg_value) Read PHY register. Note Usually the PHY register read/write function is provided by MAC (SMI interface), but if the PHY device is managed by other interface (e.g. I2C), then user needs to implement the corresponding read/write. Setting this to NULL means your PHY device is managed by MAC's SMI interface. Param eth_handle [in] handle of Ethernet driver Param phy_addr [in] PHY chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [out] PHY register value Return ESP_OK: read PHY register successfully ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument ESP_ERR_TIMEOUT: read PHY register failed because of timeout ESP_FAIL: read PHY register failed because some other error occurred ESP_OK: read PHY register successfully ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument ESP_ERR_TIMEOUT: read PHY register failed because of timeout ESP_FAIL: read PHY register failed because some other error occurred ESP_OK: read PHY register successfully Param eth_handle [in] handle of Ethernet driver Param phy_addr [in] PHY chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [out] PHY register value Return ESP_OK: read PHY register successfully ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument ESP_ERR_TIMEOUT: read PHY register failed because of timeout ESP_FAIL: read PHY register failed because some other error occurred esp_err_t (*read_phy_reg)(esp_eth_handle_t eth_handle, uint32_t phy_addr, uint32_t phy_reg, uint32_t *reg_value) Read PHY register. Note Usually the PHY register read/write function is provided by MAC (SMI interface), but if the PHY device is managed by other interface (e.g. I2C), then user needs to implement the corresponding read/write. Setting this to NULL means your PHY device is managed by MAC's SMI interface. Param eth_handle [in] handle of Ethernet driver Param phy_addr [in] PHY chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [out] PHY register value Return ESP_OK: read PHY register successfully ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument ESP_ERR_TIMEOUT: read PHY register failed because of timeout ESP_FAIL: read PHY register failed because some other error occurred esp_err_t (*write_phy_reg)(esp_eth_handle_t eth_handle, uint32_t phy_addr, uint32_t phy_reg, uint32_t reg_value) Write PHY register. Note Usually the PHY register read/write function is provided by MAC (SMI interface), but if the PHY device is managed by other interface (e.g. I2C), then user needs to implement the corresponding read/write. Setting this to NULL means your PHY device is managed by MAC's SMI interface. Param eth_handle [in] handle of Ethernet driver Param phy_addr [in] PHY chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [in] PHY register value Return ESP_OK: write PHY register successfully ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument ESP_ERR_TIMEOUT: write PHY register failed because of timeout ESP_FAIL: write PHY register failed because some other error occurred ESP_OK: write PHY register successfully ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument ESP_ERR_TIMEOUT: write PHY register failed because of timeout ESP_FAIL: write PHY register failed because some other error occurred ESP_OK: write PHY register successfully Param eth_handle [in] handle of Ethernet driver Param phy_addr [in] PHY chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [in] PHY register value Return ESP_OK: write PHY register successfully ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument ESP_ERR_TIMEOUT: write PHY register failed because of timeout ESP_FAIL: write PHY register failed because some other error occurred esp_err_t (*write_phy_reg)(esp_eth_handle_t eth_handle, uint32_t phy_addr, uint32_t phy_reg, uint32_t reg_value) Write PHY register. Note Usually the PHY register read/write function is provided by MAC (SMI interface), but if the PHY device is managed by other interface (e.g. I2C), then user needs to implement the corresponding read/write. Setting this to NULL means your PHY device is managed by MAC's SMI interface. Param eth_handle [in] handle of Ethernet driver Param phy_addr [in] PHY chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [in] PHY register value Return ESP_OK: write PHY register successfully ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument ESP_ERR_TIMEOUT: write PHY register failed because of timeout ESP_FAIL: write PHY register failed because some other error occurred esp_eth_mac_t *mac struct esp_eth_phy_reg_rw_data_t Data structure to Read/Write PHY register via ioctl API. Macros ETH_DEFAULT_CONFIG(emac, ephy) Default configuration for Ethernet driver. Type Definitions typedef void *esp_eth_handle_t Handle of Ethernet driver. Enumerations enum esp_eth_io_cmd_t Command list for ioctl API. Values: enumerator ETH_CMD_G_MAC_ADDR Get MAC address enumerator ETH_CMD_G_MAC_ADDR Get MAC address enumerator ETH_CMD_S_MAC_ADDR Set MAC address enumerator ETH_CMD_S_MAC_ADDR Set MAC address enumerator ETH_CMD_G_PHY_ADDR Get PHY address enumerator ETH_CMD_G_PHY_ADDR Get PHY address enumerator ETH_CMD_S_PHY_ADDR Set PHY address enumerator ETH_CMD_S_PHY_ADDR Set PHY address enumerator ETH_CMD_G_AUTONEGO Get PHY Auto Negotiation enumerator ETH_CMD_G_AUTONEGO Get PHY Auto Negotiation enumerator ETH_CMD_S_AUTONEGO Set PHY Auto Negotiation enumerator ETH_CMD_S_AUTONEGO Set PHY Auto Negotiation enumerator ETH_CMD_G_SPEED Get Speed enumerator ETH_CMD_G_SPEED Get Speed enumerator ETH_CMD_S_SPEED Set Speed enumerator ETH_CMD_S_SPEED Set Speed enumerator ETH_CMD_S_PROMISCUOUS Set promiscuous mode enumerator ETH_CMD_S_PROMISCUOUS Set promiscuous mode enumerator ETH_CMD_S_FLOW_CTRL Set flow control enumerator ETH_CMD_S_FLOW_CTRL Set flow control enumerator ETH_CMD_G_DUPLEX_MODE Get Duplex mode enumerator ETH_CMD_G_DUPLEX_MODE Get Duplex mode enumerator ETH_CMD_S_DUPLEX_MODE Set Duplex mode enumerator ETH_CMD_S_DUPLEX_MODE Set Duplex mode enumerator ETH_CMD_S_PHY_LOOPBACK Set PHY loopback enumerator ETH_CMD_S_PHY_LOOPBACK Set PHY loopback enumerator ETH_CMD_READ_PHY_REG Read PHY register enumerator ETH_CMD_READ_PHY_REG Read PHY register enumerator ETH_CMD_WRITE_PHY_REG Write PHY register enumerator ETH_CMD_WRITE_PHY_REG Write PHY register enumerator ETH_CMD_CUSTOM_MAC_CMDS enumerator ETH_CMD_CUSTOM_MAC_CMDS enumerator ETH_CMD_CUSTOM_PHY_CMDS enumerator ETH_CMD_CUSTOM_PHY_CMDS enumerator ETH_CMD_G_MAC_ADDR Header File This header file can be included with: #include "esp_eth_com.h" This header file is a part of the API provided by the esp_eth component. To declare that your component depends on esp_eth , add the following to your CMakeLists.txt: REQUIRES esp_eth or PRIV_REQUIRES esp_eth Structures struct esp_eth_mediator_s Ethernet mediator. Public Members esp_err_t (*phy_reg_read)(esp_eth_mediator_t *eth, uint32_t phy_addr, uint32_t phy_reg, uint32_t *reg_value) Read PHY register. Param eth [in] mediator of Ethernet driver Param phy_addr [in] PHY Chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [out] PHY register value Return ESP_OK: read PHY register successfully ESP_FAIL: read PHY register failed because some error occurred ESP_OK: read PHY register successfully ESP_FAIL: read PHY register failed because some error occurred ESP_OK: read PHY register successfully Param eth [in] mediator of Ethernet driver Param phy_addr [in] PHY Chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [out] PHY register value Return ESP_OK: read PHY register successfully ESP_FAIL: read PHY register failed because some error occurred esp_err_t (*phy_reg_read)(esp_eth_mediator_t *eth, uint32_t phy_addr, uint32_t phy_reg, uint32_t *reg_value) Read PHY register. Param eth [in] mediator of Ethernet driver Param phy_addr [in] PHY Chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [out] PHY register value Return ESP_OK: read PHY register successfully ESP_FAIL: read PHY register failed because some error occurred esp_err_t (*phy_reg_write)(esp_eth_mediator_t *eth, uint32_t phy_addr, uint32_t phy_reg, uint32_t reg_value) Write PHY register. Param eth [in] mediator of Ethernet driver Param phy_addr [in] PHY Chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [in] PHY register value Return ESP_OK: write PHY register successfully ESP_FAIL: write PHY register failed because some error occurred ESP_OK: write PHY register successfully ESP_FAIL: write PHY register failed because some error occurred ESP_OK: write PHY register successfully Param eth [in] mediator of Ethernet driver Param phy_addr [in] PHY Chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [in] PHY register value Return ESP_OK: write PHY register successfully ESP_FAIL: write PHY register failed because some error occurred esp_err_t (*phy_reg_write)(esp_eth_mediator_t *eth, uint32_t phy_addr, uint32_t phy_reg, uint32_t reg_value) Write PHY register. Param eth [in] mediator of Ethernet driver Param phy_addr [in] PHY Chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [in] PHY register value Return ESP_OK: write PHY register successfully ESP_FAIL: write PHY register failed because some error occurred esp_err_t (*stack_input)(esp_eth_mediator_t *eth, uint8_t *buffer, uint32_t length) Deliver packet to upper stack. Param eth [in] mediator of Ethernet driver Param buffer [in] packet buffer Param length [in] length of the packet Return ESP_OK: deliver packet to upper stack successfully ESP_FAIL: deliver packet failed because some error occurred ESP_OK: deliver packet to upper stack successfully ESP_FAIL: deliver packet failed because some error occurred ESP_OK: deliver packet to upper stack successfully Param eth [in] mediator of Ethernet driver Param buffer [in] packet buffer Param length [in] length of the packet Return ESP_OK: deliver packet to upper stack successfully ESP_FAIL: deliver packet failed because some error occurred esp_err_t (*stack_input)(esp_eth_mediator_t *eth, uint8_t *buffer, uint32_t length) Deliver packet to upper stack. Param eth [in] mediator of Ethernet driver Param buffer [in] packet buffer Param length [in] length of the packet Return ESP_OK: deliver packet to upper stack successfully ESP_FAIL: deliver packet failed because some error occurred esp_err_t (*on_state_changed)(esp_eth_mediator_t *eth, esp_eth_state_t state, void *args) Callback on Ethernet state changed. Param eth [in] mediator of Ethernet driver Param state [in] new state Param args [in] optional argument for the new state Return ESP_OK: process the new state successfully ESP_FAIL: process the new state failed because some error occurred ESP_OK: process the new state successfully ESP_FAIL: process the new state failed because some error occurred ESP_OK: process the new state successfully Param eth [in] mediator of Ethernet driver Param state [in] new state Param args [in] optional argument for the new state Return ESP_OK: process the new state successfully ESP_FAIL: process the new state failed because some error occurred esp_err_t (*on_state_changed)(esp_eth_mediator_t *eth, esp_eth_state_t state, void *args) Callback on Ethernet state changed. Param eth [in] mediator of Ethernet driver Param state [in] new state Param args [in] optional argument for the new state Return ESP_OK: process the new state successfully ESP_FAIL: process the new state failed because some error occurred esp_err_t (*phy_reg_read)(esp_eth_mediator_t *eth, uint32_t phy_addr, uint32_t phy_reg, uint32_t *reg_value) Type Definitions typedef struct esp_eth_mediator_s esp_eth_mediator_t Ethernet mediator. Enumerations enum esp_eth_state_t Ethernet driver state. Values: enumerator ETH_STATE_LLINIT Lowlevel init done enumerator ETH_STATE_LLINIT Lowlevel init done enumerator ETH_STATE_DEINIT Deinit done enumerator ETH_STATE_DEINIT Deinit done enumerator ETH_STATE_LINK Link status changed enumerator ETH_STATE_LINK Link status changed enumerator ETH_STATE_SPEED Speed updated enumerator ETH_STATE_SPEED Speed updated enumerator ETH_STATE_DUPLEX Duplex updated enumerator ETH_STATE_DUPLEX Duplex updated enumerator ETH_STATE_PAUSE Pause ability updated enumerator ETH_STATE_PAUSE Pause ability updated enumerator ETH_STATE_LLINIT Header File This header file can be included with: #include "esp_eth_mac.h" This header file is a part of the API provided by the esp_eth component. To declare that your component depends on esp_eth , add the following to your CMakeLists.txt: REQUIRES esp_eth or PRIV_REQUIRES esp_eth Functions esp_eth_mac_t *esp_eth_mac_new_esp32(const eth_esp32_emac_config_t *esp32_config, const eth_mac_config_t *config) Create ESP32 Ethernet MAC instance. Parameters esp32_config -- EMAC specific configuration config -- Ethernet MAC configuration esp32_config -- EMAC specific configuration config -- Ethernet MAC configuration esp32_config -- EMAC specific configuration Returns instance: create MAC instance successfully NULL: create MAC instance failed because some error occurred instance: create MAC instance successfully NULL: create MAC instance failed because some error occurred instance: create MAC instance successfully Parameters esp32_config -- EMAC specific configuration config -- Ethernet MAC configuration Returns instance: create MAC instance successfully NULL: create MAC instance failed because some error occurred Unions union eth_mac_clock_config_t #include <esp_eth_mac.h> Ethernet MAC Clock Configuration. Public Members struct eth_mac_clock_config_t::[anonymous] mii EMAC MII Clock Configuration struct eth_mac_clock_config_t::[anonymous] mii EMAC MII Clock Configuration emac_rmii_clock_mode_t clock_mode RMII Clock Mode Configuration emac_rmii_clock_mode_t clock_mode RMII Clock Mode Configuration emac_rmii_clock_gpio_t clock_gpio RMII Clock GPIO Configuration emac_rmii_clock_gpio_t clock_gpio RMII Clock GPIO Configuration struct eth_mac_clock_config_t::[anonymous] rmii EMAC RMII Clock Configuration struct eth_mac_clock_config_t::[anonymous] rmii EMAC RMII Clock Configuration struct eth_mac_clock_config_t::[anonymous] mii Structures struct esp_eth_mac_s Ethernet MAC. Public Members esp_err_t (*set_mediator)(esp_eth_mac_t *mac, esp_eth_mediator_t *eth) Set mediator for Ethernet MAC. Param mac [in] Ethernet MAC instance Param eth [in] Ethernet mediator Return ESP_OK: set mediator for Ethernet MAC successfully ESP_ERR_INVALID_ARG: set mediator for Ethernet MAC failed because of invalid argument ESP_OK: set mediator for Ethernet MAC successfully ESP_ERR_INVALID_ARG: set mediator for Ethernet MAC failed because of invalid argument ESP_OK: set mediator for Ethernet MAC successfully Param mac [in] Ethernet MAC instance Param eth [in] Ethernet mediator Return ESP_OK: set mediator for Ethernet MAC successfully ESP_ERR_INVALID_ARG: set mediator for Ethernet MAC failed because of invalid argument esp_err_t (*set_mediator)(esp_eth_mac_t *mac, esp_eth_mediator_t *eth) Set mediator for Ethernet MAC. Param mac [in] Ethernet MAC instance Param eth [in] Ethernet mediator Return ESP_OK: set mediator for Ethernet MAC successfully ESP_ERR_INVALID_ARG: set mediator for Ethernet MAC failed because of invalid argument esp_err_t (*init)(esp_eth_mac_t *mac) Initialize Ethernet MAC. Param mac [in] Ethernet MAC instance Return ESP_OK: initialize Ethernet MAC successfully ESP_ERR_TIMEOUT: initialize Ethernet MAC failed because of timeout ESP_FAIL: initialize Ethernet MAC failed because some other error occurred ESP_OK: initialize Ethernet MAC successfully ESP_ERR_TIMEOUT: initialize Ethernet MAC failed because of timeout ESP_FAIL: initialize Ethernet MAC failed because some other error occurred ESP_OK: initialize Ethernet MAC successfully Param mac [in] Ethernet MAC instance Return ESP_OK: initialize Ethernet MAC successfully ESP_ERR_TIMEOUT: initialize Ethernet MAC failed because of timeout ESP_FAIL: initialize Ethernet MAC failed because some other error occurred esp_err_t (*init)(esp_eth_mac_t *mac) Initialize Ethernet MAC. Param mac [in] Ethernet MAC instance Return ESP_OK: initialize Ethernet MAC successfully ESP_ERR_TIMEOUT: initialize Ethernet MAC failed because of timeout ESP_FAIL: initialize Ethernet MAC failed because some other error occurred esp_err_t (*deinit)(esp_eth_mac_t *mac) Deinitialize Ethernet MAC. Param mac [in] Ethernet MAC instance Return ESP_OK: deinitialize Ethernet MAC successfully ESP_FAIL: deinitialize Ethernet MAC failed because some error occurred ESP_OK: deinitialize Ethernet MAC successfully ESP_FAIL: deinitialize Ethernet MAC failed because some error occurred ESP_OK: deinitialize Ethernet MAC successfully Param mac [in] Ethernet MAC instance Return ESP_OK: deinitialize Ethernet MAC successfully ESP_FAIL: deinitialize Ethernet MAC failed because some error occurred esp_err_t (*deinit)(esp_eth_mac_t *mac) Deinitialize Ethernet MAC. Param mac [in] Ethernet MAC instance Return ESP_OK: deinitialize Ethernet MAC successfully ESP_FAIL: deinitialize Ethernet MAC failed because some error occurred esp_err_t (*start)(esp_eth_mac_t *mac) Start Ethernet MAC. Param mac [in] Ethernet MAC instance Return ESP_OK: start Ethernet MAC successfully ESP_FAIL: start Ethernet MAC failed because some other error occurred ESP_OK: start Ethernet MAC successfully ESP_FAIL: start Ethernet MAC failed because some other error occurred ESP_OK: start Ethernet MAC successfully Param mac [in] Ethernet MAC instance Return ESP_OK: start Ethernet MAC successfully ESP_FAIL: start Ethernet MAC failed because some other error occurred esp_err_t (*start)(esp_eth_mac_t *mac) Start Ethernet MAC. Param mac [in] Ethernet MAC instance Return ESP_OK: start Ethernet MAC successfully ESP_FAIL: start Ethernet MAC failed because some other error occurred esp_err_t (*stop)(esp_eth_mac_t *mac) Stop Ethernet MAC. Param mac [in] Ethernet MAC instance Return ESP_OK: stop Ethernet MAC successfully ESP_FAIL: stop Ethernet MAC failed because some error occurred ESP_OK: stop Ethernet MAC successfully ESP_FAIL: stop Ethernet MAC failed because some error occurred ESP_OK: stop Ethernet MAC successfully Param mac [in] Ethernet MAC instance Return ESP_OK: stop Ethernet MAC successfully ESP_FAIL: stop Ethernet MAC failed because some error occurred esp_err_t (*stop)(esp_eth_mac_t *mac) Stop Ethernet MAC. Param mac [in] Ethernet MAC instance Return ESP_OK: stop Ethernet MAC successfully ESP_FAIL: stop Ethernet MAC failed because some error occurred esp_err_t (*transmit)(esp_eth_mac_t *mac, uint8_t *buf, uint32_t length) Transmit packet from Ethernet MAC. Note Returned error codes may differ for each specific MAC chip. Param mac [in] Ethernet MAC instance Param buf [in] packet buffer to transmit Param length [in] length of packet Return ESP_OK: transmit packet successfully ESP_ERR_INVALID_SIZE: number of actually sent bytes differs to expected ESP_FAIL: transmit packet failed because some other error occurred ESP_OK: transmit packet successfully ESP_ERR_INVALID_SIZE: number of actually sent bytes differs to expected ESP_FAIL: transmit packet failed because some other error occurred ESP_OK: transmit packet successfully Param mac [in] Ethernet MAC instance Param buf [in] packet buffer to transmit Param length [in] length of packet Return ESP_OK: transmit packet successfully ESP_ERR_INVALID_SIZE: number of actually sent bytes differs to expected ESP_FAIL: transmit packet failed because some other error occurred esp_err_t (*transmit)(esp_eth_mac_t *mac, uint8_t *buf, uint32_t length) Transmit packet from Ethernet MAC. Note Returned error codes may differ for each specific MAC chip. Param mac [in] Ethernet MAC instance Param buf [in] packet buffer to transmit Param length [in] length of packet Return ESP_OK: transmit packet successfully ESP_ERR_INVALID_SIZE: number of actually sent bytes differs to expected ESP_FAIL: transmit packet failed because some other error occurred esp_err_t (*transmit_vargs)(esp_eth_mac_t *mac, uint32_t argc, va_list args) Transmit packet from Ethernet MAC constructed with special parameters at Layer2. Note Typical intended use case is to make possible to construct a frame from multiple higher layer buffers without a need of buffer reallocations. However, other use cases are not limited. Note Returned error codes may differ for each specific MAC chip. Param mac [in] Ethernet MAC instance Param argc [in] number variable arguments Param args [in] variable arguments Return ESP_OK: transmit packet successfully ESP_ERR_INVALID_SIZE: number of actually sent bytes differs to expected ESP_FAIL: transmit packet failed because some other error occurred ESP_OK: transmit packet successfully ESP_ERR_INVALID_SIZE: number of actually sent bytes differs to expected ESP_FAIL: transmit packet failed because some other error occurred ESP_OK: transmit packet successfully Param mac [in] Ethernet MAC instance Param argc [in] number variable arguments Param args [in] variable arguments Return ESP_OK: transmit packet successfully ESP_ERR_INVALID_SIZE: number of actually sent bytes differs to expected ESP_FAIL: transmit packet failed because some other error occurred esp_err_t (*transmit_vargs)(esp_eth_mac_t *mac, uint32_t argc, va_list args) Transmit packet from Ethernet MAC constructed with special parameters at Layer2. Note Typical intended use case is to make possible to construct a frame from multiple higher layer buffers without a need of buffer reallocations. However, other use cases are not limited. Note Returned error codes may differ for each specific MAC chip. Param mac [in] Ethernet MAC instance Param argc [in] number variable arguments Param args [in] variable arguments Return ESP_OK: transmit packet successfully ESP_ERR_INVALID_SIZE: number of actually sent bytes differs to expected ESP_FAIL: transmit packet failed because some other error occurred esp_err_t (*receive)(esp_eth_mac_t *mac, uint8_t *buf, uint32_t *length) Receive packet from Ethernet MAC. Note Memory of buf is allocated in the Layer2, make sure it get free after process. Note Before this function got invoked, the value of "length" should set by user, equals the size of buffer. After the function returned, the value of "length" means the real length of received data. Param mac [in] Ethernet MAC instance Param buf [out] packet buffer which will preserve the received frame Param length [out] length of the received packet Return ESP_OK: receive packet successfully ESP_ERR_INVALID_ARG: receive packet failed because of invalid argument ESP_ERR_INVALID_SIZE: input buffer size is not enough to hold the incoming data. in this case, value of returned "length" indicates the real size of incoming data. ESP_FAIL: receive packet failed because some other error occurred ESP_OK: receive packet successfully ESP_ERR_INVALID_ARG: receive packet failed because of invalid argument ESP_ERR_INVALID_SIZE: input buffer size is not enough to hold the incoming data. in this case, value of returned "length" indicates the real size of incoming data. ESP_FAIL: receive packet failed because some other error occurred ESP_OK: receive packet successfully Param mac [in] Ethernet MAC instance Param buf [out] packet buffer which will preserve the received frame Param length [out] length of the received packet Return ESP_OK: receive packet successfully ESP_ERR_INVALID_ARG: receive packet failed because of invalid argument ESP_ERR_INVALID_SIZE: input buffer size is not enough to hold the incoming data. in this case, value of returned "length" indicates the real size of incoming data. ESP_FAIL: receive packet failed because some other error occurred esp_err_t (*receive)(esp_eth_mac_t *mac, uint8_t *buf, uint32_t *length) Receive packet from Ethernet MAC. Note Memory of buf is allocated in the Layer2, make sure it get free after process. Note Before this function got invoked, the value of "length" should set by user, equals the size of buffer. After the function returned, the value of "length" means the real length of received data. Param mac [in] Ethernet MAC instance Param buf [out] packet buffer which will preserve the received frame Param length [out] length of the received packet Return ESP_OK: receive packet successfully ESP_ERR_INVALID_ARG: receive packet failed because of invalid argument ESP_ERR_INVALID_SIZE: input buffer size is not enough to hold the incoming data. in this case, value of returned "length" indicates the real size of incoming data. ESP_FAIL: receive packet failed because some other error occurred esp_err_t (*read_phy_reg)(esp_eth_mac_t *mac, uint32_t phy_addr, uint32_t phy_reg, uint32_t *reg_value) Read PHY register. Param mac [in] Ethernet MAC instance Param phy_addr [in] PHY chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [out] PHY register value Return ESP_OK: read PHY register successfully ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument ESP_ERR_INVALID_STATE: read PHY register failed because of wrong state of MAC ESP_ERR_TIMEOUT: read PHY register failed because of timeout ESP_FAIL: read PHY register failed because some other error occurred ESP_OK: read PHY register successfully ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument ESP_ERR_INVALID_STATE: read PHY register failed because of wrong state of MAC ESP_ERR_TIMEOUT: read PHY register failed because of timeout ESP_FAIL: read PHY register failed because some other error occurred ESP_OK: read PHY register successfully Param mac [in] Ethernet MAC instance Param phy_addr [in] PHY chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [out] PHY register value Return ESP_OK: read PHY register successfully ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument ESP_ERR_INVALID_STATE: read PHY register failed because of wrong state of MAC ESP_ERR_TIMEOUT: read PHY register failed because of timeout ESP_FAIL: read PHY register failed because some other error occurred esp_err_t (*read_phy_reg)(esp_eth_mac_t *mac, uint32_t phy_addr, uint32_t phy_reg, uint32_t *reg_value) Read PHY register. Param mac [in] Ethernet MAC instance Param phy_addr [in] PHY chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [out] PHY register value Return ESP_OK: read PHY register successfully ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument ESP_ERR_INVALID_STATE: read PHY register failed because of wrong state of MAC ESP_ERR_TIMEOUT: read PHY register failed because of timeout ESP_FAIL: read PHY register failed because some other error occurred esp_err_t (*write_phy_reg)(esp_eth_mac_t *mac, uint32_t phy_addr, uint32_t phy_reg, uint32_t reg_value) Write PHY register. Param mac [in] Ethernet MAC instance Param phy_addr [in] PHY chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [in] PHY register value Return ESP_OK: write PHY register successfully ESP_ERR_INVALID_STATE: write PHY register failed because of wrong state of MAC ESP_ERR_TIMEOUT: write PHY register failed because of timeout ESP_FAIL: write PHY register failed because some other error occurred ESP_OK: write PHY register successfully ESP_ERR_INVALID_STATE: write PHY register failed because of wrong state of MAC ESP_ERR_TIMEOUT: write PHY register failed because of timeout ESP_FAIL: write PHY register failed because some other error occurred ESP_OK: write PHY register successfully Param mac [in] Ethernet MAC instance Param phy_addr [in] PHY chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [in] PHY register value Return ESP_OK: write PHY register successfully ESP_ERR_INVALID_STATE: write PHY register failed because of wrong state of MAC ESP_ERR_TIMEOUT: write PHY register failed because of timeout ESP_FAIL: write PHY register failed because some other error occurred esp_err_t (*write_phy_reg)(esp_eth_mac_t *mac, uint32_t phy_addr, uint32_t phy_reg, uint32_t reg_value) Write PHY register. Param mac [in] Ethernet MAC instance Param phy_addr [in] PHY chip address (0~31) Param phy_reg [in] PHY register index code Param reg_value [in] PHY register value Return ESP_OK: write PHY register successfully ESP_ERR_INVALID_STATE: write PHY register failed because of wrong state of MAC ESP_ERR_TIMEOUT: write PHY register failed because of timeout ESP_FAIL: write PHY register failed because some other error occurred esp_err_t (*set_addr)(esp_eth_mac_t *mac, uint8_t *addr) Set MAC address. Param mac [in] Ethernet MAC instance Param addr [in] MAC address Return ESP_OK: set MAC address successfully ESP_ERR_INVALID_ARG: set MAC address failed because of invalid argument ESP_FAIL: set MAC address failed because some other error occurred ESP_OK: set MAC address successfully ESP_ERR_INVALID_ARG: set MAC address failed because of invalid argument ESP_FAIL: set MAC address failed because some other error occurred ESP_OK: set MAC address successfully Param mac [in] Ethernet MAC instance Param addr [in] MAC address Return ESP_OK: set MAC address successfully ESP_ERR_INVALID_ARG: set MAC address failed because of invalid argument ESP_FAIL: set MAC address failed because some other error occurred esp_err_t (*set_addr)(esp_eth_mac_t *mac, uint8_t *addr) Set MAC address. Param mac [in] Ethernet MAC instance Param addr [in] MAC address Return ESP_OK: set MAC address successfully ESP_ERR_INVALID_ARG: set MAC address failed because of invalid argument ESP_FAIL: set MAC address failed because some other error occurred esp_err_t (*get_addr)(esp_eth_mac_t *mac, uint8_t *addr) Get MAC address. Param mac [in] Ethernet MAC instance Param addr [out] MAC address Return ESP_OK: get MAC address successfully ESP_ERR_INVALID_ARG: get MAC address failed because of invalid argument ESP_FAIL: get MAC address failed because some other error occurred ESP_OK: get MAC address successfully ESP_ERR_INVALID_ARG: get MAC address failed because of invalid argument ESP_FAIL: get MAC address failed because some other error occurred ESP_OK: get MAC address successfully Param mac [in] Ethernet MAC instance Param addr [out] MAC address Return ESP_OK: get MAC address successfully ESP_ERR_INVALID_ARG: get MAC address failed because of invalid argument ESP_FAIL: get MAC address failed because some other error occurred esp_err_t (*get_addr)(esp_eth_mac_t *mac, uint8_t *addr) Get MAC address. Param mac [in] Ethernet MAC instance Param addr [out] MAC address Return ESP_OK: get MAC address successfully ESP_ERR_INVALID_ARG: get MAC address failed because of invalid argument ESP_FAIL: get MAC address failed because some other error occurred esp_err_t (*set_speed)(esp_eth_mac_t *mac, eth_speed_t speed) Set speed of MAC. Param ma:c [in] Ethernet MAC instance Param speed [in] MAC speed Return ESP_OK: set MAC speed successfully ESP_ERR_INVALID_ARG: set MAC speed failed because of invalid argument ESP_FAIL: set MAC speed failed because some other error occurred ESP_OK: set MAC speed successfully ESP_ERR_INVALID_ARG: set MAC speed failed because of invalid argument ESP_FAIL: set MAC speed failed because some other error occurred ESP_OK: set MAC speed successfully Param ma:c [in] Ethernet MAC instance Param speed [in] MAC speed Return ESP_OK: set MAC speed successfully ESP_ERR_INVALID_ARG: set MAC speed failed because of invalid argument ESP_FAIL: set MAC speed failed because some other error occurred esp_err_t (*set_speed)(esp_eth_mac_t *mac, eth_speed_t speed) Set speed of MAC. Param ma:c [in] Ethernet MAC instance Param speed [in] MAC speed Return ESP_OK: set MAC speed successfully ESP_ERR_INVALID_ARG: set MAC speed failed because of invalid argument ESP_FAIL: set MAC speed failed because some other error occurred esp_err_t (*set_duplex)(esp_eth_mac_t *mac, eth_duplex_t duplex) Set duplex mode of MAC. Param mac [in] Ethernet MAC instance Param duplex [in] MAC duplex Return ESP_OK: set MAC duplex mode successfully ESP_ERR_INVALID_ARG: set MAC duplex failed because of invalid argument ESP_FAIL: set MAC duplex failed because some other error occurred ESP_OK: set MAC duplex mode successfully ESP_ERR_INVALID_ARG: set MAC duplex failed because of invalid argument ESP_FAIL: set MAC duplex failed because some other error occurred ESP_OK: set MAC duplex mode successfully Param mac [in] Ethernet MAC instance Param duplex [in] MAC duplex Return ESP_OK: set MAC duplex mode successfully ESP_ERR_INVALID_ARG: set MAC duplex failed because of invalid argument ESP_FAIL: set MAC duplex failed because some other error occurred esp_err_t (*set_duplex)(esp_eth_mac_t *mac, eth_duplex_t duplex) Set duplex mode of MAC. Param mac [in] Ethernet MAC instance Param duplex [in] MAC duplex Return ESP_OK: set MAC duplex mode successfully ESP_ERR_INVALID_ARG: set MAC duplex failed because of invalid argument ESP_FAIL: set MAC duplex failed because some other error occurred esp_err_t (*set_link)(esp_eth_mac_t *mac, eth_link_t link) Set link status of MAC. Param mac [in] Ethernet MAC instance Param link [in] Link status Return ESP_OK: set link status successfully ESP_ERR_INVALID_ARG: set link status failed because of invalid argument ESP_FAIL: set link status failed because some other error occurred ESP_OK: set link status successfully ESP_ERR_INVALID_ARG: set link status failed because of invalid argument ESP_FAIL: set link status failed because some other error occurred ESP_OK: set link status successfully Param mac [in] Ethernet MAC instance Param link [in] Link status Return ESP_OK: set link status successfully ESP_ERR_INVALID_ARG: set link status failed because of invalid argument ESP_FAIL: set link status failed because some other error occurred esp_err_t (*set_link)(esp_eth_mac_t *mac, eth_link_t link) Set link status of MAC. Param mac [in] Ethernet MAC instance Param link [in] Link status Return ESP_OK: set link status successfully ESP_ERR_INVALID_ARG: set link status failed because of invalid argument ESP_FAIL: set link status failed because some other error occurred esp_err_t (*set_promiscuous)(esp_eth_mac_t *mac, bool enable) Set promiscuous of MAC. Param mac [in] Ethernet MAC instance Param enable [in] set true to enable promiscuous mode; set false to disable promiscuous mode Return ESP_OK: set promiscuous mode successfully ESP_FAIL: set promiscuous mode failed because some error occurred ESP_OK: set promiscuous mode successfully ESP_FAIL: set promiscuous mode failed because some error occurred ESP_OK: set promiscuous mode successfully Param mac [in] Ethernet MAC instance Param enable [in] set true to enable promiscuous mode; set false to disable promiscuous mode Return ESP_OK: set promiscuous mode successfully ESP_FAIL: set promiscuous mode failed because some error occurred esp_err_t (*set_promiscuous)(esp_eth_mac_t *mac, bool enable) Set promiscuous of MAC. Param mac [in] Ethernet MAC instance Param enable [in] set true to enable promiscuous mode; set false to disable promiscuous mode Return ESP_OK: set promiscuous mode successfully ESP_FAIL: set promiscuous mode failed because some error occurred esp_err_t (*enable_flow_ctrl)(esp_eth_mac_t *mac, bool enable) Enable flow control on MAC layer or not. Param mac [in] Ethernet MAC instance Param enable [in] set true to enable flow control; set false to disable flow control Return ESP_OK: set flow control successfully ESP_FAIL: set flow control failed because some error occurred ESP_OK: set flow control successfully ESP_FAIL: set flow control failed because some error occurred ESP_OK: set flow control successfully Param mac [in] Ethernet MAC instance Param enable [in] set true to enable flow control; set false to disable flow control Return ESP_OK: set flow control successfully ESP_FAIL: set flow control failed because some error occurred esp_err_t (*enable_flow_ctrl)(esp_eth_mac_t *mac, bool enable) Enable flow control on MAC layer or not. Param mac [in] Ethernet MAC instance Param enable [in] set true to enable flow control; set false to disable flow control Return ESP_OK: set flow control successfully ESP_FAIL: set flow control failed because some error occurred esp_err_t (*set_peer_pause_ability)(esp_eth_mac_t *mac, uint32_t ability) Set the PAUSE ability of peer node. Param mac [in] Ethernet MAC instance Param ability [in] zero indicates that pause function is supported by link partner; non-zero indicates that pause function is not supported by link partner Return ESP_OK: set peer pause ability successfully ESP_FAIL: set peer pause ability failed because some error occurred ESP_OK: set peer pause ability successfully ESP_FAIL: set peer pause ability failed because some error occurred ESP_OK: set peer pause ability successfully Param mac [in] Ethernet MAC instance Param ability [in] zero indicates that pause function is supported by link partner; non-zero indicates that pause function is not supported by link partner Return ESP_OK: set peer pause ability successfully ESP_FAIL: set peer pause ability failed because some error occurred esp_err_t (*set_peer_pause_ability)(esp_eth_mac_t *mac, uint32_t ability) Set the PAUSE ability of peer node. Param mac [in] Ethernet MAC instance Param ability [in] zero indicates that pause function is supported by link partner; non-zero indicates that pause function is not supported by link partner Return ESP_OK: set peer pause ability successfully ESP_FAIL: set peer pause ability failed because some error occurred esp_err_t (*custom_ioctl)(esp_eth_mac_t *mac, uint32_t cmd, void *data) Custom IO function of MAC driver. This function is intended to extend common options of esp_eth_ioctl to cover specifics of MAC chip. Note This function may not be assigned when the MAC chip supports only most common set of configuration options. Param mac [in] Ethernet MAC instance Param cmd [in] IO control command Param data [inout] address of data for set command or address where to store the data when used with get command Return ESP_OK: process io command successfully ESP_ERR_INVALID_ARG: process io command failed because of some invalid argument ESP_FAIL: process io command failed because some other error occurred ESP_ERR_NOT_SUPPORTED: requested feature is not supported ESP_OK: process io command successfully ESP_ERR_INVALID_ARG: process io command failed because of some invalid argument ESP_FAIL: process io command failed because some other error occurred ESP_ERR_NOT_SUPPORTED: requested feature is not supported ESP_OK: process io command successfully Param mac [in] Ethernet MAC instance Param cmd [in] IO control command Param data [inout] address of data for set command or address where to store the data when used with get command Return ESP_OK: process io command successfully ESP_ERR_INVALID_ARG: process io command failed because of some invalid argument ESP_FAIL: process io command failed because some other error occurred ESP_ERR_NOT_SUPPORTED: requested feature is not supported esp_err_t (*custom_ioctl)(esp_eth_mac_t *mac, uint32_t cmd, void *data) Custom IO function of MAC driver. This function is intended to extend common options of esp_eth_ioctl to cover specifics of MAC chip. Note This function may not be assigned when the MAC chip supports only most common set of configuration options. Param mac [in] Ethernet MAC instance Param cmd [in] IO control command Param data [inout] address of data for set command or address where to store the data when used with get command Return ESP_OK: process io command successfully ESP_ERR_INVALID_ARG: process io command failed because of some invalid argument ESP_FAIL: process io command failed because some other error occurred ESP_ERR_NOT_SUPPORTED: requested feature is not supported esp_err_t (*del)(esp_eth_mac_t *mac) Free memory of Ethernet MAC. Param mac [in] Ethernet MAC instance Return ESP_OK: free Ethernet MAC instance successfully ESP_FAIL: free Ethernet MAC instance failed because some error occurred ESP_OK: free Ethernet MAC instance successfully ESP_FAIL: free Ethernet MAC instance failed because some error occurred ESP_OK: free Ethernet MAC instance successfully Param mac [in] Ethernet MAC instance Return ESP_OK: free Ethernet MAC instance successfully ESP_FAIL: free Ethernet MAC instance failed because some error occurred esp_err_t (*del)(esp_eth_mac_t *mac) Free memory of Ethernet MAC. Param mac [in] Ethernet MAC instance Return ESP_OK: free Ethernet MAC instance successfully ESP_FAIL: free Ethernet MAC instance failed because some error occurred esp_err_t (*set_mediator)(esp_eth_mac_t *mac, esp_eth_mediator_t *eth) struct eth_mac_config_t Configuration of Ethernet MAC object. struct eth_esp32_emac_config_t EMAC specific configuration. Public Members int smi_mdc_gpio_num SMI MDC GPIO number, set to -1 could bypass the SMI GPIO configuration int smi_mdc_gpio_num SMI MDC GPIO number, set to -1 could bypass the SMI GPIO configuration int smi_mdio_gpio_num SMI MDIO GPIO number, set to -1 could bypass the SMI GPIO configuration int smi_mdio_gpio_num SMI MDIO GPIO number, set to -1 could bypass the SMI GPIO configuration eth_data_interface_t interface EMAC Data interface to PHY (MII/RMII) eth_data_interface_t interface EMAC Data interface to PHY (MII/RMII) eth_mac_clock_config_t clock_config EMAC Interface clock configuration eth_mac_clock_config_t clock_config EMAC Interface clock configuration eth_mac_dma_burst_len_t dma_burst_len EMAC DMA burst length for both Tx and Rx eth_mac_dma_burst_len_t dma_burst_len EMAC DMA burst length for both Tx and Rx int smi_mdc_gpio_num struct eth_spi_custom_driver_config_t Custom SPI Driver Configuration. This structure declares configuration and callback functions to access Ethernet SPI module via user's custom SPI driver. Public Members void *config Custom driver specific configuration data used by init() function. Note Type and its content is fully under user's control void *config Custom driver specific configuration data used by init() function. Note Type and its content is fully under user's control void *(*init)(const void *spi_config) Custom driver SPI Initialization. Note return type and its content is fully under user's control Param spi_config [in] Custom driver specific configuration Return spi_ctx: when initialization is successful, a pointer to context structure holding all variables needed for subsequent SPI access operations (e.g. SPI bus identification, mutexes, etc.) NULL: driver initialization failed spi_ctx: when initialization is successful, a pointer to context structure holding all variables needed for subsequent SPI access operations (e.g. SPI bus identification, mutexes, etc.) NULL: driver initialization failed spi_ctx: when initialization is successful, a pointer to context structure holding all variables needed for subsequent SPI access operations (e.g. SPI bus identification, mutexes, etc.) Param spi_config [in] Custom driver specific configuration Return spi_ctx: when initialization is successful, a pointer to context structure holding all variables needed for subsequent SPI access operations (e.g. SPI bus identification, mutexes, etc.) NULL: driver initialization failed void *(*init)(const void *spi_config) Custom driver SPI Initialization. Note return type and its content is fully under user's control Param spi_config [in] Custom driver specific configuration Return spi_ctx: when initialization is successful, a pointer to context structure holding all variables needed for subsequent SPI access operations (e.g. SPI bus identification, mutexes, etc.) NULL: driver initialization failed esp_err_t (*deinit)(void *spi_ctx) Custom driver De-initialization. Param spi_ctx [in] a pointer to driver specific context structure Return ESP_OK: driver de-initialization was successful ESP_FAIL: driver de-initialization failed any other failure codes are allowed to be used to provide failure isolation ESP_OK: driver de-initialization was successful ESP_FAIL: driver de-initialization failed any other failure codes are allowed to be used to provide failure isolation ESP_OK: driver de-initialization was successful Param spi_ctx [in] a pointer to driver specific context structure Return ESP_OK: driver de-initialization was successful ESP_FAIL: driver de-initialization failed any other failure codes are allowed to be used to provide failure isolation esp_err_t (*deinit)(void *spi_ctx) Custom driver De-initialization. Param spi_ctx [in] a pointer to driver specific context structure Return ESP_OK: driver de-initialization was successful ESP_FAIL: driver de-initialization failed any other failure codes are allowed to be used to provide failure isolation esp_err_t (*read)(void *spi_ctx, uint32_t cmd, uint32_t addr, void *data, uint32_t data_len) Custom driver SPI read. Note The read function is responsible to construct command, address and data fields of the SPI frame in format expected by particular SPI Ethernet module Param spi_ctx [in] a pointer to driver specific context structure Param cmd [in] command Param addr [in] register address Param data [out] read data Param data_len [in] read data length in bytes Return ESP_OK: read was successful ESP_FAIL: read failed any other failure codes are allowed to be used to provide failure isolation ESP_OK: read was successful ESP_FAIL: read failed any other failure codes are allowed to be used to provide failure isolation ESP_OK: read was successful Param spi_ctx [in] a pointer to driver specific context structure Param cmd [in] command Param addr [in] register address Param data [out] read data Param data_len [in] read data length in bytes Return ESP_OK: read was successful ESP_FAIL: read failed any other failure codes are allowed to be used to provide failure isolation esp_err_t (*read)(void *spi_ctx, uint32_t cmd, uint32_t addr, void *data, uint32_t data_len) Custom driver SPI read. Note The read function is responsible to construct command, address and data fields of the SPI frame in format expected by particular SPI Ethernet module Param spi_ctx [in] a pointer to driver specific context structure Param cmd [in] command Param addr [in] register address Param data [out] read data Param data_len [in] read data length in bytes Return ESP_OK: read was successful ESP_FAIL: read failed any other failure codes are allowed to be used to provide failure isolation esp_err_t (*write)(void *spi_ctx, uint32_t cmd, uint32_t addr, const void *data, uint32_t data_len) Custom driver SPI write. Note The write function is responsible to construct command, address and data fields of the SPI frame in format expected by particular SPI Ethernet module Param spi_ctx [in] a pointer to driver specific context structure Param cmd [in] command Param addr [in] register address Param data [in] data to write Param data_len [in] length of data to write in bytes Return ESP_OK: write was successful ESP_FAIL: write failed any other failure codes are allowed to be used to provide failure isolation ESP_OK: write was successful ESP_FAIL: write failed any other failure codes are allowed to be used to provide failure isolation ESP_OK: write was successful Param spi_ctx [in] a pointer to driver specific context structure Param cmd [in] command Param addr [in] register address Param data [in] data to write Param data_len [in] length of data to write in bytes Return ESP_OK: write was successful ESP_FAIL: write failed any other failure codes are allowed to be used to provide failure isolation esp_err_t (*write)(void *spi_ctx, uint32_t cmd, uint32_t addr, const void *data, uint32_t data_len) Custom driver SPI write. Note The write function is responsible to construct command, address and data fields of the SPI frame in format expected by particular SPI Ethernet module Param spi_ctx [in] a pointer to driver specific context structure Param cmd [in] command Param addr [in] register address Param data [in] data to write Param data_len [in] length of data to write in bytes Return ESP_OK: write was successful ESP_FAIL: write failed any other failure codes are allowed to be used to provide failure isolation void *config Macros ETH_MAC_FLAG_WORK_WITH_CACHE_DISABLE MAC driver can work when cache is disabled ETH_MAC_FLAG_PIN_TO_CORE Pin MAC task to the CPU core where driver installation happened ETH_MAC_DEFAULT_CONFIG() Default configuration for Ethernet MAC object. ETH_ESP32_EMAC_DEFAULT_CONFIG() Default ESP32's EMAC specific configuration. ETH_DEFAULT_SPI Default configuration of the custom SPI driver. Internal ESP-IDF SPI Master driver is used by default. Type Definitions typedef struct esp_eth_mac_s esp_eth_mac_t Ethernet MAC. Enumerations enum emac_rmii_clock_mode_t RMII Clock Mode Options. Values: enumerator EMAC_CLK_DEFAULT Default values configured using Kconfig are going to be used when "Default" selected. enumerator EMAC_CLK_DEFAULT Default values configured using Kconfig are going to be used when "Default" selected. enumerator EMAC_CLK_EXT_IN Input RMII Clock from external. EMAC Clock GPIO number needs to be configured when this option is selected. Note MAC will get RMII clock from outside. Note that ESP32 only supports GPIO0 to input the RMII clock. enumerator EMAC_CLK_EXT_IN Input RMII Clock from external. EMAC Clock GPIO number needs to be configured when this option is selected. Note MAC will get RMII clock from outside. Note that ESP32 only supports GPIO0 to input the RMII clock. enumerator EMAC_CLK_OUT Output RMII Clock from internal APLL Clock. EMAC Clock GPIO number needs to be configured when this option is selected. enumerator EMAC_CLK_OUT Output RMII Clock from internal APLL Clock. EMAC Clock GPIO number needs to be configured when this option is selected. enumerator EMAC_CLK_DEFAULT enum emac_rmii_clock_gpio_t RMII Clock GPIO number Options. Values: enumerator EMAC_CLK_IN_GPIO MAC will get RMII clock from outside at this GPIO. Note ESP32 only supports GPIO0 to input the RMII clock. enumerator EMAC_CLK_IN_GPIO MAC will get RMII clock from outside at this GPIO. Note ESP32 only supports GPIO0 to input the RMII clock. enumerator EMAC_APPL_CLK_OUT_GPIO Output RMII Clock from internal APLL Clock available at GPIO0. Note GPIO0 can be set to output a pre-divided PLL clock (test only!). Enabling this option will configure GPIO0 to output a 50MHz clock. In fact this clock doesn’t have directly relationship with EMAC peripheral. Sometimes this clock won’t work well with your PHY chip. You might need to add some extra devices after GPIO0 (e.g. inverter). Note that outputting RMII clock on GPIO0 is an experimental practice. If you want the Ethernet to work with WiFi, don’t select GPIO0 output mode for stability. enumerator EMAC_APPL_CLK_OUT_GPIO Output RMII Clock from internal APLL Clock available at GPIO0. Note GPIO0 can be set to output a pre-divided PLL clock (test only!). Enabling this option will configure GPIO0 to output a 50MHz clock. In fact this clock doesn’t have directly relationship with EMAC peripheral. Sometimes this clock won’t work well with your PHY chip. You might need to add some extra devices after GPIO0 (e.g. inverter). Note that outputting RMII clock on GPIO0 is an experimental practice. If you want the Ethernet to work with WiFi, don’t select GPIO0 output mode for stability. enumerator EMAC_CLK_OUT_GPIO Output RMII Clock from internal APLL Clock available at GPIO16. enumerator EMAC_CLK_OUT_GPIO Output RMII Clock from internal APLL Clock available at GPIO16. enumerator EMAC_CLK_OUT_180_GPIO Inverted Output RMII Clock from internal APLL Clock available at GPIO17. enumerator EMAC_CLK_OUT_180_GPIO Inverted Output RMII Clock from internal APLL Clock available at GPIO17. enumerator EMAC_CLK_IN_GPIO Header File This header file can be included with: #include "esp_eth_phy.h" This header file is a part of the API provided by the esp_eth component. To declare that your component depends on esp_eth , add the following to your CMakeLists.txt: REQUIRES esp_eth or PRIV_REQUIRES esp_eth Functions esp_eth_phy_t *esp_eth_phy_new_ip101(const eth_phy_config_t *config) Create a PHY instance of IP101. Parameters config -- [in] configuration of PHY Returns instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred instance: create PHY instance successfully Parameters config -- [in] configuration of PHY Returns instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred esp_eth_phy_t *esp_eth_phy_new_rtl8201(const eth_phy_config_t *config) Create a PHY instance of RTL8201. Parameters config -- [in] configuration of PHY Returns instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred instance: create PHY instance successfully Parameters config -- [in] configuration of PHY Returns instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred esp_eth_phy_t *esp_eth_phy_new_lan87xx(const eth_phy_config_t *config) Create a PHY instance of LAN87xx. Parameters config -- [in] configuration of PHY Returns instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred instance: create PHY instance successfully Parameters config -- [in] configuration of PHY Returns instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred esp_eth_phy_t *esp_eth_phy_new_dp83848(const eth_phy_config_t *config) Create a PHY instance of DP83848. Parameters config -- [in] configuration of PHY Returns instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred instance: create PHY instance successfully Parameters config -- [in] configuration of PHY Returns instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred esp_eth_phy_t *esp_eth_phy_new_ksz80xx(const eth_phy_config_t *config) Create a PHY instance of KSZ80xx. The phy model from the KSZ80xx series is detected automatically. If the driver is unable to detect a supported model, NULL is returned. Currently, the following models are supported: KSZ8001, KSZ8021, KSZ8031, KSZ8041, KSZ8051, KSZ8061, KSZ8081, KSZ8091 Parameters config -- [in] configuration of PHY Returns instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred instance: create PHY instance successfully Parameters config -- [in] configuration of PHY Returns instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred Structures struct esp_eth_phy_s Ethernet PHY. Public Members esp_err_t (*set_mediator)(esp_eth_phy_t *phy, esp_eth_mediator_t *mediator) Set mediator for PHY. Param phy [in] Ethernet PHY instance Param mediator [in] mediator of Ethernet driver Return ESP_OK: set mediator for Ethernet PHY instance successfully ESP_ERR_INVALID_ARG: set mediator for Ethernet PHY instance failed because of some invalid arguments ESP_OK: set mediator for Ethernet PHY instance successfully ESP_ERR_INVALID_ARG: set mediator for Ethernet PHY instance failed because of some invalid arguments ESP_OK: set mediator for Ethernet PHY instance successfully Param phy [in] Ethernet PHY instance Param mediator [in] mediator of Ethernet driver Return ESP_OK: set mediator for Ethernet PHY instance successfully ESP_ERR_INVALID_ARG: set mediator for Ethernet PHY instance failed because of some invalid arguments esp_err_t (*set_mediator)(esp_eth_phy_t *phy, esp_eth_mediator_t *mediator) Set mediator for PHY. Param phy [in] Ethernet PHY instance Param mediator [in] mediator of Ethernet driver Return ESP_OK: set mediator for Ethernet PHY instance successfully ESP_ERR_INVALID_ARG: set mediator for Ethernet PHY instance failed because of some invalid arguments esp_err_t (*reset)(esp_eth_phy_t *phy) Software Reset Ethernet PHY. Param phy [in] Ethernet PHY instance Return ESP_OK: reset Ethernet PHY successfully ESP_FAIL: reset Ethernet PHY failed because some error occurred ESP_OK: reset Ethernet PHY successfully ESP_FAIL: reset Ethernet PHY failed because some error occurred ESP_OK: reset Ethernet PHY successfully Param phy [in] Ethernet PHY instance Return ESP_OK: reset Ethernet PHY successfully ESP_FAIL: reset Ethernet PHY failed because some error occurred esp_err_t (*reset)(esp_eth_phy_t *phy) Software Reset Ethernet PHY. Param phy [in] Ethernet PHY instance Return ESP_OK: reset Ethernet PHY successfully ESP_FAIL: reset Ethernet PHY failed because some error occurred esp_err_t (*reset_hw)(esp_eth_phy_t *phy) Hardware Reset Ethernet PHY. Note Hardware reset is mostly done by pull down and up PHY's nRST pin Param phy [in] Ethernet PHY instance Return ESP_OK: reset Ethernet PHY successfully ESP_FAIL: reset Ethernet PHY failed because some error occurred ESP_OK: reset Ethernet PHY successfully ESP_FAIL: reset Ethernet PHY failed because some error occurred ESP_OK: reset Ethernet PHY successfully Param phy [in] Ethernet PHY instance Return ESP_OK: reset Ethernet PHY successfully ESP_FAIL: reset Ethernet PHY failed because some error occurred esp_err_t (*reset_hw)(esp_eth_phy_t *phy) Hardware Reset Ethernet PHY. Note Hardware reset is mostly done by pull down and up PHY's nRST pin Param phy [in] Ethernet PHY instance Return ESP_OK: reset Ethernet PHY successfully ESP_FAIL: reset Ethernet PHY failed because some error occurred esp_err_t (*init)(esp_eth_phy_t *phy) Initialize Ethernet PHY. Param phy [in] Ethernet PHY instance Return ESP_OK: initialize Ethernet PHY successfully ESP_FAIL: initialize Ethernet PHY failed because some error occurred ESP_OK: initialize Ethernet PHY successfully ESP_FAIL: initialize Ethernet PHY failed because some error occurred ESP_OK: initialize Ethernet PHY successfully Param phy [in] Ethernet PHY instance Return ESP_OK: initialize Ethernet PHY successfully ESP_FAIL: initialize Ethernet PHY failed because some error occurred esp_err_t (*init)(esp_eth_phy_t *phy) Initialize Ethernet PHY. Param phy [in] Ethernet PHY instance Return ESP_OK: initialize Ethernet PHY successfully ESP_FAIL: initialize Ethernet PHY failed because some error occurred esp_err_t (*deinit)(esp_eth_phy_t *phy) Deinitialize Ethernet PHY. Param phy [in] Ethernet PHY instance Return ESP_OK: deinitialize Ethernet PHY successfully ESP_FAIL: deinitialize Ethernet PHY failed because some error occurred ESP_OK: deinitialize Ethernet PHY successfully ESP_FAIL: deinitialize Ethernet PHY failed because some error occurred ESP_OK: deinitialize Ethernet PHY successfully Param phy [in] Ethernet PHY instance Return ESP_OK: deinitialize Ethernet PHY successfully ESP_FAIL: deinitialize Ethernet PHY failed because some error occurred esp_err_t (*deinit)(esp_eth_phy_t *phy) Deinitialize Ethernet PHY. Param phy [in] Ethernet PHY instance Return ESP_OK: deinitialize Ethernet PHY successfully ESP_FAIL: deinitialize Ethernet PHY failed because some error occurred esp_err_t (*autonego_ctrl)(esp_eth_phy_t *phy, eth_phy_autoneg_cmd_t cmd, bool *autonego_en_stat) Configure auto negotiation. Param phy [in] Ethernet PHY instance Param cmd [in] Configuration command, it is possible to Enable (restart), Disable or get current status of PHY auto negotiation Param autonego_en_stat [out] Address where to store current status of auto negotiation configuration Return ESP_OK: restart auto negotiation successfully ESP_FAIL: restart auto negotiation failed because some error occurred ESP_ERR_INVALID_ARG: invalid command ESP_OK: restart auto negotiation successfully ESP_FAIL: restart auto negotiation failed because some error occurred ESP_ERR_INVALID_ARG: invalid command ESP_OK: restart auto negotiation successfully Param phy [in] Ethernet PHY instance Param cmd [in] Configuration command, it is possible to Enable (restart), Disable or get current status of PHY auto negotiation Param autonego_en_stat [out] Address where to store current status of auto negotiation configuration Return ESP_OK: restart auto negotiation successfully ESP_FAIL: restart auto negotiation failed because some error occurred ESP_ERR_INVALID_ARG: invalid command esp_err_t (*autonego_ctrl)(esp_eth_phy_t *phy, eth_phy_autoneg_cmd_t cmd, bool *autonego_en_stat) Configure auto negotiation. Param phy [in] Ethernet PHY instance Param cmd [in] Configuration command, it is possible to Enable (restart), Disable or get current status of PHY auto negotiation Param autonego_en_stat [out] Address where to store current status of auto negotiation configuration Return ESP_OK: restart auto negotiation successfully ESP_FAIL: restart auto negotiation failed because some error occurred ESP_ERR_INVALID_ARG: invalid command esp_err_t (*get_link)(esp_eth_phy_t *phy) Get Ethernet PHY link status. Param phy [in] Ethernet PHY instance Return ESP_OK: get Ethernet PHY link status successfully ESP_FAIL: get Ethernet PHY link status failed because some error occurred ESP_OK: get Ethernet PHY link status successfully ESP_FAIL: get Ethernet PHY link status failed because some error occurred ESP_OK: get Ethernet PHY link status successfully Param phy [in] Ethernet PHY instance Return ESP_OK: get Ethernet PHY link status successfully ESP_FAIL: get Ethernet PHY link status failed because some error occurred esp_err_t (*get_link)(esp_eth_phy_t *phy) Get Ethernet PHY link status. Param phy [in] Ethernet PHY instance Return ESP_OK: get Ethernet PHY link status successfully ESP_FAIL: get Ethernet PHY link status failed because some error occurred esp_err_t (*pwrctl)(esp_eth_phy_t *phy, bool enable) Power control of Ethernet PHY. Param phy [in] Ethernet PHY instance Param enable [in] set true to power on Ethernet PHY; ser false to power off Ethernet PHY Return ESP_OK: control Ethernet PHY power successfully ESP_FAIL: control Ethernet PHY power failed because some error occurred ESP_OK: control Ethernet PHY power successfully ESP_FAIL: control Ethernet PHY power failed because some error occurred ESP_OK: control Ethernet PHY power successfully Param phy [in] Ethernet PHY instance Param enable [in] set true to power on Ethernet PHY; ser false to power off Ethernet PHY Return ESP_OK: control Ethernet PHY power successfully ESP_FAIL: control Ethernet PHY power failed because some error occurred esp_err_t (*pwrctl)(esp_eth_phy_t *phy, bool enable) Power control of Ethernet PHY. Param phy [in] Ethernet PHY instance Param enable [in] set true to power on Ethernet PHY; ser false to power off Ethernet PHY Return ESP_OK: control Ethernet PHY power successfully ESP_FAIL: control Ethernet PHY power failed because some error occurred esp_err_t (*set_addr)(esp_eth_phy_t *phy, uint32_t addr) Set PHY chip address. Param phy [in] Ethernet PHY instance Param addr [in] PHY chip address Return ESP_OK: set Ethernet PHY address successfully ESP_FAIL: set Ethernet PHY address failed because some error occurred ESP_OK: set Ethernet PHY address successfully ESP_FAIL: set Ethernet PHY address failed because some error occurred ESP_OK: set Ethernet PHY address successfully Param phy [in] Ethernet PHY instance Param addr [in] PHY chip address Return ESP_OK: set Ethernet PHY address successfully ESP_FAIL: set Ethernet PHY address failed because some error occurred esp_err_t (*set_addr)(esp_eth_phy_t *phy, uint32_t addr) Set PHY chip address. Param phy [in] Ethernet PHY instance Param addr [in] PHY chip address Return ESP_OK: set Ethernet PHY address successfully ESP_FAIL: set Ethernet PHY address failed because some error occurred esp_err_t (*get_addr)(esp_eth_phy_t *phy, uint32_t *addr) Get PHY chip address. Param phy [in] Ethernet PHY instance Param addr [out] PHY chip address Return ESP_OK: get Ethernet PHY address successfully ESP_ERR_INVALID_ARG: get Ethernet PHY address failed because of invalid argument ESP_OK: get Ethernet PHY address successfully ESP_ERR_INVALID_ARG: get Ethernet PHY address failed because of invalid argument ESP_OK: get Ethernet PHY address successfully Param phy [in] Ethernet PHY instance Param addr [out] PHY chip address Return ESP_OK: get Ethernet PHY address successfully ESP_ERR_INVALID_ARG: get Ethernet PHY address failed because of invalid argument esp_err_t (*get_addr)(esp_eth_phy_t *phy, uint32_t *addr) Get PHY chip address. Param phy [in] Ethernet PHY instance Param addr [out] PHY chip address Return ESP_OK: get Ethernet PHY address successfully ESP_ERR_INVALID_ARG: get Ethernet PHY address failed because of invalid argument esp_err_t (*advertise_pause_ability)(esp_eth_phy_t *phy, uint32_t ability) Advertise pause function supported by MAC layer. Param phy [in] Ethernet PHY instance Param addr [out] Pause ability Return ESP_OK: Advertise pause ability successfully ESP_ERR_INVALID_ARG: Advertise pause ability failed because of invalid argument ESP_OK: Advertise pause ability successfully ESP_ERR_INVALID_ARG: Advertise pause ability failed because of invalid argument ESP_OK: Advertise pause ability successfully Param phy [in] Ethernet PHY instance Param addr [out] Pause ability Return ESP_OK: Advertise pause ability successfully ESP_ERR_INVALID_ARG: Advertise pause ability failed because of invalid argument esp_err_t (*advertise_pause_ability)(esp_eth_phy_t *phy, uint32_t ability) Advertise pause function supported by MAC layer. Param phy [in] Ethernet PHY instance Param addr [out] Pause ability Return ESP_OK: Advertise pause ability successfully ESP_ERR_INVALID_ARG: Advertise pause ability failed because of invalid argument esp_err_t (*loopback)(esp_eth_phy_t *phy, bool enable) Sets the PHY to loopback mode. Param phy [in] Ethernet PHY instance Param enable [in] enables or disables PHY loopback Return ESP_OK: PHY instance loopback mode has been configured successfully ESP_FAIL: PHY instance loopback configuration failed because some error occurred ESP_OK: PHY instance loopback mode has been configured successfully ESP_FAIL: PHY instance loopback configuration failed because some error occurred ESP_OK: PHY instance loopback mode has been configured successfully Param phy [in] Ethernet PHY instance Param enable [in] enables or disables PHY loopback Return ESP_OK: PHY instance loopback mode has been configured successfully ESP_FAIL: PHY instance loopback configuration failed because some error occurred esp_err_t (*loopback)(esp_eth_phy_t *phy, bool enable) Sets the PHY to loopback mode. Param phy [in] Ethernet PHY instance Param enable [in] enables or disables PHY loopback Return ESP_OK: PHY instance loopback mode has been configured successfully ESP_FAIL: PHY instance loopback configuration failed because some error occurred esp_err_t (*set_speed)(esp_eth_phy_t *phy, eth_speed_t speed) Sets PHY speed mode. Note Autonegotiation feature needs to be disabled prior to calling this function for the new setting to be applied Param phy [in] Ethernet PHY instance Param speed [in] Speed mode to be set Return ESP_OK: PHY instance speed mode has been configured successfully ESP_FAIL: PHY instance speed mode configuration failed because some error occurred ESP_OK: PHY instance speed mode has been configured successfully ESP_FAIL: PHY instance speed mode configuration failed because some error occurred ESP_OK: PHY instance speed mode has been configured successfully Param phy [in] Ethernet PHY instance Param speed [in] Speed mode to be set Return ESP_OK: PHY instance speed mode has been configured successfully ESP_FAIL: PHY instance speed mode configuration failed because some error occurred esp_err_t (*set_speed)(esp_eth_phy_t *phy, eth_speed_t speed) Sets PHY speed mode. Note Autonegotiation feature needs to be disabled prior to calling this function for the new setting to be applied Param phy [in] Ethernet PHY instance Param speed [in] Speed mode to be set Return ESP_OK: PHY instance speed mode has been configured successfully ESP_FAIL: PHY instance speed mode configuration failed because some error occurred esp_err_t (*set_duplex)(esp_eth_phy_t *phy, eth_duplex_t duplex) Sets PHY duplex mode. Note Autonegotiation feature needs to be disabled prior to calling this function for the new setting to be applied Param phy [in] Ethernet PHY instance Param duplex [in] Duplex mode to be set Return ESP_OK: PHY instance duplex mode has been configured successfully ESP_FAIL: PHY instance duplex mode configuration failed because some error occurred ESP_OK: PHY instance duplex mode has been configured successfully ESP_FAIL: PHY instance duplex mode configuration failed because some error occurred ESP_OK: PHY instance duplex mode has been configured successfully Param phy [in] Ethernet PHY instance Param duplex [in] Duplex mode to be set Return ESP_OK: PHY instance duplex mode has been configured successfully ESP_FAIL: PHY instance duplex mode configuration failed because some error occurred esp_err_t (*set_duplex)(esp_eth_phy_t *phy, eth_duplex_t duplex) Sets PHY duplex mode. Note Autonegotiation feature needs to be disabled prior to calling this function for the new setting to be applied Param phy [in] Ethernet PHY instance Param duplex [in] Duplex mode to be set Return ESP_OK: PHY instance duplex mode has been configured successfully ESP_FAIL: PHY instance duplex mode configuration failed because some error occurred esp_err_t (*custom_ioctl)(esp_eth_phy_t *phy, uint32_t cmd, void *data) Custom IO function of PHY driver. This function is intended to extend common options of esp_eth_ioctl to cover specifics of PHY chip. Note This function may not be assigned when the PHY chip supports only most common set of configuration options. Param phy [in] Ethernet PHY instance Param cmd [in] IO control command Param data [inout] address of data for set command or address where to store the data when used with get command Return ESP_OK: process io command successfully ESP_ERR_INVALID_ARG: process io command failed because of some invalid argument ESP_FAIL: process io command failed because some other error occurred ESP_ERR_NOT_SUPPORTED: requested feature is not supported ESP_OK: process io command successfully ESP_ERR_INVALID_ARG: process io command failed because of some invalid argument ESP_FAIL: process io command failed because some other error occurred ESP_ERR_NOT_SUPPORTED: requested feature is not supported ESP_OK: process io command successfully Param phy [in] Ethernet PHY instance Param cmd [in] IO control command Param data [inout] address of data for set command or address where to store the data when used with get command Return ESP_OK: process io command successfully ESP_ERR_INVALID_ARG: process io command failed because of some invalid argument ESP_FAIL: process io command failed because some other error occurred ESP_ERR_NOT_SUPPORTED: requested feature is not supported esp_err_t (*custom_ioctl)(esp_eth_phy_t *phy, uint32_t cmd, void *data) Custom IO function of PHY driver. This function is intended to extend common options of esp_eth_ioctl to cover specifics of PHY chip. Note This function may not be assigned when the PHY chip supports only most common set of configuration options. Param phy [in] Ethernet PHY instance Param cmd [in] IO control command Param data [inout] address of data for set command or address where to store the data when used with get command Return ESP_OK: process io command successfully ESP_ERR_INVALID_ARG: process io command failed because of some invalid argument ESP_FAIL: process io command failed because some other error occurred ESP_ERR_NOT_SUPPORTED: requested feature is not supported esp_err_t (*del)(esp_eth_phy_t *phy) Free memory of Ethernet PHY instance. Param phy [in] Ethernet PHY instance Return ESP_OK: free PHY instance successfully ESP_FAIL: free PHY instance failed because some error occurred ESP_OK: free PHY instance successfully ESP_FAIL: free PHY instance failed because some error occurred ESP_OK: free PHY instance successfully Param phy [in] Ethernet PHY instance Return ESP_OK: free PHY instance successfully ESP_FAIL: free PHY instance failed because some error occurred esp_err_t (*del)(esp_eth_phy_t *phy) Free memory of Ethernet PHY instance. Param phy [in] Ethernet PHY instance Return ESP_OK: free PHY instance successfully ESP_FAIL: free PHY instance failed because some error occurred esp_err_t (*set_mediator)(esp_eth_phy_t *phy, esp_eth_mediator_t *mediator) struct eth_phy_config_t Ethernet PHY configuration. Public Members int32_t phy_addr PHY address, set -1 to enable PHY address detection at initialization stage int32_t phy_addr PHY address, set -1 to enable PHY address detection at initialization stage uint32_t reset_timeout_ms Reset timeout value (Unit: ms) uint32_t reset_timeout_ms Reset timeout value (Unit: ms) uint32_t autonego_timeout_ms Auto-negotiation timeout value (Unit: ms) uint32_t autonego_timeout_ms Auto-negotiation timeout value (Unit: ms) int reset_gpio_num Reset GPIO number, -1 means no hardware reset int reset_gpio_num Reset GPIO number, -1 means no hardware reset int32_t phy_addr Macros ESP_ETH_PHY_ADDR_AUTO ETH_PHY_DEFAULT_CONFIG() Default configuration for Ethernet PHY object. Type Definitions typedef struct esp_eth_phy_s esp_eth_phy_t Ethernet PHY. Enumerations Header File This header file can be included with: #include "esp_eth_phy_802_3.h" This header file is a part of the API provided by the esp_eth component. To declare that your component depends on esp_eth , add the following to your CMakeLists.txt: REQUIRES esp_eth or PRIV_REQUIRES esp_eth Functions esp_err_t esp_eth_phy_802_3_set_mediator(phy_802_3_t *phy_802_3, esp_eth_mediator_t *eth) Set Ethernet mediator. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure eth -- Ethernet mediator pointer phy_802_3 -- IEEE 802.3 PHY object infostructure eth -- Ethernet mediator pointer phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethermet mediator set successfuly ESP_ERR_INVALID_ARG: if eth is NULL ESP_OK: Ethermet mediator set successfuly ESP_ERR_INVALID_ARG: if eth is NULL ESP_OK: Ethermet mediator set successfuly Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure eth -- Ethernet mediator pointer Returns ESP_OK: Ethermet mediator set successfuly ESP_ERR_INVALID_ARG: if eth is NULL esp_err_t esp_eth_phy_802_3_reset(phy_802_3_t *phy_802_3) Reset PHY. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethernet PHY reset successfuly ESP_FAIL: reset Ethernet PHY failed because some error occured ESP_OK: Ethernet PHY reset successfuly ESP_FAIL: reset Ethernet PHY failed because some error occured ESP_OK: Ethernet PHY reset successfuly Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethernet PHY reset successfuly ESP_FAIL: reset Ethernet PHY failed because some error occured esp_err_t esp_eth_phy_802_3_autonego_ctrl(phy_802_3_t *phy_802_3, eth_phy_autoneg_cmd_t cmd, bool *autonego_en_stat) Control autonegotiation mode of Ethernet PHY. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure cmd -- autonegotiation command enumeration autonego_en_stat -- [out] autonegotiation enabled flag phy_802_3 -- IEEE 802.3 PHY object infostructure cmd -- autonegotiation command enumeration autonego_en_stat -- [out] autonegotiation enabled flag phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethernet PHY autonegotiation configured successfuly ESP_FAIL: Ethernet PHY autonegotiation configuration fail because some error occured ESP_ERR_INVALID_ARG: invalid value of cmd ESP_OK: Ethernet PHY autonegotiation configured successfuly ESP_FAIL: Ethernet PHY autonegotiation configuration fail because some error occured ESP_ERR_INVALID_ARG: invalid value of cmd ESP_OK: Ethernet PHY autonegotiation configured successfuly Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure cmd -- autonegotiation command enumeration autonego_en_stat -- [out] autonegotiation enabled flag Returns ESP_OK: Ethernet PHY autonegotiation configured successfuly ESP_FAIL: Ethernet PHY autonegotiation configuration fail because some error occured ESP_ERR_INVALID_ARG: invalid value of cmd esp_err_t esp_eth_phy_802_3_pwrctl(phy_802_3_t *phy_802_3, bool enable) Power control of Ethernet PHY. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure enable -- set true to power ON Ethernet PHY; set false to power OFF Ethernet PHY phy_802_3 -- IEEE 802.3 PHY object infostructure enable -- set true to power ON Ethernet PHY; set false to power OFF Ethernet PHY phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethernet PHY power down mode set successfuly ESP_FAIL: Ethernet PHY power up or power down failed because some error occured ESP_OK: Ethernet PHY power down mode set successfuly ESP_FAIL: Ethernet PHY power up or power down failed because some error occured ESP_OK: Ethernet PHY power down mode set successfuly Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure enable -- set true to power ON Ethernet PHY; set false to power OFF Ethernet PHY Returns ESP_OK: Ethernet PHY power down mode set successfuly ESP_FAIL: Ethernet PHY power up or power down failed because some error occured esp_err_t esp_eth_phy_802_3_set_addr(phy_802_3_t *phy_802_3, uint32_t addr) Set Ethernet PHY address. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure addr -- new PHY address phy_802_3 -- IEEE 802.3 PHY object infostructure addr -- new PHY address phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethernet PHY address set ESP_OK: Ethernet PHY address set ESP_OK: Ethernet PHY address set Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure addr -- new PHY address Returns ESP_OK: Ethernet PHY address set esp_err_t esp_eth_phy_802_3_get_addr(phy_802_3_t *phy_802_3, uint32_t *addr) Get Ethernet PHY address. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure addr -- [out] Ethernet PHY address phy_802_3 -- IEEE 802.3 PHY object infostructure addr -- [out] Ethernet PHY address phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethernet PHY address read successfuly ESP_ERR_INVALID_ARG: addr pointer is NULL ESP_OK: Ethernet PHY address read successfuly ESP_ERR_INVALID_ARG: addr pointer is NULL ESP_OK: Ethernet PHY address read successfuly Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure addr -- [out] Ethernet PHY address Returns ESP_OK: Ethernet PHY address read successfuly ESP_ERR_INVALID_ARG: addr pointer is NULL esp_err_t esp_eth_phy_802_3_advertise_pause_ability(phy_802_3_t *phy_802_3, uint32_t ability) Advertise pause function ability. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure ability -- enable or disable pause ability phy_802_3 -- IEEE 802.3 PHY object infostructure ability -- enable or disable pause ability phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: pause ability set successfuly ESP_FAIL: Advertise pause function ability failed because some error occured ESP_OK: pause ability set successfuly ESP_FAIL: Advertise pause function ability failed because some error occured ESP_OK: pause ability set successfuly Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure ability -- enable or disable pause ability Returns ESP_OK: pause ability set successfuly ESP_FAIL: Advertise pause function ability failed because some error occured esp_err_t esp_eth_phy_802_3_loopback(phy_802_3_t *phy_802_3, bool enable) Set Ethernet PHY loopback mode. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure enable -- set true to enable loopback; set false to disable loopback phy_802_3 -- IEEE 802.3 PHY object infostructure enable -- set true to enable loopback; set false to disable loopback phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethernet PHY loopback mode set successfuly ESP_FAIL: Ethernet PHY loopback configuration failed because some error occured ESP_OK: Ethernet PHY loopback mode set successfuly ESP_FAIL: Ethernet PHY loopback configuration failed because some error occured ESP_OK: Ethernet PHY loopback mode set successfuly Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure enable -- set true to enable loopback; set false to disable loopback Returns ESP_OK: Ethernet PHY loopback mode set successfuly ESP_FAIL: Ethernet PHY loopback configuration failed because some error occured esp_err_t esp_eth_phy_802_3_set_speed(phy_802_3_t *phy_802_3, eth_speed_t speed) Set Ethernet PHY speed. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure speed -- new speed of Ethernet PHY link phy_802_3 -- IEEE 802.3 PHY object infostructure speed -- new speed of Ethernet PHY link phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethernet PHY speed set successfuly ESP_FAIL: Set Ethernet PHY speed failed because some error occured ESP_OK: Ethernet PHY speed set successfuly ESP_FAIL: Set Ethernet PHY speed failed because some error occured ESP_OK: Ethernet PHY speed set successfuly Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure speed -- new speed of Ethernet PHY link Returns ESP_OK: Ethernet PHY speed set successfuly ESP_FAIL: Set Ethernet PHY speed failed because some error occured esp_err_t esp_eth_phy_802_3_set_duplex(phy_802_3_t *phy_802_3, eth_duplex_t duplex) Set Ethernet PHY duplex mode. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure duplex -- new duplex mode for Ethernet PHY link phy_802_3 -- IEEE 802.3 PHY object infostructure duplex -- new duplex mode for Ethernet PHY link phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethernet PHY duplex mode set successfuly ESP_ERR_INVALID_STATE: unable to set duplex mode to Half if loopback is enabled ESP_FAIL: Set Ethernet PHY duplex mode failed because some error occured ESP_OK: Ethernet PHY duplex mode set successfuly ESP_ERR_INVALID_STATE: unable to set duplex mode to Half if loopback is enabled ESP_FAIL: Set Ethernet PHY duplex mode failed because some error occured ESP_OK: Ethernet PHY duplex mode set successfuly Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure duplex -- new duplex mode for Ethernet PHY link Returns ESP_OK: Ethernet PHY duplex mode set successfuly ESP_ERR_INVALID_STATE: unable to set duplex mode to Half if loopback is enabled ESP_FAIL: Set Ethernet PHY duplex mode failed because some error occured esp_err_t esp_eth_phy_802_3_init(phy_802_3_t *phy_802_3) Initialize Ethernet PHY. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethernet PHY initialized successfuly ESP_OK: Ethernet PHY initialized successfuly ESP_OK: Ethernet PHY initialized successfuly Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethernet PHY initialized successfuly esp_err_t esp_eth_phy_802_3_deinit(phy_802_3_t *phy_802_3) Power off Eternet PHY. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethernet PHY powered off successfuly ESP_OK: Ethernet PHY powered off successfuly ESP_OK: Ethernet PHY powered off successfuly Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethernet PHY powered off successfuly esp_err_t esp_eth_phy_802_3_del(phy_802_3_t *phy_802_3) Delete Ethernet PHY infostructure. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethrnet PHY infostructure deleted ESP_OK: Ethrnet PHY infostructure deleted ESP_OK: Ethrnet PHY infostructure deleted Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Ethrnet PHY infostructure deleted esp_err_t esp_eth_phy_802_3_reset_hw(phy_802_3_t *phy_802_3, uint32_t reset_assert_us) Performs hardware reset with specific reset pin assertion time. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure reset_assert_us -- Hardware reset pin assertion time phy_802_3 -- IEEE 802.3 PHY object infostructure reset_assert_us -- Hardware reset pin assertion time phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: reset Ethernet PHY successfully ESP_OK: reset Ethernet PHY successfully ESP_OK: reset Ethernet PHY successfully Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure reset_assert_us -- Hardware reset pin assertion time Returns ESP_OK: reset Ethernet PHY successfully esp_err_t esp_eth_phy_802_3_detect_phy_addr(esp_eth_mediator_t *eth, int *detected_addr) Detect PHY address. Parameters eth -- Mediator of Ethernet driver detected_addr -- [out] a valid address after detection eth -- Mediator of Ethernet driver detected_addr -- [out] a valid address after detection eth -- Mediator of Ethernet driver Returns ESP_OK: detect phy address successfully ESP_ERR_INVALID_ARG: invalid parameter ESP_ERR_NOT_FOUND: can't detect any PHY device ESP_FAIL: detect phy address failed because some error occurred ESP_OK: detect phy address successfully ESP_ERR_INVALID_ARG: invalid parameter ESP_ERR_NOT_FOUND: can't detect any PHY device ESP_FAIL: detect phy address failed because some error occurred ESP_OK: detect phy address successfully Parameters eth -- Mediator of Ethernet driver detected_addr -- [out] a valid address after detection Returns ESP_OK: detect phy address successfully ESP_ERR_INVALID_ARG: invalid parameter ESP_ERR_NOT_FOUND: can't detect any PHY device ESP_FAIL: detect phy address failed because some error occurred esp_err_t esp_eth_phy_802_3_basic_phy_init(phy_802_3_t *phy_802_3) Performs basic PHY chip initialization. Note It should be called as the first function in PHY specific driver instance Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: initialized Ethernet PHY successfully ESP_FAIL: initialization of Ethernet PHY failed because some error occurred ESP_ERR_INVALID_ARG: invalid argument ESP_ERR_NOT_FOUND: PHY device not detected ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation ESP_OK: initialized Ethernet PHY successfully ESP_FAIL: initialization of Ethernet PHY failed because some error occurred ESP_ERR_INVALID_ARG: invalid argument ESP_ERR_NOT_FOUND: PHY device not detected ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation ESP_OK: initialized Ethernet PHY successfully Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: initialized Ethernet PHY successfully ESP_FAIL: initialization of Ethernet PHY failed because some error occurred ESP_ERR_INVALID_ARG: invalid argument ESP_ERR_NOT_FOUND: PHY device not detected ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation esp_err_t esp_eth_phy_802_3_basic_phy_deinit(phy_802_3_t *phy_802_3) Performs basic PHY chip de-initialization. Note It should be called as the last function in PHY specific driver instance Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: de-initialized Ethernet PHY successfully ESP_FAIL: de-initialization of Ethernet PHY failed because some error occurred ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation ESP_OK: de-initialized Ethernet PHY successfully ESP_FAIL: de-initialization of Ethernet PHY failed because some error occurred ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation ESP_OK: de-initialized Ethernet PHY successfully Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: de-initialized Ethernet PHY successfully ESP_FAIL: de-initialization of Ethernet PHY failed because some error occurred ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation esp_err_t esp_eth_phy_802_3_read_oui(phy_802_3_t *phy_802_3, uint32_t *oui) Reads raw content of OUI field. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure oui -- [out] OUI value phy_802_3 -- IEEE 802.3 PHY object infostructure oui -- [out] OUI value phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: OUI field read successfully ESP_FAIL: OUI field read failed because some error occurred ESP_ERR_INVALID_ARG: invalid oui argument ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation ESP_OK: OUI field read successfully ESP_FAIL: OUI field read failed because some error occurred ESP_ERR_INVALID_ARG: invalid oui argument ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation ESP_OK: OUI field read successfully Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure oui -- [out] OUI value Returns ESP_OK: OUI field read successfully ESP_FAIL: OUI field read failed because some error occurred ESP_ERR_INVALID_ARG: invalid oui argument ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation esp_err_t esp_eth_phy_802_3_read_manufac_info(phy_802_3_t *phy_802_3, uint8_t *model, uint8_t *rev) Reads manufacturer’s model and revision number. Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure model -- [out] Manufacturer’s model number (can be NULL when not required) rev -- [out] Manufacturer’s revision number (can be NULL when not required) phy_802_3 -- IEEE 802.3 PHY object infostructure model -- [out] Manufacturer’s model number (can be NULL when not required) rev -- [out] Manufacturer’s revision number (can be NULL when not required) phy_802_3 -- IEEE 802.3 PHY object infostructure Returns ESP_OK: Manufacturer’s info read successfully ESP_FAIL: Manufacturer’s info read failed because some error occurred ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation ESP_OK: Manufacturer’s info read successfully ESP_FAIL: Manufacturer’s info read failed because some error occurred ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation ESP_OK: Manufacturer’s info read successfully Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure model -- [out] Manufacturer’s model number (can be NULL when not required) rev -- [out] Manufacturer’s revision number (can be NULL when not required) Returns ESP_OK: Manufacturer’s info read successfully ESP_FAIL: Manufacturer’s info read failed because some error occurred ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation inline phy_802_3_t *esp_eth_phy_into_phy_802_3(esp_eth_phy_t *phy) Returns address to parent IEEE 802.3 PHY object infostructure. Parameters phy -- Ethernet PHY instance Returns phy_802_3_t* address to parent IEEE 802.3 PHY object infostructure address to parent IEEE 802.3 PHY object infostructure address to parent IEEE 802.3 PHY object infostructure Parameters phy -- Ethernet PHY instance Returns phy_802_3_t* address to parent IEEE 802.3 PHY object infostructure esp_err_t esp_eth_phy_802_3_obj_config_init(phy_802_3_t *phy_802_3, const eth_phy_config_t *config) Initializes configuration of parent IEEE 802.3 PHY object infostructure. Parameters phy_802_3 -- Address to IEEE 802.3 PHY object infostructure config -- Configuration of the IEEE 802.3 PHY object phy_802_3 -- Address to IEEE 802.3 PHY object infostructure config -- Configuration of the IEEE 802.3 PHY object phy_802_3 -- Address to IEEE 802.3 PHY object infostructure Returns ESP_OK: configuration initialized successfully ESP_ERR_INVALID_ARG: invalid config argument ESP_OK: configuration initialized successfully ESP_ERR_INVALID_ARG: invalid config argument ESP_OK: configuration initialized successfully Parameters phy_802_3 -- Address to IEEE 802.3 PHY object infostructure config -- Configuration of the IEEE 802.3 PHY object Returns ESP_OK: configuration initialized successfully ESP_ERR_INVALID_ARG: invalid config argument Structures struct phy_802_3_t IEEE 802.3 PHY object infostructure. Public Members esp_eth_phy_t parent Parent Ethernet PHY instance esp_eth_phy_t parent Parent Ethernet PHY instance esp_eth_mediator_t *eth Mediator of Ethernet driver esp_eth_mediator_t *eth Mediator of Ethernet driver int addr PHY address int addr PHY address uint32_t reset_timeout_ms Reset timeout value (Unit: ms) uint32_t reset_timeout_ms Reset timeout value (Unit: ms) uint32_t autonego_timeout_ms Auto-negotiation timeout value (Unit: ms) uint32_t autonego_timeout_ms Auto-negotiation timeout value (Unit: ms) eth_link_t link_status Current Link status eth_link_t link_status Current Link status int reset_gpio_num Reset GPIO number, -1 means no hardware reset int reset_gpio_num Reset GPIO number, -1 means no hardware reset esp_eth_phy_t parent Header File This header file can be included with: #include "esp_eth_netif_glue.h" This header file is a part of the API provided by the esp_eth component. To declare that your component depends on esp_eth , add the following to your CMakeLists.txt: REQUIRES esp_eth or PRIV_REQUIRES esp_eth Functions esp_eth_netif_glue_handle_t esp_eth_new_netif_glue(esp_eth_handle_t eth_hdl) Create a netif glue for Ethernet driver. Note netif glue is used to attach io driver to TCP/IP netif Parameters eth_hdl -- Ethernet driver handle Returns glue object, which inherits esp_netif_driver_base_t Parameters eth_hdl -- Ethernet driver handle Returns glue object, which inherits esp_netif_driver_base_t esp_err_t esp_eth_del_netif_glue(esp_eth_netif_glue_handle_t eth_netif_glue) Delete netif glue of Ethernet driver. Parameters eth_netif_glue -- netif glue Returns -ESP_OK: delete netif glue successfully Parameters eth_netif_glue -- netif glue Returns -ESP_OK: delete netif glue successfully Type Definitions typedef struct esp_eth_netif_glue_t *esp_eth_netif_glue_handle_t Handle of netif glue - an intermediate layer between netif and Ethernet driver.
Ethernet Overview ESP-IDF provides a set of consistent and flexible APIs to support both internal Ethernet MAC (EMAC) controller and external SPI-Ethernet modules. This programming guide is split into the following sections: Basic Ethernet Concepts Ethernet is an asynchronous Carrier Sense Multiple Access with Collision Detect (CSMA/CD) protocol/interface. It is generally not well suited for low-power applications. However, with ubiquitous deployment, internet connectivity, high data rates, and limitless-range expandability, Ethernet can accommodate nearly all wired communications. Normal IEEE 802.3 compliant Ethernet frames are between 64 and 1518 bytes in length. They are made up of five or six different fields: a destination MAC address (DA), a source MAC address (SA), a type/length field, a data payload, an optional padding field and a Cyclic Redundancy Check (CRC). Additionally, when transmitted on the Ethernet medium, a 7-byte preamble field and Start-of-Frame (SOF) delimiter byte are appended to the beginning of the Ethernet packet. Thus the traffic on the twist-pair cabling appears as shown below: Preamble and Start-of-Frame Delimiter The preamble contains seven bytes of 55H. It allows the receiver to lock onto the stream of data before the actual frame arrives. The Start-of-Frame Delimiter (SFD) is a binary sequence 10101011 (as seen on the physical medium). It is sometimes considered to be part of the preamble. When transmitting and receiving data, the preamble and SFD bytes will be automatically generated or stripped from the packets. Destination Address The destination address field contains a 6-byte length MAC address of the device that the packet is directed to. If the Least Significant bit in the first byte of the MAC address is set, the address is a multicast destination. For example, 01-00-00-00-F0-00 and 33-45-67-89-AB-CD are multi-cast addresses, while 00-00-00-00-F0-00 and 32-45-67-89-AB-CD are not. Packets with multi-cast destination addresses are designed to arrive and be important to a selected group of Ethernet nodes. If the destination address field is the reserved multicast address, i.e., FF-FF-FF-FF-FF-FF, the packet is a broadcast packet and it will be directed to everyone sharing the network. If the Least Significant bit in the first byte of the MAC address is clear, the address is a unicast address and will be designed for usage by only the addressed node. Normally the EMAC controller incorporates receive filters which can be used to discard or accept packets with multi-cast, broadcast and/or unicast destination addresses. When transmitting packets, the host controller is responsible for writing the desired destination address into the transmit buffer. Source Address The source address field contains a 6-byte length MAC address of the node which created the Ethernet packet. Users of Ethernet must generate a unique MAC address for each controller used. MAC addresses consist of two portions. The first three bytes are known as the Organizationally Unique Identifier (OUI). OUIs are distributed by the IEEE. The last three bytes are address bytes at the discretion of the company that purchased the OUI. For more information about MAC Address used in ESP-IDF, please see MAC Address Allocation. When transmitting packets, the assigned source MAC address must be written into the transmit buffer by the host controller. Type/Length The type/length field is a 2-byte field. If the value in this field is <= 1500 (decimal), it is considered a length field and it specifies the amount of non-padding data which follows in the data field. If the value is >= 1536, it represents the protocol the following packet data belongs to. The followings are the most common type values: - IPv4 = 0800H - IPv6 = 86DDH - ARP = 0806H Users implementing proprietary networks may choose to treat this field as a length field, while applications implementing protocols such as the Internet Protocol (IP) or Address Resolution Protocol (ARP), should program this field with the appropriate type defined by the protocol's specification when transmitting packets. Payload The payload field is a variable length field, anywhere from 0 to 1500 bytes. Larger data packets violates Ethernet standards and will be dropped by most Ethernet nodes. This field contains the client data, such as an IP datagram. Padding and FCS The padding field is a variable length field added to meet the IEEE 802.3 specification requirements when small data payloads are used. The DA, SA, type, payload, and padding of an Ethernet packet must be no smaller than 60 bytes in total. If the required 4-byte FCS field is added, packets must be no smaller than 64 bytes. If the payload field is less than 46-byte long, a padding field is required. The FCS field is a 4-byte field that contains an industry-standard 32-bit CRC calculated with the data from the DA, SA, type, payload, and padding fields. Given the complexity of calculating a CRC, the hardware normally automatically generates a valid CRC and transmit it. Otherwise, the host controller must generate the CRC and place it in the transmit buffer. Normally, the host controller does not need to concern itself with padding and the CRC which the hardware EMAC will also be able to automatically generate when transmitting and verify when receiving. However, the padding and CRC fields will be written into the receive buffer when packets arrive, so they may be evaluated by the host controller if needed. Note Besides the basic data frame described above, there are two other common frame types in 10/100 Mbps Ethernet: control frames and VLAN-tagged frames. They are not supported in ESP-IDF. Configure MAC and PHY The Ethernet driver is composed of two parts: MAC and PHY. The communication between MAC and PHY can have diverse choices: MII (Media Independent Interface), RMII (Reduced Media Independent Interface), etc. One of the obvious differences between MII and RMII is signal consumption. MII usually costs up to 18 signals, while the RMII interface can reduce the consumption to 9. In RMII mode, both the receiver and transmitter signals are referenced to the REF_CLK. REF_CLK must be stable during any access to PHY and MAC. Generally, there are three ways to generate the REF_CLK depending on the PHY device in your design: Some PHY chips can derive the REF_CLKfrom its externally connected 25 MHz crystal oscillator (as seen the option a in the picture). In this case, you should select CONFIG_ETH_RMII_CLK_INPUTin CONFIG_ETH_RMII_CLK_MODE. Some PHY chip uses an externally connected 50MHz crystal oscillator or other clock sources, which can also be used as the REF_CLKfor the MAC side (as seen the option b in the picture). In this case, you still need to select CONFIG_ETH_RMII_CLK_INPUTin CONFIG_ETH_RMII_CLK_MODE. Some EMAC controllers can generate the REF_CLKusing an internal high-precision PLL (as seen the option c in the picture). In this case, you should select CONFIG_ETH_RMII_CLK_OUTPUTin CONFIG_ETH_RMII_CLK_MODE. Note REF_CLK is configured via Project Configuration as described above by default. However, it can be overwritten from user application code by appropriately setting eth_esp32_emac_config_t::interface and eth_esp32_emac_config_t::clock_config members. See emac_rmii_clock_mode_t and emac_rmii_clock_gpio_t for more details. Warning If the RMII clock mode is selected to CONFIG_ETH_RMII_CLK_OUTPUT, then GPIO0 can be used to output the REF_CLK signal. See CONFIG_ETH_RMII_CLK_OUTPUT_GPIO0 for more information. What is more, if you are not using PSRAM in your design, GPIO16 and GPIO17 are also available to output the reference clock. See CONFIG_ETH_RMII_CLK_OUT_GPIO for more information. If the RMII clock mode is selected to CONFIG_ETH_RMII_CLK_INPUT, then GPIO0 is the only choice to input the REF_CLK signal. Please note that GPIO0 is also an important strapping GPIO on ESP32. If GPIO0 samples a low level during power-up, ESP32 will go into download mode. The system will get halted until a manually reset. The workaround for this issue is disabling the REF_CLK in hardware by default so that the strapping pin is not interfered by other signals in the boot stage. Then, re-enable the REF_CLK in the Ethernet driver installation stage. The ways to disable the REF_CLK signal can be: Disable or power down the crystal oscillator (as the case b in the picture). Force the PHY device to reset status (as the case a in the picture). This could fail for some PHY device (i.e., it still outputs signals to GPIO0 even in reset state). No matter which RMII clock mode you select, you really need to take care of the signal integrity of REF_CLK in your hardware design! Keep the trace as short as possible. Keep it away from RF devices and inductor elements. Note ESP-IDF only supports the RMII interface (i.e., always select CONFIG_ETH_PHY_INTERFACE_RMII in the Kconfig option CONFIG_ETH_PHY_INTERFACE). Signals used in the data plane are fixed to specific GPIOs via MUX, they can not be modified to other GPIOs. Signals used in the control plane can be routed to any free GPIOs via Matrix. Please refer to ESP32-Ethernet-Kit for hardware design example. You need to set up the necessary parameters for MAC and PHY respectively based on your Ethernet board design, and then combine the two together to complete the driver installation. Configuration for MAC is described in eth_mac_config_t, including: eth_mac_config_t::sw_reset_timeout_ms: software reset timeout value, in milliseconds. Typically, MAC reset should be finished within 100 ms. eth_mac_config_t::rx_task_stack_sizeand eth_mac_config_t::rx_task_prio: the MAC driver creates a dedicated task to process incoming packets. These two parameters are used to set the stack size and priority of the task. eth_mac_config_t::flags: specifying extra features that the MAC driver should have, it could be useful in some special situations. The value of this field can be OR'd with macros prefixed with ETH_MAC_FLAG_. For example, if the MAC driver should work when the cache is disabled, then you should configure this field with ETH_MAC_FLAG_WORK_WITH_CACHE_DISABLE. eth_esp32_emac_config_t::smi_mdc_gpio_numand eth_esp32_emac_config_t::smi_mdio_gpio_num: the GPIO number used to connect the SMI signals. eth_esp32_emac_config_t::interface: configuration of MAC Data interface to PHY (MII/RMII). eth_esp32_emac_config_t::clock_config: configuration of EMAC Interface clock ( REF_CLKmode and GPIO number in case of RMII). Configuration for PHY is described in eth_phy_config_t, including: eth_phy_config_t::phy_addr: multiple PHY devices can share the same SMI bus, so each PHY needs a unique address. Usually, this address is configured during hardware design by pulling up/down some PHY strapping pins. You can set the value from 0to 15based on your Ethernet board. Especially, if the SMI bus is shared by only one PHY device, setting this value to -1can enable the driver to detect the PHY address automatically. eth_phy_config_t::reset_timeout_ms: reset timeout value, in milliseconds. Typically, PHY reset should be finished within 100 ms. eth_phy_config_t::autonego_timeout_ms: auto-negotiation timeout value, in milliseconds. The Ethernet driver starts negotiation with the peer Ethernet node automatically, to determine to duplex and speed mode. This value usually depends on the ability of the PHY device on your board. eth_phy_config_t::reset_gpio_num: if your board also connects the PHY reset pin to one of the GPIO, then set it here. Otherwise, set this field to -1. ESP-IDF provides a default configuration for MAC and PHY in macro ETH_MAC_DEFAULT_CONFIG and ETH_PHY_DEFAULT_CONFIG. Create MAC and PHY Instance The Ethernet driver is implemented in an Object-Oriented style. Any operation on MAC and PHY should be based on the instance of the two. Internal EMAC + External PHY eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG(); // apply default common MAC configuration eth_esp32_emac_config_t esp32_emac_config = ETH_ESP32_EMAC_DEFAULT_CONFIG(); // apply default vendor-specific MAC configuration esp32_emac_config.smi_mdc_gpio_num = CONFIG_EXAMPLE_ETH_MDC_GPIO; // alter the GPIO used for MDC signal esp32_emac_config.smi_mdio_gpio_num = CONFIG_EXAMPLE_ETH_MDIO_GPIO; // alter the GPIO used for MDIO signal esp_eth_mac_t *mac = esp_eth_mac_new_esp32(&esp32_emac_config, &mac_config); // create MAC instance eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG(); // apply default PHY configuration phy_config.phy_addr = CONFIG_EXAMPLE_ETH_PHY_ADDR; // alter the PHY address according to your board design phy_config.reset_gpio_num = CONFIG_EXAMPLE_ETH_PHY_RST_GPIO; // alter the GPIO used for PHY reset esp_eth_phy_t *phy = esp_eth_phy_new_ip101(&phy_config); // create PHY instance // ESP-IDF officially supports several different Ethernet PHY chip driver // esp_eth_phy_t *phy = esp_eth_phy_new_rtl8201(&phy_config); // esp_eth_phy_t *phy = esp_eth_phy_new_lan8720(&phy_config); // esp_eth_phy_t *phy = esp_eth_phy_new_dp83848(&phy_config); Optional Runtime MAC Clock Configuration EMAC REF_CLK can be optionally configured from the user application code. eth_esp32_emac_config_t esp32_emac_config = ETH_ESP32_EMAC_DEFAULT_CONFIG(); // apply default vendor-specific MAC configuration // ... esp32_emac_config.interface = EMAC_DATA_INTERFACE_RMII; // alter EMAC Data Interface esp32_emac_config.clock_config.rmii.clock_mode = EMAC_CLK_OUT; // select EMAC REF_CLK mode esp32_emac_config.clock_config.rmii.clock_gpio = EMAC_CLK_OUT_GPIO; // select GPIO number used to input/output EMAC REF_CLK esp_eth_mac_t *mac = esp_eth_mac_new_esp32(&esp32_emac_config, &mac_config); // create MAC instance SPI-Ethernet Module eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG(); // apply default common MAC configuration eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG(); // apply default PHY configuration phy_config.phy_addr = CONFIG_EXAMPLE_ETH_PHY_ADDR; // alter the PHY address according to your board design phy_config.reset_gpio_num = CONFIG_EXAMPLE_ETH_PHY_RST_GPIO; // alter the GPIO used for PHY reset // Install GPIO interrupt service (as the SPI-Ethernet module is interrupt-driven) gpio_install_isr_service(0); // SPI bus configuration spi_device_handle_t spi_handle = NULL; spi_bus_config_t buscfg = { .miso_io_num = CONFIG_EXAMPLE_ETH_SPI_MISO_GPIO, .mosi_io_num = CONFIG_EXAMPLE_ETH_SPI_MOSI_GPIO, .sclk_io_num = CONFIG_EXAMPLE_ETH_SPI_SCLK_GPIO, .quadwp_io_num = -1, .quadhd_io_num = -1, }; ESP_ERROR_CHECK(spi_bus_initialize(CONFIG_EXAMPLE_ETH_SPI_HOST, &buscfg, 1)); // Configure SPI device spi_device_interface_config_t spi_devcfg = { .mode = 0, .clock_speed_hz = CONFIG_EXAMPLE_ETH_SPI_CLOCK_MHZ * 1000 * 1000, .spics_io_num = CONFIG_EXAMPLE_ETH_SPI_CS_GPIO, .queue_size = 20 }; /* dm9051 ethernet driver is based on spi driver */ eth_dm9051_config_t dm9051_config = ETH_DM9051_DEFAULT_CONFIG(CONFIG_EXAMPLE_ETH_SPI_HOST, &spi_devcfg); dm9051_config.int_gpio_num = CONFIG_EXAMPLE_ETH_SPI_INT_GPIO; esp_eth_mac_t *mac = esp_eth_mac_new_dm9051(&dm9051_config, &mac_config); esp_eth_phy_t *phy = esp_eth_phy_new_dm9051(&phy_config); Note When creating MAC and PHY instances for SPI-Ethernet modules (e.g., DM9051), the constructor function must have the same suffix (e.g., esp_eth_mac_new_dm9051 and esp_eth_phy_new_dm9051). This is because we don not have other choices but the integrated PHY. The SPI device configuration (i.e., spi_device_interface_config_t) may slightly differ for other Ethernet modules or to meet SPI timing on specific PCB. Please check out your module's specs and the examples in ESP-IDF. Install Driver To install the Ethernet driver, we need to combine the instance of MAC and PHY and set some additional high-level configurations (i.e., not specific to either MAC or PHY) in esp_eth_config_t: esp_eth_config_t::mac: instance that created from MAC generator (e.g., esp_eth_mac_new_esp32()). esp_eth_config_t::phy: instance that created from PHY generator (e.g., esp_eth_phy_new_ip101()). esp_eth_config_t::check_link_period_ms: Ethernet driver starts an OS timer to check the link status periodically, this field is used to set the interval, in milliseconds. esp_eth_config_t::stack_input: In most Ethernet IoT applications, any Ethernet frame received by a driver should be passed to the upper layer (e.g., TCP/IP stack). This field is set to a function that is responsible to deal with the incoming frames. You can even update this field at runtime via function esp_eth_update_input_path()after driver installation. esp_eth_config_t::on_lowlevel_init_doneand esp_eth_config_t::on_lowlevel_deinit_done: These two fields are used to specify the hooks which get invoked when low-level hardware has been initialized or de-initialized. ESP-IDF provides a default configuration for driver installation in macro ETH_DEFAULT_CONFIG. esp_eth_config_t config = ETH_DEFAULT_CONFIG(mac, phy); // apply default driver configuration esp_eth_handle_t eth_handle = NULL; // after the driver is installed, we will get the handle of the driver esp_eth_driver_install(&config, ð_handle); // install driver The Ethernet driver also includes an event-driven model, which sends useful and important events to user space. We need to initialize the event loop before installing the Ethernet driver. For more information about event-driven programming, please refer to ESP Event. /** Event handler for Ethernet events */ static void eth_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { uint8_t mac_addr[6] = {0}; /* we can get the ethernet driver handle from event data */ esp_eth_handle_t eth_handle = *(esp_eth_handle_t *)event_data; switch (event_id) { case ETHERNET_EVENT_CONNECTED: esp_eth_ioctl(eth_handle, ETH_CMD_G_MAC_ADDR, mac_addr); ESP_LOGI(TAG, "Ethernet Link Up"); ESP_LOGI(TAG, "Ethernet HW Addr %02x:%02x:%02x:%02x:%02x:%02x", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); break; case ETHERNET_EVENT_DISCONNECTED: ESP_LOGI(TAG, "Ethernet Link Down"); break; case ETHERNET_EVENT_START: ESP_LOGI(TAG, "Ethernet Started"); break; case ETHERNET_EVENT_STOP: ESP_LOGI(TAG, "Ethernet Stopped"); break; default: break; } } esp_event_loop_create_default(); // create a default event loop that runs in the background esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, ð_event_handler, NULL); // register Ethernet event handler (to deal with user-specific stuff when events like link up/down happened) Start Ethernet Driver After driver installation, we can start Ethernet immediately. esp_eth_start(eth_handle); // start Ethernet driver state machine Connect Driver to TCP/IP Stack Up until now, we have installed the Ethernet driver. From the view of OSI (Open System Interconnection), we are still on level 2 (i.e., Data Link Layer). While we can detect link up and down events and gain MAC address in user space, it is infeasible to obtain the IP address, let alone send an HTTP request. The TCP/IP stack used in ESP-IDF is called LwIP. For more information about it, please refer to LwIP. To connect the Ethernet driver to TCP/IP stack, follow these three steps: Create a network interface for the Ethernet driver Attach the network interface to the Ethernet driver Register IP event handlers For more information about the network interface, please refer to Network Interface. /** Event handler for IP_EVENT_ETH_GOT_IP */ static void got_ip_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { ip_event_got_ip_t *event = (ip_event_got_ip_t *) event_data; const esp_netif_ip_info_t *ip_info = &event->ip_info; ESP_LOGI(TAG, "Ethernet Got IP Address"); ESP_LOGI(TAG, "~~~~~~~~~~~"); ESP_LOGI(TAG, "ETHIP:" IPSTR, IP2STR(&ip_info->ip)); ESP_LOGI(TAG, "ETHMASK:" IPSTR, IP2STR(&ip_info->netmask)); ESP_LOGI(TAG, "ETHGW:" IPSTR, IP2STR(&ip_info->gw)); ESP_LOGI(TAG, "~~~~~~~~~~~"); } esp_netif_init()); // Initialize TCP/IP network interface (should be called only once in application) esp_netif_config_t cfg = ESP_NETIF_DEFAULT_ETH(); // apply default network interface configuration for Ethernet esp_netif_t *eth_netif = esp_netif_new(&cfg); // create network interface for Ethernet driver esp_netif_attach(eth_netif, esp_eth_new_netif_glue(eth_handle)); // attach Ethernet driver to TCP/IP stack esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &got_ip_event_handler, NULL); // register user defined IP event handlers esp_eth_start(eth_handle); // start Ethernet driver state machine Warning It is recommended to fully initialize the Ethernet driver and network interface before registering the user's Ethernet/IP event handlers, i.e., register the event handlers as the last thing prior to starting the Ethernet driver. Such an approach ensures that Ethernet/IP events get executed first by the Ethernet driver or network interface so the system is in the expected state when executing the user's handlers. Misc Control of Ethernet Driver The following functions should only be invoked after the Ethernet driver has been installed. Stop Ethernet driver: esp_eth_stop() Update Ethernet data input path: esp_eth_update_input_path() Misc get/set of Ethernet driver attributes: esp_eth_ioctl() /* get MAC address */ uint8_t mac_addr[6]; memset(mac_addr, 0, sizeof(mac_addr)); esp_eth_ioctl(eth_handle, ETH_CMD_G_MAC_ADDR, mac_addr); ESP_LOGI(TAG, "Ethernet MAC Address: %02x:%02x:%02x:%02x:%02x:%02x", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); /* get PHY address */ int phy_addr = -1; esp_eth_ioctl(eth_handle, ETH_CMD_G_PHY_ADDR, &phy_addr); ESP_LOGI(TAG, "Ethernet PHY Address: %d", phy_addr); Flow Control Ethernet on MCU usually has a limitation in the number of frames it can handle during network congestion, because of the limitation in RAM size. A sending station might be transmitting data faster than the peer end can accept it. The ethernet flow control mechanism allows the receiving node to signal the sender requesting the suspension of transmissions until the receiver catches up. The magic behind that is the pause frame, which was defined in IEEE 802.3x. Pause frame is a special Ethernet frame used to carry the pause command, whose EtherType field is 0x8808, with the Control opcode set to 0x0001. Only stations configured for full-duplex operation may send pause frames. When a station wishes to pause the other end of a link, it sends a pause frame to the 48-bit reserved multicast address of 01-80-C2-00-00-01. The pause frame also includes the period of pause time being requested, in the form of a two-byte integer, ranging from 0 to 65535. After the Ethernet driver installation, the flow control feature is disabled by default. You can enable it by: 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. Application Examples - Ethernet basic example: ethernet/basic - Ethernet iperf example: ethernet/iperf - Ethernet to Wi-Fi AP "router": network/eth2ap - Wi-Fi station to Ethernet "bridge": network/sta2eth - Most protocol examples should also work for Ethernet: protocols 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. A set of management registers is defined to control chip behavior, link properties, auto-negotiation configuration, etc. This basic management functionality is addressed by 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 esp_eth/src/esp_eth_phy_802_3.c. However, the following may require developing chip-specific management functions: - Link status which is almost always chip-specific - Chip initialization, even though not strictly required, should be customized to at least ensure that the expected chip is used - Chip-specific features configuration Steps to create a custom PHY driver: Define vendor-specific registry layout based on the PHY datasheet. See esp_eth/src/esp_eth_phy_ip101.c as an example. Prepare derived PHY management object info structure which: must contain at least parent IEEE 802.3 phy_802_3_tobject optionally contain additional variables needed to support non-IEEE 802.3 or customized functionality. See esp_eth/src/esp_eth_phy_ksz80xx.c as an example. - Define chip-specific management call-back functions. Initialize parent IEEE 802.3 object and re-assign chip-specific management call-back functions. Once you finish the new custom PHY driver implementation, consider sharing it among other users via IDF Component Registry. API Reference Header File This header file can be included with: #include "esp_eth.h" This header file is a part of the API provided by the esp_ethcomponent. To declare that your component depends on esp_eth, add the following to your CMakeLists.txt: REQUIRES esp_eth or PRIV_REQUIRES esp_eth Header File This header file can be included with: #include "esp_eth_driver.h" This header file is a part of the API provided by the esp_ethcomponent. To declare that your component depends on esp_eth, add the following to your CMakeLists.txt: REQUIRES esp_eth or PRIV_REQUIRES esp_eth Functions - esp_err_t esp_eth_driver_install(const esp_eth_config_t *config, esp_eth_handle_t *out_hdl) Install Ethernet driver. - Parameters config -- [in] configuration of the Ethernet driver out_hdl -- [out] handle of Ethernet driver - - Returns ESP_OK: install esp_eth driver successfully ESP_ERR_INVALID_ARG: install esp_eth driver failed because of some invalid argument ESP_ERR_NO_MEM: install esp_eth driver failed because there's no memory for driver ESP_FAIL: install esp_eth driver failed because some other error occurred - - esp_err_t esp_eth_driver_uninstall(esp_eth_handle_t hdl) Uninstall Ethernet driver. Note It's not recommended to uninstall Ethernet driver unless it won't get used any more in application code. To uninstall Ethernet driver, you have to make sure, all references to the driver are released. Ethernet driver can only be uninstalled successfully when reference counter equals to one. - Parameters hdl -- [in] handle of Ethernet driver - Returns ESP_OK: uninstall esp_eth driver successfully ESP_ERR_INVALID_ARG: uninstall esp_eth driver failed because of some invalid argument ESP_ERR_INVALID_STATE: uninstall esp_eth driver failed because it has more than one reference ESP_FAIL: uninstall esp_eth driver failed because some other error occurred - - esp_err_t esp_eth_start(esp_eth_handle_t hdl) Start Ethernet driver ONLY in standalone mode (i.e. without TCP/IP stack) Note This API will start driver state machine and internal software timer (for checking link status). - Parameters hdl -- [in] handle of Ethernet driver - Returns ESP_OK: start esp_eth driver successfully ESP_ERR_INVALID_ARG: start esp_eth driver failed because of some invalid argument ESP_ERR_INVALID_STATE: start esp_eth driver failed because driver has started already ESP_FAIL: start esp_eth driver failed because some other error occurred - - esp_err_t esp_eth_stop(esp_eth_handle_t hdl) Stop Ethernet driver. Note This function does the oppsite operation of esp_eth_start. - Parameters hdl -- [in] handle of Ethernet driver - Returns ESP_OK: stop esp_eth driver successfully ESP_ERR_INVALID_ARG: stop esp_eth driver failed because of some invalid argument ESP_ERR_INVALID_STATE: stop esp_eth driver failed because driver has not started yet ESP_FAIL: stop esp_eth driver failed because some other error occurred - - esp_err_t esp_eth_update_input_path(esp_eth_handle_t hdl, esp_err_t (*stack_input)(esp_eth_handle_t hdl, uint8_t *buffer, uint32_t length, void *priv), void *priv) Update Ethernet data input path (i.e. specify where to pass the input buffer) Note After install driver, Ethernet still don't know where to deliver the input buffer. In fact, this API registers a callback function which get invoked when Ethernet received new packets. - Parameters hdl -- [in] handle of Ethernet driver stack_input -- [in] function pointer, which does the actual process on incoming packets priv -- [in] private resource, which gets passed to stack_inputcallback without any modification - - Returns ESP_OK: update input path successfully ESP_ERR_INVALID_ARG: update input path failed because of some invalid argument ESP_FAIL: update input path failed because some other error occurred - - esp_err_t esp_eth_transmit(esp_eth_handle_t hdl, void *buf, size_t length) General Transmit. - Parameters hdl -- [in] handle of Ethernet driver buf -- [in] buffer of the packet to transfer length -- [in] length of the buffer to transfer - - Returns ESP_OK: transmit frame buffer successfully ESP_ERR_INVALID_ARG: transmit frame buffer failed because of some invalid argument ESP_ERR_INVALID_STATE: invalid driver state (e.i. driver is not started) ESP_ERR_TIMEOUT: transmit frame buffer failed because HW was not get available in predefined period ESP_FAIL: transmit frame buffer failed because some other error occurred - - esp_err_t esp_eth_transmit_vargs(esp_eth_handle_t hdl, uint32_t argc, ...) Special Transmit with variable number of arguments. - Parameters hdl -- [in] handle of Ethernet driver argc -- [in] number variable arguments ... -- variable arguments - - Returns ESP_OK: transmit successfull ESP_ERR_INVALID_STATE: invalid driver state (e.i. driver is not started) ESP_ERR_TIMEOUT: transmit frame buffer failed because HW was not get available in predefined period ESP_FAIL: transmit frame buffer failed because some other error occurred - - esp_err_t esp_eth_ioctl(esp_eth_handle_t hdl, esp_eth_io_cmd_t cmd, void *data) Misc IO function of Etherent driver. The following common IO control commands are supported: ETH_CMD_S_MAC_ADDRsets Ethernet interface MAC address. dataargument is pointer to MAC address buffer with expected size of 6 bytes. ETH_CMD_G_MAC_ADDRgets Ethernet interface MAC address. dataargument is pointer to a buffer to which MAC address is to be copied. The buffer size must be at least 6 bytes. ETH_CMD_S_PHY_ADDRsets PHY address in range of <0-31>. dataargument is pointer to memory of uint32_t datatype from where the configuration option is read. ETH_CMD_G_PHY_ADDRgets PHY address. dataargument is pointer to memory of uint32_t datatype to which the PHY address is to be stored. ETH_CMD_S_AUTONEGOenables or disables Ethernet link speed and duplex mode autonegotiation. dataargument is pointer to memory of bool datatype from which the configuration option is read. Preconditions: Ethernet driver needs to be stopped. ETH_CMD_G_AUTONEGOgets current configuration of the Ethernet link speed and duplex mode autonegotiation. dataargument is pointer to memory of bool datatype to which the current configuration is to be stored. ETH_CMD_S_SPEEDsets the Ethernet link speed. dataargument is pointer to memory of eth_speed_t datatype from which the configuration option is read. Preconditions: Ethernet driver needs to be stopped and auto-negotiation disabled. ETH_CMD_G_SPEEDgets current Ethernet link speed. dataargument is pointer to memory of eth_speed_t datatype to which the speed is to be stored. ETH_CMD_S_PROMISCUOUSsets/resets Ethernet interface promiscuous mode. dataargument is pointer to memory of bool datatype from which the configuration option is read. ETH_CMD_S_FLOW_CTRLsets/resets Ethernet interface flow control. dataargument is pointer to memory of bool datatype from which the configuration option is read. ETH_CMD_S_DUPLEX_MODEsets the Ethernet duplex mode. dataargument is pointer to memory of eth_duplex_t datatype from which the configuration option is read. Preconditions: Ethernet driver needs to be stopped and auto-negotiation disabled. ETH_CMD_G_DUPLEX_MODEgets current Ethernet link duplex mode. dataargument is pointer to memory of eth_duplex_t datatype to which the duplex mode is to be stored. ETH_CMD_S_PHY_LOOPBACKsets/resets PHY to/from loopback mode. dataargument is pointer to memory of bool datatype from which the configuration option is read. Note that additional control commands may be available for specific MAC or PHY chips. Please consult specific MAC or PHY documentation or driver code. - Parameters hdl -- [in] handle of Ethernet driver cmd -- [in] IO control command data -- [inout] address of data for setcommand or address where to store the data when used with getcommand - - Returns ESP_OK: process io command successfully ESP_ERR_INVALID_ARG: process io command failed because of some invalid argument ESP_FAIL: process io command failed because some other error occurred ESP_ERR_NOT_SUPPORTED: requested feature is not supported - - - esp_err_t esp_eth_increase_reference(esp_eth_handle_t hdl) Increase Ethernet driver reference. Note Ethernet driver handle can be obtained by os timer, netif, etc. It's dangerous when thread A is using Ethernet but thread B uninstall the driver. Using reference counter can prevent such risk, but care should be taken, when you obtain Ethernet driver, this API must be invoked so that the driver won't be uninstalled during your using time. - Parameters hdl -- [in] handle of Ethernet driver - Returns ESP_OK: increase reference successfully ESP_ERR_INVALID_ARG: increase reference failed because of some invalid argument - - esp_err_t esp_eth_decrease_reference(esp_eth_handle_t hdl) Decrease Ethernet driver reference. - Parameters hdl -- [in] handle of Ethernet driver - Returns ESP_OK: increase reference successfully ESP_ERR_INVALID_ARG: increase reference failed because of some invalid argument - Structures - struct esp_eth_config_t Configuration of Ethernet driver. Public Members - esp_eth_mac_t *mac Ethernet MAC object. - esp_eth_phy_t *phy Ethernet PHY object. - uint32_t check_link_period_ms Period time of checking Ethernet link status. - esp_err_t (*stack_input)(esp_eth_handle_t eth_handle, uint8_t *buffer, uint32_t length, void *priv) Input frame buffer to user's stack. - Param eth_handle [in] handle of Ethernet driver - Param buffer [in] frame buffer that will get input to upper stack - Param length [in] length of the frame buffer - Return ESP_OK: input frame buffer to upper stack successfully ESP_FAIL: error occurred when inputting buffer to upper stack - - esp_err_t (*on_lowlevel_init_done)(esp_eth_handle_t eth_handle) Callback function invoked when lowlevel initialization is finished. - Param eth_handle [in] handle of Ethernet driver - Return ESP_OK: process extra lowlevel initialization successfully ESP_FAIL: error occurred when processing extra lowlevel initialization - - esp_err_t (*on_lowlevel_deinit_done)(esp_eth_handle_t eth_handle) Callback function invoked when lowlevel deinitialization is finished. - Param eth_handle [in] handle of Ethernet driver - Return ESP_OK: process extra lowlevel deinitialization successfully ESP_FAIL: error occurred when processing extra lowlevel deinitialization - - esp_err_t (*read_phy_reg)(esp_eth_handle_t eth_handle, uint32_t phy_addr, uint32_t phy_reg, uint32_t *reg_value) Read PHY register. Note Usually the PHY register read/write function is provided by MAC (SMI interface), but if the PHY device is managed by other interface (e.g. I2C), then user needs to implement the corresponding read/write. Setting this to NULL means your PHY device is managed by MAC's SMI interface. - Param eth_handle [in] handle of Ethernet driver - Param phy_addr [in] PHY chip address (0~31) - Param phy_reg [in] PHY register index code - Param reg_value [out] PHY register value - Return ESP_OK: read PHY register successfully ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument ESP_ERR_TIMEOUT: read PHY register failed because of timeout ESP_FAIL: read PHY register failed because some other error occurred - - esp_err_t (*write_phy_reg)(esp_eth_handle_t eth_handle, uint32_t phy_addr, uint32_t phy_reg, uint32_t reg_value) Write PHY register. Note Usually the PHY register read/write function is provided by MAC (SMI interface), but if the PHY device is managed by other interface (e.g. I2C), then user needs to implement the corresponding read/write. Setting this to NULL means your PHY device is managed by MAC's SMI interface. - Param eth_handle [in] handle of Ethernet driver - Param phy_addr [in] PHY chip address (0~31) - Param phy_reg [in] PHY register index code - Param reg_value [in] PHY register value - Return ESP_OK: write PHY register successfully ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument ESP_ERR_TIMEOUT: write PHY register failed because of timeout ESP_FAIL: write PHY register failed because some other error occurred - - esp_eth_mac_t *mac - struct esp_eth_phy_reg_rw_data_t Data structure to Read/Write PHY register via ioctl API. Macros - ETH_DEFAULT_CONFIG(emac, ephy) Default configuration for Ethernet driver. Type Definitions - typedef void *esp_eth_handle_t Handle of Ethernet driver. Enumerations - enum esp_eth_io_cmd_t Command list for ioctl API. Values: - enumerator ETH_CMD_G_MAC_ADDR Get MAC address - enumerator ETH_CMD_S_MAC_ADDR Set MAC address - enumerator ETH_CMD_G_PHY_ADDR Get PHY address - enumerator ETH_CMD_S_PHY_ADDR Set PHY address - enumerator ETH_CMD_G_AUTONEGO Get PHY Auto Negotiation - enumerator ETH_CMD_S_AUTONEGO Set PHY Auto Negotiation - enumerator ETH_CMD_G_SPEED Get Speed - enumerator ETH_CMD_S_SPEED Set Speed - enumerator ETH_CMD_S_PROMISCUOUS Set promiscuous mode - enumerator ETH_CMD_S_FLOW_CTRL Set flow control - enumerator ETH_CMD_G_DUPLEX_MODE Get Duplex mode - enumerator ETH_CMD_S_DUPLEX_MODE Set Duplex mode - enumerator ETH_CMD_S_PHY_LOOPBACK Set PHY loopback - enumerator ETH_CMD_READ_PHY_REG Read PHY register - enumerator ETH_CMD_WRITE_PHY_REG Write PHY register - enumerator ETH_CMD_CUSTOM_MAC_CMDS - enumerator ETH_CMD_CUSTOM_PHY_CMDS - enumerator ETH_CMD_G_MAC_ADDR Header File This header file can be included with: #include "esp_eth_com.h" This header file is a part of the API provided by the esp_ethcomponent. To declare that your component depends on esp_eth, add the following to your CMakeLists.txt: REQUIRES esp_eth or PRIV_REQUIRES esp_eth Structures - struct esp_eth_mediator_s Ethernet mediator. Public Members - esp_err_t (*phy_reg_read)(esp_eth_mediator_t *eth, uint32_t phy_addr, uint32_t phy_reg, uint32_t *reg_value) Read PHY register. - Param eth [in] mediator of Ethernet driver - Param phy_addr [in] PHY Chip address (0~31) - Param phy_reg [in] PHY register index code - Param reg_value [out] PHY register value - Return ESP_OK: read PHY register successfully ESP_FAIL: read PHY register failed because some error occurred - - esp_err_t (*phy_reg_write)(esp_eth_mediator_t *eth, uint32_t phy_addr, uint32_t phy_reg, uint32_t reg_value) Write PHY register. - Param eth [in] mediator of Ethernet driver - Param phy_addr [in] PHY Chip address (0~31) - Param phy_reg [in] PHY register index code - Param reg_value [in] PHY register value - Return ESP_OK: write PHY register successfully ESP_FAIL: write PHY register failed because some error occurred - - esp_err_t (*stack_input)(esp_eth_mediator_t *eth, uint8_t *buffer, uint32_t length) Deliver packet to upper stack. - Param eth [in] mediator of Ethernet driver - Param buffer [in] packet buffer - Param length [in] length of the packet - Return ESP_OK: deliver packet to upper stack successfully ESP_FAIL: deliver packet failed because some error occurred - - esp_err_t (*on_state_changed)(esp_eth_mediator_t *eth, esp_eth_state_t state, void *args) Callback on Ethernet state changed. - Param eth [in] mediator of Ethernet driver - Param state [in] new state - Param args [in] optional argument for the new state - Return ESP_OK: process the new state successfully ESP_FAIL: process the new state failed because some error occurred - - esp_err_t (*phy_reg_read)(esp_eth_mediator_t *eth, uint32_t phy_addr, uint32_t phy_reg, uint32_t *reg_value) Type Definitions - typedef struct esp_eth_mediator_s esp_eth_mediator_t Ethernet mediator. Enumerations - enum esp_eth_state_t Ethernet driver state. Values: - enumerator ETH_STATE_LLINIT Lowlevel init done - enumerator ETH_STATE_DEINIT Deinit done - enumerator ETH_STATE_LINK Link status changed - enumerator ETH_STATE_SPEED Speed updated - enumerator ETH_STATE_DUPLEX Duplex updated - enumerator ETH_STATE_PAUSE Pause ability updated - enumerator ETH_STATE_LLINIT Header File This header file can be included with: #include "esp_eth_mac.h" This header file is a part of the API provided by the esp_ethcomponent. To declare that your component depends on esp_eth, add the following to your CMakeLists.txt: REQUIRES esp_eth or PRIV_REQUIRES esp_eth Functions - esp_eth_mac_t *esp_eth_mac_new_esp32(const eth_esp32_emac_config_t *esp32_config, const eth_mac_config_t *config) Create ESP32 Ethernet MAC instance. - Parameters esp32_config -- EMAC specific configuration config -- Ethernet MAC configuration - - Returns instance: create MAC instance successfully NULL: create MAC instance failed because some error occurred - Unions - union eth_mac_clock_config_t - #include <esp_eth_mac.h> Ethernet MAC Clock Configuration. Public Members - struct eth_mac_clock_config_t::[anonymous] mii EMAC MII Clock Configuration - emac_rmii_clock_mode_t clock_mode RMII Clock Mode Configuration - emac_rmii_clock_gpio_t clock_gpio RMII Clock GPIO Configuration - struct eth_mac_clock_config_t::[anonymous] rmii EMAC RMII Clock Configuration - struct eth_mac_clock_config_t::[anonymous] mii Structures - struct esp_eth_mac_s Ethernet MAC. Public Members - esp_err_t (*set_mediator)(esp_eth_mac_t *mac, esp_eth_mediator_t *eth) Set mediator for Ethernet MAC. - Param mac [in] Ethernet MAC instance - Param eth [in] Ethernet mediator - Return ESP_OK: set mediator for Ethernet MAC successfully ESP_ERR_INVALID_ARG: set mediator for Ethernet MAC failed because of invalid argument - - esp_err_t (*init)(esp_eth_mac_t *mac) Initialize Ethernet MAC. - Param mac [in] Ethernet MAC instance - Return ESP_OK: initialize Ethernet MAC successfully ESP_ERR_TIMEOUT: initialize Ethernet MAC failed because of timeout ESP_FAIL: initialize Ethernet MAC failed because some other error occurred - - esp_err_t (*deinit)(esp_eth_mac_t *mac) Deinitialize Ethernet MAC. - Param mac [in] Ethernet MAC instance - Return ESP_OK: deinitialize Ethernet MAC successfully ESP_FAIL: deinitialize Ethernet MAC failed because some error occurred - - esp_err_t (*start)(esp_eth_mac_t *mac) Start Ethernet MAC. - Param mac [in] Ethernet MAC instance - Return ESP_OK: start Ethernet MAC successfully ESP_FAIL: start Ethernet MAC failed because some other error occurred - - esp_err_t (*stop)(esp_eth_mac_t *mac) Stop Ethernet MAC. - Param mac [in] Ethernet MAC instance - Return ESP_OK: stop Ethernet MAC successfully ESP_FAIL: stop Ethernet MAC failed because some error occurred - - esp_err_t (*transmit)(esp_eth_mac_t *mac, uint8_t *buf, uint32_t length) Transmit packet from Ethernet MAC. Note Returned error codes may differ for each specific MAC chip. - Param mac [in] Ethernet MAC instance - Param buf [in] packet buffer to transmit - Param length [in] length of packet - Return ESP_OK: transmit packet successfully ESP_ERR_INVALID_SIZE: number of actually sent bytes differs to expected ESP_FAIL: transmit packet failed because some other error occurred - - esp_err_t (*transmit_vargs)(esp_eth_mac_t *mac, uint32_t argc, va_list args) Transmit packet from Ethernet MAC constructed with special parameters at Layer2. Note Typical intended use case is to make possible to construct a frame from multiple higher layer buffers without a need of buffer reallocations. However, other use cases are not limited. Note Returned error codes may differ for each specific MAC chip. - Param mac [in] Ethernet MAC instance - Param argc [in] number variable arguments - Param args [in] variable arguments - Return ESP_OK: transmit packet successfully ESP_ERR_INVALID_SIZE: number of actually sent bytes differs to expected ESP_FAIL: transmit packet failed because some other error occurred - - esp_err_t (*receive)(esp_eth_mac_t *mac, uint8_t *buf, uint32_t *length) Receive packet from Ethernet MAC. Note Memory of buf is allocated in the Layer2, make sure it get free after process. Note Before this function got invoked, the value of "length" should set by user, equals the size of buffer. After the function returned, the value of "length" means the real length of received data. - Param mac [in] Ethernet MAC instance - Param buf [out] packet buffer which will preserve the received frame - Param length [out] length of the received packet - Return ESP_OK: receive packet successfully ESP_ERR_INVALID_ARG: receive packet failed because of invalid argument ESP_ERR_INVALID_SIZE: input buffer size is not enough to hold the incoming data. in this case, value of returned "length" indicates the real size of incoming data. ESP_FAIL: receive packet failed because some other error occurred - - esp_err_t (*read_phy_reg)(esp_eth_mac_t *mac, uint32_t phy_addr, uint32_t phy_reg, uint32_t *reg_value) Read PHY register. - Param mac [in] Ethernet MAC instance - Param phy_addr [in] PHY chip address (0~31) - Param phy_reg [in] PHY register index code - Param reg_value [out] PHY register value - Return ESP_OK: read PHY register successfully ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument ESP_ERR_INVALID_STATE: read PHY register failed because of wrong state of MAC ESP_ERR_TIMEOUT: read PHY register failed because of timeout ESP_FAIL: read PHY register failed because some other error occurred - - esp_err_t (*write_phy_reg)(esp_eth_mac_t *mac, uint32_t phy_addr, uint32_t phy_reg, uint32_t reg_value) Write PHY register. - Param mac [in] Ethernet MAC instance - Param phy_addr [in] PHY chip address (0~31) - Param phy_reg [in] PHY register index code - Param reg_value [in] PHY register value - Return ESP_OK: write PHY register successfully ESP_ERR_INVALID_STATE: write PHY register failed because of wrong state of MAC ESP_ERR_TIMEOUT: write PHY register failed because of timeout ESP_FAIL: write PHY register failed because some other error occurred - - esp_err_t (*set_addr)(esp_eth_mac_t *mac, uint8_t *addr) Set MAC address. - Param mac [in] Ethernet MAC instance - Param addr [in] MAC address - Return ESP_OK: set MAC address successfully ESP_ERR_INVALID_ARG: set MAC address failed because of invalid argument ESP_FAIL: set MAC address failed because some other error occurred - - esp_err_t (*get_addr)(esp_eth_mac_t *mac, uint8_t *addr) Get MAC address. - Param mac [in] Ethernet MAC instance - Param addr [out] MAC address - Return ESP_OK: get MAC address successfully ESP_ERR_INVALID_ARG: get MAC address failed because of invalid argument ESP_FAIL: get MAC address failed because some other error occurred - - esp_err_t (*set_speed)(esp_eth_mac_t *mac, eth_speed_t speed) Set speed of MAC. - Param ma:c [in] Ethernet MAC instance - Param speed [in] MAC speed - Return ESP_OK: set MAC speed successfully ESP_ERR_INVALID_ARG: set MAC speed failed because of invalid argument ESP_FAIL: set MAC speed failed because some other error occurred - - esp_err_t (*set_duplex)(esp_eth_mac_t *mac, eth_duplex_t duplex) Set duplex mode of MAC. - Param mac [in] Ethernet MAC instance - Param duplex [in] MAC duplex - Return ESP_OK: set MAC duplex mode successfully ESP_ERR_INVALID_ARG: set MAC duplex failed because of invalid argument ESP_FAIL: set MAC duplex failed because some other error occurred - - esp_err_t (*set_link)(esp_eth_mac_t *mac, eth_link_t link) Set link status of MAC. - Param mac [in] Ethernet MAC instance - Param link [in] Link status - Return ESP_OK: set link status successfully ESP_ERR_INVALID_ARG: set link status failed because of invalid argument ESP_FAIL: set link status failed because some other error occurred - - esp_err_t (*set_promiscuous)(esp_eth_mac_t *mac, bool enable) Set promiscuous of MAC. - Param mac [in] Ethernet MAC instance - Param enable [in] set true to enable promiscuous mode; set false to disable promiscuous mode - Return ESP_OK: set promiscuous mode successfully ESP_FAIL: set promiscuous mode failed because some error occurred - - esp_err_t (*enable_flow_ctrl)(esp_eth_mac_t *mac, bool enable) Enable flow control on MAC layer or not. - Param mac [in] Ethernet MAC instance - Param enable [in] set true to enable flow control; set false to disable flow control - Return ESP_OK: set flow control successfully ESP_FAIL: set flow control failed because some error occurred - - esp_err_t (*set_peer_pause_ability)(esp_eth_mac_t *mac, uint32_t ability) Set the PAUSE ability of peer node. - Param mac [in] Ethernet MAC instance - Param ability [in] zero indicates that pause function is supported by link partner; non-zero indicates that pause function is not supported by link partner - Return ESP_OK: set peer pause ability successfully ESP_FAIL: set peer pause ability failed because some error occurred - - esp_err_t (*custom_ioctl)(esp_eth_mac_t *mac, uint32_t cmd, void *data) Custom IO function of MAC driver. This function is intended to extend common options of esp_eth_ioctl to cover specifics of MAC chip. Note This function may not be assigned when the MAC chip supports only most common set of configuration options. - Param mac [in] Ethernet MAC instance - Param cmd [in] IO control command - Param data [inout] address of data for setcommand or address where to store the data when used with getcommand - Return ESP_OK: process io command successfully ESP_ERR_INVALID_ARG: process io command failed because of some invalid argument ESP_FAIL: process io command failed because some other error occurred ESP_ERR_NOT_SUPPORTED: requested feature is not supported - - esp_err_t (*del)(esp_eth_mac_t *mac) Free memory of Ethernet MAC. - Param mac [in] Ethernet MAC instance - Return ESP_OK: free Ethernet MAC instance successfully ESP_FAIL: free Ethernet MAC instance failed because some error occurred - - esp_err_t (*set_mediator)(esp_eth_mac_t *mac, esp_eth_mediator_t *eth) - struct eth_mac_config_t Configuration of Ethernet MAC object. - struct eth_esp32_emac_config_t EMAC specific configuration. Public Members - int smi_mdc_gpio_num SMI MDC GPIO number, set to -1 could bypass the SMI GPIO configuration - int smi_mdio_gpio_num SMI MDIO GPIO number, set to -1 could bypass the SMI GPIO configuration - eth_data_interface_t interface EMAC Data interface to PHY (MII/RMII) - eth_mac_clock_config_t clock_config EMAC Interface clock configuration - eth_mac_dma_burst_len_t dma_burst_len EMAC DMA burst length for both Tx and Rx - int smi_mdc_gpio_num - struct eth_spi_custom_driver_config_t Custom SPI Driver Configuration. This structure declares configuration and callback functions to access Ethernet SPI module via user's custom SPI driver. Public Members - void *config Custom driver specific configuration data used by init()function. Note Type and its content is fully under user's control - void *(*init)(const void *spi_config) Custom driver SPI Initialization. Note return type and its content is fully under user's control - Param spi_config [in] Custom driver specific configuration - Return spi_ctx: when initialization is successful, a pointer to context structure holding all variables needed for subsequent SPI access operations (e.g. SPI bus identification, mutexes, etc.) NULL: driver initialization failed - - esp_err_t (*deinit)(void *spi_ctx) Custom driver De-initialization. - Param spi_ctx [in] a pointer to driver specific context structure - Return ESP_OK: driver de-initialization was successful ESP_FAIL: driver de-initialization failed any other failure codes are allowed to be used to provide failure isolation - - esp_err_t (*read)(void *spi_ctx, uint32_t cmd, uint32_t addr, void *data, uint32_t data_len) Custom driver SPI read. Note The read function is responsible to construct command, address and data fields of the SPI frame in format expected by particular SPI Ethernet module - Param spi_ctx [in] a pointer to driver specific context structure - Param cmd [in] command - Param addr [in] register address - Param data [out] read data - Param data_len [in] read data length in bytes - Return ESP_OK: read was successful ESP_FAIL: read failed any other failure codes are allowed to be used to provide failure isolation - - esp_err_t (*write)(void *spi_ctx, uint32_t cmd, uint32_t addr, const void *data, uint32_t data_len) Custom driver SPI write. Note The write function is responsible to construct command, address and data fields of the SPI frame in format expected by particular SPI Ethernet module - Param spi_ctx [in] a pointer to driver specific context structure - Param cmd [in] command - Param addr [in] register address - Param data [in] data to write - Param data_len [in] length of data to write in bytes - Return ESP_OK: write was successful ESP_FAIL: write failed any other failure codes are allowed to be used to provide failure isolation - - void *config Macros - ETH_MAC_FLAG_WORK_WITH_CACHE_DISABLE MAC driver can work when cache is disabled - ETH_MAC_FLAG_PIN_TO_CORE Pin MAC task to the CPU core where driver installation happened - ETH_MAC_DEFAULT_CONFIG() Default configuration for Ethernet MAC object. - ETH_ESP32_EMAC_DEFAULT_CONFIG() Default ESP32's EMAC specific configuration. - ETH_DEFAULT_SPI Default configuration of the custom SPI driver. Internal ESP-IDF SPI Master driver is used by default. Type Definitions - typedef struct esp_eth_mac_s esp_eth_mac_t Ethernet MAC. Enumerations - enum emac_rmii_clock_mode_t RMII Clock Mode Options. Values: - enumerator EMAC_CLK_DEFAULT Default values configured using Kconfig are going to be used when "Default" selected. - enumerator EMAC_CLK_EXT_IN Input RMII Clock from external. EMAC Clock GPIO number needs to be configured when this option is selected. Note MAC will get RMII clock from outside. Note that ESP32 only supports GPIO0 to input the RMII clock. - enumerator EMAC_CLK_OUT Output RMII Clock from internal APLL Clock. EMAC Clock GPIO number needs to be configured when this option is selected. - enumerator EMAC_CLK_DEFAULT - enum emac_rmii_clock_gpio_t RMII Clock GPIO number Options. Values: - enumerator EMAC_CLK_IN_GPIO MAC will get RMII clock from outside at this GPIO. Note ESP32 only supports GPIO0 to input the RMII clock. - enumerator EMAC_APPL_CLK_OUT_GPIO Output RMII Clock from internal APLL Clock available at GPIO0. Note GPIO0 can be set to output a pre-divided PLL clock (test only!). Enabling this option will configure GPIO0 to output a 50MHz clock. In fact this clock doesn’t have directly relationship with EMAC peripheral. Sometimes this clock won’t work well with your PHY chip. You might need to add some extra devices after GPIO0 (e.g. inverter). Note that outputting RMII clock on GPIO0 is an experimental practice. If you want the Ethernet to work with WiFi, don’t select GPIO0 output mode for stability. - enumerator EMAC_CLK_OUT_GPIO Output RMII Clock from internal APLL Clock available at GPIO16. - enumerator EMAC_CLK_OUT_180_GPIO Inverted Output RMII Clock from internal APLL Clock available at GPIO17. - enumerator EMAC_CLK_IN_GPIO Header File This header file can be included with: #include "esp_eth_phy.h" This header file is a part of the API provided by the esp_ethcomponent. To declare that your component depends on esp_eth, add the following to your CMakeLists.txt: REQUIRES esp_eth or PRIV_REQUIRES esp_eth Functions - esp_eth_phy_t *esp_eth_phy_new_ip101(const eth_phy_config_t *config) Create a PHY instance of IP101. - Parameters config -- [in] configuration of PHY - Returns instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred - - esp_eth_phy_t *esp_eth_phy_new_rtl8201(const eth_phy_config_t *config) Create a PHY instance of RTL8201. - Parameters config -- [in] configuration of PHY - Returns instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred - - esp_eth_phy_t *esp_eth_phy_new_lan87xx(const eth_phy_config_t *config) Create a PHY instance of LAN87xx. - Parameters config -- [in] configuration of PHY - Returns instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred - - esp_eth_phy_t *esp_eth_phy_new_dp83848(const eth_phy_config_t *config) Create a PHY instance of DP83848. - Parameters config -- [in] configuration of PHY - Returns instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred - - esp_eth_phy_t *esp_eth_phy_new_ksz80xx(const eth_phy_config_t *config) Create a PHY instance of KSZ80xx. The phy model from the KSZ80xx series is detected automatically. If the driver is unable to detect a supported model, NULLis returned. Currently, the following models are supported: KSZ8001, KSZ8021, KSZ8031, KSZ8041, KSZ8051, KSZ8061, KSZ8081, KSZ8091 - Parameters config -- [in] configuration of PHY - Returns instance: create PHY instance successfully NULL: create PHY instance failed because some error occurred - Structures - struct esp_eth_phy_s Ethernet PHY. Public Members - esp_err_t (*set_mediator)(esp_eth_phy_t *phy, esp_eth_mediator_t *mediator) Set mediator for PHY. - Param phy [in] Ethernet PHY instance - Param mediator [in] mediator of Ethernet driver - Return ESP_OK: set mediator for Ethernet PHY instance successfully ESP_ERR_INVALID_ARG: set mediator for Ethernet PHY instance failed because of some invalid arguments - - esp_err_t (*reset)(esp_eth_phy_t *phy) Software Reset Ethernet PHY. - Param phy [in] Ethernet PHY instance - Return ESP_OK: reset Ethernet PHY successfully ESP_FAIL: reset Ethernet PHY failed because some error occurred - - esp_err_t (*reset_hw)(esp_eth_phy_t *phy) Hardware Reset Ethernet PHY. Note Hardware reset is mostly done by pull down and up PHY's nRST pin - Param phy [in] Ethernet PHY instance - Return ESP_OK: reset Ethernet PHY successfully ESP_FAIL: reset Ethernet PHY failed because some error occurred - - esp_err_t (*init)(esp_eth_phy_t *phy) Initialize Ethernet PHY. - Param phy [in] Ethernet PHY instance - Return ESP_OK: initialize Ethernet PHY successfully ESP_FAIL: initialize Ethernet PHY failed because some error occurred - - esp_err_t (*deinit)(esp_eth_phy_t *phy) Deinitialize Ethernet PHY. - Param phy [in] Ethernet PHY instance - Return ESP_OK: deinitialize Ethernet PHY successfully ESP_FAIL: deinitialize Ethernet PHY failed because some error occurred - - esp_err_t (*autonego_ctrl)(esp_eth_phy_t *phy, eth_phy_autoneg_cmd_t cmd, bool *autonego_en_stat) Configure auto negotiation. - Param phy [in] Ethernet PHY instance - Param cmd [in] Configuration command, it is possible to Enable (restart), Disable or get current status of PHY auto negotiation - Param autonego_en_stat [out] Address where to store current status of auto negotiation configuration - Return ESP_OK: restart auto negotiation successfully ESP_FAIL: restart auto negotiation failed because some error occurred ESP_ERR_INVALID_ARG: invalid command - - esp_err_t (*get_link)(esp_eth_phy_t *phy) Get Ethernet PHY link status. - Param phy [in] Ethernet PHY instance - Return ESP_OK: get Ethernet PHY link status successfully ESP_FAIL: get Ethernet PHY link status failed because some error occurred - - esp_err_t (*pwrctl)(esp_eth_phy_t *phy, bool enable) Power control of Ethernet PHY. - Param phy [in] Ethernet PHY instance - Param enable [in] set true to power on Ethernet PHY; ser false to power off Ethernet PHY - Return ESP_OK: control Ethernet PHY power successfully ESP_FAIL: control Ethernet PHY power failed because some error occurred - - esp_err_t (*set_addr)(esp_eth_phy_t *phy, uint32_t addr) Set PHY chip address. - Param phy [in] Ethernet PHY instance - Param addr [in] PHY chip address - Return ESP_OK: set Ethernet PHY address successfully ESP_FAIL: set Ethernet PHY address failed because some error occurred - - esp_err_t (*get_addr)(esp_eth_phy_t *phy, uint32_t *addr) Get PHY chip address. - Param phy [in] Ethernet PHY instance - Param addr [out] PHY chip address - Return ESP_OK: get Ethernet PHY address successfully ESP_ERR_INVALID_ARG: get Ethernet PHY address failed because of invalid argument - - esp_err_t (*advertise_pause_ability)(esp_eth_phy_t *phy, uint32_t ability) Advertise pause function supported by MAC layer. - Param phy [in] Ethernet PHY instance - Param addr [out] Pause ability - Return ESP_OK: Advertise pause ability successfully ESP_ERR_INVALID_ARG: Advertise pause ability failed because of invalid argument - - esp_err_t (*loopback)(esp_eth_phy_t *phy, bool enable) Sets the PHY to loopback mode. - Param phy [in] Ethernet PHY instance - Param enable [in] enables or disables PHY loopback - Return ESP_OK: PHY instance loopback mode has been configured successfully ESP_FAIL: PHY instance loopback configuration failed because some error occurred - - esp_err_t (*set_speed)(esp_eth_phy_t *phy, eth_speed_t speed) Sets PHY speed mode. Note Autonegotiation feature needs to be disabled prior to calling this function for the new setting to be applied - Param phy [in] Ethernet PHY instance - Param speed [in] Speed mode to be set - Return ESP_OK: PHY instance speed mode has been configured successfully ESP_FAIL: PHY instance speed mode configuration failed because some error occurred - - esp_err_t (*set_duplex)(esp_eth_phy_t *phy, eth_duplex_t duplex) Sets PHY duplex mode. Note Autonegotiation feature needs to be disabled prior to calling this function for the new setting to be applied - Param phy [in] Ethernet PHY instance - Param duplex [in] Duplex mode to be set - Return ESP_OK: PHY instance duplex mode has been configured successfully ESP_FAIL: PHY instance duplex mode configuration failed because some error occurred - - esp_err_t (*custom_ioctl)(esp_eth_phy_t *phy, uint32_t cmd, void *data) Custom IO function of PHY driver. This function is intended to extend common options of esp_eth_ioctl to cover specifics of PHY chip. Note This function may not be assigned when the PHY chip supports only most common set of configuration options. - Param phy [in] Ethernet PHY instance - Param cmd [in] IO control command - Param data [inout] address of data for setcommand or address where to store the data when used with getcommand - Return ESP_OK: process io command successfully ESP_ERR_INVALID_ARG: process io command failed because of some invalid argument ESP_FAIL: process io command failed because some other error occurred ESP_ERR_NOT_SUPPORTED: requested feature is not supported - - esp_err_t (*del)(esp_eth_phy_t *phy) Free memory of Ethernet PHY instance. - Param phy [in] Ethernet PHY instance - Return ESP_OK: free PHY instance successfully ESP_FAIL: free PHY instance failed because some error occurred - - esp_err_t (*set_mediator)(esp_eth_phy_t *phy, esp_eth_mediator_t *mediator) - struct eth_phy_config_t Ethernet PHY configuration. Public Members - int32_t phy_addr PHY address, set -1 to enable PHY address detection at initialization stage - uint32_t reset_timeout_ms Reset timeout value (Unit: ms) - uint32_t autonego_timeout_ms Auto-negotiation timeout value (Unit: ms) - int reset_gpio_num Reset GPIO number, -1 means no hardware reset - int32_t phy_addr Macros - ESP_ETH_PHY_ADDR_AUTO - ETH_PHY_DEFAULT_CONFIG() Default configuration for Ethernet PHY object. Type Definitions - typedef struct esp_eth_phy_s esp_eth_phy_t Ethernet PHY. Enumerations Header File This header file can be included with: #include "esp_eth_phy_802_3.h" This header file is a part of the API provided by the esp_ethcomponent. To declare that your component depends on esp_eth, add the following to your CMakeLists.txt: REQUIRES esp_eth or PRIV_REQUIRES esp_eth Functions - esp_err_t esp_eth_phy_802_3_set_mediator(phy_802_3_t *phy_802_3, esp_eth_mediator_t *eth) Set Ethernet mediator. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure eth -- Ethernet mediator pointer - - Returns ESP_OK: Ethermet mediator set successfuly ESP_ERR_INVALID_ARG: if ethis NULL - - esp_err_t esp_eth_phy_802_3_reset(phy_802_3_t *phy_802_3) Reset PHY. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure - Returns ESP_OK: Ethernet PHY reset successfuly ESP_FAIL: reset Ethernet PHY failed because some error occured - - esp_err_t esp_eth_phy_802_3_autonego_ctrl(phy_802_3_t *phy_802_3, eth_phy_autoneg_cmd_t cmd, bool *autonego_en_stat) Control autonegotiation mode of Ethernet PHY. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure cmd -- autonegotiation command enumeration autonego_en_stat -- [out] autonegotiation enabled flag - - Returns ESP_OK: Ethernet PHY autonegotiation configured successfuly ESP_FAIL: Ethernet PHY autonegotiation configuration fail because some error occured ESP_ERR_INVALID_ARG: invalid value of cmd - - esp_err_t esp_eth_phy_802_3_pwrctl(phy_802_3_t *phy_802_3, bool enable) Power control of Ethernet PHY. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure enable -- set true to power ON Ethernet PHY; set false to power OFF Ethernet PHY - - Returns ESP_OK: Ethernet PHY power down mode set successfuly ESP_FAIL: Ethernet PHY power up or power down failed because some error occured - - esp_err_t esp_eth_phy_802_3_set_addr(phy_802_3_t *phy_802_3, uint32_t addr) Set Ethernet PHY address. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure addr -- new PHY address - - Returns ESP_OK: Ethernet PHY address set - - esp_err_t esp_eth_phy_802_3_get_addr(phy_802_3_t *phy_802_3, uint32_t *addr) Get Ethernet PHY address. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure addr -- [out] Ethernet PHY address - - Returns ESP_OK: Ethernet PHY address read successfuly ESP_ERR_INVALID_ARG: addrpointer is NULL - - esp_err_t esp_eth_phy_802_3_advertise_pause_ability(phy_802_3_t *phy_802_3, uint32_t ability) Advertise pause function ability. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure ability -- enable or disable pause ability - - Returns ESP_OK: pause ability set successfuly ESP_FAIL: Advertise pause function ability failed because some error occured - - esp_err_t esp_eth_phy_802_3_loopback(phy_802_3_t *phy_802_3, bool enable) Set Ethernet PHY loopback mode. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure enable -- set true to enable loopback; set false to disable loopback - - Returns ESP_OK: Ethernet PHY loopback mode set successfuly ESP_FAIL: Ethernet PHY loopback configuration failed because some error occured - - esp_err_t esp_eth_phy_802_3_set_speed(phy_802_3_t *phy_802_3, eth_speed_t speed) Set Ethernet PHY speed. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure speed -- new speed of Ethernet PHY link - - Returns ESP_OK: Ethernet PHY speed set successfuly ESP_FAIL: Set Ethernet PHY speed failed because some error occured - - esp_err_t esp_eth_phy_802_3_set_duplex(phy_802_3_t *phy_802_3, eth_duplex_t duplex) Set Ethernet PHY duplex mode. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure duplex -- new duplex mode for Ethernet PHY link - - Returns ESP_OK: Ethernet PHY duplex mode set successfuly ESP_ERR_INVALID_STATE: unable to set duplex mode to Half if loopback is enabled ESP_FAIL: Set Ethernet PHY duplex mode failed because some error occured - - esp_err_t esp_eth_phy_802_3_init(phy_802_3_t *phy_802_3) Initialize Ethernet PHY. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure - Returns ESP_OK: Ethernet PHY initialized successfuly - - esp_err_t esp_eth_phy_802_3_deinit(phy_802_3_t *phy_802_3) Power off Eternet PHY. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure - Returns ESP_OK: Ethernet PHY powered off successfuly - - esp_err_t esp_eth_phy_802_3_del(phy_802_3_t *phy_802_3) Delete Ethernet PHY infostructure. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure - Returns ESP_OK: Ethrnet PHY infostructure deleted - - esp_err_t esp_eth_phy_802_3_reset_hw(phy_802_3_t *phy_802_3, uint32_t reset_assert_us) Performs hardware reset with specific reset pin assertion time. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure reset_assert_us -- Hardware reset pin assertion time - - Returns ESP_OK: reset Ethernet PHY successfully - - esp_err_t esp_eth_phy_802_3_detect_phy_addr(esp_eth_mediator_t *eth, int *detected_addr) Detect PHY address. - Parameters eth -- Mediator of Ethernet driver detected_addr -- [out] a valid address after detection - - Returns ESP_OK: detect phy address successfully ESP_ERR_INVALID_ARG: invalid parameter ESP_ERR_NOT_FOUND: can't detect any PHY device ESP_FAIL: detect phy address failed because some error occurred - - esp_err_t esp_eth_phy_802_3_basic_phy_init(phy_802_3_t *phy_802_3) Performs basic PHY chip initialization. Note It should be called as the first function in PHY specific driver instance - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure - Returns ESP_OK: initialized Ethernet PHY successfully ESP_FAIL: initialization of Ethernet PHY failed because some error occurred ESP_ERR_INVALID_ARG: invalid argument ESP_ERR_NOT_FOUND: PHY device not detected ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation - - esp_err_t esp_eth_phy_802_3_basic_phy_deinit(phy_802_3_t *phy_802_3) Performs basic PHY chip de-initialization. Note It should be called as the last function in PHY specific driver instance - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure - Returns ESP_OK: de-initialized Ethernet PHY successfully ESP_FAIL: de-initialization of Ethernet PHY failed because some error occurred ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation - - esp_err_t esp_eth_phy_802_3_read_oui(phy_802_3_t *phy_802_3, uint32_t *oui) Reads raw content of OUI field. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure oui -- [out] OUI value - - Returns ESP_OK: OUI field read successfully ESP_FAIL: OUI field read failed because some error occurred ESP_ERR_INVALID_ARG: invalid ouiargument ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation - - esp_err_t esp_eth_phy_802_3_read_manufac_info(phy_802_3_t *phy_802_3, uint8_t *model, uint8_t *rev) Reads manufacturer’s model and revision number. - Parameters phy_802_3 -- IEEE 802.3 PHY object infostructure model -- [out] Manufacturer’s model number (can be NULL when not required) rev -- [out] Manufacturer’s revision number (can be NULL when not required) - - Returns ESP_OK: Manufacturer’s info read successfully ESP_FAIL: Manufacturer’s info read failed because some error occurred ESP_ERR_TIMEOUT: MII Management read/write operation timeout ESP_ERR_INVALID_STATE: PHY is in invalid state to perform requested operation - - inline phy_802_3_t *esp_eth_phy_into_phy_802_3(esp_eth_phy_t *phy) Returns address to parent IEEE 802.3 PHY object infostructure. - Parameters phy -- Ethernet PHY instance - Returns phy_802_3_t* address to parent IEEE 802.3 PHY object infostructure - - esp_err_t esp_eth_phy_802_3_obj_config_init(phy_802_3_t *phy_802_3, const eth_phy_config_t *config) Initializes configuration of parent IEEE 802.3 PHY object infostructure. - Parameters phy_802_3 -- Address to IEEE 802.3 PHY object infostructure config -- Configuration of the IEEE 802.3 PHY object - - Returns ESP_OK: configuration initialized successfully ESP_ERR_INVALID_ARG: invalid configargument - Structures - struct phy_802_3_t IEEE 802.3 PHY object infostructure. Public Members - esp_eth_phy_t parent Parent Ethernet PHY instance - esp_eth_mediator_t *eth Mediator of Ethernet driver - int addr PHY address - uint32_t reset_timeout_ms Reset timeout value (Unit: ms) - uint32_t autonego_timeout_ms Auto-negotiation timeout value (Unit: ms) - eth_link_t link_status Current Link status - int reset_gpio_num Reset GPIO number, -1 means no hardware reset - esp_eth_phy_t parent Header File This header file can be included with: #include "esp_eth_netif_glue.h" This header file is a part of the API provided by the esp_ethcomponent. To declare that your component depends on esp_eth, add the following to your CMakeLists.txt: REQUIRES esp_eth or PRIV_REQUIRES esp_eth Functions - esp_eth_netif_glue_handle_t esp_eth_new_netif_glue(esp_eth_handle_t eth_hdl) Create a netif glue for Ethernet driver. Note netif glue is used to attach io driver to TCP/IP netif - Parameters eth_hdl -- Ethernet driver handle - Returns glue object, which inherits esp_netif_driver_base_t - esp_err_t esp_eth_del_netif_glue(esp_eth_netif_glue_handle_t eth_netif_glue) Delete netif glue of Ethernet driver. - Parameters eth_netif_glue -- netif glue - Returns -ESP_OK: delete netif glue successfully Type Definitions - typedef struct esp_eth_netif_glue_t *esp_eth_netif_glue_handle_t Handle of netif glue - an intermediate layer between netif and Ethernet driver.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/network/esp_eth.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Thread
null
espressif.com
2016-01-01
9756f2f82c1391c1
null
null
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 openthread directory of ESP-IDF examples contains the following applications: The OpenThread interactive shell openthread/ot_cli The Thread Border Router openthread/ot_br The Thread Radio Co-Processor 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. Header File This header file can be included with: #include "esp_openthread.h" This header file is a part of the API provided by the openthread component. To declare that your component depends on openthread , add the following to your CMakeLists.txt: REQUIRES openthread or PRIV_REQUIRES openthread Functions esp_err_t esp_openthread_init(const esp_openthread_platform_config_t *init_config) Initializes the full OpenThread stack. Note The OpenThread instance will also be initialized in this function. Parameters init_config -- [in] The initialization configuration. Returns ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_ERR_INVALID_ARG if radio or host connection mode not supported ESP_ERR_INVALID_STATE if already initialized ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_ERR_INVALID_ARG if radio or host connection mode not supported ESP_ERR_INVALID_STATE if already initialized ESP_OK on success Parameters init_config -- [in] The initialization configuration. Returns ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_ERR_INVALID_ARG if radio or host connection mode not supported ESP_ERR_INVALID_STATE if already initialized esp_err_t esp_openthread_auto_start(otOperationalDatasetTlvs *datasetTlvs) Starts the Thread protocol operation and attaches to a Thread network. Parameters datasetTlvs -- [in] The operational dataset (TLV encoded), if it's NULL, the function will generate the dataset based on the configurations from kconfig. Returns ESP_OK on success ESP_FAIL on failures ESP_OK on success ESP_FAIL on failures ESP_OK on success Parameters datasetTlvs -- [in] The operational dataset (TLV encoded), if it's NULL, the function will generate the dataset based on the configurations from kconfig. Returns ESP_OK on success ESP_FAIL on failures esp_err_t esp_openthread_launch_mainloop(void) Launches the OpenThread main loop. Note This function will not return unless error happens when running the OpenThread stack. Returns ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_FAIL on other failures ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_FAIL on other failures ESP_OK on success Returns ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_FAIL on other failures esp_err_t esp_openthread_deinit(void) This function performs OpenThread stack and platform driver deinitialization. Returns ESP_OK on success ESP_ERR_INVALID_STATE if not initialized ESP_OK on success ESP_ERR_INVALID_STATE if not initialized ESP_OK on success Returns ESP_OK on success ESP_ERR_INVALID_STATE if not initialized otInstance *esp_openthread_get_instance(void) This function acquires the underlying OpenThread instance. Note This function can be called on other tasks without lock. Returns The OpenThread instance pointer Returns The OpenThread instance pointer Header File This header file can be included with: #include "esp_openthread_types.h" This header file is a part of the API provided by the openthread component. To declare that your component depends on openthread , add the following to your CMakeLists.txt: REQUIRES openthread or PRIV_REQUIRES openthread Structures struct esp_openthread_role_changed_event_t OpenThread role changed event data. struct esp_openthread_mainloop_context_t This structure represents a context for a select() based mainloop. struct esp_openthread_uart_config_t The uart port config for OpenThread. Public Members uart_port_t port UART port number uart_port_t port UART port number uart_config_t uart_config UART configuration, see uart_config_t docs uart_config_t uart_config UART configuration, see uart_config_t docs gpio_num_t rx_pin UART RX pin gpio_num_t rx_pin UART RX pin gpio_num_t tx_pin UART TX pin gpio_num_t tx_pin UART TX pin uart_port_t port struct esp_openthread_spi_host_config_t The spi port config for OpenThread. Public Members spi_host_device_t host_device SPI host device spi_host_device_t host_device SPI host device spi_dma_chan_t dma_channel DMA channel spi_dma_chan_t dma_channel DMA channel spi_bus_config_t spi_interface SPI bus spi_bus_config_t spi_interface SPI bus spi_device_interface_config_t spi_device SPI peripheral device spi_device_interface_config_t spi_device SPI peripheral device gpio_num_t intr_pin SPI interrupt pin gpio_num_t intr_pin SPI interrupt pin spi_host_device_t host_device struct esp_openthread_spi_slave_config_t The spi slave config for OpenThread. Public Members spi_host_device_t host_device SPI host device spi_host_device_t host_device SPI host device spi_bus_config_t bus_config SPI bus config spi_bus_config_t bus_config SPI bus config spi_slave_interface_config_t slave_config SPI slave config spi_slave_interface_config_t slave_config SPI slave config gpio_num_t intr_pin SPI interrupt pin gpio_num_t intr_pin SPI interrupt pin spi_host_device_t host_device struct esp_openthread_radio_config_t The OpenThread radio configuration. Public Members esp_openthread_radio_mode_t radio_mode The radio mode esp_openthread_radio_mode_t radio_mode The radio mode esp_openthread_uart_config_t radio_uart_config The uart configuration to RCP esp_openthread_uart_config_t radio_uart_config The uart configuration to RCP esp_openthread_spi_host_config_t radio_spi_config The spi configuration to RCP esp_openthread_spi_host_config_t radio_spi_config The spi configuration to RCP esp_openthread_radio_mode_t radio_mode struct esp_openthread_host_connection_config_t The OpenThread host connection configuration. Public Members esp_openthread_host_connection_mode_t host_connection_mode The host connection mode esp_openthread_host_connection_mode_t host_connection_mode The host connection mode esp_openthread_uart_config_t host_uart_config The uart configuration to host esp_openthread_uart_config_t host_uart_config The uart configuration to host usb_serial_jtag_driver_config_t host_usb_config The usb configuration to host usb_serial_jtag_driver_config_t host_usb_config The usb configuration to host esp_openthread_spi_slave_config_t spi_slave_config The spi configuration to host esp_openthread_spi_slave_config_t spi_slave_config The spi configuration to host esp_openthread_host_connection_mode_t host_connection_mode struct esp_openthread_port_config_t The OpenThread port specific configuration. struct esp_openthread_platform_config_t The OpenThread platform configuration. Public Members esp_openthread_radio_config_t radio_config The radio configuration esp_openthread_radio_config_t radio_config The radio configuration esp_openthread_host_connection_config_t host_config The host connection configuration esp_openthread_host_connection_config_t host_config The host connection configuration esp_openthread_port_config_t port_config The port configuration esp_openthread_port_config_t port_config The port configuration esp_openthread_radio_config_t radio_config Type Definitions typedef void (*esp_openthread_rcp_failure_handler)(void) Enumerations enum esp_openthread_event_t OpenThread event declarations. Values: enumerator OPENTHREAD_EVENT_START OpenThread stack start enumerator OPENTHREAD_EVENT_START OpenThread stack start enumerator OPENTHREAD_EVENT_STOP OpenThread stack stop enumerator OPENTHREAD_EVENT_STOP OpenThread stack stop enumerator OPENTHREAD_EVENT_DETACHED OpenThread detached enumerator OPENTHREAD_EVENT_DETACHED OpenThread detached enumerator OPENTHREAD_EVENT_ATTACHED OpenThread attached enumerator OPENTHREAD_EVENT_ATTACHED OpenThread attached enumerator OPENTHREAD_EVENT_ROLE_CHANGED OpenThread role changed enumerator OPENTHREAD_EVENT_ROLE_CHANGED OpenThread role changed enumerator OPENTHREAD_EVENT_IF_UP OpenThread network interface up enumerator OPENTHREAD_EVENT_IF_UP OpenThread network interface up enumerator OPENTHREAD_EVENT_IF_DOWN OpenThread network interface down enumerator OPENTHREAD_EVENT_IF_DOWN OpenThread network interface down enumerator OPENTHREAD_EVENT_GOT_IP6 OpenThread stack added IPv6 address enumerator OPENTHREAD_EVENT_GOT_IP6 OpenThread stack added IPv6 address enumerator OPENTHREAD_EVENT_LOST_IP6 OpenThread stack removed IPv6 address enumerator OPENTHREAD_EVENT_LOST_IP6 OpenThread stack removed IPv6 address enumerator OPENTHREAD_EVENT_MULTICAST_GROUP_JOIN OpenThread stack joined IPv6 multicast group enumerator OPENTHREAD_EVENT_MULTICAST_GROUP_JOIN OpenThread stack joined IPv6 multicast group enumerator OPENTHREAD_EVENT_MULTICAST_GROUP_LEAVE OpenThread stack left IPv6 multicast group enumerator OPENTHREAD_EVENT_MULTICAST_GROUP_LEAVE OpenThread stack left IPv6 multicast group enumerator OPENTHREAD_EVENT_TREL_ADD_IP6 OpenThread stack added TREL IPv6 address enumerator OPENTHREAD_EVENT_TREL_ADD_IP6 OpenThread stack added TREL IPv6 address enumerator OPENTHREAD_EVENT_TREL_REMOVE_IP6 OpenThread stack removed TREL IPv6 address enumerator OPENTHREAD_EVENT_TREL_REMOVE_IP6 OpenThread stack removed TREL IPv6 address enumerator OPENTHREAD_EVENT_TREL_MULTICAST_GROUP_JOIN OpenThread stack joined TREL IPv6 multicast group enumerator OPENTHREAD_EVENT_TREL_MULTICAST_GROUP_JOIN OpenThread stack joined TREL IPv6 multicast group enumerator OPENTHREAD_EVENT_SET_DNS_SERVER OpenThread stack set DNS server > enumerator OPENTHREAD_EVENT_SET_DNS_SERVER OpenThread stack set DNS server > enumerator OPENTHREAD_EVENT_START enum esp_openthread_radio_mode_t The radio mode of OpenThread. Values: enumerator RADIO_MODE_NATIVE Use the native 15.4 radio enumerator RADIO_MODE_NATIVE Use the native 15.4 radio enumerator RADIO_MODE_UART_RCP UART connection to a 15.4 capable radio co-processor (RCP) enumerator RADIO_MODE_UART_RCP UART connection to a 15.4 capable radio co-processor (RCP) enumerator RADIO_MODE_SPI_RCP SPI connection to a 15.4 capable radio co-processor (RCP) enumerator RADIO_MODE_SPI_RCP SPI connection to a 15.4 capable radio co-processor (RCP) enumerator RADIO_MODE_MAX Using for parameter check enumerator RADIO_MODE_MAX Using for parameter check enumerator RADIO_MODE_NATIVE enum esp_openthread_host_connection_mode_t How OpenThread connects to the host. Values: enumerator HOST_CONNECTION_MODE_NONE Disable host connection enumerator HOST_CONNECTION_MODE_NONE Disable host connection enumerator HOST_CONNECTION_MODE_CLI_UART CLI UART connection to the host enumerator HOST_CONNECTION_MODE_CLI_UART CLI UART connection to the host enumerator HOST_CONNECTION_MODE_CLI_USB CLI USB connection to the host enumerator HOST_CONNECTION_MODE_CLI_USB CLI USB connection to the host enumerator HOST_CONNECTION_MODE_RCP_UART RCP UART connection to the host enumerator HOST_CONNECTION_MODE_RCP_UART RCP UART connection to the host enumerator HOST_CONNECTION_MODE_RCP_SPI RCP SPI connection to the host enumerator HOST_CONNECTION_MODE_RCP_SPI RCP SPI connection to the host enumerator HOST_CONNECTION_MODE_MAX Using for parameter check enumerator HOST_CONNECTION_MODE_MAX Using for parameter check enumerator HOST_CONNECTION_MODE_NONE Header File This header file can be included with: #include "esp_openthread_lock.h" This header file is a part of the API provided by the openthread component. To declare that your component depends on openthread , add the following to your CMakeLists.txt: REQUIRES openthread or PRIV_REQUIRES openthread Functions esp_err_t esp_openthread_lock_init(void) This function initializes the OpenThread API lock. Returns ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_ERR_INVALID_STATE if already initialized ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_ERR_INVALID_STATE if already initialized ESP_OK on success Returns ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_ERR_INVALID_STATE if already initialized void esp_openthread_lock_deinit(void) This function deinitializes the OpenThread API lock. bool esp_openthread_lock_acquire(TickType_t block_ticks) This function acquires the OpenThread API lock. Note Every OT APIs that takes an otInstance argument MUST be protected with this API lock except that the call site is in OT callbacks. Parameters block_ticks -- [in] The maxinum number of RTOS ticks to wait for the lock. Returns True on lock acquired False on failing to acquire the lock with the timeout. True on lock acquired False on failing to acquire the lock with the timeout. True on lock acquired Parameters block_ticks -- [in] The maxinum number of RTOS ticks to wait for the lock. Returns True on lock acquired False on failing to acquire the lock with the timeout. void esp_openthread_lock_release(void) This function releases the OpenThread API lock. bool esp_openthread_task_switching_lock_acquire(TickType_t block_ticks) This function acquires the OpenThread API task switching lock. Note In OpenThread API context, it waits for some actions to be done in other tasks (like lwip), after task switching, it needs to call OpenThread API again. Normally it's not allowed, since the previous OpenThread API lock is not released yet. This task_switching lock allows the OpenThread API can be called in this case. Note Please use esp_openthread_lock_acquire() for normal cases. Parameters block_ticks -- [in] The maxinum number of RTOS ticks to wait for the lock. Returns True on lock acquired False on failing to acquire the lock with the timeout. True on lock acquired False on failing to acquire the lock with the timeout. True on lock acquired Parameters block_ticks -- [in] The maxinum number of RTOS ticks to wait for the lock. Returns True on lock acquired False on failing to acquire the lock with the timeout. void esp_openthread_task_switching_lock_release(void) This function releases the OpenThread API task switching lock. Header File This header file can be included with: #include "esp_openthread_netif_glue.h" This header file is a part of the API provided by the openthread component. To declare that your component depends on openthread , add the following to your CMakeLists.txt: REQUIRES openthread or PRIV_REQUIRES openthread Functions void *esp_openthread_netif_glue_init(const esp_openthread_platform_config_t *config) This function initializes the OpenThread network interface glue. Parameters config -- [in] The platform configuration. Returns glue pointer on success NULL on failure glue pointer on success NULL on failure glue pointer on success Parameters config -- [in] The platform configuration. Returns glue pointer on success NULL on failure void esp_openthread_netif_glue_deinit(void) This function deinitializes the OpenThread network interface glue. esp_netif_t *esp_openthread_get_netif(void) This function acquires the OpenThread netif. Returns The OpenThread netif or NULL if not initialzied. Returns The OpenThread netif or NULL if not initialzied. Macros ESP_NETIF_INHERENT_DEFAULT_OPENTHREAD() Default configuration reference of OT esp-netif. ESP_NETIF_DEFAULT_OPENTHREAD() Header File components/openthread/include/esp_openthread_border_router.h This header file can be included with: #include "esp_openthread_border_router.h" This header file is a part of the API provided by the openthread component. To declare that your component depends on openthread , add the following to your CMakeLists.txt: REQUIRES openthread or PRIV_REQUIRES openthread Functions void esp_openthread_set_backbone_netif(esp_netif_t *backbone_netif) Sets the backbone interface used for border routing. Note This function must be called before esp_openthread_init Parameters backbone_netif -- [in] The backbone network interface (WiFi or ethernet) Parameters backbone_netif -- [in] The backbone network interface (WiFi or ethernet) esp_err_t esp_openthread_border_router_init(void) Initializes the border router features of OpenThread. Note Calling this function will make the device behave as an OpenThread border router. Kconfig option CONFIG_OPENTHREAD_BORDER_ROUTER is required. Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if feature not supported ESP_ERR_INVALID_STATE if already initialized ESP_FIAL on other failures ESP_OK on success ESP_ERR_NOT_SUPPORTED if feature not supported ESP_ERR_INVALID_STATE if already initialized ESP_FIAL on other failures ESP_OK on success Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if feature not supported ESP_ERR_INVALID_STATE if already initialized ESP_FIAL on other failures esp_err_t esp_openthread_border_router_deinit(void) Deinitializes the border router features of OpenThread. Returns ESP_OK on success ESP_ERR_INVALID_STATE if not initialized ESP_FIAL on other failures ESP_OK on success ESP_ERR_INVALID_STATE if not initialized ESP_FIAL on other failures ESP_OK on success Returns ESP_OK on success ESP_ERR_INVALID_STATE if not initialized ESP_FIAL on other failures esp_netif_t *esp_openthread_get_backbone_netif(void) Gets the backbone interface of OpenThread border router. Returns The backbone interface or NULL if border router not initialized. Returns The backbone interface or NULL if border router not initialized. void esp_openthread_register_rcp_failure_handler(esp_openthread_rcp_failure_handler handler) Registers the callback for RCP failure. esp_err_t esp_openthread_rcp_deinit(void) Deinitializes the conneciton to RCP. Returns ESP_OK on success ESP_ERR_INVALID_STATE if fail to deinitialize RCP ESP_OK on success ESP_ERR_INVALID_STATE if fail to deinitialize RCP ESP_OK on success Returns ESP_OK on success ESP_ERR_INVALID_STATE if fail to deinitialize RCP
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 openthread directory of ESP-IDF examples contains the following applications: The OpenThread interactive shell openthread/ot_cli The Thread Border Router openthread/ot_br The Thread Radio Co-Processor 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. Header File This header file can be included with: #include "esp_openthread.h" This header file is a part of the API provided by the openthreadcomponent. To declare that your component depends on openthread, add the following to your CMakeLists.txt: REQUIRES openthread or PRIV_REQUIRES openthread Functions - esp_err_t esp_openthread_init(const esp_openthread_platform_config_t *init_config) Initializes the full OpenThread stack. Note The OpenThread instance will also be initialized in this function. - Parameters init_config -- [in] The initialization configuration. - Returns ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_ERR_INVALID_ARG if radio or host connection mode not supported ESP_ERR_INVALID_STATE if already initialized - - esp_err_t esp_openthread_auto_start(otOperationalDatasetTlvs *datasetTlvs) Starts the Thread protocol operation and attaches to a Thread network. - Parameters datasetTlvs -- [in] The operational dataset (TLV encoded), if it's NULL, the function will generate the dataset based on the configurations from kconfig. - Returns ESP_OK on success ESP_FAIL on failures - - esp_err_t esp_openthread_launch_mainloop(void) Launches the OpenThread main loop. Note This function will not return unless error happens when running the OpenThread stack. - Returns ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_FAIL on other failures - - esp_err_t esp_openthread_deinit(void) This function performs OpenThread stack and platform driver deinitialization. - Returns ESP_OK on success ESP_ERR_INVALID_STATE if not initialized - - otInstance *esp_openthread_get_instance(void) This function acquires the underlying OpenThread instance. Note This function can be called on other tasks without lock. - Returns The OpenThread instance pointer Header File This header file can be included with: #include "esp_openthread_types.h" This header file is a part of the API provided by the openthreadcomponent. To declare that your component depends on openthread, add the following to your CMakeLists.txt: REQUIRES openthread or PRIV_REQUIRES openthread Structures - struct esp_openthread_role_changed_event_t OpenThread role changed event data. - struct esp_openthread_mainloop_context_t This structure represents a context for a select() based mainloop. - struct esp_openthread_uart_config_t The uart port config for OpenThread. Public Members - uart_port_t port UART port number - uart_config_t uart_config UART configuration, see uart_config_t docs - gpio_num_t rx_pin UART RX pin - gpio_num_t tx_pin UART TX pin - uart_port_t port - struct esp_openthread_spi_host_config_t The spi port config for OpenThread. Public Members - spi_host_device_t host_device SPI host device - spi_dma_chan_t dma_channel DMA channel - spi_bus_config_t spi_interface SPI bus - spi_device_interface_config_t spi_device SPI peripheral device - gpio_num_t intr_pin SPI interrupt pin - spi_host_device_t host_device - struct esp_openthread_spi_slave_config_t The spi slave config for OpenThread. Public Members - spi_host_device_t host_device SPI host device - spi_bus_config_t bus_config SPI bus config - spi_slave_interface_config_t slave_config SPI slave config - gpio_num_t intr_pin SPI interrupt pin - spi_host_device_t host_device - struct esp_openthread_radio_config_t The OpenThread radio configuration. Public Members - esp_openthread_radio_mode_t radio_mode The radio mode - esp_openthread_uart_config_t radio_uart_config The uart configuration to RCP - esp_openthread_spi_host_config_t radio_spi_config The spi configuration to RCP - esp_openthread_radio_mode_t radio_mode - struct esp_openthread_host_connection_config_t The OpenThread host connection configuration. Public Members - esp_openthread_host_connection_mode_t host_connection_mode The host connection mode - esp_openthread_uart_config_t host_uart_config The uart configuration to host - usb_serial_jtag_driver_config_t host_usb_config The usb configuration to host - esp_openthread_spi_slave_config_t spi_slave_config The spi configuration to host - esp_openthread_host_connection_mode_t host_connection_mode - struct esp_openthread_port_config_t The OpenThread port specific configuration. - struct esp_openthread_platform_config_t The OpenThread platform configuration. Public Members - esp_openthread_radio_config_t radio_config The radio configuration - esp_openthread_host_connection_config_t host_config The host connection configuration - esp_openthread_port_config_t port_config The port configuration - esp_openthread_radio_config_t radio_config Type Definitions - typedef void (*esp_openthread_rcp_failure_handler)(void) Enumerations - enum esp_openthread_event_t OpenThread event declarations. Values: - enumerator OPENTHREAD_EVENT_START OpenThread stack start - enumerator OPENTHREAD_EVENT_STOP OpenThread stack stop - enumerator OPENTHREAD_EVENT_DETACHED OpenThread detached - enumerator OPENTHREAD_EVENT_ATTACHED OpenThread attached - enumerator OPENTHREAD_EVENT_ROLE_CHANGED OpenThread role changed - enumerator OPENTHREAD_EVENT_IF_UP OpenThread network interface up - enumerator OPENTHREAD_EVENT_IF_DOWN OpenThread network interface down - enumerator OPENTHREAD_EVENT_GOT_IP6 OpenThread stack added IPv6 address - enumerator OPENTHREAD_EVENT_LOST_IP6 OpenThread stack removed IPv6 address - enumerator OPENTHREAD_EVENT_MULTICAST_GROUP_JOIN OpenThread stack joined IPv6 multicast group - enumerator OPENTHREAD_EVENT_MULTICAST_GROUP_LEAVE OpenThread stack left IPv6 multicast group - enumerator OPENTHREAD_EVENT_TREL_ADD_IP6 OpenThread stack added TREL IPv6 address - enumerator OPENTHREAD_EVENT_TREL_REMOVE_IP6 OpenThread stack removed TREL IPv6 address - enumerator OPENTHREAD_EVENT_TREL_MULTICAST_GROUP_JOIN OpenThread stack joined TREL IPv6 multicast group - enumerator OPENTHREAD_EVENT_SET_DNS_SERVER OpenThread stack set DNS server > - enumerator OPENTHREAD_EVENT_START - enum esp_openthread_radio_mode_t The radio mode of OpenThread. Values: - enumerator RADIO_MODE_NATIVE Use the native 15.4 radio - enumerator RADIO_MODE_UART_RCP UART connection to a 15.4 capable radio co-processor (RCP) - enumerator RADIO_MODE_SPI_RCP SPI connection to a 15.4 capable radio co-processor (RCP) - enumerator RADIO_MODE_MAX Using for parameter check - enumerator RADIO_MODE_NATIVE - enum esp_openthread_host_connection_mode_t How OpenThread connects to the host. Values: - enumerator HOST_CONNECTION_MODE_NONE Disable host connection - enumerator HOST_CONNECTION_MODE_CLI_UART CLI UART connection to the host - enumerator HOST_CONNECTION_MODE_CLI_USB CLI USB connection to the host - enumerator HOST_CONNECTION_MODE_RCP_UART RCP UART connection to the host - enumerator HOST_CONNECTION_MODE_RCP_SPI RCP SPI connection to the host - enumerator HOST_CONNECTION_MODE_MAX Using for parameter check - enumerator HOST_CONNECTION_MODE_NONE Header File This header file can be included with: #include "esp_openthread_lock.h" This header file is a part of the API provided by the openthreadcomponent. To declare that your component depends on openthread, add the following to your CMakeLists.txt: REQUIRES openthread or PRIV_REQUIRES openthread Functions - esp_err_t esp_openthread_lock_init(void) This function initializes the OpenThread API lock. - Returns ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_ERR_INVALID_STATE if already initialized - - void esp_openthread_lock_deinit(void) This function deinitializes the OpenThread API lock. - bool esp_openthread_lock_acquire(TickType_t block_ticks) This function acquires the OpenThread API lock. Note Every OT APIs that takes an otInstance argument MUST be protected with this API lock except that the call site is in OT callbacks. - Parameters block_ticks -- [in] The maxinum number of RTOS ticks to wait for the lock. - Returns True on lock acquired False on failing to acquire the lock with the timeout. - - void esp_openthread_lock_release(void) This function releases the OpenThread API lock. - bool esp_openthread_task_switching_lock_acquire(TickType_t block_ticks) This function acquires the OpenThread API task switching lock. Note In OpenThread API context, it waits for some actions to be done in other tasks (like lwip), after task switching, it needs to call OpenThread API again. Normally it's not allowed, since the previous OpenThread API lock is not released yet. This task_switching lock allows the OpenThread API can be called in this case. Note Please use esp_openthread_lock_acquire() for normal cases. - Parameters block_ticks -- [in] The maxinum number of RTOS ticks to wait for the lock. - Returns True on lock acquired False on failing to acquire the lock with the timeout. - - void esp_openthread_task_switching_lock_release(void) This function releases the OpenThread API task switching lock. Header File This header file can be included with: #include "esp_openthread_netif_glue.h" This header file is a part of the API provided by the openthreadcomponent. To declare that your component depends on openthread, add the following to your CMakeLists.txt: REQUIRES openthread or PRIV_REQUIRES openthread Functions - void *esp_openthread_netif_glue_init(const esp_openthread_platform_config_t *config) This function initializes the OpenThread network interface glue. - Parameters config -- [in] The platform configuration. - Returns glue pointer on success NULL on failure - - void esp_openthread_netif_glue_deinit(void) This function deinitializes the OpenThread network interface glue. - esp_netif_t *esp_openthread_get_netif(void) This function acquires the OpenThread netif. - Returns The OpenThread netif or NULL if not initialzied. Macros - ESP_NETIF_INHERENT_DEFAULT_OPENTHREAD() Default configuration reference of OT esp-netif. - ESP_NETIF_DEFAULT_OPENTHREAD() Header File components/openthread/include/esp_openthread_border_router.h This header file can be included with: #include "esp_openthread_border_router.h" This header file is a part of the API provided by the openthreadcomponent. To declare that your component depends on openthread, add the following to your CMakeLists.txt: REQUIRES openthread or PRIV_REQUIRES openthread Functions - void esp_openthread_set_backbone_netif(esp_netif_t *backbone_netif) Sets the backbone interface used for border routing. Note This function must be called before esp_openthread_init - Parameters backbone_netif -- [in] The backbone network interface (WiFi or ethernet) - esp_err_t esp_openthread_border_router_init(void) Initializes the border router features of OpenThread. Note Calling this function will make the device behave as an OpenThread border router. Kconfig option CONFIG_OPENTHREAD_BORDER_ROUTER is required. - Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if feature not supported ESP_ERR_INVALID_STATE if already initialized ESP_FIAL on other failures - - esp_err_t esp_openthread_border_router_deinit(void) Deinitializes the border router features of OpenThread. - Returns ESP_OK on success ESP_ERR_INVALID_STATE if not initialized ESP_FIAL on other failures - - esp_netif_t *esp_openthread_get_backbone_netif(void) Gets the backbone interface of OpenThread border router. - Returns The backbone interface or NULL if border router not initialized. - void esp_openthread_register_rcp_failure_handler(esp_openthread_rcp_failure_handler handler) Registers the callback for RCP failure. - esp_err_t esp_openthread_rcp_deinit(void) Deinitializes the conneciton to RCP. - Returns ESP_OK on success ESP_ERR_INVALID_STATE if fail to deinitialize RCP -
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/network/esp_openthread.html
ESP-IDF Programming Guide v5.2.1 documentation
null
ESP-NETIF
null
espressif.com
2016-01-01
b204fc5bf01399c2
null
null
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 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. ESP-NETIF Architecture | (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_transmit |--<------| netif_output | | | | | | | | | | | |--->----|---| esp_netif_receive |-->------| netif_input | | | | | | | + ----------------+ | | |...<....|...| esp_netif_free_rx_buffer |...<.....| packet buffer | +-----| | | | | | | | | | | | | (D) | (B) | | | | (C) | +-----------------------+ --------+ | | +===========================+ COMMUNICATION | | NETWORK STACK DRIVER | | ESP-NETIF | | +------------------+ | | +---------------------------+.........| open/close | | | | | | | | -<--| l2tap_write |-----<---| write | | | | | | ---->--| esp_vfs_l2tap_eth_filter |----->---| read | | | | | | (E) | +------------------+ +---------------------------+ USER CODE ESP-NETIF L2 TAP Data and Event Flow in the Diagram ........ Initialization line from user code to ESP-NETIF and communication driver --<--->-- Data packets going from communication media to TCP/IP stack and back ******** Events aggregated in ESP-NETIF propagate to the driver, user code, and network stack | User settings and runtime configuration 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: Initialization code Initializes IO driver Creates a new instance of ESP-NETIF and configure it with ESP-NETIF specific options (flags, behavior, name) Network stack options (netif init and input functions, not publicly available) IO driver specific options (transmit, free rx buffer functions, IO driver handle) Attaches the IO driver handle to the ESP-NETIF instance created in the above steps Configures event handlers Use default handlers for common interfaces defined in IO drivers; or define a specific handler for customized behavior or new interfaces Register handlers for app-related events (such as IP lost or acquired) Interaction with network interfaces using ESP-NETIF API Gets and sets TCP/IP-related parameters (DHCP, IP, etc) Receives IP events (connect or disconnect) 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: Event handlers: Defines behavior patterns of interaction with ESP-NETIF (e.g., ethernet link-up -> turn netif on) Glue IO layer: Adapts the input or output functions to use ESP-NETIF transmit, receive, and free receive buffer Installs driver_transmit to the appropriate ESP-NETIF object so that outgoing packets from the network stack are passed to the IO driver Calls esp_netif_receive() to pass incoming data to the network stack 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: Initialization APIs (to create and configure ESP-NETIF instance) Input or Output API (for passing data between IO driver and network stack) Event or Action API Used for network interface lifecycle management ESP-NETIF provides building blocks for designing event handlers Setters and Getters API for basic network interface properties Network stack abstraction API: enabling user interaction with TCP/IP stack Set interface up or down DHCP server and client API DNS API 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. 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 Virtual Filesystem Component. 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. 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 CONFIG_ESP_NETIF_L2_TAP first and then registered by esp_vfs_l2tap_intf_register() prior usage of any VFS function. open()  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 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()  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. The following configuration options are available to do so: L2TAP_S_INTF_DEVICE - bounds the file descriptor to a specific Network Interface that is identified by its if_key . ESP-NETIF Network Interface if_key is passed to ioctl() as the third parameter. Note that default Network Interfaces if_key 's used in ESP-IDF can be found in esp_netif/include/esp_netif_defaults.h. L2TAP_S_DEVICE_DRV_HNDL - is another way to bound the file descriptor to a specific Network Interface. In this case, the Network interface is identified directly by IO Driver handle (e.g., esp_eth_handle_t in case of Ethernet). The IO Driver handle is passed to ioctl() as the third parameter. L2TAP_S_RCV_FILTER - sets the filter to frames with the type to be passed to the file descriptor. In the case of Ethernet frames, the frames are to be filtered based on the Length and Ethernet type field. In case the filter value is set less than or equal to 0x05DC, the Ethernet type field is considered to represent IEEE802.3 Length Field, and all frames with values in interval <0, 0x05DC> at that field are passed to the file descriptor. The IEEE802.2 logical link control (LLC) resolution is then expected to be performed by the user's application. In case the filter value is set greater than 0x05DC, the Ethernet type field is considered to represent protocol identification and only frames that are equal to the set value are to be passed to the file descriptor. 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. ioctl() returns 0. On error, -1 is returned, and errno is set to indicate the error. fcntl()  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: F_GETFD - the function returns the file descriptor flags, and the third argument is ignored. F_SETFD - sets the file descriptor flags to the value specified by the third argument. Zero is returned. ioctl() returns 0. On error, -1 is returned, and errno is set to indicate the error. read()  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. 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 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). 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. O_NONBLOCK ), and the read would block. write()  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: Destination MAC Source MAC Type/Length Payload (protocol header/data) 6 B 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. 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. 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. close()  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. The first's task read operation then ends with an error. close() returns zero. On error, -1 is returned, and errno is set to indicate the error. select()  select()  Select is used in a standard way, just CONFIG_VFS_SUPPORT_SELECT needs to be enabled to make the select() function available. SNTP API You can find a brief introduction to SNTP in general, its initialization code, and basic modes in Section SNTP Time Synchronization in 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: Initialize and configure the service using esp_netif_sntp_init() . Start the service via esp_netif_sntp_start() . 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. Wait for the system time to synchronize using esp_netif_sntp_sync_wait() (only if needed). Stop and destroy the service using 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: 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 CONFIG_LWIP_SNTP_MAX_SERVERS. Use DHCP-Obtained SNTP Server(s) First of all, we have to enable the lwIP configuration option CONFIG_LWIP_DHCP_GET_NTP_SRV. Then we have to initialize the SNTP module with the DHCP option and without the NTP server: 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: 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. 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). 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.ip_event_to_renew = IP_EVENT_STA_GOT_IP; // IP event on which we refresh the configuration Then we start the service normally with esp_netif_sntp_start() . ESP-NETIF Programmer's Manual Please refer to the following example to understand the initialization process of the default interface: Wi-Fi Station: wifi/getting_started/station/main/station_example_main.c Wi-Fi Access Point: wifi/getting_started/softAP/main/softap_example_main.c For more specific cases, please consult this guide: ESP-NETIF Custom I/O Driver. 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: 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: The created object has to be destroyed if a network de-initialization is provided by an application using esp_netif_destroy_default_wifi() . These default interfaces must not be created multiple times unless the created handle is deleted using esp_netif_destroy() . When using Wi-Fi in AP+STA mode, both these interfaces have to be created. API Reference Header File This header file can be included with: #include "esp_netif.h" This header file is a part of the API provided by the esp_netif component. To declare that your component depends on esp_netif , add the following to your CMakeLists.txt: REQUIRES esp_netif or PRIV_REQUIRES esp_netif Functions esp_err_t esp_netif_init(void) Initialize the underlying TCP/IP stack. Note This function should be called exactly once from application code, when the application starts up. Returns ESP_OK on success ESP_FAIL if initializing failed ESP_OK on success ESP_FAIL if initializing failed ESP_OK on success Returns ESP_OK on success ESP_FAIL if initializing failed esp_err_t esp_netif_deinit(void) Deinitialize the esp-netif component (and the underlying TCP/IP stack) Note: Deinitialization is not supported yet Returns ESP_ERR_INVALID_STATE if esp_netif not initialized ESP_ERR_NOT_SUPPORTED otherwise ESP_ERR_INVALID_STATE if esp_netif not initialized ESP_ERR_NOT_SUPPORTED otherwise ESP_ERR_INVALID_STATE if esp_netif not initialized Returns ESP_ERR_INVALID_STATE if esp_netif not initialized ESP_ERR_NOT_SUPPORTED otherwise esp_netif_t *esp_netif_new(const esp_netif_config_t *esp_netif_config) Creates an instance of new esp-netif object based on provided config. Parameters esp_netif_config -- [in] pointer esp-netif configuration Returns pointer to esp-netif object on success NULL otherwise pointer to esp-netif object on success NULL otherwise pointer to esp-netif object on success Parameters esp_netif_config -- [in] pointer esp-netif configuration Returns pointer to esp-netif object on success NULL otherwise void esp_netif_destroy(esp_netif_t *esp_netif) Destroys the esp_netif object. Parameters esp_netif -- [in] pointer to the object to be deleted Parameters esp_netif -- [in] pointer to the object to be deleted esp_err_t esp_netif_set_driver_config(esp_netif_t *esp_netif, const esp_netif_driver_ifconfig_t *driver_config) Configures driver related options of esp_netif object. Parameters esp_netif -- [inout] pointer to the object to be configured driver_config -- [in] pointer esp-netif io driver related configuration esp_netif -- [inout] pointer to the object to be configured driver_config -- [in] pointer esp-netif io driver related configuration esp_netif -- [inout] pointer to the object to be configured Returns ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS if invalid parameters provided ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS if invalid parameters provided ESP_OK on success Parameters esp_netif -- [inout] pointer to the object to be configured driver_config -- [in] pointer esp-netif io driver related configuration Returns ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS if invalid parameters provided esp_err_t esp_netif_attach(esp_netif_t *esp_netif, esp_netif_iodriver_handle driver_handle) Attaches esp_netif instance to the io driver handle. Calling this function enables connecting specific esp_netif object with already initialized io driver to update esp_netif object with driver specific configuration (i.e. calls post_attach callback, which typically sets io driver callbacks to esp_netif instance and starts the driver) Parameters esp_netif -- [inout] pointer to esp_netif object to be attached driver_handle -- [in] pointer to the driver handle esp_netif -- [inout] pointer to esp_netif object to be attached driver_handle -- [in] pointer to the driver handle esp_netif -- [inout] pointer to esp_netif object to be attached Returns ESP_OK on success ESP_ERR_ESP_NETIF_DRIVER_ATTACH_FAILED if driver's pot_attach callback failed ESP_OK on success ESP_ERR_ESP_NETIF_DRIVER_ATTACH_FAILED if driver's pot_attach callback failed ESP_OK on success Parameters esp_netif -- [inout] pointer to esp_netif object to be attached driver_handle -- [in] pointer to the driver handle Returns ESP_OK on success ESP_ERR_ESP_NETIF_DRIVER_ATTACH_FAILED if driver's pot_attach callback failed esp_err_t esp_netif_receive(esp_netif_t *esp_netif, void *buffer, size_t len, void *eb) Passes the raw packets from communication media to the appropriate TCP/IP stack. This function is called from the configured (peripheral) driver layer. The data are then forwarded as frames to the TCP/IP stack. Parameters esp_netif -- [in] Handle to esp-netif instance buffer -- [in] Received data len -- [in] Length of the data frame eb -- [in] Pointer to internal buffer (used in Wi-Fi driver) esp_netif -- [in] Handle to esp-netif instance buffer -- [in] Received data len -- [in] Length of the data frame eb -- [in] Pointer to internal buffer (used in Wi-Fi driver) esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_OK ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance buffer -- [in] Received data len -- [in] Length of the data frame eb -- [in] Pointer to internal buffer (used in Wi-Fi driver) Returns ESP_OK void esp_netif_action_start(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IO driver start event Creates network interface, if AUTOUP enabled turns the interface on, if DHCPS enabled starts dhcp server. Note This API can be directly used as event handler Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event void esp_netif_action_stop(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IO driver stop event. Note This API can be directly used as event handler Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event void esp_netif_action_connected(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IO driver connected event. Note This API can be directly used as event handler Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event void esp_netif_action_disconnected(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IO driver disconnected event. Note This API can be directly used as event handler Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event void esp_netif_action_got_ip(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon network got IP event. Note This API can be directly used as event handler Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event void esp_netif_action_join_ip6_multicast_group(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IPv6 multicast group join. Note This API can be directly used as event handler Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event void esp_netif_action_leave_ip6_multicast_group(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IPv6 multicast group leave. Note This API can be directly used as event handler Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event void esp_netif_action_add_ip6_address(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IPv6 address added by the underlying stack. Note This API can be directly used as event handler Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event void esp_netif_action_remove_ip6_address(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IPv6 address removed by the underlying stack. Note This API can be directly used as event handler Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_netif -- [in] Handle to esp-netif instance Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event esp_err_t esp_netif_set_default_netif(esp_netif_t *esp_netif) Manual configuration of the default netif. This API overrides the automatic configuration of the default interface based on the route_prio If the selected netif is set default using this API, no other interface could be set-default disregarding its route_prio number (unless the selected netif gets destroyed) Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK on success Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK on success esp_netif_t *esp_netif_get_default_netif(void) Getter function of the default netif. This API returns the selected default netif. Returns Handle to esp-netif instance of the default netif. Returns Handle to esp-netif instance of the default netif. esp_err_t esp_netif_join_ip6_multicast_group(esp_netif_t *esp_netif, const esp_ip6_addr_t *addr) Cause the TCP/IP stack to join a IPv6 multicast group. Parameters esp_netif -- [in] Handle to esp-netif instance addr -- [in] The multicast group to join esp_netif -- [in] Handle to esp-netif instance addr -- [in] The multicast group to join esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_MLD6_FAILED ESP_ERR_NO_MEM ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_MLD6_FAILED ESP_ERR_NO_MEM ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance addr -- [in] The multicast group to join Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_MLD6_FAILED ESP_ERR_NO_MEM esp_err_t esp_netif_leave_ip6_multicast_group(esp_netif_t *esp_netif, const esp_ip6_addr_t *addr) Cause the TCP/IP stack to leave a IPv6 multicast group. Parameters esp_netif -- [in] Handle to esp-netif instance addr -- [in] The multicast group to leave esp_netif -- [in] Handle to esp-netif instance addr -- [in] The multicast group to leave esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_MLD6_FAILED ESP_ERR_NO_MEM ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_MLD6_FAILED ESP_ERR_NO_MEM ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance addr -- [in] The multicast group to leave Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_MLD6_FAILED ESP_ERR_NO_MEM esp_err_t esp_netif_set_mac(esp_netif_t *esp_netif, uint8_t mac[]) Set the mac address for the interface instance. Parameters esp_netif -- [in] Handle to esp-netif instance mac -- [in] Desired mac address for the related network interface esp_netif -- [in] Handle to esp-netif instance mac -- [in] Desired mac address for the related network interface esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_NOT_SUPPORTED - mac not supported on this interface ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_NOT_SUPPORTED - mac not supported on this interface ESP_OK - success Parameters esp_netif -- [in] Handle to esp-netif instance mac -- [in] Desired mac address for the related network interface Returns ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_NOT_SUPPORTED - mac not supported on this interface esp_err_t esp_netif_get_mac(esp_netif_t *esp_netif, uint8_t mac[]) Get the mac address for the interface instance. Parameters esp_netif -- [in] Handle to esp-netif instance mac -- [out] Resultant mac address for the related network interface esp_netif -- [in] Handle to esp-netif instance mac -- [out] Resultant mac address for the related network interface esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_NOT_SUPPORTED - mac not supported on this interface ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_NOT_SUPPORTED - mac not supported on this interface ESP_OK - success Parameters esp_netif -- [in] Handle to esp-netif instance mac -- [out] Resultant mac address for the related network interface Returns ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_NOT_SUPPORTED - mac not supported on this interface esp_err_t esp_netif_set_hostname(esp_netif_t *esp_netif, const char *hostname) Set the hostname of an interface. The configured hostname overrides the default configuration value CONFIG_LWIP_LOCAL_HOSTNAME. Please note that when the hostname is altered after interface started/connected the changes would only be reflected once the interface restarts/reconnects Parameters esp_netif -- [in] Handle to esp-netif instance hostname -- [in] New hostname for the interface. Maximum length 32 bytes. esp_netif -- [in] Handle to esp-netif instance hostname -- [in] New hostname for the interface. Maximum length 32 bytes. esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_ESP_NETIF_INVALID_PARAMS - parameter error ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_ESP_NETIF_INVALID_PARAMS - parameter error ESP_OK - success Parameters esp_netif -- [in] Handle to esp-netif instance hostname -- [in] New hostname for the interface. Maximum length 32 bytes. Returns ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_ESP_NETIF_INVALID_PARAMS - parameter error esp_err_t esp_netif_get_hostname(esp_netif_t *esp_netif, const char **hostname) Get interface hostname. Parameters esp_netif -- [in] Handle to esp-netif instance hostname -- [out] Returns a pointer to the hostname. May be NULL if no hostname is set. If set non-NULL, pointer remains valid (and string may change if the hostname changes). esp_netif -- [in] Handle to esp-netif instance hostname -- [out] Returns a pointer to the hostname. May be NULL if no hostname is set. If set non-NULL, pointer remains valid (and string may change if the hostname changes). esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_ESP_NETIF_INVALID_PARAMS - parameter error ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_ESP_NETIF_INVALID_PARAMS - parameter error ESP_OK - success Parameters esp_netif -- [in] Handle to esp-netif instance hostname -- [out] Returns a pointer to the hostname. May be NULL if no hostname is set. If set non-NULL, pointer remains valid (and string may change if the hostname changes). Returns ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_ESP_NETIF_INVALID_PARAMS - parameter error bool esp_netif_is_netif_up(esp_netif_t *esp_netif) Test if supplied interface is up or down. Parameters esp_netif -- [in] Handle to esp-netif instance Returns true - Interface is up false - Interface is down true - Interface is up false - Interface is down true - Interface is up Parameters esp_netif -- [in] Handle to esp-netif instance Returns true - Interface is up false - Interface is down esp_err_t esp_netif_get_ip_info(esp_netif_t *esp_netif, esp_netif_ip_info_t *ip_info) Get interface's IP address information. If the interface is up, IP information is read directly from the TCP/IP stack. If the interface is down, IP information is read from a copy kept in the ESP-NETIF instance Parameters esp_netif -- [in] Handle to esp-netif instance ip_info -- [out] If successful, IP information will be returned in this argument. esp_netif -- [in] Handle to esp-netif instance ip_info -- [out] If successful, IP information will be returned in this argument. esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance ip_info -- [out] If successful, IP information will be returned in this argument. Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS esp_err_t esp_netif_get_old_ip_info(esp_netif_t *esp_netif, esp_netif_ip_info_t *ip_info) Get interface's old IP information. Returns an "old" IP address previously stored for the interface when the valid IP changed. If the IP lost timer has expired (meaning the interface was down for longer than the configured interval) then the old IP information will be zero. Parameters esp_netif -- [in] Handle to esp-netif instance ip_info -- [out] If successful, IP information will be returned in this argument. esp_netif -- [in] Handle to esp-netif instance ip_info -- [out] If successful, IP information will be returned in this argument. esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance ip_info -- [out] If successful, IP information will be returned in this argument. Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS esp_err_t esp_netif_set_ip_info(esp_netif_t *esp_netif, const esp_netif_ip_info_t *ip_info) Set interface's IP address information. This function is mainly used to set a static IP on an interface. If the interface is up, the new IP information is set directly in the TCP/IP stack. The copy of IP information kept in the ESP-NETIF instance is also updated (this copy is returned if the IP is queried while the interface is still down.) Note DHCP client/server must be stopped (if enabled for this interface) before setting new IP information. Note Calling this interface for may generate a SYSTEM_EVENT_STA_GOT_IP or SYSTEM_EVENT_ETH_GOT_IP event. Parameters esp_netif -- [in] Handle to esp-netif instance ip_info -- [in] IP information to set on the specified interface esp_netif -- [in] Handle to esp-netif instance ip_info -- [in] IP information to set on the specified interface esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_NOT_STOPPED If DHCP server or client is still running ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_NOT_STOPPED If DHCP server or client is still running ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance ip_info -- [in] IP information to set on the specified interface Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_NOT_STOPPED If DHCP server or client is still running esp_err_t esp_netif_set_old_ip_info(esp_netif_t *esp_netif, const esp_netif_ip_info_t *ip_info) Set interface old IP information. This function is called from the DHCP client (if enabled), before a new IP is set. It is also called from the default handlers for the SYSTEM_EVENT_STA_CONNECTED and SYSTEM_EVENT_ETH_CONNECTED events. Calling this function stores the previously configured IP, which can be used to determine if the IP changes in the future. If the interface is disconnected or down for too long, the "IP lost timer" will expire (after the configured interval) and set the old IP information to zero. Parameters esp_netif -- [in] Handle to esp-netif instance ip_info -- [in] Store the old IP information for the specified interface esp_netif -- [in] Handle to esp-netif instance ip_info -- [in] Store the old IP information for the specified interface esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance ip_info -- [in] Store the old IP information for the specified interface Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS int esp_netif_get_netif_impl_index(esp_netif_t *esp_netif) Get net interface index from network stack implementation. Note This index could be used in setsockopt() to bind socket with multicast interface Parameters esp_netif -- [in] Handle to esp-netif instance Returns implementation specific index of interface represented with supplied esp_netif Parameters esp_netif -- [in] Handle to esp-netif instance Returns implementation specific index of interface represented with supplied esp_netif esp_err_t esp_netif_get_netif_impl_name(esp_netif_t *esp_netif, char *name) Get net interface name from network stack implementation. Note This name could be used in setsockopt() to bind socket with appropriate interface Parameters esp_netif -- [in] Handle to esp-netif instance name -- [out] Interface name as specified in underlying TCP/IP stack. Note that the actual name will be copied to the specified buffer, which must be allocated to hold maximum interface name size (6 characters for lwIP) esp_netif -- [in] Handle to esp-netif instance name -- [out] Interface name as specified in underlying TCP/IP stack. Note that the actual name will be copied to the specified buffer, which must be allocated to hold maximum interface name size (6 characters for lwIP) esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance name -- [out] Interface name as specified in underlying TCP/IP stack. Note that the actual name will be copied to the specified buffer, which must be allocated to hold maximum interface name size (6 characters for lwIP) Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS esp_err_t esp_netif_napt_enable(esp_netif_t *esp_netif) Enable NAPT on an interface. Note Enable operation can be performed only on one interface at a time. NAPT cannot be enabled on multiple interfaces according to this implementation. Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_FAIL ESP_ERR_NOT_SUPPORTED ESP_OK ESP_FAIL ESP_ERR_NOT_SUPPORTED ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_FAIL ESP_ERR_NOT_SUPPORTED esp_err_t esp_netif_napt_disable(esp_netif_t *esp_netif) Disable NAPT on an interface. Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_FAIL ESP_ERR_NOT_SUPPORTED ESP_OK ESP_FAIL ESP_ERR_NOT_SUPPORTED ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_FAIL ESP_ERR_NOT_SUPPORTED esp_err_t esp_netif_dhcps_option(esp_netif_t *esp_netif, esp_netif_dhcp_option_mode_t opt_op, esp_netif_dhcp_option_id_t opt_id, void *opt_val, uint32_t opt_len) Set or Get DHCP server option. Parameters esp_netif -- [in] Handle to esp-netif instance opt_op -- [in] ESP_NETIF_OP_SET to set an option, ESP_NETIF_OP_GET to get an option. opt_id -- [in] Option index to get or set, must be one of the supported enum values. opt_val -- [inout] Pointer to the option parameter. opt_len -- [in] Length of the option parameter. esp_netif -- [in] Handle to esp-netif instance opt_op -- [in] ESP_NETIF_OP_SET to set an option, ESP_NETIF_OP_GET to get an option. opt_id -- [in] Option index to get or set, must be one of the supported enum values. opt_val -- [inout] Pointer to the option parameter. opt_len -- [in] Length of the option parameter. esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance opt_op -- [in] ESP_NETIF_OP_SET to set an option, ESP_NETIF_OP_GET to get an option. opt_id -- [in] Option index to get or set, must be one of the supported enum values. opt_val -- [inout] Pointer to the option parameter. opt_len -- [in] Length of the option parameter. Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED esp_err_t esp_netif_dhcpc_option(esp_netif_t *esp_netif, esp_netif_dhcp_option_mode_t opt_op, esp_netif_dhcp_option_id_t opt_id, void *opt_val, uint32_t opt_len) Set or Get DHCP client option. Parameters esp_netif -- [in] Handle to esp-netif instance opt_op -- [in] ESP_NETIF_OP_SET to set an option, ESP_NETIF_OP_GET to get an option. opt_id -- [in] Option index to get or set, must be one of the supported enum values. opt_val -- [inout] Pointer to the option parameter. opt_len -- [in] Length of the option parameter. esp_netif -- [in] Handle to esp-netif instance opt_op -- [in] ESP_NETIF_OP_SET to set an option, ESP_NETIF_OP_GET to get an option. opt_id -- [in] Option index to get or set, must be one of the supported enum values. opt_val -- [inout] Pointer to the option parameter. opt_len -- [in] Length of the option parameter. esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance opt_op -- [in] ESP_NETIF_OP_SET to set an option, ESP_NETIF_OP_GET to get an option. opt_id -- [in] Option index to get or set, must be one of the supported enum values. opt_val -- [inout] Pointer to the option parameter. opt_len -- [in] Length of the option parameter. Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED esp_err_t esp_netif_dhcpc_start(esp_netif_t *esp_netif) Start DHCP client (only if enabled in interface object) Note The default event handlers for the SYSTEM_EVENT_STA_CONNECTED and SYSTEM_EVENT_ETH_CONNECTED events call this function. Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED ESP_ERR_ESP_NETIF_DHCPC_START_FAILED ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED ESP_ERR_ESP_NETIF_DHCPC_START_FAILED ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED ESP_ERR_ESP_NETIF_DHCPC_START_FAILED esp_err_t esp_netif_dhcpc_stop(esp_netif_t *esp_netif) Stop DHCP client (only if enabled in interface object) Note Calling action_netif_stop() will also stop the DHCP Client if it is running. Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_IF_NOT_READY ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_IF_NOT_READY ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_IF_NOT_READY esp_err_t esp_netif_dhcpc_get_status(esp_netif_t *esp_netif, esp_netif_dhcp_status_t *status) Get DHCP client status. Parameters esp_netif -- [in] Handle to esp-netif instance status -- [out] If successful, the status of DHCP client will be returned in this argument. esp_netif -- [in] Handle to esp-netif instance status -- [out] If successful, the status of DHCP client will be returned in this argument. esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_OK ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance status -- [out] If successful, the status of DHCP client will be returned in this argument. Returns ESP_OK esp_err_t esp_netif_dhcps_get_status(esp_netif_t *esp_netif, esp_netif_dhcp_status_t *status) Get DHCP Server status. Parameters esp_netif -- [in] Handle to esp-netif instance status -- [out] If successful, the status of the DHCP server will be returned in this argument. esp_netif -- [in] Handle to esp-netif instance status -- [out] If successful, the status of the DHCP server will be returned in this argument. esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_OK ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance status -- [out] If successful, the status of the DHCP server will be returned in this argument. Returns ESP_OK esp_err_t esp_netif_dhcps_start(esp_netif_t *esp_netif) Start DHCP server (only if enabled in interface object) Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED esp_err_t esp_netif_dhcps_stop(esp_netif_t *esp_netif) Stop DHCP server (only if enabled in interface object) Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_IF_NOT_READY ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_IF_NOT_READY ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_IF_NOT_READY esp_err_t esp_netif_dhcps_get_clients_by_mac(esp_netif_t *esp_netif, int num, esp_netif_pair_mac_ip_t *mac_ip_pair) Populate IP addresses of clients connected to DHCP server listed by their MAC addresses. Parameters esp_netif -- [in] Handle to esp-netif instance num -- [in] Number of clients with specified MAC addresses in the array of pairs mac_ip_pair -- [inout] Array of pairs of MAC and IP addresses (MAC are inputs, IP outputs) esp_netif -- [in] Handle to esp-netif instance num -- [in] Number of clients with specified MAC addresses in the array of pairs mac_ip_pair -- [inout] Array of pairs of MAC and IP addresses (MAC are inputs, IP outputs) esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS on invalid params ESP_ERR_NOT_SUPPORTED if DHCP server not enabled ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS on invalid params ESP_ERR_NOT_SUPPORTED if DHCP server not enabled ESP_OK on success Parameters esp_netif -- [in] Handle to esp-netif instance num -- [in] Number of clients with specified MAC addresses in the array of pairs mac_ip_pair -- [inout] Array of pairs of MAC and IP addresses (MAC are inputs, IP outputs) Returns ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS on invalid params ESP_ERR_NOT_SUPPORTED if DHCP server not enabled esp_err_t esp_netif_set_dns_info(esp_netif_t *esp_netif, esp_netif_dns_type_t type, esp_netif_dns_info_t *dns) Set DNS Server information. This function behaves differently if DHCP server or client is enabled If DHCP client is enabled, main and backup DNS servers will be updated automatically from the DHCP lease if the relevant DHCP options are set. Fallback DNS Server is never updated from the DHCP lease and is designed to be set via this API. If DHCP client is disabled, all DNS server types can be set via this API only. If DHCP server is enabled, the Main DNS Server setting is used by the DHCP server to provide a DNS Server option to DHCP clients (Wi-Fi stations). The default Main DNS server is typically the IP of the DHCP server itself. This function can override it by setting server type ESP_NETIF_DNS_MAIN. Other DNS Server types are not supported for the DHCP server. To propagate the DNS info to client, please stop the DHCP server before using this API. The default Main DNS server is typically the IP of the DHCP server itself. This function can override it by setting server type ESP_NETIF_DNS_MAIN. Other DNS Server types are not supported for the DHCP server. To propagate the DNS info to client, please stop the DHCP server before using this API. Parameters esp_netif -- [in] Handle to esp-netif instance type -- [in] Type of DNS Server to set: ESP_NETIF_DNS_MAIN, ESP_NETIF_DNS_BACKUP, ESP_NETIF_DNS_FALLBACK dns -- [in] DNS Server address to set esp_netif -- [in] Handle to esp-netif instance type -- [in] Type of DNS Server to set: ESP_NETIF_DNS_MAIN, ESP_NETIF_DNS_BACKUP, ESP_NETIF_DNS_FALLBACK dns -- [in] DNS Server address to set esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS invalid params ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS invalid params ESP_OK on success Parameters esp_netif -- [in] Handle to esp-netif instance type -- [in] Type of DNS Server to set: ESP_NETIF_DNS_MAIN, ESP_NETIF_DNS_BACKUP, ESP_NETIF_DNS_FALLBACK dns -- [in] DNS Server address to set Returns ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS invalid params The default Main DNS server is typically the IP of the DHCP server itself. esp_err_t esp_netif_get_dns_info(esp_netif_t *esp_netif, esp_netif_dns_type_t type, esp_netif_dns_info_t *dns) Get DNS Server information. Return the currently configured DNS Server address for the specified interface and Server type. This may be result of a previous call to esp_netif_set_dns_info(). If the interface's DHCP client is enabled, the Main or Backup DNS Server may be set by the current DHCP lease. Parameters esp_netif -- [in] Handle to esp-netif instance type -- [in] Type of DNS Server to get: ESP_NETIF_DNS_MAIN, ESP_NETIF_DNS_BACKUP, ESP_NETIF_DNS_FALLBACK dns -- [out] DNS Server result is written here on success esp_netif -- [in] Handle to esp-netif instance type -- [in] Type of DNS Server to get: ESP_NETIF_DNS_MAIN, ESP_NETIF_DNS_BACKUP, ESP_NETIF_DNS_FALLBACK dns -- [out] DNS Server result is written here on success esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS invalid params ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS invalid params ESP_OK on success Parameters esp_netif -- [in] Handle to esp-netif instance type -- [in] Type of DNS Server to get: ESP_NETIF_DNS_MAIN, ESP_NETIF_DNS_BACKUP, ESP_NETIF_DNS_FALLBACK dns -- [out] DNS Server result is written here on success Returns ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS invalid params esp_err_t esp_netif_create_ip6_linklocal(esp_netif_t *esp_netif) Create interface link-local IPv6 address. Cause the TCP/IP stack to create a link-local IPv6 address for the specified interface. This function also registers a callback for the specified interface, so that if the link-local address becomes verified as the preferred address then a SYSTEM_EVENT_GOT_IP6 event will be sent. Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS esp_err_t esp_netif_get_ip6_linklocal(esp_netif_t *esp_netif, esp_ip6_addr_t *if_ip6) Get interface link-local IPv6 address. If the specified interface is up and a preferred link-local IPv6 address has been created for the interface, return a copy of it. Parameters esp_netif -- [in] Handle to esp-netif instance if_ip6 -- [out] IPv6 information will be returned in this argument if successful. esp_netif -- [in] Handle to esp-netif instance if_ip6 -- [out] IPv6 information will be returned in this argument if successful. esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_FAIL If interface is down, does not have a link-local IPv6 address, or the link-local IPv6 address is not a preferred address. ESP_OK ESP_FAIL If interface is down, does not have a link-local IPv6 address, or the link-local IPv6 address is not a preferred address. ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance if_ip6 -- [out] IPv6 information will be returned in this argument if successful. Returns ESP_OK ESP_FAIL If interface is down, does not have a link-local IPv6 address, or the link-local IPv6 address is not a preferred address. esp_err_t esp_netif_get_ip6_global(esp_netif_t *esp_netif, esp_ip6_addr_t *if_ip6) Get interface global IPv6 address. If the specified interface is up and a preferred global IPv6 address has been created for the interface, return a copy of it. Parameters esp_netif -- [in] Handle to esp-netif instance if_ip6 -- [out] IPv6 information will be returned in this argument if successful. esp_netif -- [in] Handle to esp-netif instance if_ip6 -- [out] IPv6 information will be returned in this argument if successful. esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK ESP_FAIL If interface is down, does not have a global IPv6 address, or the global IPv6 address is not a preferred address. ESP_OK ESP_FAIL If interface is down, does not have a global IPv6 address, or the global IPv6 address is not a preferred address. ESP_OK Parameters esp_netif -- [in] Handle to esp-netif instance if_ip6 -- [out] IPv6 information will be returned in this argument if successful. Returns ESP_OK ESP_FAIL If interface is down, does not have a global IPv6 address, or the global IPv6 address is not a preferred address. int esp_netif_get_all_ip6(esp_netif_t *esp_netif, esp_ip6_addr_t if_ip6[]) Get all IPv6 addresses of the specified interface. Parameters esp_netif -- [in] Handle to esp-netif instance if_ip6 -- [out] Array of IPv6 addresses will be copied to the argument esp_netif -- [in] Handle to esp-netif instance if_ip6 -- [out] Array of IPv6 addresses will be copied to the argument esp_netif -- [in] Handle to esp-netif instance Returns number of returned IPv6 addresses Parameters esp_netif -- [in] Handle to esp-netif instance if_ip6 -- [out] Array of IPv6 addresses will be copied to the argument Returns number of returned IPv6 addresses void esp_netif_set_ip4_addr(esp_ip4_addr_t *addr, uint8_t a, uint8_t b, uint8_t c, uint8_t d) Sets IPv4 address to the specified octets. Parameters addr -- [out] IP address to be set a -- the first octet (127 for IP 127.0.0.1) b -- c -- d -- addr -- [out] IP address to be set a -- the first octet (127 for IP 127.0.0.1) b -- c -- d -- addr -- [out] IP address to be set Parameters addr -- [out] IP address to be set a -- the first octet (127 for IP 127.0.0.1) b -- c -- d -- char *esp_ip4addr_ntoa(const esp_ip4_addr_t *addr, char *buf, int buflen) Converts numeric IP address into decimal dotted ASCII representation. Parameters addr -- ip address in network order to convert buf -- target buffer where the string is stored buflen -- length of buf addr -- ip address in network order to convert buf -- target buffer where the string is stored buflen -- length of buf addr -- ip address in network order to convert Returns either pointer to buf which now holds the ASCII representation of addr or NULL if buf was too small Parameters addr -- ip address in network order to convert buf -- target buffer where the string is stored buflen -- length of buf Returns either pointer to buf which now holds the ASCII representation of addr or NULL if buf was too small uint32_t esp_ip4addr_aton(const char *addr) Ascii internet address interpretation routine The value returned is in network order. Parameters addr -- IP address in ascii representation (e.g. "127.0.0.1") Returns ip address in network order Parameters addr -- IP address in ascii representation (e.g. "127.0.0.1") Returns ip address in network order esp_err_t esp_netif_str_to_ip4(const char *src, esp_ip4_addr_t *dst) Converts Ascii internet IPv4 address into esp_ip4_addr_t. Parameters src -- [in] IPv4 address in ascii representation (e.g. "127.0.0.1") dst -- [out] Address of the target esp_ip4_addr_t structure to receive converted address src -- [in] IPv4 address in ascii representation (e.g. "127.0.0.1") dst -- [out] Address of the target esp_ip4_addr_t structure to receive converted address src -- [in] IPv4 address in ascii representation (e.g. "127.0.0.1") Returns ESP_OK on success ESP_FAIL if conversion failed ESP_ERR_INVALID_ARG if invalid parameter is passed into ESP_OK on success ESP_FAIL if conversion failed ESP_ERR_INVALID_ARG if invalid parameter is passed into ESP_OK on success Parameters src -- [in] IPv4 address in ascii representation (e.g. "127.0.0.1") dst -- [out] Address of the target esp_ip4_addr_t structure to receive converted address Returns ESP_OK on success ESP_FAIL if conversion failed ESP_ERR_INVALID_ARG if invalid parameter is passed into esp_err_t esp_netif_str_to_ip6(const char *src, esp_ip6_addr_t *dst) Converts Ascii internet IPv6 address into esp_ip4_addr_t Zeros in the IP address can be stripped or completely ommited: "2001:db8:85a3:0:0:0:2:1" or "2001:db8::2:1") Parameters src -- [in] IPv6 address in ascii representation (e.g. ""2001:0db8:85a3:0000:0000:0000:0002:0001") dst -- [out] Address of the target esp_ip6_addr_t structure to receive converted address src -- [in] IPv6 address in ascii representation (e.g. ""2001:0db8:85a3:0000:0000:0000:0002:0001") dst -- [out] Address of the target esp_ip6_addr_t structure to receive converted address src -- [in] IPv6 address in ascii representation (e.g. ""2001:0db8:85a3:0000:0000:0000:0002:0001") Returns ESP_OK on success ESP_FAIL if conversion failed ESP_ERR_INVALID_ARG if invalid parameter is passed into ESP_OK on success ESP_FAIL if conversion failed ESP_ERR_INVALID_ARG if invalid parameter is passed into ESP_OK on success Parameters src -- [in] IPv6 address in ascii representation (e.g. ""2001:0db8:85a3:0000:0000:0000:0002:0001") dst -- [out] Address of the target esp_ip6_addr_t structure to receive converted address Returns ESP_OK on success ESP_FAIL if conversion failed ESP_ERR_INVALID_ARG if invalid parameter is passed into esp_netif_iodriver_handle esp_netif_get_io_driver(esp_netif_t *esp_netif) Gets media driver handle for this esp-netif instance. Parameters esp_netif -- [in] Handle to esp-netif instance Returns opaque pointer of related IO driver Parameters esp_netif -- [in] Handle to esp-netif instance Returns opaque pointer of related IO driver esp_netif_t *esp_netif_get_handle_from_ifkey(const char *if_key) Searches over a list of created objects to find an instance with supplied if key. Parameters if_key -- Textual description of network interface Returns Handle to esp-netif instance Parameters if_key -- Textual description of network interface Returns Handle to esp-netif instance esp_netif_flags_t esp_netif_get_flags(esp_netif_t *esp_netif) Returns configured flags for this interface. Parameters esp_netif -- [in] Handle to esp-netif instance Returns Configuration flags Parameters esp_netif -- [in] Handle to esp-netif instance Returns Configuration flags const char *esp_netif_get_ifkey(esp_netif_t *esp_netif) Returns configured interface key for this esp-netif instance. Parameters esp_netif -- [in] Handle to esp-netif instance Returns Textual description of related interface Parameters esp_netif -- [in] Handle to esp-netif instance Returns Textual description of related interface const char *esp_netif_get_desc(esp_netif_t *esp_netif) Returns configured interface type for this esp-netif instance. Parameters esp_netif -- [in] Handle to esp-netif instance Returns Enumerated type of this interface, such as station, AP, ethernet Parameters esp_netif -- [in] Handle to esp-netif instance Returns Enumerated type of this interface, such as station, AP, ethernet int esp_netif_get_route_prio(esp_netif_t *esp_netif) Returns configured routing priority number. Parameters esp_netif -- [in] Handle to esp-netif instance Returns Integer representing the instance's route-prio, or -1 if invalid paramters Parameters esp_netif -- [in] Handle to esp-netif instance Returns Integer representing the instance's route-prio, or -1 if invalid paramters int32_t esp_netif_get_event_id(esp_netif_t *esp_netif, esp_netif_ip_event_type_t event_type) Returns configured event for this esp-netif instance and supplied event type. Parameters esp_netif -- [in] Handle to esp-netif instance event_type -- (either get or lost IP) esp_netif -- [in] Handle to esp-netif instance event_type -- (either get or lost IP) esp_netif -- [in] Handle to esp-netif instance Returns specific event id which is configured to be raised if the interface lost or acquired IP address -1 if supplied event_type is not known Parameters esp_netif -- [in] Handle to esp-netif instance event_type -- (either get or lost IP) Returns specific event id which is configured to be raised if the interface lost or acquired IP address -1 if supplied event_type is not known esp_netif_t *esp_netif_next(esp_netif_t *esp_netif) Iterates over list of interfaces. Returns first netif if NULL given as parameter. Note This API doesn't lock the list, nor the TCPIP context, as this it's usually required to get atomic access between iteration steps rather that within a single iteration. Therefore it is recommended to iterate over the interfaces inside esp_netif_tcpip_exec() Note This API is deprecated. Please use esp_netif_next_unsafe() directly if all the system interfaces are under your control and you can safely iterate over them. Otherwise, iterate over interfaces using esp_netif_tcpip_exec(), or use esp_netif_find_if() to search in the list of netifs with defined predicate. Parameters esp_netif -- [in] Handle to esp-netif instance Returns First netif from the list if supplied parameter is NULL, next one otherwise Parameters esp_netif -- [in] Handle to esp-netif instance Returns First netif from the list if supplied parameter is NULL, next one otherwise esp_netif_t *esp_netif_next_unsafe(esp_netif_t *esp_netif) Iterates over list of interfaces without list locking. Returns first netif if NULL given as parameter. Used for bulk search loops within TCPIP context, e.g. using esp_netif_tcpip_exec(), or if we're sure that the iteration is safe from our application perspective (e.g. no interface is removed between iterations) Parameters esp_netif -- [in] Handle to esp-netif instance Returns First netif from the list if supplied parameter is NULL, next one otherwise Parameters esp_netif -- [in] Handle to esp-netif instance Returns First netif from the list if supplied parameter is NULL, next one otherwise esp_netif_t *esp_netif_find_if(esp_netif_find_predicate_t fn, void *ctx) Return a netif pointer for the first interface that meets criteria defined by the callback. Parameters fn -- Predicate function returning true for the desired interface ctx -- Context pointer passed to the predicate, typically a descriptor to compare with fn -- Predicate function returning true for the desired interface ctx -- Context pointer passed to the predicate, typically a descriptor to compare with fn -- Predicate function returning true for the desired interface Returns valid netif pointer if found, NULL if not Parameters fn -- Predicate function returning true for the desired interface ctx -- Context pointer passed to the predicate, typically a descriptor to compare with Returns valid netif pointer if found, NULL if not size_t esp_netif_get_nr_of_ifs(void) Returns number of registered esp_netif objects. Returns Number of esp_netifs Returns Number of esp_netifs void esp_netif_netstack_buf_ref(void *netstack_buf) increase the reference counter of net stack buffer Parameters netstack_buf -- [in] the net stack buffer Parameters netstack_buf -- [in] the net stack buffer void esp_netif_netstack_buf_free(void *netstack_buf) free the netstack buffer Parameters netstack_buf -- [in] the net stack buffer Parameters netstack_buf -- [in] the net stack buffer esp_err_t esp_netif_tcpip_exec(esp_netif_callback_fn fn, void *ctx) Utility to execute the supplied callback in TCP/IP context. Parameters fn -- Pointer to the callback ctx -- Parameter to the callback fn -- Pointer to the callback ctx -- Parameter to the callback fn -- Pointer to the callback Returns The error code (esp_err_t) returned by the callback Parameters fn -- Pointer to the callback ctx -- Parameter to the callback Returns The error code (esp_err_t) returned by the callback Type Definitions typedef bool (*esp_netif_find_predicate_t)(esp_netif_t *netif, void *ctx) Predicate callback for esp_netif_find_if() used to find interface which meets defined criteria. typedef esp_err_t (*esp_netif_callback_fn)(void *ctx) TCPIP thread safe callback used with esp_netif_tcpip_exec() Header File This header file can be included with: #include "esp_netif_sntp.h" This header file is a part of the API provided by the esp_netif component. To declare that your component depends on esp_netif , add the following to your CMakeLists.txt: REQUIRES esp_netif or PRIV_REQUIRES esp_netif Functions esp_err_t esp_netif_sntp_init(const esp_sntp_config_t *config) Initialize SNTP with supplied config struct. Parameters config -- Config struct Returns ESP_OK on success Parameters config -- Config struct Returns ESP_OK on success esp_err_t esp_netif_sntp_start(void) Start SNTP service if it wasn't started during init (config.start = false) or restart it if already started. Returns ESP_OK on success Returns ESP_OK on success void esp_netif_sntp_deinit(void) Deinitialize esp_netif SNTP module. esp_err_t esp_netif_sntp_sync_wait(TickType_t tout) Wait for time sync event. Parameters tout -- Specified timeout in RTOS ticks Returns ESP_TIMEOUT if sync event didn't came withing the timeout ESP_ERR_NOT_FINISHED if the sync event came, but we're in smooth update mode and still in progress (SNTP_SYNC_STATUS_IN_PROGRESS) ESP_OK if time sync'ed Parameters tout -- Specified timeout in RTOS ticks Returns ESP_TIMEOUT if sync event didn't came withing the timeout ESP_ERR_NOT_FINISHED if the sync event came, but we're in smooth update mode and still in progress (SNTP_SYNC_STATUS_IN_PROGRESS) ESP_OK if time sync'ed Structures struct esp_sntp_config SNTP configuration struct. Public Members bool smooth_sync set to true if smooth sync required bool smooth_sync set to true if smooth sync required bool server_from_dhcp set to true to request NTP server config from DHCP bool server_from_dhcp set to true to request NTP server config from DHCP bool wait_for_sync if true, we create a semaphore to signal time sync event bool wait_for_sync if true, we create a semaphore to signal time sync event bool start set to true to automatically start the SNTP service bool start set to true to automatically start the SNTP service esp_sntp_time_cb_t sync_cb optionally sets callback function on time sync event esp_sntp_time_cb_t sync_cb optionally sets callback function on time sync event bool renew_servers_after_new_IP this is used to refresh server list if NTP provided by DHCP (which cleans other pre-configured servers) bool renew_servers_after_new_IP this is used to refresh server list if NTP provided by DHCP (which cleans other pre-configured servers) ip_event_t ip_event_to_renew set the IP event id on which we refresh server list (if renew_servers_after_new_IP=true) ip_event_t ip_event_to_renew set the IP event id on which we refresh server list (if renew_servers_after_new_IP=true) size_t index_of_first_server refresh server list after this server (if renew_servers_after_new_IP=true) size_t index_of_first_server refresh server list after this server (if renew_servers_after_new_IP=true) size_t num_of_servers number of preconfigured NTP servers size_t num_of_servers number of preconfigured NTP servers const char *servers[1] list of servers const char *servers[1] list of servers bool smooth_sync Macros ESP_SNTP_SERVER_LIST(...) Utility macro for providing multiple servers in parentheses. ESP_NETIF_SNTP_DEFAULT_CONFIG_MULTIPLE(servers_in_list, list_of_servers) Default configuration to init SNTP with multiple servers. Parameters servers_in_list -- Number of servers in the list list_of_servers -- List of servers (use ESP_SNTP_SERVER_LIST(...)) servers_in_list -- Number of servers in the list list_of_servers -- List of servers (use ESP_SNTP_SERVER_LIST(...)) servers_in_list -- Number of servers in the list Parameters servers_in_list -- Number of servers in the list list_of_servers -- List of servers (use ESP_SNTP_SERVER_LIST(...)) ESP_NETIF_SNTP_DEFAULT_CONFIG(server) Default configuration with a single server. Type Definitions typedef void (*esp_sntp_time_cb_t)(struct timeval *tv) Time sync notification function. typedef struct esp_sntp_config esp_sntp_config_t SNTP configuration struct. Header File This header file can be included with: #include "esp_netif_types.h" This header file is a part of the API provided by the esp_netif component. To declare that your component depends on esp_netif , add the following to your CMakeLists.txt: REQUIRES esp_netif or PRIV_REQUIRES esp_netif Structures struct esp_netif_dns_info_t DNS server info. Public Members esp_ip_addr_t ip IPV4 address of DNS server esp_ip_addr_t ip IPV4 address of DNS server esp_ip_addr_t ip struct esp_netif_ip_info_t Event structure for IP_EVENT_STA_GOT_IP, IP_EVENT_ETH_GOT_IP events Public Members esp_ip4_addr_t ip Interface IPV4 address esp_ip4_addr_t ip Interface IPV4 address esp_ip4_addr_t netmask Interface IPV4 netmask esp_ip4_addr_t netmask Interface IPV4 netmask esp_ip4_addr_t gw Interface IPV4 gateway address esp_ip4_addr_t gw Interface IPV4 gateway address esp_ip4_addr_t ip struct esp_netif_ip6_info_t IPV6 IP address information. Public Members esp_ip6_addr_t ip Interface IPV6 address esp_ip6_addr_t ip Interface IPV6 address esp_ip6_addr_t ip struct ip_event_got_ip_t Event structure for IP_EVENT_GOT_IP event. Public Members esp_netif_t *esp_netif Pointer to corresponding esp-netif object esp_netif_t *esp_netif Pointer to corresponding esp-netif object esp_netif_ip_info_t ip_info IP address, netmask, gatway IP address esp_netif_ip_info_t ip_info IP address, netmask, gatway IP address bool ip_changed Whether the assigned IP has changed or not bool ip_changed Whether the assigned IP has changed or not esp_netif_t *esp_netif struct ip_event_got_ip6_t Event structure for IP_EVENT_GOT_IP6 event Public Members esp_netif_t *esp_netif Pointer to corresponding esp-netif object esp_netif_t *esp_netif Pointer to corresponding esp-netif object esp_netif_ip6_info_t ip6_info IPv6 address of the interface esp_netif_ip6_info_t ip6_info IPv6 address of the interface int ip_index IPv6 address index int ip_index IPv6 address index esp_netif_t *esp_netif struct ip_event_add_ip6_t Event structure for ADD_IP6 event Public Members esp_ip6_addr_t addr The address to be added to the interface esp_ip6_addr_t addr The address to be added to the interface bool preferred The default preference of the address bool preferred The default preference of the address esp_ip6_addr_t addr struct ip_event_ap_staipassigned_t Event structure for IP_EVENT_AP_STAIPASSIGNED event Public Members esp_netif_t *esp_netif Pointer to the associated netif handle esp_netif_t *esp_netif Pointer to the associated netif handle esp_ip4_addr_t ip IP address which was assigned to the station esp_ip4_addr_t ip IP address which was assigned to the station uint8_t mac[6] MAC address of the connected client uint8_t mac[6] MAC address of the connected client esp_netif_t *esp_netif struct bridgeif_config LwIP bridge configuration struct esp_netif_inherent_config ESP-netif inherent config parameters. Public Members esp_netif_flags_t flags flags that define esp-netif behavior esp_netif_flags_t flags flags that define esp-netif behavior uint8_t mac[6] initial mac address for this interface uint8_t mac[6] initial mac address for this interface const esp_netif_ip_info_t *ip_info initial ip address for this interface const esp_netif_ip_info_t *ip_info initial ip address for this interface uint32_t get_ip_event event id to be raised when interface gets an IP uint32_t get_ip_event event id to be raised when interface gets an IP uint32_t lost_ip_event event id to be raised when interface losts its IP uint32_t lost_ip_event event id to be raised when interface losts its IP const char *if_key string identifier of the interface const char *if_key string identifier of the interface const char *if_desc textual description of the interface const char *if_desc textual description of the interface int route_prio numeric priority of this interface to become a default routing if (if other netifs are up). A higher value of route_prio indicates a higher priority int route_prio numeric priority of this interface to become a default routing if (if other netifs are up). A higher value of route_prio indicates a higher priority bridgeif_config_t *bridge_info LwIP bridge configuration bridgeif_config_t *bridge_info LwIP bridge configuration esp_netif_flags_t flags struct esp_netif_driver_base_s ESP-netif driver base handle. Public Members esp_err_t (*post_attach)(esp_netif_t *netif, esp_netif_iodriver_handle h) post attach function pointer esp_err_t (*post_attach)(esp_netif_t *netif, esp_netif_iodriver_handle h) post attach function pointer esp_netif_t *netif netif handle esp_netif_t *netif netif handle esp_err_t (*post_attach)(esp_netif_t *netif, esp_netif_iodriver_handle h) struct esp_netif_driver_ifconfig Specific IO driver configuration. Public Members esp_netif_iodriver_handle handle io-driver handle esp_netif_iodriver_handle handle io-driver handle esp_err_t (*transmit_wrap)(void *h, void *buffer, size_t len, void *netstack_buffer) transmit wrap function pointer esp_err_t (*transmit_wrap)(void *h, void *buffer, size_t len, void *netstack_buffer) transmit wrap function pointer void (*driver_free_rx_buffer)(void *h, void *buffer) free rx buffer function pointer void (*driver_free_rx_buffer)(void *h, void *buffer) free rx buffer function pointer esp_netif_iodriver_handle handle struct esp_netif_config Generic esp_netif configuration. Public Members const esp_netif_inherent_config_t *base base config const esp_netif_inherent_config_t *base base config const esp_netif_driver_ifconfig_t *driver driver config const esp_netif_driver_ifconfig_t *driver driver config const esp_netif_netstack_config_t *stack stack config const esp_netif_netstack_config_t *stack stack config const esp_netif_inherent_config_t *base struct esp_netif_pair_mac_ip_t DHCP client's addr info (pair of MAC and IP address) Public Members uint8_t mac[6] Clients MAC address uint8_t mac[6] Clients MAC address esp_ip4_addr_t ip Clients IP address esp_ip4_addr_t ip Clients IP address uint8_t mac[6] Macros ESP_ERR_ESP_NETIF_BASE Definition of ESP-NETIF based errors. ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_IF_NOT_READY ESP_ERR_ESP_NETIF_DHCPC_START_FAILED ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_NO_MEM ESP_ERR_ESP_NETIF_DHCP_NOT_STOPPED ESP_ERR_ESP_NETIF_DRIVER_ATTACH_FAILED ESP_ERR_ESP_NETIF_INIT_FAILED ESP_ERR_ESP_NETIF_DNS_NOT_CONFIGURED ESP_ERR_ESP_NETIF_MLD6_FAILED ESP_ERR_ESP_NETIF_IP6_ADDR_FAILED ESP_ERR_ESP_NETIF_DHCPS_START_FAILED ESP_NETIF_BR_FLOOD Definition of ESP-NETIF bridge controll. ESP_NETIF_BR_DROP ESP_NETIF_BR_FDW_CPU Type Definitions typedef struct esp_netif_obj esp_netif_t typedef enum esp_netif_flags esp_netif_flags_t typedef enum esp_netif_ip_event_type esp_netif_ip_event_type_t typedef struct bridgeif_config bridgeif_config_t LwIP bridge configuration typedef struct esp_netif_inherent_config esp_netif_inherent_config_t ESP-netif inherent config parameters. typedef struct esp_netif_config esp_netif_config_t typedef void *esp_netif_iodriver_handle IO driver handle type. typedef struct esp_netif_driver_base_s esp_netif_driver_base_t ESP-netif driver base handle. typedef struct esp_netif_driver_ifconfig esp_netif_driver_ifconfig_t typedef struct esp_netif_netstack_config esp_netif_netstack_config_t Specific L3 network stack configuration. typedef esp_err_t (*esp_netif_receive_t)(esp_netif_t *esp_netif, void *buffer, size_t len, void *eb) ESP-NETIF Receive function type. Enumerations enum esp_netif_dns_type_t Type of DNS server. Values: enumerator ESP_NETIF_DNS_MAIN DNS main server address enumerator ESP_NETIF_DNS_MAIN DNS main server address enumerator ESP_NETIF_DNS_BACKUP DNS backup server address (Wi-Fi STA and Ethernet only) enumerator ESP_NETIF_DNS_BACKUP DNS backup server address (Wi-Fi STA and Ethernet only) enumerator ESP_NETIF_DNS_FALLBACK DNS fallback server address (Wi-Fi STA and Ethernet only) enumerator ESP_NETIF_DNS_FALLBACK DNS fallback server address (Wi-Fi STA and Ethernet only) enumerator ESP_NETIF_DNS_MAX enumerator ESP_NETIF_DNS_MAX enumerator ESP_NETIF_DNS_MAIN enum esp_netif_dhcp_status_t Status of DHCP client or DHCP server. Values: enumerator ESP_NETIF_DHCP_INIT DHCP client/server is in initial state (not yet started) enumerator ESP_NETIF_DHCP_INIT DHCP client/server is in initial state (not yet started) enumerator ESP_NETIF_DHCP_STARTED DHCP client/server has been started enumerator ESP_NETIF_DHCP_STARTED DHCP client/server has been started enumerator ESP_NETIF_DHCP_STOPPED DHCP client/server has been stopped enumerator ESP_NETIF_DHCP_STOPPED DHCP client/server has been stopped enumerator ESP_NETIF_DHCP_STATUS_MAX enumerator ESP_NETIF_DHCP_STATUS_MAX enumerator ESP_NETIF_DHCP_INIT enum esp_netif_dhcp_option_mode_t Mode for DHCP client or DHCP server option functions. Values: enumerator ESP_NETIF_OP_START enumerator ESP_NETIF_OP_START enumerator ESP_NETIF_OP_SET Set option enumerator ESP_NETIF_OP_SET Set option enumerator ESP_NETIF_OP_GET Get option enumerator ESP_NETIF_OP_GET Get option enumerator ESP_NETIF_OP_MAX enumerator ESP_NETIF_OP_MAX enumerator ESP_NETIF_OP_START enum esp_netif_dhcp_option_id_t Supported options for DHCP client or DHCP server. Values: enumerator ESP_NETIF_SUBNET_MASK Network mask enumerator ESP_NETIF_SUBNET_MASK Network mask enumerator ESP_NETIF_DOMAIN_NAME_SERVER Domain name server enumerator ESP_NETIF_DOMAIN_NAME_SERVER Domain name server enumerator ESP_NETIF_ROUTER_SOLICITATION_ADDRESS Solicitation router address enumerator ESP_NETIF_ROUTER_SOLICITATION_ADDRESS Solicitation router address enumerator ESP_NETIF_REQUESTED_IP_ADDRESS Request specific IP address enumerator ESP_NETIF_REQUESTED_IP_ADDRESS Request specific IP address enumerator ESP_NETIF_IP_ADDRESS_LEASE_TIME Request IP address lease time enumerator ESP_NETIF_IP_ADDRESS_LEASE_TIME Request IP address lease time enumerator ESP_NETIF_IP_REQUEST_RETRY_TIME Request IP address retry counter enumerator ESP_NETIF_IP_REQUEST_RETRY_TIME Request IP address retry counter enumerator ESP_NETIF_VENDOR_CLASS_IDENTIFIER Vendor Class Identifier of a DHCP client enumerator ESP_NETIF_VENDOR_CLASS_IDENTIFIER Vendor Class Identifier of a DHCP client enumerator ESP_NETIF_VENDOR_SPECIFIC_INFO Vendor Specific Information of a DHCP server enumerator ESP_NETIF_VENDOR_SPECIFIC_INFO Vendor Specific Information of a DHCP server enumerator ESP_NETIF_SUBNET_MASK enum ip_event_t IP event declarations Values: enumerator IP_EVENT_STA_GOT_IP station got IP from connected AP enumerator IP_EVENT_STA_GOT_IP station got IP from connected AP enumerator IP_EVENT_STA_LOST_IP station lost IP and the IP is reset to 0 enumerator IP_EVENT_STA_LOST_IP station lost IP and the IP is reset to 0 enumerator IP_EVENT_AP_STAIPASSIGNED soft-AP assign an IP to a connected station enumerator IP_EVENT_AP_STAIPASSIGNED soft-AP assign an IP to a connected station enumerator IP_EVENT_GOT_IP6 station or ap or ethernet interface v6IP addr is preferred enumerator IP_EVENT_GOT_IP6 station or ap or ethernet interface v6IP addr is preferred enumerator IP_EVENT_ETH_GOT_IP ethernet got IP from connected AP enumerator IP_EVENT_ETH_GOT_IP ethernet got IP from connected AP enumerator IP_EVENT_ETH_LOST_IP ethernet lost IP and the IP is reset to 0 enumerator IP_EVENT_ETH_LOST_IP ethernet lost IP and the IP is reset to 0 enumerator IP_EVENT_PPP_GOT_IP PPP interface got IP enumerator IP_EVENT_PPP_GOT_IP PPP interface got IP enumerator IP_EVENT_PPP_LOST_IP PPP interface lost IP enumerator IP_EVENT_PPP_LOST_IP PPP interface lost IP enumerator IP_EVENT_STA_GOT_IP enum esp_netif_flags Values: enumerator ESP_NETIF_DHCP_CLIENT enumerator ESP_NETIF_DHCP_CLIENT enumerator ESP_NETIF_DHCP_SERVER enumerator ESP_NETIF_DHCP_SERVER enumerator ESP_NETIF_FLAG_AUTOUP enumerator ESP_NETIF_FLAG_AUTOUP enumerator ESP_NETIF_FLAG_GARP enumerator ESP_NETIF_FLAG_GARP enumerator ESP_NETIF_FLAG_EVENT_IP_MODIFIED enumerator ESP_NETIF_FLAG_EVENT_IP_MODIFIED enumerator ESP_NETIF_FLAG_IS_PPP enumerator ESP_NETIF_FLAG_IS_PPP enumerator ESP_NETIF_FLAG_IS_BRIDGE enumerator ESP_NETIF_FLAG_IS_BRIDGE enumerator ESP_NETIF_FLAG_MLDV6_REPORT enumerator ESP_NETIF_FLAG_MLDV6_REPORT enumerator ESP_NETIF_DHCP_CLIENT Header File This header file can be included with: #include "esp_netif_ip_addr.h" This header file is a part of the API provided by the esp_netif component. To declare that your component depends on esp_netif , add the following to your CMakeLists.txt: REQUIRES esp_netif or PRIV_REQUIRES esp_netif Functions esp_ip6_addr_type_t esp_netif_ip6_get_addr_type(esp_ip6_addr_t *ip6_addr) Get the IPv6 address type. Parameters ip6_addr -- [in] IPv6 type Returns IPv6 type in form of enum esp_ip6_addr_type_t Parameters ip6_addr -- [in] IPv6 type Returns IPv6 type in form of enum esp_ip6_addr_type_t static inline void esp_netif_ip_addr_copy(esp_ip_addr_t *dest, const esp_ip_addr_t *src) Copy IP addresses. Parameters dest -- [out] destination IP src -- [in] source IP dest -- [out] destination IP src -- [in] source IP dest -- [out] destination IP Parameters dest -- [out] destination IP src -- [in] source IP Structures struct esp_ip6_addr IPv6 address. struct _ip_addr IP address. Public Members esp_ip6_addr_t ip6 IPv6 address type esp_ip6_addr_t ip6 IPv6 address type esp_ip4_addr_t ip4 IPv4 address type esp_ip4_addr_t ip4 IPv4 address type uint8_t type ipaddress type uint8_t type ipaddress type esp_ip6_addr_t ip6 Macros esp_netif_htonl(x) esp_netif_ip4_makeu32(a, b, c, d) ESP_IP6_ADDR_BLOCK1(ip6addr) ESP_IP6_ADDR_BLOCK2(ip6addr) ESP_IP6_ADDR_BLOCK3(ip6addr) ESP_IP6_ADDR_BLOCK4(ip6addr) ESP_IP6_ADDR_BLOCK5(ip6addr) ESP_IP6_ADDR_BLOCK6(ip6addr) ESP_IP6_ADDR_BLOCK7(ip6addr) ESP_IP6_ADDR_BLOCK8(ip6addr) IPSTR esp_ip4_addr_get_byte(ipaddr, idx) esp_ip4_addr1(ipaddr) esp_ip4_addr2(ipaddr) esp_ip4_addr3(ipaddr) esp_ip4_addr4(ipaddr) esp_ip4_addr1_16(ipaddr) esp_ip4_addr2_16(ipaddr) esp_ip4_addr3_16(ipaddr) esp_ip4_addr4_16(ipaddr) IP2STR(ipaddr) IPV6STR IPV62STR(ipaddr) ESP_IPADDR_TYPE_V4 ESP_IPADDR_TYPE_V6 ESP_IPADDR_TYPE_ANY ESP_IP4TOUINT32(a, b, c, d) ESP_IP4TOADDR(a, b, c, d) ESP_IP4ADDR_INIT(a, b, c, d) ESP_IP6ADDR_INIT(a, b, c, d) IP4ADDR_STRLEN_MAX ESP_IP_IS_ANY(addr) Type Definitions typedef struct esp_ip4_addr esp_ip4_addr_t typedef struct esp_ip6_addr esp_ip6_addr_t Enumerations Header File This header file can be included with: #include "esp_vfs_l2tap.h" This header file is a part of the API provided by the esp_netif component. To declare that your component depends on esp_netif , add the following to your CMakeLists.txt: REQUIRES esp_netif or PRIV_REQUIRES esp_netif Functions esp_err_t esp_vfs_l2tap_intf_register(l2tap_vfs_config_t *config) Add L2 TAP virtual filesystem driver. This function must be called prior usage of ESP-NETIF L2 TAP Interface Parameters config -- L2 TAP virtual filesystem driver configuration. Default base path /dev/net/tap is used when this paramenter is NULL. Returns esp_err_t ESP_OK on success ESP_OK on success ESP_OK on success Parameters config -- L2 TAP virtual filesystem driver configuration. Default base path /dev/net/tap is used when this paramenter is NULL. Returns esp_err_t ESP_OK on success esp_err_t esp_vfs_l2tap_intf_unregister(const char *base_path) Removes L2 TAP virtual filesystem driver. Parameters base_path -- Base path to the L2 TAP virtual filesystem driver. Default path /dev/net/tap is used when this paramenter is NULL. Returns esp_err_t ESP_OK on success ESP_OK on success ESP_OK on success Parameters base_path -- Base path to the L2 TAP virtual filesystem driver. Default path /dev/net/tap is used when this paramenter is NULL. Returns esp_err_t ESP_OK on success esp_err_t esp_vfs_l2tap_eth_filter(l2tap_iodriver_handle driver_handle, void *buff, size_t *size) Filters received Ethernet L2 frames into L2 TAP infrastructure. Parameters driver_handle -- handle of driver at which the frame was received buff -- received L2 frame size -- input length of the L2 frame which is set to 0 when frame is filtered into L2 TAP driver_handle -- handle of driver at which the frame was received buff -- received L2 frame size -- input length of the L2 frame which is set to 0 when frame is filtered into L2 TAP driver_handle -- handle of driver at which the frame was received Returns esp_err_t ESP_OK is always returned ESP_OK is always returned ESP_OK is always returned Parameters driver_handle -- handle of driver at which the frame was received buff -- received L2 frame size -- input length of the L2 frame which is set to 0 when frame is filtered into L2 TAP Returns esp_err_t ESP_OK is always returned Structures Macros L2TAP_VFS_DEFAULT_PATH L2TAP_VFS_CONFIG_DEFAULT() Type Definitions typedef void *l2tap_iodriver_handle Enumerations Wi-Fi Default API Reference Header File This header file can be included with: #include "esp_wifi_default.h" This header file is a part of the API provided by the esp_wifi component. To declare that your component depends on esp_wifi , add the following to your CMakeLists.txt: REQUIRES esp_wifi or PRIV_REQUIRES esp_wifi Functions esp_err_t esp_netif_attach_wifi_station(esp_netif_t *esp_netif) Attaches wifi station interface to supplied netif. Parameters esp_netif -- instance to attach the wifi station to Returns ESP_OK on success ESP_FAIL if attach failed ESP_OK on success ESP_FAIL if attach failed ESP_OK on success Parameters esp_netif -- instance to attach the wifi station to Returns ESP_OK on success ESP_FAIL if attach failed esp_err_t esp_netif_attach_wifi_ap(esp_netif_t *esp_netif) Attaches wifi soft AP interface to supplied netif. Parameters esp_netif -- instance to attach the wifi AP to Returns ESP_OK on success ESP_FAIL if attach failed ESP_OK on success ESP_FAIL if attach failed ESP_OK on success Parameters esp_netif -- instance to attach the wifi AP to Returns ESP_OK on success ESP_FAIL if attach failed esp_err_t esp_wifi_set_default_wifi_sta_handlers(void) Sets default wifi event handlers for STA interface. Returns ESP_OK on success, error returned from esp_event_handler_register if failed ESP_OK on success, error returned from esp_event_handler_register if failed ESP_OK on success, error returned from esp_event_handler_register if failed Returns ESP_OK on success, error returned from esp_event_handler_register if failed esp_err_t esp_wifi_set_default_wifi_ap_handlers(void) Sets default wifi event handlers for AP interface. Returns ESP_OK on success, error returned from esp_event_handler_register if failed ESP_OK on success, error returned from esp_event_handler_register if failed ESP_OK on success, error returned from esp_event_handler_register if failed Returns ESP_OK on success, error returned from esp_event_handler_register if failed esp_err_t esp_wifi_set_default_wifi_nan_handlers(void) Sets default wifi event handlers for NAN interface. Returns ESP_OK on success, error returned from esp_event_handler_register if failed ESP_OK on success, error returned from esp_event_handler_register if failed ESP_OK on success, error returned from esp_event_handler_register if failed Returns ESP_OK on success, error returned from esp_event_handler_register if failed esp_err_t esp_wifi_clear_default_wifi_driver_and_handlers(void *esp_netif) Clears default wifi event handlers for supplied network interface. Parameters esp_netif -- instance of corresponding if object Returns ESP_OK on success, error returned from esp_event_handler_register if failed ESP_OK on success, error returned from esp_event_handler_register if failed ESP_OK on success, error returned from esp_event_handler_register if failed Parameters esp_netif -- instance of corresponding if object Returns ESP_OK on success, error returned from esp_event_handler_register if failed esp_netif_t *esp_netif_create_default_wifi_ap(void) Creates default WIFI AP. In case of any init error this API aborts. Note The API creates esp_netif object with default WiFi access point config, attaches the netif to wifi and registers wifi handlers to the default event loop. This API uses assert() to check for potential errors, so it could abort the program. (Note that the default event loop needs to be created prior to calling this API) Returns pointer to esp-netif instance Returns pointer to esp-netif instance esp_netif_t *esp_netif_create_default_wifi_sta(void) Creates default WIFI STA. In case of any init error this API aborts. Note The API creates esp_netif object with default WiFi station config, attaches the netif to wifi and registers wifi handlers to the default event loop. This API uses assert() to check for potential errors, so it could abort the program. (Note that the default event loop needs to be created prior to calling this API) Returns pointer to esp-netif instance Returns pointer to esp-netif instance esp_netif_t *esp_netif_create_default_wifi_nan(void) Creates default WIFI NAN. In case of any init error this API aborts. Note The API creates esp_netif object with default WiFi station config, attaches the netif to wifi and registers wifi handlers to the default event loop. (Note that the default event loop needs to be created prior to calling this API) Returns pointer to esp-netif instance Returns pointer to esp-netif instance void esp_netif_destroy_default_wifi(void *esp_netif) Destroys default WIFI netif created with esp_netif_create_default_wifi_...() API. Note This API unregisters wifi handlers and detaches the created object from the wifi. (this function is a no-operation if esp_netif is NULL) Parameters esp_netif -- [in] object to detach from WiFi and destroy Parameters esp_netif -- [in] object to detach from WiFi and destroy esp_netif_t *esp_netif_create_wifi(wifi_interface_t wifi_if, const esp_netif_inherent_config_t *esp_netif_config) Creates esp_netif WiFi object based on the custom configuration. Attention This API DOES NOT register default handlers! Attention This API DOES NOT register default handlers! Parameters wifi_if -- [in] type of wifi interface esp_netif_config -- [in] inherent esp-netif configuration pointer wifi_if -- [in] type of wifi interface esp_netif_config -- [in] inherent esp-netif configuration pointer wifi_if -- [in] type of wifi interface Returns pointer to esp-netif instance Parameters wifi_if -- [in] type of wifi interface esp_netif_config -- [in] inherent esp-netif configuration pointer Returns pointer to esp-netif instance esp_err_t esp_netif_create_default_wifi_mesh_netifs(esp_netif_t **p_netif_sta, esp_netif_t **p_netif_ap) Creates default STA and AP network interfaces for esp-mesh. Both netifs are almost identical to the default station and softAP, but with DHCP client and server disabled. Please note that the DHCP client is typically enabled only if the device is promoted to a root node. Returns created interfaces which could be ignored setting parameters to NULL if an application code does not need to save the interface instances for further processing. Parameters p_netif_sta -- [out] pointer where the resultant STA interface is saved (if non NULL) p_netif_ap -- [out] pointer where the resultant AP interface is saved (if non NULL) p_netif_sta -- [out] pointer where the resultant STA interface is saved (if non NULL) p_netif_ap -- [out] pointer where the resultant AP interface is saved (if non NULL) p_netif_sta -- [out] pointer where the resultant STA interface is saved (if non NULL) Returns ESP_OK on success Parameters p_netif_sta -- [out] pointer where the resultant STA interface is saved (if non NULL) p_netif_ap -- [out] pointer where the resultant AP interface is saved (if non NULL) Returns ESP_OK on success
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 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. ESP-NETIF Architecture | (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_transmit |--<------| netif_output | | | | | | | | | | | |--->----|---| esp_netif_receive |-->------| netif_input | | | | | | | + ----------------+ | | |...<....|...| esp_netif_free_rx_buffer |...<.....| packet buffer | +-----| | | | | | | | | | | | | (D) | (B) | | | | (C) | +-----------------------+ --------+ | | +===========================+ COMMUNICATION | | NETWORK STACK DRIVER | | ESP-NETIF | | +------------------+ | | +---------------------------+.........| open/close | | | | | | | | -<--| l2tap_write |-----<---| write | | | | | | ---->--| esp_vfs_l2tap_eth_filter |----->---| read | | | | | | (E) | +------------------+ +---------------------------+ USER CODE ESP-NETIF L2 TAP Data and Event Flow in the Diagram ........Initialization line from user code to ESP-NETIF and communication driver --<--->--Data packets going from communication media to TCP/IP stack and back ********Events aggregated in ESP-NETIF propagate to the driver, user code, and network stack |User settings and runtime configuration 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: Initialization code - Initializes IO driver - Creates a new instance of ESP-NETIF and configure it with - ESP-NETIF specific options (flags, behavior, name) - Network stack options (netif init and input functions, not publicly available) - IO driver specific options (transmit, free rx buffer functions, IO driver handle) - Attaches the IO driver handle to the ESP-NETIF instance created in the above steps - Configures event handlers - Use default handlers for common interfaces defined in IO drivers; or define a specific handler for customized behavior or new interfaces - Register handlers for app-related events (such as IP lost or acquired) Interaction with network interfaces using ESP-NETIF API - Gets and sets TCP/IP-related parameters (DHCP, IP, etc) - Receives IP events (connect or disconnect) - 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: Event handlers: Defines behavior patterns of interaction with ESP-NETIF (e.g., ethernet link-up -> turn netif on) Glue IO layer: Adapts the input or output functions to use ESP-NETIF transmit, receive, and free receive buffer - Installs driver_transmit to the appropriate ESP-NETIF object so that outgoing packets from the network stack are passed to the IO driver - Calls esp_netif_receive()to pass incoming data to the network stack 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: Initialization APIs (to create and configure ESP-NETIF instance) Input or Output API (for passing data between IO driver and network stack) Event or Action API - Used for network interface lifecycle management - ESP-NETIF provides building blocks for designing event handlers Setters and Getters API for basic network interface properties Network stack abstraction API: enabling user interaction with TCP/IP stack - Set interface up or down - DHCP server and client API - DNS API - 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. 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 Virtual Filesystem Component. 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. 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 CONFIG_ESP_NETIF_L2_TAP first and then registered by esp_vfs_l2tap_intf_register() prior usage of any VFS function. 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 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. The following configuration options are available to do so: - L2TAP_S_INTF_DEVICE- bounds the file descriptor to a specific Network Interface that is identified by its if_key. ESP-NETIF Network Interface if_keyis passed to ioctl()as the third parameter. Note that default Network Interfaces if_key's used in ESP-IDF can be found in esp_netif/include/esp_netif_defaults.h. - L2TAP_S_DEVICE_DRV_HNDL- is another way to bound the file descriptor to a specific Network Interface. In this case, the Network interface is identified directly by IO Driver handle (e.g., esp_eth_handle_tin case of Ethernet). The IO Driver handle is passed to ioctl()as the third parameter. - L2TAP_S_RCV_FILTER- sets the filter to frames with the type to be passed to the file descriptor. In the case of Ethernet frames, the frames are to be filtered based on the Length and Ethernet type field. In case the filter value is set less than or equal to 0x05DC, the Ethernet type field is considered to represent IEEE802.3 Length Field, and all frames with values in interval <0, 0x05DC> at that field are passed to the file descriptor. The IEEE802.2 logical link control (LLC) resolution is then expected to be performed by the user's application. In case the filter value is set greater than 0x05DC, the Ethernet type field is considered to represent protocol identification and only frames that are equal to the set value are to be passed to the file descriptor. 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. ioctl() returns 0. On error, -1 is returned, and errno is set to indicate the error. 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: - F_GETFD- the function returns the file descriptor flags, and the third argument is ignored. - F_SETFD- sets the file descriptor flags to the value specified by the third argument. Zero is returned. ioctl() returns 0. On error, -1 is returned, and errno is set to indicate the error. 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. 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 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). 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. O_NONBLOCK), and the read would block. 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: | Destination MAC | Source MAC | Type/Length | Payload (protocol header/data) | 6 B | 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. 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. 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. 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. The first's task read operation then ends with an error. close() returns zero. On error, -1 is returned, and errno is set to indicate the error. select() Select is used in a standard way, just CONFIG_VFS_SUPPORT_SELECT needs to be enabled to make the select() function available. SNTP API You can find a brief introduction to SNTP in general, its initialization code, and basic modes in Section SNTP Time Synchronization in 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: Initialize and configure the service using esp_netif_sntp_init(). Start the service via esp_netif_sntp_start(). 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. Wait for the system time to synchronize using esp_netif_sntp_sync_wait()(only if needed). Stop and destroy the service using 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: 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 CONFIG_LWIP_SNTP_MAX_SERVERS. Use DHCP-Obtained SNTP Server(s) First of all, we have to enable the lwIP configuration option CONFIG_LWIP_DHCP_GET_NTP_SRV. Then we have to initialize the SNTP module with the DHCP option and without the NTP server: 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: 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. 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). 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.ip_event_to_renew = IP_EVENT_STA_GOT_IP; // IP event on which we refresh the configuration Then we start the service normally with esp_netif_sntp_start(). ESP-NETIF Programmer's Manual Please refer to the following example to understand the initialization process of the default interface: Wi-Fi Station: wifi/getting_started/station/main/station_example_main.c Wi-Fi Access Point: wifi/getting_started/softAP/main/softap_example_main.c For more specific cases, please consult this guide: ESP-NETIF Custom I/O Driver. 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: 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: The created object has to be destroyed if a network de-initialization is provided by an application using esp_netif_destroy_default_wifi(). These default interfaces must not be created multiple times unless the created handle is deleted using esp_netif_destroy(). When using Wi-Fi in AP+STAmode, both these interfaces have to be created. API Reference Header File This header file can be included with: #include "esp_netif.h" This header file is a part of the API provided by the esp_netifcomponent. To declare that your component depends on esp_netif, add the following to your CMakeLists.txt: REQUIRES esp_netif or PRIV_REQUIRES esp_netif Functions - esp_err_t esp_netif_init(void) Initialize the underlying TCP/IP stack. Note This function should be called exactly once from application code, when the application starts up. - Returns ESP_OK on success ESP_FAIL if initializing failed - - esp_err_t esp_netif_deinit(void) Deinitialize the esp-netif component (and the underlying TCP/IP stack) Note: Deinitialization is not supported yet - Returns ESP_ERR_INVALID_STATE if esp_netif not initialized ESP_ERR_NOT_SUPPORTED otherwise - - esp_netif_t *esp_netif_new(const esp_netif_config_t *esp_netif_config) Creates an instance of new esp-netif object based on provided config. - Parameters esp_netif_config -- [in] pointer esp-netif configuration - Returns pointer to esp-netif object on success NULL otherwise - - void esp_netif_destroy(esp_netif_t *esp_netif) Destroys the esp_netif object. - Parameters esp_netif -- [in] pointer to the object to be deleted - esp_err_t esp_netif_set_driver_config(esp_netif_t *esp_netif, const esp_netif_driver_ifconfig_t *driver_config) Configures driver related options of esp_netif object. - Parameters esp_netif -- [inout] pointer to the object to be configured driver_config -- [in] pointer esp-netif io driver related configuration - - Returns ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS if invalid parameters provided - - esp_err_t esp_netif_attach(esp_netif_t *esp_netif, esp_netif_iodriver_handle driver_handle) Attaches esp_netif instance to the io driver handle. Calling this function enables connecting specific esp_netif object with already initialized io driver to update esp_netif object with driver specific configuration (i.e. calls post_attach callback, which typically sets io driver callbacks to esp_netif instance and starts the driver) - Parameters esp_netif -- [inout] pointer to esp_netif object to be attached driver_handle -- [in] pointer to the driver handle - - Returns ESP_OK on success ESP_ERR_ESP_NETIF_DRIVER_ATTACH_FAILED if driver's pot_attach callback failed - - esp_err_t esp_netif_receive(esp_netif_t *esp_netif, void *buffer, size_t len, void *eb) Passes the raw packets from communication media to the appropriate TCP/IP stack. This function is called from the configured (peripheral) driver layer. The data are then forwarded as frames to the TCP/IP stack. - Parameters esp_netif -- [in] Handle to esp-netif instance buffer -- [in] Received data len -- [in] Length of the data frame eb -- [in] Pointer to internal buffer (used in Wi-Fi driver) - - Returns ESP_OK - - void esp_netif_action_start(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IO driver start event Creates network interface, if AUTOUP enabled turns the interface on, if DHCPS enabled starts dhcp server. Note This API can be directly used as event handler - Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event - - void esp_netif_action_stop(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IO driver stop event. Note This API can be directly used as event handler - Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event - - void esp_netif_action_connected(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IO driver connected event. Note This API can be directly used as event handler - Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event - - void esp_netif_action_disconnected(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IO driver disconnected event. Note This API can be directly used as event handler - Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event - - void esp_netif_action_got_ip(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon network got IP event. Note This API can be directly used as event handler - Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event - - void esp_netif_action_join_ip6_multicast_group(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IPv6 multicast group join. Note This API can be directly used as event handler - Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event - - void esp_netif_action_leave_ip6_multicast_group(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IPv6 multicast group leave. Note This API can be directly used as event handler - Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event - - void esp_netif_action_add_ip6_address(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IPv6 address added by the underlying stack. Note This API can be directly used as event handler - Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event - - void esp_netif_action_remove_ip6_address(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IPv6 address removed by the underlying stack. Note This API can be directly used as event handler - Parameters esp_netif -- [in] Handle to esp-netif instance base -- The base type of the event event_id -- The specific ID of the event data -- Optional data associated with the event - - esp_err_t esp_netif_set_default_netif(esp_netif_t *esp_netif) Manual configuration of the default netif. This API overrides the automatic configuration of the default interface based on the route_prio If the selected netif is set default using this API, no other interface could be set-default disregarding its route_prio number (unless the selected netif gets destroyed) - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns ESP_OK on success - esp_netif_t *esp_netif_get_default_netif(void) Getter function of the default netif. This API returns the selected default netif. - Returns Handle to esp-netif instance of the default netif. - esp_err_t esp_netif_join_ip6_multicast_group(esp_netif_t *esp_netif, const esp_ip6_addr_t *addr) Cause the TCP/IP stack to join a IPv6 multicast group. - Parameters esp_netif -- [in] Handle to esp-netif instance addr -- [in] The multicast group to join - - Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_MLD6_FAILED ESP_ERR_NO_MEM - - esp_err_t esp_netif_leave_ip6_multicast_group(esp_netif_t *esp_netif, const esp_ip6_addr_t *addr) Cause the TCP/IP stack to leave a IPv6 multicast group. - Parameters esp_netif -- [in] Handle to esp-netif instance addr -- [in] The multicast group to leave - - Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_MLD6_FAILED ESP_ERR_NO_MEM - - esp_err_t esp_netif_set_mac(esp_netif_t *esp_netif, uint8_t mac[]) Set the mac address for the interface instance. - Parameters esp_netif -- [in] Handle to esp-netif instance mac -- [in] Desired mac address for the related network interface - - Returns ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_NOT_SUPPORTED - mac not supported on this interface - - esp_err_t esp_netif_get_mac(esp_netif_t *esp_netif, uint8_t mac[]) Get the mac address for the interface instance. - Parameters esp_netif -- [in] Handle to esp-netif instance mac -- [out] Resultant mac address for the related network interface - - Returns ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_NOT_SUPPORTED - mac not supported on this interface - - esp_err_t esp_netif_set_hostname(esp_netif_t *esp_netif, const char *hostname) Set the hostname of an interface. The configured hostname overrides the default configuration value CONFIG_LWIP_LOCAL_HOSTNAME. Please note that when the hostname is altered after interface started/connected the changes would only be reflected once the interface restarts/reconnects - Parameters esp_netif -- [in] Handle to esp-netif instance hostname -- [in] New hostname for the interface. Maximum length 32 bytes. - - Returns ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_ESP_NETIF_INVALID_PARAMS - parameter error - - esp_err_t esp_netif_get_hostname(esp_netif_t *esp_netif, const char **hostname) Get interface hostname. - Parameters esp_netif -- [in] Handle to esp-netif instance hostname -- [out] Returns a pointer to the hostname. May be NULL if no hostname is set. If set non-NULL, pointer remains valid (and string may change if the hostname changes). - - Returns ESP_OK - success ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error ESP_ERR_ESP_NETIF_INVALID_PARAMS - parameter error - - bool esp_netif_is_netif_up(esp_netif_t *esp_netif) Test if supplied interface is up or down. - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns true - Interface is up false - Interface is down - - esp_err_t esp_netif_get_ip_info(esp_netif_t *esp_netif, esp_netif_ip_info_t *ip_info) Get interface's IP address information. If the interface is up, IP information is read directly from the TCP/IP stack. If the interface is down, IP information is read from a copy kept in the ESP-NETIF instance - Parameters esp_netif -- [in] Handle to esp-netif instance ip_info -- [out] If successful, IP information will be returned in this argument. - - Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS - - esp_err_t esp_netif_get_old_ip_info(esp_netif_t *esp_netif, esp_netif_ip_info_t *ip_info) Get interface's old IP information. Returns an "old" IP address previously stored for the interface when the valid IP changed. If the IP lost timer has expired (meaning the interface was down for longer than the configured interval) then the old IP information will be zero. - Parameters esp_netif -- [in] Handle to esp-netif instance ip_info -- [out] If successful, IP information will be returned in this argument. - - Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS - - esp_err_t esp_netif_set_ip_info(esp_netif_t *esp_netif, const esp_netif_ip_info_t *ip_info) Set interface's IP address information. This function is mainly used to set a static IP on an interface. If the interface is up, the new IP information is set directly in the TCP/IP stack. The copy of IP information kept in the ESP-NETIF instance is also updated (this copy is returned if the IP is queried while the interface is still down.) Note DHCP client/server must be stopped (if enabled for this interface) before setting new IP information. Note Calling this interface for may generate a SYSTEM_EVENT_STA_GOT_IP or SYSTEM_EVENT_ETH_GOT_IP event. - Parameters esp_netif -- [in] Handle to esp-netif instance ip_info -- [in] IP information to set on the specified interface - - Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_NOT_STOPPED If DHCP server or client is still running - - esp_err_t esp_netif_set_old_ip_info(esp_netif_t *esp_netif, const esp_netif_ip_info_t *ip_info) Set interface old IP information. This function is called from the DHCP client (if enabled), before a new IP is set. It is also called from the default handlers for the SYSTEM_EVENT_STA_CONNECTED and SYSTEM_EVENT_ETH_CONNECTED events. Calling this function stores the previously configured IP, which can be used to determine if the IP changes in the future. If the interface is disconnected or down for too long, the "IP lost timer" will expire (after the configured interval) and set the old IP information to zero. - Parameters esp_netif -- [in] Handle to esp-netif instance ip_info -- [in] Store the old IP information for the specified interface - - Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS - - int esp_netif_get_netif_impl_index(esp_netif_t *esp_netif) Get net interface index from network stack implementation. Note This index could be used in setsockopt()to bind socket with multicast interface - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns implementation specific index of interface represented with supplied esp_netif - esp_err_t esp_netif_get_netif_impl_name(esp_netif_t *esp_netif, char *name) Get net interface name from network stack implementation. Note This name could be used in setsockopt()to bind socket with appropriate interface - Parameters esp_netif -- [in] Handle to esp-netif instance name -- [out] Interface name as specified in underlying TCP/IP stack. Note that the actual name will be copied to the specified buffer, which must be allocated to hold maximum interface name size (6 characters for lwIP) - - Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS - - esp_err_t esp_netif_napt_enable(esp_netif_t *esp_netif) Enable NAPT on an interface. Note Enable operation can be performed only on one interface at a time. NAPT cannot be enabled on multiple interfaces according to this implementation. - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns ESP_OK ESP_FAIL ESP_ERR_NOT_SUPPORTED - - esp_err_t esp_netif_napt_disable(esp_netif_t *esp_netif) Disable NAPT on an interface. - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns ESP_OK ESP_FAIL ESP_ERR_NOT_SUPPORTED - - esp_err_t esp_netif_dhcps_option(esp_netif_t *esp_netif, esp_netif_dhcp_option_mode_t opt_op, esp_netif_dhcp_option_id_t opt_id, void *opt_val, uint32_t opt_len) Set or Get DHCP server option. - Parameters esp_netif -- [in] Handle to esp-netif instance opt_op -- [in] ESP_NETIF_OP_SET to set an option, ESP_NETIF_OP_GET to get an option. opt_id -- [in] Option index to get or set, must be one of the supported enum values. opt_val -- [inout] Pointer to the option parameter. opt_len -- [in] Length of the option parameter. - - Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED - - esp_err_t esp_netif_dhcpc_option(esp_netif_t *esp_netif, esp_netif_dhcp_option_mode_t opt_op, esp_netif_dhcp_option_id_t opt_id, void *opt_val, uint32_t opt_len) Set or Get DHCP client option. - Parameters esp_netif -- [in] Handle to esp-netif instance opt_op -- [in] ESP_NETIF_OP_SET to set an option, ESP_NETIF_OP_GET to get an option. opt_id -- [in] Option index to get or set, must be one of the supported enum values. opt_val -- [inout] Pointer to the option parameter. opt_len -- [in] Length of the option parameter. - - Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED - - esp_err_t esp_netif_dhcpc_start(esp_netif_t *esp_netif) Start DHCP client (only if enabled in interface object) Note The default event handlers for the SYSTEM_EVENT_STA_CONNECTED and SYSTEM_EVENT_ETH_CONNECTED events call this function. - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED ESP_ERR_ESP_NETIF_DHCPC_START_FAILED - - esp_err_t esp_netif_dhcpc_stop(esp_netif_t *esp_netif) Stop DHCP client (only if enabled in interface object) Note Calling action_netif_stop() will also stop the DHCP Client if it is running. - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_IF_NOT_READY - - esp_err_t esp_netif_dhcpc_get_status(esp_netif_t *esp_netif, esp_netif_dhcp_status_t *status) Get DHCP client status. - Parameters esp_netif -- [in] Handle to esp-netif instance status -- [out] If successful, the status of DHCP client will be returned in this argument. - - Returns ESP_OK - - esp_err_t esp_netif_dhcps_get_status(esp_netif_t *esp_netif, esp_netif_dhcp_status_t *status) Get DHCP Server status. - Parameters esp_netif -- [in] Handle to esp-netif instance status -- [out] If successful, the status of the DHCP server will be returned in this argument. - - Returns ESP_OK - - esp_err_t esp_netif_dhcps_start(esp_netif_t *esp_netif) Start DHCP server (only if enabled in interface object) - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED - - esp_err_t esp_netif_dhcps_stop(esp_netif_t *esp_netif) Stop DHCP server (only if enabled in interface object) - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_IF_NOT_READY - - esp_err_t esp_netif_dhcps_get_clients_by_mac(esp_netif_t *esp_netif, int num, esp_netif_pair_mac_ip_t *mac_ip_pair) Populate IP addresses of clients connected to DHCP server listed by their MAC addresses. - Parameters esp_netif -- [in] Handle to esp-netif instance num -- [in] Number of clients with specified MAC addresses in the array of pairs mac_ip_pair -- [inout] Array of pairs of MAC and IP addresses (MAC are inputs, IP outputs) - - Returns ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS on invalid params ESP_ERR_NOT_SUPPORTED if DHCP server not enabled - - esp_err_t esp_netif_set_dns_info(esp_netif_t *esp_netif, esp_netif_dns_type_t type, esp_netif_dns_info_t *dns) Set DNS Server information. This function behaves differently if DHCP server or client is enabled If DHCP client is enabled, main and backup DNS servers will be updated automatically from the DHCP lease if the relevant DHCP options are set. Fallback DNS Server is never updated from the DHCP lease and is designed to be set via this API. If DHCP client is disabled, all DNS server types can be set via this API only. If DHCP server is enabled, the Main DNS Server setting is used by the DHCP server to provide a DNS Server option to DHCP clients (Wi-Fi stations). The default Main DNS server is typically the IP of the DHCP server itself. This function can override it by setting server type ESP_NETIF_DNS_MAIN. Other DNS Server types are not supported for the DHCP server. To propagate the DNS info to client, please stop the DHCP server before using this API. - Parameters esp_netif -- [in] Handle to esp-netif instance type -- [in] Type of DNS Server to set: ESP_NETIF_DNS_MAIN, ESP_NETIF_DNS_BACKUP, ESP_NETIF_DNS_FALLBACK dns -- [in] DNS Server address to set - - Returns ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS invalid params - - - esp_err_t esp_netif_get_dns_info(esp_netif_t *esp_netif, esp_netif_dns_type_t type, esp_netif_dns_info_t *dns) Get DNS Server information. Return the currently configured DNS Server address for the specified interface and Server type. This may be result of a previous call to esp_netif_set_dns_info(). If the interface's DHCP client is enabled, the Main or Backup DNS Server may be set by the current DHCP lease. - Parameters esp_netif -- [in] Handle to esp-netif instance type -- [in] Type of DNS Server to get: ESP_NETIF_DNS_MAIN, ESP_NETIF_DNS_BACKUP, ESP_NETIF_DNS_FALLBACK dns -- [out] DNS Server result is written here on success - - Returns ESP_OK on success ESP_ERR_ESP_NETIF_INVALID_PARAMS invalid params - - esp_err_t esp_netif_create_ip6_linklocal(esp_netif_t *esp_netif) Create interface link-local IPv6 address. Cause the TCP/IP stack to create a link-local IPv6 address for the specified interface. This function also registers a callback for the specified interface, so that if the link-local address becomes verified as the preferred address then a SYSTEM_EVENT_GOT_IP6 event will be sent. - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns ESP_OK ESP_ERR_ESP_NETIF_INVALID_PARAMS - - esp_err_t esp_netif_get_ip6_linklocal(esp_netif_t *esp_netif, esp_ip6_addr_t *if_ip6) Get interface link-local IPv6 address. If the specified interface is up and a preferred link-local IPv6 address has been created for the interface, return a copy of it. - Parameters esp_netif -- [in] Handle to esp-netif instance if_ip6 -- [out] IPv6 information will be returned in this argument if successful. - - Returns ESP_OK ESP_FAIL If interface is down, does not have a link-local IPv6 address, or the link-local IPv6 address is not a preferred address. - - esp_err_t esp_netif_get_ip6_global(esp_netif_t *esp_netif, esp_ip6_addr_t *if_ip6) Get interface global IPv6 address. If the specified interface is up and a preferred global IPv6 address has been created for the interface, return a copy of it. - Parameters esp_netif -- [in] Handle to esp-netif instance if_ip6 -- [out] IPv6 information will be returned in this argument if successful. - - Returns ESP_OK ESP_FAIL If interface is down, does not have a global IPv6 address, or the global IPv6 address is not a preferred address. - - int esp_netif_get_all_ip6(esp_netif_t *esp_netif, esp_ip6_addr_t if_ip6[]) Get all IPv6 addresses of the specified interface. - Parameters esp_netif -- [in] Handle to esp-netif instance if_ip6 -- [out] Array of IPv6 addresses will be copied to the argument - - Returns number of returned IPv6 addresses - void esp_netif_set_ip4_addr(esp_ip4_addr_t *addr, uint8_t a, uint8_t b, uint8_t c, uint8_t d) Sets IPv4 address to the specified octets. - Parameters addr -- [out] IP address to be set a -- the first octet (127 for IP 127.0.0.1) b -- c -- d -- - - char *esp_ip4addr_ntoa(const esp_ip4_addr_t *addr, char *buf, int buflen) Converts numeric IP address into decimal dotted ASCII representation. - Parameters addr -- ip address in network order to convert buf -- target buffer where the string is stored buflen -- length of buf - - Returns either pointer to buf which now holds the ASCII representation of addr or NULL if buf was too small - uint32_t esp_ip4addr_aton(const char *addr) Ascii internet address interpretation routine The value returned is in network order. - Parameters addr -- IP address in ascii representation (e.g. "127.0.0.1") - Returns ip address in network order - esp_err_t esp_netif_str_to_ip4(const char *src, esp_ip4_addr_t *dst) Converts Ascii internet IPv4 address into esp_ip4_addr_t. - Parameters src -- [in] IPv4 address in ascii representation (e.g. "127.0.0.1") dst -- [out] Address of the target esp_ip4_addr_t structure to receive converted address - - Returns ESP_OK on success ESP_FAIL if conversion failed ESP_ERR_INVALID_ARG if invalid parameter is passed into - - esp_err_t esp_netif_str_to_ip6(const char *src, esp_ip6_addr_t *dst) Converts Ascii internet IPv6 address into esp_ip4_addr_t Zeros in the IP address can be stripped or completely ommited: "2001:db8:85a3:0:0:0:2:1" or "2001:db8::2:1") - Parameters src -- [in] IPv6 address in ascii representation (e.g. ""2001:0db8:85a3:0000:0000:0000:0002:0001") dst -- [out] Address of the target esp_ip6_addr_t structure to receive converted address - - Returns ESP_OK on success ESP_FAIL if conversion failed ESP_ERR_INVALID_ARG if invalid parameter is passed into - - esp_netif_iodriver_handle esp_netif_get_io_driver(esp_netif_t *esp_netif) Gets media driver handle for this esp-netif instance. - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns opaque pointer of related IO driver - esp_netif_t *esp_netif_get_handle_from_ifkey(const char *if_key) Searches over a list of created objects to find an instance with supplied if key. - Parameters if_key -- Textual description of network interface - Returns Handle to esp-netif instance - esp_netif_flags_t esp_netif_get_flags(esp_netif_t *esp_netif) Returns configured flags for this interface. - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns Configuration flags - const char *esp_netif_get_ifkey(esp_netif_t *esp_netif) Returns configured interface key for this esp-netif instance. - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns Textual description of related interface - const char *esp_netif_get_desc(esp_netif_t *esp_netif) Returns configured interface type for this esp-netif instance. - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns Enumerated type of this interface, such as station, AP, ethernet - int esp_netif_get_route_prio(esp_netif_t *esp_netif) Returns configured routing priority number. - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns Integer representing the instance's route-prio, or -1 if invalid paramters - int32_t esp_netif_get_event_id(esp_netif_t *esp_netif, esp_netif_ip_event_type_t event_type) Returns configured event for this esp-netif instance and supplied event type. - Parameters esp_netif -- [in] Handle to esp-netif instance event_type -- (either get or lost IP) - - Returns specific event id which is configured to be raised if the interface lost or acquired IP address -1 if supplied event_type is not known - esp_netif_t *esp_netif_next(esp_netif_t *esp_netif) Iterates over list of interfaces. Returns first netif if NULL given as parameter. Note This API doesn't lock the list, nor the TCPIP context, as this it's usually required to get atomic access between iteration steps rather that within a single iteration. Therefore it is recommended to iterate over the interfaces inside esp_netif_tcpip_exec() Note This API is deprecated. Please use esp_netif_next_unsafe() directly if all the system interfaces are under your control and you can safely iterate over them. Otherwise, iterate over interfaces using esp_netif_tcpip_exec(), or use esp_netif_find_if() to search in the list of netifs with defined predicate. - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns First netif from the list if supplied parameter is NULL, next one otherwise - esp_netif_t *esp_netif_next_unsafe(esp_netif_t *esp_netif) Iterates over list of interfaces without list locking. Returns first netif if NULL given as parameter. Used for bulk search loops within TCPIP context, e.g. using esp_netif_tcpip_exec(), or if we're sure that the iteration is safe from our application perspective (e.g. no interface is removed between iterations) - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns First netif from the list if supplied parameter is NULL, next one otherwise - esp_netif_t *esp_netif_find_if(esp_netif_find_predicate_t fn, void *ctx) Return a netif pointer for the first interface that meets criteria defined by the callback. - Parameters fn -- Predicate function returning true for the desired interface ctx -- Context pointer passed to the predicate, typically a descriptor to compare with - - Returns valid netif pointer if found, NULL if not - size_t esp_netif_get_nr_of_ifs(void) Returns number of registered esp_netif objects. - Returns Number of esp_netifs - void esp_netif_netstack_buf_ref(void *netstack_buf) increase the reference counter of net stack buffer - Parameters netstack_buf -- [in] the net stack buffer - void esp_netif_netstack_buf_free(void *netstack_buf) free the netstack buffer - Parameters netstack_buf -- [in] the net stack buffer - esp_err_t esp_netif_tcpip_exec(esp_netif_callback_fn fn, void *ctx) Utility to execute the supplied callback in TCP/IP context. - Parameters fn -- Pointer to the callback ctx -- Parameter to the callback - - Returns The error code (esp_err_t) returned by the callback Type Definitions - typedef bool (*esp_netif_find_predicate_t)(esp_netif_t *netif, void *ctx) Predicate callback for esp_netif_find_if() used to find interface which meets defined criteria. - typedef esp_err_t (*esp_netif_callback_fn)(void *ctx) TCPIP thread safe callback used with esp_netif_tcpip_exec() Header File This header file can be included with: #include "esp_netif_sntp.h" This header file is a part of the API provided by the esp_netifcomponent. To declare that your component depends on esp_netif, add the following to your CMakeLists.txt: REQUIRES esp_netif or PRIV_REQUIRES esp_netif Functions - esp_err_t esp_netif_sntp_init(const esp_sntp_config_t *config) Initialize SNTP with supplied config struct. - Parameters config -- Config struct - Returns ESP_OK on success - esp_err_t esp_netif_sntp_start(void) Start SNTP service if it wasn't started during init (config.start = false) or restart it if already started. - Returns ESP_OK on success - void esp_netif_sntp_deinit(void) Deinitialize esp_netif SNTP module. - esp_err_t esp_netif_sntp_sync_wait(TickType_t tout) Wait for time sync event. - Parameters tout -- Specified timeout in RTOS ticks - Returns ESP_TIMEOUT if sync event didn't came withing the timeout ESP_ERR_NOT_FINISHED if the sync event came, but we're in smooth update mode and still in progress (SNTP_SYNC_STATUS_IN_PROGRESS) ESP_OK if time sync'ed Structures - struct esp_sntp_config SNTP configuration struct. Public Members - bool smooth_sync set to true if smooth sync required - bool server_from_dhcp set to true to request NTP server config from DHCP - bool wait_for_sync if true, we create a semaphore to signal time sync event - bool start set to true to automatically start the SNTP service - esp_sntp_time_cb_t sync_cb optionally sets callback function on time sync event - bool renew_servers_after_new_IP this is used to refresh server list if NTP provided by DHCP (which cleans other pre-configured servers) - ip_event_t ip_event_to_renew set the IP event id on which we refresh server list (if renew_servers_after_new_IP=true) - size_t index_of_first_server refresh server list after this server (if renew_servers_after_new_IP=true) - size_t num_of_servers number of preconfigured NTP servers - const char *servers[1] list of servers - bool smooth_sync Macros - ESP_SNTP_SERVER_LIST(...) Utility macro for providing multiple servers in parentheses. - ESP_NETIF_SNTP_DEFAULT_CONFIG_MULTIPLE(servers_in_list, list_of_servers) Default configuration to init SNTP with multiple servers. - Parameters servers_in_list -- Number of servers in the list list_of_servers -- List of servers (use ESP_SNTP_SERVER_LIST(...)) - - ESP_NETIF_SNTP_DEFAULT_CONFIG(server) Default configuration with a single server. Type Definitions - typedef void (*esp_sntp_time_cb_t)(struct timeval *tv) Time sync notification function. - typedef struct esp_sntp_config esp_sntp_config_t SNTP configuration struct. Header File This header file can be included with: #include "esp_netif_types.h" This header file is a part of the API provided by the esp_netifcomponent. To declare that your component depends on esp_netif, add the following to your CMakeLists.txt: REQUIRES esp_netif or PRIV_REQUIRES esp_netif Structures - struct esp_netif_dns_info_t DNS server info. Public Members - esp_ip_addr_t ip IPV4 address of DNS server - esp_ip_addr_t ip - struct esp_netif_ip_info_t Event structure for IP_EVENT_STA_GOT_IP, IP_EVENT_ETH_GOT_IP events Public Members - esp_ip4_addr_t ip Interface IPV4 address - esp_ip4_addr_t netmask Interface IPV4 netmask - esp_ip4_addr_t gw Interface IPV4 gateway address - esp_ip4_addr_t ip - struct esp_netif_ip6_info_t IPV6 IP address information. Public Members - esp_ip6_addr_t ip Interface IPV6 address - esp_ip6_addr_t ip - struct ip_event_got_ip_t Event structure for IP_EVENT_GOT_IP event. Public Members - esp_netif_t *esp_netif Pointer to corresponding esp-netif object - esp_netif_ip_info_t ip_info IP address, netmask, gatway IP address - bool ip_changed Whether the assigned IP has changed or not - esp_netif_t *esp_netif - struct ip_event_got_ip6_t Event structure for IP_EVENT_GOT_IP6 event Public Members - esp_netif_t *esp_netif Pointer to corresponding esp-netif object - esp_netif_ip6_info_t ip6_info IPv6 address of the interface - int ip_index IPv6 address index - esp_netif_t *esp_netif - struct ip_event_add_ip6_t Event structure for ADD_IP6 event Public Members - esp_ip6_addr_t addr The address to be added to the interface - bool preferred The default preference of the address - esp_ip6_addr_t addr - struct ip_event_ap_staipassigned_t Event structure for IP_EVENT_AP_STAIPASSIGNED event Public Members - esp_netif_t *esp_netif Pointer to the associated netif handle - esp_ip4_addr_t ip IP address which was assigned to the station - uint8_t mac[6] MAC address of the connected client - esp_netif_t *esp_netif - struct bridgeif_config LwIP bridge configuration - struct esp_netif_inherent_config ESP-netif inherent config parameters. Public Members - esp_netif_flags_t flags flags that define esp-netif behavior - uint8_t mac[6] initial mac address for this interface - const esp_netif_ip_info_t *ip_info initial ip address for this interface - uint32_t get_ip_event event id to be raised when interface gets an IP - uint32_t lost_ip_event event id to be raised when interface losts its IP - const char *if_key string identifier of the interface - const char *if_desc textual description of the interface - int route_prio numeric priority of this interface to become a default routing if (if other netifs are up). A higher value of route_prio indicates a higher priority - bridgeif_config_t *bridge_info LwIP bridge configuration - esp_netif_flags_t flags - struct esp_netif_driver_base_s ESP-netif driver base handle. Public Members - esp_err_t (*post_attach)(esp_netif_t *netif, esp_netif_iodriver_handle h) post attach function pointer - esp_netif_t *netif netif handle - esp_err_t (*post_attach)(esp_netif_t *netif, esp_netif_iodriver_handle h) - struct esp_netif_driver_ifconfig Specific IO driver configuration. Public Members - esp_netif_iodriver_handle handle io-driver handle - esp_err_t (*transmit_wrap)(void *h, void *buffer, size_t len, void *netstack_buffer) transmit wrap function pointer - void (*driver_free_rx_buffer)(void *h, void *buffer) free rx buffer function pointer - esp_netif_iodriver_handle handle - struct esp_netif_config Generic esp_netif configuration. Public Members - const esp_netif_inherent_config_t *base base config - const esp_netif_driver_ifconfig_t *driver driver config - const esp_netif_netstack_config_t *stack stack config - const esp_netif_inherent_config_t *base - struct esp_netif_pair_mac_ip_t DHCP client's addr info (pair of MAC and IP address) Public Members - uint8_t mac[6] Clients MAC address - esp_ip4_addr_t ip Clients IP address - uint8_t mac[6] Macros - ESP_ERR_ESP_NETIF_BASE Definition of ESP-NETIF based errors. - ESP_ERR_ESP_NETIF_INVALID_PARAMS - ESP_ERR_ESP_NETIF_IF_NOT_READY - ESP_ERR_ESP_NETIF_DHCPC_START_FAILED - ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED - ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED - ESP_ERR_ESP_NETIF_NO_MEM - ESP_ERR_ESP_NETIF_DHCP_NOT_STOPPED - ESP_ERR_ESP_NETIF_DRIVER_ATTACH_FAILED - ESP_ERR_ESP_NETIF_INIT_FAILED - ESP_ERR_ESP_NETIF_DNS_NOT_CONFIGURED - ESP_ERR_ESP_NETIF_MLD6_FAILED - ESP_ERR_ESP_NETIF_IP6_ADDR_FAILED - ESP_ERR_ESP_NETIF_DHCPS_START_FAILED - ESP_NETIF_BR_FLOOD Definition of ESP-NETIF bridge controll. - ESP_NETIF_BR_DROP - ESP_NETIF_BR_FDW_CPU Type Definitions - typedef struct esp_netif_obj esp_netif_t - typedef enum esp_netif_flags esp_netif_flags_t - typedef enum esp_netif_ip_event_type esp_netif_ip_event_type_t - typedef struct bridgeif_config bridgeif_config_t LwIP bridge configuration - typedef struct esp_netif_inherent_config esp_netif_inherent_config_t ESP-netif inherent config parameters. - typedef struct esp_netif_config esp_netif_config_t - typedef void *esp_netif_iodriver_handle IO driver handle type. - typedef struct esp_netif_driver_base_s esp_netif_driver_base_t ESP-netif driver base handle. - typedef struct esp_netif_driver_ifconfig esp_netif_driver_ifconfig_t - typedef struct esp_netif_netstack_config esp_netif_netstack_config_t Specific L3 network stack configuration. - typedef esp_err_t (*esp_netif_receive_t)(esp_netif_t *esp_netif, void *buffer, size_t len, void *eb) ESP-NETIF Receive function type. Enumerations - enum esp_netif_dns_type_t Type of DNS server. Values: - enumerator ESP_NETIF_DNS_MAIN DNS main server address - enumerator ESP_NETIF_DNS_BACKUP DNS backup server address (Wi-Fi STA and Ethernet only) - enumerator ESP_NETIF_DNS_FALLBACK DNS fallback server address (Wi-Fi STA and Ethernet only) - enumerator ESP_NETIF_DNS_MAX - enumerator ESP_NETIF_DNS_MAIN - enum esp_netif_dhcp_status_t Status of DHCP client or DHCP server. Values: - enumerator ESP_NETIF_DHCP_INIT DHCP client/server is in initial state (not yet started) - enumerator ESP_NETIF_DHCP_STARTED DHCP client/server has been started - enumerator ESP_NETIF_DHCP_STOPPED DHCP client/server has been stopped - enumerator ESP_NETIF_DHCP_STATUS_MAX - enumerator ESP_NETIF_DHCP_INIT - enum esp_netif_dhcp_option_mode_t Mode for DHCP client or DHCP server option functions. Values: - enumerator ESP_NETIF_OP_START - enumerator ESP_NETIF_OP_SET Set option - enumerator ESP_NETIF_OP_GET Get option - enumerator ESP_NETIF_OP_MAX - enumerator ESP_NETIF_OP_START - enum esp_netif_dhcp_option_id_t Supported options for DHCP client or DHCP server. Values: - enumerator ESP_NETIF_SUBNET_MASK Network mask - enumerator ESP_NETIF_DOMAIN_NAME_SERVER Domain name server - enumerator ESP_NETIF_ROUTER_SOLICITATION_ADDRESS Solicitation router address - enumerator ESP_NETIF_REQUESTED_IP_ADDRESS Request specific IP address - enumerator ESP_NETIF_IP_ADDRESS_LEASE_TIME Request IP address lease time - enumerator ESP_NETIF_IP_REQUEST_RETRY_TIME Request IP address retry counter - enumerator ESP_NETIF_VENDOR_CLASS_IDENTIFIER Vendor Class Identifier of a DHCP client - enumerator ESP_NETIF_VENDOR_SPECIFIC_INFO Vendor Specific Information of a DHCP server - enumerator ESP_NETIF_SUBNET_MASK - enum ip_event_t IP event declarations Values: - enumerator IP_EVENT_STA_GOT_IP station got IP from connected AP - enumerator IP_EVENT_STA_LOST_IP station lost IP and the IP is reset to 0 - enumerator IP_EVENT_AP_STAIPASSIGNED soft-AP assign an IP to a connected station - enumerator IP_EVENT_GOT_IP6 station or ap or ethernet interface v6IP addr is preferred - enumerator IP_EVENT_ETH_GOT_IP ethernet got IP from connected AP - enumerator IP_EVENT_ETH_LOST_IP ethernet lost IP and the IP is reset to 0 - enumerator IP_EVENT_PPP_GOT_IP PPP interface got IP - enumerator IP_EVENT_PPP_LOST_IP PPP interface lost IP - enumerator IP_EVENT_STA_GOT_IP - enum esp_netif_flags Values: - enumerator ESP_NETIF_DHCP_CLIENT - enumerator ESP_NETIF_DHCP_SERVER - enumerator ESP_NETIF_FLAG_AUTOUP - enumerator ESP_NETIF_FLAG_GARP - enumerator ESP_NETIF_FLAG_EVENT_IP_MODIFIED - enumerator ESP_NETIF_FLAG_IS_PPP - enumerator ESP_NETIF_FLAG_IS_BRIDGE - enumerator ESP_NETIF_FLAG_MLDV6_REPORT - enumerator ESP_NETIF_DHCP_CLIENT Header File This header file can be included with: #include "esp_netif_ip_addr.h" This header file is a part of the API provided by the esp_netifcomponent. To declare that your component depends on esp_netif, add the following to your CMakeLists.txt: REQUIRES esp_netif or PRIV_REQUIRES esp_netif Functions - esp_ip6_addr_type_t esp_netif_ip6_get_addr_type(esp_ip6_addr_t *ip6_addr) Get the IPv6 address type. - Parameters ip6_addr -- [in] IPv6 type - Returns IPv6 type in form of enum esp_ip6_addr_type_t - static inline void esp_netif_ip_addr_copy(esp_ip_addr_t *dest, const esp_ip_addr_t *src) Copy IP addresses. - Parameters dest -- [out] destination IP src -- [in] source IP - Structures - struct esp_ip6_addr IPv6 address. - struct _ip_addr IP address. Public Members - esp_ip6_addr_t ip6 IPv6 address type - esp_ip4_addr_t ip4 IPv4 address type - uint8_t type ipaddress type - esp_ip6_addr_t ip6 Macros - esp_netif_htonl(x) - esp_netif_ip4_makeu32(a, b, c, d) - ESP_IP6_ADDR_BLOCK1(ip6addr) - ESP_IP6_ADDR_BLOCK2(ip6addr) - ESP_IP6_ADDR_BLOCK3(ip6addr) - ESP_IP6_ADDR_BLOCK4(ip6addr) - ESP_IP6_ADDR_BLOCK5(ip6addr) - ESP_IP6_ADDR_BLOCK6(ip6addr) - ESP_IP6_ADDR_BLOCK7(ip6addr) - ESP_IP6_ADDR_BLOCK8(ip6addr) - IPSTR - esp_ip4_addr_get_byte(ipaddr, idx) - esp_ip4_addr1(ipaddr) - esp_ip4_addr2(ipaddr) - esp_ip4_addr3(ipaddr) - esp_ip4_addr4(ipaddr) - esp_ip4_addr1_16(ipaddr) - esp_ip4_addr2_16(ipaddr) - esp_ip4_addr3_16(ipaddr) - esp_ip4_addr4_16(ipaddr) - IP2STR(ipaddr) - IPV6STR - IPV62STR(ipaddr) - ESP_IPADDR_TYPE_V4 - ESP_IPADDR_TYPE_V6 - ESP_IPADDR_TYPE_ANY - ESP_IP4TOUINT32(a, b, c, d) - ESP_IP4TOADDR(a, b, c, d) - ESP_IP4ADDR_INIT(a, b, c, d) - ESP_IP6ADDR_INIT(a, b, c, d) - IP4ADDR_STRLEN_MAX - ESP_IP_IS_ANY(addr) Type Definitions - typedef struct esp_ip4_addr esp_ip4_addr_t - typedef struct esp_ip6_addr esp_ip6_addr_t Enumerations Header File This header file can be included with: #include "esp_vfs_l2tap.h" This header file is a part of the API provided by the esp_netifcomponent. To declare that your component depends on esp_netif, add the following to your CMakeLists.txt: REQUIRES esp_netif or PRIV_REQUIRES esp_netif Functions - esp_err_t esp_vfs_l2tap_intf_register(l2tap_vfs_config_t *config) Add L2 TAP virtual filesystem driver. This function must be called prior usage of ESP-NETIF L2 TAP Interface - Parameters config -- L2 TAP virtual filesystem driver configuration. Default base path /dev/net/tap is used when this paramenter is NULL. - Returns esp_err_t ESP_OK on success - - esp_err_t esp_vfs_l2tap_intf_unregister(const char *base_path) Removes L2 TAP virtual filesystem driver. - Parameters base_path -- Base path to the L2 TAP virtual filesystem driver. Default path /dev/net/tap is used when this paramenter is NULL. - Returns esp_err_t ESP_OK on success - - esp_err_t esp_vfs_l2tap_eth_filter(l2tap_iodriver_handle driver_handle, void *buff, size_t *size) Filters received Ethernet L2 frames into L2 TAP infrastructure. - Parameters driver_handle -- handle of driver at which the frame was received buff -- received L2 frame size -- input length of the L2 frame which is set to 0 when frame is filtered into L2 TAP - - Returns esp_err_t ESP_OK is always returned - Structures Macros - L2TAP_VFS_DEFAULT_PATH - L2TAP_VFS_CONFIG_DEFAULT() Type Definitions - typedef void *l2tap_iodriver_handle Enumerations Wi-Fi Default API Reference Header File This header file can be included with: #include "esp_wifi_default.h" This header file is a part of the API provided by the esp_wificomponent. To declare that your component depends on esp_wifi, add the following to your CMakeLists.txt: REQUIRES esp_wifi or PRIV_REQUIRES esp_wifi Functions - esp_err_t esp_netif_attach_wifi_station(esp_netif_t *esp_netif) Attaches wifi station interface to supplied netif. - Parameters esp_netif -- instance to attach the wifi station to - Returns ESP_OK on success ESP_FAIL if attach failed - - esp_err_t esp_netif_attach_wifi_ap(esp_netif_t *esp_netif) Attaches wifi soft AP interface to supplied netif. - Parameters esp_netif -- instance to attach the wifi AP to - Returns ESP_OK on success ESP_FAIL if attach failed - - esp_err_t esp_wifi_set_default_wifi_sta_handlers(void) Sets default wifi event handlers for STA interface. - Returns ESP_OK on success, error returned from esp_event_handler_register if failed - - esp_err_t esp_wifi_set_default_wifi_ap_handlers(void) Sets default wifi event handlers for AP interface. - Returns ESP_OK on success, error returned from esp_event_handler_register if failed - - esp_err_t esp_wifi_set_default_wifi_nan_handlers(void) Sets default wifi event handlers for NAN interface. - Returns ESP_OK on success, error returned from esp_event_handler_register if failed - - esp_err_t esp_wifi_clear_default_wifi_driver_and_handlers(void *esp_netif) Clears default wifi event handlers for supplied network interface. - Parameters esp_netif -- instance of corresponding if object - Returns ESP_OK on success, error returned from esp_event_handler_register if failed - - esp_netif_t *esp_netif_create_default_wifi_ap(void) Creates default WIFI AP. In case of any init error this API aborts. Note The API creates esp_netif object with default WiFi access point config, attaches the netif to wifi and registers wifi handlers to the default event loop. This API uses assert() to check for potential errors, so it could abort the program. (Note that the default event loop needs to be created prior to calling this API) - Returns pointer to esp-netif instance - esp_netif_t *esp_netif_create_default_wifi_sta(void) Creates default WIFI STA. In case of any init error this API aborts. Note The API creates esp_netif object with default WiFi station config, attaches the netif to wifi and registers wifi handlers to the default event loop. This API uses assert() to check for potential errors, so it could abort the program. (Note that the default event loop needs to be created prior to calling this API) - Returns pointer to esp-netif instance - esp_netif_t *esp_netif_create_default_wifi_nan(void) Creates default WIFI NAN. In case of any init error this API aborts. Note The API creates esp_netif object with default WiFi station config, attaches the netif to wifi and registers wifi handlers to the default event loop. (Note that the default event loop needs to be created prior to calling this API) - Returns pointer to esp-netif instance - void esp_netif_destroy_default_wifi(void *esp_netif) Destroys default WIFI netif created with esp_netif_create_default_wifi_...() API. Note This API unregisters wifi handlers and detaches the created object from the wifi. (this function is a no-operation if esp_netif is NULL) - Parameters esp_netif -- [in] object to detach from WiFi and destroy - esp_netif_t *esp_netif_create_wifi(wifi_interface_t wifi_if, const esp_netif_inherent_config_t *esp_netif_config) Creates esp_netif WiFi object based on the custom configuration. - Attention This API DOES NOT register default handlers! - Parameters wifi_if -- [in] type of wifi interface esp_netif_config -- [in] inherent esp-netif configuration pointer - - Returns pointer to esp-netif instance - esp_err_t esp_netif_create_default_wifi_mesh_netifs(esp_netif_t **p_netif_sta, esp_netif_t **p_netif_ap) Creates default STA and AP network interfaces for esp-mesh. Both netifs are almost identical to the default station and softAP, but with DHCP client and server disabled. Please note that the DHCP client is typically enabled only if the device is promoted to a root node. Returns created interfaces which could be ignored setting parameters to NULL if an application code does not need to save the interface instances for further processing. - Parameters p_netif_sta -- [out] pointer where the resultant STA interface is saved (if non NULL) p_netif_ap -- [out] pointer where the resultant AP interface is saved (if non NULL) - - Returns ESP_OK on success
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/network/esp_netif.html
ESP-IDF Programming Guide v5.2.1 documentation
null
ESP-NETIF Custom I/O Driver
null
espressif.com
2016-01-01
bf9bda1bd012ba84
null
null
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 ESP-NETIF Architecture 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 esp_netif_receive() on a new data received event. 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: 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: post-attach function callback related ESP-NETIF instance As a result, the I/O driver has to create an instance of the struct per below: typedef struct my_netif_driver_s { esp_netif_driver_base_t base; /*!< base structure reserved as esp-netif driver */ driver_impl *h; /*!< handle of driver implementation */ } my_netif_driver_t; with actual values of my_netif_driver_t::base.post_attach and the actual drivers handle my_netif_driver_t::h . So when the esp_netif_attach() gets called from the initialization code, the post-attach callback from I/O driver's code gets executed to mutually register callbacks between ESP-NETIF and I/O driver instances. Typically the driver is started as well in the post-attach callback. An example of a simple post-attach callback is outlined below: static esp_err_t my_post_attach_start(esp_netif_t * esp_netif, void * args) { my_netif_driver_t *driver = args; const esp_netif_driver_ifconfig_t driver_ifconfig = { .driver_free_rx_buffer = my_free_rx_buf, .transmit = my_transmit, .handle = driver->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. For example driver start -> network start, etc. An example of such a default handler is provided below: 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 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. The following API reference outlines these network stack interaction with the ESP-NETIF: Header File This header file can be included with: #include "esp_netif_net_stack.h" This header file is a part of the API provided by the esp_netif component. To declare that your component depends on esp_netif , add the following to your CMakeLists.txt: REQUIRES esp_netif or PRIV_REQUIRES esp_netif Functions esp_netif_t *esp_netif_get_handle_from_netif_impl(void *dev) Returns esp-netif handle. Parameters dev -- [in] opaque ptr to network interface of specific TCP/IP stack Returns handle to related esp-netif instance Parameters dev -- [in] opaque ptr to network interface of specific TCP/IP stack Returns handle to related esp-netif instance void *esp_netif_get_netif_impl(esp_netif_t *esp_netif) Returns network stack specific implementation handle (if supported) Note that it is not supported to acquire PPP netif impl pointer and this function will return NULL for esp_netif instances configured to PPP mode Parameters esp_netif -- [in] Handle to esp-netif instance Returns handle to related network stack netif handle Parameters esp_netif -- [in] Handle to esp-netif instance Returns handle to related network stack netif handle esp_err_t esp_netif_set_link_speed(esp_netif_t *esp_netif, uint32_t speed) Set link-speed for the specified network interface. Parameters esp_netif -- [in] Handle to esp-netif instance speed -- [in] Link speed in bit/s esp_netif -- [in] Handle to esp-netif instance speed -- [in] Link speed in bit/s esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK on success Parameters esp_netif -- [in] Handle to esp-netif instance speed -- [in] Link speed in bit/s Returns ESP_OK on success esp_err_t esp_netif_transmit(esp_netif_t *esp_netif, void *data, size_t len) Outputs packets from the TCP/IP stack to the media to be transmitted. This function gets called from network stack to output packets to IO driver. Parameters esp_netif -- [in] Handle to esp-netif instance data -- [in] Data to be transmitted len -- [in] Length of the data frame esp_netif -- [in] Handle to esp-netif instance data -- [in] Data to be transmitted len -- [in] Length of the data frame esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK on success, an error passed from the I/O driver otherwise Parameters esp_netif -- [in] Handle to esp-netif instance data -- [in] Data to be transmitted len -- [in] Length of the data frame Returns ESP_OK on success, an error passed from the I/O driver otherwise esp_err_t esp_netif_transmit_wrap(esp_netif_t *esp_netif, void *data, size_t len, void *netstack_buf) Outputs packets from the TCP/IP stack to the media to be transmitted. This function gets called from network stack to output packets to IO driver. Parameters esp_netif -- [in] Handle to esp-netif instance data -- [in] Data to be transmitted len -- [in] Length of the data frame netstack_buf -- [in] net stack buffer esp_netif -- [in] Handle to esp-netif instance data -- [in] Data to be transmitted len -- [in] Length of the data frame netstack_buf -- [in] net stack buffer esp_netif -- [in] Handle to esp-netif instance Returns ESP_OK on success, an error passed from the I/O driver otherwise Parameters esp_netif -- [in] Handle to esp-netif instance data -- [in] Data to be transmitted len -- [in] Length of the data frame netstack_buf -- [in] net stack buffer Returns ESP_OK on success, an error passed from the I/O driver otherwise void esp_netif_free_rx_buffer(void *esp_netif, void *buffer) Free the rx buffer allocated by the media driver. This function gets called from network stack when the rx buffer to be freed in IO driver context, i.e. to deallocate a buffer owned by io driver (when data packets were passed to higher levels to avoid copying) Parameters esp_netif -- [in] Handle to esp-netif instance buffer -- [in] Rx buffer pointer esp_netif -- [in] Handle to esp-netif instance buffer -- [in] Rx buffer pointer esp_netif -- [in] Handle to esp-netif instance Parameters esp_netif -- [in] Handle to esp-netif instance buffer -- [in] Rx buffer pointer
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 ESP-NETIF Architecture 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 esp_netif_receive() on a new data received event. 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: 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: post-attach function callback related ESP-NETIF instance As a result, the I/O driver has to create an instance of the struct per below: typedef struct my_netif_driver_s { esp_netif_driver_base_t base; /*!< base structure reserved as esp-netif driver */ driver_impl *h; /*!< handle of driver implementation */ } my_netif_driver_t; with actual values of my_netif_driver_t::base.post_attach and the actual drivers handle my_netif_driver_t::h. So when the esp_netif_attach() gets called from the initialization code, the post-attach callback from I/O driver's code gets executed to mutually register callbacks between ESP-NETIF and I/O driver instances. Typically the driver is started as well in the post-attach callback. An example of a simple post-attach callback is outlined below: static esp_err_t my_post_attach_start(esp_netif_t * esp_netif, void * args) { my_netif_driver_t *driver = args; const esp_netif_driver_ifconfig_t driver_ifconfig = { .driver_free_rx_buffer = my_free_rx_buf, .transmit = my_transmit, .handle = driver->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. For example driver start -> network start, etc. An example of such a default handler is provided below: 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 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. The following API reference outlines these network stack interaction with the ESP-NETIF: Header File This header file can be included with: #include "esp_netif_net_stack.h" This header file is a part of the API provided by the esp_netifcomponent. To declare that your component depends on esp_netif, add the following to your CMakeLists.txt: REQUIRES esp_netif or PRIV_REQUIRES esp_netif Functions - esp_netif_t *esp_netif_get_handle_from_netif_impl(void *dev) Returns esp-netif handle. - Parameters dev -- [in] opaque ptr to network interface of specific TCP/IP stack - Returns handle to related esp-netif instance - void *esp_netif_get_netif_impl(esp_netif_t *esp_netif) Returns network stack specific implementation handle (if supported) Note that it is not supported to acquire PPP netif impl pointer and this function will return NULL for esp_netif instances configured to PPP mode - Parameters esp_netif -- [in] Handle to esp-netif instance - Returns handle to related network stack netif handle - esp_err_t esp_netif_set_link_speed(esp_netif_t *esp_netif, uint32_t speed) Set link-speed for the specified network interface. - Parameters esp_netif -- [in] Handle to esp-netif instance speed -- [in] Link speed in bit/s - - Returns ESP_OK on success - esp_err_t esp_netif_transmit(esp_netif_t *esp_netif, void *data, size_t len) Outputs packets from the TCP/IP stack to the media to be transmitted. This function gets called from network stack to output packets to IO driver. - Parameters esp_netif -- [in] Handle to esp-netif instance data -- [in] Data to be transmitted len -- [in] Length of the data frame - - Returns ESP_OK on success, an error passed from the I/O driver otherwise - esp_err_t esp_netif_transmit_wrap(esp_netif_t *esp_netif, void *data, size_t len, void *netstack_buf) Outputs packets from the TCP/IP stack to the media to be transmitted. This function gets called from network stack to output packets to IO driver. - Parameters esp_netif -- [in] Handle to esp-netif instance data -- [in] Data to be transmitted len -- [in] Length of the data frame netstack_buf -- [in] net stack buffer - - Returns ESP_OK on success, an error passed from the I/O driver otherwise - void esp_netif_free_rx_buffer(void *esp_netif, void *buffer) Free the rx buffer allocated by the media driver. This function gets called from network stack when the rx buffer to be freed in IO driver context, i.e. to deallocate a buffer owned by io driver (when data packets were passed to higher levels to avoid copying) - Parameters esp_netif -- [in] Handle to esp-netif instance buffer -- [in] Rx buffer pointer -
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/network/esp_netif_driver.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Analog to Digital Converter (ADC) Oneshot Mode Driver
null
espressif.com
2016-01-01
875a9bb63e1ed141
null
null
Analog to Digital Converter (ADC) Oneshot Mode Driver Introduction The Analog to Digital Converter is integrated on the chip and is capable of measuring analog signals from specific analog IO pins. ESP32 has two ADC unit(s), which can be used in scenario(s) like: Generate one-shot ADC conversion result Generate continuous ADC conversion results This guide introduces ADC oneshot mode conversion. Functional Overview The following sections of this document cover the typical steps to install and operate an ADC: Resource Allocation - covers which parameters should be set up to get an ADC handle and how to recycle the resources when ADC finishes working. Unit Configuration - covers the parameters that should be set up to configure the ADC unit, so as to get ADC conversion raw result. Read Conversion Result - covers how to get ADC conversion raw result. Hardware Limitations - describes the ADC-related hardware limitations. Power Management - covers power management-related information. IRAM Safe - describes tips on how to read ADC conversion raw results when the cache is disabled. Thread Safety - lists which APIs are guaranteed to be thread-safe by the driver. Kconfig Options - lists the supported Kconfig options that can be used to make a different effect on driver behavior. Resource Allocation The ADC oneshot mode driver is implemented based on ESP32 SAR ADC module. Different ESP chips might have different numbers of independent ADCs. From the oneshot mode driver's point of view, an ADC instance is represented by adc_oneshot_unit_handle_t . To install an ADC instance, set up the required initial configuration structure adc_oneshot_unit_init_cfg_t : adc_oneshot_unit_init_cfg_t::unit_id selects the ADC. Please refer to the datasheet to know dedicated analog IOs for this ADC. adc_oneshot_unit_init_cfg_t::clk_src selects the source clock of the ADC. If set to 0, the driver will fall back to using a default clock source, see adc_oneshot_clk_src_t to know the details. adc_oneshot_unit_init_cfg_t::ulp_mode sets if the ADC will be working under ULP mode. After setting up the initial configurations for the ADC, call adc_oneshot_new_unit() with the prepared adc_oneshot_unit_init_cfg_t . This function will return an ADC unit handle if the allocation is successful. This function may fail due to various errors such as invalid arguments, insufficient memory, etc. Specifically, when the to-be-allocated ADC instance is registered already, this function will return ESP_ERR_NOT_FOUND error. Number of available ADC(s) is recorded by SOC_ADC_PERIPH_NUM . If a previously created ADC instance is no longer required, you should recycle the ADC instance by calling adc_oneshot_del_unit() , related hardware and software resources will be recycled as well. Create an ADC Unit Handle Under Normal Oneshot Mode adc_oneshot_unit_handle_t adc1_handle; adc_oneshot_unit_init_cfg_t init_config1 = { .unit_id = ADC_UNIT_1, .ulp_mode = ADC_ULP_MODE_DISABLE, }; ESP_ERROR_CHECK(adc_oneshot_new_unit(&init_config1, &adc1_handle)); Recycle the ADC Unit ESP_ERROR_CHECK(adc_oneshot_del_unit(adc1_handle)); Unit Configuration After an ADC instance is created, set up the adc_oneshot_chan_cfg_t to configure ADC IOs to measure analog signal: adc_oneshot_chan_cfg_t::atten , ADC attenuation. Refer to TRM > On-Chip Sensor and Analog Signal Processing . adc_oneshot_chan_cfg_t::bitwidth , the bitwidth of the raw conversion result. Note For the IO corresponding ADC channel number, check datasheet to know the ADC IOs. Additionally, adc_continuous_io_to_channel() and adc_continuous_channel_to_io() can be used to know the ADC channels and ADC IOs. To make these settings take effect, call adc_oneshot_config_channel() with the above configuration structure. You should specify an ADC channel to be configured as well. Function adc_oneshot_config_channel() can be called multiple times to configure different ADC channels. The Driver will save each of these channel configurations internally. Configure Two ADC Channels adc_oneshot_chan_cfg_t config = { .bitwidth = ADC_BITWIDTH_DEFAULT, .atten = ADC_ATTEN_DB_12, }; ESP_ERROR_CHECK(adc_oneshot_config_channel(adc1_handle, EXAMPLE_ADC1_CHAN0, &config)); ESP_ERROR_CHECK(adc_oneshot_config_channel(adc1_handle, EXAMPLE_ADC1_CHAN1, &config)); Read Conversion Result After above configurations, the ADC is ready to measure the analog signal(s) from the configured ADC channel(s). Call adc_oneshot_read() to get the conversion raw result of an ADC channel. adc_oneshot_read() is safe to use. ADC(s) are shared by some other drivers/peripherals, see Hardware Limitations. This function uses mutexes to avoid concurrent hardware usage. Therefore, this function should not be used in an ISR context. This function may fail when the ADC is in use by other drivers/peripherals, and return ESP_ERR_TIMEOUT . Under this condition, the ADC raw result is invalid. This function will fail due to invalid arguments. The ADC conversion results read from this function are raw data. To calculate the voltage based on the ADC raw results, this formula can be used: Vout = Dout * Vmax / Dmax (1) where: Vout Digital output result, standing for the voltage. Dout ADC raw digital reading result. Vmax Maximum measurable input analog voltage, this is related to the ADC attenuation, please refer to TRM > Dmax Maximum of the output ADC raw digital reading result, which is 2^bitwidth, where bitwidth is the :cpp:member::adc_oneshot_chan_cfg_t:bitwidth configured before. To do further calibration to convert the ADC raw result to voltage in mV, please refer to calibration doc Analog to Digital Converter (ADC) Calibration Driver. Read Raw Result ESP_ERROR_CHECK(adc_oneshot_read(adc1_handle, EXAMPLE_ADC1_CHAN0, &adc_raw[0][0])); ESP_LOGI(TAG, "ADC%d Channel[%d] Raw Data: %d", ADC_UNIT_1 + 1, EXAMPLE_ADC1_CHAN0, adc_raw[0][0]); ESP_ERROR_CHECK(adc_oneshot_read(adc1_handle, EXAMPLE_ADC1_CHAN1, &adc_raw[0][1])); ESP_LOGI(TAG, "ADC%d Channel[%d] Raw Data: %d", ADC_UNIT_1 + 1, EXAMPLE_ADC1_CHAN1, adc_raw[0][1]); Hardware Limitations Random Number Generator (RNG) uses ADC as an input source. When ADC adc_oneshot_read() works, the random number generated from RNG will be less random. A specific ADC unit can only work under one operating mode at any one time, either continuous mode or oneshot mode. adc_oneshot_read() has provided the protection. ADC2 is also used by Wi-Fi. adc_oneshot_read() has provided protection between the Wi-Fi driver and ADC oneshot mode driver. ESP32-DevKitC: GPIO0 cannot be used in oneshot mode, because the DevKit has used it for auto-flash. ESP-WROVER-KIT: GPIO 0, 2, 4, and 15 cannot be used due to external connections for different purposes. Power Management When power management is enabled, i.e., CONFIG_PM_ENABLE is on, the system clock frequency may be adjusted when the system is in an idle state. However, the ADC oneshot mode driver works in a polling routine, the adc_oneshot_read() will poll the CPU until the function returns. During this period of time, the task in which ADC oneshot mode driver resides will not be blocked. Therefore the clock frequency is stable when reading. IRAM Safe By default, all the ADC oneshot mode driver APIs are not supposed to be run when the Cache is disabled. Cache may be disabled due to many reasons, such as Flash writing/erasing, OTA, etc. If these APIs execute when the Cache is disabled, you will probably see errors like Illegal Instruction or Load/Store Prohibited . Thread Safety Above functions are guaranteed to be thread-safe. Therefore, you can call them from different RTOS tasks without protection by extra locks. adc_oneshot_del_unit() is not thread-safe. Besides, concurrently calling this function may result in failures of the above thread-safe APIs. Kconfig Options CONFIG_ADC_ONESHOT_CTRL_FUNC_IN_IRAM controls where to place the ADC fast read function (IRAM or Flash), see IRAM Safe for more details. Application Examples ADC oneshot mode example: peripherals/adc/oneshot_read. API Reference Header File This header file can be included with: #include "hal/adc_types.h" Structures struct adc_digi_pattern_config_t ADC digital controller pattern configuration. struct adc_digi_output_data_t ADC digital controller (DMA mode) output data format. Used to analyze the acquired ADC (DMA) data. Note ESP32: Only type1 is valid. ADC2 does not support DMA mode. Note ESP32-S2: Member channel can be used to judge the validity of the ADC data, because the role of the arbiter may get invalid ADC data. Public Members uint16_t data ADC real output data info. Resolution: 12 bit. ADC real output data info. Resolution: 11 bit. uint16_t data ADC real output data info. Resolution: 12 bit. ADC real output data info. Resolution: 11 bit. uint16_t channel ADC channel index info. ADC channel index info. For ESP32-S2: If (channel < ADC_CHANNEL_MAX), The data is valid. If (channel > ADC_CHANNEL_MAX), The data is invalid. uint16_t channel ADC channel index info. ADC channel index info. For ESP32-S2: If (channel < ADC_CHANNEL_MAX), The data is valid. If (channel > ADC_CHANNEL_MAX), The data is invalid. struct adc_digi_output_data_t::[anonymous]::[anonymous] type1 ADC type1 struct adc_digi_output_data_t::[anonymous]::[anonymous] type1 ADC type1 uint16_t unit ADC unit index info. 0: ADC1; 1: ADC2. uint16_t unit ADC unit index info. 0: ADC1; 1: ADC2. struct adc_digi_output_data_t::[anonymous]::[anonymous] type2 When the configured output format is 11bit. struct adc_digi_output_data_t::[anonymous]::[anonymous] type2 When the configured output format is 11bit. uint16_t val Raw data value uint16_t val Raw data value uint16_t data Type Definitions typedef soc_periph_adc_digi_clk_src_t adc_oneshot_clk_src_t Clock source type of oneshot mode which uses digital controller. typedef soc_periph_adc_digi_clk_src_t adc_continuous_clk_src_t Clock source type of continuous mode which uses digital controller. Enumerations enum adc_unit_t ADC unit. Values: enumerator ADC_UNIT_1 SAR ADC 1. enumerator ADC_UNIT_1 SAR ADC 1. enumerator ADC_UNIT_2 SAR ADC 2. enumerator ADC_UNIT_2 SAR ADC 2. enumerator ADC_UNIT_1 enum adc_channel_t ADC channels. Values: enumerator ADC_CHANNEL_0 ADC channel. enumerator ADC_CHANNEL_0 ADC channel. enumerator ADC_CHANNEL_1 ADC channel. enumerator ADC_CHANNEL_1 ADC channel. enumerator ADC_CHANNEL_2 ADC channel. enumerator ADC_CHANNEL_2 ADC channel. enumerator ADC_CHANNEL_3 ADC channel. enumerator ADC_CHANNEL_3 ADC channel. enumerator ADC_CHANNEL_4 ADC channel. enumerator ADC_CHANNEL_4 ADC channel. enumerator ADC_CHANNEL_5 ADC channel. enumerator ADC_CHANNEL_5 ADC channel. enumerator ADC_CHANNEL_6 ADC channel. enumerator ADC_CHANNEL_6 ADC channel. enumerator ADC_CHANNEL_7 ADC channel. enumerator ADC_CHANNEL_7 ADC channel. enumerator ADC_CHANNEL_8 ADC channel. enumerator ADC_CHANNEL_8 ADC channel. enumerator ADC_CHANNEL_9 ADC channel. enumerator ADC_CHANNEL_9 ADC channel. enumerator ADC_CHANNEL_0 enum adc_atten_t ADC attenuation parameter. Different parameters determine the range of the ADC. Values: enumerator ADC_ATTEN_DB_0 No input attenuation, ADC can measure up to approx. enumerator ADC_ATTEN_DB_0 No input attenuation, ADC can measure up to approx. enumerator ADC_ATTEN_DB_2_5 The input voltage of ADC will be attenuated extending the range of measurement by about 2.5 dB. enumerator ADC_ATTEN_DB_2_5 The input voltage of ADC will be attenuated extending the range of measurement by about 2.5 dB. enumerator ADC_ATTEN_DB_6 The input voltage of ADC will be attenuated extending the range of measurement by about 6 dB. enumerator ADC_ATTEN_DB_6 The input voltage of ADC will be attenuated extending the range of measurement by about 6 dB. enumerator ADC_ATTEN_DB_12 The input voltage of ADC will be attenuated extending the range of measurement by about 12 dB. enumerator ADC_ATTEN_DB_12 The input voltage of ADC will be attenuated extending the range of measurement by about 12 dB. enumerator ADC_ATTEN_DB_11 This is deprecated, it behaves the same as ADC_ATTEN_DB_12 enumerator ADC_ATTEN_DB_11 This is deprecated, it behaves the same as ADC_ATTEN_DB_12 enumerator ADC_ATTEN_DB_0 enum adc_bitwidth_t Values: enumerator ADC_BITWIDTH_DEFAULT Default ADC output bits, max supported width will be selected. enumerator ADC_BITWIDTH_DEFAULT Default ADC output bits, max supported width will be selected. enumerator ADC_BITWIDTH_9 ADC output width is 9Bit. enumerator ADC_BITWIDTH_9 ADC output width is 9Bit. enumerator ADC_BITWIDTH_10 ADC output width is 10Bit. enumerator ADC_BITWIDTH_10 ADC output width is 10Bit. enumerator ADC_BITWIDTH_11 ADC output width is 11Bit. enumerator ADC_BITWIDTH_11 ADC output width is 11Bit. enumerator ADC_BITWIDTH_12 ADC output width is 12Bit. enumerator ADC_BITWIDTH_12 ADC output width is 12Bit. enumerator ADC_BITWIDTH_13 ADC output width is 13Bit. enumerator ADC_BITWIDTH_13 ADC output width is 13Bit. enumerator ADC_BITWIDTH_DEFAULT enum adc_ulp_mode_t Values: enumerator ADC_ULP_MODE_DISABLE ADC ULP mode is disabled. enumerator ADC_ULP_MODE_DISABLE ADC ULP mode is disabled. enumerator ADC_ULP_MODE_FSM ADC is controlled by ULP FSM. enumerator ADC_ULP_MODE_FSM ADC is controlled by ULP FSM. enumerator ADC_ULP_MODE_RISCV ADC is controlled by ULP RISCV. enumerator ADC_ULP_MODE_RISCV ADC is controlled by ULP RISCV. enumerator ADC_ULP_MODE_DISABLE enum adc_digi_convert_mode_t ADC digital controller (DMA mode) work mode. Values: enumerator ADC_CONV_SINGLE_UNIT_1 Only use ADC1 for conversion. enumerator ADC_CONV_SINGLE_UNIT_1 Only use ADC1 for conversion. enumerator ADC_CONV_SINGLE_UNIT_2 Only use ADC2 for conversion. enumerator ADC_CONV_SINGLE_UNIT_2 Only use ADC2 for conversion. enumerator ADC_CONV_BOTH_UNIT Use Both ADC1 and ADC2 for conversion simultaneously. enumerator ADC_CONV_BOTH_UNIT Use Both ADC1 and ADC2 for conversion simultaneously. enumerator ADC_CONV_ALTER_UNIT Use both ADC1 and ADC2 for conversion by turn. e.g. ADC1 -> ADC2 -> ADC1 -> ADC2 ..... enumerator ADC_CONV_ALTER_UNIT Use both ADC1 and ADC2 for conversion by turn. e.g. ADC1 -> ADC2 -> ADC1 -> ADC2 ..... enumerator ADC_CONV_SINGLE_UNIT_1 enum adc_digi_output_format_t ADC digital controller (DMA mode) output data format option. Values: enumerator ADC_DIGI_OUTPUT_FORMAT_TYPE1 enumerator ADC_DIGI_OUTPUT_FORMAT_TYPE1 enumerator ADC_DIGI_OUTPUT_FORMAT_TYPE2 enumerator ADC_DIGI_OUTPUT_FORMAT_TYPE2 enumerator ADC_DIGI_OUTPUT_FORMAT_TYPE1 enum adc_digi_iir_filter_t ADC IIR Filter ID. Values: enumerator ADC_DIGI_IIR_FILTER_0 Filter 0. enumerator ADC_DIGI_IIR_FILTER_0 Filter 0. enumerator ADC_DIGI_IIR_FILTER_1 Filter 1. enumerator ADC_DIGI_IIR_FILTER_1 Filter 1. enumerator ADC_DIGI_IIR_FILTER_0 enum adc_digi_iir_filter_coeff_t IIR Filter Coefficient. Values: enumerator ADC_DIGI_IIR_FILTER_COEFF_2 The filter coefficient is 2. enumerator ADC_DIGI_IIR_FILTER_COEFF_2 The filter coefficient is 2. enumerator ADC_DIGI_IIR_FILTER_COEFF_4 The filter coefficient is 4. enumerator ADC_DIGI_IIR_FILTER_COEFF_4 The filter coefficient is 4. enumerator ADC_DIGI_IIR_FILTER_COEFF_8 The filter coefficient is 8. enumerator ADC_DIGI_IIR_FILTER_COEFF_8 The filter coefficient is 8. enumerator ADC_DIGI_IIR_FILTER_COEFF_16 The filter coefficient is 16. enumerator ADC_DIGI_IIR_FILTER_COEFF_16 The filter coefficient is 16. enumerator ADC_DIGI_IIR_FILTER_COEFF_64 The filter coefficient is 64. enumerator ADC_DIGI_IIR_FILTER_COEFF_64 The filter coefficient is 64. enumerator ADC_DIGI_IIR_FILTER_COEFF_2 enum adc_monitor_id_t ADC monitor (continuous mode) ID. Values: enumerator ADC_MONITOR_0 The monitor index 0. enumerator ADC_MONITOR_0 The monitor index 0. enumerator ADC_MONITOR_1 The monitor index 1. enumerator ADC_MONITOR_1 The monitor index 1. enumerator ADC_MONITOR_0 Header File This header file can be included with: #include "esp_adc/adc_oneshot.h" This header file is a part of the API provided by the esp_adc component. To declare that your component depends on esp_adc , add the following to your CMakeLists.txt: REQUIRES esp_adc or PRIV_REQUIRES esp_adc Functions esp_err_t adc_oneshot_new_unit(const adc_oneshot_unit_init_cfg_t *init_config, adc_oneshot_unit_handle_t *ret_unit) Create a handle to a specific ADC unit. Note This API is thread-safe. For more details, see ADC programming guide Parameters init_config -- [in] Driver initial configurations ret_unit -- [out] ADC unit handle init_config -- [in] Driver initial configurations ret_unit -- [out] ADC unit handle init_config -- [in] Driver initial configurations Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_NO_MEM: No memory ESP_ERR_NOT_FOUND: The ADC peripheral to be claimed is already in use ESP_FAIL: Clock source isn't initialised correctly ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_NO_MEM: No memory ESP_ERR_NOT_FOUND: The ADC peripheral to be claimed is already in use ESP_FAIL: Clock source isn't initialised correctly ESP_OK: On success Parameters init_config -- [in] Driver initial configurations ret_unit -- [out] ADC unit handle Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_NO_MEM: No memory ESP_ERR_NOT_FOUND: The ADC peripheral to be claimed is already in use ESP_FAIL: Clock source isn't initialised correctly esp_err_t adc_oneshot_config_channel(adc_oneshot_unit_handle_t handle, adc_channel_t channel, const adc_oneshot_chan_cfg_t *config) Set ADC oneshot mode required configurations. Note This API is thread-safe. For more details, see ADC programming guide Parameters handle -- [in] ADC handle channel -- [in] ADC channel to be configured config -- [in] ADC configurations handle -- [in] ADC handle channel -- [in] ADC channel to be configured config -- [in] ADC configurations handle -- [in] ADC handle Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_OK: On success Parameters handle -- [in] ADC handle channel -- [in] ADC channel to be configured config -- [in] ADC configurations Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments esp_err_t adc_oneshot_read(adc_oneshot_unit_handle_t handle, adc_channel_t chan, int *out_raw) Get one ADC conversion raw result. Note This API is thread-safe. For more details, see ADC programming guide Note This API should NOT be called in an ISR context Parameters handle -- [in] ADC handle chan -- [in] ADC channel out_raw -- [out] ADC conversion raw result handle -- [in] ADC handle chan -- [in] ADC channel out_raw -- [out] ADC conversion raw result handle -- [in] ADC handle Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_TIMEOUT: Timeout, the ADC result is invalid ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_TIMEOUT: Timeout, the ADC result is invalid ESP_OK: On success Parameters handle -- [in] ADC handle chan -- [in] ADC channel out_raw -- [out] ADC conversion raw result Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_TIMEOUT: Timeout, the ADC result is invalid esp_err_t adc_oneshot_del_unit(adc_oneshot_unit_handle_t handle) Delete the ADC unit handle. Note This API is thread-safe. For more details, see ADC programming guide Parameters handle -- [in] ADC handle Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_NOT_FOUND: The ADC peripheral to be disclaimed isn't in use ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_NOT_FOUND: The ADC peripheral to be disclaimed isn't in use ESP_OK: On success Parameters handle -- [in] ADC handle Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_NOT_FOUND: The ADC peripheral to be disclaimed isn't in use esp_err_t adc_oneshot_io_to_channel(int io_num, adc_unit_t *const unit_id, adc_channel_t *const channel) Get ADC channel from the given GPIO number. Parameters io_num -- [in] GPIO number unit_id -- [out] ADC unit channel -- [out] ADC channel io_num -- [in] GPIO number unit_id -- [out] ADC unit channel -- [out] ADC channel io_num -- [in] GPIO number Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_NOT_FOUND: The IO is not a valid ADC pad ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_NOT_FOUND: The IO is not a valid ADC pad ESP_OK: On success Parameters io_num -- [in] GPIO number unit_id -- [out] ADC unit channel -- [out] ADC channel Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_NOT_FOUND: The IO is not a valid ADC pad esp_err_t adc_oneshot_channel_to_io(adc_unit_t unit_id, adc_channel_t channel, int *const io_num) Get GPIO number from the given ADC channel. Parameters unit_id -- [in] ADC unit channel -- [in] ADC channel io_num -- [out] GPIO number - -- ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_INVALID_ARG: Invalid argument unit_id -- [in] ADC unit channel -- [in] ADC channel io_num -- [out] GPIO number - -- ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument unit_id -- [in] ADC unit Parameters unit_id -- [in] ADC unit channel -- [in] ADC channel io_num -- [out] GPIO number - -- ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument esp_err_t adc_oneshot_get_calibrated_result(adc_oneshot_unit_handle_t handle, adc_cali_handle_t cali_handle, adc_channel_t chan, int *cali_result) Convenience function to get ADC calibrated result. This is an all-in-one function which does: oneshot read ADC raw result calibrate the raw result and convert it into calibrated result (in mV) oneshot read ADC raw result calibrate the raw result and convert it into calibrated result (in mV) Parameters handle -- [in] ADC oneshot handle, you should call adc_oneshot_new_unit() to get this handle cali_handle -- [in] ADC calibration handle, you should call adc_cali_create_scheme_x() in adc_cali_scheme.h to create a handle chan -- [in] ADC channel cali_result -- [out] Calibrated ADC result (in mV) handle -- [in] ADC oneshot handle, you should call adc_oneshot_new_unit() to get this handle cali_handle -- [in] ADC calibration handle, you should call adc_cali_create_scheme_x() in adc_cali_scheme.h to create a handle chan -- [in] ADC channel cali_result -- [out] Calibrated ADC result (in mV) handle -- [in] ADC oneshot handle, you should call adc_oneshot_new_unit() to get this handle Returns ESP_OK Other return errors from adc_oneshot_read() and adc_cali_raw_to_voltage() ESP_OK Other return errors from adc_oneshot_read() and adc_cali_raw_to_voltage() ESP_OK Other return errors from adc_oneshot_read() and adc_cali_raw_to_voltage() Parameters handle -- [in] ADC oneshot handle, you should call adc_oneshot_new_unit() to get this handle cali_handle -- [in] ADC calibration handle, you should call adc_cali_create_scheme_x() in adc_cali_scheme.h to create a handle chan -- [in] ADC channel cali_result -- [out] Calibrated ADC result (in mV) Returns ESP_OK Other return errors from adc_oneshot_read() and adc_cali_raw_to_voltage() oneshot read ADC raw result Structures struct adc_oneshot_unit_init_cfg_t ADC oneshot driver initial configurations. Public Members adc_unit_t unit_id ADC unit. adc_unit_t unit_id ADC unit. adc_oneshot_clk_src_t clk_src Clock source. adc_oneshot_clk_src_t clk_src Clock source. adc_ulp_mode_t ulp_mode ADC controlled by ULP, see adc_ulp_mode_t adc_ulp_mode_t ulp_mode ADC controlled by ULP, see adc_ulp_mode_t adc_unit_t unit_id struct adc_oneshot_chan_cfg_t ADC channel configurations. Public Members adc_atten_t atten ADC attenuation. adc_atten_t atten ADC attenuation. adc_bitwidth_t bitwidth ADC conversion result bits. adc_bitwidth_t bitwidth ADC conversion result bits. adc_atten_t atten Type Definitions typedef struct adc_oneshot_unit_ctx_t *adc_oneshot_unit_handle_t Type of ADC unit handle for oneshot mode.
Analog to Digital Converter (ADC) Oneshot Mode Driver Introduction The Analog to Digital Converter is integrated on the chip and is capable of measuring analog signals from specific analog IO pins. ESP32 has two ADC unit(s), which can be used in scenario(s) like: Generate one-shot ADC conversion result Generate continuous ADC conversion results This guide introduces ADC oneshot mode conversion. Functional Overview The following sections of this document cover the typical steps to install and operate an ADC: Resource Allocation - covers which parameters should be set up to get an ADC handle and how to recycle the resources when ADC finishes working. Unit Configuration - covers the parameters that should be set up to configure the ADC unit, so as to get ADC conversion raw result. Read Conversion Result - covers how to get ADC conversion raw result. Hardware Limitations - describes the ADC-related hardware limitations. Power Management - covers power management-related information. IRAM Safe - describes tips on how to read ADC conversion raw results when the cache is disabled. Thread Safety - lists which APIs are guaranteed to be thread-safe by the driver. Kconfig Options - lists the supported Kconfig options that can be used to make a different effect on driver behavior. Resource Allocation The ADC oneshot mode driver is implemented based on ESP32 SAR ADC module. Different ESP chips might have different numbers of independent ADCs. From the oneshot mode driver's point of view, an ADC instance is represented by adc_oneshot_unit_handle_t. To install an ADC instance, set up the required initial configuration structure adc_oneshot_unit_init_cfg_t: adc_oneshot_unit_init_cfg_t::unit_idselects the ADC. Please refer to the datasheet to know dedicated analog IOs for this ADC. adc_oneshot_unit_init_cfg_t::clk_srcselects the source clock of the ADC. If set to 0, the driver will fall back to using a default clock source, see adc_oneshot_clk_src_tto know the details. adc_oneshot_unit_init_cfg_t::ulp_modesets if the ADC will be working under ULP mode. After setting up the initial configurations for the ADC, call adc_oneshot_new_unit() with the prepared adc_oneshot_unit_init_cfg_t. This function will return an ADC unit handle if the allocation is successful. This function may fail due to various errors such as invalid arguments, insufficient memory, etc. Specifically, when the to-be-allocated ADC instance is registered already, this function will return ESP_ERR_NOT_FOUND error. Number of available ADC(s) is recorded by SOC_ADC_PERIPH_NUM. If a previously created ADC instance is no longer required, you should recycle the ADC instance by calling adc_oneshot_del_unit(), related hardware and software resources will be recycled as well. Create an ADC Unit Handle Under Normal Oneshot Mode adc_oneshot_unit_handle_t adc1_handle; adc_oneshot_unit_init_cfg_t init_config1 = { .unit_id = ADC_UNIT_1, .ulp_mode = ADC_ULP_MODE_DISABLE, }; ESP_ERROR_CHECK(adc_oneshot_new_unit(&init_config1, &adc1_handle)); Recycle the ADC Unit ESP_ERROR_CHECK(adc_oneshot_del_unit(adc1_handle)); Unit Configuration After an ADC instance is created, set up the adc_oneshot_chan_cfg_t to configure ADC IOs to measure analog signal: adc_oneshot_chan_cfg_t::atten, ADC attenuation. Refer to TRM > On-Chip Sensor and Analog Signal Processing. adc_oneshot_chan_cfg_t::bitwidth, the bitwidth of the raw conversion result. Note For the IO corresponding ADC channel number, check datasheet to know the ADC IOs. Additionally, adc_continuous_io_to_channel() and adc_continuous_channel_to_io() can be used to know the ADC channels and ADC IOs. To make these settings take effect, call adc_oneshot_config_channel() with the above configuration structure. You should specify an ADC channel to be configured as well. Function adc_oneshot_config_channel() can be called multiple times to configure different ADC channels. The Driver will save each of these channel configurations internally. Configure Two ADC Channels adc_oneshot_chan_cfg_t config = { .bitwidth = ADC_BITWIDTH_DEFAULT, .atten = ADC_ATTEN_DB_12, }; ESP_ERROR_CHECK(adc_oneshot_config_channel(adc1_handle, EXAMPLE_ADC1_CHAN0, &config)); ESP_ERROR_CHECK(adc_oneshot_config_channel(adc1_handle, EXAMPLE_ADC1_CHAN1, &config)); Read Conversion Result After above configurations, the ADC is ready to measure the analog signal(s) from the configured ADC channel(s). Call adc_oneshot_read() to get the conversion raw result of an ADC channel. adc_oneshot_read()is safe to use. ADC(s) are shared by some other drivers/peripherals, see Hardware Limitations. This function uses mutexes to avoid concurrent hardware usage. Therefore, this function should not be used in an ISR context. This function may fail when the ADC is in use by other drivers/peripherals, and return ESP_ERR_TIMEOUT. Under this condition, the ADC raw result is invalid. This function will fail due to invalid arguments. The ADC conversion results read from this function are raw data. To calculate the voltage based on the ADC raw results, this formula can be used: Vout = Dout * Vmax / Dmax (1) where: | Vout | Digital output result, standing for the voltage. | Dout | ADC raw digital reading result. | Vmax | Maximum measurable input analog voltage, this is related to the ADC attenuation, please refer to TRM > | Dmax | Maximum of the output ADC raw digital reading result, which is 2^bitwidth, where bitwidth is the :cpp:member::adc_oneshot_chan_cfg_t:bitwidth configured before. To do further calibration to convert the ADC raw result to voltage in mV, please refer to calibration doc Analog to Digital Converter (ADC) Calibration Driver. Read Raw Result ESP_ERROR_CHECK(adc_oneshot_read(adc1_handle, EXAMPLE_ADC1_CHAN0, &adc_raw[0][0])); ESP_LOGI(TAG, "ADC%d Channel[%d] Raw Data: %d", ADC_UNIT_1 + 1, EXAMPLE_ADC1_CHAN0, adc_raw[0][0]); ESP_ERROR_CHECK(adc_oneshot_read(adc1_handle, EXAMPLE_ADC1_CHAN1, &adc_raw[0][1])); ESP_LOGI(TAG, "ADC%d Channel[%d] Raw Data: %d", ADC_UNIT_1 + 1, EXAMPLE_ADC1_CHAN1, adc_raw[0][1]); Hardware Limitations Random Number Generator (RNG) uses ADC as an input source. When ADC adc_oneshot_read()works, the random number generated from RNG will be less random. A specific ADC unit can only work under one operating mode at any one time, either continuous mode or oneshot mode. adc_oneshot_read()has provided the protection. ADC2 is also used by Wi-Fi. adc_oneshot_read()has provided protection between the Wi-Fi driver and ADC oneshot mode driver. ESP32-DevKitC: GPIO0 cannot be used in oneshot mode, because the DevKit has used it for auto-flash. ESP-WROVER-KIT: GPIO 0, 2, 4, and 15 cannot be used due to external connections for different purposes. Power Management When power management is enabled, i.e., CONFIG_PM_ENABLE is on, the system clock frequency may be adjusted when the system is in an idle state. However, the ADC oneshot mode driver works in a polling routine, the adc_oneshot_read() will poll the CPU until the function returns. During this period of time, the task in which ADC oneshot mode driver resides will not be blocked. Therefore the clock frequency is stable when reading. IRAM Safe By default, all the ADC oneshot mode driver APIs are not supposed to be run when the Cache is disabled. Cache may be disabled due to many reasons, such as Flash writing/erasing, OTA, etc. If these APIs execute when the Cache is disabled, you will probably see errors like Illegal Instruction or Load/Store Prohibited. Thread Safety Above functions are guaranteed to be thread-safe. Therefore, you can call them from different RTOS tasks without protection by extra locks. adc_oneshot_del_unit()is not thread-safe. Besides, concurrently calling this function may result in failures of the above thread-safe APIs. Kconfig Options CONFIG_ADC_ONESHOT_CTRL_FUNC_IN_IRAM controls where to place the ADC fast read function (IRAM or Flash), see IRAM Safe for more details. Application Examples ADC oneshot mode example: peripherals/adc/oneshot_read. API Reference Header File This header file can be included with: #include "hal/adc_types.h" Structures - struct adc_digi_pattern_config_t ADC digital controller pattern configuration. - struct adc_digi_output_data_t ADC digital controller (DMA mode) output data format. Used to analyze the acquired ADC (DMA) data. Note ESP32: Only type1is valid. ADC2 does not support DMA mode. Note ESP32-S2: Member channelcan be used to judge the validity of the ADC data, because the role of the arbiter may get invalid ADC data. Public Members - uint16_t data ADC real output data info. Resolution: 12 bit. ADC real output data info. Resolution: 11 bit. - uint16_t channel ADC channel index info. ADC channel index info. For ESP32-S2: If (channel < ADC_CHANNEL_MAX), The data is valid. If (channel > ADC_CHANNEL_MAX), The data is invalid. - struct adc_digi_output_data_t::[anonymous]::[anonymous] type1 ADC type1 - uint16_t unit ADC unit index info. 0: ADC1; 1: ADC2. - struct adc_digi_output_data_t::[anonymous]::[anonymous] type2 When the configured output format is 11bit. - uint16_t val Raw data value - uint16_t data Type Definitions - typedef soc_periph_adc_digi_clk_src_t adc_oneshot_clk_src_t Clock source type of oneshot mode which uses digital controller. - typedef soc_periph_adc_digi_clk_src_t adc_continuous_clk_src_t Clock source type of continuous mode which uses digital controller. Enumerations - enum adc_unit_t ADC unit. Values: - enumerator ADC_UNIT_1 SAR ADC 1. - enumerator ADC_UNIT_2 SAR ADC 2. - enumerator ADC_UNIT_1 - enum adc_channel_t ADC channels. Values: - enumerator ADC_CHANNEL_0 ADC channel. - enumerator ADC_CHANNEL_1 ADC channel. - enumerator ADC_CHANNEL_2 ADC channel. - enumerator ADC_CHANNEL_3 ADC channel. - enumerator ADC_CHANNEL_4 ADC channel. - enumerator ADC_CHANNEL_5 ADC channel. - enumerator ADC_CHANNEL_6 ADC channel. - enumerator ADC_CHANNEL_7 ADC channel. - enumerator ADC_CHANNEL_8 ADC channel. - enumerator ADC_CHANNEL_9 ADC channel. - enumerator ADC_CHANNEL_0 - enum adc_atten_t ADC attenuation parameter. Different parameters determine the range of the ADC. Values: - enumerator ADC_ATTEN_DB_0 No input attenuation, ADC can measure up to approx. - enumerator ADC_ATTEN_DB_2_5 The input voltage of ADC will be attenuated extending the range of measurement by about 2.5 dB. - enumerator ADC_ATTEN_DB_6 The input voltage of ADC will be attenuated extending the range of measurement by about 6 dB. - enumerator ADC_ATTEN_DB_12 The input voltage of ADC will be attenuated extending the range of measurement by about 12 dB. - enumerator ADC_ATTEN_DB_11 This is deprecated, it behaves the same as ADC_ATTEN_DB_12 - enumerator ADC_ATTEN_DB_0 - enum adc_bitwidth_t Values: - enumerator ADC_BITWIDTH_DEFAULT Default ADC output bits, max supported width will be selected. - enumerator ADC_BITWIDTH_9 ADC output width is 9Bit. - enumerator ADC_BITWIDTH_10 ADC output width is 10Bit. - enumerator ADC_BITWIDTH_11 ADC output width is 11Bit. - enumerator ADC_BITWIDTH_12 ADC output width is 12Bit. - enumerator ADC_BITWIDTH_13 ADC output width is 13Bit. - enumerator ADC_BITWIDTH_DEFAULT - enum adc_ulp_mode_t Values: - enumerator ADC_ULP_MODE_DISABLE ADC ULP mode is disabled. - enumerator ADC_ULP_MODE_FSM ADC is controlled by ULP FSM. - enumerator ADC_ULP_MODE_RISCV ADC is controlled by ULP RISCV. - enumerator ADC_ULP_MODE_DISABLE - enum adc_digi_convert_mode_t ADC digital controller (DMA mode) work mode. Values: - enumerator ADC_CONV_SINGLE_UNIT_1 Only use ADC1 for conversion. - enumerator ADC_CONV_SINGLE_UNIT_2 Only use ADC2 for conversion. - enumerator ADC_CONV_BOTH_UNIT Use Both ADC1 and ADC2 for conversion simultaneously. - enumerator ADC_CONV_ALTER_UNIT Use both ADC1 and ADC2 for conversion by turn. e.g. ADC1 -> ADC2 -> ADC1 -> ADC2 ..... - enumerator ADC_CONV_SINGLE_UNIT_1 - enum adc_digi_output_format_t ADC digital controller (DMA mode) output data format option. Values: - enumerator ADC_DIGI_OUTPUT_FORMAT_TYPE1 - enumerator ADC_DIGI_OUTPUT_FORMAT_TYPE2 - enumerator ADC_DIGI_OUTPUT_FORMAT_TYPE1 - enum adc_digi_iir_filter_t ADC IIR Filter ID. Values: - enumerator ADC_DIGI_IIR_FILTER_0 Filter 0. - enumerator ADC_DIGI_IIR_FILTER_1 Filter 1. - enumerator ADC_DIGI_IIR_FILTER_0 - enum adc_digi_iir_filter_coeff_t IIR Filter Coefficient. Values: - enumerator ADC_DIGI_IIR_FILTER_COEFF_2 The filter coefficient is 2. - enumerator ADC_DIGI_IIR_FILTER_COEFF_4 The filter coefficient is 4. - enumerator ADC_DIGI_IIR_FILTER_COEFF_8 The filter coefficient is 8. - enumerator ADC_DIGI_IIR_FILTER_COEFF_16 The filter coefficient is 16. - enumerator ADC_DIGI_IIR_FILTER_COEFF_64 The filter coefficient is 64. - enumerator ADC_DIGI_IIR_FILTER_COEFF_2 - enum adc_monitor_id_t ADC monitor (continuous mode) ID. Values: - enumerator ADC_MONITOR_0 The monitor index 0. - enumerator ADC_MONITOR_1 The monitor index 1. - enumerator ADC_MONITOR_0 Header File This header file can be included with: #include "esp_adc/adc_oneshot.h" This header file is a part of the API provided by the esp_adccomponent. To declare that your component depends on esp_adc, add the following to your CMakeLists.txt: REQUIRES esp_adc or PRIV_REQUIRES esp_adc Functions - esp_err_t adc_oneshot_new_unit(const adc_oneshot_unit_init_cfg_t *init_config, adc_oneshot_unit_handle_t *ret_unit) Create a handle to a specific ADC unit. Note This API is thread-safe. For more details, see ADC programming guide - Parameters init_config -- [in] Driver initial configurations ret_unit -- [out] ADC unit handle - - Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_NO_MEM: No memory ESP_ERR_NOT_FOUND: The ADC peripheral to be claimed is already in use ESP_FAIL: Clock source isn't initialised correctly - - esp_err_t adc_oneshot_config_channel(adc_oneshot_unit_handle_t handle, adc_channel_t channel, const adc_oneshot_chan_cfg_t *config) Set ADC oneshot mode required configurations. Note This API is thread-safe. For more details, see ADC programming guide - Parameters handle -- [in] ADC handle channel -- [in] ADC channel to be configured config -- [in] ADC configurations - - Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments - - esp_err_t adc_oneshot_read(adc_oneshot_unit_handle_t handle, adc_channel_t chan, int *out_raw) Get one ADC conversion raw result. Note This API is thread-safe. For more details, see ADC programming guide Note This API should NOT be called in an ISR context - Parameters handle -- [in] ADC handle chan -- [in] ADC channel out_raw -- [out] ADC conversion raw result - - Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_TIMEOUT: Timeout, the ADC result is invalid - - esp_err_t adc_oneshot_del_unit(adc_oneshot_unit_handle_t handle) Delete the ADC unit handle. Note This API is thread-safe. For more details, see ADC programming guide - Parameters handle -- [in] ADC handle - Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_NOT_FOUND: The ADC peripheral to be disclaimed isn't in use - - esp_err_t adc_oneshot_io_to_channel(int io_num, adc_unit_t *const unit_id, adc_channel_t *const channel) Get ADC channel from the given GPIO number. - Parameters io_num -- [in] GPIO number unit_id -- [out] ADC unit channel -- [out] ADC channel - - Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_NOT_FOUND: The IO is not a valid ADC pad - - esp_err_t adc_oneshot_channel_to_io(adc_unit_t unit_id, adc_channel_t channel, int *const io_num) Get GPIO number from the given ADC channel. - Parameters unit_id -- [in] ADC unit channel -- [in] ADC channel io_num -- [out] GPIO number - -- ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument - - - esp_err_t adc_oneshot_get_calibrated_result(adc_oneshot_unit_handle_t handle, adc_cali_handle_t cali_handle, adc_channel_t chan, int *cali_result) Convenience function to get ADC calibrated result. This is an all-in-one function which does: oneshot read ADC raw result calibrate the raw result and convert it into calibrated result (in mV) - Parameters handle -- [in] ADC oneshot handle, you should call adc_oneshot_new_unit() to get this handle cali_handle -- [in] ADC calibration handle, you should call adc_cali_create_scheme_x() in adc_cali_scheme.h to create a handle chan -- [in] ADC channel cali_result -- [out] Calibrated ADC result (in mV) - - Returns ESP_OK Other return errors from adc_oneshot_read() and adc_cali_raw_to_voltage() - - Structures - struct adc_oneshot_unit_init_cfg_t ADC oneshot driver initial configurations. Public Members - adc_unit_t unit_id ADC unit. - adc_oneshot_clk_src_t clk_src Clock source. - adc_ulp_mode_t ulp_mode ADC controlled by ULP, see adc_ulp_mode_t - adc_unit_t unit_id - struct adc_oneshot_chan_cfg_t ADC channel configurations. Public Members - adc_atten_t atten ADC attenuation. - adc_bitwidth_t bitwidth ADC conversion result bits. - adc_atten_t atten Type Definitions - typedef struct adc_oneshot_unit_ctx_t *adc_oneshot_unit_handle_t Type of ADC unit handle for oneshot mode.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/adc_oneshot.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Analog to Digital Converter (ADC) Continuous Mode Driver
null
espressif.com
2016-01-01
9ed19a11b2369101
null
null
Analog to Digital Converter (ADC) Continuous Mode Driver Introduction The Analog to Digital Converter is integrated on the chip and is capable of measuring analog signals from specific analog IO pads. Additionally, the Direct Memory Access (DMA) functionality is utilized to efficiently retrieve ADC conversion results. ESP32 has two ADC unit(s), which can be used in scenarios like: Generate one-shot ADC conversion result Generate continuous ADC conversion results This guide introduces ADC continuous mode conversion. Driver Concepts ADC continuous mode conversion is made up of multiple conversion frames. Conversion Frame: One conversion frame contains multiple conversion results. Conversion frame size is configured in adc_continuous_new_handle() in bytes. Conversion Result: One conversion result contains multiple bytes, see SOC_ADC_DIGI_RESULT_BYTES . Its structure is adc_digi_output_data_t , including ADC unit, ADC channel, and raw data. Functional Overview The following sections of this document cover the typical steps to install the ADC continuous mode driver, and read ADC conversion results from a group of ADC channels continuously: Resource Allocation: covers which parameters should be set up to initialize the ADC continuous mode driver and how to deinitialize it. ADC Configurations: describes how to configure the ADC(s) to make it work under continuous mode. ADC Control: describes ADC control functions. Register Event Callbacks: describes how to hook user-specific code to an ADC continuous mode event callback function. Read Conversion Result: covers how to get ADC conversion result. Hardware Limitations: describes the ADC-related hardware limitations. Power Management: covers power management-related information. IRAM Safe: covers the IRAM safe functions. Thread Safety: lists which APIs are guaranteed to be thread-safe by the driver. Resource Allocation The ADC continuous mode driver is implemented based on ESP32 SAR ADC module. Different ESP targets might have different numbers of independent ADCs. To create an ADC continuous mode driver handle, set up the required configuration structure adc_continuous_handle_cfg_t : adc_continuous_handle_cfg_t::max_store_buf_size : set the maximum size of the pool in bytes, and the driver saves ADC conversion result into the pool. If this pool is full, new conversion results will be lost. adc_continuous_handle_cfg_t::conv_frame_size : set the size of the ADC conversion frame, in bytes. adc_continuous_handle_cfg_t::flags : set the flags that can change the driver's behavior. flush_pool : auto flush the pool when it's full. flush_pool : auto flush the pool when it's full. flush_pool : auto flush the pool when it's full. After setting up the above configurations for the ADC, call adc_continuous_new_handle() with the prepared adc_continuous_handle_cfg_t . This function may fail due to various errors such as invalid arguments, insufficient memory, etc. Especially, when this function returns ESP_ERR_NOT_FOUND , this means the I2S0 peripheral is in use. See Hardware Limitations for more information. If the ADC continuous mode driver is no longer used, you should deinitialize the driver by calling adc_continuous_deinit() . Initialize the ADC Continuous Mode Driver adc_continuous_handle_cfg_t adc_config = { .max_store_buf_size = 1024, .conv_frame_size = 100, }; ESP_ERROR_CHECK(adc_continuous_new_handle(&adc_config)); Recycle the ADC Unit ESP_ERROR_CHECK(adc_continuous_deinit()); ADC Configurations After the ADC continuous mode driver is initialized, set up the adc_continuous_config_t to configure ADC IOs to measure analog signal: adc_continuous_config_t::pattern_num : number of ADC channels that will be used. adc_continuous_config_t::adc_pattern : list of configs for each ADC channel that will be used, see the description below. adc_continuous_config_t::sample_freq_hz : expected ADC sampling frequency in Hz. adc_continuous_config_t::conv_mode : continuous conversion mode. adc_continuous_config_t::format : conversion output format. Set adc_digi_pattern_config_t with the following process: adc_digi_pattern_config_t::atten : ADC attenuation. Refer to the On-Chip Sensor and Analog Signal Processing chapter in TRM. adc_digi_pattern_config_t::channel : the IO corresponding ADC channel number. See the note below. adc_digi_pattern_config_t::unit : the ADC that the IO is subordinate to. adc_digi_pattern_config_t::bit_width : the bitwidth of the raw conversion result. Note For the IO corresponding ADC channel number, check TRM to acquire the ADC IOs. Besides, adc_continuous_io_to_channel() and adc_continuous_channel_to_io() can be used to acquire the ADC channels and ADC IOs. To make these settings take effect, call adc_continuous_config() with the configuration structure above. This API may fail due to reasons like ESP_ERR_INVALID_ARG . When it returns ESP_ERR_INVALID_STATE , this means the ADC continuous mode driver is started, you should not call this API at this moment. See ADC continuous mode example peripherals/adc/continuous_read to see configuration codes. ADC Control Start and Stop Calling adc_continuous_start() makes the ADC start to measure analog signals from the configured ADC channels, and generate the conversion results. On the contrary, calling adc_continuous_stop() stops the ADC conversion. ESP_ERROR_CHECK(adc_continuous_stop()); Register Event Callbacks By calling adc_continuous_register_event_callbacks() , you can hook your own function to the driver ISR. Supported event callbacks are listed in adc_continuous_evt_cbs_t . adc_continuous_evt_cbs_t::on_conv_done : this is invoked when one conversion frame finishes. adc_continuous_evt_cbs_t::on_pool_ovf : this is invoked when the internal pool is full. Newer conversion results will be discarded. As the above callbacks are called in an ISR context, you should always ensure the callback function is suitable for an ISR context. Blocking logic should not appear in these callbacks. The callback function prototype is declared in adc_continuous_callback_t . You can also register your own context when calling adc_continuous_register_event_callbacks() by the parameter user_data . This user data will be passed to the callback functions directly. This function may fail due to reasons like ESP_ERR_INVALID_ARG . Especially, when CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is enabled, this error may indicate that the callback functions are not in the internal RAM. Check the error log for more details. Besides, when it fails due to ESP_ERR_INVALID_STATE , it indicates that the ADC continuous mode driver is started, and you should not add a callback at this moment. Conversion Done Event When the driver completes a conversion, it triggers the adc_continuous_evt_cbs_t::on_conv_done event and fills the event data. Event data contains a buffer pointer to a conversion frame buffer, together with the size. Refer to adc_continuous_evt_data_t to know the event data structure. Note It is worth noting that, the data buffer adc_continuous_evt_data_t::conv_frame_buffer is maintained by the driver itself. Therefore, never free this piece of memory. Note When the Kconfig option CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is enabled, the registered callbacks and the functions called by the callbacks should be placed in IRAM. The involved variables should be placed in internal RAM as well. Pool Overflow Event The ADC continuous mode driver has an internal pool to save the conversion results. When the pool is full, a pool overflow event will emerge. Under this condition, the driver will not fill in the event data. This usually happens because the speed to read data from the pool by calling adc_continuous_read() is much slower than the ADC conversion speed. Read Conversion Result After calling adc_continuous_start() , the ADC continuous conversion starts. Call adc_continuous_read() to get the conversion results of the ADC channels. You need to provide a buffer to get the raw results. Function adc_continuous_read() tries to read the expected length of conversion results each time. When calling adc_continuous_read() , you can request to read a conversion result of the specified length. Sometimes, however, the actual available conversion results may be less than the requested length, in which case the function still moves the data from the internal pool into the buffer you provided. Therefore, to learn the number of conversion results actually moved into the buffer, please check the value of out_length . If there is no conversion result generated in the internal pool, the function will block for timeout_ms until the conversion results are generated. If there are still no generated results, the function will return ESP_ERR_TIMEOUT . If the generated results fill up the internal pool, newly generated results will be lost. Next time when adc_continuous_read() is called, this function will return ESP_ERR_INVALID_STATE to indicate this situation. This API aims to give you a chance to read all the ADC continuous conversion results. The ADC conversion results read from the above function are raw data. To calculate the voltage based on the ADC raw results, this formula can be used: Vout = Dout * Vmax / Dmax (1) where: Vout Digital output result, standing for the voltage. Dout ADC raw digital reading result. Vmax Maximum measurable input analog voltage, this is related to the ADC attenuation, please refer to the On-Chip Sensor and Analog Signal Processing chapter in TRM. Dmax Maximum of the output ADC raw digital reading result, which is 2^bitwidth, where the bitwidth is the To do further calibration to convert the ADC raw result to voltage in mV, please refer to Analog to Digital Converter (ADC) Calibration Driver. Hardware Limitations A specific ADC unit can only work under one operating mode at any one time, either continuous mode or one-shot mode. adc_continuous_start() has provided the protection. Random Number Generator (RNG) uses ADC as an input source. When ADC continuous mode driver works, the random number generated from RNG will be less random. ADC2 is also used by Wi-Fi. adc_continuous_start() has provided the protection between Wi-Fi driver and ADC continuous mode driver. ADC continuous mode driver uses I2S0 peripheral as hardware DMA FIFO. Therefore, if I2S0 is in use already, the adc_continuous_new_handle() will return ESP_ERR_NOT_FOUND . ESP32 DevKitC: GPIO 0 cannot be used due to external auto program circuits. ESP-WROVER-KIT: GPIO 0, 2, 4, and 15 cannot be used due to external connections for different purposes. Power Management When power management is enabled, i.e., CONFIG_PM_ENABLE is on, the APB clock frequency may be adjusted when the system is in an idle state, thus potentially changing the behavior of ADC continuous conversion. However, the continuous mode driver can prevent this change by acquiring a power management lock of type ESP_PM_APB_FREQ_MAX . The lock is acquired after the continuous conversion is started by adc_continuous_start() . Similarly, the lock will be released after adc_continuous_stop() . Therefore, adc_continuous_start() and adc_continuous_stop() should appear in pairs, otherwise, the power management will be out of action. IRAM Safe All the ADC continuous mode driver APIs are not IRAM-safe. They are not supposed to be run when the Cache is disabled. By enabling the Kconfig option CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE, the driver's internal ISR handler is IRAM-safe, which means even when the Cache is disabled, the driver will still save the conversion results into its internal pool. Thread Safety ADC continuous mode driver APIs are not guaranteed to be thread-safe. However, the share hardware mutual exclusion is provided by the driver. See Hardware Limitations for more details. Application Examples ADC continuous mode example: peripherals/adc/continuous_read. API Reference Header File This header file can be included with: #include "esp_adc/adc_continuous.h" This header file is a part of the API provided by the esp_adc component. To declare that your component depends on esp_adc , add the following to your CMakeLists.txt: REQUIRES esp_adc or PRIV_REQUIRES esp_adc Functions esp_err_t adc_continuous_new_handle(const adc_continuous_handle_cfg_t *hdl_config, adc_continuous_handle_t *ret_handle) Initialize ADC continuous driver and get a handle to it. Parameters hdl_config -- [in] Pointer to ADC initilization config. Refer to adc_continuous_handle_cfg_t . ret_handle -- [out] ADC continuous mode driver handle hdl_config -- [in] Pointer to ADC initilization config. Refer to adc_continuous_handle_cfg_t . ret_handle -- [out] ADC continuous mode driver handle hdl_config -- [in] Pointer to ADC initilization config. Refer to adc_continuous_handle_cfg_t . Returns ESP_ERR_INVALID_ARG If the combination of arguments is invalid. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_ERR_NO_MEM If out of memory ESP_OK On success ESP_ERR_INVALID_ARG If the combination of arguments is invalid. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_ERR_NO_MEM If out of memory ESP_OK On success ESP_ERR_INVALID_ARG If the combination of arguments is invalid. Parameters hdl_config -- [in] Pointer to ADC initilization config. Refer to adc_continuous_handle_cfg_t . ret_handle -- [out] ADC continuous mode driver handle Returns ESP_ERR_INVALID_ARG If the combination of arguments is invalid. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_ERR_NO_MEM If out of memory ESP_OK On success esp_err_t adc_continuous_config(adc_continuous_handle_t handle, const adc_continuous_config_t *config) Set ADC continuous mode required configurations. Parameters handle -- [in] ADC continuous mode driver handle config -- [in] Refer to adc_digi_config_t . handle -- [in] ADC continuous mode driver handle config -- [in] Refer to adc_digi_config_t . handle -- [in] ADC continuous mode driver handle Returns ESP_ERR_INVALID_STATE: Driver state is invalid, you shouldn't call this API at this moment ESP_ERR_INVALID_ARG: If the combination of arguments is invalid. ESP_OK: On success ESP_ERR_INVALID_STATE: Driver state is invalid, you shouldn't call this API at this moment ESP_ERR_INVALID_ARG: If the combination of arguments is invalid. ESP_OK: On success ESP_ERR_INVALID_STATE: Driver state is invalid, you shouldn't call this API at this moment Parameters handle -- [in] ADC continuous mode driver handle config -- [in] Refer to adc_digi_config_t . Returns ESP_ERR_INVALID_STATE: Driver state is invalid, you shouldn't call this API at this moment ESP_ERR_INVALID_ARG: If the combination of arguments is invalid. ESP_OK: On success esp_err_t adc_continuous_register_event_callbacks(adc_continuous_handle_t handle, const adc_continuous_evt_cbs_t *cbs, void *user_data) Register callbacks. Note User can deregister a previously registered callback by calling this function and setting the to-be-deregistered callback member in the cbs structure to NULL. Note When CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. Involved variables (including user_data ) should be in internal RAM as well. Note You should only call this API when the ADC continuous mode driver isn't started. Check return value to know this. Parameters handle -- [in] ADC continuous mode driver handle cbs -- [in] Group of callback functions user_data -- [in] User data, which will be delivered to the callback functions directly handle -- [in] ADC continuous mode driver handle cbs -- [in] Group of callback functions user_data -- [in] User data, which will be delivered to the callback functions directly handle -- [in] ADC continuous mode driver handle Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_INVALID_STATE: Driver state is invalid, you shouldn't call this API at this moment ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_INVALID_STATE: Driver state is invalid, you shouldn't call this API at this moment ESP_OK: On success Parameters handle -- [in] ADC continuous mode driver handle cbs -- [in] Group of callback functions user_data -- [in] User data, which will be delivered to the callback functions directly Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_INVALID_STATE: Driver state is invalid, you shouldn't call this API at this moment esp_err_t adc_continuous_start(adc_continuous_handle_t handle) Start the ADC under continuous mode. After this, the hardware starts working. Parameters handle -- [in] ADC continuous mode driver handle Returns ESP_ERR_INVALID_STATE Driver state is invalid. ESP_OK On success ESP_ERR_INVALID_STATE Driver state is invalid. ESP_OK On success ESP_ERR_INVALID_STATE Driver state is invalid. Parameters handle -- [in] ADC continuous mode driver handle Returns ESP_ERR_INVALID_STATE Driver state is invalid. ESP_OK On success esp_err_t adc_continuous_read(adc_continuous_handle_t handle, uint8_t *buf, uint32_t length_max, uint32_t *out_length, uint32_t timeout_ms) Read bytes from ADC under continuous mode. Parameters handle -- [in] ADC continuous mode driver handle buf -- [out] Conversion result buffer to read from ADC. Suggest convert to adc_digi_output_data_t for ADC Conversion Results . See the subsection Driver Backgrounds in this header file to learn about this concept. length_max -- [in] Expected length of the Conversion Results read from the ADC, in bytes. out_length -- [out] Real length of the Conversion Results read from the ADC via this API, in bytes. timeout_ms -- [in] Time to wait for data via this API, in millisecond. handle -- [in] ADC continuous mode driver handle buf -- [out] Conversion result buffer to read from ADC. Suggest convert to adc_digi_output_data_t for ADC Conversion Results . See the subsection Driver Backgrounds in this header file to learn about this concept. length_max -- [in] Expected length of the Conversion Results read from the ADC, in bytes. out_length -- [out] Real length of the Conversion Results read from the ADC via this API, in bytes. timeout_ms -- [in] Time to wait for data via this API, in millisecond. handle -- [in] ADC continuous mode driver handle Returns ESP_ERR_INVALID_STATE Driver state is invalid. Usually it means the ADC sampling rate is faster than the task processing rate. ESP_ERR_TIMEOUT Operation timed out ESP_OK On success ESP_ERR_INVALID_STATE Driver state is invalid. Usually it means the ADC sampling rate is faster than the task processing rate. ESP_ERR_TIMEOUT Operation timed out ESP_OK On success ESP_ERR_INVALID_STATE Driver state is invalid. Usually it means the ADC sampling rate is faster than the task processing rate. Parameters handle -- [in] ADC continuous mode driver handle buf -- [out] Conversion result buffer to read from ADC. Suggest convert to adc_digi_output_data_t for ADC Conversion Results . See the subsection Driver Backgrounds in this header file to learn about this concept. length_max -- [in] Expected length of the Conversion Results read from the ADC, in bytes. out_length -- [out] Real length of the Conversion Results read from the ADC via this API, in bytes. timeout_ms -- [in] Time to wait for data via this API, in millisecond. Returns ESP_ERR_INVALID_STATE Driver state is invalid. Usually it means the ADC sampling rate is faster than the task processing rate. ESP_ERR_TIMEOUT Operation timed out ESP_OK On success esp_err_t adc_continuous_stop(adc_continuous_handle_t handle) Stop the ADC. After this, the hardware stops working. Parameters handle -- [in] ADC continuous mode driver handle Returns ESP_ERR_INVALID_STATE Driver state is invalid. ESP_OK On success ESP_ERR_INVALID_STATE Driver state is invalid. ESP_OK On success ESP_ERR_INVALID_STATE Driver state is invalid. Parameters handle -- [in] ADC continuous mode driver handle Returns ESP_ERR_INVALID_STATE Driver state is invalid. ESP_OK On success esp_err_t adc_continuous_deinit(adc_continuous_handle_t handle) Deinitialize the ADC continuous driver. Parameters handle -- [in] ADC continuous mode driver handle Returns ESP_ERR_INVALID_STATE Driver state is invalid. ESP_OK On success ESP_ERR_INVALID_STATE Driver state is invalid. ESP_OK On success ESP_ERR_INVALID_STATE Driver state is invalid. Parameters handle -- [in] ADC continuous mode driver handle Returns ESP_ERR_INVALID_STATE Driver state is invalid. ESP_OK On success esp_err_t adc_continuous_flush_pool(adc_continuous_handle_t handle) Flush the driver internal pool. Note This API is not supposed to be called in an ISR context Parameters handle -- [in] ADC continuous mode driver handle Returns ESP_ERR_INVALID_STATE Driver state is invalid, you should call this API when it's in init state ESP_ERR_INVALID_ARG: Invalid arguments ESP_OK On success ESP_ERR_INVALID_STATE Driver state is invalid, you should call this API when it's in init state ESP_ERR_INVALID_ARG: Invalid arguments ESP_OK On success ESP_ERR_INVALID_STATE Driver state is invalid, you should call this API when it's in init state Parameters handle -- [in] ADC continuous mode driver handle Returns ESP_ERR_INVALID_STATE Driver state is invalid, you should call this API when it's in init state ESP_ERR_INVALID_ARG: Invalid arguments ESP_OK On success esp_err_t adc_continuous_io_to_channel(int io_num, adc_unit_t *const unit_id, adc_channel_t *const channel) Get ADC channel from the given GPIO number. Parameters io_num -- [in] GPIO number unit_id -- [out] ADC unit channel -- [out] ADC channel io_num -- [in] GPIO number unit_id -- [out] ADC unit channel -- [out] ADC channel io_num -- [in] GPIO number Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_NOT_FOUND: The IO is not a valid ADC pad ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_NOT_FOUND: The IO is not a valid ADC pad ESP_OK: On success Parameters io_num -- [in] GPIO number unit_id -- [out] ADC unit channel -- [out] ADC channel Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_NOT_FOUND: The IO is not a valid ADC pad esp_err_t adc_continuous_channel_to_io(adc_unit_t unit_id, adc_channel_t channel, int *const io_num) Get GPIO number from the given ADC channel. Parameters unit_id -- [in] ADC unit channel -- [in] ADC channel io_num -- [out] GPIO number - -- ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_INVALID_ARG: Invalid argument unit_id -- [in] ADC unit channel -- [in] ADC channel io_num -- [out] GPIO number - -- ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument unit_id -- [in] ADC unit Parameters unit_id -- [in] ADC unit channel -- [in] ADC channel io_num -- [out] GPIO number - -- ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument Structures struct adc_continuous_handle_cfg_t ADC continuous mode driver initial configurations. Public Members uint32_t max_store_buf_size Max length of the conversion results that driver can store, in bytes. uint32_t max_store_buf_size Max length of the conversion results that driver can store, in bytes. uint32_t conv_frame_size Conversion frame size, in bytes. This should be in multiples of SOC_ADC_DIGI_DATA_BYTES_PER_CONV . uint32_t conv_frame_size Conversion frame size, in bytes. This should be in multiples of SOC_ADC_DIGI_DATA_BYTES_PER_CONV . uint32_t flush_pool Flush the internal pool when the pool is full. uint32_t flush_pool Flush the internal pool when the pool is full. struct adc_continuous_handle_cfg_t::[anonymous] flags Driver flags. struct adc_continuous_handle_cfg_t::[anonymous] flags Driver flags. uint32_t max_store_buf_size struct adc_continuous_config_t ADC continuous mode driver configurations. Public Members uint32_t pattern_num Number of ADC channels that will be used. uint32_t pattern_num Number of ADC channels that will be used. adc_digi_pattern_config_t *adc_pattern List of configs for each ADC channel that will be used. adc_digi_pattern_config_t *adc_pattern List of configs for each ADC channel that will be used. uint32_t sample_freq_hz The expected ADC sampling frequency in Hz. Please refer to soc/soc_caps.h to know available sampling frequency range uint32_t sample_freq_hz The expected ADC sampling frequency in Hz. Please refer to soc/soc_caps.h to know available sampling frequency range adc_digi_convert_mode_t conv_mode ADC DMA conversion mode, see adc_digi_convert_mode_t . adc_digi_convert_mode_t conv_mode ADC DMA conversion mode, see adc_digi_convert_mode_t . adc_digi_output_format_t format ADC DMA conversion output format, see adc_digi_output_format_t . adc_digi_output_format_t format ADC DMA conversion output format, see adc_digi_output_format_t . uint32_t pattern_num struct adc_continuous_evt_data_t Event data structure. Note The conv_frame_buffer is maintained by the driver itself, so never free this piece of memory. struct adc_continuous_evt_cbs_t Group of ADC continuous mode callbacks. Note These callbacks are all running in an ISR environment. Note When CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. Involved variables should be in internal RAM as well. Public Members adc_continuous_callback_t on_conv_done Event callback, invoked when one conversion frame is done. See the subsection Driver Backgrounds in this header file to learn about the conversion frame concept. adc_continuous_callback_t on_conv_done Event callback, invoked when one conversion frame is done. See the subsection Driver Backgrounds in this header file to learn about the conversion frame concept. adc_continuous_callback_t on_pool_ovf Event callback, invoked when the internal pool is full. adc_continuous_callback_t on_pool_ovf Event callback, invoked when the internal pool is full. adc_continuous_callback_t on_conv_done Macros ADC_MAX_DELAY ADC read max timeout value, it may make the adc_continuous_read block forever if the OS supports. Type Definitions typedef struct adc_continuous_ctx_t *adc_continuous_handle_t Type of adc continuous mode driver handle. typedef bool (*adc_continuous_callback_t)(adc_continuous_handle_t handle, const adc_continuous_evt_data_t *edata, void *user_data) Prototype of ADC continuous mode event callback. Param handle [in] ADC continuous mode driver handle Param edata [in] Pointer to ADC continuous mode event data Param user_data [in] User registered context, registered when in adc_continuous_register_event_callbacks() Return Whether a high priority task is woken up by this function Param handle [in] ADC continuous mode driver handle Param edata [in] Pointer to ADC continuous mode event data Param user_data [in] User registered context, registered when in adc_continuous_register_event_callbacks() Return Whether a high priority task is woken up by this function
Analog to Digital Converter (ADC) Continuous Mode Driver Introduction The Analog to Digital Converter is integrated on the chip and is capable of measuring analog signals from specific analog IO pads. Additionally, the Direct Memory Access (DMA) functionality is utilized to efficiently retrieve ADC conversion results. ESP32 has two ADC unit(s), which can be used in scenarios like: Generate one-shot ADC conversion result Generate continuous ADC conversion results This guide introduces ADC continuous mode conversion. Driver Concepts ADC continuous mode conversion is made up of multiple conversion frames. Conversion Frame: One conversion frame contains multiple conversion results. Conversion frame size is configured in adc_continuous_new_handle()in bytes. Conversion Result: One conversion result contains multiple bytes, see SOC_ADC_DIGI_RESULT_BYTES. Its structure is adc_digi_output_data_t, including ADC unit, ADC channel, and raw data. Functional Overview The following sections of this document cover the typical steps to install the ADC continuous mode driver, and read ADC conversion results from a group of ADC channels continuously: Resource Allocation: covers which parameters should be set up to initialize the ADC continuous mode driver and how to deinitialize it. ADC Configurations: describes how to configure the ADC(s) to make it work under continuous mode. ADC Control: describes ADC control functions. Register Event Callbacks: describes how to hook user-specific code to an ADC continuous mode event callback function. Read Conversion Result: covers how to get ADC conversion result. Hardware Limitations: describes the ADC-related hardware limitations. Power Management: covers power management-related information. IRAM Safe: covers the IRAM safe functions. Thread Safety: lists which APIs are guaranteed to be thread-safe by the driver. Resource Allocation The ADC continuous mode driver is implemented based on ESP32 SAR ADC module. Different ESP targets might have different numbers of independent ADCs. To create an ADC continuous mode driver handle, set up the required configuration structure adc_continuous_handle_cfg_t: adc_continuous_handle_cfg_t::max_store_buf_size: set the maximum size of the pool in bytes, and the driver saves ADC conversion result into the pool. If this pool is full, new conversion results will be lost. adc_continuous_handle_cfg_t::conv_frame_size: set the size of the ADC conversion frame, in bytes. adc_continuous_handle_cfg_t::flags: set the flags that can change the driver's behavior. flush_pool: auto flush the pool when it's full. - After setting up the above configurations for the ADC, call adc_continuous_new_handle() with the prepared adc_continuous_handle_cfg_t. This function may fail due to various errors such as invalid arguments, insufficient memory, etc. Especially, when this function returns ESP_ERR_NOT_FOUND, this means the I2S0 peripheral is in use. See Hardware Limitations for more information. If the ADC continuous mode driver is no longer used, you should deinitialize the driver by calling adc_continuous_deinit(). Initialize the ADC Continuous Mode Driver adc_continuous_handle_cfg_t adc_config = { .max_store_buf_size = 1024, .conv_frame_size = 100, }; ESP_ERROR_CHECK(adc_continuous_new_handle(&adc_config)); Recycle the ADC Unit ESP_ERROR_CHECK(adc_continuous_deinit()); ADC Configurations After the ADC continuous mode driver is initialized, set up the adc_continuous_config_t to configure ADC IOs to measure analog signal: adc_continuous_config_t::pattern_num: number of ADC channels that will be used. adc_continuous_config_t::adc_pattern: list of configs for each ADC channel that will be used, see the description below. adc_continuous_config_t::sample_freq_hz: expected ADC sampling frequency in Hz. adc_continuous_config_t::conv_mode: continuous conversion mode. adc_continuous_config_t::format: conversion output format. Set adc_digi_pattern_config_t with the following process: adc_digi_pattern_config_t::atten: ADC attenuation. Refer to the On-Chip Sensor and Analog Signal Processing chapter in TRM. adc_digi_pattern_config_t::channel: the IO corresponding ADC channel number. See the note below. adc_digi_pattern_config_t::unit: the ADC that the IO is subordinate to. adc_digi_pattern_config_t::bit_width: the bitwidth of the raw conversion result. Note For the IO corresponding ADC channel number, check TRM to acquire the ADC IOs. Besides, adc_continuous_io_to_channel() and adc_continuous_channel_to_io() can be used to acquire the ADC channels and ADC IOs. To make these settings take effect, call adc_continuous_config() with the configuration structure above. This API may fail due to reasons like ESP_ERR_INVALID_ARG. When it returns ESP_ERR_INVALID_STATE, this means the ADC continuous mode driver is started, you should not call this API at this moment. See ADC continuous mode example peripherals/adc/continuous_read to see configuration codes. ADC Control Start and Stop Calling adc_continuous_start() makes the ADC start to measure analog signals from the configured ADC channels, and generate the conversion results. On the contrary, calling adc_continuous_stop() stops the ADC conversion. ESP_ERROR_CHECK(adc_continuous_stop()); Register Event Callbacks By calling adc_continuous_register_event_callbacks(), you can hook your own function to the driver ISR. Supported event callbacks are listed in adc_continuous_evt_cbs_t. adc_continuous_evt_cbs_t::on_conv_done: this is invoked when one conversion frame finishes. adc_continuous_evt_cbs_t::on_pool_ovf: this is invoked when the internal pool is full. Newer conversion results will be discarded. As the above callbacks are called in an ISR context, you should always ensure the callback function is suitable for an ISR context. Blocking logic should not appear in these callbacks. The callback function prototype is declared in adc_continuous_callback_t. You can also register your own context when calling adc_continuous_register_event_callbacks() by the parameter user_data. This user data will be passed to the callback functions directly. This function may fail due to reasons like ESP_ERR_INVALID_ARG. Especially, when CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is enabled, this error may indicate that the callback functions are not in the internal RAM. Check the error log for more details. Besides, when it fails due to ESP_ERR_INVALID_STATE, it indicates that the ADC continuous mode driver is started, and you should not add a callback at this moment. Conversion Done Event When the driver completes a conversion, it triggers the adc_continuous_evt_cbs_t::on_conv_done event and fills the event data. Event data contains a buffer pointer to a conversion frame buffer, together with the size. Refer to adc_continuous_evt_data_t to know the event data structure. Note It is worth noting that, the data buffer adc_continuous_evt_data_t::conv_frame_buffer is maintained by the driver itself. Therefore, never free this piece of memory. Note When the Kconfig option CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is enabled, the registered callbacks and the functions called by the callbacks should be placed in IRAM. The involved variables should be placed in internal RAM as well. Pool Overflow Event The ADC continuous mode driver has an internal pool to save the conversion results. When the pool is full, a pool overflow event will emerge. Under this condition, the driver will not fill in the event data. This usually happens because the speed to read data from the pool by calling adc_continuous_read() is much slower than the ADC conversion speed. Read Conversion Result After calling adc_continuous_start(), the ADC continuous conversion starts. Call adc_continuous_read() to get the conversion results of the ADC channels. You need to provide a buffer to get the raw results. Function adc_continuous_read() tries to read the expected length of conversion results each time. When calling adc_continuous_read(), you can request to read a conversion result of the specified length. Sometimes, however, the actual available conversion results may be less than the requested length, in which case the function still moves the data from the internal pool into the buffer you provided. Therefore, to learn the number of conversion results actually moved into the buffer, please check the value of out_length. If there is no conversion result generated in the internal pool, the function will block for timeout_msuntil the conversion results are generated. If there are still no generated results, the function will return ESP_ERR_TIMEOUT. If the generated results fill up the internal pool, newly generated results will be lost. Next time when adc_continuous_read()is called, this function will return ESP_ERR_INVALID_STATEto indicate this situation. This API aims to give you a chance to read all the ADC continuous conversion results. The ADC conversion results read from the above function are raw data. To calculate the voltage based on the ADC raw results, this formula can be used: Vout = Dout * Vmax / Dmax (1) where: | Vout | Digital output result, standing for the voltage. | Dout | ADC raw digital reading result. | Vmax | Maximum measurable input analog voltage, this is related to the ADC attenuation, please refer to the On-Chip Sensor and Analog Signal Processing chapter in TRM. | Dmax | Maximum of the output ADC raw digital reading result, which is 2^bitwidth, where the bitwidth is the To do further calibration to convert the ADC raw result to voltage in mV, please refer to Analog to Digital Converter (ADC) Calibration Driver. Hardware Limitations A specific ADC unit can only work under one operating mode at any one time, either continuous mode or one-shot mode. adc_continuous_start()has provided the protection. Random Number Generator (RNG) uses ADC as an input source. When ADC continuous mode driver works, the random number generated from RNG will be less random. ADC2 is also used by Wi-Fi. adc_continuous_start()has provided the protection between Wi-Fi driver and ADC continuous mode driver. ADC continuous mode driver uses I2S0 peripheral as hardware DMA FIFO. Therefore, if I2S0 is in use already, the adc_continuous_new_handle()will return ESP_ERR_NOT_FOUND. ESP32 DevKitC: GPIO 0 cannot be used due to external auto program circuits. ESP-WROVER-KIT: GPIO 0, 2, 4, and 15 cannot be used due to external connections for different purposes. Power Management When power management is enabled, i.e., CONFIG_PM_ENABLE is on, the APB clock frequency may be adjusted when the system is in an idle state, thus potentially changing the behavior of ADC continuous conversion. However, the continuous mode driver can prevent this change by acquiring a power management lock of type ESP_PM_APB_FREQ_MAX. The lock is acquired after the continuous conversion is started by adc_continuous_start(). Similarly, the lock will be released after adc_continuous_stop(). Therefore, adc_continuous_start() and adc_continuous_stop() should appear in pairs, otherwise, the power management will be out of action. IRAM Safe All the ADC continuous mode driver APIs are not IRAM-safe. They are not supposed to be run when the Cache is disabled. By enabling the Kconfig option CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE, the driver's internal ISR handler is IRAM-safe, which means even when the Cache is disabled, the driver will still save the conversion results into its internal pool. Thread Safety ADC continuous mode driver APIs are not guaranteed to be thread-safe. However, the share hardware mutual exclusion is provided by the driver. See Hardware Limitations for more details. Application Examples ADC continuous mode example: peripherals/adc/continuous_read. API Reference Header File This header file can be included with: #include "esp_adc/adc_continuous.h" This header file is a part of the API provided by the esp_adccomponent. To declare that your component depends on esp_adc, add the following to your CMakeLists.txt: REQUIRES esp_adc or PRIV_REQUIRES esp_adc Functions - esp_err_t adc_continuous_new_handle(const adc_continuous_handle_cfg_t *hdl_config, adc_continuous_handle_t *ret_handle) Initialize ADC continuous driver and get a handle to it. - Parameters hdl_config -- [in] Pointer to ADC initilization config. Refer to adc_continuous_handle_cfg_t. ret_handle -- [out] ADC continuous mode driver handle - - Returns ESP_ERR_INVALID_ARG If the combination of arguments is invalid. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_ERR_NO_MEM If out of memory ESP_OK On success - - esp_err_t adc_continuous_config(adc_continuous_handle_t handle, const adc_continuous_config_t *config) Set ADC continuous mode required configurations. - Parameters handle -- [in] ADC continuous mode driver handle config -- [in] Refer to adc_digi_config_t. - - Returns ESP_ERR_INVALID_STATE: Driver state is invalid, you shouldn't call this API at this moment ESP_ERR_INVALID_ARG: If the combination of arguments is invalid. ESP_OK: On success - - esp_err_t adc_continuous_register_event_callbacks(adc_continuous_handle_t handle, const adc_continuous_evt_cbs_t *cbs, void *user_data) Register callbacks. Note User can deregister a previously registered callback by calling this function and setting the to-be-deregistered callback member in the cbsstructure to NULL. Note When CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. Involved variables (including user_data) should be in internal RAM as well. Note You should only call this API when the ADC continuous mode driver isn't started. Check return value to know this. - Parameters handle -- [in] ADC continuous mode driver handle cbs -- [in] Group of callback functions user_data -- [in] User data, which will be delivered to the callback functions directly - - Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_INVALID_STATE: Driver state is invalid, you shouldn't call this API at this moment - - esp_err_t adc_continuous_start(adc_continuous_handle_t handle) Start the ADC under continuous mode. After this, the hardware starts working. - Parameters handle -- [in] ADC continuous mode driver handle - Returns ESP_ERR_INVALID_STATE Driver state is invalid. ESP_OK On success - - esp_err_t adc_continuous_read(adc_continuous_handle_t handle, uint8_t *buf, uint32_t length_max, uint32_t *out_length, uint32_t timeout_ms) Read bytes from ADC under continuous mode. - Parameters handle -- [in] ADC continuous mode driver handle buf -- [out] Conversion result buffer to read from ADC. Suggest convert to adc_digi_output_data_tfor ADC Conversion Results. See the subsection Driver Backgroundsin this header file to learn about this concept. length_max -- [in] Expected length of the Conversion Results read from the ADC, in bytes. out_length -- [out] Real length of the Conversion Results read from the ADC via this API, in bytes. timeout_ms -- [in] Time to wait for data via this API, in millisecond. - - Returns ESP_ERR_INVALID_STATE Driver state is invalid. Usually it means the ADC sampling rate is faster than the task processing rate. ESP_ERR_TIMEOUT Operation timed out ESP_OK On success - - esp_err_t adc_continuous_stop(adc_continuous_handle_t handle) Stop the ADC. After this, the hardware stops working. - Parameters handle -- [in] ADC continuous mode driver handle - Returns ESP_ERR_INVALID_STATE Driver state is invalid. ESP_OK On success - - esp_err_t adc_continuous_deinit(adc_continuous_handle_t handle) Deinitialize the ADC continuous driver. - Parameters handle -- [in] ADC continuous mode driver handle - Returns ESP_ERR_INVALID_STATE Driver state is invalid. ESP_OK On success - - esp_err_t adc_continuous_flush_pool(adc_continuous_handle_t handle) Flush the driver internal pool. Note This API is not supposed to be called in an ISR context - Parameters handle -- [in] ADC continuous mode driver handle - Returns ESP_ERR_INVALID_STATE Driver state is invalid, you should call this API when it's in init state ESP_ERR_INVALID_ARG: Invalid arguments ESP_OK On success - - esp_err_t adc_continuous_io_to_channel(int io_num, adc_unit_t *const unit_id, adc_channel_t *const channel) Get ADC channel from the given GPIO number. - Parameters io_num -- [in] GPIO number unit_id -- [out] ADC unit channel -- [out] ADC channel - - Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_NOT_FOUND: The IO is not a valid ADC pad - - esp_err_t adc_continuous_channel_to_io(adc_unit_t unit_id, adc_channel_t channel, int *const io_num) Get GPIO number from the given ADC channel. - Parameters unit_id -- [in] ADC unit channel -- [in] ADC channel io_num -- [out] GPIO number - -- ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument - - Structures - struct adc_continuous_handle_cfg_t ADC continuous mode driver initial configurations. Public Members - uint32_t max_store_buf_size Max length of the conversion results that driver can store, in bytes. - uint32_t conv_frame_size Conversion frame size, in bytes. This should be in multiples of SOC_ADC_DIGI_DATA_BYTES_PER_CONV. - uint32_t flush_pool Flush the internal pool when the pool is full. - struct adc_continuous_handle_cfg_t::[anonymous] flags Driver flags. - uint32_t max_store_buf_size - struct adc_continuous_config_t ADC continuous mode driver configurations. Public Members - uint32_t pattern_num Number of ADC channels that will be used. - adc_digi_pattern_config_t *adc_pattern List of configs for each ADC channel that will be used. - uint32_t sample_freq_hz The expected ADC sampling frequency in Hz. Please refer to soc/soc_caps.hto know available sampling frequency range - adc_digi_convert_mode_t conv_mode ADC DMA conversion mode, see adc_digi_convert_mode_t. - adc_digi_output_format_t format ADC DMA conversion output format, see adc_digi_output_format_t. - uint32_t pattern_num - struct adc_continuous_evt_data_t Event data structure. Note The conv_frame_bufferis maintained by the driver itself, so never free this piece of memory. - struct adc_continuous_evt_cbs_t Group of ADC continuous mode callbacks. Note These callbacks are all running in an ISR environment. Note When CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. Involved variables should be in internal RAM as well. Public Members - adc_continuous_callback_t on_conv_done Event callback, invoked when one conversion frame is done. See the subsection Driver Backgroundsin this header file to learn about the conversion frameconcept. - adc_continuous_callback_t on_pool_ovf Event callback, invoked when the internal pool is full. - adc_continuous_callback_t on_conv_done Macros - ADC_MAX_DELAY ADC read max timeout value, it may make the adc_continuous_readblock forever if the OS supports. Type Definitions - typedef struct adc_continuous_ctx_t *adc_continuous_handle_t Type of adc continuous mode driver handle. - typedef bool (*adc_continuous_callback_t)(adc_continuous_handle_t handle, const adc_continuous_evt_data_t *edata, void *user_data) Prototype of ADC continuous mode event callback. - Param handle [in] ADC continuous mode driver handle - Param edata [in] Pointer to ADC continuous mode event data - Param user_data [in] User registered context, registered when in adc_continuous_register_event_callbacks() - Return Whether a high priority task is woken up by this function
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/adc_continuous.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Analog to Digital Converter (ADC) Calibration Driver
null
espressif.com
2016-01-01
deb38c77a61b01d3
null
null
Analog to Digital Converter (ADC) Calibration Driver Introduction In ESP32, the digital-to-analog converter (ADC) compares the input analog voltage to the reference, and determines each bit of the output digital result. By design, the ADC reference voltage for ESP32 is 1100 mV. However, the true reference voltage can range from 1000 mV to 1200 mV among different chips. This guide introduces the ADC calibration driver to minimize the effect of different reference voltages, and get more accurate output results. Functional Overview The following sections of this document cover the typical steps to install and use the ADC calibration driver: Calibration Scheme Creation - covers how to create a calibration scheme handle and delete the calibration scheme handle. Result Conversion - covers how to convert ADC raw result to calibrated result. Thread Safety - lists which APIs are guaranteed to be thread-safe by the driver. Minimize Noise - describes a general way to minimize the noise. Kconfig Options - lists the supported Kconfig options that can be used to make a different effect on driver behavior. Calibration Scheme Creation The ADC calibration driver provides ADC calibration scheme(s). From the calibration driver's point of view, an ADC calibration scheme is created for an ADC calibration handle adc_cali_handle_t . adc_cali_check_scheme() can be used to know which calibration scheme is supported on the chip. If you already know the supported schemes, this step can be skipped. Just call the corresponding function to create the scheme handle. If you use your custom ADC calibration schemes, you could either modify this function adc_cali_check_scheme() , or just skip this step and call your custom creation function. ADC Calibration Line Fitting Scheme ESP32 supports ADC_CALI_SCHEME_VER_LINE_FITTING scheme. To create this scheme, set up adc_cali_line_fitting_config_t first. adc_cali_line_fitting_config_t::unit_id , the ADC that your ADC raw results are from. adc_cali_line_fitting_config_t::atten , ADC attenuation that your ADC raw results use. adc_cali_line_fitting_config_t::bitwidth , bit width of ADC raw result. There is also a configuration adc_cali_line_fitting_config_t::default_vref . Normally this can be simply set to 0. Line Fitting scheme does not rely on this value. However, if the Line Fitting scheme required eFuse bits are not burned on your board, the driver will rely on this value to do the calibration. You can use adc_cali_scheme_line_fitting_check_efuse() to check the eFuse bits. Normally the Line Fitting scheme eFuse value is ADC_CALI_LINE_FITTING_EFUSE_VAL_EFUSE_TP or ADC_CALI_LINE_FITTING_EFUSE_VAL_EFUSE_VREF . This means the Line Fitting scheme uses calibration parameters burned in the eFuse to do the calibration. When the Line Fitting scheme eFuse value is ADC_CALI_LINE_FITTING_EFUSE_VAL_DEFAULT_VREF , you need to set the esp_adc_cali_line_fitting_init::default_vref . Default vref is an estimate of the ADC reference voltage provided as a parameter during calibration. After setting up the configuration structure, call adc_cali_create_scheme_line_fitting() to create a Line Fitting calibration scheme handle. ESP_LOGI(TAG, "calibration scheme version is %s", "Line Fitting"); adc_cali_line_fitting_config_t cali_config = { .unit_id = unit, .atten = atten, .bitwidth = ADC_BITWIDTH_DEFAULT, }; ESP_ERROR_CHECK(adc_cali_create_scheme_line_fitting(&cali_config, &handle)); When the ADC calibration is no longer used, please delete the calibration scheme handle by calling adc_cali_delete_scheme_line_fitting() . Delete Line Fitting Scheme ESP_LOGI(TAG, "delete %s calibration scheme", "Line Fitting"); ESP_ERROR_CHECK(adc_cali_delete_scheme_line_fitting(handle)); Note If you want to use your custom calibration schemes, you could provide a creation function to create your calibration scheme handle. Check the function table adc_cali_scheme_t in components/esp_adc/interface/adc_cali_interface.h to know the ESP ADC calibration interface. Result Conversion After setting up the calibration characteristics, you can call adc_cali_raw_to_voltage() to convert the ADC raw result into calibrated result. The calibrated result is in the unit of mV. This function may fail due to an invalid argument. Especially, if this function returns ESP_ERR_INVALID_STATE , this means the calibration scheme is not created. You need to create a calibration scheme handle, use adc_cali_check_scheme() to know the supported calibration scheme. On the other hand, you could also provide a custom calibration scheme and create the handle. Get Voltage ESP_ERROR_CHECK(adc_cali_raw_to_voltage(adc_cali_handle, adc_raw[0][0], &voltage[0][0])); ESP_LOGI(TAG, "ADC%d Channel[%d] Cali Voltage: %d mV", ADC_UNIT_1 + 1, EXAMPLE_ADC1_CHAN0, voltage[0][0]); Thread Safety The factory function esp_adc_cali_new_scheme() is guaranteed to be thread-safe by the driver. Therefore, you can call them from different RTOS tasks without protection by extra locks. Other functions that take the adc_cali_handle_t as the first positional parameter are not thread-safe, you should avoid calling them from multiple tasks. Kconfig Options CONFIG_ADC_CAL_EFUSE_TP_ENABLE - disable this to decrease the code size, if the calibration eFuse value is not set to ADC_CALI_LINE_FITTING_EFUSE_VAL_EFUSE_TP . CONFIG_ADC_CAL_EFUSE_VREF_ENABLE - disable this to decrease the code size, if the calibration eFuse value is not set to ADC_CALI_LINE_FITTING_EFUSE_VAL_EFUSE_VREF . CONFIG_ADC_CAL_LUT_ENABLE - disable this to decrease the code size, if you do not calibrate the ADC raw results under ADC_ATTEN_DB_12 . Minimize Noise The ESP32 ADC is sensitive to noise, leading to large discrepancies in ADC readings. Depending on the usage scenario, you may need to connect a bypass capacitor (e.g., a 100 nF ceramic capacitor) to the ADC input pad in use, to minimize noise. Besides, multisampling may also be used to further mitigate the effects of noise. API Reference Header File This header file can be included with: #include "esp_adc/adc_cali.h" This header file is a part of the API provided by the esp_adc component. To declare that your component depends on esp_adc , add the following to your CMakeLists.txt: REQUIRES esp_adc or PRIV_REQUIRES esp_adc Functions esp_err_t adc_cali_check_scheme(adc_cali_scheme_ver_t *scheme_mask) Check the supported ADC calibration scheme. Parameters scheme_mask -- [out] Supported ADC calibration scheme(s) Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_NOT_SUPPORTED: No supported calibration scheme ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_NOT_SUPPORTED: No supported calibration scheme ESP_OK: On success Parameters scheme_mask -- [out] Supported ADC calibration scheme(s) Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_NOT_SUPPORTED: No supported calibration scheme esp_err_t adc_cali_raw_to_voltage(adc_cali_handle_t handle, int raw, int *voltage) Convert ADC raw data to calibrated voltage. Parameters handle -- [in] ADC calibration handle raw -- [in] ADC raw data voltage -- [out] Calibrated ADC voltage (in mV) handle -- [in] ADC calibration handle raw -- [in] ADC raw data voltage -- [out] Calibrated ADC voltage (in mV) handle -- [in] ADC calibration handle Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_INVALID_STATE: Invalid state, scheme didn't registered ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_INVALID_STATE: Invalid state, scheme didn't registered ESP_OK: On success Parameters handle -- [in] ADC calibration handle raw -- [in] ADC raw data voltage -- [out] Calibrated ADC voltage (in mV) Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_INVALID_STATE: Invalid state, scheme didn't registered Type Definitions typedef struct adc_cali_scheme_t *adc_cali_handle_t ADC calibration handle. Enumerations Header File This header file can be included with: #include "esp_adc/adc_cali_scheme.h" This header file is a part of the API provided by the esp_adc component. To declare that your component depends on esp_adc , add the following to your CMakeLists.txt: REQUIRES esp_adc or PRIV_REQUIRES esp_adc
Analog to Digital Converter (ADC) Calibration Driver Introduction In ESP32, the digital-to-analog converter (ADC) compares the input analog voltage to the reference, and determines each bit of the output digital result. By design, the ADC reference voltage for ESP32 is 1100 mV. However, the true reference voltage can range from 1000 mV to 1200 mV among different chips. This guide introduces the ADC calibration driver to minimize the effect of different reference voltages, and get more accurate output results. Functional Overview The following sections of this document cover the typical steps to install and use the ADC calibration driver: Calibration Scheme Creation - covers how to create a calibration scheme handle and delete the calibration scheme handle. Result Conversion - covers how to convert ADC raw result to calibrated result. Thread Safety - lists which APIs are guaranteed to be thread-safe by the driver. Minimize Noise - describes a general way to minimize the noise. Kconfig Options - lists the supported Kconfig options that can be used to make a different effect on driver behavior. Calibration Scheme Creation The ADC calibration driver provides ADC calibration scheme(s). From the calibration driver's point of view, an ADC calibration scheme is created for an ADC calibration handle adc_cali_handle_t. adc_cali_check_scheme() can be used to know which calibration scheme is supported on the chip. If you already know the supported schemes, this step can be skipped. Just call the corresponding function to create the scheme handle. If you use your custom ADC calibration schemes, you could either modify this function adc_cali_check_scheme(), or just skip this step and call your custom creation function. ADC Calibration Line Fitting Scheme ESP32 supports ADC_CALI_SCHEME_VER_LINE_FITTING scheme. To create this scheme, set up adc_cali_line_fitting_config_t first. adc_cali_line_fitting_config_t::unit_id, the ADC that your ADC raw results are from. adc_cali_line_fitting_config_t::atten, ADC attenuation that your ADC raw results use. adc_cali_line_fitting_config_t::bitwidth, bit width of ADC raw result. There is also a configuration adc_cali_line_fitting_config_t::default_vref. Normally this can be simply set to 0. Line Fitting scheme does not rely on this value. However, if the Line Fitting scheme required eFuse bits are not burned on your board, the driver will rely on this value to do the calibration. You can use adc_cali_scheme_line_fitting_check_efuse() to check the eFuse bits. Normally the Line Fitting scheme eFuse value is ADC_CALI_LINE_FITTING_EFUSE_VAL_EFUSE_TP or ADC_CALI_LINE_FITTING_EFUSE_VAL_EFUSE_VREF. This means the Line Fitting scheme uses calibration parameters burned in the eFuse to do the calibration. When the Line Fitting scheme eFuse value is ADC_CALI_LINE_FITTING_EFUSE_VAL_DEFAULT_VREF, you need to set the esp_adc_cali_line_fitting_init::default_vref. Default vref is an estimate of the ADC reference voltage provided as a parameter during calibration. After setting up the configuration structure, call adc_cali_create_scheme_line_fitting() to create a Line Fitting calibration scheme handle. ESP_LOGI(TAG, "calibration scheme version is %s", "Line Fitting"); adc_cali_line_fitting_config_t cali_config = { .unit_id = unit, .atten = atten, .bitwidth = ADC_BITWIDTH_DEFAULT, }; ESP_ERROR_CHECK(adc_cali_create_scheme_line_fitting(&cali_config, &handle)); When the ADC calibration is no longer used, please delete the calibration scheme handle by calling adc_cali_delete_scheme_line_fitting(). Delete Line Fitting Scheme ESP_LOGI(TAG, "delete %s calibration scheme", "Line Fitting"); ESP_ERROR_CHECK(adc_cali_delete_scheme_line_fitting(handle)); Note If you want to use your custom calibration schemes, you could provide a creation function to create your calibration scheme handle. Check the function table adc_cali_scheme_t in components/esp_adc/interface/adc_cali_interface.h to know the ESP ADC calibration interface. Result Conversion After setting up the calibration characteristics, you can call adc_cali_raw_to_voltage() to convert the ADC raw result into calibrated result. The calibrated result is in the unit of mV. This function may fail due to an invalid argument. Especially, if this function returns ESP_ERR_INVALID_STATE, this means the calibration scheme is not created. You need to create a calibration scheme handle, use adc_cali_check_scheme() to know the supported calibration scheme. On the other hand, you could also provide a custom calibration scheme and create the handle. Get Voltage ESP_ERROR_CHECK(adc_cali_raw_to_voltage(adc_cali_handle, adc_raw[0][0], &voltage[0][0])); ESP_LOGI(TAG, "ADC%d Channel[%d] Cali Voltage: %d mV", ADC_UNIT_1 + 1, EXAMPLE_ADC1_CHAN0, voltage[0][0]); Thread Safety The factory function esp_adc_cali_new_scheme() is guaranteed to be thread-safe by the driver. Therefore, you can call them from different RTOS tasks without protection by extra locks. Other functions that take the adc_cali_handle_t as the first positional parameter are not thread-safe, you should avoid calling them from multiple tasks. Kconfig Options CONFIG_ADC_CAL_EFUSE_TP_ENABLE - disable this to decrease the code size, if the calibration eFuse value is not set to ADC_CALI_LINE_FITTING_EFUSE_VAL_EFUSE_TP. CONFIG_ADC_CAL_EFUSE_VREF_ENABLE - disable this to decrease the code size, if the calibration eFuse value is not set to ADC_CALI_LINE_FITTING_EFUSE_VAL_EFUSE_VREF. CONFIG_ADC_CAL_LUT_ENABLE - disable this to decrease the code size, if you do not calibrate the ADC raw results under ADC_ATTEN_DB_12. Minimize Noise The ESP32 ADC is sensitive to noise, leading to large discrepancies in ADC readings. Depending on the usage scenario, you may need to connect a bypass capacitor (e.g., a 100 nF ceramic capacitor) to the ADC input pad in use, to minimize noise. Besides, multisampling may also be used to further mitigate the effects of noise. API Reference Header File This header file can be included with: #include "esp_adc/adc_cali.h" This header file is a part of the API provided by the esp_adccomponent. To declare that your component depends on esp_adc, add the following to your CMakeLists.txt: REQUIRES esp_adc or PRIV_REQUIRES esp_adc Functions - esp_err_t adc_cali_check_scheme(adc_cali_scheme_ver_t *scheme_mask) Check the supported ADC calibration scheme. - Parameters scheme_mask -- [out] Supported ADC calibration scheme(s) - Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_NOT_SUPPORTED: No supported calibration scheme - - esp_err_t adc_cali_raw_to_voltage(adc_cali_handle_t handle, int raw, int *voltage) Convert ADC raw data to calibrated voltage. - Parameters handle -- [in] ADC calibration handle raw -- [in] ADC raw data voltage -- [out] Calibrated ADC voltage (in mV) - - Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_INVALID_STATE: Invalid state, scheme didn't registered - Type Definitions - typedef struct adc_cali_scheme_t *adc_cali_handle_t ADC calibration handle. Enumerations Header File This header file can be included with: #include "esp_adc/adc_cali_scheme.h" This header file is a part of the API provided by the esp_adccomponent. To declare that your component depends on esp_adc, add the following to your CMakeLists.txt: REQUIRES esp_adc or PRIV_REQUIRES esp_adc
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/adc_calibration.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Clock Tree
null
espressif.com
2016-01-01
8770ba38260aa866
null
null
Clock Tree The clock subsystem of ESP32 is used to source and distribute system/module clocks from a range of root clocks. The clock tree driver maintains the basic functionality of the system clock and the intricate relationship among module clocks. This document starts with the introduction to root and module clocks. Then it covers the clock tree APIs that can be called to monitor the status of the module clocks at runtime. Introduction This section lists definitions of ESP32's supported root clocks and module clocks. These definitions are commonly used in the driver configuration, to help select a proper source clock for the peripheral. Root Clocks Root clocks generate reliable clock signals. These clock signals then pass through various gates, muxes, dividers, or multipliers to become the clock sources for every functional module: the CPU core(s), Wi-Fi, Bluetooth, the RTC, and the peripherals. ESP32's root clocks are listed in soc_root_clk_t : Internal 8 MHz RC Oscillator (RC_FAST) This RC oscillator generates a about 8.5 MHz clock signal output as the RC_FAST_CLK . The about 8.5 MHz signal output is also passed into a configurable divider, which by default divides the input clock frequency by 256, to generate a RC_FAST_D256_CLK . The exact frequency of RC_FAST_CLK can be computed in runtime through calibration on the RC_FAST_D256_CLK . External 2 ~ 40 MHz Crystal (XTAL) Internal 150 kHz RC Oscillator (RC_SLOW) This RC oscillator generates a about 150kHz clock signal output as the RC_SLOW_CLK . The exact frequency of this clock can be computed in runtime through calibration. External 32 kHz Crystal - optional (XTAL32K) The clock source for this XTAL32K_CLK can be either a 32 kHz crystal connecting to the 32K_XP and 32K_XN pins or a 32 kHz clock signal generated by an external circuit. The external signal must be connected to the 32K_XN pin. Additionally, a 1 nF capacitor must be placed between the 32K_XP pin and ground. In this case, the 32K_XP pin cannot be used as a GPIO pin. XTAL32K_CLK can also be calibrated to get its exact frequency. Typically, the frequency of the signal generated from an RC oscillator circuit is less accurate and more sensitive to the environment compared to the signal generated from a crystal. ESP32 provides several clock source options for the RTC_SLOW_CLK , and it is possible to make the choice based on the requirements for system time accuracy and power consumption. For more details, please refer to RTC Timer Clock Sources. Module Clocks ESP32's available module clocks are listed in soc_module_clk_t . Each module clock has a unique ID. You can get more information on each clock by checking the documented enum value. API Usage The clock tree driver provides an all-in-one API to get the frequency of the module clocks, esp_clk_tree_src_get_freq_hz() . This function allows you to obtain the clock frequency at any time by providing the clock name soc_module_clk_t and specifying the desired precision level for the returned frequency value esp_clk_tree_src_freq_precision_t . API Reference Header File This header file can be included with: #include "soc/clk_tree_defs.h" Macros SOC_CLK_RC_FAST_FREQ_APPROX Approximate RC_FAST_CLK frequency in Hz SOC_CLK_RC_SLOW_FREQ_APPROX Approximate RC_SLOW_CLK frequency in Hz SOC_CLK_RC_FAST_D256_FREQ_APPROX Approximate RC_FAST_D256_CLK frequency in Hz SOC_CLK_XTAL32K_FREQ_APPROX Approximate XTAL32K_CLK frequency in Hz SOC_GPTIMER_CLKS Array initializer for all supported clock sources of GPTimer. The following code can be used to iterate all possible clocks: soc_periph_gptimer_clk_src_t gptimer_clks[] = (soc_periph_gptimer_clk_src_t)SOC_GPTIMER_CLKS; for (size_t i = 0; i< sizeof(gptimer_clks) / sizeof(gptimer_clks[0]); i++) { soc_periph_gptimer_clk_src_t clk = gptimer_clks[i]; // Test GPTimer with the clock `clk` } SOC_LCD_CLKS Array initializer for all supported clock sources of LCD. SOC_RMT_CLKS Array initializer for all supported clock sources of RMT. SOC_MCPWM_TIMER_CLKS Array initializer for all supported clock sources of MCPWM Timer. SOC_MCPWM_CAPTURE_CLKS Array initializer for all supported clock sources of MCPWM Capture Timer. SOC_MCPWM_CARRIER_CLKS Array initializer for all supported clock sources of MCPWM Carrier. SOC_I2S_CLKS Array initializer for all supported clock sources of I2S. SOC_I2C_CLKS Array initializer for all supported clock sources of I2C. SOC_SPI_CLKS Array initializer for all supported clock sources of SPI. SOC_SDM_CLKS Array initializer for all supported clock sources of SDM. SOC_DAC_DIGI_CLKS Array initializer for all supported clock sources of DAC digital controller. SOC_DAC_COSINE_CLKS Array initializer for all supported clock sources of DAC cosine wave generator. SOC_TWAI_CLKS Array initializer for all supported clock sources of TWAI. SOC_ADC_DIGI_CLKS Array initializer for all supported clock sources of ADC digital controller. SOC_ADC_RTC_CLKS Array initializer for all supported clock sources of ADC RTC controller. SOC_MWDT_CLKS Array initializer for all supported clock sources of MWDT. SOC_LEDC_CLKS Array initializer for all supported clock sources of LEDC. SOC_SDMMC_CLKS Array initializer for all supported clock sources of SDMMC. Enumerations enum soc_root_clk_t Root clock. Values: enumerator SOC_ROOT_CLK_INT_RC_FAST Internal 8MHz RC oscillator enumerator SOC_ROOT_CLK_INT_RC_FAST Internal 8MHz RC oscillator enumerator SOC_ROOT_CLK_INT_RC_SLOW Internal 150kHz RC oscillator enumerator SOC_ROOT_CLK_INT_RC_SLOW Internal 150kHz RC oscillator enumerator SOC_ROOT_CLK_EXT_XTAL External 2~40MHz crystal enumerator SOC_ROOT_CLK_EXT_XTAL External 2~40MHz crystal enumerator SOC_ROOT_CLK_EXT_XTAL32K External 32kHz crystal/clock signal enumerator SOC_ROOT_CLK_EXT_XTAL32K External 32kHz crystal/clock signal enumerator SOC_ROOT_CLK_INT_RC_FAST enum soc_cpu_clk_src_t CPU_CLK mux inputs, which are the supported clock sources for the CPU_CLK. Note Enum values are matched with the register field values on purpose Values: enumerator SOC_CPU_CLK_SRC_XTAL Select XTAL_CLK as CPU_CLK source enumerator SOC_CPU_CLK_SRC_XTAL Select XTAL_CLK as CPU_CLK source enumerator SOC_CPU_CLK_SRC_PLL Select PLL_CLK as CPU_CLK source (PLL_CLK is the output of 40MHz crystal oscillator frequency multiplier, can be 480MHz or 320MHz) enumerator SOC_CPU_CLK_SRC_PLL Select PLL_CLK as CPU_CLK source (PLL_CLK is the output of 40MHz crystal oscillator frequency multiplier, can be 480MHz or 320MHz) enumerator SOC_CPU_CLK_SRC_RC_FAST Select RC_FAST_CLK as CPU_CLK source enumerator SOC_CPU_CLK_SRC_RC_FAST Select RC_FAST_CLK as CPU_CLK source enumerator SOC_CPU_CLK_SRC_APLL Select APLL_CLK as CPU_CLK source enumerator SOC_CPU_CLK_SRC_APLL Select APLL_CLK as CPU_CLK source enumerator SOC_CPU_CLK_SRC_INVALID Invalid CPU_CLK source enumerator SOC_CPU_CLK_SRC_INVALID Invalid CPU_CLK source enumerator SOC_CPU_CLK_SRC_XTAL enum soc_rtc_slow_clk_src_t RTC_SLOW_CLK mux inputs, which are the supported clock sources for the RTC_SLOW_CLK. Note Enum values are matched with the register field values on purpose Values: enumerator SOC_RTC_SLOW_CLK_SRC_RC_SLOW Select RC_SLOW_CLK as RTC_SLOW_CLK source enumerator SOC_RTC_SLOW_CLK_SRC_RC_SLOW Select RC_SLOW_CLK as RTC_SLOW_CLK source enumerator SOC_RTC_SLOW_CLK_SRC_XTAL32K Select XTAL32K_CLK as RTC_SLOW_CLK source enumerator SOC_RTC_SLOW_CLK_SRC_XTAL32K Select XTAL32K_CLK as RTC_SLOW_CLK source enumerator SOC_RTC_SLOW_CLK_SRC_RC_FAST_D256 Select RC_FAST_D256_CLK (referred as FOSC_DIV or 8m_d256/8md256 in TRM and reg. description) as RTC_SLOW_CLK source enumerator SOC_RTC_SLOW_CLK_SRC_RC_FAST_D256 Select RC_FAST_D256_CLK (referred as FOSC_DIV or 8m_d256/8md256 in TRM and reg. description) as RTC_SLOW_CLK source enumerator SOC_RTC_SLOW_CLK_SRC_INVALID Invalid RTC_SLOW_CLK source enumerator SOC_RTC_SLOW_CLK_SRC_INVALID Invalid RTC_SLOW_CLK source enumerator SOC_RTC_SLOW_CLK_SRC_RC_SLOW enum soc_rtc_fast_clk_src_t RTC_FAST_CLK mux inputs, which are the supported clock sources for the RTC_FAST_CLK. Note Enum values are matched with the register field values on purpose Values: enumerator SOC_RTC_FAST_CLK_SRC_XTAL_D4 Select XTAL_D4_CLK (may referred as XTAL_CLK_DIV_4) as RTC_FAST_CLK source enumerator SOC_RTC_FAST_CLK_SRC_XTAL_D4 Select XTAL_D4_CLK (may referred as XTAL_CLK_DIV_4) as RTC_FAST_CLK source enumerator SOC_RTC_FAST_CLK_SRC_XTAL_DIV Alias name for SOC_RTC_FAST_CLK_SRC_XTAL_D4 enumerator SOC_RTC_FAST_CLK_SRC_XTAL_DIV Alias name for SOC_RTC_FAST_CLK_SRC_XTAL_D4 enumerator SOC_RTC_FAST_CLK_SRC_RC_FAST Select RC_FAST_CLK as RTC_FAST_CLK source enumerator SOC_RTC_FAST_CLK_SRC_RC_FAST Select RC_FAST_CLK as RTC_FAST_CLK source enumerator SOC_RTC_FAST_CLK_SRC_INVALID Invalid RTC_FAST_CLK source enumerator SOC_RTC_FAST_CLK_SRC_INVALID Invalid RTC_FAST_CLK source enumerator SOC_RTC_FAST_CLK_SRC_XTAL_D4 enum soc_module_clk_t Supported clock sources for modules (CPU, peripherals, RTC, etc.) Note enum starts from 1, to save 0 for special purpose Values: enumerator SOC_MOD_CLK_CPU CPU_CLK can be sourced from XTAL, PLL, RC_FAST, or APLL by configuring soc_cpu_clk_src_t enumerator SOC_MOD_CLK_CPU CPU_CLK can be sourced from XTAL, PLL, RC_FAST, or APLL by configuring soc_cpu_clk_src_t enumerator SOC_MOD_CLK_RTC_FAST RTC_FAST_CLK can be sourced from XTAL_D4 or RC_FAST by configuring soc_rtc_fast_clk_src_t enumerator SOC_MOD_CLK_RTC_FAST RTC_FAST_CLK can be sourced from XTAL_D4 or RC_FAST by configuring soc_rtc_fast_clk_src_t enumerator SOC_MOD_CLK_RTC_SLOW RTC_SLOW_CLK can be sourced from RC_SLOW, XTAL32K, or RC_FAST_D256 by configuring soc_rtc_slow_clk_src_t enumerator SOC_MOD_CLK_RTC_SLOW RTC_SLOW_CLK can be sourced from RC_SLOW, XTAL32K, or RC_FAST_D256 by configuring soc_rtc_slow_clk_src_t enumerator SOC_MOD_CLK_APB APB_CLK is highly dependent on the CPU_CLK source enumerator SOC_MOD_CLK_APB APB_CLK is highly dependent on the CPU_CLK source enumerator SOC_MOD_CLK_PLL_D2 PLL_D2_CLK is derived from PLL, it has a fixed divider of 2 enumerator SOC_MOD_CLK_PLL_D2 PLL_D2_CLK is derived from PLL, it has a fixed divider of 2 enumerator SOC_MOD_CLK_PLL_F160M PLL_F160M_CLK is derived from PLL, and has a fixed frequency of 160MHz enumerator SOC_MOD_CLK_PLL_F160M PLL_F160M_CLK is derived from PLL, and has a fixed frequency of 160MHz enumerator SOC_MOD_CLK_XTAL32K XTAL32K_CLK comes from the external 32kHz crystal, passing a clock gating to the peripherals enumerator SOC_MOD_CLK_XTAL32K XTAL32K_CLK comes from the external 32kHz crystal, passing a clock gating to the peripherals enumerator SOC_MOD_CLK_RC_FAST RC_FAST_CLK comes from the internal 8MHz rc oscillator, passing a clock gating to the peripherals enumerator SOC_MOD_CLK_RC_FAST RC_FAST_CLK comes from the internal 8MHz rc oscillator, passing a clock gating to the peripherals enumerator SOC_MOD_CLK_RC_FAST_D256 RC_FAST_D256_CLK comes from the internal 8MHz rc oscillator, divided by 256, and passing a clock gating to the peripherals enumerator SOC_MOD_CLK_RC_FAST_D256 RC_FAST_D256_CLK comes from the internal 8MHz rc oscillator, divided by 256, and passing a clock gating to the peripherals enumerator SOC_MOD_CLK_XTAL XTAL_CLK comes from the external crystal (2~40MHz) enumerator SOC_MOD_CLK_XTAL XTAL_CLK comes from the external crystal (2~40MHz) enumerator SOC_MOD_CLK_REF_TICK REF_TICK is derived from APB, it has a fixed frequency of 1MHz even when APB frequency changes enumerator SOC_MOD_CLK_REF_TICK REF_TICK is derived from APB, it has a fixed frequency of 1MHz even when APB frequency changes enumerator SOC_MOD_CLK_APLL APLL is sourced from PLL, and its frequency is configurable through APLL configuration registers enumerator SOC_MOD_CLK_APLL APLL is sourced from PLL, and its frequency is configurable through APLL configuration registers enumerator SOC_MOD_CLK_INVALID Indication of the end of the available module clock sources enumerator SOC_MOD_CLK_INVALID Indication of the end of the available module clock sources enumerator SOC_MOD_CLK_CPU enum soc_periph_systimer_clk_src_t Type of SYSTIMER clock source. Values: enumerator SYSTIMER_CLK_SRC_XTAL SYSTIMER source clock is XTAL enumerator SYSTIMER_CLK_SRC_XTAL SYSTIMER source clock is XTAL enumerator SYSTIMER_CLK_SRC_DEFAULT SYSTIMER source clock default choice is XTAL enumerator SYSTIMER_CLK_SRC_DEFAULT SYSTIMER source clock default choice is XTAL enumerator SYSTIMER_CLK_SRC_XTAL enum soc_periph_gptimer_clk_src_t Type of GPTimer clock source. Values: enumerator GPTIMER_CLK_SRC_APB Select APB as the source clock enumerator GPTIMER_CLK_SRC_APB Select APB as the source clock enumerator GPTIMER_CLK_SRC_DEFAULT Select APB as the default choice enumerator GPTIMER_CLK_SRC_DEFAULT Select APB as the default choice enumerator GPTIMER_CLK_SRC_APB enum soc_periph_tg_clk_src_legacy_t Type of Timer Group clock source, reserved for the legacy timer group driver. Values: enumerator TIMER_SRC_CLK_APB Timer group source clock is APB enumerator TIMER_SRC_CLK_APB Timer group source clock is APB enumerator TIMER_SRC_CLK_DEFAULT Timer group source clock default choice is APB enumerator TIMER_SRC_CLK_DEFAULT Timer group source clock default choice is APB enumerator TIMER_SRC_CLK_APB enum soc_periph_lcd_clk_src_t Type of LCD clock source. Values: enumerator LCD_CLK_SRC_PLL160M Select PLL_160M as the source clock enumerator LCD_CLK_SRC_PLL160M Select PLL_160M as the source clock enumerator LCD_CLK_SRC_DEFAULT Select PLL_160M as the default choice enumerator LCD_CLK_SRC_DEFAULT Select PLL_160M as the default choice enumerator LCD_CLK_SRC_PLL160M enum soc_periph_rmt_clk_src_t Type of RMT clock source. Values: enumerator RMT_CLK_SRC_APB Select APB as the source clock enumerator RMT_CLK_SRC_APB Select APB as the source clock enumerator RMT_CLK_SRC_REF_TICK Select REF_TICK as the source clock enumerator RMT_CLK_SRC_REF_TICK Select REF_TICK as the source clock enumerator RMT_CLK_SRC_DEFAULT Select APB as the default choice enumerator RMT_CLK_SRC_DEFAULT Select APB as the default choice enumerator RMT_CLK_SRC_APB enum soc_periph_rmt_clk_src_legacy_t Type of RMT clock source, reserved for the legacy RMT driver. Values: enumerator RMT_BASECLK_APB RMT source clock is APB CLK enumerator RMT_BASECLK_APB RMT source clock is APB CLK enumerator RMT_BASECLK_REF RMT source clock is REF_TICK enumerator RMT_BASECLK_REF RMT source clock is REF_TICK enumerator RMT_BASECLK_DEFAULT RMT source clock default choice is APB enumerator RMT_BASECLK_DEFAULT RMT source clock default choice is APB enumerator RMT_BASECLK_APB enum soc_periph_uart_clk_src_legacy_t Type of UART clock source, reserved for the legacy UART driver. Values: enumerator UART_SCLK_APB UART source clock is APB CLK enumerator UART_SCLK_APB UART source clock is APB CLK enumerator UART_SCLK_REF_TICK UART source clock is REF_TICK enumerator UART_SCLK_REF_TICK UART source clock is REF_TICK enumerator UART_SCLK_DEFAULT UART source clock default choice is APB enumerator UART_SCLK_DEFAULT UART source clock default choice is APB enumerator UART_SCLK_APB enum soc_periph_mcpwm_timer_clk_src_t Type of MCPWM timer clock source. Values: enumerator MCPWM_TIMER_CLK_SRC_PLL160M Select PLL_F160M as the source clock enumerator MCPWM_TIMER_CLK_SRC_PLL160M Select PLL_F160M as the source clock enumerator MCPWM_TIMER_CLK_SRC_DEFAULT Select PLL_F160M as the default clock choice enumerator MCPWM_TIMER_CLK_SRC_DEFAULT Select PLL_F160M as the default clock choice enumerator MCPWM_TIMER_CLK_SRC_PLL160M enum soc_periph_mcpwm_capture_clk_src_t Type of MCPWM capture clock source. Values: enumerator MCPWM_CAPTURE_CLK_SRC_APB Select APB as the source clock enumerator MCPWM_CAPTURE_CLK_SRC_APB Select APB as the source clock enumerator MCPWM_CAPTURE_CLK_SRC_DEFAULT Select APB as the default clock choice enumerator MCPWM_CAPTURE_CLK_SRC_DEFAULT Select APB as the default clock choice enumerator MCPWM_CAPTURE_CLK_SRC_APB enum soc_periph_mcpwm_carrier_clk_src_t Type of MCPWM carrier clock source. Values: enumerator MCPWM_CARRIER_CLK_SRC_PLL160M Select PLL_F160M as the source clock enumerator MCPWM_CARRIER_CLK_SRC_PLL160M Select PLL_F160M as the source clock enumerator MCPWM_CARRIER_CLK_SRC_DEFAULT Select PLL_F160M as the default clock choice enumerator MCPWM_CARRIER_CLK_SRC_DEFAULT Select PLL_F160M as the default clock choice enumerator MCPWM_CARRIER_CLK_SRC_PLL160M enum soc_periph_i2s_clk_src_t I2S clock source enum. Values: enumerator I2S_CLK_SRC_DEFAULT Select PLL_F160M as the default source clock enumerator I2S_CLK_SRC_DEFAULT Select PLL_F160M as the default source clock enumerator I2S_CLK_SRC_PLL_160M Select PLL_F160M as the source clock enumerator I2S_CLK_SRC_PLL_160M Select PLL_F160M as the source clock enumerator I2S_CLK_SRC_APLL Select APLL as the source clock enumerator I2S_CLK_SRC_APLL Select APLL as the source clock enumerator I2S_CLK_SRC_DEFAULT enum soc_periph_i2c_clk_src_t Type of I2C clock source. Values: enumerator I2C_CLK_SRC_APB enumerator I2C_CLK_SRC_APB enumerator I2C_CLK_SRC_DEFAULT enumerator I2C_CLK_SRC_DEFAULT enumerator I2C_CLK_SRC_APB enum soc_periph_spi_clk_src_t Type of SPI clock source. Values: enumerator SPI_CLK_SRC_DEFAULT Select APB as SPI source clock enumerator SPI_CLK_SRC_DEFAULT Select APB as SPI source clock enumerator SPI_CLK_SRC_APB Select APB as SPI source clock enumerator SPI_CLK_SRC_APB Select APB as SPI source clock enumerator SPI_CLK_SRC_DEFAULT enum soc_periph_sdm_clk_src_t Sigma Delta Modulator clock source. Values: enumerator SDM_CLK_SRC_APB Select APB as the source clock enumerator SDM_CLK_SRC_APB Select APB as the source clock enumerator SDM_CLK_SRC_DEFAULT Select APB as the default clock choice enumerator SDM_CLK_SRC_DEFAULT Select APB as the default clock choice enumerator SDM_CLK_SRC_APB enum soc_periph_dac_digi_clk_src_t DAC digital controller clock source. Values: enumerator DAC_DIGI_CLK_SRC_PLLD2 Select PLL_D2 as the source clock enumerator DAC_DIGI_CLK_SRC_PLLD2 Select PLL_D2 as the source clock enumerator DAC_DIGI_CLK_SRC_APLL Select APLL as the source clock enumerator DAC_DIGI_CLK_SRC_APLL Select APLL as the source clock enumerator DAC_DIGI_CLK_SRC_DEFAULT Select PLL_D2 as the default source clock enumerator DAC_DIGI_CLK_SRC_DEFAULT Select PLL_D2 as the default source clock enumerator DAC_DIGI_CLK_SRC_PLLD2 enum soc_periph_dac_cosine_clk_src_t DAC cosine wave generator clock source. Values: enumerator DAC_COSINE_CLK_SRC_RTC_FAST Select RTC FAST as the source clock enumerator DAC_COSINE_CLK_SRC_RTC_FAST Select RTC FAST as the source clock enumerator DAC_COSINE_CLK_SRC_DEFAULT Select RTC FAST as the default source clock enumerator DAC_COSINE_CLK_SRC_DEFAULT Select RTC FAST as the default source clock enumerator DAC_COSINE_CLK_SRC_RTC_FAST enum soc_periph_twai_clk_src_t TWAI clock source. Values: enumerator TWAI_CLK_SRC_APB Select APB as the source clock enumerator TWAI_CLK_SRC_APB Select APB as the source clock enumerator TWAI_CLK_SRC_DEFAULT Select APB as the default clock choice enumerator TWAI_CLK_SRC_DEFAULT Select APB as the default clock choice enumerator TWAI_CLK_SRC_APB enum soc_periph_adc_digi_clk_src_t ADC digital controller clock source. Note ADC DMA mode is clocked from I2S on ESP32, using ADC_DIGI_ here for compatibility Its clock source is same as I2S Values: enumerator ADC_DIGI_CLK_SRC_PLL_F160M Select F160M as the source clock enumerator ADC_DIGI_CLK_SRC_PLL_F160M Select F160M as the source clock enumerator ADC_DIGI_CLK_SRC_APLL Select APLL as the source clock enumerator ADC_DIGI_CLK_SRC_APLL Select APLL as the source clock enumerator ADC_DIGI_CLK_SRC_DEFAULT Select F160M as the default clock choice enumerator ADC_DIGI_CLK_SRC_DEFAULT Select F160M as the default clock choice enumerator ADC_DIGI_CLK_SRC_PLL_F160M enum soc_periph_adc_rtc_clk_src_t ADC RTC controller clock source. Values: enumerator ADC_RTC_CLK_SRC_RC_FAST Select RC_FAST as the source clock enumerator ADC_RTC_CLK_SRC_RC_FAST Select RC_FAST as the source clock enumerator ADC_RTC_CLK_SRC_DEFAULT Select RC_FAST as the default clock choice enumerator ADC_RTC_CLK_SRC_DEFAULT Select RC_FAST as the default clock choice enumerator ADC_RTC_CLK_SRC_RC_FAST enum soc_periph_mwdt_clk_src_t MWDT clock source. Values: enumerator MWDT_CLK_SRC_APB Select APB as the source clock enumerator MWDT_CLK_SRC_APB Select APB as the source clock enumerator MWDT_CLK_SRC_DEFAULT Select APB as the default clock choice enumerator MWDT_CLK_SRC_DEFAULT Select APB as the default clock choice enumerator MWDT_CLK_SRC_APB enum soc_periph_ledc_clk_src_legacy_t Type of LEDC clock source, reserved for the legacy LEDC driver. Values: enumerator LEDC_AUTO_CLK LEDC source clock will be automatically selected based on the giving resolution and duty parameter when init the timer enumerator LEDC_AUTO_CLK LEDC source clock will be automatically selected based on the giving resolution and duty parameter when init the timer enumerator LEDC_USE_APB_CLK Select APB as the source clock enumerator LEDC_USE_APB_CLK Select APB as the source clock enumerator LEDC_USE_RC_FAST_CLK Select RC_FAST as the source clock enumerator LEDC_USE_RC_FAST_CLK Select RC_FAST as the source clock enumerator LEDC_USE_REF_TICK Select REF_TICK as the source clock enumerator LEDC_USE_REF_TICK Select REF_TICK as the source clock enumerator LEDC_USE_RTC8M_CLK Alias of 'LEDC_USE_RC_FAST_CLK' enumerator LEDC_USE_RTC8M_CLK Alias of 'LEDC_USE_RC_FAST_CLK' enumerator LEDC_AUTO_CLK enum soc_periph_sdmmc_clk_src_t Type of SDMMC clock source. Values: enumerator SDMMC_CLK_SRC_DEFAULT Select PLL_160M as the default choice enumerator SDMMC_CLK_SRC_DEFAULT Select PLL_160M as the default choice enumerator SDMMC_CLK_SRC_PLL160M Select PLL_160M as the source clock enumerator SDMMC_CLK_SRC_PLL160M Select PLL_160M as the source clock enumerator SDMMC_CLK_SRC_DEFAULT enum soc_clkout_sig_id_t Values: enumerator CLKOUT_SIG_I2S0 I2S0 clock, depends on the i2s driver configuration enumerator CLKOUT_SIG_I2S0 I2S0 clock, depends on the i2s driver configuration enumerator CLKOUT_SIG_PLL PLL_CLK is the output of crystal oscillator frequency multiplier enumerator CLKOUT_SIG_PLL PLL_CLK is the output of crystal oscillator frequency multiplier enumerator CLKOUT_SIG_RC_SLOW RC slow clock, depends on the RTC_CLK_SRC configuration enumerator CLKOUT_SIG_RC_SLOW RC slow clock, depends on the RTC_CLK_SRC configuration enumerator CLKOUT_SIG_XTAL Main crystal oscillator clock enumerator CLKOUT_SIG_XTAL Main crystal oscillator clock enumerator CLKOUT_SIG_APLL Divided by PLL, frequency is configurable enumerator CLKOUT_SIG_APLL Divided by PLL, frequency is configurable enumerator CLKOUT_SIG_REF_TICK Divided by APB clock, usually be 1MHz enumerator CLKOUT_SIG_REF_TICK Divided by APB clock, usually be 1MHz enumerator CLKOUT_SIG_PLL_F80M From PLL, usually be 80MHz enumerator CLKOUT_SIG_PLL_F80M From PLL, usually be 80MHz enumerator CLKOUT_SIG_RC_FAST RC fast clock, about 8MHz enumerator CLKOUT_SIG_RC_FAST RC fast clock, about 8MHz enumerator CLKOUT_SIG_I2S1 I2S1 clock, depends on the i2s driver configuration enumerator CLKOUT_SIG_I2S1 I2S1 clock, depends on the i2s driver configuration enumerator CLKOUT_SIG_INVALID enumerator CLKOUT_SIG_INVALID enumerator CLKOUT_SIG_I2S0 Header File This header file can be included with: #include "esp_clk_tree.h" Functions esp_err_t esp_clk_tree_src_get_freq_hz(soc_module_clk_t clk_src, esp_clk_tree_src_freq_precision_t precision, uint32_t *freq_value) Get frequency of module clock source. Parameters clk_src -- [in] Clock source available to modules, in soc_module_clk_t precision -- [in] Degree of precision, one of esp_clk_tree_src_freq_precision_t values This arg only applies to the clock sources that their frequencies can vary: SOC_MOD_CLK_RTC_FAST, SOC_MOD_CLK_RTC_SLOW, SOC_MOD_CLK_RC_FAST, SOC_MOD_CLK_RC_FAST_D256, SOC_MOD_CLK_XTAL32K For other clock sources, this field is ignored. freq_value -- [out] Frequency of the clock source, in Hz clk_src -- [in] Clock source available to modules, in soc_module_clk_t precision -- [in] Degree of precision, one of esp_clk_tree_src_freq_precision_t values This arg only applies to the clock sources that their frequencies can vary: SOC_MOD_CLK_RTC_FAST, SOC_MOD_CLK_RTC_SLOW, SOC_MOD_CLK_RC_FAST, SOC_MOD_CLK_RC_FAST_D256, SOC_MOD_CLK_XTAL32K For other clock sources, this field is ignored. freq_value -- [out] Frequency of the clock source, in Hz clk_src -- [in] Clock source available to modules, in soc_module_clk_t Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Calibration failed ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Calibration failed ESP_OK Success Parameters clk_src -- [in] Clock source available to modules, in soc_module_clk_t precision -- [in] Degree of precision, one of esp_clk_tree_src_freq_precision_t values This arg only applies to the clock sources that their frequencies can vary: SOC_MOD_CLK_RTC_FAST, SOC_MOD_CLK_RTC_SLOW, SOC_MOD_CLK_RC_FAST, SOC_MOD_CLK_RC_FAST_D256, SOC_MOD_CLK_XTAL32K For other clock sources, this field is ignored. freq_value -- [out] Frequency of the clock source, in Hz Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Calibration failed Enumerations enum esp_clk_tree_src_freq_precision_t Degree of precision of frequency value to be returned by esp_clk_tree_src_get_freq_hz() Values: enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_CACHED enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_CACHED enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_APPROX enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_APPROX enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_EXACT enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_EXACT enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_INVALID enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_INVALID enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_CACHED
Clock Tree The clock subsystem of ESP32 is used to source and distribute system/module clocks from a range of root clocks. The clock tree driver maintains the basic functionality of the system clock and the intricate relationship among module clocks. This document starts with the introduction to root and module clocks. Then it covers the clock tree APIs that can be called to monitor the status of the module clocks at runtime. Introduction This section lists definitions of ESP32's supported root clocks and module clocks. These definitions are commonly used in the driver configuration, to help select a proper source clock for the peripheral. Root Clocks Root clocks generate reliable clock signals. These clock signals then pass through various gates, muxes, dividers, or multipliers to become the clock sources for every functional module: the CPU core(s), Wi-Fi, Bluetooth, the RTC, and the peripherals. ESP32's root clocks are listed in soc_root_clk_t: - Internal 8 MHz RC Oscillator (RC_FAST) This RC oscillator generates a about 8.5 MHz clock signal output as the RC_FAST_CLK. The about 8.5 MHz signal output is also passed into a configurable divider, which by default divides the input clock frequency by 256, to generate a RC_FAST_D256_CLK. The exact frequency of RC_FAST_CLKcan be computed in runtime through calibration on the RC_FAST_D256_CLK. - External 2 ~ 40 MHz Crystal (XTAL) - Internal 150 kHz RC Oscillator (RC_SLOW) This RC oscillator generates a about 150kHz clock signal output as the RC_SLOW_CLK. The exact frequency of this clock can be computed in runtime through calibration. - External 32 kHz Crystal - optional (XTAL32K) The clock source for this XTAL32K_CLKcan be either a 32 kHz crystal connecting to the 32K_XPand 32K_XNpins or a 32 kHz clock signal generated by an external circuit. The external signal must be connected to the 32K_XNpin. Additionally, a 1 nF capacitor must be placed between the 32K_XPpin and ground. In this case, the 32K_XPpin cannot be used as a GPIO pin. XTAL32K_CLKcan also be calibrated to get its exact frequency. Typically, the frequency of the signal generated from an RC oscillator circuit is less accurate and more sensitive to the environment compared to the signal generated from a crystal. ESP32 provides several clock source options for the RTC_SLOW_CLK, and it is possible to make the choice based on the requirements for system time accuracy and power consumption. For more details, please refer to RTC Timer Clock Sources. Module Clocks ESP32's available module clocks are listed in soc_module_clk_t. Each module clock has a unique ID. You can get more information on each clock by checking the documented enum value. API Usage The clock tree driver provides an all-in-one API to get the frequency of the module clocks, esp_clk_tree_src_get_freq_hz(). This function allows you to obtain the clock frequency at any time by providing the clock name soc_module_clk_t and specifying the desired precision level for the returned frequency value esp_clk_tree_src_freq_precision_t. API Reference Header File This header file can be included with: #include "soc/clk_tree_defs.h" Macros - SOC_CLK_RC_FAST_FREQ_APPROX Approximate RC_FAST_CLK frequency in Hz - SOC_CLK_RC_SLOW_FREQ_APPROX Approximate RC_SLOW_CLK frequency in Hz - SOC_CLK_RC_FAST_D256_FREQ_APPROX Approximate RC_FAST_D256_CLK frequency in Hz - SOC_CLK_XTAL32K_FREQ_APPROX Approximate XTAL32K_CLK frequency in Hz - SOC_GPTIMER_CLKS Array initializer for all supported clock sources of GPTimer. The following code can be used to iterate all possible clocks: soc_periph_gptimer_clk_src_t gptimer_clks[] = (soc_periph_gptimer_clk_src_t)SOC_GPTIMER_CLKS; for (size_t i = 0; i< sizeof(gptimer_clks) / sizeof(gptimer_clks[0]); i++) { soc_periph_gptimer_clk_src_t clk = gptimer_clks[i]; // Test GPTimer with the clock `clk` } - SOC_LCD_CLKS Array initializer for all supported clock sources of LCD. - SOC_RMT_CLKS Array initializer for all supported clock sources of RMT. - SOC_MCPWM_TIMER_CLKS Array initializer for all supported clock sources of MCPWM Timer. - SOC_MCPWM_CAPTURE_CLKS Array initializer for all supported clock sources of MCPWM Capture Timer. - SOC_MCPWM_CARRIER_CLKS Array initializer for all supported clock sources of MCPWM Carrier. - SOC_I2S_CLKS Array initializer for all supported clock sources of I2S. - SOC_I2C_CLKS Array initializer for all supported clock sources of I2C. - SOC_SPI_CLKS Array initializer for all supported clock sources of SPI. - SOC_SDM_CLKS Array initializer for all supported clock sources of SDM. - SOC_DAC_DIGI_CLKS Array initializer for all supported clock sources of DAC digital controller. - SOC_DAC_COSINE_CLKS Array initializer for all supported clock sources of DAC cosine wave generator. - SOC_TWAI_CLKS Array initializer for all supported clock sources of TWAI. - SOC_ADC_DIGI_CLKS Array initializer for all supported clock sources of ADC digital controller. - SOC_ADC_RTC_CLKS Array initializer for all supported clock sources of ADC RTC controller. - SOC_MWDT_CLKS Array initializer for all supported clock sources of MWDT. - SOC_LEDC_CLKS Array initializer for all supported clock sources of LEDC. - SOC_SDMMC_CLKS Array initializer for all supported clock sources of SDMMC. Enumerations - enum soc_root_clk_t Root clock. Values: - enumerator SOC_ROOT_CLK_INT_RC_FAST Internal 8MHz RC oscillator - enumerator SOC_ROOT_CLK_INT_RC_SLOW Internal 150kHz RC oscillator - enumerator SOC_ROOT_CLK_EXT_XTAL External 2~40MHz crystal - enumerator SOC_ROOT_CLK_EXT_XTAL32K External 32kHz crystal/clock signal - enumerator SOC_ROOT_CLK_INT_RC_FAST - enum soc_cpu_clk_src_t CPU_CLK mux inputs, which are the supported clock sources for the CPU_CLK. Note Enum values are matched with the register field values on purpose Values: - enumerator SOC_CPU_CLK_SRC_XTAL Select XTAL_CLK as CPU_CLK source - enumerator SOC_CPU_CLK_SRC_PLL Select PLL_CLK as CPU_CLK source (PLL_CLK is the output of 40MHz crystal oscillator frequency multiplier, can be 480MHz or 320MHz) - enumerator SOC_CPU_CLK_SRC_RC_FAST Select RC_FAST_CLK as CPU_CLK source - enumerator SOC_CPU_CLK_SRC_APLL Select APLL_CLK as CPU_CLK source - enumerator SOC_CPU_CLK_SRC_INVALID Invalid CPU_CLK source - enumerator SOC_CPU_CLK_SRC_XTAL - enum soc_rtc_slow_clk_src_t RTC_SLOW_CLK mux inputs, which are the supported clock sources for the RTC_SLOW_CLK. Note Enum values are matched with the register field values on purpose Values: - enumerator SOC_RTC_SLOW_CLK_SRC_RC_SLOW Select RC_SLOW_CLK as RTC_SLOW_CLK source - enumerator SOC_RTC_SLOW_CLK_SRC_XTAL32K Select XTAL32K_CLK as RTC_SLOW_CLK source - enumerator SOC_RTC_SLOW_CLK_SRC_RC_FAST_D256 Select RC_FAST_D256_CLK (referred as FOSC_DIV or 8m_d256/8md256 in TRM and reg. description) as RTC_SLOW_CLK source - enumerator SOC_RTC_SLOW_CLK_SRC_INVALID Invalid RTC_SLOW_CLK source - enumerator SOC_RTC_SLOW_CLK_SRC_RC_SLOW - enum soc_rtc_fast_clk_src_t RTC_FAST_CLK mux inputs, which are the supported clock sources for the RTC_FAST_CLK. Note Enum values are matched with the register field values on purpose Values: - enumerator SOC_RTC_FAST_CLK_SRC_XTAL_D4 Select XTAL_D4_CLK (may referred as XTAL_CLK_DIV_4) as RTC_FAST_CLK source - enumerator SOC_RTC_FAST_CLK_SRC_XTAL_DIV Alias name for SOC_RTC_FAST_CLK_SRC_XTAL_D4 - enumerator SOC_RTC_FAST_CLK_SRC_RC_FAST Select RC_FAST_CLK as RTC_FAST_CLK source - enumerator SOC_RTC_FAST_CLK_SRC_INVALID Invalid RTC_FAST_CLK source - enumerator SOC_RTC_FAST_CLK_SRC_XTAL_D4 - enum soc_module_clk_t Supported clock sources for modules (CPU, peripherals, RTC, etc.) Note enum starts from 1, to save 0 for special purpose Values: - enumerator SOC_MOD_CLK_CPU CPU_CLK can be sourced from XTAL, PLL, RC_FAST, or APLL by configuring soc_cpu_clk_src_t - enumerator SOC_MOD_CLK_RTC_FAST RTC_FAST_CLK can be sourced from XTAL_D4 or RC_FAST by configuring soc_rtc_fast_clk_src_t - enumerator SOC_MOD_CLK_RTC_SLOW RTC_SLOW_CLK can be sourced from RC_SLOW, XTAL32K, or RC_FAST_D256 by configuring soc_rtc_slow_clk_src_t - enumerator SOC_MOD_CLK_APB APB_CLK is highly dependent on the CPU_CLK source - enumerator SOC_MOD_CLK_PLL_D2 PLL_D2_CLK is derived from PLL, it has a fixed divider of 2 - enumerator SOC_MOD_CLK_PLL_F160M PLL_F160M_CLK is derived from PLL, and has a fixed frequency of 160MHz - enumerator SOC_MOD_CLK_XTAL32K XTAL32K_CLK comes from the external 32kHz crystal, passing a clock gating to the peripherals - enumerator SOC_MOD_CLK_RC_FAST RC_FAST_CLK comes from the internal 8MHz rc oscillator, passing a clock gating to the peripherals - enumerator SOC_MOD_CLK_RC_FAST_D256 RC_FAST_D256_CLK comes from the internal 8MHz rc oscillator, divided by 256, and passing a clock gating to the peripherals - enumerator SOC_MOD_CLK_XTAL XTAL_CLK comes from the external crystal (2~40MHz) - enumerator SOC_MOD_CLK_REF_TICK REF_TICK is derived from APB, it has a fixed frequency of 1MHz even when APB frequency changes - enumerator SOC_MOD_CLK_APLL APLL is sourced from PLL, and its frequency is configurable through APLL configuration registers - enumerator SOC_MOD_CLK_INVALID Indication of the end of the available module clock sources - enumerator SOC_MOD_CLK_CPU - enum soc_periph_systimer_clk_src_t Type of SYSTIMER clock source. Values: - enumerator SYSTIMER_CLK_SRC_XTAL SYSTIMER source clock is XTAL - enumerator SYSTIMER_CLK_SRC_DEFAULT SYSTIMER source clock default choice is XTAL - enumerator SYSTIMER_CLK_SRC_XTAL - enum soc_periph_gptimer_clk_src_t Type of GPTimer clock source. Values: - enumerator GPTIMER_CLK_SRC_APB Select APB as the source clock - enumerator GPTIMER_CLK_SRC_DEFAULT Select APB as the default choice - enumerator GPTIMER_CLK_SRC_APB - enum soc_periph_tg_clk_src_legacy_t Type of Timer Group clock source, reserved for the legacy timer group driver. Values: - enumerator TIMER_SRC_CLK_APB Timer group source clock is APB - enumerator TIMER_SRC_CLK_DEFAULT Timer group source clock default choice is APB - enumerator TIMER_SRC_CLK_APB - enum soc_periph_lcd_clk_src_t Type of LCD clock source. Values: - enumerator LCD_CLK_SRC_PLL160M Select PLL_160M as the source clock - enumerator LCD_CLK_SRC_DEFAULT Select PLL_160M as the default choice - enumerator LCD_CLK_SRC_PLL160M - enum soc_periph_rmt_clk_src_t Type of RMT clock source. Values: - enumerator RMT_CLK_SRC_APB Select APB as the source clock - enumerator RMT_CLK_SRC_REF_TICK Select REF_TICK as the source clock - enumerator RMT_CLK_SRC_DEFAULT Select APB as the default choice - enumerator RMT_CLK_SRC_APB - enum soc_periph_rmt_clk_src_legacy_t Type of RMT clock source, reserved for the legacy RMT driver. Values: - enumerator RMT_BASECLK_APB RMT source clock is APB CLK - enumerator RMT_BASECLK_REF RMT source clock is REF_TICK - enumerator RMT_BASECLK_DEFAULT RMT source clock default choice is APB - enumerator RMT_BASECLK_APB - enum soc_periph_uart_clk_src_legacy_t Type of UART clock source, reserved for the legacy UART driver. Values: - enumerator UART_SCLK_APB UART source clock is APB CLK - enumerator UART_SCLK_REF_TICK UART source clock is REF_TICK - enumerator UART_SCLK_DEFAULT UART source clock default choice is APB - enumerator UART_SCLK_APB - enum soc_periph_mcpwm_timer_clk_src_t Type of MCPWM timer clock source. Values: - enumerator MCPWM_TIMER_CLK_SRC_PLL160M Select PLL_F160M as the source clock - enumerator MCPWM_TIMER_CLK_SRC_DEFAULT Select PLL_F160M as the default clock choice - enumerator MCPWM_TIMER_CLK_SRC_PLL160M - enum soc_periph_mcpwm_capture_clk_src_t Type of MCPWM capture clock source. Values: - enumerator MCPWM_CAPTURE_CLK_SRC_APB Select APB as the source clock - enumerator MCPWM_CAPTURE_CLK_SRC_DEFAULT Select APB as the default clock choice - enumerator MCPWM_CAPTURE_CLK_SRC_APB - enum soc_periph_mcpwm_carrier_clk_src_t Type of MCPWM carrier clock source. Values: - enumerator MCPWM_CARRIER_CLK_SRC_PLL160M Select PLL_F160M as the source clock - enumerator MCPWM_CARRIER_CLK_SRC_DEFAULT Select PLL_F160M as the default clock choice - enumerator MCPWM_CARRIER_CLK_SRC_PLL160M - enum soc_periph_i2s_clk_src_t I2S clock source enum. Values: - enumerator I2S_CLK_SRC_DEFAULT Select PLL_F160M as the default source clock - enumerator I2S_CLK_SRC_PLL_160M Select PLL_F160M as the source clock - enumerator I2S_CLK_SRC_APLL Select APLL as the source clock - enumerator I2S_CLK_SRC_DEFAULT - enum soc_periph_i2c_clk_src_t Type of I2C clock source. Values: - enumerator I2C_CLK_SRC_APB - enumerator I2C_CLK_SRC_DEFAULT - enumerator I2C_CLK_SRC_APB - enum soc_periph_spi_clk_src_t Type of SPI clock source. Values: - enumerator SPI_CLK_SRC_DEFAULT Select APB as SPI source clock - enumerator SPI_CLK_SRC_APB Select APB as SPI source clock - enumerator SPI_CLK_SRC_DEFAULT - enum soc_periph_sdm_clk_src_t Sigma Delta Modulator clock source. Values: - enumerator SDM_CLK_SRC_APB Select APB as the source clock - enumerator SDM_CLK_SRC_DEFAULT Select APB as the default clock choice - enumerator SDM_CLK_SRC_APB - enum soc_periph_dac_digi_clk_src_t DAC digital controller clock source. Values: - enumerator DAC_DIGI_CLK_SRC_PLLD2 Select PLL_D2 as the source clock - enumerator DAC_DIGI_CLK_SRC_APLL Select APLL as the source clock - enumerator DAC_DIGI_CLK_SRC_DEFAULT Select PLL_D2 as the default source clock - enumerator DAC_DIGI_CLK_SRC_PLLD2 - enum soc_periph_dac_cosine_clk_src_t DAC cosine wave generator clock source. Values: - enumerator DAC_COSINE_CLK_SRC_RTC_FAST Select RTC FAST as the source clock - enumerator DAC_COSINE_CLK_SRC_DEFAULT Select RTC FAST as the default source clock - enumerator DAC_COSINE_CLK_SRC_RTC_FAST - enum soc_periph_twai_clk_src_t TWAI clock source. Values: - enumerator TWAI_CLK_SRC_APB Select APB as the source clock - enumerator TWAI_CLK_SRC_DEFAULT Select APB as the default clock choice - enumerator TWAI_CLK_SRC_APB - enum soc_periph_adc_digi_clk_src_t ADC digital controller clock source. Note ADC DMA mode is clocked from I2S on ESP32, using ADC_DIGI_here for compatibility Its clock source is same as I2S Values: - enumerator ADC_DIGI_CLK_SRC_PLL_F160M Select F160M as the source clock - enumerator ADC_DIGI_CLK_SRC_APLL Select APLL as the source clock - enumerator ADC_DIGI_CLK_SRC_DEFAULT Select F160M as the default clock choice - enumerator ADC_DIGI_CLK_SRC_PLL_F160M - enum soc_periph_adc_rtc_clk_src_t ADC RTC controller clock source. Values: - enumerator ADC_RTC_CLK_SRC_RC_FAST Select RC_FAST as the source clock - enumerator ADC_RTC_CLK_SRC_DEFAULT Select RC_FAST as the default clock choice - enumerator ADC_RTC_CLK_SRC_RC_FAST - enum soc_periph_mwdt_clk_src_t MWDT clock source. Values: - enumerator MWDT_CLK_SRC_APB Select APB as the source clock - enumerator MWDT_CLK_SRC_DEFAULT Select APB as the default clock choice - enumerator MWDT_CLK_SRC_APB - enum soc_periph_ledc_clk_src_legacy_t Type of LEDC clock source, reserved for the legacy LEDC driver. Values: - enumerator LEDC_AUTO_CLK LEDC source clock will be automatically selected based on the giving resolution and duty parameter when init the timer - enumerator LEDC_USE_APB_CLK Select APB as the source clock - enumerator LEDC_USE_RC_FAST_CLK Select RC_FAST as the source clock - enumerator LEDC_USE_REF_TICK Select REF_TICK as the source clock - enumerator LEDC_USE_RTC8M_CLK Alias of 'LEDC_USE_RC_FAST_CLK' - enumerator LEDC_AUTO_CLK - enum soc_periph_sdmmc_clk_src_t Type of SDMMC clock source. Values: - enumerator SDMMC_CLK_SRC_DEFAULT Select PLL_160M as the default choice - enumerator SDMMC_CLK_SRC_PLL160M Select PLL_160M as the source clock - enumerator SDMMC_CLK_SRC_DEFAULT - enum soc_clkout_sig_id_t Values: - enumerator CLKOUT_SIG_I2S0 I2S0 clock, depends on the i2s driver configuration - enumerator CLKOUT_SIG_PLL PLL_CLK is the output of crystal oscillator frequency multiplier - enumerator CLKOUT_SIG_RC_SLOW RC slow clock, depends on the RTC_CLK_SRC configuration - enumerator CLKOUT_SIG_XTAL Main crystal oscillator clock - enumerator CLKOUT_SIG_APLL Divided by PLL, frequency is configurable - enumerator CLKOUT_SIG_REF_TICK Divided by APB clock, usually be 1MHz - enumerator CLKOUT_SIG_PLL_F80M From PLL, usually be 80MHz - enumerator CLKOUT_SIG_RC_FAST RC fast clock, about 8MHz - enumerator CLKOUT_SIG_I2S1 I2S1 clock, depends on the i2s driver configuration - enumerator CLKOUT_SIG_INVALID - enumerator CLKOUT_SIG_I2S0 Header File This header file can be included with: #include "esp_clk_tree.h" Functions - esp_err_t esp_clk_tree_src_get_freq_hz(soc_module_clk_t clk_src, esp_clk_tree_src_freq_precision_t precision, uint32_t *freq_value) Get frequency of module clock source. - Parameters clk_src -- [in] Clock source available to modules, in soc_module_clk_t precision -- [in] Degree of precision, one of esp_clk_tree_src_freq_precision_t values This arg only applies to the clock sources that their frequencies can vary: SOC_MOD_CLK_RTC_FAST, SOC_MOD_CLK_RTC_SLOW, SOC_MOD_CLK_RC_FAST, SOC_MOD_CLK_RC_FAST_D256, SOC_MOD_CLK_XTAL32K For other clock sources, this field is ignored. freq_value -- [out] Frequency of the clock source, in Hz - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Calibration failed - Enumerations - enum esp_clk_tree_src_freq_precision_t Degree of precision of frequency value to be returned by esp_clk_tree_src_get_freq_hz() Values: - enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_CACHED - enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_APPROX - enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_EXACT - enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_INVALID - enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_CACHED
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/clk_tree.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Digital To Analog Converter (DAC)
null
espressif.com
2016-01-01
9cda9c1e2654d793
null
null
Digital To Analog Converter (DAC) Overview ESP32 has two 8-bit DAC (digital to analog converter) channels respectively connected to GPIO25 (Channel 1) and GPIO26 (Channel 2). Each DAC channel can convert the digital value 0~255 to the analog voltage 0~Vref (The reference voltage 'Vref' here is input from the pin VDD3P3_RTC, which ideally equals to the power supply VDD). The output voltage can be calculated as the following: out_voltage = Vref * digi_val / 255 The DAC peripheral supports outputting analog signal in the following ways: Outputting a voltage directly. The DAC channel keeps outputting a specified voltage. Outputting continuous analog signal by DMA. The DAC converts the data in a buffer at a specified frequency. Outputting a cosine wave by the cosine wave generator. The DAC channel can output a cosine wave with specified frequency and amplitude. For other analog output options, see Sigma-Delta Modulation and LED Control. Both modules produce high-frequency PWM/PDM output, which can be hardware low-pass filtered in order to generate a lower frequency analog output. DAC File Structure Public headers that need to be included in the DAC application are listed as follows: dac.h : The top header file of the legacy DAC driver, which should be only included in the apps which use the legacy driver API. dac_oneshot.h : The top header file of the new DAC driver, which should be included in the apps which use the new driver API with one-shot mode. dac_cosine.h : The top header file of the new DAC driver, which should be included in the apps which use the new driver API with cosine mode. dac_continuous.h : The top header file of the new DAC driver, which should be included in the apps which use the new driver API with continuous mode. Note The legacy driver cannot coexist with the new driver. Include dac.h to use the legacy driver or dac_oneshot.h , dac_cosine.h , and dac_continuous.h to use the new driver. The legacy driver might be removed in the future. Functional Overview Resources Management The DAC on ESP32 has two channels. The channels have separate software resources and can be managed by dac_oneshot_handle_t , dac_cosine_handle_t , or dac_continuous_handle_t according to the usage. Registering different modes on a same DAC channel is not allowed. Direct Voltage Output (One-shot/Direct Mode) The DAC channels in the group can convert an 8-bit digital value into the analog when dac_oneshot_output_voltage() is called (it can be called in ISR). The analog voltage is kept on the DAC channel until the next conversion starts. To start the voltage conversion, the DAC channels need to be enabled first through registering by dac_oneshot_new_channel() . Continuous Wave Output (Continuous/DMA Mode) DAC channels can convert digital data continuously via the DMA. There are three ways to write the DAC data: Normal writing (synchronous): Data can be transmitted at one time and kept blocked until all the data has been loaded into the DMA buffer, and the voltage is kept as the last conversion value while no more data is inputted. It is usually used to transport a long signal like an audio. To convert data continuously, the continuous channel handle need to be allocated by calling dac_continuous_new_channels() and the DMA conversion should be enabled by calling dac_continuous_enable() . Then data can be written by dac_continuous_write() synchronously. Refer to peripherals/dac/dac_continuous/dac_audio for examples. Cyclical writing: A piece of data can be converted cyclically without blocking, and no more operation is needed after the data are loaded into the DMA buffer. But note that the inputted buffer size is limited by the number of descriptors and the DMA buffer size. It is usually used to transport short signals that need to be repeated, e.g., a sine wave. To achieve cyclical writing, call dac_continuous_write_cyclically() after the DAC continuous mode is enabled. Refer to peripherals/dac/dac_continuous/signal_generator for examples. Asynchronous writing: Data can be transmitted asynchronously based on the event callback. dac_event_callbacks_t::on_convert_done must be registered to use asynchronous mode. Users can get the dac_event_data_t in the callback which contains the DMA buffer address and length, allowing them to load the data into the buffer directly. To use the asynchronous writing, call dac_continuous_register_event_callback() to register the dac_event_callbacks_t::on_convert_done before enabling, and then dac_continuous_start_async_writing() to start the asynchronous writing. Note that once the asynchronous writing is started, the callback function will be triggered continuously. Call dac_continuous_write_asynchronously() to load the data either in a separate task or in the callback directly. Refer to peripherals/dac/dac_continuous/dac_audio for examples. On ESP32, the DAC digital controller can be connected internally to the I2S0 and use its DMA for continuous conversion. Although the DAC only needs 8-bit data for conversion, it has to be the left-shifted 8 bits (i.e., the high 8 bits in a 16-bit slot) to satisfy the I2S communication format. By default, the driver helps to expand the data to 16-bit wide automatically. To expand manually, please disable CONFIG_DAC_DMA_AUTO_16BIT_ALIGN in the menuconfig. The clock of the DAC digital controller comes from I2S0 as well, so there are two clock sources for selection: dac_continuous_digi_clk_src_t::DAC_DIGI_CLK_SRC_PLL_D2 supports frequency between 19.6 KHz to several MHz. It is the default clock which can also be selected by dac_continuous_digi_clk_src_t::DAC_DIGI_CLK_SRC_DEFAULT . dac_continuous_digi_clk_src_t::DAC_DIGI_CLK_SRC_APLL supports frequency between 648 Hz to several MHz. However, it might be occupied by other peripherals, thus not providing the required frequency. In such case, this clock source is available only if APLL still can be correctly divided into the target DAC DMA frequency. Cosine Wave Output (Cosine Mode) The DAC peripheral has a cosine wave generator, which can generate cosine wave on the channels. Users can specify the frequency, amplitude, and phase of the cosine wave. To output the cosine wave, please acquire the DAC to cosine mode using dac_cosine_new_channel() , and then start the cosine wave generator by dac_cosine_start() . Currently, the clock source of the cosine wave generator only comes from RTC_FAST which can be selected by dac_cosine_clk_src_t::DAC_COSINE_CLK_SRC_RTC_FAST . It is also the default clock source which is the same as dac_cosine_clk_src_t::DAC_COSINE_CLK_SRC_RTC_DEFAULT . Power Management When the power management is enabled (i.e., CONFIG_PM_ENABLE is on), the system will adjust or stop the clock source of DAC before entering Light-sleep mode, thus potential influence to the DAC signals may lead to false data conversion. When using DAC driver in continuous mode, it can prevent the system from changing or stopping the clock source in DMA or cosine mode by acquiring a power management lock. When the clock source is generated from APB, the lock type will be set to esp_pm_lock_type_t::ESP_PM_APB_FREQ_MAX . When the clock source is APLL (only in DMA mode), it will be set to esp_pm_lock_type_t::ESP_PM_NO_LIGHT_SLEEP . Whenever the DAC is converting (i.e., DMA or cosine wave generator is working), the driver guarantees that the power management lock is acquired after calling dac_continuous_enable() . Likewise, the driver will release the lock when dac_continuous_disable() is called. IRAM Safe By default, the DAC DMA interrupt will be deferred when the cache is disabled for reasons like writing/erasing Flash. Thus the DMA EOF interrupt will not get executed in time. To avoid such case in real-time applications, you can enable the Kconfig option CONFIG_DAC_ISR_IRAM_SAFE which: Enables the interrupt being serviced even when cache is disabled; Places driver object into DRAM (in case it is linked to PSRAM by accident). This allows the interrupt to run while the cache is disabled but comes at the cost of increased IRAM consumption. Thread Safety All the public DAC APIs are guaranteed to be thread safe by the driver, which means users can call them from different RTOS tasks without protection by extra locks. Notice that the DAC driver uses mutex lock to ensure the thread safety, thus the APIs except dac_oneshot_output_voltage() are not allowed to be used in ISR. Kconfig Options CONFIG_DAC_ISR_IRAM_SAFE controls whether the default ISR handler can work when cache is disabled. See IRAM Safe for more information. CONFIG_DAC_SUPPRESS_DEPRECATE_WARN controls whether to suppress the warning message compilation while using the legacy DAC driver. CONFIG_DAC_ENABLE_DEBUG_LOG is used to enable the debug log output. Enable this option increases the firmware binary size. CONFIG_DAC_DMA_AUTO_16BIT_ALIGN auto expands the 8-bit data to 16-bit data in the driver to satisfy the I2S DMA format. Application Example The basic examples for the One-shot Mode , Continuous Mode , and Cosine Mode can be found in: API Reference Header File This header file can be included with: #include "driver/dac_oneshot.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t dac_oneshot_new_channel(const dac_oneshot_config_t *oneshot_cfg, dac_oneshot_handle_t *ret_handle) Allocate a new DAC oneshot channel. Note The channel will be enabled as well when the channel allocated Parameters oneshot_cfg -- [in] The configuration for the oneshot channel ret_handle -- [out] The returned oneshot channel handle oneshot_cfg -- [in] The configuration for the oneshot channel ret_handle -- [out] The returned oneshot channel handle oneshot_cfg -- [in] The configuration for the oneshot channel Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC channel has been registered already ESP_ERR_NO_MEM No memory for the DAC oneshot channel resources ESP_OK Allocate the new DAC oneshot channel success ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC channel has been registered already ESP_ERR_NO_MEM No memory for the DAC oneshot channel resources ESP_OK Allocate the new DAC oneshot channel success ESP_ERR_INVALID_ARG The input parameter is invalid Parameters oneshot_cfg -- [in] The configuration for the oneshot channel ret_handle -- [out] The returned oneshot channel handle Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC channel has been registered already ESP_ERR_NO_MEM No memory for the DAC oneshot channel resources ESP_OK Allocate the new DAC oneshot channel success esp_err_t dac_oneshot_del_channel(dac_oneshot_handle_t handle) Delete the DAC oneshot channel. Note The channel will be disabled as well when the channel deleted Parameters handle -- [in] The DAC oneshot channel handle Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has already been de-registered ESP_OK Delete the oneshot channel success ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has already been de-registered ESP_OK Delete the oneshot channel success ESP_ERR_INVALID_ARG The input parameter is invalid Parameters handle -- [in] The DAC oneshot channel handle Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has already been de-registered ESP_OK Delete the oneshot channel success esp_err_t dac_oneshot_output_voltage(dac_oneshot_handle_t handle, uint8_t digi_value) Output the voltage. Note Generally it'll take 7~11 us on ESP32 and 10~21 us on ESP32-S2 Parameters handle -- [in] The DAC oneshot channel handle digi_value -- [in] The digital value that need to be converted handle -- [in] The DAC oneshot channel handle digi_value -- [in] The digital value that need to be converted handle -- [in] The DAC oneshot channel handle Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_OK Convert the digital value success ESP_ERR_INVALID_ARG The input parameter is invalid ESP_OK Convert the digital value success ESP_ERR_INVALID_ARG The input parameter is invalid Parameters handle -- [in] The DAC oneshot channel handle digi_value -- [in] The digital value that need to be converted Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_OK Convert the digital value success Structures struct dac_oneshot_config_t DAC oneshot channel configuration. Public Members dac_channel_t chan_id DAC channel id dac_channel_t chan_id DAC channel id dac_channel_t chan_id Type Definitions typedef struct dac_oneshot_s *dac_oneshot_handle_t DAC oneshot channel handle Header File This header file can be included with: #include "driver/dac_cosine.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t dac_cosine_new_channel(const dac_cosine_config_t *cos_cfg, dac_cosine_handle_t *ret_handle) Allocate a new DAC cosine wave channel. Note Since there is only one cosine wave generator, only the first channel can set the frequency of the cosine wave. Normally, the latter one is not allowed to set a different frequency, but the it can be forced to set by setting the bit force_set_freq in the configuration, notice that another channel will be affected as well when the frequency is updated. Parameters cos_cfg -- [in] The configuration of cosine wave channel ret_handle -- [out] The returned cosine wave channel handle cos_cfg -- [in] The configuration of cosine wave channel ret_handle -- [out] The returned cosine wave channel handle cos_cfg -- [in] The configuration of cosine wave channel Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC channel has been registered already ESP_ERR_NO_MEM No memory for the DAC cosine wave channel resources ESP_OK Allocate the new DAC cosine wave channel success ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC channel has been registered already ESP_ERR_NO_MEM No memory for the DAC cosine wave channel resources ESP_OK Allocate the new DAC cosine wave channel success ESP_ERR_INVALID_ARG The input parameter is invalid Parameters cos_cfg -- [in] The configuration of cosine wave channel ret_handle -- [out] The returned cosine wave channel handle Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC channel has been registered already ESP_ERR_NO_MEM No memory for the DAC cosine wave channel resources ESP_OK Allocate the new DAC cosine wave channel success esp_err_t dac_cosine_del_channel(dac_cosine_handle_t handle) Delete the DAC cosine wave channel. Parameters handle -- [in] The DAC cosine wave channel handle Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has already been deregistered ESP_OK Delete the cosine wave channel success ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has already been deregistered ESP_OK Delete the cosine wave channel success ESP_ERR_INVALID_ARG The input parameter is invalid Parameters handle -- [in] The DAC cosine wave channel handle Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has already been deregistered ESP_OK Delete the cosine wave channel success esp_err_t dac_cosine_start(dac_cosine_handle_t handle) Start outputting the cosine wave on the channel. Parameters handle -- [in] The DAC cosine wave channel handle Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has been started already ESP_OK Start the cosine wave success ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has been started already ESP_OK Start the cosine wave success ESP_ERR_INVALID_ARG The input parameter is invalid Parameters handle -- [in] The DAC cosine wave channel handle Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has been started already ESP_OK Start the cosine wave success esp_err_t dac_cosine_stop(dac_cosine_handle_t handle) Stop outputting the cosine wave on the channel. Parameters handle -- [in] The DAC cosine wave channel handle Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has been stopped already ESP_OK Stop the cosine wave success ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has been stopped already ESP_OK Stop the cosine wave success ESP_ERR_INVALID_ARG The input parameter is invalid Parameters handle -- [in] The DAC cosine wave channel handle Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has been stopped already ESP_OK Stop the cosine wave success Structures struct dac_cosine_config_t DAC cosine channel configurations. Public Members dac_channel_t chan_id The cosine wave channel id dac_channel_t chan_id The cosine wave channel id uint32_t freq_hz The frequency of cosine wave, unit: Hz. The cosine wave generator is driven by RTC_FAST clock which is divide from RC_FAST, With the default RTC clock, the minimum frequency of cosine wave is about 130 Hz, Although it can support up to several MHz frequency theoretically, the waveform will distort at high frequency due to the hardware limitation. Typically not suggest to set the frequency higher than 200 KHz uint32_t freq_hz The frequency of cosine wave, unit: Hz. The cosine wave generator is driven by RTC_FAST clock which is divide from RC_FAST, With the default RTC clock, the minimum frequency of cosine wave is about 130 Hz, Although it can support up to several MHz frequency theoretically, the waveform will distort at high frequency due to the hardware limitation. Typically not suggest to set the frequency higher than 200 KHz dac_cosine_clk_src_t clk_src The clock source of the cosine wave generator, currently only support DAC_COSINE_CLK_SRC_DEFAULT dac_cosine_clk_src_t clk_src The clock source of the cosine wave generator, currently only support DAC_COSINE_CLK_SRC_DEFAULT dac_cosine_atten_t atten The attenuation of cosine wave amplitude dac_cosine_atten_t atten The attenuation of cosine wave amplitude dac_cosine_phase_t phase The phase of cosine wave, can only support DAC_COSINE_PHASE_0 or DAC_COSINE_PHASE_180, default as 0 while setting an unsupported phase dac_cosine_phase_t phase The phase of cosine wave, can only support DAC_COSINE_PHASE_0 or DAC_COSINE_PHASE_180, default as 0 while setting an unsupported phase int8_t offset The DC offset of cosine wave int8_t offset The DC offset of cosine wave bool force_set_freq Force to set the cosine wave frequency bool force_set_freq Force to set the cosine wave frequency struct dac_cosine_config_t::[anonymous] flags Flags of cosine mode struct dac_cosine_config_t::[anonymous] flags Flags of cosine mode dac_channel_t chan_id Type Definitions typedef struct dac_cosine_s *dac_cosine_handle_t DAC cosine wave channel handle Header File This header file can be included with: #include "driver/dac_continuous.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t dac_continuous_new_channels(const dac_continuous_config_t *cont_cfg, dac_continuous_handle_t *ret_handle) Allocate new DAC channels in continuous mode. Note The DAC channels can't be registered to continuous mode separately Parameters cont_cfg -- [in] Continuous mode configuration ret_handle -- [out] The returned continuous mode handle cont_cfg -- [in] Continuous mode configuration ret_handle -- [out] The returned continuous mode handle cont_cfg -- [in] Continuous mode configuration Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC channel has been registered already ESP_ERR_NOT_FOUND Not found the available dma peripheral, might be occupied ESP_ERR_NO_MEM No memory for the DAC continuous mode resources ESP_OK Allocate the new DAC continuous mode success ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC channel has been registered already ESP_ERR_NOT_FOUND Not found the available dma peripheral, might be occupied ESP_ERR_NO_MEM No memory for the DAC continuous mode resources ESP_OK Allocate the new DAC continuous mode success ESP_ERR_INVALID_ARG The input parameter is invalid Parameters cont_cfg -- [in] Continuous mode configuration ret_handle -- [out] The returned continuous mode handle Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC channel has been registered already ESP_ERR_NOT_FOUND Not found the available dma peripheral, might be occupied ESP_ERR_NO_MEM No memory for the DAC continuous mode resources ESP_OK Allocate the new DAC continuous mode success esp_err_t dac_continuous_del_channels(dac_continuous_handle_t handle) Delete the DAC continuous handle. Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channels have already been deregistered or not disabled ESP_OK Delete the continuous channels success ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channels have already been deregistered or not disabled ESP_OK Delete the continuous channels success ESP_ERR_INVALID_ARG The input parameter is invalid Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channels have already been deregistered or not disabled ESP_OK Delete the continuous channels success esp_err_t dac_continuous_enable(dac_continuous_handle_t handle) Enabled the DAC continuous mode. Note Must enable the channels before Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channels have been enabled already ESP_OK Enable the continuous output success ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channels have been enabled already ESP_OK Enable the continuous output success ESP_ERR_INVALID_ARG The input parameter is invalid Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channels have been enabled already ESP_OK Enable the continuous output success esp_err_t dac_continuous_disable(dac_continuous_handle_t handle) Disable the DAC continuous mode. Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channels have been enabled already ESP_OK Disable the continuous output success ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channels have been enabled already ESP_OK Disable the continuous output success ESP_ERR_INVALID_ARG The input parameter is invalid Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channels have been enabled already ESP_OK Disable the continuous output success esp_err_t dac_continuous_write(dac_continuous_handle_t handle, uint8_t *buf, size_t buf_size, size_t *bytes_loaded, int timeout_ms) Write DAC data continuously. Note The data in buffer will only be converted one time, This function will be blocked until all data loaded or timeout then the DAC output will keep outputting the voltage of the last data in the buffer Note Specially, on ESP32, the data bit width of DAC continuous data is fixed to 16 bits while only the high 8 bits are available, The driver will help to expand the inputted buffer automatically by default, you can also align the data to 16 bits manually by clearing CONFIG_DAC_DMA_AUTO_16BIT_ALIGN in menuconfig. Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' buf -- [in] The digital data buffer to convert buf_size -- [in] The buffer size of digital data buffer bytes_loaded -- [out] The bytes that has been loaded into DMA buffer, can be NULL if don't need it timeout_ms -- [in] The timeout time in millisecond, set a minus value means will block forever handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' buf -- [in] The digital data buffer to convert buf_size -- [in] The buffer size of digital data buffer bytes_loaded -- [out] The bytes that has been loaded into DMA buffer, can be NULL if don't need it timeout_ms -- [in] The timeout time in millisecond, set a minus value means will block forever handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC continuous mode has not been enabled yet ESP_ERR_TIMEOUT Waiting for semaphore or message queue timeout ESP_OK Success to output the acyclic DAC data ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC continuous mode has not been enabled yet ESP_ERR_TIMEOUT Waiting for semaphore or message queue timeout ESP_OK Success to output the acyclic DAC data ESP_ERR_INVALID_ARG The input parameter is invalid Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' buf -- [in] The digital data buffer to convert buf_size -- [in] The buffer size of digital data buffer bytes_loaded -- [out] The bytes that has been loaded into DMA buffer, can be NULL if don't need it timeout_ms -- [in] The timeout time in millisecond, set a minus value means will block forever Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC continuous mode has not been enabled yet ESP_ERR_TIMEOUT Waiting for semaphore or message queue timeout ESP_OK Success to output the acyclic DAC data esp_err_t dac_continuous_write_cyclically(dac_continuous_handle_t handle, uint8_t *buf, size_t buf_size, size_t *bytes_loaded) Write DAC continuous data cyclically. Note The data in buffer will be converted cyclically using DMA once this function is called, This function will return once the data loaded into DMA buffers. Note The buffer size of cyclically output is limited by the descriptor number and dma buffer size while initializing the continuous mode. Concretely, in order to load all the data into descriptors, the cyclic buffer size is not supposed to be greater than desc_num * buf_size Note Specially, on ESP32, the data bit width of DAC continuous data is fixed to 16 bits while only the high 8 bits are available, The driver will help to expand the inputted buffer automatically by default, you can also align the data to 16 bits manually by clearing CONFIG_DAC_DMA_AUTO_16BIT_ALIGN in menuconfig. Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' buf -- [in] The digital data buffer to convert buf_size -- [in] The buffer size of digital data buffer bytes_loaded -- [out] The bytes that has been loaded into DMA buffer, can be NULL if don't need it handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' buf -- [in] The digital data buffer to convert buf_size -- [in] The buffer size of digital data buffer bytes_loaded -- [out] The bytes that has been loaded into DMA buffer, can be NULL if don't need it handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC continuous mode has not been enabled yet ESP_OK Success to output the acyclic DAC data ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC continuous mode has not been enabled yet ESP_OK Success to output the acyclic DAC data ESP_ERR_INVALID_ARG The input parameter is invalid Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' buf -- [in] The digital data buffer to convert buf_size -- [in] The buffer size of digital data buffer bytes_loaded -- [out] The bytes that has been loaded into DMA buffer, can be NULL if don't need it Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC continuous mode has not been enabled yet ESP_OK Success to output the acyclic DAC data esp_err_t dac_continuous_register_event_callback(dac_continuous_handle_t handle, const dac_event_callbacks_t *callbacks, void *user_data) Set event callbacks for DAC continuous mode. Note User can deregister a previously registered callback by calling this function and setting the callback member in the callbacks structure to NULL. Note When CONFIG_DAC_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in this function, including the user_data , should be in the internal RAM as well. Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' callbacks -- [in] Group of callback functions, input NULL to clear the former callbacks user_data -- [in] User data, which will be passed to callback functions directly handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' callbacks -- [in] Group of callback functions, input NULL to clear the former callbacks user_data -- [in] User data, which will be passed to callback functions directly handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' Returns ESP_OK Set event callbacks successfully ESP_ERR_INVALID_ARG Set event callbacks failed because of invalid argument ESP_OK Set event callbacks successfully ESP_ERR_INVALID_ARG Set event callbacks failed because of invalid argument ESP_OK Set event callbacks successfully Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' callbacks -- [in] Group of callback functions, input NULL to clear the former callbacks user_data -- [in] User data, which will be passed to callback functions directly Returns ESP_OK Set event callbacks successfully ESP_ERR_INVALID_ARG Set event callbacks failed because of invalid argument esp_err_t dac_continuous_start_async_writing(dac_continuous_handle_t handle) Start the async writing. Note When the asynchronous writing start, the DAC will keep outputting '0' until the data are loaded into the DMA buffer. To loaded the data into DMA buffer, 'on_convert_done' callback is required, which can be registered by 'dac_continuous_register_event_callback' before enabling Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' Returns ESP_OK Start asynchronous writing successfully ESP_ERR_INVALID_ARG The handle is NULL ESP_ERR_INVALID_STATE The channel is not enabled or the 'on_convert_done' callback is not registered ESP_OK Start asynchronous writing successfully ESP_ERR_INVALID_ARG The handle is NULL ESP_ERR_INVALID_STATE The channel is not enabled or the 'on_convert_done' callback is not registered ESP_OK Start asynchronous writing successfully Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' Returns ESP_OK Start asynchronous writing successfully ESP_ERR_INVALID_ARG The handle is NULL ESP_ERR_INVALID_STATE The channel is not enabled or the 'on_convert_done' callback is not registered esp_err_t dac_continuous_stop_async_writing(dac_continuous_handle_t handle) Stop the sync writing. Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' Returns ESP_OK Stop asynchronous writing successfully ESP_ERR_INVALID_ARG The handle is NULL ESP_ERR_INVALID_STATE Asynchronous writing has not started ESP_OK Stop asynchronous writing successfully ESP_ERR_INVALID_ARG The handle is NULL ESP_ERR_INVALID_STATE Asynchronous writing has not started ESP_OK Stop asynchronous writing successfully Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' Returns ESP_OK Stop asynchronous writing successfully ESP_ERR_INVALID_ARG The handle is NULL ESP_ERR_INVALID_STATE Asynchronous writing has not started esp_err_t dac_continuous_write_asynchronously(dac_continuous_handle_t handle, uint8_t *dma_buf, size_t dma_buf_len, const uint8_t *data, size_t data_len, size_t *bytes_loaded) Write DAC data asynchronously. Note This function can be called when the asynchronous writing started, and it can be called in the callback directly but recommend to writing data in a task, referring to :example: peripherals/dac/dac_continuous/dac_audio Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' dma_buf -- [in] The DMA buffer address, it can be acquired from 'dac_event_data_t' in the 'on_convert_done' callback dma_buf_len -- [in] The DMA buffer length, it can be acquired from 'dac_event_data_t' in the 'on_convert_done' callback data -- [in] The data that need to be written data_len -- [in] The data length the need to be written bytes_loaded -- [out] The bytes number that has been loaded/written into the DMA buffer handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' dma_buf -- [in] The DMA buffer address, it can be acquired from 'dac_event_data_t' in the 'on_convert_done' callback dma_buf_len -- [in] The DMA buffer length, it can be acquired from 'dac_event_data_t' in the 'on_convert_done' callback data -- [in] The data that need to be written data_len -- [in] The data length the need to be written bytes_loaded -- [out] The bytes number that has been loaded/written into the DMA buffer handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' Returns ESP_OK Write the data into DMA buffer successfully ESP_ERR_INVALID_ARG NULL pointer ESP_ERR_INVALID_STATE The channels haven't start the asynchronous writing ESP_ERR_NOT_FOUND The param 'dam_buf' not match any existed DMA buffer ESP_OK Write the data into DMA buffer successfully ESP_ERR_INVALID_ARG NULL pointer ESP_ERR_INVALID_STATE The channels haven't start the asynchronous writing ESP_ERR_NOT_FOUND The param 'dam_buf' not match any existed DMA buffer ESP_OK Write the data into DMA buffer successfully Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' dma_buf -- [in] The DMA buffer address, it can be acquired from 'dac_event_data_t' in the 'on_convert_done' callback dma_buf_len -- [in] The DMA buffer length, it can be acquired from 'dac_event_data_t' in the 'on_convert_done' callback data -- [in] The data that need to be written data_len -- [in] The data length the need to be written bytes_loaded -- [out] The bytes number that has been loaded/written into the DMA buffer Returns ESP_OK Write the data into DMA buffer successfully ESP_ERR_INVALID_ARG NULL pointer ESP_ERR_INVALID_STATE The channels haven't start the asynchronous writing ESP_ERR_NOT_FOUND The param 'dam_buf' not match any existed DMA buffer Structures struct dac_continuous_config_t DAC continuous channels' configurations. Public Members dac_channel_mask_t chan_mask DAC channels' mask for selecting which channels are used dac_channel_mask_t chan_mask DAC channels' mask for selecting which channels are used uint32_t desc_num The number of DMA descriptor, at least 2 descriptors are required The number of descriptors is directly proportional to the max data buffer size while converting in cyclic output but only need to ensure it is greater than '1' in acyclic output Typically, suggest to set the number bigger than 5, in case the DMA stopped while sending a short buffer uint32_t desc_num The number of DMA descriptor, at least 2 descriptors are required The number of descriptors is directly proportional to the max data buffer size while converting in cyclic output but only need to ensure it is greater than '1' in acyclic output Typically, suggest to set the number bigger than 5, in case the DMA stopped while sending a short buffer size_t buf_size The DMA buffer size, should be within 32~4092 bytes. Each DMA buffer will be attached to a DMA descriptor, i.e. the number of DMA buffer will be equal to the DMA descriptor number The DMA buffer size is not allowed to be greater than 4092 bytes The total DMA buffer size equal to desc_num * buf_size Typically, suggest to set the size to the multiple of 4 size_t buf_size The DMA buffer size, should be within 32~4092 bytes. Each DMA buffer will be attached to a DMA descriptor, i.e. the number of DMA buffer will be equal to the DMA descriptor number The DMA buffer size is not allowed to be greater than 4092 bytes The total DMA buffer size equal to desc_num * buf_size Typically, suggest to set the size to the multiple of 4 uint32_t freq_hz The frequency of DAC conversion in continuous mode, unit: Hz The supported range is related to the target and the clock source. For the clock DAC_DIGI_CLK_SRC_DEFAULT : the range is 19.6 KHz to several MHz on ESP32 and 77 Hz to several MHz on ESP32-S2. For the clock DAC_DIGI_CLK_SRC_APLL : the range is 648 Hz to several MHz on ESP32 and 6 Hz to several MHz on ESP32-S2. Typically not suggest to set the frequency higher than 2 MHz, otherwise the severe distortion will appear uint32_t freq_hz The frequency of DAC conversion in continuous mode, unit: Hz The supported range is related to the target and the clock source. For the clock DAC_DIGI_CLK_SRC_DEFAULT : the range is 19.6 KHz to several MHz on ESP32 and 77 Hz to several MHz on ESP32-S2. For the clock DAC_DIGI_CLK_SRC_APLL : the range is 648 Hz to several MHz on ESP32 and 6 Hz to several MHz on ESP32-S2. Typically not suggest to set the frequency higher than 2 MHz, otherwise the severe distortion will appear int8_t offset The offset of the DAC digital data. Range -128~127 int8_t offset The offset of the DAC digital data. Range -128~127 dac_continuous_digi_clk_src_t clk_src The clock source of digital controller, which can affect the range of supported frequency Currently DAC_DIGI_CLK_SRC_DEFAULT and DAC_DIGI_CLK_SRC_APLL are available dac_continuous_digi_clk_src_t clk_src The clock source of digital controller, which can affect the range of supported frequency Currently DAC_DIGI_CLK_SRC_DEFAULT and DAC_DIGI_CLK_SRC_APLL are available dac_continuous_channel_mode_t chan_mode The channel mode of continuous mode, only take effect when multiple channels enabled, depends converting the buffer alternately or simultaneously dac_continuous_channel_mode_t chan_mode The channel mode of continuous mode, only take effect when multiple channels enabled, depends converting the buffer alternately or simultaneously dac_channel_mask_t chan_mask struct dac_event_data_t Event structure used in DAC event queue. Public Members void *buf The pointer of DMA buffer that just finished sending void *buf The pointer of DMA buffer that just finished sending size_t buf_size The writable buffer size of the DMA buffer, equal to 'dac_continuous_config_t::buf_size' size_t buf_size The writable buffer size of the DMA buffer, equal to 'dac_continuous_config_t::buf_size' size_t write_bytes The number of bytes that be written successfully size_t write_bytes The number of bytes that be written successfully void *buf struct dac_event_callbacks_t Group of DAC callbacks. Note The callbacks are all running under ISR environment Note When CONFIG_DAC_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. Public Members dac_isr_callback_t on_convert_done Callback of data conversion done event An event data buffer previously loaded to the driver has been output and converted. The event data includes DMA buffer address and size that just finished converting. dac_isr_callback_t on_convert_done Callback of data conversion done event An event data buffer previously loaded to the driver has been output and converted. The event data includes DMA buffer address and size that just finished converting. dac_isr_callback_t on_stop Callback of finished sending all the data. All loaded event data buffers are converted. Driver is pending for new data buffers to be loaded. The event data will be NULL in this callback. dac_isr_callback_t on_stop Callback of finished sending all the data. All loaded event data buffers are converted. Driver is pending for new data buffers to be loaded. The event data will be NULL in this callback. dac_isr_callback_t on_convert_done Type Definitions typedef struct dac_continuous_s *dac_continuous_handle_t DAC continuous channel handle typedef bool (*dac_isr_callback_t)(dac_continuous_handle_t handle, const dac_event_data_t *event, void *user_data) DAC event callback. Param handle [in] DAC channel handle, created from dac_continuous_new_channels() Param event [in] DAC event data Param user_data [in] User registered context, passed from dac_continuous_register_event_callback() Return Whether a high priority task has been waken up by this callback function Param handle [in] DAC channel handle, created from dac_continuous_new_channels() Param event [in] DAC event data Param user_data [in] User registered context, passed from dac_continuous_register_event_callback() Return Whether a high priority task has been waken up by this callback function Enumerations Header File This header file can be included with: #include "driver/dac_types.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Type Definitions typedef soc_periph_dac_digi_clk_src_t dac_continuous_digi_clk_src_t DAC DMA (digitial controller) clock source. typedef soc_periph_dac_cosine_clk_src_t dac_cosine_clk_src_t DAC cosine wave generator clock source. Enumerations enum dac_continuous_channel_mode_t DAC channel work mode in dma mode. Note Only take effect when multiple channels enabled. Note Assume the data in buffer is 'A B C D E F' DAC_CHANNEL_MODE_SIMUL: channel 0: A B C D E F channel 1: A B C D E F DAC_CHANNEL_MODE_ALTER: channel 0: A C E channel 1: B D F channel 0: A B C D E F channel 1: A B C D E F DAC_CHANNEL_MODE_ALTER: channel 0: A C E channel 1: B D F Values: enumerator DAC_CHANNEL_MODE_SIMUL The data in the DMA buffer is simultaneously output to the enable channel of the DAC. enumerator DAC_CHANNEL_MODE_SIMUL The data in the DMA buffer is simultaneously output to the enable channel of the DAC. enumerator DAC_CHANNEL_MODE_ALTER The data in the DMA buffer is alternately output to the enable channel of the DAC. enumerator DAC_CHANNEL_MODE_ALTER The data in the DMA buffer is alternately output to the enable channel of the DAC. channel 0: A B C D E F Header File This header file can be included with: #include "hal/dac_types.h" Enumerations enum dac_channel_t Values: enumerator DAC_CHAN_0 DAC channel 0 is GPIO25(ESP32) / GPIO17(ESP32S2) enumerator DAC_CHAN_0 DAC channel 0 is GPIO25(ESP32) / GPIO17(ESP32S2) enumerator DAC_CHAN_1 DAC channel 1 is GPIO26(ESP32) / GPIO18(ESP32S2) enumerator DAC_CHAN_1 DAC channel 1 is GPIO26(ESP32) / GPIO18(ESP32S2) enumerator DAC_CHANNEL_1 Alias of 'DAC_CHAN_0', now the channel index start from '0' enumerator DAC_CHANNEL_1 Alias of 'DAC_CHAN_0', now the channel index start from '0' enumerator DAC_CHANNEL_2 Alias of 'DAC_CHAN_1', now the channel index start from '0' enumerator DAC_CHANNEL_2 Alias of 'DAC_CHAN_1', now the channel index start from '0' enumerator DAC_CHAN_0 enum dac_cosine_atten_t The attenuation of the amplitude of the cosine wave generator. The max amplitude is VDD3P3_RTC. Values: enumerator DAC_COSINE_ATTEN_DEFAULT No attenuation to the DAC cosine wave amplitude. Default. enumerator DAC_COSINE_ATTEN_DEFAULT No attenuation to the DAC cosine wave amplitude. Default. enumerator DAC_COSINE_ATTEN_DB_0 Original amplitude of the DAC cosine wave, equals to DAC_COSINE_ATTEN_DEFAULT enumerator DAC_COSINE_ATTEN_DB_0 Original amplitude of the DAC cosine wave, equals to DAC_COSINE_ATTEN_DEFAULT enumerator DAC_COSINE_ATTEN_DB_6 1/2 amplitude of the DAC cosine wave enumerator DAC_COSINE_ATTEN_DB_6 1/2 amplitude of the DAC cosine wave enumerator DAC_COSINE_ATTEN_DB_12 1/4 amplitude of the DAC cosine wave enumerator DAC_COSINE_ATTEN_DB_12 1/4 amplitude of the DAC cosine wave enumerator DAC_COSINE_ATTEN_DB_18 1/8 amplitude of the DAC cosine wave enumerator DAC_COSINE_ATTEN_DB_18 1/8 amplitude of the DAC cosine wave enumerator DAC_COSINE_ATTEN_DEFAULT
Digital To Analog Converter (DAC) Overview ESP32 has two 8-bit DAC (digital to analog converter) channels respectively connected to GPIO25 (Channel 1) and GPIO26 (Channel 2). Each DAC channel can convert the digital value 0~255 to the analog voltage 0~Vref (The reference voltage 'Vref' here is input from the pin VDD3P3_RTC, which ideally equals to the power supply VDD). The output voltage can be calculated as the following: out_voltage = Vref * digi_val / 255 The DAC peripheral supports outputting analog signal in the following ways: Outputting a voltage directly. The DAC channel keeps outputting a specified voltage. Outputting continuous analog signal by DMA. The DAC converts the data in a buffer at a specified frequency. Outputting a cosine wave by the cosine wave generator. The DAC channel can output a cosine wave with specified frequency and amplitude. For other analog output options, see Sigma-Delta Modulation and LED Control. Both modules produce high-frequency PWM/PDM output, which can be hardware low-pass filtered in order to generate a lower frequency analog output. DAC File Structure Public headers that need to be included in the DAC application are listed as follows: dac.h: The top header file of the legacy DAC driver, which should be only included in the apps which use the legacy driver API. dac_oneshot.h: The top header file of the new DAC driver, which should be included in the apps which use the new driver API with one-shot mode. dac_cosine.h: The top header file of the new DAC driver, which should be included in the apps which use the new driver API with cosine mode. dac_continuous.h: The top header file of the new DAC driver, which should be included in the apps which use the new driver API with continuous mode. Note The legacy driver cannot coexist with the new driver. Include dac.h to use the legacy driver or dac_oneshot.h, dac_cosine.h, and dac_continuous.h to use the new driver. The legacy driver might be removed in the future. Functional Overview Resources Management The DAC on ESP32 has two channels. The channels have separate software resources and can be managed by dac_oneshot_handle_t, dac_cosine_handle_t, or dac_continuous_handle_t according to the usage. Registering different modes on a same DAC channel is not allowed. Direct Voltage Output (One-shot/Direct Mode) The DAC channels in the group can convert an 8-bit digital value into the analog when dac_oneshot_output_voltage() is called (it can be called in ISR). The analog voltage is kept on the DAC channel until the next conversion starts. To start the voltage conversion, the DAC channels need to be enabled first through registering by dac_oneshot_new_channel(). Continuous Wave Output (Continuous/DMA Mode) DAC channels can convert digital data continuously via the DMA. There are three ways to write the DAC data: - Normal writing (synchronous): Data can be transmitted at one time and kept blocked until all the data has been loaded into the DMA buffer, and the voltage is kept as the last conversion value while no more data is inputted. It is usually used to transport a long signal like an audio. To convert data continuously, the continuous channel handle need to be allocated by calling dac_continuous_new_channels()and the DMA conversion should be enabled by calling dac_continuous_enable(). Then data can be written by dac_continuous_write()synchronously. Refer to peripherals/dac/dac_continuous/dac_audio for examples. - Cyclical writing: A piece of data can be converted cyclically without blocking, and no more operation is needed after the data are loaded into the DMA buffer. But note that the inputted buffer size is limited by the number of descriptors and the DMA buffer size. It is usually used to transport short signals that need to be repeated, e.g., a sine wave. To achieve cyclical writing, call dac_continuous_write_cyclically()after the DAC continuous mode is enabled. Refer to peripherals/dac/dac_continuous/signal_generator for examples. - Asynchronous writing: Data can be transmitted asynchronously based on the event callback. dac_event_callbacks_t::on_convert_donemust be registered to use asynchronous mode. Users can get the dac_event_data_tin the callback which contains the DMA buffer address and length, allowing them to load the data into the buffer directly. To use the asynchronous writing, call dac_continuous_register_event_callback()to register the dac_event_callbacks_t::on_convert_donebefore enabling, and then dac_continuous_start_async_writing()to start the asynchronous writing. Note that once the asynchronous writing is started, the callback function will be triggered continuously. Call dac_continuous_write_asynchronously()to load the data either in a separate task or in the callback directly. Refer to peripherals/dac/dac_continuous/dac_audio for examples. On ESP32, the DAC digital controller can be connected internally to the I2S0 and use its DMA for continuous conversion. Although the DAC only needs 8-bit data for conversion, it has to be the left-shifted 8 bits (i.e., the high 8 bits in a 16-bit slot) to satisfy the I2S communication format. By default, the driver helps to expand the data to 16-bit wide automatically. To expand manually, please disable CONFIG_DAC_DMA_AUTO_16BIT_ALIGN in the menuconfig. The clock of the DAC digital controller comes from I2S0 as well, so there are two clock sources for selection: dac_continuous_digi_clk_src_t::DAC_DIGI_CLK_SRC_PLL_D2supports frequency between 19.6 KHz to several MHz. It is the default clock which can also be selected by dac_continuous_digi_clk_src_t::DAC_DIGI_CLK_SRC_DEFAULT. dac_continuous_digi_clk_src_t::DAC_DIGI_CLK_SRC_APLLsupports frequency between 648 Hz to several MHz. However, it might be occupied by other peripherals, thus not providing the required frequency. In such case, this clock source is available only if APLL still can be correctly divided into the target DAC DMA frequency. Cosine Wave Output (Cosine Mode) The DAC peripheral has a cosine wave generator, which can generate cosine wave on the channels. Users can specify the frequency, amplitude, and phase of the cosine wave. To output the cosine wave, please acquire the DAC to cosine mode using dac_cosine_new_channel(), and then start the cosine wave generator by dac_cosine_start(). Currently, the clock source of the cosine wave generator only comes from RTC_FAST which can be selected by dac_cosine_clk_src_t::DAC_COSINE_CLK_SRC_RTC_FAST. It is also the default clock source which is the same as dac_cosine_clk_src_t::DAC_COSINE_CLK_SRC_RTC_DEFAULT. Power Management When the power management is enabled (i.e., CONFIG_PM_ENABLE is on), the system will adjust or stop the clock source of DAC before entering Light-sleep mode, thus potential influence to the DAC signals may lead to false data conversion. When using DAC driver in continuous mode, it can prevent the system from changing or stopping the clock source in DMA or cosine mode by acquiring a power management lock. When the clock source is generated from APB, the lock type will be set to esp_pm_lock_type_t::ESP_PM_APB_FREQ_MAX. When the clock source is APLL (only in DMA mode), it will be set to esp_pm_lock_type_t::ESP_PM_NO_LIGHT_SLEEP. Whenever the DAC is converting (i.e., DMA or cosine wave generator is working), the driver guarantees that the power management lock is acquired after calling dac_continuous_enable(). Likewise, the driver will release the lock when dac_continuous_disable() is called. IRAM Safe By default, the DAC DMA interrupt will be deferred when the cache is disabled for reasons like writing/erasing Flash. Thus the DMA EOF interrupt will not get executed in time. To avoid such case in real-time applications, you can enable the Kconfig option CONFIG_DAC_ISR_IRAM_SAFE which: Enables the interrupt being serviced even when cache is disabled; Places driver object into DRAM (in case it is linked to PSRAM by accident). This allows the interrupt to run while the cache is disabled but comes at the cost of increased IRAM consumption. Thread Safety All the public DAC APIs are guaranteed to be thread safe by the driver, which means users can call them from different RTOS tasks without protection by extra locks. Notice that the DAC driver uses mutex lock to ensure the thread safety, thus the APIs except dac_oneshot_output_voltage() are not allowed to be used in ISR. Kconfig Options CONFIG_DAC_ISR_IRAM_SAFE controls whether the default ISR handler can work when cache is disabled. See IRAM Safe for more information. CONFIG_DAC_SUPPRESS_DEPRECATE_WARN controls whether to suppress the warning message compilation while using the legacy DAC driver. CONFIG_DAC_ENABLE_DEBUG_LOG is used to enable the debug log output. Enable this option increases the firmware binary size. CONFIG_DAC_DMA_AUTO_16BIT_ALIGN auto expands the 8-bit data to 16-bit data in the driver to satisfy the I2S DMA format. Application Example The basic examples for the One-shot Mode, Continuous Mode, and Cosine Mode can be found in: API Reference Header File This header file can be included with: #include "driver/dac_oneshot.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t dac_oneshot_new_channel(const dac_oneshot_config_t *oneshot_cfg, dac_oneshot_handle_t *ret_handle) Allocate a new DAC oneshot channel. Note The channel will be enabled as well when the channel allocated - Parameters oneshot_cfg -- [in] The configuration for the oneshot channel ret_handle -- [out] The returned oneshot channel handle - - Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC channel has been registered already ESP_ERR_NO_MEM No memory for the DAC oneshot channel resources ESP_OK Allocate the new DAC oneshot channel success - - esp_err_t dac_oneshot_del_channel(dac_oneshot_handle_t handle) Delete the DAC oneshot channel. Note The channel will be disabled as well when the channel deleted - Parameters handle -- [in] The DAC oneshot channel handle - Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has already been de-registered ESP_OK Delete the oneshot channel success - - esp_err_t dac_oneshot_output_voltage(dac_oneshot_handle_t handle, uint8_t digi_value) Output the voltage. Note Generally it'll take 7~11 us on ESP32 and 10~21 us on ESP32-S2 - Parameters handle -- [in] The DAC oneshot channel handle digi_value -- [in] The digital value that need to be converted - - Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_OK Convert the digital value success - Structures - struct dac_oneshot_config_t DAC oneshot channel configuration. Public Members - dac_channel_t chan_id DAC channel id - dac_channel_t chan_id Type Definitions - typedef struct dac_oneshot_s *dac_oneshot_handle_t DAC oneshot channel handle Header File This header file can be included with: #include "driver/dac_cosine.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t dac_cosine_new_channel(const dac_cosine_config_t *cos_cfg, dac_cosine_handle_t *ret_handle) Allocate a new DAC cosine wave channel. Note Since there is only one cosine wave generator, only the first channel can set the frequency of the cosine wave. Normally, the latter one is not allowed to set a different frequency, but the it can be forced to set by setting the bit force_set_freqin the configuration, notice that another channel will be affected as well when the frequency is updated. - Parameters cos_cfg -- [in] The configuration of cosine wave channel ret_handle -- [out] The returned cosine wave channel handle - - Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC channel has been registered already ESP_ERR_NO_MEM No memory for the DAC cosine wave channel resources ESP_OK Allocate the new DAC cosine wave channel success - - esp_err_t dac_cosine_del_channel(dac_cosine_handle_t handle) Delete the DAC cosine wave channel. - Parameters handle -- [in] The DAC cosine wave channel handle - Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has already been deregistered ESP_OK Delete the cosine wave channel success - - esp_err_t dac_cosine_start(dac_cosine_handle_t handle) Start outputting the cosine wave on the channel. - Parameters handle -- [in] The DAC cosine wave channel handle - Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has been started already ESP_OK Start the cosine wave success - - esp_err_t dac_cosine_stop(dac_cosine_handle_t handle) Stop outputting the cosine wave on the channel. - Parameters handle -- [in] The DAC cosine wave channel handle - Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channel has been stopped already ESP_OK Stop the cosine wave success - Structures - struct dac_cosine_config_t DAC cosine channel configurations. Public Members - dac_channel_t chan_id The cosine wave channel id - uint32_t freq_hz The frequency of cosine wave, unit: Hz. The cosine wave generator is driven by RTC_FAST clock which is divide from RC_FAST, With the default RTC clock, the minimum frequency of cosine wave is about 130 Hz, Although it can support up to several MHz frequency theoretically, the waveform will distort at high frequency due to the hardware limitation. Typically not suggest to set the frequency higher than 200 KHz - dac_cosine_clk_src_t clk_src The clock source of the cosine wave generator, currently only support DAC_COSINE_CLK_SRC_DEFAULT - dac_cosine_atten_t atten The attenuation of cosine wave amplitude - dac_cosine_phase_t phase The phase of cosine wave, can only support DAC_COSINE_PHASE_0 or DAC_COSINE_PHASE_180, default as 0 while setting an unsupported phase - int8_t offset The DC offset of cosine wave - bool force_set_freq Force to set the cosine wave frequency - struct dac_cosine_config_t::[anonymous] flags Flags of cosine mode - dac_channel_t chan_id Type Definitions - typedef struct dac_cosine_s *dac_cosine_handle_t DAC cosine wave channel handle Header File This header file can be included with: #include "driver/dac_continuous.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t dac_continuous_new_channels(const dac_continuous_config_t *cont_cfg, dac_continuous_handle_t *ret_handle) Allocate new DAC channels in continuous mode. Note The DAC channels can't be registered to continuous mode separately - Parameters cont_cfg -- [in] Continuous mode configuration ret_handle -- [out] The returned continuous mode handle - - Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC channel has been registered already ESP_ERR_NOT_FOUND Not found the available dma peripheral, might be occupied ESP_ERR_NO_MEM No memory for the DAC continuous mode resources ESP_OK Allocate the new DAC continuous mode success - - esp_err_t dac_continuous_del_channels(dac_continuous_handle_t handle) Delete the DAC continuous handle. - Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' - Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channels have already been deregistered or not disabled ESP_OK Delete the continuous channels success - - esp_err_t dac_continuous_enable(dac_continuous_handle_t handle) Enabled the DAC continuous mode. Note Must enable the channels before - Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' - Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channels have been enabled already ESP_OK Enable the continuous output success - - esp_err_t dac_continuous_disable(dac_continuous_handle_t handle) Disable the DAC continuous mode. - Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' - Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The channels have been enabled already ESP_OK Disable the continuous output success - - esp_err_t dac_continuous_write(dac_continuous_handle_t handle, uint8_t *buf, size_t buf_size, size_t *bytes_loaded, int timeout_ms) Write DAC data continuously. Note The data in buffer will only be converted one time, This function will be blocked until all data loaded or timeout then the DAC output will keep outputting the voltage of the last data in the buffer Note Specially, on ESP32, the data bit width of DAC continuous data is fixed to 16 bits while only the high 8 bits are available, The driver will help to expand the inputted buffer automatically by default, you can also align the data to 16 bits manually by clearing CONFIG_DAC_DMA_AUTO_16BIT_ALIGNin menuconfig. - Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' buf -- [in] The digital data buffer to convert buf_size -- [in] The buffer size of digital data buffer bytes_loaded -- [out] The bytes that has been loaded into DMA buffer, can be NULL if don't need it timeout_ms -- [in] The timeout time in millisecond, set a minus value means will block forever - - Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC continuous mode has not been enabled yet ESP_ERR_TIMEOUT Waiting for semaphore or message queue timeout ESP_OK Success to output the acyclic DAC data - - esp_err_t dac_continuous_write_cyclically(dac_continuous_handle_t handle, uint8_t *buf, size_t buf_size, size_t *bytes_loaded) Write DAC continuous data cyclically. Note The data in buffer will be converted cyclically using DMA once this function is called, This function will return once the data loaded into DMA buffers. Note The buffer size of cyclically output is limited by the descriptor number and dma buffer size while initializing the continuous mode. Concretely, in order to load all the data into descriptors, the cyclic buffer size is not supposed to be greater than desc_num * buf_size Note Specially, on ESP32, the data bit width of DAC continuous data is fixed to 16 bits while only the high 8 bits are available, The driver will help to expand the inputted buffer automatically by default, you can also align the data to 16 bits manually by clearing CONFIG_DAC_DMA_AUTO_16BIT_ALIGNin menuconfig. - Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' buf -- [in] The digital data buffer to convert buf_size -- [in] The buffer size of digital data buffer bytes_loaded -- [out] The bytes that has been loaded into DMA buffer, can be NULL if don't need it - - Returns ESP_ERR_INVALID_ARG The input parameter is invalid ESP_ERR_INVALID_STATE The DAC continuous mode has not been enabled yet ESP_OK Success to output the acyclic DAC data - - esp_err_t dac_continuous_register_event_callback(dac_continuous_handle_t handle, const dac_event_callbacks_t *callbacks, void *user_data) Set event callbacks for DAC continuous mode. Note User can deregister a previously registered callback by calling this function and setting the callback member in the callbacksstructure to NULL. Note When CONFIG_DAC_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in this function, including the user_data, should be in the internal RAM as well. - Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' callbacks -- [in] Group of callback functions, input NULL to clear the former callbacks user_data -- [in] User data, which will be passed to callback functions directly - - Returns ESP_OK Set event callbacks successfully ESP_ERR_INVALID_ARG Set event callbacks failed because of invalid argument - - esp_err_t dac_continuous_start_async_writing(dac_continuous_handle_t handle) Start the async writing. Note When the asynchronous writing start, the DAC will keep outputting '0' until the data are loaded into the DMA buffer. To loaded the data into DMA buffer, 'on_convert_done' callback is required, which can be registered by 'dac_continuous_register_event_callback' before enabling - Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' - Returns ESP_OK Start asynchronous writing successfully ESP_ERR_INVALID_ARG The handle is NULL ESP_ERR_INVALID_STATE The channel is not enabled or the 'on_convert_done' callback is not registered - - esp_err_t dac_continuous_stop_async_writing(dac_continuous_handle_t handle) Stop the sync writing. - Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' - Returns ESP_OK Stop asynchronous writing successfully ESP_ERR_INVALID_ARG The handle is NULL ESP_ERR_INVALID_STATE Asynchronous writing has not started - - esp_err_t dac_continuous_write_asynchronously(dac_continuous_handle_t handle, uint8_t *dma_buf, size_t dma_buf_len, const uint8_t *data, size_t data_len, size_t *bytes_loaded) Write DAC data asynchronously. Note This function can be called when the asynchronous writing started, and it can be called in the callback directly but recommend to writing data in a task, referring to :example: peripherals/dac/dac_continuous/dac_audio - Parameters handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels' dma_buf -- [in] The DMA buffer address, it can be acquired from 'dac_event_data_t' in the 'on_convert_done' callback dma_buf_len -- [in] The DMA buffer length, it can be acquired from 'dac_event_data_t' in the 'on_convert_done' callback data -- [in] The data that need to be written data_len -- [in] The data length the need to be written bytes_loaded -- [out] The bytes number that has been loaded/written into the DMA buffer - - Returns ESP_OK Write the data into DMA buffer successfully ESP_ERR_INVALID_ARG NULL pointer ESP_ERR_INVALID_STATE The channels haven't start the asynchronous writing ESP_ERR_NOT_FOUND The param 'dam_buf' not match any existed DMA buffer - Structures - struct dac_continuous_config_t DAC continuous channels' configurations. Public Members - dac_channel_mask_t chan_mask DAC channels' mask for selecting which channels are used - uint32_t desc_num The number of DMA descriptor, at least 2 descriptors are required The number of descriptors is directly proportional to the max data buffer size while converting in cyclic output but only need to ensure it is greater than '1' in acyclic output Typically, suggest to set the number bigger than 5, in case the DMA stopped while sending a short buffer - size_t buf_size The DMA buffer size, should be within 32~4092 bytes. Each DMA buffer will be attached to a DMA descriptor, i.e. the number of DMA buffer will be equal to the DMA descriptor number The DMA buffer size is not allowed to be greater than 4092 bytes The total DMA buffer size equal to desc_num * buf_sizeTypically, suggest to set the size to the multiple of 4 - uint32_t freq_hz The frequency of DAC conversion in continuous mode, unit: Hz The supported range is related to the target and the clock source. For the clock DAC_DIGI_CLK_SRC_DEFAULT: the range is 19.6 KHz to several MHz on ESP32 and 77 Hz to several MHz on ESP32-S2. For the clock DAC_DIGI_CLK_SRC_APLL: the range is 648 Hz to several MHz on ESP32 and 6 Hz to several MHz on ESP32-S2. Typically not suggest to set the frequency higher than 2 MHz, otherwise the severe distortion will appear - int8_t offset The offset of the DAC digital data. Range -128~127 - dac_continuous_digi_clk_src_t clk_src The clock source of digital controller, which can affect the range of supported frequency Currently DAC_DIGI_CLK_SRC_DEFAULTand DAC_DIGI_CLK_SRC_APLLare available - dac_continuous_channel_mode_t chan_mode The channel mode of continuous mode, only take effect when multiple channels enabled, depends converting the buffer alternately or simultaneously - dac_channel_mask_t chan_mask - struct dac_event_data_t Event structure used in DAC event queue. Public Members - void *buf The pointer of DMA buffer that just finished sending - size_t buf_size The writable buffer size of the DMA buffer, equal to 'dac_continuous_config_t::buf_size' - size_t write_bytes The number of bytes that be written successfully - void *buf - struct dac_event_callbacks_t Group of DAC callbacks. Note The callbacks are all running under ISR environment Note When CONFIG_DAC_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. Public Members - dac_isr_callback_t on_convert_done Callback of data conversion done event An event data buffer previously loaded to the driver has been output and converted. The event data includes DMA buffer address and size that just finished converting. - dac_isr_callback_t on_stop Callback of finished sending all the data. All loaded event data buffers are converted. Driver is pending for new data buffers to be loaded. The event data will be NULL in this callback. - dac_isr_callback_t on_convert_done Type Definitions - typedef struct dac_continuous_s *dac_continuous_handle_t DAC continuous channel handle - typedef bool (*dac_isr_callback_t)(dac_continuous_handle_t handle, const dac_event_data_t *event, void *user_data) DAC event callback. - Param handle [in] DAC channel handle, created from dac_continuous_new_channels() - Param event [in] DAC event data - Param user_data [in] User registered context, passed from dac_continuous_register_event_callback() - Return Whether a high priority task has been waken up by this callback function Enumerations Header File This header file can be included with: #include "driver/dac_types.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Type Definitions - typedef soc_periph_dac_digi_clk_src_t dac_continuous_digi_clk_src_t DAC DMA (digitial controller) clock source. - typedef soc_periph_dac_cosine_clk_src_t dac_cosine_clk_src_t DAC cosine wave generator clock source. Enumerations - enum dac_continuous_channel_mode_t DAC channel work mode in dma mode. Note Only take effect when multiple channels enabled. Note Assume the data in buffer is 'A B C D E F' DAC_CHANNEL_MODE_SIMUL: channel 0: A B C D E F channel 1: A B C D E F DAC_CHANNEL_MODE_ALTER: channel 0: A C E channel 1: B D F Values: - enumerator DAC_CHANNEL_MODE_SIMUL The data in the DMA buffer is simultaneously output to the enable channel of the DAC. - enumerator DAC_CHANNEL_MODE_ALTER The data in the DMA buffer is alternately output to the enable channel of the DAC. - Header File This header file can be included with: #include "hal/dac_types.h" Enumerations - enum dac_channel_t Values: - enumerator DAC_CHAN_0 DAC channel 0 is GPIO25(ESP32) / GPIO17(ESP32S2) - enumerator DAC_CHAN_1 DAC channel 1 is GPIO26(ESP32) / GPIO18(ESP32S2) - enumerator DAC_CHANNEL_1 Alias of 'DAC_CHAN_0', now the channel index start from '0' - enumerator DAC_CHANNEL_2 Alias of 'DAC_CHAN_1', now the channel index start from '0' - enumerator DAC_CHAN_0 - enum dac_cosine_atten_t The attenuation of the amplitude of the cosine wave generator. The max amplitude is VDD3P3_RTC. Values: - enumerator DAC_COSINE_ATTEN_DEFAULT No attenuation to the DAC cosine wave amplitude. Default. - enumerator DAC_COSINE_ATTEN_DB_0 Original amplitude of the DAC cosine wave, equals to DAC_COSINE_ATTEN_DEFAULT - enumerator DAC_COSINE_ATTEN_DB_6 1/2 amplitude of the DAC cosine wave - enumerator DAC_COSINE_ATTEN_DB_12 1/4 amplitude of the DAC cosine wave - enumerator DAC_COSINE_ATTEN_DB_18 1/8 amplitude of the DAC cosine wave - enumerator DAC_COSINE_ATTEN_DEFAULT
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/dac.html
ESP-IDF Programming Guide v5.2.1 documentation
null
GPIO & RTC GPIO
null
espressif.com
2016-01-01
9247da07153cb842
null
null
GPIO & RTC GPIO GPIO Summary The ESP32 chip features 34 physical GPIO pins (GPIO0 ~ GPIO19, GPIO21 ~ GPIO23, GPIO25 ~ GPIO27, and GPIO32 ~ GPIO39). Each pin can be used as a general-purpose I/O, or be connected to an internal peripheral signal. Through IO MUX, RTC IO MUX and the GPIO matrix, peripheral input signals can be from any IO pins, and peripheral output signals can be routed to any IO pins. Together these modules provide highly configurable I/O. For more details, see ESP32 Technical Reference Manual > IO MUX and GPIO Matrix (GPIO, IO_MUX) [PDF]. The table below provides more information on pin usage, and please note the comments in the table for GPIOs with restrictions. GPIO Analog Function RTC GPIO Comments GPIO0 ADC2_CH1 RTC_GPIO11 Strapping pin GPIO1 TXD GPIO2 ADC2_CH2 RTC_GPIO12 Strapping pin GPIO3 RXD GPIO4 ADC2_CH0 RTC_GPIO10 GPIO5 Strapping pin GPIO6 SPI0/1 GPIO7 SPI0/1 GPIO8 SPI0/1 GPIO9 SPI0/1 GPIO10 SPI0/1 GPIO11 SPI0/1 GPIO12 ADC2_CH5 RTC_GPIO15 Strapping pin; JTAG GPIO13 ADC2_CH4 RTC_GPIO14 JTAG GPIO14 ADC2_CH6 RTC_GPIO16 JTAG GPIO15 ADC2_CH3 RTC_GPIO13 Strapping pin; JTAG GPIO16 SPI0/1 GPIO17 SPI0/1 GPIO18 GPIO19 GPIO21 GPIO22 GPIO23 GPIO25 ADC2_CH8 RTC_GPIO6 GPIO26 ADC2_CH9 RTC_GPIO7 GPIO27 ADC2_CH7 RTC_GPIO17 GPIO32 ADC1_CH4 RTC_GPIO9 GPIO33 ADC1_CH5 RTC_GPIO8 GPIO34 ADC1_CH6 RTC_GPIO4 GPI GPIO35 ADC1_CH7 RTC_GPIO5 GPI GPIO36 ADC1_CH0 RTC_GPIO0 GPI GPIO37 ADC1_CH1 RTC_GPIO1 GPI GPIO38 ADC1_CH2 RTC_GPIO2 GPI GPIO39 ADC1_CH3 RTC_GPIO3 GPI Note Strapping pin: GPIO0, GPIO2, GPIO5, GPIO12 (MTDI), and GPIO15 (MTDO) are strapping pins. For more infomation, please refer to ESP32 datasheet. SPI0/1: GPIO6-11 and GPIO16-17 are usually connected to the SPI flash and PSRAM integrated on the module and therefore should not be used for other purposes. JTAG: GPIO12-15 are usually used for inline debug. GPI: GPIO34-39 can only be set as input mode and do not have software-enabled pullup or pulldown functions. TXD & RXD are usually used for flashing and debugging. ADC2: ADC2 pins cannot be used when Wi-Fi is used. So, if you are having trouble getting the value from an ADC2 GPIO while using Wi-Fi, you may consider using an ADC1 GPIO instead, which should solve your problem. For more details, please refer to Hardware Limitations of ADC Continuous Mode and Hardware Limitations of ADC Oneshot Mode. Please do not use the interrupt of GPIO36 and GPIO39 when using ADC or Wi-Fi and Bluetooth with sleep mode enabled. Please refer to ESP32 ECO and Workarounds for Bugs > Section 3.11 for the detailed description of the issue. GPIO driver offers a dump function gpio_dump_io_configuration() to show the configurations of the IOs at the moment, such as pull-up / pull-down, input / output enable, pin mapping etc. Below is an example dump: ================IO DUMP Start================ IO[4] - Pullup: 1, Pulldown: 0, DriveCap: 2 InputEn: 1, OutputEn: 0, OpenDrain: 0 FuncSel: 1 (GPIO) GPIO Matrix SigIn ID: (simple GPIO input) SleepSelEn: 1 IO[18] - Pullup: 0, Pulldown: 0, DriveCap: 2 InputEn: 0, OutputEn: 1, OpenDrain: 0 FuncSel: 1 (GPIO) GPIO Matrix SigOut ID: 256 (simple GPIO output) SleepSelEn: 1 IO[26] **RESERVED** - Pullup: 1, Pulldown: 0, DriveCap: 2 InputEn: 1, OutputEn: 0, OpenDrain: 0 FuncSel: 0 (IOMUX) SleepSelEn: 1 =================IO DUMP End================== If an IO pin is routed to a peripheral signal through the GPIO matrix, the signal ID printed in the dump information is defined in the soc/gpio_sig_map.h file. The word **RESERVED** indicates the IO is occupied by either FLASH or PSRAM. It is strongly not recommended to reconfigure them for other application purposes. There is also separate "RTC GPIO" support, which functions when GPIOs are routed to the "RTC" low-power and analog subsystem. These pin functions can be used when: In Deep-sleep mode The Ultra Low Power co-processor is running Analog functions such as ADC/DAC/etc are in use Application Example GPIO output and input interrupt example: peripherals/gpio/generic_gpio. API Reference - Normal GPIO Header File This header file can be included with: #include "driver/gpio.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t gpio_config(const gpio_config_t *pGPIOConfig) GPIO common configuration. Configure GPIO's Mode,pull-up,PullDown,IntrType Parameters pGPIOConfig -- Pointer to GPIO configure struct Returns ESP_OK success ESP_ERR_INVALID_ARG Parameter error ESP_OK success ESP_ERR_INVALID_ARG Parameter error ESP_OK success Parameters pGPIOConfig -- Pointer to GPIO configure struct Returns ESP_OK success ESP_ERR_INVALID_ARG Parameter error esp_err_t gpio_reset_pin(gpio_num_t gpio_num) Reset an gpio to default state (select gpio function, enable pullup and disable input and output). Note This function also configures the IOMUX for this pin to the GPIO function, and disconnects any other peripheral output configured via GPIO Matrix. Parameters gpio_num -- GPIO number. Returns Always return ESP_OK. Parameters gpio_num -- GPIO number. Returns Always return ESP_OK. esp_err_t gpio_set_intr_type(gpio_num_t gpio_num, gpio_int_type_t intr_type) GPIO set interrupt trigger type. Parameters gpio_num -- GPIO number. If you want to set the trigger type of e.g. of GPIO16, gpio_num should be GPIO_NUM_16 (16); intr_type -- Interrupt type, select from gpio_int_type_t gpio_num -- GPIO number. If you want to set the trigger type of e.g. of GPIO16, gpio_num should be GPIO_NUM_16 (16); intr_type -- Interrupt type, select from gpio_int_type_t gpio_num -- GPIO number. If you want to set the trigger type of e.g. of GPIO16, gpio_num should be GPIO_NUM_16 (16); Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- GPIO number. If you want to set the trigger type of e.g. of GPIO16, gpio_num should be GPIO_NUM_16 (16); intr_type -- Interrupt type, select from gpio_int_type_t Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t gpio_intr_enable(gpio_num_t gpio_num) Enable GPIO module interrupt signal. Note ESP32: Please do not use the interrupt of GPIO36 and GPIO39 when using ADC or Wi-Fi and Bluetooth with sleep mode enabled. Please refer to the comments of adc1_get_raw . Please refer to Section 3.11 of ESP32 ECO and Workarounds for Bugs for the description of this issue. Parameters gpio_num -- GPIO number. If you want to enable an interrupt on e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- GPIO number. If you want to enable an interrupt on e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t gpio_intr_disable(gpio_num_t gpio_num) Disable GPIO module interrupt signal. Note This function is allowed to be executed when Cache is disabled within ISR context, by enabling CONFIG_GPIO_CTRL_FUNC_IN_IRAM Parameters gpio_num -- GPIO number. If you want to disable the interrupt of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); Returns ESP_OK success ESP_ERR_INVALID_ARG Parameter error ESP_OK success ESP_ERR_INVALID_ARG Parameter error ESP_OK success Parameters gpio_num -- GPIO number. If you want to disable the interrupt of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); Returns ESP_OK success ESP_ERR_INVALID_ARG Parameter error esp_err_t gpio_set_level(gpio_num_t gpio_num, uint32_t level) GPIO set output level. Note This function is allowed to be executed when Cache is disabled within ISR context, by enabling CONFIG_GPIO_CTRL_FUNC_IN_IRAM Parameters gpio_num -- GPIO number. If you want to set the output level of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); level -- Output level. 0: low ; 1: high gpio_num -- GPIO number. If you want to set the output level of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); level -- Output level. 0: low ; 1: high gpio_num -- GPIO number. If you want to set the output level of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO number error ESP_OK Success ESP_ERR_INVALID_ARG GPIO number error ESP_OK Success Parameters gpio_num -- GPIO number. If you want to set the output level of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); level -- Output level. 0: low ; 1: high Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO number error int gpio_get_level(gpio_num_t gpio_num) GPIO get input level. Warning If the pad is not configured for input (or input and output) the returned value is always 0. Parameters gpio_num -- GPIO number. If you want to get the logic level of e.g. pin GPIO16, gpio_num should be GPIO_NUM_16 (16); Returns 0 the GPIO input level is 0 1 the GPIO input level is 1 0 the GPIO input level is 0 1 the GPIO input level is 1 0 the GPIO input level is 0 Parameters gpio_num -- GPIO number. If you want to get the logic level of e.g. pin GPIO16, gpio_num should be GPIO_NUM_16 (16); Returns 0 the GPIO input level is 0 1 the GPIO input level is 1 esp_err_t gpio_set_direction(gpio_num_t gpio_num, gpio_mode_t mode) GPIO set direction. Configure GPIO direction,such as output_only,input_only,output_and_input Parameters gpio_num -- Configure GPIO pins number, it should be GPIO number. If you want to set direction of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); mode -- GPIO direction gpio_num -- Configure GPIO pins number, it should be GPIO number. If you want to set direction of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); mode -- GPIO direction gpio_num -- Configure GPIO pins number, it should be GPIO number. If you want to set direction of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO error ESP_OK Success ESP_ERR_INVALID_ARG GPIO error ESP_OK Success Parameters gpio_num -- Configure GPIO pins number, it should be GPIO number. If you want to set direction of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); mode -- GPIO direction Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO error esp_err_t gpio_set_pull_mode(gpio_num_t gpio_num, gpio_pull_mode_t pull) Configure GPIO pull-up/pull-down resistors. Note ESP32: Only pins that support both input & output have integrated pull-up and pull-down resistors. Input-only GPIOs 34-39 do not. Parameters gpio_num -- GPIO number. If you want to set pull up or down mode for e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); pull -- GPIO pull up/down mode. gpio_num -- GPIO number. If you want to set pull up or down mode for e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); pull -- GPIO pull up/down mode. gpio_num -- GPIO number. If you want to set pull up or down mode for e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); Returns ESP_OK Success ESP_ERR_INVALID_ARG : Parameter error ESP_OK Success ESP_ERR_INVALID_ARG : Parameter error ESP_OK Success Parameters gpio_num -- GPIO number. If you want to set pull up or down mode for e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); pull -- GPIO pull up/down mode. Returns ESP_OK Success ESP_ERR_INVALID_ARG : Parameter error esp_err_t gpio_wakeup_enable(gpio_num_t gpio_num, gpio_int_type_t intr_type) Enable GPIO wake-up function. Parameters gpio_num -- GPIO number. intr_type -- GPIO wake-up type. Only GPIO_INTR_LOW_LEVEL or GPIO_INTR_HIGH_LEVEL can be used. gpio_num -- GPIO number. intr_type -- GPIO wake-up type. Only GPIO_INTR_LOW_LEVEL or GPIO_INTR_HIGH_LEVEL can be used. gpio_num -- GPIO number. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- GPIO number. intr_type -- GPIO wake-up type. Only GPIO_INTR_LOW_LEVEL or GPIO_INTR_HIGH_LEVEL can be used. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t gpio_wakeup_disable(gpio_num_t gpio_num) Disable GPIO wake-up function. Parameters gpio_num -- GPIO number Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- GPIO number Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t gpio_isr_register(void (*fn)(void*), void *arg, int intr_alloc_flags, gpio_isr_handle_t *handle) Register GPIO interrupt handler, the handler is an ISR. The handler will be attached to the same CPU core that this function is running on. This ISR function is called whenever any GPIO interrupt occurs. See the alternative gpio_install_isr_service() and gpio_isr_handler_add() API in order to have the driver support per-GPIO ISRs. To disable or remove the ISR, pass the returned handle to the interrupt allocation functions. Parameters fn -- Interrupt handler function. arg -- Parameter for handler function intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. handle -- Pointer to return handle. If non-NULL, a handle for the interrupt will be returned here. fn -- Interrupt handler function. arg -- Parameter for handler function intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. handle -- Pointer to return handle. If non-NULL, a handle for the interrupt will be returned here. fn -- Interrupt handler function. Returns ESP_OK Success ; ESP_ERR_INVALID_ARG GPIO error ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_OK Success ; ESP_ERR_INVALID_ARG GPIO error ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_OK Success ; Parameters fn -- Interrupt handler function. arg -- Parameter for handler function intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. handle -- Pointer to return handle. If non-NULL, a handle for the interrupt will be returned here. Returns ESP_OK Success ; ESP_ERR_INVALID_ARG GPIO error ESP_ERR_NOT_FOUND No free interrupt found with the specified flags esp_err_t gpio_pullup_en(gpio_num_t gpio_num) Enable pull-up on GPIO. Parameters gpio_num -- GPIO number Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- GPIO number Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t gpio_pullup_dis(gpio_num_t gpio_num) Disable pull-up on GPIO. Parameters gpio_num -- GPIO number Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- GPIO number Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t gpio_pulldown_en(gpio_num_t gpio_num) Enable pull-down on GPIO. Parameters gpio_num -- GPIO number Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- GPIO number Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t gpio_pulldown_dis(gpio_num_t gpio_num) Disable pull-down on GPIO. Parameters gpio_num -- GPIO number Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- GPIO number Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t gpio_install_isr_service(int intr_alloc_flags) Install the GPIO driver's ETS_GPIO_INTR_SOURCE ISR handler service, which allows per-pin GPIO interrupt handlers. This function is incompatible with gpio_isr_register() - if that function is used, a single global ISR is registered for all GPIO interrupts. If this function is used, the ISR service provides a global GPIO ISR and individual pin handlers are registered via the gpio_isr_handler_add() function. Parameters intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. Returns ESP_OK Success ESP_ERR_NO_MEM No memory to install this service ESP_ERR_INVALID_STATE ISR service already installed. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_ERR_INVALID_ARG GPIO error ESP_OK Success ESP_ERR_NO_MEM No memory to install this service ESP_ERR_INVALID_STATE ISR service already installed. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_ERR_INVALID_ARG GPIO error ESP_OK Success Parameters intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. Returns ESP_OK Success ESP_ERR_NO_MEM No memory to install this service ESP_ERR_INVALID_STATE ISR service already installed. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_ERR_INVALID_ARG GPIO error void gpio_uninstall_isr_service(void) Uninstall the driver's GPIO ISR service, freeing related resources. esp_err_t gpio_isr_handler_add(gpio_num_t gpio_num, gpio_isr_t isr_handler, void *args) Add ISR handler for the corresponding GPIO pin. Call this function after using gpio_install_isr_service() to install the driver's GPIO ISR handler service. The pin ISR handlers no longer need to be declared with IRAM_ATTR, unless you pass the ESP_INTR_FLAG_IRAM flag when allocating the ISR in gpio_install_isr_service(). This ISR handler will be called from an ISR. So there is a stack size limit (configurable as "ISR stack size" in menuconfig). This limit is smaller compared to a global GPIO interrupt handler due to the additional level of indirection. Parameters gpio_num -- GPIO number isr_handler -- ISR handler function for the corresponding GPIO number. args -- parameter for ISR handler. gpio_num -- GPIO number isr_handler -- ISR handler function for the corresponding GPIO number. args -- parameter for ISR handler. gpio_num -- GPIO number Returns ESP_OK Success ESP_ERR_INVALID_STATE Wrong state, the ISR service has not been initialized. ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_STATE Wrong state, the ISR service has not been initialized. ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- GPIO number isr_handler -- ISR handler function for the corresponding GPIO number. args -- parameter for ISR handler. Returns ESP_OK Success ESP_ERR_INVALID_STATE Wrong state, the ISR service has not been initialized. ESP_ERR_INVALID_ARG Parameter error esp_err_t gpio_isr_handler_remove(gpio_num_t gpio_num) Remove ISR handler for the corresponding GPIO pin. Parameters gpio_num -- GPIO number Returns ESP_OK Success ESP_ERR_INVALID_STATE Wrong state, the ISR service has not been initialized. ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_STATE Wrong state, the ISR service has not been initialized. ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- GPIO number Returns ESP_OK Success ESP_ERR_INVALID_STATE Wrong state, the ISR service has not been initialized. ESP_ERR_INVALID_ARG Parameter error esp_err_t gpio_set_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t strength) Set GPIO pad drive capability. Parameters gpio_num -- GPIO number, only support output GPIOs strength -- Drive capability of the pad gpio_num -- GPIO number, only support output GPIOs strength -- Drive capability of the pad gpio_num -- GPIO number, only support output GPIOs Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- GPIO number, only support output GPIOs strength -- Drive capability of the pad Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t gpio_get_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t *strength) Get GPIO pad drive capability. Parameters gpio_num -- GPIO number, only support output GPIOs strength -- Pointer to accept drive capability of the pad gpio_num -- GPIO number, only support output GPIOs strength -- Pointer to accept drive capability of the pad gpio_num -- GPIO number, only support output GPIOs Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- GPIO number, only support output GPIOs strength -- Pointer to accept drive capability of the pad Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t gpio_hold_en(gpio_num_t gpio_num) Enable gpio pad hold function. When a GPIO is set to hold, its state is latched at that moment and will not change when the internal signal or the IO MUX/GPIO configuration is modified (including input enable, output enable, output value, function, and drive strength values). This function can be used to retain the state of GPIOs when the chip or system is reset, for example, when watchdog time-out or Deep-sleep events are triggered. This function works in both input and output modes, and only applicable to output-capable GPIOs. If this function is enabled: in output mode: the output level of the GPIO will be locked and can not be changed. in input mode: the input read value can still reflect the changes of the input signal. However, on ESP32/S2/C3/S3/C2, this function cannot be used to hold the state of a digital GPIO during Deep-sleep. Even if this function is enabled, the digital GPIO will be reset to its default state when the chip wakes up from Deep-sleep. If you want to hold the state of a digital GPIO during Deep-sleep, please call gpio_deep_sleep_hold_en . Power down or call gpio_hold_dis will disable this function. Parameters gpio_num -- GPIO number, only support output-capable GPIOs Returns ESP_OK Success ESP_ERR_NOT_SUPPORTED Not support pad hold function ESP_OK Success ESP_ERR_NOT_SUPPORTED Not support pad hold function ESP_OK Success Parameters gpio_num -- GPIO number, only support output-capable GPIOs Returns ESP_OK Success ESP_ERR_NOT_SUPPORTED Not support pad hold function esp_err_t gpio_hold_dis(gpio_num_t gpio_num) Disable gpio pad hold function. When the chip is woken up from Deep-sleep, the gpio will be set to the default mode, so, the gpio will output the default level if this function is called. If you don't want the level changes, the gpio should be configured to a known state before this function is called. e.g. If you hold gpio18 high during Deep-sleep, after the chip is woken up and gpio_hold_dis is called, gpio18 will output low level(because gpio18 is input mode by default). If you don't want this behavior, you should configure gpio18 as output mode and set it to hight level before calling gpio_hold_dis . Parameters gpio_num -- GPIO number, only support output-capable GPIOs Returns ESP_OK Success ESP_ERR_NOT_SUPPORTED Not support pad hold function ESP_OK Success ESP_ERR_NOT_SUPPORTED Not support pad hold function ESP_OK Success Parameters gpio_num -- GPIO number, only support output-capable GPIOs Returns ESP_OK Success ESP_ERR_NOT_SUPPORTED Not support pad hold function void gpio_deep_sleep_hold_en(void) Enable all digital gpio pads hold function during Deep-sleep. Enabling this feature makes all digital gpio pads be at the holding state during Deep-sleep. The state of each pad holds is its active configuration (not pad's sleep configuration!). Note that this pad hold feature only works when the chip is in Deep-sleep mode. When the chip is in active mode, the digital gpio state can be changed freely even you have called this function. After this API is being called, the digital gpio Deep-sleep hold feature will work during every sleep process. You should call gpio_deep_sleep_hold_dis to disable this feature. void gpio_deep_sleep_hold_dis(void) Disable all digital gpio pads hold function during Deep-sleep. void gpio_iomux_in(uint32_t gpio_num, uint32_t signal_idx) SOC_GPIO_SUPPORT_HOLD_SINGLE_IO_IN_DSLP. Set pad input to a peripheral signal through the IOMUX. Parameters gpio_num -- GPIO number of the pad. signal_idx -- Peripheral signal id to input. One of the *_IN_IDX signals in soc/gpio_sig_map.h . gpio_num -- GPIO number of the pad. signal_idx -- Peripheral signal id to input. One of the *_IN_IDX signals in soc/gpio_sig_map.h . gpio_num -- GPIO number of the pad. Parameters gpio_num -- GPIO number of the pad. signal_idx -- Peripheral signal id to input. One of the *_IN_IDX signals in soc/gpio_sig_map.h . void gpio_iomux_out(uint8_t gpio_num, int func, bool oen_inv) Set peripheral output to an GPIO pad through the IOMUX. Parameters gpio_num -- gpio_num GPIO number of the pad. func -- The function number of the peripheral pin to output pin. One of the FUNC_X_* of specified pin (X) in soc/io_mux_reg.h . oen_inv -- True if the output enable needs to be inverted, otherwise False. gpio_num -- gpio_num GPIO number of the pad. func -- The function number of the peripheral pin to output pin. One of the FUNC_X_* of specified pin (X) in soc/io_mux_reg.h . oen_inv -- True if the output enable needs to be inverted, otherwise False. gpio_num -- gpio_num GPIO number of the pad. Parameters gpio_num -- gpio_num GPIO number of the pad. func -- The function number of the peripheral pin to output pin. One of the FUNC_X_* of specified pin (X) in soc/io_mux_reg.h . oen_inv -- True if the output enable needs to be inverted, otherwise False. esp_err_t gpio_sleep_sel_en(gpio_num_t gpio_num) Enable SLP_SEL to change GPIO status automantically in lightsleep. Parameters gpio_num -- GPIO number of the pad. Returns ESP_OK Success ESP_OK Success ESP_OK Success Parameters gpio_num -- GPIO number of the pad. Returns ESP_OK Success esp_err_t gpio_sleep_sel_dis(gpio_num_t gpio_num) Disable SLP_SEL to change GPIO status automantically in lightsleep. Parameters gpio_num -- GPIO number of the pad. Returns ESP_OK Success ESP_OK Success ESP_OK Success Parameters gpio_num -- GPIO number of the pad. Returns ESP_OK Success esp_err_t gpio_sleep_set_direction(gpio_num_t gpio_num, gpio_mode_t mode) GPIO set direction at sleep. Configure GPIO direction,such as output_only,input_only,output_and_input Parameters gpio_num -- Configure GPIO pins number, it should be GPIO number. If you want to set direction of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); mode -- GPIO direction gpio_num -- Configure GPIO pins number, it should be GPIO number. If you want to set direction of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); mode -- GPIO direction gpio_num -- Configure GPIO pins number, it should be GPIO number. If you want to set direction of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO error ESP_OK Success ESP_ERR_INVALID_ARG GPIO error ESP_OK Success Parameters gpio_num -- Configure GPIO pins number, it should be GPIO number. If you want to set direction of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); mode -- GPIO direction Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO error esp_err_t gpio_sleep_set_pull_mode(gpio_num_t gpio_num, gpio_pull_mode_t pull) Configure GPIO pull-up/pull-down resistors at sleep. Note ESP32: Only pins that support both input & output have integrated pull-up and pull-down resistors. Input-only GPIOs 34-39 do not. Parameters gpio_num -- GPIO number. If you want to set pull up or down mode for e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); pull -- GPIO pull up/down mode. gpio_num -- GPIO number. If you want to set pull up or down mode for e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); pull -- GPIO pull up/down mode. gpio_num -- GPIO number. If you want to set pull up or down mode for e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); Returns ESP_OK Success ESP_ERR_INVALID_ARG : Parameter error ESP_OK Success ESP_ERR_INVALID_ARG : Parameter error ESP_OK Success Parameters gpio_num -- GPIO number. If you want to set pull up or down mode for e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); pull -- GPIO pull up/down mode. Returns ESP_OK Success ESP_ERR_INVALID_ARG : Parameter error Structures struct gpio_config_t Configuration parameters of GPIO pad for gpio_config function. Public Members uint64_t pin_bit_mask GPIO pin: set with bit mask, each bit maps to a GPIO uint64_t pin_bit_mask GPIO pin: set with bit mask, each bit maps to a GPIO gpio_mode_t mode GPIO mode: set input/output mode gpio_mode_t mode GPIO mode: set input/output mode gpio_pullup_t pull_up_en GPIO pull-up gpio_pullup_t pull_up_en GPIO pull-up gpio_pulldown_t pull_down_en GPIO pull-down gpio_pulldown_t pull_down_en GPIO pull-down gpio_int_type_t intr_type GPIO interrupt type gpio_int_type_t intr_type GPIO interrupt type uint64_t pin_bit_mask Macros GPIO_PIN_COUNT GPIO_IS_VALID_GPIO(gpio_num) Check whether it is a valid GPIO number. GPIO_IS_VALID_OUTPUT_GPIO(gpio_num) Check whether it can be a valid GPIO number of output mode. GPIO_IS_VALID_DIGITAL_IO_PAD(gpio_num) Check whether it can be a valid digital I/O pad. Type Definitions typedef intr_handle_t gpio_isr_handle_t typedef void (*gpio_isr_t)(void *arg) GPIO interrupt handler. Param arg User registered data Param arg User registered data Header File This header file can be included with: #include "hal/gpio_types.h" Macros GPIO_PIN_REG_0 GPIO_PIN_REG_1 GPIO_PIN_REG_2 GPIO_PIN_REG_3 GPIO_PIN_REG_4 GPIO_PIN_REG_5 GPIO_PIN_REG_6 GPIO_PIN_REG_7 GPIO_PIN_REG_8 GPIO_PIN_REG_9 GPIO_PIN_REG_10 GPIO_PIN_REG_11 GPIO_PIN_REG_12 GPIO_PIN_REG_13 GPIO_PIN_REG_14 GPIO_PIN_REG_15 GPIO_PIN_REG_16 GPIO_PIN_REG_17 GPIO_PIN_REG_18 GPIO_PIN_REG_19 GPIO_PIN_REG_20 GPIO_PIN_REG_21 GPIO_PIN_REG_22 GPIO_PIN_REG_23 GPIO_PIN_REG_24 GPIO_PIN_REG_25 GPIO_PIN_REG_26 GPIO_PIN_REG_27 GPIO_PIN_REG_28 GPIO_PIN_REG_29 GPIO_PIN_REG_30 GPIO_PIN_REG_31 GPIO_PIN_REG_32 GPIO_PIN_REG_33 GPIO_PIN_REG_34 GPIO_PIN_REG_35 GPIO_PIN_REG_36 GPIO_PIN_REG_37 GPIO_PIN_REG_38 GPIO_PIN_REG_39 GPIO_PIN_REG_40 GPIO_PIN_REG_41 GPIO_PIN_REG_42 GPIO_PIN_REG_43 GPIO_PIN_REG_44 GPIO_PIN_REG_45 GPIO_PIN_REG_46 GPIO_PIN_REG_47 GPIO_PIN_REG_48 GPIO_PIN_REG_49 GPIO_PIN_REG_50 GPIO_PIN_REG_51 GPIO_PIN_REG_52 GPIO_PIN_REG_53 GPIO_PIN_REG_54 GPIO_PIN_REG_55 GPIO_PIN_REG_56 Enumerations enum gpio_int_type_t Values: enumerator GPIO_INTR_DISABLE Disable GPIO interrupt enumerator GPIO_INTR_DISABLE Disable GPIO interrupt enumerator GPIO_INTR_POSEDGE GPIO interrupt type : rising edge enumerator GPIO_INTR_POSEDGE GPIO interrupt type : rising edge enumerator GPIO_INTR_NEGEDGE GPIO interrupt type : falling edge enumerator GPIO_INTR_NEGEDGE GPIO interrupt type : falling edge enumerator GPIO_INTR_ANYEDGE GPIO interrupt type : both rising and falling edge enumerator GPIO_INTR_ANYEDGE GPIO interrupt type : both rising and falling edge enumerator GPIO_INTR_LOW_LEVEL GPIO interrupt type : input low level trigger enumerator GPIO_INTR_LOW_LEVEL GPIO interrupt type : input low level trigger enumerator GPIO_INTR_HIGH_LEVEL GPIO interrupt type : input high level trigger enumerator GPIO_INTR_HIGH_LEVEL GPIO interrupt type : input high level trigger enumerator GPIO_INTR_MAX enumerator GPIO_INTR_MAX enumerator GPIO_INTR_DISABLE enum gpio_mode_t Values: enumerator GPIO_MODE_DISABLE GPIO mode : disable input and output enumerator GPIO_MODE_DISABLE GPIO mode : disable input and output enumerator GPIO_MODE_INPUT GPIO mode : input only enumerator GPIO_MODE_INPUT GPIO mode : input only enumerator GPIO_MODE_OUTPUT GPIO mode : output only mode enumerator GPIO_MODE_OUTPUT GPIO mode : output only mode enumerator GPIO_MODE_OUTPUT_OD GPIO mode : output only with open-drain mode enumerator GPIO_MODE_OUTPUT_OD GPIO mode : output only with open-drain mode enumerator GPIO_MODE_INPUT_OUTPUT_OD GPIO mode : output and input with open-drain mode enumerator GPIO_MODE_INPUT_OUTPUT_OD GPIO mode : output and input with open-drain mode enumerator GPIO_MODE_INPUT_OUTPUT GPIO mode : output and input mode enumerator GPIO_MODE_INPUT_OUTPUT GPIO mode : output and input mode enumerator GPIO_MODE_DISABLE enum gpio_pullup_t Values: enumerator GPIO_PULLUP_DISABLE Disable GPIO pull-up resistor enumerator GPIO_PULLUP_DISABLE Disable GPIO pull-up resistor enumerator GPIO_PULLUP_ENABLE Enable GPIO pull-up resistor enumerator GPIO_PULLUP_ENABLE Enable GPIO pull-up resistor enumerator GPIO_PULLUP_DISABLE enum gpio_pulldown_t Values: enumerator GPIO_PULLDOWN_DISABLE Disable GPIO pull-down resistor enumerator GPIO_PULLDOWN_DISABLE Disable GPIO pull-down resistor enumerator GPIO_PULLDOWN_ENABLE Enable GPIO pull-down resistor enumerator GPIO_PULLDOWN_ENABLE Enable GPIO pull-down resistor enumerator GPIO_PULLDOWN_DISABLE enum gpio_pull_mode_t Values: enumerator GPIO_PULLUP_ONLY Pad pull up enumerator GPIO_PULLUP_ONLY Pad pull up enumerator GPIO_PULLDOWN_ONLY Pad pull down enumerator GPIO_PULLDOWN_ONLY Pad pull down enumerator GPIO_PULLUP_PULLDOWN Pad pull up + pull down enumerator GPIO_PULLUP_PULLDOWN Pad pull up + pull down enumerator GPIO_FLOATING Pad floating enumerator GPIO_FLOATING Pad floating enumerator GPIO_PULLUP_ONLY enum gpio_drive_cap_t Values: enumerator GPIO_DRIVE_CAP_0 Pad drive capability: weak enumerator GPIO_DRIVE_CAP_0 Pad drive capability: weak enumerator GPIO_DRIVE_CAP_1 Pad drive capability: stronger enumerator GPIO_DRIVE_CAP_1 Pad drive capability: stronger enumerator GPIO_DRIVE_CAP_2 Pad drive capability: medium enumerator GPIO_DRIVE_CAP_2 Pad drive capability: medium enumerator GPIO_DRIVE_CAP_DEFAULT Pad drive capability: medium enumerator GPIO_DRIVE_CAP_DEFAULT Pad drive capability: medium enumerator GPIO_DRIVE_CAP_3 Pad drive capability: strongest enumerator GPIO_DRIVE_CAP_3 Pad drive capability: strongest enumerator GPIO_DRIVE_CAP_MAX enumerator GPIO_DRIVE_CAP_MAX enumerator GPIO_DRIVE_CAP_0 API Reference - RTC GPIO Header File This header file can be included with: #include "driver/rtc_io.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions bool rtc_gpio_is_valid_gpio(gpio_num_t gpio_num) Determine if the specified GPIO is a valid RTC GPIO. Parameters gpio_num -- GPIO number Returns true if GPIO is valid for RTC GPIO use. false otherwise. Parameters gpio_num -- GPIO number Returns true if GPIO is valid for RTC GPIO use. false otherwise. int rtc_io_number_get(gpio_num_t gpio_num) Get RTC IO index number by gpio number. Parameters gpio_num -- GPIO number Returns >=0: Index of rtcio. -1 : The gpio is not rtcio. Parameters gpio_num -- GPIO number Returns >=0: Index of rtcio. -1 : The gpio is not rtcio. esp_err_t rtc_gpio_init(gpio_num_t gpio_num) Init a GPIO as RTC GPIO. This function must be called when initializing a pad for an analog function. Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK success Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK success ESP_ERR_INVALID_ARG GPIO is not an RTC IO esp_err_t rtc_gpio_deinit(gpio_num_t gpio_num) Init a GPIO as digital GPIO. Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK success Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK success ESP_ERR_INVALID_ARG GPIO is not an RTC IO uint32_t rtc_gpio_get_level(gpio_num_t gpio_num) Get the RTC IO input level. Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns 1 High level 0 Low level ESP_ERR_INVALID_ARG GPIO is not an RTC IO 1 High level 0 Low level ESP_ERR_INVALID_ARG GPIO is not an RTC IO 1 High level Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns 1 High level 0 Low level ESP_ERR_INVALID_ARG GPIO is not an RTC IO esp_err_t rtc_gpio_set_level(gpio_num_t gpio_num, uint32_t level) Set the RTC IO output level. Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) level -- output level gpio_num -- GPIO number (e.g. GPIO_NUM_12) level -- output level gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) level -- output level Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO esp_err_t rtc_gpio_set_direction(gpio_num_t gpio_num, rtc_gpio_mode_t mode) RTC GPIO set direction. Configure RTC GPIO direction, such as output only, input only, output and input. Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) mode -- GPIO direction gpio_num -- GPIO number (e.g. GPIO_NUM_12) mode -- GPIO direction gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) mode -- GPIO direction Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO esp_err_t rtc_gpio_set_direction_in_sleep(gpio_num_t gpio_num, rtc_gpio_mode_t mode) RTC GPIO set direction in deep sleep mode or disable sleep status (default). In some application scenarios, IO needs to have another states during deep sleep. NOTE: ESP32 supports INPUT_ONLY mode. The rest targets support INPUT_ONLY, OUTPUT_ONLY, INPUT_OUTPUT mode. Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) mode -- GPIO direction gpio_num -- GPIO number (e.g. GPIO_NUM_12) mode -- GPIO direction gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) mode -- GPIO direction Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO esp_err_t rtc_gpio_pullup_en(gpio_num_t gpio_num) RTC GPIO pullup enable. This function only works for RTC IOs. In general, call gpio_pullup_en, which will work both for normal GPIOs and RTC IOs. Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO esp_err_t rtc_gpio_pulldown_en(gpio_num_t gpio_num) RTC GPIO pulldown enable. This function only works for RTC IOs. In general, call gpio_pulldown_en, which will work both for normal GPIOs and RTC IOs. Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO esp_err_t rtc_gpio_pullup_dis(gpio_num_t gpio_num) RTC GPIO pullup disable. This function only works for RTC IOs. In general, call gpio_pullup_dis, which will work both for normal GPIOs and RTC IOs. Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO esp_err_t rtc_gpio_pulldown_dis(gpio_num_t gpio_num) RTC GPIO pulldown disable. This function only works for RTC IOs. In general, call gpio_pulldown_dis, which will work both for normal GPIOs and RTC IOs. Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO esp_err_t rtc_gpio_set_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t strength) Set RTC GPIO pad drive capability. Parameters gpio_num -- GPIO number, only support output GPIOs strength -- Drive capability of the pad gpio_num -- GPIO number, only support output GPIOs strength -- Drive capability of the pad gpio_num -- GPIO number, only support output GPIOs Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- GPIO number, only support output GPIOs strength -- Drive capability of the pad Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t rtc_gpio_get_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t *strength) Get RTC GPIO pad drive capability. Parameters gpio_num -- GPIO number, only support output GPIOs strength -- Pointer to accept drive capability of the pad gpio_num -- GPIO number, only support output GPIOs strength -- Pointer to accept drive capability of the pad gpio_num -- GPIO number, only support output GPIOs Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- GPIO number, only support output GPIOs strength -- Pointer to accept drive capability of the pad Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t rtc_gpio_iomux_func_sel(gpio_num_t gpio_num, int func) Select a RTC IOMUX function for the RTC IO. Parameters gpio_num -- GPIO number func -- Function to assign to the pin gpio_num -- GPIO number func -- Function to assign to the pin gpio_num -- GPIO number Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- GPIO number func -- Function to assign to the pin Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t rtc_gpio_hold_en(gpio_num_t gpio_num) Enable hold function on an RTC IO pad. Enabling HOLD function will cause the pad to latch current values of input enable, output enable, output value, function, drive strength values. This function is useful when going into light or deep sleep mode to prevent the pin configuration from changing. Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO esp_err_t rtc_gpio_hold_dis(gpio_num_t gpio_num) Disable hold function on an RTC IO pad. Disabling hold function will allow the pad receive the values of input enable, output enable, output value, function, drive strength from RTC_IO peripheral. Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO ESP_OK Success Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO esp_err_t rtc_gpio_force_hold_en_all(void) Enable force hold signal for all RTC IOs. Each RTC pad has a "force hold" input signal from the RTC controller. If this signal is set, pad latches current values of input enable, function, output enable, and other signals which come from the RTC mux. Force hold signal is enabled before going into deep sleep for pins which are used for EXT1 wakeup. esp_err_t rtc_gpio_wakeup_enable(gpio_num_t gpio_num, gpio_int_type_t intr_type) Enable wakeup from sleep mode using specific GPIO. Parameters gpio_num -- GPIO number intr_type -- Wakeup on high level (GPIO_INTR_HIGH_LEVEL) or low level (GPIO_INTR_LOW_LEVEL) gpio_num -- GPIO number intr_type -- Wakeup on high level (GPIO_INTR_HIGH_LEVEL) or low level (GPIO_INTR_LOW_LEVEL) gpio_num -- GPIO number Returns ESP_OK on success ESP_ERR_INVALID_ARG if gpio_num is not an RTC IO, or intr_type is not one of GPIO_INTR_HIGH_LEVEL, GPIO_INTR_LOW_LEVEL. ESP_OK on success ESP_ERR_INVALID_ARG if gpio_num is not an RTC IO, or intr_type is not one of GPIO_INTR_HIGH_LEVEL, GPIO_INTR_LOW_LEVEL. ESP_OK on success Parameters gpio_num -- GPIO number intr_type -- Wakeup on high level (GPIO_INTR_HIGH_LEVEL) or low level (GPIO_INTR_LOW_LEVEL) Returns ESP_OK on success ESP_ERR_INVALID_ARG if gpio_num is not an RTC IO, or intr_type is not one of GPIO_INTR_HIGH_LEVEL, GPIO_INTR_LOW_LEVEL. Macros RTC_GPIO_IS_VALID_GPIO(gpio_num) Header File This header file can be included with: #include "driver/lp_io.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Header File This header file can be included with: #include "hal/rtc_io_types.h" Enumerations enum rtc_gpio_mode_t RTCIO output/input mode type. Values: enumerator RTC_GPIO_MODE_INPUT_ONLY Pad input enumerator RTC_GPIO_MODE_INPUT_ONLY Pad input enumerator RTC_GPIO_MODE_OUTPUT_ONLY Pad output enumerator RTC_GPIO_MODE_OUTPUT_ONLY Pad output enumerator RTC_GPIO_MODE_INPUT_OUTPUT Pad input + output enumerator RTC_GPIO_MODE_INPUT_OUTPUT Pad input + output enumerator RTC_GPIO_MODE_DISABLED Pad (output + input) disable enumerator RTC_GPIO_MODE_DISABLED Pad (output + input) disable enumerator RTC_GPIO_MODE_OUTPUT_OD Pad open-drain output enumerator RTC_GPIO_MODE_OUTPUT_OD Pad open-drain output enumerator RTC_GPIO_MODE_INPUT_OUTPUT_OD Pad input + open-drain output enumerator RTC_GPIO_MODE_INPUT_OUTPUT_OD Pad input + open-drain output enumerator RTC_GPIO_MODE_INPUT_ONLY
GPIO & RTC GPIO GPIO Summary The ESP32 chip features 34 physical GPIO pins (GPIO0 ~ GPIO19, GPIO21 ~ GPIO23, GPIO25 ~ GPIO27, and GPIO32 ~ GPIO39). Each pin can be used as a general-purpose I/O, or be connected to an internal peripheral signal. Through IO MUX, RTC IO MUX and the GPIO matrix, peripheral input signals can be from any IO pins, and peripheral output signals can be routed to any IO pins. Together these modules provide highly configurable I/O. For more details, see ESP32 Technical Reference Manual > IO MUX and GPIO Matrix (GPIO, IO_MUX) [PDF]. The table below provides more information on pin usage, and please note the comments in the table for GPIOs with restrictions. | GPIO | Analog Function | RTC GPIO | Comments | GPIO0 | ADC2_CH1 | RTC_GPIO11 | Strapping pin | GPIO1 | TXD | GPIO2 | ADC2_CH2 | RTC_GPIO12 | Strapping pin | GPIO3 | RXD | GPIO4 | ADC2_CH0 | RTC_GPIO10 | GPIO5 | Strapping pin | GPIO6 | SPI0/1 | GPIO7 | SPI0/1 | GPIO8 | SPI0/1 | GPIO9 | SPI0/1 | GPIO10 | SPI0/1 | GPIO11 | SPI0/1 | GPIO12 | ADC2_CH5 | RTC_GPIO15 | Strapping pin; JTAG | GPIO13 | ADC2_CH4 | RTC_GPIO14 | JTAG | GPIO14 | ADC2_CH6 | RTC_GPIO16 | JTAG | GPIO15 | ADC2_CH3 | RTC_GPIO13 | Strapping pin; JTAG | GPIO16 | SPI0/1 | GPIO17 | SPI0/1 | GPIO18 | GPIO19 | GPIO21 | GPIO22 | GPIO23 | GPIO25 | ADC2_CH8 | RTC_GPIO6 | GPIO26 | ADC2_CH9 | RTC_GPIO7 | GPIO27 | ADC2_CH7 | RTC_GPIO17 | GPIO32 | ADC1_CH4 | RTC_GPIO9 | GPIO33 | ADC1_CH5 | RTC_GPIO8 | GPIO34 | ADC1_CH6 | RTC_GPIO4 | GPI | GPIO35 | ADC1_CH7 | RTC_GPIO5 | GPI | GPIO36 | ADC1_CH0 | RTC_GPIO0 | GPI | GPIO37 | ADC1_CH1 | RTC_GPIO1 | GPI | GPIO38 | ADC1_CH2 | RTC_GPIO2 | GPI | GPIO39 | ADC1_CH3 | RTC_GPIO3 | GPI Note Strapping pin: GPIO0, GPIO2, GPIO5, GPIO12 (MTDI), and GPIO15 (MTDO) are strapping pins. For more infomation, please refer to ESP32 datasheet. SPI0/1: GPIO6-11 and GPIO16-17 are usually connected to the SPI flash and PSRAM integrated on the module and therefore should not be used for other purposes. JTAG: GPIO12-15 are usually used for inline debug. GPI: GPIO34-39 can only be set as input mode and do not have software-enabled pullup or pulldown functions. TXD & RXD are usually used for flashing and debugging. ADC2: ADC2 pins cannot be used when Wi-Fi is used. So, if you are having trouble getting the value from an ADC2 GPIO while using Wi-Fi, you may consider using an ADC1 GPIO instead, which should solve your problem. For more details, please refer to Hardware Limitations of ADC Continuous Mode and Hardware Limitations of ADC Oneshot Mode. Please do not use the interrupt of GPIO36 and GPIO39 when using ADC or Wi-Fi and Bluetooth with sleep mode enabled. Please refer to ESP32 ECO and Workarounds for Bugs > Section 3.11 for the detailed description of the issue. GPIO driver offers a dump function gpio_dump_io_configuration() to show the configurations of the IOs at the moment, such as pull-up / pull-down, input / output enable, pin mapping etc. Below is an example dump: ================IO DUMP Start================ IO[4] - Pullup: 1, Pulldown: 0, DriveCap: 2 InputEn: 1, OutputEn: 0, OpenDrain: 0 FuncSel: 1 (GPIO) GPIO Matrix SigIn ID: (simple GPIO input) SleepSelEn: 1 IO[18] - Pullup: 0, Pulldown: 0, DriveCap: 2 InputEn: 0, OutputEn: 1, OpenDrain: 0 FuncSel: 1 (GPIO) GPIO Matrix SigOut ID: 256 (simple GPIO output) SleepSelEn: 1 IO[26] **RESERVED** - Pullup: 1, Pulldown: 0, DriveCap: 2 InputEn: 1, OutputEn: 0, OpenDrain: 0 FuncSel: 0 (IOMUX) SleepSelEn: 1 =================IO DUMP End================== If an IO pin is routed to a peripheral signal through the GPIO matrix, the signal ID printed in the dump information is defined in the soc/gpio_sig_map.h file. The word **RESERVED** indicates the IO is occupied by either FLASH or PSRAM. It is strongly not recommended to reconfigure them for other application purposes. There is also separate "RTC GPIO" support, which functions when GPIOs are routed to the "RTC" low-power and analog subsystem. These pin functions can be used when: In Deep-sleep mode The Ultra Low Power co-processor is running Analog functions such as ADC/DAC/etc are in use Application Example GPIO output and input interrupt example: peripherals/gpio/generic_gpio. API Reference - Normal GPIO Header File This header file can be included with: #include "driver/gpio.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t gpio_config(const gpio_config_t *pGPIOConfig) GPIO common configuration. Configure GPIO's Mode,pull-up,PullDown,IntrType - Parameters pGPIOConfig -- Pointer to GPIO configure struct - Returns ESP_OK success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t gpio_reset_pin(gpio_num_t gpio_num) Reset an gpio to default state (select gpio function, enable pullup and disable input and output). Note This function also configures the IOMUX for this pin to the GPIO function, and disconnects any other peripheral output configured via GPIO Matrix. - Parameters gpio_num -- GPIO number. - Returns Always return ESP_OK. - esp_err_t gpio_set_intr_type(gpio_num_t gpio_num, gpio_int_type_t intr_type) GPIO set interrupt trigger type. - Parameters gpio_num -- GPIO number. If you want to set the trigger type of e.g. of GPIO16, gpio_num should be GPIO_NUM_16 (16); intr_type -- Interrupt type, select from gpio_int_type_t - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t gpio_intr_enable(gpio_num_t gpio_num) Enable GPIO module interrupt signal. Note ESP32: Please do not use the interrupt of GPIO36 and GPIO39 when using ADC or Wi-Fi and Bluetooth with sleep mode enabled. Please refer to the comments of adc1_get_raw. Please refer to Section 3.11 of ESP32 ECO and Workarounds for Bugs for the description of this issue. - Parameters gpio_num -- GPIO number. If you want to enable an interrupt on e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t gpio_intr_disable(gpio_num_t gpio_num) Disable GPIO module interrupt signal. Note This function is allowed to be executed when Cache is disabled within ISR context, by enabling CONFIG_GPIO_CTRL_FUNC_IN_IRAM - Parameters gpio_num -- GPIO number. If you want to disable the interrupt of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); - Returns ESP_OK success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t gpio_set_level(gpio_num_t gpio_num, uint32_t level) GPIO set output level. Note This function is allowed to be executed when Cache is disabled within ISR context, by enabling CONFIG_GPIO_CTRL_FUNC_IN_IRAM - Parameters gpio_num -- GPIO number. If you want to set the output level of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); level -- Output level. 0: low ; 1: high - - Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO number error - - int gpio_get_level(gpio_num_t gpio_num) GPIO get input level. Warning If the pad is not configured for input (or input and output) the returned value is always 0. - Parameters gpio_num -- GPIO number. If you want to get the logic level of e.g. pin GPIO16, gpio_num should be GPIO_NUM_16 (16); - Returns 0 the GPIO input level is 0 1 the GPIO input level is 1 - - esp_err_t gpio_set_direction(gpio_num_t gpio_num, gpio_mode_t mode) GPIO set direction. Configure GPIO direction,such as output_only,input_only,output_and_input - Parameters gpio_num -- Configure GPIO pins number, it should be GPIO number. If you want to set direction of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); mode -- GPIO direction - - Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO error - - esp_err_t gpio_set_pull_mode(gpio_num_t gpio_num, gpio_pull_mode_t pull) Configure GPIO pull-up/pull-down resistors. Note ESP32: Only pins that support both input & output have integrated pull-up and pull-down resistors. Input-only GPIOs 34-39 do not. - Parameters gpio_num -- GPIO number. If you want to set pull up or down mode for e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); pull -- GPIO pull up/down mode. - - Returns ESP_OK Success ESP_ERR_INVALID_ARG : Parameter error - - esp_err_t gpio_wakeup_enable(gpio_num_t gpio_num, gpio_int_type_t intr_type) Enable GPIO wake-up function. - Parameters gpio_num -- GPIO number. intr_type -- GPIO wake-up type. Only GPIO_INTR_LOW_LEVEL or GPIO_INTR_HIGH_LEVEL can be used. - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t gpio_wakeup_disable(gpio_num_t gpio_num) Disable GPIO wake-up function. - Parameters gpio_num -- GPIO number - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t gpio_isr_register(void (*fn)(void*), void *arg, int intr_alloc_flags, gpio_isr_handle_t *handle) Register GPIO interrupt handler, the handler is an ISR. The handler will be attached to the same CPU core that this function is running on. This ISR function is called whenever any GPIO interrupt occurs. See the alternative gpio_install_isr_service() and gpio_isr_handler_add() API in order to have the driver support per-GPIO ISRs. To disable or remove the ISR, pass the returned handle to the interrupt allocation functions. - Parameters fn -- Interrupt handler function. arg -- Parameter for handler function intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. handle -- Pointer to return handle. If non-NULL, a handle for the interrupt will be returned here. - - Returns ESP_OK Success ; ESP_ERR_INVALID_ARG GPIO error ESP_ERR_NOT_FOUND No free interrupt found with the specified flags - - esp_err_t gpio_pullup_en(gpio_num_t gpio_num) Enable pull-up on GPIO. - Parameters gpio_num -- GPIO number - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t gpio_pullup_dis(gpio_num_t gpio_num) Disable pull-up on GPIO. - Parameters gpio_num -- GPIO number - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t gpio_pulldown_en(gpio_num_t gpio_num) Enable pull-down on GPIO. - Parameters gpio_num -- GPIO number - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t gpio_pulldown_dis(gpio_num_t gpio_num) Disable pull-down on GPIO. - Parameters gpio_num -- GPIO number - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t gpio_install_isr_service(int intr_alloc_flags) Install the GPIO driver's ETS_GPIO_INTR_SOURCE ISR handler service, which allows per-pin GPIO interrupt handlers. This function is incompatible with gpio_isr_register() - if that function is used, a single global ISR is registered for all GPIO interrupts. If this function is used, the ISR service provides a global GPIO ISR and individual pin handlers are registered via the gpio_isr_handler_add() function. - Parameters intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. - Returns ESP_OK Success ESP_ERR_NO_MEM No memory to install this service ESP_ERR_INVALID_STATE ISR service already installed. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_ERR_INVALID_ARG GPIO error - - void gpio_uninstall_isr_service(void) Uninstall the driver's GPIO ISR service, freeing related resources. - esp_err_t gpio_isr_handler_add(gpio_num_t gpio_num, gpio_isr_t isr_handler, void *args) Add ISR handler for the corresponding GPIO pin. Call this function after using gpio_install_isr_service() to install the driver's GPIO ISR handler service. The pin ISR handlers no longer need to be declared with IRAM_ATTR, unless you pass the ESP_INTR_FLAG_IRAM flag when allocating the ISR in gpio_install_isr_service(). This ISR handler will be called from an ISR. So there is a stack size limit (configurable as "ISR stack size" in menuconfig). This limit is smaller compared to a global GPIO interrupt handler due to the additional level of indirection. - Parameters gpio_num -- GPIO number isr_handler -- ISR handler function for the corresponding GPIO number. args -- parameter for ISR handler. - - Returns ESP_OK Success ESP_ERR_INVALID_STATE Wrong state, the ISR service has not been initialized. ESP_ERR_INVALID_ARG Parameter error - - esp_err_t gpio_isr_handler_remove(gpio_num_t gpio_num) Remove ISR handler for the corresponding GPIO pin. - Parameters gpio_num -- GPIO number - Returns ESP_OK Success ESP_ERR_INVALID_STATE Wrong state, the ISR service has not been initialized. ESP_ERR_INVALID_ARG Parameter error - - esp_err_t gpio_set_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t strength) Set GPIO pad drive capability. - Parameters gpio_num -- GPIO number, only support output GPIOs strength -- Drive capability of the pad - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t gpio_get_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t *strength) Get GPIO pad drive capability. - Parameters gpio_num -- GPIO number, only support output GPIOs strength -- Pointer to accept drive capability of the pad - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t gpio_hold_en(gpio_num_t gpio_num) Enable gpio pad hold function. When a GPIO is set to hold, its state is latched at that moment and will not change when the internal signal or the IO MUX/GPIO configuration is modified (including input enable, output enable, output value, function, and drive strength values). This function can be used to retain the state of GPIOs when the chip or system is reset, for example, when watchdog time-out or Deep-sleep events are triggered. This function works in both input and output modes, and only applicable to output-capable GPIOs. If this function is enabled: in output mode: the output level of the GPIO will be locked and can not be changed. in input mode: the input read value can still reflect the changes of the input signal. However, on ESP32/S2/C3/S3/C2, this function cannot be used to hold the state of a digital GPIO during Deep-sleep. Even if this function is enabled, the digital GPIO will be reset to its default state when the chip wakes up from Deep-sleep. If you want to hold the state of a digital GPIO during Deep-sleep, please call gpio_deep_sleep_hold_en. Power down or call gpio_hold_diswill disable this function. - Parameters gpio_num -- GPIO number, only support output-capable GPIOs - Returns ESP_OK Success ESP_ERR_NOT_SUPPORTED Not support pad hold function - - esp_err_t gpio_hold_dis(gpio_num_t gpio_num) Disable gpio pad hold function. When the chip is woken up from Deep-sleep, the gpio will be set to the default mode, so, the gpio will output the default level if this function is called. If you don't want the level changes, the gpio should be configured to a known state before this function is called. e.g. If you hold gpio18 high during Deep-sleep, after the chip is woken up and gpio_hold_disis called, gpio18 will output low level(because gpio18 is input mode by default). If you don't want this behavior, you should configure gpio18 as output mode and set it to hight level before calling gpio_hold_dis. - Parameters gpio_num -- GPIO number, only support output-capable GPIOs - Returns ESP_OK Success ESP_ERR_NOT_SUPPORTED Not support pad hold function - - void gpio_deep_sleep_hold_en(void) Enable all digital gpio pads hold function during Deep-sleep. Enabling this feature makes all digital gpio pads be at the holding state during Deep-sleep. The state of each pad holds is its active configuration (not pad's sleep configuration!). Note that this pad hold feature only works when the chip is in Deep-sleep mode. When the chip is in active mode, the digital gpio state can be changed freely even you have called this function. After this API is being called, the digital gpio Deep-sleep hold feature will work during every sleep process. You should call gpio_deep_sleep_hold_disto disable this feature. - void gpio_deep_sleep_hold_dis(void) Disable all digital gpio pads hold function during Deep-sleep. - void gpio_iomux_in(uint32_t gpio_num, uint32_t signal_idx) SOC_GPIO_SUPPORT_HOLD_SINGLE_IO_IN_DSLP. Set pad input to a peripheral signal through the IOMUX. - Parameters gpio_num -- GPIO number of the pad. signal_idx -- Peripheral signal id to input. One of the *_IN_IDXsignals in soc/gpio_sig_map.h. - - void gpio_iomux_out(uint8_t gpio_num, int func, bool oen_inv) Set peripheral output to an GPIO pad through the IOMUX. - Parameters gpio_num -- gpio_num GPIO number of the pad. func -- The function number of the peripheral pin to output pin. One of the FUNC_X_*of specified pin (X) in soc/io_mux_reg.h. oen_inv -- True if the output enable needs to be inverted, otherwise False. - - esp_err_t gpio_sleep_sel_en(gpio_num_t gpio_num) Enable SLP_SEL to change GPIO status automantically in lightsleep. - Parameters gpio_num -- GPIO number of the pad. - Returns ESP_OK Success - - esp_err_t gpio_sleep_sel_dis(gpio_num_t gpio_num) Disable SLP_SEL to change GPIO status automantically in lightsleep. - Parameters gpio_num -- GPIO number of the pad. - Returns ESP_OK Success - - esp_err_t gpio_sleep_set_direction(gpio_num_t gpio_num, gpio_mode_t mode) GPIO set direction at sleep. Configure GPIO direction,such as output_only,input_only,output_and_input - Parameters gpio_num -- Configure GPIO pins number, it should be GPIO number. If you want to set direction of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); mode -- GPIO direction - - Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO error - - esp_err_t gpio_sleep_set_pull_mode(gpio_num_t gpio_num, gpio_pull_mode_t pull) Configure GPIO pull-up/pull-down resistors at sleep. Note ESP32: Only pins that support both input & output have integrated pull-up and pull-down resistors. Input-only GPIOs 34-39 do not. - Parameters gpio_num -- GPIO number. If you want to set pull up or down mode for e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); pull -- GPIO pull up/down mode. - - Returns ESP_OK Success ESP_ERR_INVALID_ARG : Parameter error - Structures - struct gpio_config_t Configuration parameters of GPIO pad for gpio_config function. Public Members - uint64_t pin_bit_mask GPIO pin: set with bit mask, each bit maps to a GPIO - gpio_mode_t mode GPIO mode: set input/output mode - gpio_pullup_t pull_up_en GPIO pull-up - gpio_pulldown_t pull_down_en GPIO pull-down - gpio_int_type_t intr_type GPIO interrupt type - uint64_t pin_bit_mask Macros - GPIO_PIN_COUNT - GPIO_IS_VALID_GPIO(gpio_num) Check whether it is a valid GPIO number. - GPIO_IS_VALID_OUTPUT_GPIO(gpio_num) Check whether it can be a valid GPIO number of output mode. - GPIO_IS_VALID_DIGITAL_IO_PAD(gpio_num) Check whether it can be a valid digital I/O pad. Type Definitions - typedef intr_handle_t gpio_isr_handle_t - typedef void (*gpio_isr_t)(void *arg) GPIO interrupt handler. - Param arg User registered data Header File This header file can be included with: #include "hal/gpio_types.h" Macros - GPIO_PIN_REG_0 - GPIO_PIN_REG_1 - GPIO_PIN_REG_2 - GPIO_PIN_REG_3 - GPIO_PIN_REG_4 - GPIO_PIN_REG_5 - GPIO_PIN_REG_6 - GPIO_PIN_REG_7 - GPIO_PIN_REG_8 - GPIO_PIN_REG_9 - GPIO_PIN_REG_10 - GPIO_PIN_REG_11 - GPIO_PIN_REG_12 - GPIO_PIN_REG_13 - GPIO_PIN_REG_14 - GPIO_PIN_REG_15 - GPIO_PIN_REG_16 - GPIO_PIN_REG_17 - GPIO_PIN_REG_18 - GPIO_PIN_REG_19 - GPIO_PIN_REG_20 - GPIO_PIN_REG_21 - GPIO_PIN_REG_22 - GPIO_PIN_REG_23 - GPIO_PIN_REG_24 - GPIO_PIN_REG_25 - GPIO_PIN_REG_26 - GPIO_PIN_REG_27 - GPIO_PIN_REG_28 - GPIO_PIN_REG_29 - GPIO_PIN_REG_30 - GPIO_PIN_REG_31 - GPIO_PIN_REG_32 - GPIO_PIN_REG_33 - GPIO_PIN_REG_34 - GPIO_PIN_REG_35 - GPIO_PIN_REG_36 - GPIO_PIN_REG_37 - GPIO_PIN_REG_38 - GPIO_PIN_REG_39 - GPIO_PIN_REG_40 - GPIO_PIN_REG_41 - GPIO_PIN_REG_42 - GPIO_PIN_REG_43 - GPIO_PIN_REG_44 - GPIO_PIN_REG_45 - GPIO_PIN_REG_46 - GPIO_PIN_REG_47 - GPIO_PIN_REG_48 - GPIO_PIN_REG_49 - GPIO_PIN_REG_50 - GPIO_PIN_REG_51 - GPIO_PIN_REG_52 - GPIO_PIN_REG_53 - GPIO_PIN_REG_54 - GPIO_PIN_REG_55 - GPIO_PIN_REG_56 Enumerations - enum gpio_int_type_t Values: - enumerator GPIO_INTR_DISABLE Disable GPIO interrupt - enumerator GPIO_INTR_POSEDGE GPIO interrupt type : rising edge - enumerator GPIO_INTR_NEGEDGE GPIO interrupt type : falling edge - enumerator GPIO_INTR_ANYEDGE GPIO interrupt type : both rising and falling edge - enumerator GPIO_INTR_LOW_LEVEL GPIO interrupt type : input low level trigger - enumerator GPIO_INTR_HIGH_LEVEL GPIO interrupt type : input high level trigger - enumerator GPIO_INTR_MAX - enumerator GPIO_INTR_DISABLE - enum gpio_mode_t Values: - enumerator GPIO_MODE_DISABLE GPIO mode : disable input and output - enumerator GPIO_MODE_INPUT GPIO mode : input only - enumerator GPIO_MODE_OUTPUT GPIO mode : output only mode - enumerator GPIO_MODE_OUTPUT_OD GPIO mode : output only with open-drain mode - enumerator GPIO_MODE_INPUT_OUTPUT_OD GPIO mode : output and input with open-drain mode - enumerator GPIO_MODE_INPUT_OUTPUT GPIO mode : output and input mode - enumerator GPIO_MODE_DISABLE - enum gpio_pullup_t Values: - enumerator GPIO_PULLUP_DISABLE Disable GPIO pull-up resistor - enumerator GPIO_PULLUP_ENABLE Enable GPIO pull-up resistor - enumerator GPIO_PULLUP_DISABLE - enum gpio_pulldown_t Values: - enumerator GPIO_PULLDOWN_DISABLE Disable GPIO pull-down resistor - enumerator GPIO_PULLDOWN_ENABLE Enable GPIO pull-down resistor - enumerator GPIO_PULLDOWN_DISABLE - enum gpio_pull_mode_t Values: - enumerator GPIO_PULLUP_ONLY Pad pull up - enumerator GPIO_PULLDOWN_ONLY Pad pull down - enumerator GPIO_PULLUP_PULLDOWN Pad pull up + pull down - enumerator GPIO_FLOATING Pad floating - enumerator GPIO_PULLUP_ONLY - enum gpio_drive_cap_t Values: - enumerator GPIO_DRIVE_CAP_0 Pad drive capability: weak - enumerator GPIO_DRIVE_CAP_1 Pad drive capability: stronger - enumerator GPIO_DRIVE_CAP_2 Pad drive capability: medium - enumerator GPIO_DRIVE_CAP_DEFAULT Pad drive capability: medium - enumerator GPIO_DRIVE_CAP_3 Pad drive capability: strongest - enumerator GPIO_DRIVE_CAP_MAX - enumerator GPIO_DRIVE_CAP_0 API Reference - RTC GPIO Header File This header file can be included with: #include "driver/rtc_io.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - bool rtc_gpio_is_valid_gpio(gpio_num_t gpio_num) Determine if the specified GPIO is a valid RTC GPIO. - Parameters gpio_num -- GPIO number - Returns true if GPIO is valid for RTC GPIO use. false otherwise. - int rtc_io_number_get(gpio_num_t gpio_num) Get RTC IO index number by gpio number. - Parameters gpio_num -- GPIO number - Returns >=0: Index of rtcio. -1 : The gpio is not rtcio. - esp_err_t rtc_gpio_init(gpio_num_t gpio_num) Init a GPIO as RTC GPIO. This function must be called when initializing a pad for an analog function. - Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) - Returns ESP_OK success ESP_ERR_INVALID_ARG GPIO is not an RTC IO - - esp_err_t rtc_gpio_deinit(gpio_num_t gpio_num) Init a GPIO as digital GPIO. - Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) - Returns ESP_OK success ESP_ERR_INVALID_ARG GPIO is not an RTC IO - - uint32_t rtc_gpio_get_level(gpio_num_t gpio_num) Get the RTC IO input level. - Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) - Returns 1 High level 0 Low level ESP_ERR_INVALID_ARG GPIO is not an RTC IO - - esp_err_t rtc_gpio_set_level(gpio_num_t gpio_num, uint32_t level) Set the RTC IO output level. - Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) level -- output level - - Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO - - esp_err_t rtc_gpio_set_direction(gpio_num_t gpio_num, rtc_gpio_mode_t mode) RTC GPIO set direction. Configure RTC GPIO direction, such as output only, input only, output and input. - Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) mode -- GPIO direction - - Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO - - esp_err_t rtc_gpio_set_direction_in_sleep(gpio_num_t gpio_num, rtc_gpio_mode_t mode) RTC GPIO set direction in deep sleep mode or disable sleep status (default). In some application scenarios, IO needs to have another states during deep sleep. NOTE: ESP32 supports INPUT_ONLY mode. The rest targets support INPUT_ONLY, OUTPUT_ONLY, INPUT_OUTPUT mode. - Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) mode -- GPIO direction - - Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO - - esp_err_t rtc_gpio_pullup_en(gpio_num_t gpio_num) RTC GPIO pullup enable. This function only works for RTC IOs. In general, call gpio_pullup_en, which will work both for normal GPIOs and RTC IOs. - Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) - Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO - - esp_err_t rtc_gpio_pulldown_en(gpio_num_t gpio_num) RTC GPIO pulldown enable. This function only works for RTC IOs. In general, call gpio_pulldown_en, which will work both for normal GPIOs and RTC IOs. - Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) - Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO - - esp_err_t rtc_gpio_pullup_dis(gpio_num_t gpio_num) RTC GPIO pullup disable. This function only works for RTC IOs. In general, call gpio_pullup_dis, which will work both for normal GPIOs and RTC IOs. - Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) - Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO - - esp_err_t rtc_gpio_pulldown_dis(gpio_num_t gpio_num) RTC GPIO pulldown disable. This function only works for RTC IOs. In general, call gpio_pulldown_dis, which will work both for normal GPIOs and RTC IOs. - Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) - Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO - - esp_err_t rtc_gpio_set_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t strength) Set RTC GPIO pad drive capability. - Parameters gpio_num -- GPIO number, only support output GPIOs strength -- Drive capability of the pad - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t rtc_gpio_get_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t *strength) Get RTC GPIO pad drive capability. - Parameters gpio_num -- GPIO number, only support output GPIOs strength -- Pointer to accept drive capability of the pad - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t rtc_gpio_iomux_func_sel(gpio_num_t gpio_num, int func) Select a RTC IOMUX function for the RTC IO. - Parameters gpio_num -- GPIO number func -- Function to assign to the pin - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t rtc_gpio_hold_en(gpio_num_t gpio_num) Enable hold function on an RTC IO pad. Enabling HOLD function will cause the pad to latch current values of input enable, output enable, output value, function, drive strength values. This function is useful when going into light or deep sleep mode to prevent the pin configuration from changing. - Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) - Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO - - esp_err_t rtc_gpio_hold_dis(gpio_num_t gpio_num) Disable hold function on an RTC IO pad. Disabling hold function will allow the pad receive the values of input enable, output enable, output value, function, drive strength from RTC_IO peripheral. - Parameters gpio_num -- GPIO number (e.g. GPIO_NUM_12) - Returns ESP_OK Success ESP_ERR_INVALID_ARG GPIO is not an RTC IO - - esp_err_t rtc_gpio_force_hold_en_all(void) Enable force hold signal for all RTC IOs. Each RTC pad has a "force hold" input signal from the RTC controller. If this signal is set, pad latches current values of input enable, function, output enable, and other signals which come from the RTC mux. Force hold signal is enabled before going into deep sleep for pins which are used for EXT1 wakeup. - esp_err_t rtc_gpio_wakeup_enable(gpio_num_t gpio_num, gpio_int_type_t intr_type) Enable wakeup from sleep mode using specific GPIO. - Parameters gpio_num -- GPIO number intr_type -- Wakeup on high level (GPIO_INTR_HIGH_LEVEL) or low level (GPIO_INTR_LOW_LEVEL) - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if gpio_num is not an RTC IO, or intr_type is not one of GPIO_INTR_HIGH_LEVEL, GPIO_INTR_LOW_LEVEL. - Macros - RTC_GPIO_IS_VALID_GPIO(gpio_num) Header File This header file can be included with: #include "driver/lp_io.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Header File This header file can be included with: #include "hal/rtc_io_types.h" Enumerations - enum rtc_gpio_mode_t RTCIO output/input mode type. Values: - enumerator RTC_GPIO_MODE_INPUT_ONLY Pad input - enumerator RTC_GPIO_MODE_OUTPUT_ONLY Pad output - enumerator RTC_GPIO_MODE_INPUT_OUTPUT Pad input + output - enumerator RTC_GPIO_MODE_DISABLED Pad (output + input) disable - enumerator RTC_GPIO_MODE_OUTPUT_OD Pad open-drain output - enumerator RTC_GPIO_MODE_INPUT_OUTPUT_OD Pad input + open-drain output - enumerator RTC_GPIO_MODE_INPUT_ONLY
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/gpio.html
ESP-IDF Programming Guide v5.2.1 documentation
null
General Purpose Timer (GPTimer)
null
espressif.com
2016-01-01
6e55bc12b407b389
null
null
General Purpose Timer (GPTimer) Introduction GPTimer (General Purpose Timer) is the driver of ESP32 Timer Group peripheral. The hardware timer features high resolution and flexible alarm action. The behavior when the internal counter of a timer reaches a specific target value is called a timer alarm. When a timer alarms, a user registered per-timer callback would be called. Typically, a general purpose timer can be used in scenarios like: Free running as a wall clock, fetching a high-resolution timestamp at any time and any places Generate period alarms, trigger events periodically Generate one-shot alarm, respond in target time Functional Overview The following sections of this document cover the typical steps to install and operate a timer: Resource Allocation - covers which parameters should be set up to get a timer handle and how to recycle the resources when GPTimer finishes working. Set and Get Count Value - covers how to force the timer counting from a start point and how to get the count value at anytime. Set up Alarm Action - covers the parameters that should be set up to enable the alarm event. Register Event Callbacks - covers how to hook user specific code to the alarm event callback function. Enable and Disable Timer - covers how to enable and disable the timer. Start and Stop Timer - shows some typical use cases that start the timer with different alarm behavior. Power Management - describes how different source clock selections can affect power consumption. IRAM Safe - describes tips on how to make the timer interrupt and IO control functions work better along with a disabled cache. Thread Safety - lists which APIs are guaranteed to be thread safe by the driver. Kconfig Options - lists the supported Kconfig options that can be used to make a different effect on driver behavior. Resource Allocation Different ESP chips might have different numbers of independent timer groups, and within each group, there could also be several independent timers. 1 A GPTimer instance is represented by gptimer_handle_t . The driver behind manages all available hardware resources in a pool, so that you do not need to care about which timer and which group it belongs to. To install a timer instance, there is a configuration structure that needs to be given in advance: gptimer_config_t : gptimer_config_t::clk_src selects the source clock for the timer. The available clocks are listed in gptimer_clock_source_t , you can only pick one of them. For the effect on power consumption of different clock source, please refer to Section Power Management. gptimer_config_t::direction sets the counting direction of the timer, supported directions are listed in gptimer_count_direction_t , you can only pick one of them. gptimer_config_t::resolution_hz sets the resolution of the internal counter. Each count step is equivalent to 1 / resolution_hz seconds. gptimer_config::intr_priority sets the priority of the timer interrupt. If it is set to 0 , the driver will allocate an interrupt with a default priority. Otherwise, the driver will use the given priority. Optional gptimer_config_t::intr_shared sets whether or not mark the timer interrupt source as a shared one. For the pros/cons of a shared interrupt, you can refer to Interrupt Handling. With all the above configurations set in the structure, the structure can be passed to gptimer_new_timer() which will instantiate the timer instance and return a handle of the timer. The function can fail due to various errors such as insufficient memory, invalid arguments, etc. Specifically, when there are no more free timers (i.e., all hardware resources have been used up), then ESP_ERR_NOT_FOUND will be returned. The total number of available timers is represented by the SOC_TIMER_GROUP_TOTAL_TIMERS and its value depends on the ESP chip. If a previously created GPTimer instance is no longer required, you should recycle the timer by calling gptimer_del_timer() . This allows the underlying HW timer to be used for other purposes. Before deleting a GPTimer handle, please disable it by gptimer_disable() in advance or make sure it has not enabled yet by gptimer_enable() . Creating a GPTimer Handle with Resolution of 1 MHz gptimer_handle_t gptimer = NULL; gptimer_config_t timer_config = { .clk_src = GPTIMER_CLK_SRC_DEFAULT, .direction = GPTIMER_COUNT_UP, .resolution_hz = 1 * 1000 * 1000, // 1MHz, 1 tick = 1us }; ESP_ERROR_CHECK(gptimer_new_timer(&timer_config, &gptimer)); Set and Get Count Value When the GPTimer is created, the internal counter will be reset to zero by default. The counter value can be updated asynchronously by gptimer_set_raw_count() . The maximum count value is dependent on the bit width of the hardware timer, which is also reflected by the SOC macro SOC_TIMER_GROUP_COUNTER_BIT_WIDTH . When updating the raw count of an active timer, the timer will immediately start counting from the new value. Count value can be retrieved by gptimer_get_raw_count() , at any time. Set up Alarm Action For most of the use cases of GPTimer, you should set up the alarm action before starting the timer, except for the simple wall-clock scenario, where a free running timer is enough. To set up the alarm action, you should configure several members of gptimer_alarm_config_t based on how you make use of the alarm event: gptimer_alarm_config_t::alarm_count sets the target count value that triggers the alarm event. You should also take the counting direction into consideration when setting the alarm value. Specially, gptimer_alarm_config_t::alarm_count and gptimer_alarm_config_t::reload_count cannot be set to the same value when gptimer_alarm_config_t::auto_reload_on_alarm is true, as keeping reload with a target alarm count is meaningless. gptimer_alarm_config_t::reload_count sets the count value to be reloaded when the alarm event happens. This configuration only takes effect when gptimer_alarm_config_t::auto_reload_on_alarm is set to true. gptimer_alarm_config_t::auto_reload_on_alarm flag sets whether to enable the auto-reload feature. If enabled, the hardware timer will reload the value of gptimer_alarm_config_t::reload_count into counter immediately when an alarm event happens. To make the alarm configurations take effect, you should call gptimer_set_alarm_action() . Especially, if gptimer_alarm_config_t is set to NULL , the alarm function will be disabled. Note If an alarm value is set and the timer has already exceeded this value, the alarm will be triggered immediately. Register Event Callbacks After the timer starts up, it can generate a specific event (e.g., the "Alarm Event") dynamically. If you have some functions that should be called when the event happens, please hook your function to the interrupt service routine by calling gptimer_register_event_callbacks() . All supported event callbacks are listed in gptimer_event_callbacks_t : gptimer_event_callbacks_t::on_alarm sets a callback function for alarm events. As this function is called within the ISR context, you must ensure that the function does not attempt to block (e.g., by making sure that only FreeRTOS APIs with ISR suffix are called from within the function). The function prototype is declared in gptimer_alarm_cb_t . You can save your own context to gptimer_register_event_callbacks() as well, via the parameter user_data . The user data will be directly passed to the callback function. This function lazy installs the interrupt service for the timer but not enable it. So please call this function before gptimer_enable() , otherwise the ESP_ERR_INVALID_STATE error will be returned. See Section Enable and Disable Timer for more information. Enable and Disable Timer Before doing IO control to the timer, you needs to enable the timer first, by calling gptimer_enable() . This function: Switches the timer driver state from init to enable. Enables the interrupt service if it has been lazy installed by gptimer_register_event_callbacks() . Acquires a proper power management lock if a specific clock source (e.g., APB clock) is selected. See Section Power Management for more information. Calling gptimer_disable() does the opposite, that is, put the timer driver back to the init state, disable the interrupts service and release the power management lock. Start and Stop Timer The basic IO operation of a timer is to start and stop. Calling gptimer_start() can make the internal counter work, while calling gptimer_stop() can make the counter stop working. The following illustrates how to start a timer with or without an alarm event. Calling gptimer_start() transits the driver state from enable to run, and vice versa. You need to make sure the start and stop functions are used in pairs, otherwise, the functions may return ESP_ERR_INVALID_STATE . Most of the time, this error means that the timer is already stopped or in the "start protection" state (i.e., gptimer_start() is called but not finished). Start Timer as a Wall Clock ESP_ERROR_CHECK(gptimer_enable(gptimer)); ESP_ERROR_CHECK(gptimer_start(gptimer)); // Retrieve the timestamp at any time uint64_t count; ESP_ERROR_CHECK(gptimer_get_raw_count(gptimer, &count)); Trigger Period Events typedef struct { uint64_t event_count; } example_queue_element_t; static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx) { BaseType_t high_task_awoken = pdFALSE; QueueHandle_t queue = (QueueHandle_t)user_ctx; // Retrieve the count value from event data example_queue_element_t ele = { .event_count = edata->count_value }; // Optional: send the event data to other task by OS queue // Do not introduce complex logics in callbacks // Suggest dealing with event data in the main loop, instead of in this callback xQueueSendFromISR(queue, &ele, &high_task_awoken); // return whether we need to yield at the end of ISR return high_task_awoken == pdTRUE; } gptimer_alarm_config_t alarm_config = { .reload_count = 0, // counter will reload with 0 on alarm event .alarm_count = 1000000, // period = 1s @resolution 1MHz .flags.auto_reload_on_alarm = true, // enable auto-reload }; ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config)); gptimer_event_callbacks_t cbs = { .on_alarm = example_timer_on_alarm_cb, // register user callback }; ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, queue)); ESP_ERROR_CHECK(gptimer_enable(gptimer)); ESP_ERROR_CHECK(gptimer_start(gptimer)); Trigger One-Shot Event typedef struct { uint64_t event_count; } example_queue_element_t; static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx) { BaseType_t high_task_awoken = pdFALSE; QueueHandle_t queue = (QueueHandle_t)user_ctx; // Stop timer the sooner the better gptimer_stop(timer); // Retrieve the count value from event data example_queue_element_t ele = { .event_count = edata->count_value }; // Optional: send the event data to other task by OS queue xQueueSendFromISR(queue, &ele, &high_task_awoken); // return whether we need to yield at the end of ISR return high_task_awoken == pdTRUE; } gptimer_alarm_config_t alarm_config = { .alarm_count = 1 * 1000 * 1000, // alarm target = 1s @resolution 1MHz }; ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config)); gptimer_event_callbacks_t cbs = { .on_alarm = example_timer_on_alarm_cb, // register user callback }; ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, queue)); ESP_ERROR_CHECK(gptimer_enable(gptimer)); ESP_ERROR_CHECK(gptimer_start(gptimer)); Dynamic Alarm Update Alarm value can be updated dynamically inside the ISR handler callback, by changing gptimer_alarm_event_data_t::alarm_value . Then the alarm value will be updated after the callback function returns. typedef struct { uint64_t event_count; } example_queue_element_t; static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx) { BaseType_t high_task_awoken = pdFALSE; QueueHandle_t queue = (QueueHandle_t)user_data; // Retrieve the count value from event data example_queue_element_t ele = { .event_count = edata->count_value }; // Optional: send the event data to other task by OS queue xQueueSendFromISR(queue, &ele, &high_task_awoken); // reconfigure alarm value gptimer_alarm_config_t alarm_config = { .alarm_count = edata->alarm_value + 1000000, // alarm in next 1s }; gptimer_set_alarm_action(timer, &alarm_config); // return whether we need to yield at the end of ISR return high_task_awoken == pdTRUE; } gptimer_alarm_config_t alarm_config = { .alarm_count = 1000000, // initial alarm target = 1s @resolution 1MHz }; ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config)); gptimer_event_callbacks_t cbs = { .on_alarm = example_timer_on_alarm_cb, // register user callback }; ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, queue)); ESP_ERROR_CHECK(gptimer_enable(gptimer)); ESP_ERROR_CHECK(gptimer_start(gptimer, &alarm_config)); Power Management There are some power management strategies, which might turn off or change the frequency of GPTimer's source clock to save power consumption. For example, during DFS, APB clock will be scaled down. If light-sleep is also enabled, PLL and XTAL clocks will be powered off. Both of them can result in an inaccurate time keeping. The driver can prevent the above situation from happening by creating different power management lock according to different clock source. The driver increases the reference count of that power management lock in the gptimer_enable() and decrease it in the gptimer_disable() . So we can ensure the clock source is stable between gptimer_enable() and gptimer_disable() . IRAM Safe By default, the GPTimer interrupt will be deferred when the cache is disabled because of writing or erasing the flash. Thus the alarm interrupt will not get executed in time, which is not expected in a real-time application. There is a Kconfig option CONFIG_GPTIMER_ISR_IRAM_SAFE that: Enables the interrupt being serviced even when the cache is disabled Places all functions that used by the ISR into IRAM 2 Places driver object into DRAM (in case it is mapped to PSRAM by accident) This allows the interrupt to run while the cache is disabled, but comes at the cost of increased IRAM consumption. There is another Kconfig option CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM that can put commonly used IO control functions into IRAM as well. So, these functions can also be executable when the cache is disabled. These IO control functions are as follows: Thread Safety All the APIs provided by the driver are guaranteed to be thread safe, which means you can call them from different RTOS tasks without protection by extra locks. The following functions are allowed to run under ISR context. Kconfig Options CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM controls where to place the GPTimer control functions (IRAM or flash). CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM controls where to place the GPTimer ISR handler (IRAM or flash). CONFIG_GPTIMER_ISR_IRAM_SAFE controls whether the default ISR handler should be masked when the cache is disabled, see Section IRAM Safe for more information. CONFIG_GPTIMER_ENABLE_DEBUG_LOG is used to enabled the debug log output. Enable this option will increase the firmware binary size. Application Examples Typical use cases of GPTimer are listed in the example peripherals/timer_group/gptimer. API Reference Header File This header file can be included with: #include "driver/gptimer.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t gptimer_new_timer(const gptimer_config_t *config, gptimer_handle_t *ret_timer) Create a new General Purpose Timer, and return the handle. Note The newly created timer is put in the "init" state. Parameters config -- [in] GPTimer configuration ret_timer -- [out] Returned timer handle config -- [in] GPTimer configuration ret_timer -- [out] Returned timer handle config -- [in] GPTimer configuration Returns ESP_OK: Create GPTimer successfully ESP_ERR_INVALID_ARG: Create GPTimer failed because of invalid argument ESP_ERR_NO_MEM: Create GPTimer failed because out of memory ESP_ERR_NOT_FOUND: Create GPTimer failed because all hardware timers are used up and no more free one ESP_FAIL: Create GPTimer failed because of other error ESP_OK: Create GPTimer successfully ESP_ERR_INVALID_ARG: Create GPTimer failed because of invalid argument ESP_ERR_NO_MEM: Create GPTimer failed because out of memory ESP_ERR_NOT_FOUND: Create GPTimer failed because all hardware timers are used up and no more free one ESP_FAIL: Create GPTimer failed because of other error ESP_OK: Create GPTimer successfully Parameters config -- [in] GPTimer configuration ret_timer -- [out] Returned timer handle Returns ESP_OK: Create GPTimer successfully ESP_ERR_INVALID_ARG: Create GPTimer failed because of invalid argument ESP_ERR_NO_MEM: Create GPTimer failed because out of memory ESP_ERR_NOT_FOUND: Create GPTimer failed because all hardware timers are used up and no more free one ESP_FAIL: Create GPTimer failed because of other error esp_err_t gptimer_del_timer(gptimer_handle_t timer) Delete the GPTimer handle. Note A timer must be in the "init" state before it can be deleted. Parameters timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Delete GPTimer successfully ESP_ERR_INVALID_ARG: Delete GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Delete GPTimer failed because the timer is not in init state ESP_FAIL: Delete GPTimer failed because of other error ESP_OK: Delete GPTimer successfully ESP_ERR_INVALID_ARG: Delete GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Delete GPTimer failed because the timer is not in init state ESP_FAIL: Delete GPTimer failed because of other error ESP_OK: Delete GPTimer successfully Parameters timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Delete GPTimer successfully ESP_ERR_INVALID_ARG: Delete GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Delete GPTimer failed because the timer is not in init state ESP_FAIL: Delete GPTimer failed because of other error esp_err_t gptimer_set_raw_count(gptimer_handle_t timer, uint64_t value) Set GPTimer raw count value. Note When updating the raw count of an active timer, the timer will immediately start counting from the new value. Note This function is allowed to run within ISR context Note If CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled. Parameters timer -- [in] Timer handle created by gptimer_new_timer value -- [in] Count value to be set timer -- [in] Timer handle created by gptimer_new_timer value -- [in] Count value to be set timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Set GPTimer raw count value successfully ESP_ERR_INVALID_ARG: Set GPTimer raw count value failed because of invalid argument ESP_FAIL: Set GPTimer raw count value failed because of other error ESP_OK: Set GPTimer raw count value successfully ESP_ERR_INVALID_ARG: Set GPTimer raw count value failed because of invalid argument ESP_FAIL: Set GPTimer raw count value failed because of other error ESP_OK: Set GPTimer raw count value successfully Parameters timer -- [in] Timer handle created by gptimer_new_timer value -- [in] Count value to be set Returns ESP_OK: Set GPTimer raw count value successfully ESP_ERR_INVALID_ARG: Set GPTimer raw count value failed because of invalid argument ESP_FAIL: Set GPTimer raw count value failed because of other error esp_err_t gptimer_get_raw_count(gptimer_handle_t timer, uint64_t *value) Get GPTimer raw count value. Note This function will trigger a software capture event and then return the captured count value. Note With the raw count value and the resolution returned from gptimer_get_resolution , you can convert the count value into seconds. Note This function is allowed to run within ISR context Note If CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled. Parameters timer -- [in] Timer handle created by gptimer_new_timer value -- [out] Returned GPTimer count value timer -- [in] Timer handle created by gptimer_new_timer value -- [out] Returned GPTimer count value timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Get GPTimer raw count value successfully ESP_ERR_INVALID_ARG: Get GPTimer raw count value failed because of invalid argument ESP_FAIL: Get GPTimer raw count value failed because of other error ESP_OK: Get GPTimer raw count value successfully ESP_ERR_INVALID_ARG: Get GPTimer raw count value failed because of invalid argument ESP_FAIL: Get GPTimer raw count value failed because of other error ESP_OK: Get GPTimer raw count value successfully Parameters timer -- [in] Timer handle created by gptimer_new_timer value -- [out] Returned GPTimer count value Returns ESP_OK: Get GPTimer raw count value successfully ESP_ERR_INVALID_ARG: Get GPTimer raw count value failed because of invalid argument ESP_FAIL: Get GPTimer raw count value failed because of other error esp_err_t gptimer_get_resolution(gptimer_handle_t timer, uint32_t *out_resolution) Return the real resolution of the timer. Note usually the timer resolution is same as what you configured in the gptimer_config_t::resolution_hz , but some unstable clock source (e.g. RC_FAST) will do a calibration, the real resolution can be different from the configured one. Parameters timer -- [in] Timer handle created by gptimer_new_timer out_resolution -- [out] Returned timer resolution, in Hz timer -- [in] Timer handle created by gptimer_new_timer out_resolution -- [out] Returned timer resolution, in Hz timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Get GPTimer resolution successfully ESP_ERR_INVALID_ARG: Get GPTimer resolution failed because of invalid argument ESP_FAIL: Get GPTimer resolution failed because of other error ESP_OK: Get GPTimer resolution successfully ESP_ERR_INVALID_ARG: Get GPTimer resolution failed because of invalid argument ESP_FAIL: Get GPTimer resolution failed because of other error ESP_OK: Get GPTimer resolution successfully Parameters timer -- [in] Timer handle created by gptimer_new_timer out_resolution -- [out] Returned timer resolution, in Hz Returns ESP_OK: Get GPTimer resolution successfully ESP_ERR_INVALID_ARG: Get GPTimer resolution failed because of invalid argument ESP_FAIL: Get GPTimer resolution failed because of other error esp_err_t gptimer_get_captured_count(gptimer_handle_t timer, uint64_t *value) Get GPTimer captured count value. Note The capture action can be issued either by ETM event or by software (see also gptimer_get_raw_count ). Note This function is allowed to run within ISR context Note If CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled. Parameters timer -- [in] Timer handle created by gptimer_new_timer value -- [out] Returned captured count value timer -- [in] Timer handle created by gptimer_new_timer value -- [out] Returned captured count value timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Get GPTimer captured count value successfully ESP_ERR_INVALID_ARG: Get GPTimer captured count value failed because of invalid argument ESP_FAIL: Get GPTimer captured count value failed because of other error ESP_OK: Get GPTimer captured count value successfully ESP_ERR_INVALID_ARG: Get GPTimer captured count value failed because of invalid argument ESP_FAIL: Get GPTimer captured count value failed because of other error ESP_OK: Get GPTimer captured count value successfully Parameters timer -- [in] Timer handle created by gptimer_new_timer value -- [out] Returned captured count value Returns ESP_OK: Get GPTimer captured count value successfully ESP_ERR_INVALID_ARG: Get GPTimer captured count value failed because of invalid argument ESP_FAIL: Get GPTimer captured count value failed because of other error esp_err_t gptimer_register_event_callbacks(gptimer_handle_t timer, const gptimer_event_callbacks_t *cbs, void *user_data) Set callbacks for GPTimer. Note User registered callbacks are expected to be runnable within ISR context Note The first call to this function needs to be before the call to gptimer_enable Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbs structure to NULL. Parameters timer -- [in] Timer handle created by gptimer_new_timer cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly timer -- [in] Timer handle created by gptimer_new_timer cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because the timer is not in init state ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because the timer is not in init state ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully Parameters timer -- [in] Timer handle created by gptimer_new_timer cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because the timer is not in init state ESP_FAIL: Set event callbacks failed because of other error esp_err_t gptimer_set_alarm_action(gptimer_handle_t timer, const gptimer_alarm_config_t *config) Set alarm event actions for GPTimer. Note This function is allowed to run within ISR context, so that user can set new alarm action immediately in the ISR callback. Note If CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled. Parameters timer -- [in] Timer handle created by gptimer_new_timer config -- [in] Alarm configuration, especially, set config to NULL means disabling the alarm function timer -- [in] Timer handle created by gptimer_new_timer config -- [in] Alarm configuration, especially, set config to NULL means disabling the alarm function timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Set alarm action for GPTimer successfully ESP_ERR_INVALID_ARG: Set alarm action for GPTimer failed because of invalid argument ESP_FAIL: Set alarm action for GPTimer failed because of other error ESP_OK: Set alarm action for GPTimer successfully ESP_ERR_INVALID_ARG: Set alarm action for GPTimer failed because of invalid argument ESP_FAIL: Set alarm action for GPTimer failed because of other error ESP_OK: Set alarm action for GPTimer successfully Parameters timer -- [in] Timer handle created by gptimer_new_timer config -- [in] Alarm configuration, especially, set config to NULL means disabling the alarm function Returns ESP_OK: Set alarm action for GPTimer successfully ESP_ERR_INVALID_ARG: Set alarm action for GPTimer failed because of invalid argument ESP_FAIL: Set alarm action for GPTimer failed because of other error esp_err_t gptimer_enable(gptimer_handle_t timer) Enable GPTimer. Note This function will transit the timer state from "init" to "enable". Note This function will enable the interrupt service, if it's lazy installed in gptimer_register_event_callbacks . Note This function will acquire a PM lock, if a specific source clock (e.g. APB) is selected in the gptimer_config_t , while CONFIG_PM_ENABLE is enabled. Note Enable a timer doesn't mean to start it. See also gptimer_start for how to make the timer start counting. Parameters timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Enable GPTimer successfully ESP_ERR_INVALID_ARG: Enable GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Enable GPTimer failed because the timer is already enabled ESP_FAIL: Enable GPTimer failed because of other error ESP_OK: Enable GPTimer successfully ESP_ERR_INVALID_ARG: Enable GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Enable GPTimer failed because the timer is already enabled ESP_FAIL: Enable GPTimer failed because of other error ESP_OK: Enable GPTimer successfully Parameters timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Enable GPTimer successfully ESP_ERR_INVALID_ARG: Enable GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Enable GPTimer failed because the timer is already enabled ESP_FAIL: Enable GPTimer failed because of other error esp_err_t gptimer_disable(gptimer_handle_t timer) Disable GPTimer. Note This function will transit the timer state from "enable" to "init". Note This function will disable the interrupt service if it's installed. Note This function will release the PM lock if it's acquired in the gptimer_enable . Note Disable a timer doesn't mean to stop it. See also gptimer_stop for how to make the timer stop counting. Parameters timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Disable GPTimer successfully ESP_ERR_INVALID_ARG: Disable GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Disable GPTimer failed because the timer is not enabled yet ESP_FAIL: Disable GPTimer failed because of other error ESP_OK: Disable GPTimer successfully ESP_ERR_INVALID_ARG: Disable GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Disable GPTimer failed because the timer is not enabled yet ESP_FAIL: Disable GPTimer failed because of other error ESP_OK: Disable GPTimer successfully Parameters timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Disable GPTimer successfully ESP_ERR_INVALID_ARG: Disable GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Disable GPTimer failed because the timer is not enabled yet ESP_FAIL: Disable GPTimer failed because of other error esp_err_t gptimer_start(gptimer_handle_t timer) Start GPTimer (internal counter starts counting) Note This function will transit the timer state from "enable" to "run". Note This function is allowed to run within ISR context Note If CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled. Parameters timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Start GPTimer successfully ESP_ERR_INVALID_ARG: Start GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Start GPTimer failed because the timer is not enabled or is already in running ESP_FAIL: Start GPTimer failed because of other error ESP_OK: Start GPTimer successfully ESP_ERR_INVALID_ARG: Start GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Start GPTimer failed because the timer is not enabled or is already in running ESP_FAIL: Start GPTimer failed because of other error ESP_OK: Start GPTimer successfully Parameters timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Start GPTimer successfully ESP_ERR_INVALID_ARG: Start GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Start GPTimer failed because the timer is not enabled or is already in running ESP_FAIL: Start GPTimer failed because of other error esp_err_t gptimer_stop(gptimer_handle_t timer) Stop GPTimer (internal counter stops counting) Note This function will transit the timer state from "run" to "enable". Note This function is allowed to run within ISR context Note If CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled. Parameters timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Stop GPTimer successfully ESP_ERR_INVALID_ARG: Stop GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Stop GPTimer failed because the timer is not in running. ESP_FAIL: Stop GPTimer failed because of other error ESP_OK: Stop GPTimer successfully ESP_ERR_INVALID_ARG: Stop GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Stop GPTimer failed because the timer is not in running. ESP_FAIL: Stop GPTimer failed because of other error ESP_OK: Stop GPTimer successfully Parameters timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Stop GPTimer successfully ESP_ERR_INVALID_ARG: Stop GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Stop GPTimer failed because the timer is not in running. ESP_FAIL: Stop GPTimer failed because of other error Structures struct gptimer_config_t General Purpose Timer configuration. Public Members gptimer_clock_source_t clk_src GPTimer clock source gptimer_clock_source_t clk_src GPTimer clock source gptimer_count_direction_t direction Count direction gptimer_count_direction_t direction Count direction uint32_t resolution_hz Counter resolution (working frequency) in Hz, hence, the step size of each count tick equals to (1 / resolution_hz) seconds uint32_t resolution_hz Counter resolution (working frequency) in Hz, hence, the step size of each count tick equals to (1 / resolution_hz) seconds int intr_priority GPTimer interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) int intr_priority GPTimer interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) Set true, the timer interrupt number can be shared with other peripherals Set true, the timer interrupt number can be shared with other peripherals struct gptimer_config_t::[anonymous] flags GPTimer config flags struct gptimer_config_t::[anonymous] flags GPTimer config flags gptimer_clock_source_t clk_src struct gptimer_event_callbacks_t Group of supported GPTimer callbacks. Note The callbacks are all running under ISR environment Note When CONFIG_GPTIMER_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. Public Members gptimer_alarm_cb_t on_alarm Timer alarm callback gptimer_alarm_cb_t on_alarm Timer alarm callback gptimer_alarm_cb_t on_alarm struct gptimer_alarm_config_t General Purpose Timer alarm configuration. Public Members uint64_t alarm_count Alarm target count value uint64_t alarm_count Alarm target count value uint64_t reload_count Alarm reload count value, effect only when auto_reload_on_alarm is set to true uint64_t reload_count Alarm reload count value, effect only when auto_reload_on_alarm is set to true uint32_t auto_reload_on_alarm Reload the count value by hardware, immediately at the alarm event uint32_t auto_reload_on_alarm Reload the count value by hardware, immediately at the alarm event struct gptimer_alarm_config_t::[anonymous] flags Alarm config flags struct gptimer_alarm_config_t::[anonymous] flags Alarm config flags uint64_t alarm_count Header File This header file can be included with: #include "driver/gptimer_etm.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t gptimer_new_etm_event(gptimer_handle_t timer, const gptimer_etm_event_config_t *config, esp_etm_event_handle_t *out_event) Get the ETM event for GPTimer. Note The created ETM event object can be deleted later by calling esp_etm_del_event Parameters timer -- [in] Timer handle created by gptimer_new_timer config -- [in] GPTimer ETM event configuration out_event -- [out] Returned ETM event handle timer -- [in] Timer handle created by gptimer_new_timer config -- [in] GPTimer ETM event configuration out_event -- [out] Returned ETM event handle timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Get ETM event successfully ESP_ERR_INVALID_ARG: Get ETM event failed because of invalid argument ESP_FAIL: Get ETM event failed because of other error ESP_OK: Get ETM event successfully ESP_ERR_INVALID_ARG: Get ETM event failed because of invalid argument ESP_FAIL: Get ETM event failed because of other error ESP_OK: Get ETM event successfully Parameters timer -- [in] Timer handle created by gptimer_new_timer config -- [in] GPTimer ETM event configuration out_event -- [out] Returned ETM event handle Returns ESP_OK: Get ETM event successfully ESP_ERR_INVALID_ARG: Get ETM event failed because of invalid argument ESP_FAIL: Get ETM event failed because of other error esp_err_t gptimer_new_etm_task(gptimer_handle_t timer, const gptimer_etm_task_config_t *config, esp_etm_task_handle_t *out_task) Get the ETM task for GPTimer. Note The created ETM task object can be deleted later by calling esp_etm_del_task Parameters timer -- [in] Timer handle created by gptimer_new_timer config -- [in] GPTimer ETM task configuration out_task -- [out] Returned ETM task handle timer -- [in] Timer handle created by gptimer_new_timer config -- [in] GPTimer ETM task configuration out_task -- [out] Returned ETM task handle timer -- [in] Timer handle created by gptimer_new_timer Returns ESP_OK: Get ETM task successfully ESP_ERR_INVALID_ARG: Get ETM task failed because of invalid argument ESP_FAIL: Get ETM task failed because of other error ESP_OK: Get ETM task successfully ESP_ERR_INVALID_ARG: Get ETM task failed because of invalid argument ESP_FAIL: Get ETM task failed because of other error ESP_OK: Get ETM task successfully Parameters timer -- [in] Timer handle created by gptimer_new_timer config -- [in] GPTimer ETM task configuration out_task -- [out] Returned ETM task handle Returns ESP_OK: Get ETM task successfully ESP_ERR_INVALID_ARG: Get ETM task failed because of invalid argument ESP_FAIL: Get ETM task failed because of other error Structures struct gptimer_etm_event_config_t GPTimer ETM event configuration. Public Members gptimer_etm_event_type_t event_type GPTimer ETM event type gptimer_etm_event_type_t event_type GPTimer ETM event type gptimer_etm_event_type_t event_type struct gptimer_etm_task_config_t GPTimer ETM task configuration. Public Members gptimer_etm_task_type_t task_type GPTimer ETM task type gptimer_etm_task_type_t task_type GPTimer ETM task type gptimer_etm_task_type_t task_type Header File This header file can be included with: #include "driver/gptimer_types.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Structures struct gptimer_alarm_event_data_t GPTimer alarm event data. Type Definitions typedef struct gptimer_t *gptimer_handle_t Type of General Purpose Timer handle. typedef bool (*gptimer_alarm_cb_t)(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx) Timer alarm callback prototype. Param timer [in] Timer handle created by gptimer_new_timer Param edata [in] Alarm event data, fed by driver Param user_ctx [in] User data, passed from gptimer_register_event_callbacks Return Whether a high priority task has been waken up by this function Param timer [in] Timer handle created by gptimer_new_timer Param edata [in] Alarm event data, fed by driver Param user_ctx [in] User data, passed from gptimer_register_event_callbacks Return Whether a high priority task has been waken up by this function Header File This header file can be included with: #include "hal/timer_types.h" Type Definitions typedef soc_periph_gptimer_clk_src_t gptimer_clock_source_t GPTimer clock source. Note User should select the clock source based on the power and resolution requirement Enumerations enum gptimer_count_direction_t GPTimer count direction. Values: enumerator GPTIMER_COUNT_DOWN Decrease count value enumerator GPTIMER_COUNT_DOWN Decrease count value enumerator GPTIMER_COUNT_UP Increase count value enumerator GPTIMER_COUNT_UP Increase count value enumerator GPTIMER_COUNT_DOWN enum gptimer_etm_task_type_t GPTimer specific tasks that supported by the ETM module. Values: enumerator GPTIMER_ETM_TASK_START_COUNT Start the counter enumerator GPTIMER_ETM_TASK_START_COUNT Start the counter enumerator GPTIMER_ETM_TASK_STOP_COUNT Stop the counter enumerator GPTIMER_ETM_TASK_STOP_COUNT Stop the counter enumerator GPTIMER_ETM_TASK_EN_ALARM Enable the alarm enumerator GPTIMER_ETM_TASK_EN_ALARM Enable the alarm enumerator GPTIMER_ETM_TASK_RELOAD Reload preset value into counter enumerator GPTIMER_ETM_TASK_RELOAD Reload preset value into counter enumerator GPTIMER_ETM_TASK_CAPTURE Capture current count value into specific register enumerator GPTIMER_ETM_TASK_CAPTURE Capture current count value into specific register enumerator GPTIMER_ETM_TASK_MAX Maximum number of tasks enumerator GPTIMER_ETM_TASK_MAX Maximum number of tasks enumerator GPTIMER_ETM_TASK_START_COUNT enum gptimer_etm_event_type_t GPTimer specific events that supported by the ETM module. Values: enumerator GPTIMER_ETM_EVENT_ALARM_MATCH Count value matches the alarm target value enumerator GPTIMER_ETM_EVENT_ALARM_MATCH Count value matches the alarm target value enumerator GPTIMER_ETM_EVENT_MAX Maximum number of events enumerator GPTIMER_ETM_EVENT_MAX Maximum number of events enumerator GPTIMER_ETM_EVENT_ALARM_MATCH 1 Different ESP chip series might have different numbers of GPTimer instances. For more details, please refer to ESP32 Technical Reference Manual > Chapter Timer Group (TIMG) [PDF]. The driver does forbid you from applying for more timers, but it returns error when all available hardware resources are used up. Please always check the return value when doing resource allocation (e.g., gptimer_new_timer() ). 2 gptimer_event_callbacks_t::on_alarm callback and the functions invoked by the callback should also be placed in IRAM, please take care of them by yourself.
General Purpose Timer (GPTimer) Introduction GPTimer (General Purpose Timer) is the driver of ESP32 Timer Group peripheral. The hardware timer features high resolution and flexible alarm action. The behavior when the internal counter of a timer reaches a specific target value is called a timer alarm. When a timer alarms, a user registered per-timer callback would be called. Typically, a general purpose timer can be used in scenarios like: Free running as a wall clock, fetching a high-resolution timestamp at any time and any places Generate period alarms, trigger events periodically Generate one-shot alarm, respond in target time Functional Overview The following sections of this document cover the typical steps to install and operate a timer: Resource Allocation - covers which parameters should be set up to get a timer handle and how to recycle the resources when GPTimer finishes working. Set and Get Count Value - covers how to force the timer counting from a start point and how to get the count value at anytime. Set up Alarm Action - covers the parameters that should be set up to enable the alarm event. Register Event Callbacks - covers how to hook user specific code to the alarm event callback function. Enable and Disable Timer - covers how to enable and disable the timer. Start and Stop Timer - shows some typical use cases that start the timer with different alarm behavior. Power Management - describes how different source clock selections can affect power consumption. IRAM Safe - describes tips on how to make the timer interrupt and IO control functions work better along with a disabled cache. Thread Safety - lists which APIs are guaranteed to be thread safe by the driver. Kconfig Options - lists the supported Kconfig options that can be used to make a different effect on driver behavior. Resource Allocation Different ESP chips might have different numbers of independent timer groups, and within each group, there could also be several independent timers. 1 A GPTimer instance is represented by gptimer_handle_t. The driver behind manages all available hardware resources in a pool, so that you do not need to care about which timer and which group it belongs to. To install a timer instance, there is a configuration structure that needs to be given in advance: gptimer_config_t: gptimer_config_t::clk_srcselects the source clock for the timer. The available clocks are listed in gptimer_clock_source_t, you can only pick one of them. For the effect on power consumption of different clock source, please refer to Section Power Management. gptimer_config_t::directionsets the counting direction of the timer, supported directions are listed in gptimer_count_direction_t, you can only pick one of them. gptimer_config_t::resolution_hzsets the resolution of the internal counter. Each count step is equivalent to 1 / resolution_hz seconds. gptimer_config::intr_prioritysets the priority of the timer interrupt. If it is set to 0, the driver will allocate an interrupt with a default priority. Otherwise, the driver will use the given priority. Optional gptimer_config_t::intr_sharedsets whether or not mark the timer interrupt source as a shared one. For the pros/cons of a shared interrupt, you can refer to Interrupt Handling. With all the above configurations set in the structure, the structure can be passed to gptimer_new_timer() which will instantiate the timer instance and return a handle of the timer. The function can fail due to various errors such as insufficient memory, invalid arguments, etc. Specifically, when there are no more free timers (i.e., all hardware resources have been used up), then ESP_ERR_NOT_FOUND will be returned. The total number of available timers is represented by the SOC_TIMER_GROUP_TOTAL_TIMERS and its value depends on the ESP chip. If a previously created GPTimer instance is no longer required, you should recycle the timer by calling gptimer_del_timer(). This allows the underlying HW timer to be used for other purposes. Before deleting a GPTimer handle, please disable it by gptimer_disable() in advance or make sure it has not enabled yet by gptimer_enable(). Creating a GPTimer Handle with Resolution of 1 MHz gptimer_handle_t gptimer = NULL; gptimer_config_t timer_config = { .clk_src = GPTIMER_CLK_SRC_DEFAULT, .direction = GPTIMER_COUNT_UP, .resolution_hz = 1 * 1000 * 1000, // 1MHz, 1 tick = 1us }; ESP_ERROR_CHECK(gptimer_new_timer(&timer_config, &gptimer)); Set and Get Count Value When the GPTimer is created, the internal counter will be reset to zero by default. The counter value can be updated asynchronously by gptimer_set_raw_count(). The maximum count value is dependent on the bit width of the hardware timer, which is also reflected by the SOC macro SOC_TIMER_GROUP_COUNTER_BIT_WIDTH. When updating the raw count of an active timer, the timer will immediately start counting from the new value. Count value can be retrieved by gptimer_get_raw_count(), at any time. Set up Alarm Action For most of the use cases of GPTimer, you should set up the alarm action before starting the timer, except for the simple wall-clock scenario, where a free running timer is enough. To set up the alarm action, you should configure several members of gptimer_alarm_config_t based on how you make use of the alarm event: gptimer_alarm_config_t::alarm_countsets the target count value that triggers the alarm event. You should also take the counting direction into consideration when setting the alarm value. Specially, gptimer_alarm_config_t::alarm_countand gptimer_alarm_config_t::reload_countcannot be set to the same value when gptimer_alarm_config_t::auto_reload_on_alarmis true, as keeping reload with a target alarm count is meaningless. gptimer_alarm_config_t::reload_countsets the count value to be reloaded when the alarm event happens. This configuration only takes effect when gptimer_alarm_config_t::auto_reload_on_alarmis set to true. gptimer_alarm_config_t::auto_reload_on_alarmflag sets whether to enable the auto-reload feature. If enabled, the hardware timer will reload the value of gptimer_alarm_config_t::reload_countinto counter immediately when an alarm event happens. To make the alarm configurations take effect, you should call gptimer_set_alarm_action(). Especially, if gptimer_alarm_config_t is set to NULL, the alarm function will be disabled. Note If an alarm value is set and the timer has already exceeded this value, the alarm will be triggered immediately. Register Event Callbacks After the timer starts up, it can generate a specific event (e.g., the "Alarm Event") dynamically. If you have some functions that should be called when the event happens, please hook your function to the interrupt service routine by calling gptimer_register_event_callbacks(). All supported event callbacks are listed in gptimer_event_callbacks_t: gptimer_event_callbacks_t::on_alarmsets a callback function for alarm events. As this function is called within the ISR context, you must ensure that the function does not attempt to block (e.g., by making sure that only FreeRTOS APIs with ISRsuffix are called from within the function). The function prototype is declared in gptimer_alarm_cb_t. You can save your own context to gptimer_register_event_callbacks() as well, via the parameter user_data. The user data will be directly passed to the callback function. This function lazy installs the interrupt service for the timer but not enable it. So please call this function before gptimer_enable(), otherwise the ESP_ERR_INVALID_STATE error will be returned. See Section Enable and Disable Timer for more information. Enable and Disable Timer Before doing IO control to the timer, you needs to enable the timer first, by calling gptimer_enable(). This function: Switches the timer driver state from init to enable. Enables the interrupt service if it has been lazy installed by gptimer_register_event_callbacks(). Acquires a proper power management lock if a specific clock source (e.g., APB clock) is selected. See Section Power Management for more information. Calling gptimer_disable() does the opposite, that is, put the timer driver back to the init state, disable the interrupts service and release the power management lock. Start and Stop Timer The basic IO operation of a timer is to start and stop. Calling gptimer_start() can make the internal counter work, while calling gptimer_stop() can make the counter stop working. The following illustrates how to start a timer with or without an alarm event. Calling gptimer_start() transits the driver state from enable to run, and vice versa. You need to make sure the start and stop functions are used in pairs, otherwise, the functions may return ESP_ERR_INVALID_STATE. Most of the time, this error means that the timer is already stopped or in the "start protection" state (i.e., gptimer_start() is called but not finished). Start Timer as a Wall Clock ESP_ERROR_CHECK(gptimer_enable(gptimer)); ESP_ERROR_CHECK(gptimer_start(gptimer)); // Retrieve the timestamp at any time uint64_t count; ESP_ERROR_CHECK(gptimer_get_raw_count(gptimer, &count)); Trigger Period Events typedef struct { uint64_t event_count; } example_queue_element_t; static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx) { BaseType_t high_task_awoken = pdFALSE; QueueHandle_t queue = (QueueHandle_t)user_ctx; // Retrieve the count value from event data example_queue_element_t ele = { .event_count = edata->count_value }; // Optional: send the event data to other task by OS queue // Do not introduce complex logics in callbacks // Suggest dealing with event data in the main loop, instead of in this callback xQueueSendFromISR(queue, &ele, &high_task_awoken); // return whether we need to yield at the end of ISR return high_task_awoken == pdTRUE; } gptimer_alarm_config_t alarm_config = { .reload_count = 0, // counter will reload with 0 on alarm event .alarm_count = 1000000, // period = 1s @resolution 1MHz .flags.auto_reload_on_alarm = true, // enable auto-reload }; ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config)); gptimer_event_callbacks_t cbs = { .on_alarm = example_timer_on_alarm_cb, // register user callback }; ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, queue)); ESP_ERROR_CHECK(gptimer_enable(gptimer)); ESP_ERROR_CHECK(gptimer_start(gptimer)); Trigger One-Shot Event typedef struct { uint64_t event_count; } example_queue_element_t; static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx) { BaseType_t high_task_awoken = pdFALSE; QueueHandle_t queue = (QueueHandle_t)user_ctx; // Stop timer the sooner the better gptimer_stop(timer); // Retrieve the count value from event data example_queue_element_t ele = { .event_count = edata->count_value }; // Optional: send the event data to other task by OS queue xQueueSendFromISR(queue, &ele, &high_task_awoken); // return whether we need to yield at the end of ISR return high_task_awoken == pdTRUE; } gptimer_alarm_config_t alarm_config = { .alarm_count = 1 * 1000 * 1000, // alarm target = 1s @resolution 1MHz }; ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config)); gptimer_event_callbacks_t cbs = { .on_alarm = example_timer_on_alarm_cb, // register user callback }; ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, queue)); ESP_ERROR_CHECK(gptimer_enable(gptimer)); ESP_ERROR_CHECK(gptimer_start(gptimer)); Dynamic Alarm Update Alarm value can be updated dynamically inside the ISR handler callback, by changing gptimer_alarm_event_data_t::alarm_value. Then the alarm value will be updated after the callback function returns. typedef struct { uint64_t event_count; } example_queue_element_t; static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx) { BaseType_t high_task_awoken = pdFALSE; QueueHandle_t queue = (QueueHandle_t)user_data; // Retrieve the count value from event data example_queue_element_t ele = { .event_count = edata->count_value }; // Optional: send the event data to other task by OS queue xQueueSendFromISR(queue, &ele, &high_task_awoken); // reconfigure alarm value gptimer_alarm_config_t alarm_config = { .alarm_count = edata->alarm_value + 1000000, // alarm in next 1s }; gptimer_set_alarm_action(timer, &alarm_config); // return whether we need to yield at the end of ISR return high_task_awoken == pdTRUE; } gptimer_alarm_config_t alarm_config = { .alarm_count = 1000000, // initial alarm target = 1s @resolution 1MHz }; ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config)); gptimer_event_callbacks_t cbs = { .on_alarm = example_timer_on_alarm_cb, // register user callback }; ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, queue)); ESP_ERROR_CHECK(gptimer_enable(gptimer)); ESP_ERROR_CHECK(gptimer_start(gptimer, &alarm_config)); Power Management There are some power management strategies, which might turn off or change the frequency of GPTimer's source clock to save power consumption. For example, during DFS, APB clock will be scaled down. If light-sleep is also enabled, PLL and XTAL clocks will be powered off. Both of them can result in an inaccurate time keeping. The driver can prevent the above situation from happening by creating different power management lock according to different clock source. The driver increases the reference count of that power management lock in the gptimer_enable() and decrease it in the gptimer_disable(). So we can ensure the clock source is stable between gptimer_enable() and gptimer_disable(). IRAM Safe By default, the GPTimer interrupt will be deferred when the cache is disabled because of writing or erasing the flash. Thus the alarm interrupt will not get executed in time, which is not expected in a real-time application. There is a Kconfig option CONFIG_GPTIMER_ISR_IRAM_SAFE that: Enables the interrupt being serviced even when the cache is disabled Places all functions that used by the ISR into IRAM 2 Places driver object into DRAM (in case it is mapped to PSRAM by accident) This allows the interrupt to run while the cache is disabled, but comes at the cost of increased IRAM consumption. There is another Kconfig option CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM that can put commonly used IO control functions into IRAM as well. So, these functions can also be executable when the cache is disabled. These IO control functions are as follows: Thread Safety All the APIs provided by the driver are guaranteed to be thread safe, which means you can call them from different RTOS tasks without protection by extra locks. The following functions are allowed to run under ISR context. Kconfig Options CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM controls where to place the GPTimer control functions (IRAM or flash). CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM controls where to place the GPTimer ISR handler (IRAM or flash). CONFIG_GPTIMER_ISR_IRAM_SAFE controls whether the default ISR handler should be masked when the cache is disabled, see Section IRAM Safe for more information. CONFIG_GPTIMER_ENABLE_DEBUG_LOG is used to enabled the debug log output. Enable this option will increase the firmware binary size. Application Examples Typical use cases of GPTimer are listed in the example peripherals/timer_group/gptimer. API Reference Header File This header file can be included with: #include "driver/gptimer.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t gptimer_new_timer(const gptimer_config_t *config, gptimer_handle_t *ret_timer) Create a new General Purpose Timer, and return the handle. Note The newly created timer is put in the "init" state. - Parameters config -- [in] GPTimer configuration ret_timer -- [out] Returned timer handle - - Returns ESP_OK: Create GPTimer successfully ESP_ERR_INVALID_ARG: Create GPTimer failed because of invalid argument ESP_ERR_NO_MEM: Create GPTimer failed because out of memory ESP_ERR_NOT_FOUND: Create GPTimer failed because all hardware timers are used up and no more free one ESP_FAIL: Create GPTimer failed because of other error - - esp_err_t gptimer_del_timer(gptimer_handle_t timer) Delete the GPTimer handle. Note A timer must be in the "init" state before it can be deleted. - Parameters timer -- [in] Timer handle created by gptimer_new_timer - Returns ESP_OK: Delete GPTimer successfully ESP_ERR_INVALID_ARG: Delete GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Delete GPTimer failed because the timer is not in init state ESP_FAIL: Delete GPTimer failed because of other error - - esp_err_t gptimer_set_raw_count(gptimer_handle_t timer, uint64_t value) Set GPTimer raw count value. Note When updating the raw count of an active timer, the timer will immediately start counting from the new value. Note This function is allowed to run within ISR context Note If CONFIG_GPTIMER_CTRL_FUNC_IN_IRAMis enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled. - Parameters timer -- [in] Timer handle created by gptimer_new_timer value -- [in] Count value to be set - - Returns ESP_OK: Set GPTimer raw count value successfully ESP_ERR_INVALID_ARG: Set GPTimer raw count value failed because of invalid argument ESP_FAIL: Set GPTimer raw count value failed because of other error - - esp_err_t gptimer_get_raw_count(gptimer_handle_t timer, uint64_t *value) Get GPTimer raw count value. Note This function will trigger a software capture event and then return the captured count value. Note With the raw count value and the resolution returned from gptimer_get_resolution, you can convert the count value into seconds. Note This function is allowed to run within ISR context Note If CONFIG_GPTIMER_CTRL_FUNC_IN_IRAMis enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled. - Parameters timer -- [in] Timer handle created by gptimer_new_timer value -- [out] Returned GPTimer count value - - Returns ESP_OK: Get GPTimer raw count value successfully ESP_ERR_INVALID_ARG: Get GPTimer raw count value failed because of invalid argument ESP_FAIL: Get GPTimer raw count value failed because of other error - - esp_err_t gptimer_get_resolution(gptimer_handle_t timer, uint32_t *out_resolution) Return the real resolution of the timer. Note usually the timer resolution is same as what you configured in the gptimer_config_t::resolution_hz, but some unstable clock source (e.g. RC_FAST) will do a calibration, the real resolution can be different from the configured one. - Parameters timer -- [in] Timer handle created by gptimer_new_timer out_resolution -- [out] Returned timer resolution, in Hz - - Returns ESP_OK: Get GPTimer resolution successfully ESP_ERR_INVALID_ARG: Get GPTimer resolution failed because of invalid argument ESP_FAIL: Get GPTimer resolution failed because of other error - - esp_err_t gptimer_get_captured_count(gptimer_handle_t timer, uint64_t *value) Get GPTimer captured count value. Note The capture action can be issued either by ETM event or by software (see also gptimer_get_raw_count). Note This function is allowed to run within ISR context Note If CONFIG_GPTIMER_CTRL_FUNC_IN_IRAMis enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled. - Parameters timer -- [in] Timer handle created by gptimer_new_timer value -- [out] Returned captured count value - - Returns ESP_OK: Get GPTimer captured count value successfully ESP_ERR_INVALID_ARG: Get GPTimer captured count value failed because of invalid argument ESP_FAIL: Get GPTimer captured count value failed because of other error - - esp_err_t gptimer_register_event_callbacks(gptimer_handle_t timer, const gptimer_event_callbacks_t *cbs, void *user_data) Set callbacks for GPTimer. Note User registered callbacks are expected to be runnable within ISR context Note The first call to this function needs to be before the call to gptimer_enable Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbsstructure to NULL. - Parameters timer -- [in] Timer handle created by gptimer_new_timer cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly - - Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because the timer is not in init state ESP_FAIL: Set event callbacks failed because of other error - - esp_err_t gptimer_set_alarm_action(gptimer_handle_t timer, const gptimer_alarm_config_t *config) Set alarm event actions for GPTimer. Note This function is allowed to run within ISR context, so that user can set new alarm action immediately in the ISR callback. Note If CONFIG_GPTIMER_CTRL_FUNC_IN_IRAMis enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled. - Parameters timer -- [in] Timer handle created by gptimer_new_timer config -- [in] Alarm configuration, especially, set config to NULL means disabling the alarm function - - Returns ESP_OK: Set alarm action for GPTimer successfully ESP_ERR_INVALID_ARG: Set alarm action for GPTimer failed because of invalid argument ESP_FAIL: Set alarm action for GPTimer failed because of other error - - esp_err_t gptimer_enable(gptimer_handle_t timer) Enable GPTimer. Note This function will transit the timer state from "init" to "enable". Note This function will enable the interrupt service, if it's lazy installed in gptimer_register_event_callbacks. Note This function will acquire a PM lock, if a specific source clock (e.g. APB) is selected in the gptimer_config_t, while CONFIG_PM_ENABLEis enabled. Note Enable a timer doesn't mean to start it. See also gptimer_startfor how to make the timer start counting. - Parameters timer -- [in] Timer handle created by gptimer_new_timer - Returns ESP_OK: Enable GPTimer successfully ESP_ERR_INVALID_ARG: Enable GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Enable GPTimer failed because the timer is already enabled ESP_FAIL: Enable GPTimer failed because of other error - - esp_err_t gptimer_disable(gptimer_handle_t timer) Disable GPTimer. Note This function will transit the timer state from "enable" to "init". Note This function will disable the interrupt service if it's installed. Note This function will release the PM lock if it's acquired in the gptimer_enable. Note Disable a timer doesn't mean to stop it. See also gptimer_stopfor how to make the timer stop counting. - Parameters timer -- [in] Timer handle created by gptimer_new_timer - Returns ESP_OK: Disable GPTimer successfully ESP_ERR_INVALID_ARG: Disable GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Disable GPTimer failed because the timer is not enabled yet ESP_FAIL: Disable GPTimer failed because of other error - - esp_err_t gptimer_start(gptimer_handle_t timer) Start GPTimer (internal counter starts counting) Note This function will transit the timer state from "enable" to "run". Note This function is allowed to run within ISR context Note If CONFIG_GPTIMER_CTRL_FUNC_IN_IRAMis enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled. - Parameters timer -- [in] Timer handle created by gptimer_new_timer - Returns ESP_OK: Start GPTimer successfully ESP_ERR_INVALID_ARG: Start GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Start GPTimer failed because the timer is not enabled or is already in running ESP_FAIL: Start GPTimer failed because of other error - - esp_err_t gptimer_stop(gptimer_handle_t timer) Stop GPTimer (internal counter stops counting) Note This function will transit the timer state from "run" to "enable". Note This function is allowed to run within ISR context Note If CONFIG_GPTIMER_CTRL_FUNC_IN_IRAMis enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled. - Parameters timer -- [in] Timer handle created by gptimer_new_timer - Returns ESP_OK: Stop GPTimer successfully ESP_ERR_INVALID_ARG: Stop GPTimer failed because of invalid argument ESP_ERR_INVALID_STATE: Stop GPTimer failed because the timer is not in running. ESP_FAIL: Stop GPTimer failed because of other error - Structures - struct gptimer_config_t General Purpose Timer configuration. Public Members - gptimer_clock_source_t clk_src GPTimer clock source - gptimer_count_direction_t direction Count direction - uint32_t resolution_hz Counter resolution (working frequency) in Hz, hence, the step size of each count tick equals to (1 / resolution_hz) seconds - int intr_priority GPTimer interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) Set true, the timer interrupt number can be shared with other peripherals - struct gptimer_config_t::[anonymous] flags GPTimer config flags - gptimer_clock_source_t clk_src - struct gptimer_event_callbacks_t Group of supported GPTimer callbacks. Note The callbacks are all running under ISR environment Note When CONFIG_GPTIMER_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. Public Members - gptimer_alarm_cb_t on_alarm Timer alarm callback - gptimer_alarm_cb_t on_alarm - struct gptimer_alarm_config_t General Purpose Timer alarm configuration. Public Members - uint64_t alarm_count Alarm target count value - uint64_t reload_count Alarm reload count value, effect only when auto_reload_on_alarmis set to true - uint32_t auto_reload_on_alarm Reload the count value by hardware, immediately at the alarm event - struct gptimer_alarm_config_t::[anonymous] flags Alarm config flags - uint64_t alarm_count Header File This header file can be included with: #include "driver/gptimer_etm.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t gptimer_new_etm_event(gptimer_handle_t timer, const gptimer_etm_event_config_t *config, esp_etm_event_handle_t *out_event) Get the ETM event for GPTimer. Note The created ETM event object can be deleted later by calling esp_etm_del_event - Parameters timer -- [in] Timer handle created by gptimer_new_timer config -- [in] GPTimer ETM event configuration out_event -- [out] Returned ETM event handle - - Returns ESP_OK: Get ETM event successfully ESP_ERR_INVALID_ARG: Get ETM event failed because of invalid argument ESP_FAIL: Get ETM event failed because of other error - - esp_err_t gptimer_new_etm_task(gptimer_handle_t timer, const gptimer_etm_task_config_t *config, esp_etm_task_handle_t *out_task) Get the ETM task for GPTimer. Note The created ETM task object can be deleted later by calling esp_etm_del_task - Parameters timer -- [in] Timer handle created by gptimer_new_timer config -- [in] GPTimer ETM task configuration out_task -- [out] Returned ETM task handle - - Returns ESP_OK: Get ETM task successfully ESP_ERR_INVALID_ARG: Get ETM task failed because of invalid argument ESP_FAIL: Get ETM task failed because of other error - Structures - struct gptimer_etm_event_config_t GPTimer ETM event configuration. Public Members - gptimer_etm_event_type_t event_type GPTimer ETM event type - gptimer_etm_event_type_t event_type - struct gptimer_etm_task_config_t GPTimer ETM task configuration. Public Members - gptimer_etm_task_type_t task_type GPTimer ETM task type - gptimer_etm_task_type_t task_type Header File This header file can be included with: #include "driver/gptimer_types.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Structures - struct gptimer_alarm_event_data_t GPTimer alarm event data. Type Definitions - typedef struct gptimer_t *gptimer_handle_t Type of General Purpose Timer handle. - typedef bool (*gptimer_alarm_cb_t)(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx) Timer alarm callback prototype. - Param timer [in] Timer handle created by gptimer_new_timer - Param edata [in] Alarm event data, fed by driver - Param user_ctx [in] User data, passed from gptimer_register_event_callbacks - Return Whether a high priority task has been waken up by this function Header File This header file can be included with: #include "hal/timer_types.h" Type Definitions - typedef soc_periph_gptimer_clk_src_t gptimer_clock_source_t GPTimer clock source. Note User should select the clock source based on the power and resolution requirement Enumerations - enum gptimer_count_direction_t GPTimer count direction. Values: - enumerator GPTIMER_COUNT_DOWN Decrease count value - enumerator GPTIMER_COUNT_UP Increase count value - enumerator GPTIMER_COUNT_DOWN - enum gptimer_etm_task_type_t GPTimer specific tasks that supported by the ETM module. Values: - enumerator GPTIMER_ETM_TASK_START_COUNT Start the counter - enumerator GPTIMER_ETM_TASK_STOP_COUNT Stop the counter - enumerator GPTIMER_ETM_TASK_EN_ALARM Enable the alarm - enumerator GPTIMER_ETM_TASK_RELOAD Reload preset value into counter - enumerator GPTIMER_ETM_TASK_CAPTURE Capture current count value into specific register - enumerator GPTIMER_ETM_TASK_MAX Maximum number of tasks - enumerator GPTIMER_ETM_TASK_START_COUNT - enum gptimer_etm_event_type_t GPTimer specific events that supported by the ETM module. Values: - enumerator GPTIMER_ETM_EVENT_ALARM_MATCH Count value matches the alarm target value - enumerator GPTIMER_ETM_EVENT_MAX Maximum number of events - enumerator GPTIMER_ETM_EVENT_ALARM_MATCH - 1 Different ESP chip series might have different numbers of GPTimer instances. For more details, please refer to ESP32 Technical Reference Manual > Chapter Timer Group (TIMG) [PDF]. The driver does forbid you from applying for more timers, but it returns error when all available hardware resources are used up. Please always check the return value when doing resource allocation (e.g., gptimer_new_timer()). - 2 gptimer_event_callbacks_t::on_alarmcallback and the functions invoked by the callback should also be placed in IRAM, please take care of them by yourself.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/gptimer.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Inter-Integrated Circuit (I2C)
null
espressif.com
2016-01-01
2ed9b813e24eb321
null
null
Inter-Integrated Circuit (I2C) Introduction I2C is a serial, synchronous, multi-device, half-duplex communication protocol that allows co-existence of multiple masters and slaves on the same bus. I2C uses two bidirectional open-drain lines: serial data line (SDA) and serial clock line (SCL), pulled up by resistors. ESP32 has 2 I2C controller (also called port), responsible for handling communication on the I2C bus. A single I2C controller can be a master or a slave. Typically, an I2C slave device has a 7-bit address or 10-bit address. ESP32 supports both I2C Standard-mode (Sm) and Fast-mode (Fm) which can go up to 100KHz and 400KHz respectively. Warning The clock frequency of SCL in master mode should not be larger than 400 KHz Note The frequency of SCL is influenced by both the pull-up resistor and the wire capacitance. Therefore, users are strongly recommended to choose appropriate pull-up resistors to make the frequency accurate. The recommended value for pull-up resistors usually ranges from 1K Ohms to 10K Ohms. Keep in mind that the higher the frequency, the smaller the pull-up resistor should be (but not less than 1 KOhms). Indeed, large resistors will decline the current, which will increase the clock switching time and reduce the frequency. We usually recommend a range of 2 KOhms to 5 KOhms, but users may also need to make some adjustments depending on their current draw requirements. I2C Clock Configuration i2c_clock_source_t::I2C_CLK_SRC_DEFAULT : Default I2C source clock. i2c_clock_source_t::I2C_CLK_SRC_APB : APB clock as I2C clock source. I2C File Structure Public headers that need to be included in the I2C application i2c.h : The header file of legacy I2C APIs (for apps using legacy driver). i2c_master.h : The header file that provides standard communication mode specific APIs (for apps using new driver with master mode). i2c_slave.h : The header file that provides standard communication mode specific APIs (for apps using new driver with slave mode). Note The legacy driver can't coexist with the new driver. Include i2c.h to use the legacy driver or the other two headers to use the new driver. Please keep in mind that the legacy driver is now deprecated and will be removed in future. Public headers that have been included in the headers above i2c_types_legacy.h : The legacy public types that only used in the legacy driver. i2c_types.h : The header file that provides public types. Functional Overview The I2C driver offers following services: Resource Allocation - covers how to allocate I2C bus with properly set of configurations. It also covers how to recycle the resources when they finished working. I2C Master Controller - covers behavior of I2C master controller. Introduce data transmit, data receive, and data transmit and receive. I2C Slave Controller - covers behavior of I2C slave controller. Involve data transmit and data receive. Power Management - describes how different source clock will affect power consumption. IRAM Safe - describes tips on how to make the I2C interrupt work better along with a disabled cache. Thread Safety - lists which APIs are guaranteed to be thread safe by the driver. Kconfig Options - lists the supported Kconfig options that can bring different effects to the driver. Resource Allocation Both I2C master bus and I2C slave bus, when supported, are represented by i2c_bus_handle_t in the driver. The available ports are managed in a resource pool that allocates a free port on request. Install I2C master bus and device The I2C master is designed based on bus-device model. So i2c_master_bus_config_t and i2c_device_config_t are required separately to allocate the I2C master bus instance and I2C device instance. I2C master bus requires the configuration that specified by i2c_master_bus_config_t : i2c_master_bus_config_t::i2c_port sets the I2C port used by the controller. i2c_master_bus_config_t::sda_io_num sets the GPIO number for the serial data bus (SDA). i2c_master_bus_config_t::scl_io_num sets the GPIO number for the serial clock bus (SCL). i2c_master_bus_config_t::clk_source selects the source clock for I2C bus. The available clocks are listed in i2c_clock_source_t . For the effect on power consumption of different clock source, please refer to Power Management section. i2c_master_bus_config_t::glitch_ignore_cnt sets the glitch period of master bus, if the glitch period on the line is less than this value, it can be filtered out, typically value is 7. i2c_master_bus_config_t::intr_priority Set the priority of the interrupt. If set to 0 , then the driver will use a interrupt with low or medium priority (priority level may be one of 1,2 or 3), otherwise use the priority indicated by i2c_master_bus_config_t::intr_priority Please use the number form (1,2,3) , not the bitmask form ((1<<1),(1<<2),(1<<3)). i2c_master_bus_config_t::trans_queue_depth Depth of internal transfer queue. Only valid in asynchronous transaction. i2c_master_bus_config_t::enable_internal_pullup Enable internal pullups. Note: This is not strong enough to pullup buses under high-speed frequency. A suitable external pullup is recommended. If the configurations in i2c_master_bus_config_t is specified, users can call i2c_new_master_bus() to allocate and initialize an I2C master bus. This function will return an I2C bus handle if it runs correctly. Specifically, when there are no more I2C port available, this function will return ESP_ERR_NOT_FOUND error. I2C master device requires the configuration that specified by i2c_device_config_t : i2c_device_config_t::dev_addr_length configure the address bit length of the slave device. User can choose from enumerator I2C_ADDR_BIT_LEN_7 or I2C_ADDR_BIT_LEN_10 (if supported). i2c_device_config_t::device_address I2C device raw address. Please parse the device address to this member directly. For example, the device address is 0x28, then parse 0x28 to i2c_device_config_t::device_address , don't carry a write/read bit. i2c_device_config_t::scl_speed_hz set the scl line frequency of this device. Once the i2c_device_config_t structure is populated with mandatory parameters, users can call i2c_master_bus_add_device() to allocate an I2C device instance and mounted to the master bus then. This function will return an I2C device handle if it runs correctly. Specifically, when the I2C bus is not initialized properly, calling this function will result in a ESP_ERR_INVALID_ARG error. #include "driver/i2c_master.h" i2c_master_bus_config_t i2c_mst_config = { .clk_source = I2C_CLK_SRC_DEFAULT, .i2c_port = TEST_I2C_PORT, .scl_io_num = I2C_MASTER_SCL_IO, .sda_io_num = I2C_MASTER_SDA_IO, .glitch_ignore_cnt = 7, .flags.enable_internal_pullup = true, }; i2c_master_bus_handle_t bus_handle; ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle)); i2c_device_config_t dev_cfg = { .dev_addr_length = I2C_ADDR_BIT_LEN_7, .device_address = 0x58, .scl_speed_hz = 100000, }; i2c_master_dev_handle_t dev_handle; ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle)); Uninstall I2C master bus and device If a previously installed I2C bus or device is no longer needed, it's recommended to recycle the resource by calling i2c_master_bus_rm_device() or i2c_del_master_bus() , so that to release the underlying hardware. Install I2C slave device I2C slave requires the configuration that specified by i2c_slave_config_t : i2c_slave_config_t::i2c_port sets the I2C port used by the controller. i2c_slave_config_t::sda_io_num sets the GPIO number for serial data bus (SDA). i2c_slave_config_t::scl_io_num sets the GPIO number for serial clock bus (SCL). i2c_slave_config_t::clk_source selects the source clock for I2C bus. The available clocks are listed in i2c_clock_source_t . For the effect on power consumption of different clock source, please refer to Power Management section. i2c_slave_config_t::send_buf_depth sets the sending buffer length. i2c_slave_config_t::slave_addr sets the slave address i2c_master_bus_config_t::intr_priority Set the priority of the interrupt. If set to 0 , then the driver will use a interrupt with low or medium priority (priority level may be one of 1,2 or 3), otherwise use the priority indicated by i2c_master_bus_config_t::intr_priority Please use the number form (1,2,3) , not the bitmask form ((1<<1),(1<<2),(1<<3)). Please pay attention that once the interrupt priority is set, it cannot be changed until i2c_del_master_bus() is called. i2c_slave_config_t::addr_bit_len sets true if you need the slave to have a 10-bit address. Once the i2c_slave_config_t structure is populated with mandatory parameters, users can call i2c_new_slave_device() to allocate and initialize an I2C master bus. This function will return an I2C bus handle if it runs correctly. Specifically, when there are no more I2C port available, this function will return ESP_ERR_NOT_FOUND error. i2c_slave_config_t i2c_slv_config = { .addr_bit_len = I2C_ADDR_BIT_LEN_7, .clk_source = I2C_CLK_SRC_DEFAULT, .i2c_port = TEST_I2C_PORT, .send_buf_depth = 256, .scl_io_num = I2C_SLAVE_SCL_IO, .sda_io_num = I2C_SLAVE_SDA_IO, .slave_addr = 0x58, }; i2c_slave_dev_handle_t slave_handle; ESP_ERROR_CHECK(i2c_new_slave_device(&i2c_slv_config, &slave_handle)); Uninstall I2C slave device If a previously installed I2C bus is no longer needed, it's recommended to recycle the resource by calling i2c_del_slave_device() , so that to release the underlying hardware. I2C Master Controller After installing the i2c master driver by i2c_new_master_bus() , ESP32 is ready to communicate with other I2C devices. I2C APIs allow the standard transactions. Like the wave as follows: I2C Master Write After installing I2C master bus successfully, you can simply call i2c_master_transmit() to write data to the slave device. The principle of this function can be explained by following chart. In order to organize the process, the driver uses a command link, that should be populated with a sequence of commands and then passed to I2C controller for execution. Simple example for writing data to slave: #define DATA_LENGTH 100 i2c_master_bus_config_t i2c_mst_config = { .clk_source = I2C_CLK_SRC_DEFAULT, .i2c_port = I2C_PORT_NUM_0, .scl_io_num = I2C_MASTER_SCL_IO, .sda_io_num = I2C_MASTER_SDA_IO, .glitch_ignore_cnt = 7, }; i2c_master_bus_handle_t bus_handle; ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle)); i2c_device_config_t dev_cfg = { .dev_addr_length = I2C_ADDR_BIT_LEN_7, .device_address = 0x58, .scl_speed_hz = 100000, }; i2c_master_dev_handle_t dev_handle; ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle)); ESP_ERROR_CHECK(i2c_master_transmit(dev_handle, data_wr, DATA_LENGTH, -1)); I2C Master Read After installing I2C master bus successfully, you can simply call i2c_master_receive() to read data from the slave device. The principle of this function can be explained by following chart. Simple example for reading data from slave: #define DATA_LENGTH 100 i2c_master_bus_config_t i2c_mst_config = { .clk_source = I2C_CLK_SRC_DEFAULT, .i2c_port = I2C_PORT_NUM_0, .scl_io_num = I2C_MASTER_SCL_IO, .sda_io_num = I2C_MASTER_SDA_IO, .glitch_ignore_cnt = 7, }; i2c_master_bus_handle_t bus_handle; ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle)); i2c_device_config_t dev_cfg = { .dev_addr_length = I2C_ADDR_BIT_LEN_7, .device_address = 0x58, .scl_speed_hz = 100000, }; i2c_master_dev_handle_t dev_handle; ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle)); i2c_master_receive(dev_handle, data_rd, DATA_LENGTH, -1); I2C Master Write and Read Some I2C device needs write configurations before reading data from it, therefore, an interface called i2c_master_transmit_receive() can help. The principle of this function can be explained by following chart. Simple example for writing and reading from slave: i2c_device_config_t dev_cfg = { .dev_addr_length = I2C_ADDR_BIT_LEN_7, .device_address = 0x58, .scl_speed_hz = 100000, }; i2c_master_dev_handle_t dev_handle; ESP_ERROR_CHECK(i2c_master_bus_add_device(I2C_PORT_NUM_0, &dev_cfg, &dev_handle)); uint8_t buf[20] = {0x20}; uint8_t buffer[2]; ESP_ERROR_CHECK(i2c_master_transmit_receive(i2c_bus_handle, buf, sizeof(buf), buffer, 2, -1)); I2C Master Probe I2C driver can use i2c_master_probe() to detect whether the specific device has been connected on I2C bus. If this function return ESP_OK , that means the device has been detected. Simple example for probing an I2C device: i2c_master_bus_config_t i2c_mst_config_1 = { .clk_source = I2C_CLK_SRC_DEFAULT, .i2c_port = TEST_I2C_PORT, .scl_io_num = I2C_MASTER_SCL_IO, .sda_io_num = I2C_MASTER_SDA_IO, .glitch_ignore_cnt = 7, .flags.enable_internal_pullup = true, }; i2c_master_bus_handle_t bus_handle; ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config_1, &bus_handle)); ESP_ERROR_CHECK(i2c_master_probe(bus_handle, 0x22, -1)); ESP_ERROR_CHECK(i2c_del_master_bus(bus_handle)); I2C Slave Controller After installing the i2c slave driver by i2c_new_slave_device() , ESP32 is ready to communicate with other I2C master as a slave. I2C Slave Write The send buffer of the I2C slave is used as a FIFO to store the data to be sent. The data will queue up until the master requests them. You can call i2c_slave_transmit() to transfer data. Simple example for writing data to FIFO: uint8_t *data_wr = (uint8_t *) malloc(DATA_LENGTH); i2c_slave_config_t i2c_slv_config = { .addr_bit_len = I2C_ADDR_BIT_LEN_7, // 7-bit address .clk_source = I2C_CLK_SRC_DEFAULT, // set the clock source .i2c_port = 0, // set I2C port number .send_buf_depth = 256, // set tx buffer length .scl_io_num = 2, // SCL gpio number .sda_io_num = 1, // SDA gpio number .slave_addr = 0x58, // slave address }; i2c_bus_handle_t i2c_bus_handle; ESP_ERROR_CHECK(i2c_new_slave_device(&i2c_slv_config, &i2c_bus_handle)); for (int i = 0; i < DATA_LENGTH; i++) { data_wr[i] = i; } ESP_ERROR_CHECK(i2c_slave_transmit(i2c_bus_handle, data_wr, DATA_LENGTH, 10000)); I2C Slave Read Whenever the master writes data to the slave, the slave will automatically store data in the receive buffer. This allows the slave application to call the function i2c_slave_receive() as its own discretion. As i2c_slave_receive() is designed as a non-blocking interface. So the user needs to register callback i2c_slave_register_event_callbacks() to know when the receive has finished. static IRAM_ATTR bool i2c_slave_rx_done_callback(i2c_slave_dev_handle_t channel, const i2c_slave_rx_done_event_data_t *edata, void *user_data) { BaseType_t high_task_wakeup = pdFALSE; QueueHandle_t receive_queue = (QueueHandle_t)user_data; xQueueSendFromISR(receive_queue, edata, &high_task_wakeup); return high_task_wakeup == pdTRUE; } uint8_t *data_rd = (uint8_t *) malloc(DATA_LENGTH); uint32_t size_rd = 0; i2c_slave_config_t i2c_slv_config = { .addr_bit_len = I2C_ADDR_BIT_LEN_7, .clk_source = I2C_CLK_SRC_DEFAULT, .i2c_port = TEST_I2C_PORT, .send_buf_depth = 256, .scl_io_num = I2C_SLAVE_SCL_IO, .sda_io_num = I2C_SLAVE_SDA_IO, .slave_addr = 0x58, }; i2c_slave_dev_handle_t slave_handle; ESP_ERROR_CHECK(i2c_new_slave_device(&i2c_slv_config, &slave_handle)); s_receive_queue = xQueueCreate(1, sizeof(i2c_slave_rx_done_event_data_t)); i2c_slave_event_callbacks_t cbs = { .on_recv_done = i2c_slave_rx_done_callback, }; ESP_ERROR_CHECK(i2c_slave_register_event_callbacks(slave_handle, &cbs, s_receive_queue)); i2c_slave_rx_done_event_data_t rx_data; ESP_ERROR_CHECK(i2c_slave_receive(slave_handle, data_rd, DATA_LENGTH)); xQueueReceive(s_receive_queue, &rx_data, pdMS_TO_TICKS(10000)); // Receive done. Register Event Callbacks I2C master callbacks When an I2C master bus triggers an interrupt, a specific event will be generated and notify the CPU. If you have some functions that need to be called when those events occurred, you can hook your functions to the ISR (Interrupt Service Routine) by calling i2c_master_register_event_callbacks() . Since the registered callback functions are called in the interrupt context, user should ensure the callback function doesn't attempt to block (e.g. by making sure that only FreeRTOS APIs with ISR suffix are called from within the function). The callback functions are required to return a boolean value, to tell the ISR whether a high priority task is woke up by it. I2C master event callbacks are listed in the i2c_master_event_callbacks_t . Although I2C is a synchronous communication protocol, we also support asynchronous behavior by registering above callback. In this way, I2C APIs will be non-blocking interface. But note that on the same bus, only one device can adopt asynchronous operation. Important I2C master asynchronous transaction is still an experimental feature. (The issue is when asynchronous transaction is very large, it will cause memory problem.) i2c_master_event_callbacks_t::on_recv_done sets a callback function for master "transaction-done" event. The function prototype is declared in i2c_master_callback_t . I2C slave callbacks When an I2C slave bus triggers an interrupt, a specific event will be generated and notify the CPU. If you have some function that needs to be called when those events occurred, you can hook your function to the ISR (Interrupt Service Routine) by calling i2c_slave_register_event_callbacks() . Since the registered callback functions are called in the interrupt context, user should ensure the callback function doesn't attempt to block (e.g. by making sure that only FreeRTOS APIs with ISR suffix are called from within the function). The callback function has a boolean return value, to tell the caller whether a high priority task is woke up by it. I2C slave event callbacks are listed in the i2c_slave_event_callbacks_t . i2c_slave_event_callbacks_t::on_recv_done sets a callback function for "receive-done" event. The function prototype is declared in i2c_slave_received_callback_t . Power Management When the power management is enabled (i.e. CONFIG_PM_ENABLE is on), the system will adjust or stop the source clock of I2C fifo before going into light sleep, thus potentially changing the I2C signals and leading to transmitting or receiving invalid data. However, the driver can prevent the system from changing APB frequency by acquiring a power management lock of type ESP_PM_APB_FREQ_MAX . Whenever user creates an I2C bus that has selected I2C_CLK_SRC_APB as the clock source, the driver will guarantee that the power management lock is acquired when I2C operations begin and release the lock automatically when I2C operations finish. IRAM Safe By default, the I2C interrupt will be deferred when the Cache is disabled for reasons like writing/erasing Flash. Thus the event callback functions will not get executed in time, which is not expected in a real-time application. There's a Kconfig option CONFIG_I2C_ISR_IRAM_SAFE that will: Enable the interrupt being serviced even when cache is disabled Place all functions that used by the ISR into IRAM Place driver object into DRAM (in case it's mapped to PSRAM by accident) This will allow the interrupt to run while the cache is disabled but will come at the cost of increased IRAM consumption. Thread Safety The factory function i2c_new_master_bus() and i2c_new_slave_device() are guaranteed to be thread safe by the driver, which means, user can call them from different RTOS tasks without protection by extra locks. Other public I2C APIs are not thread safe. which means the user should avoid calling them from multiple tasks, if user strongly needs to call them in multiple tasks, please add extra lock. Kconfig Options CONFIG_I2C_ISR_IRAM_SAFE controls whether the default ISR handler can work when cache is disabled, see also IRAM Safe for more information. CONFIG_I2C_ENABLE_DEBUG_LOG is used to enable the debug log at the cost of increased firmware binary size. API Reference Header File This header file can be included with: #include "driver/i2c_master.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t i2c_new_master_bus(const i2c_master_bus_config_t *bus_config, i2c_master_bus_handle_t *ret_bus_handle) Allocate an I2C master bus. Parameters bus_config -- [in] I2C master bus configuration. ret_bus_handle -- [out] I2C bus handle bus_config -- [in] I2C master bus configuration. ret_bus_handle -- [out] I2C bus handle bus_config -- [in] I2C master bus configuration. Returns ESP_OK: I2C master bus initialized successfully. ESP_ERR_INVALID_ARG: I2C bus initialization failed because of invalid argument. ESP_ERR_NO_MEM: Create I2C bus failed because of out of memory. ESP_ERR_NOT_FOUND: No more free bus. ESP_OK: I2C master bus initialized successfully. ESP_ERR_INVALID_ARG: I2C bus initialization failed because of invalid argument. ESP_ERR_NO_MEM: Create I2C bus failed because of out of memory. ESP_ERR_NOT_FOUND: No more free bus. ESP_OK: I2C master bus initialized successfully. Parameters bus_config -- [in] I2C master bus configuration. ret_bus_handle -- [out] I2C bus handle Returns ESP_OK: I2C master bus initialized successfully. ESP_ERR_INVALID_ARG: I2C bus initialization failed because of invalid argument. ESP_ERR_NO_MEM: Create I2C bus failed because of out of memory. ESP_ERR_NOT_FOUND: No more free bus. esp_err_t i2c_master_bus_add_device(i2c_master_bus_handle_t bus_handle, const i2c_device_config_t *dev_config, i2c_master_dev_handle_t *ret_handle) Add I2C master BUS device. Parameters bus_handle -- [in] I2C bus handle. dev_config -- [in] device config. ret_handle -- [out] device handle. bus_handle -- [in] I2C bus handle. dev_config -- [in] device config. ret_handle -- [out] device handle. bus_handle -- [in] I2C bus handle. Returns ESP_OK: Create I2C master device successfully. ESP_ERR_INVALID_ARG: I2C bus initialization failed because of invalid argument. ESP_ERR_NO_MEM: Create I2C bus failed because of out of memory. ESP_OK: Create I2C master device successfully. ESP_ERR_INVALID_ARG: I2C bus initialization failed because of invalid argument. ESP_ERR_NO_MEM: Create I2C bus failed because of out of memory. ESP_OK: Create I2C master device successfully. Parameters bus_handle -- [in] I2C bus handle. dev_config -- [in] device config. ret_handle -- [out] device handle. Returns ESP_OK: Create I2C master device successfully. ESP_ERR_INVALID_ARG: I2C bus initialization failed because of invalid argument. ESP_ERR_NO_MEM: Create I2C bus failed because of out of memory. esp_err_t i2c_del_master_bus(i2c_master_bus_handle_t bus_handle) Deinitialize the I2C master bus and delete the handle. Parameters bus_handle -- [in] I2C bus handle. Returns ESP_OK: Delete I2C bus success, otherwise, failed. Otherwise: Some module delete failed. ESP_OK: Delete I2C bus success, otherwise, failed. Otherwise: Some module delete failed. ESP_OK: Delete I2C bus success, otherwise, failed. Parameters bus_handle -- [in] I2C bus handle. Returns ESP_OK: Delete I2C bus success, otherwise, failed. Otherwise: Some module delete failed. esp_err_t i2c_master_bus_rm_device(i2c_master_dev_handle_t handle) I2C master bus delete device. Parameters handle -- i2c device handle Returns ESP_OK: If device is successfully deleted. ESP_OK: If device is successfully deleted. ESP_OK: If device is successfully deleted. Parameters handle -- i2c device handle Returns ESP_OK: If device is successfully deleted. esp_err_t i2c_master_transmit(i2c_master_dev_handle_t i2c_dev, const uint8_t *write_buffer, size_t write_size, int xfer_timeout_ms) Perform a write transaction on the I2C bus. The transaction will be undergoing until it finishes or it reaches the timeout provided. Note If a callback was registered with i2c_master_register_event_callbacks , the transaction will be asynchronous, and thus, this function will return directly, without blocking. You will get finish information from callback. Besides, data buffer should always be completely prepared when callback is registered, otherwise, the data will get corrupt. Parameters i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . write_buffer -- [in] Data bytes to send on the I2C bus. write_size -- [in] Size, in bytes, of the write buffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . write_buffer -- [in] Data bytes to send on the I2C bus. write_size -- [in] Size, in bytes, of the write buffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . Returns ESP_OK: I2C master transmit success ESP_ERR_INVALID_ARG: I2C master transmit parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. ESP_OK: I2C master transmit success ESP_ERR_INVALID_ARG: I2C master transmit parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. ESP_OK: I2C master transmit success Parameters i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . write_buffer -- [in] Data bytes to send on the I2C bus. write_size -- [in] Size, in bytes, of the write buffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. Returns ESP_OK: I2C master transmit success ESP_ERR_INVALID_ARG: I2C master transmit parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. esp_err_t i2c_master_transmit_receive(i2c_master_dev_handle_t i2c_dev, const uint8_t *write_buffer, size_t write_size, uint8_t *read_buffer, size_t read_size, int xfer_timeout_ms) Perform a write-read transaction on the I2C bus. The transaction will be undergoing until it finishes or it reaches the timeout provided. Note If a callback was registered with i2c_master_register_event_callbacks , the transaction will be asynchronous, and thus, this function will return directly, without blocking. You will get finish information from callback. Besides, data buffer should always be completely prepared when callback is registered, otherwise, the data will get corrupt. Parameters i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . write_buffer -- [in] Data bytes to send on the I2C bus. write_size -- [in] Size, in bytes, of the write buffer. read_buffer -- [out] Data bytes received from i2c bus. read_size -- [in] Size, in bytes, of the read buffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . write_buffer -- [in] Data bytes to send on the I2C bus. write_size -- [in] Size, in bytes, of the write buffer. read_buffer -- [out] Data bytes received from i2c bus. read_size -- [in] Size, in bytes, of the read buffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . Returns ESP_OK: I2C master transmit-receive success ESP_ERR_INVALID_ARG: I2C master transmit parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. ESP_OK: I2C master transmit-receive success ESP_ERR_INVALID_ARG: I2C master transmit parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. ESP_OK: I2C master transmit-receive success Parameters i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . write_buffer -- [in] Data bytes to send on the I2C bus. write_size -- [in] Size, in bytes, of the write buffer. read_buffer -- [out] Data bytes received from i2c bus. read_size -- [in] Size, in bytes, of the read buffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. Returns ESP_OK: I2C master transmit-receive success ESP_ERR_INVALID_ARG: I2C master transmit parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. esp_err_t i2c_master_receive(i2c_master_dev_handle_t i2c_dev, uint8_t *read_buffer, size_t read_size, int xfer_timeout_ms) Perform a read transaction on the I2C bus. The transaction will be undergoing until it finishes or it reaches the timeout provided. Note If a callback was registered with i2c_master_register_event_callbacks , the transaction will be asynchronous, and thus, this function will return directly, without blocking. You will get finish information from callback. Besides, data buffer should always be completely prepared when callback is registered, otherwise, the data will get corrupt. Parameters i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . read_buffer -- [out] Data bytes received from i2c bus. read_size -- [in] Size, in bytes, of the read buffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . read_buffer -- [out] Data bytes received from i2c bus. read_size -- [in] Size, in bytes, of the read buffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . Returns ESP_OK: I2C master receive success ESP_ERR_INVALID_ARG: I2C master receive parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. ESP_OK: I2C master receive success ESP_ERR_INVALID_ARG: I2C master receive parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. ESP_OK: I2C master receive success Parameters i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . read_buffer -- [out] Data bytes received from i2c bus. read_size -- [in] Size, in bytes, of the read buffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. Returns ESP_OK: I2C master receive success ESP_ERR_INVALID_ARG: I2C master receive parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. esp_err_t i2c_master_probe(i2c_master_bus_handle_t bus_handle, uint16_t address, int xfer_timeout_ms) Probe I2C address, if address is correct and ACK is received, this function will return ESP_OK. Parameters bus_handle -- [in] I2C master device handle that created by i2c_master_bus_add_device . address -- [in] I2C device address that you want to probe. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever (Not recommended in this function). bus_handle -- [in] I2C master device handle that created by i2c_master_bus_add_device . address -- [in] I2C device address that you want to probe. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever (Not recommended in this function). bus_handle -- [in] I2C master device handle that created by i2c_master_bus_add_device . Returns ESP_OK: I2C device probe successfully ESP_ERR_NOT_FOUND: I2C probe failed, doesn't find the device with specific address you gave. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. ESP_OK: I2C device probe successfully ESP_ERR_NOT_FOUND: I2C probe failed, doesn't find the device with specific address you gave. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. ESP_OK: I2C device probe successfully Parameters bus_handle -- [in] I2C master device handle that created by i2c_master_bus_add_device . address -- [in] I2C device address that you want to probe. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever (Not recommended in this function). Returns ESP_OK: I2C device probe successfully ESP_ERR_NOT_FOUND: I2C probe failed, doesn't find the device with specific address you gave. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. esp_err_t i2c_master_register_event_callbacks(i2c_master_dev_handle_t i2c_dev, const i2c_master_event_callbacks_t *cbs, void *user_data) Register I2C transaction callbacks for a master device. Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbs structure to NULL. Note When CONFIG_I2C_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. The user_data should also reside in SRAM. Note If the callback is used for helping asynchronous transaction. On the same bus, only one device can be used for performing asynchronous operation. Parameters i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . Returns ESP_OK: Set I2C transaction callbacks successfully ESP_ERR_INVALID_ARG: Set I2C transaction callbacks failed because of invalid argument ESP_FAIL: Set I2C transaction callbacks failed because of other error ESP_OK: Set I2C transaction callbacks successfully ESP_ERR_INVALID_ARG: Set I2C transaction callbacks failed because of invalid argument ESP_FAIL: Set I2C transaction callbacks failed because of other error ESP_OK: Set I2C transaction callbacks successfully Parameters i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device . cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly Returns ESP_OK: Set I2C transaction callbacks successfully ESP_ERR_INVALID_ARG: Set I2C transaction callbacks failed because of invalid argument ESP_FAIL: Set I2C transaction callbacks failed because of other error esp_err_t i2c_master_bus_reset(i2c_master_bus_handle_t bus_handle) Reset the I2C master bus. Parameters bus_handle -- I2C bus handle. Returns ESP_OK: Reset succeed. ESP_ERR_INVALID_ARG: I2C master bus handle is not initialized. Otherwise: Reset failed. ESP_OK: Reset succeed. ESP_ERR_INVALID_ARG: I2C master bus handle is not initialized. Otherwise: Reset failed. ESP_OK: Reset succeed. Parameters bus_handle -- I2C bus handle. Returns ESP_OK: Reset succeed. ESP_ERR_INVALID_ARG: I2C master bus handle is not initialized. Otherwise: Reset failed. esp_err_t i2c_master_bus_wait_all_done(i2c_master_bus_handle_t bus_handle, int timeout_ms) Wait for all pending I2C transactions done. Parameters bus_handle -- [in] I2C bus handle timeout_ms -- [in] Wait timeout, in ms. Specially, -1 means to wait forever. bus_handle -- [in] I2C bus handle timeout_ms -- [in] Wait timeout, in ms. Specially, -1 means to wait forever. bus_handle -- [in] I2C bus handle Returns ESP_OK: Flush transactions successfully ESP_ERR_INVALID_ARG: Flush transactions failed because of invalid argument ESP_ERR_TIMEOUT: Flush transactions failed because of timeout ESP_FAIL: Flush transactions failed because of other error ESP_OK: Flush transactions successfully ESP_ERR_INVALID_ARG: Flush transactions failed because of invalid argument ESP_ERR_TIMEOUT: Flush transactions failed because of timeout ESP_FAIL: Flush transactions failed because of other error ESP_OK: Flush transactions successfully Parameters bus_handle -- [in] I2C bus handle timeout_ms -- [in] Wait timeout, in ms. Specially, -1 means to wait forever. Returns ESP_OK: Flush transactions successfully ESP_ERR_INVALID_ARG: Flush transactions failed because of invalid argument ESP_ERR_TIMEOUT: Flush transactions failed because of timeout ESP_FAIL: Flush transactions failed because of other error Structures struct i2c_master_bus_config_t I2C master bus specific configurations. Public Members i2c_port_num_t i2c_port I2C port number, -1 for auto selecting i2c_port_num_t i2c_port I2C port number, -1 for auto selecting gpio_num_t sda_io_num GPIO number of I2C SDA signal, pulled-up internally gpio_num_t sda_io_num GPIO number of I2C SDA signal, pulled-up internally gpio_num_t scl_io_num GPIO number of I2C SCL signal, pulled-up internally gpio_num_t scl_io_num GPIO number of I2C SCL signal, pulled-up internally i2c_clock_source_t clk_source Clock source of I2C master bus, channels in the same group must use the same clock source i2c_clock_source_t clk_source Clock source of I2C master bus, channels in the same group must use the same clock source uint8_t glitch_ignore_cnt If the glitch period on the line is less than this value, it can be filtered out, typically value is 7 (unit: I2C module clock cycle) uint8_t glitch_ignore_cnt If the glitch period on the line is less than this value, it can be filtered out, typically value is 7 (unit: I2C module clock cycle) int intr_priority I2C interrupt priority, if set to 0, driver will select the default priority (1,2,3). int intr_priority I2C interrupt priority, if set to 0, driver will select the default priority (1,2,3). size_t trans_queue_depth Depth of internal transfer queue, increase this value can support more transfers pending in the background, only valid in asynchronous transaction. (Typically max_device_num * per_transaction) size_t trans_queue_depth Depth of internal transfer queue, increase this value can support more transfers pending in the background, only valid in asynchronous transaction. (Typically max_device_num * per_transaction) uint32_t enable_internal_pullup Enable internal pullups. Note: This is not strong enough to pullup buses under high-speed frequency. Recommend proper external pull-up if possible uint32_t enable_internal_pullup Enable internal pullups. Note: This is not strong enough to pullup buses under high-speed frequency. Recommend proper external pull-up if possible struct i2c_master_bus_config_t::[anonymous] flags I2C master config flags struct i2c_master_bus_config_t::[anonymous] flags I2C master config flags i2c_port_num_t i2c_port struct i2c_device_config_t I2C device configuration. Public Members i2c_addr_bit_len_t dev_addr_length Select the address length of the slave device. i2c_addr_bit_len_t dev_addr_length Select the address length of the slave device. uint16_t device_address I2C device raw address. (The 7/10 bit address without read/write bit) uint16_t device_address I2C device raw address. (The 7/10 bit address without read/write bit) uint32_t scl_speed_hz I2C SCL line frequency. uint32_t scl_speed_hz I2C SCL line frequency. i2c_addr_bit_len_t dev_addr_length struct i2c_master_event_callbacks_t Group of I2C master callbacks, can be used to get status during transaction or doing other small things. But take care potential concurrency issues. Note The callbacks are all running under ISR context Note When CONFIG_I2C_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. Public Members i2c_master_callback_t on_trans_done I2C master transaction finish callback i2c_master_callback_t on_trans_done I2C master transaction finish callback i2c_master_callback_t on_trans_done Header File This header file can be included with: #include "driver/i2c_slave.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t i2c_new_slave_device(const i2c_slave_config_t *slave_config, i2c_slave_dev_handle_t *ret_handle) Initialize an I2C slave device. Parameters slave_config -- [in] I2C slave device configurations ret_handle -- [out] Return a generic I2C device handle slave_config -- [in] I2C slave device configurations ret_handle -- [out] Return a generic I2C device handle slave_config -- [in] I2C slave device configurations Returns ESP_OK: I2C slave device initialized successfully ESP_ERR_INVALID_ARG: I2C device initialization failed because of invalid argument. ESP_ERR_NO_MEM: Create I2C device failed because of out of memory. ESP_OK: I2C slave device initialized successfully ESP_ERR_INVALID_ARG: I2C device initialization failed because of invalid argument. ESP_ERR_NO_MEM: Create I2C device failed because of out of memory. ESP_OK: I2C slave device initialized successfully Parameters slave_config -- [in] I2C slave device configurations ret_handle -- [out] Return a generic I2C device handle Returns ESP_OK: I2C slave device initialized successfully ESP_ERR_INVALID_ARG: I2C device initialization failed because of invalid argument. ESP_ERR_NO_MEM: Create I2C device failed because of out of memory. esp_err_t i2c_del_slave_device(i2c_slave_dev_handle_t i2c_slave) Deinitialize the I2C slave device. Parameters i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device . Returns ESP_OK: Delete I2C device successfully. ESP_ERR_INVALID_ARG: I2C device initialization failed because of invalid argument. ESP_OK: Delete I2C device successfully. ESP_ERR_INVALID_ARG: I2C device initialization failed because of invalid argument. ESP_OK: Delete I2C device successfully. Parameters i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device . Returns ESP_OK: Delete I2C device successfully. ESP_ERR_INVALID_ARG: I2C device initialization failed because of invalid argument. esp_err_t i2c_slave_receive(i2c_slave_dev_handle_t i2c_slave, uint8_t *data, size_t buffer_size) Read bytes from I2C internal buffer. Start a job to receive I2C data. Note This function is non-blocking, it initiates a new receive job and then returns. User should check the received data from the on_recv_done callback that registered by i2c_slave_register_event_callbacks() . Parameters i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device . data -- [out] Buffer to store data from I2C fifo. Should be valid until on_recv_done is triggered. buffer_size -- [in] Buffer size of data that provided by users. i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device . data -- [out] Buffer to store data from I2C fifo. Should be valid until on_recv_done is triggered. buffer_size -- [in] Buffer size of data that provided by users. i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device . Returns ESP_OK: I2C slave receive success. ESP_ERR_INVALID_ARG: I2C slave receive parameter invalid. ESP_ERR_NOT_SUPPORTED: This function should be work in fifo mode, but I2C_SLAVE_NONFIFO mode is configured ESP_OK: I2C slave receive success. ESP_ERR_INVALID_ARG: I2C slave receive parameter invalid. ESP_ERR_NOT_SUPPORTED: This function should be work in fifo mode, but I2C_SLAVE_NONFIFO mode is configured ESP_OK: I2C slave receive success. Parameters i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device . data -- [out] Buffer to store data from I2C fifo. Should be valid until on_recv_done is triggered. buffer_size -- [in] Buffer size of data that provided by users. Returns ESP_OK: I2C slave receive success. ESP_ERR_INVALID_ARG: I2C slave receive parameter invalid. ESP_ERR_NOT_SUPPORTED: This function should be work in fifo mode, but I2C_SLAVE_NONFIFO mode is configured esp_err_t i2c_slave_transmit(i2c_slave_dev_handle_t i2c_slave, const uint8_t *data, int size, int xfer_timeout_ms) Write bytes to internal ringbuffer of the I2C slave data. When the TX fifo empty, the ISR will fill the hardware FIFO with the internal ringbuffer's data. Note If you connect this slave device to some master device, the data transaction direction is from slave device to master device. Parameters i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device . data -- [in] Buffer to write to slave fifo, can pickup by master. Can be freed after this function returns. Equal or larger than size . size -- [in] In bytes, of data buffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device . data -- [in] Buffer to write to slave fifo, can pickup by master. Can be freed after this function returns. Equal or larger than size . size -- [in] In bytes, of data buffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device . Returns ESP_OK: I2C slave transmit success. ESP_ERR_INVALID_ARG: I2C slave transmit parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the device is busy or hardware crash. ESP_ERR_NOT_SUPPORTED: This function should be work in fifo mode, but I2C_SLAVE_NONFIFO mode is configured ESP_OK: I2C slave transmit success. ESP_ERR_INVALID_ARG: I2C slave transmit parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the device is busy or hardware crash. ESP_ERR_NOT_SUPPORTED: This function should be work in fifo mode, but I2C_SLAVE_NONFIFO mode is configured ESP_OK: I2C slave transmit success. Parameters i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device . data -- [in] Buffer to write to slave fifo, can pickup by master. Can be freed after this function returns. Equal or larger than size . size -- [in] In bytes, of data buffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. Returns ESP_OK: I2C slave transmit success. ESP_ERR_INVALID_ARG: I2C slave transmit parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the device is busy or hardware crash. ESP_ERR_NOT_SUPPORTED: This function should be work in fifo mode, but I2C_SLAVE_NONFIFO mode is configured esp_err_t i2c_slave_register_event_callbacks(i2c_slave_dev_handle_t i2c_slave, const i2c_slave_event_callbacks_t *cbs, void *user_data) Set I2C slave event callbacks for I2C slave channel. Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbs structure to NULL. Note When CONFIG_I2C_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. The user_data should also reside in SRAM. Parameters i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device . cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device . cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device . Returns ESP_OK: Set I2C transaction callbacks successfully ESP_ERR_INVALID_ARG: Set I2C transaction callbacks failed because of invalid argument ESP_FAIL: Set I2C transaction callbacks failed because of other error ESP_OK: Set I2C transaction callbacks successfully ESP_ERR_INVALID_ARG: Set I2C transaction callbacks failed because of invalid argument ESP_FAIL: Set I2C transaction callbacks failed because of other error ESP_OK: Set I2C transaction callbacks successfully Parameters i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device . cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly Returns ESP_OK: Set I2C transaction callbacks successfully ESP_ERR_INVALID_ARG: Set I2C transaction callbacks failed because of invalid argument ESP_FAIL: Set I2C transaction callbacks failed because of other error Structures struct i2c_slave_config_t I2C slave specific configurations. Public Members i2c_port_num_t i2c_port I2C port number, -1 for auto selecting i2c_port_num_t i2c_port I2C port number, -1 for auto selecting gpio_num_t sda_io_num SDA IO number used by I2C bus gpio_num_t sda_io_num SDA IO number used by I2C bus gpio_num_t scl_io_num SCL IO number used by I2C bus gpio_num_t scl_io_num SCL IO number used by I2C bus i2c_clock_source_t clk_source Clock source of I2C bus. i2c_clock_source_t clk_source Clock source of I2C bus. uint32_t send_buf_depth Depth of internal transfer ringbuffer, increase this value can support more transfers pending in the background uint32_t send_buf_depth Depth of internal transfer ringbuffer, increase this value can support more transfers pending in the background uint16_t slave_addr I2C slave address uint16_t slave_addr I2C slave address i2c_addr_bit_len_t addr_bit_len I2C slave address in bit length i2c_addr_bit_len_t addr_bit_len I2C slave address in bit length int intr_priority I2C interrupt priority, if set to 0, driver will select the default priority (1,2,3). int intr_priority I2C interrupt priority, if set to 0, driver will select the default priority (1,2,3). struct i2c_slave_config_t::[anonymous] flags I2C slave config flags struct i2c_slave_config_t::[anonymous] flags I2C slave config flags i2c_port_num_t i2c_port struct i2c_slave_event_callbacks_t Group of I2C slave callbacks (e.g. get i2c slave stretch cause). But take care of potential concurrency issues. Note The callbacks are all running under ISR context Note When CONFIG_I2C_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. Public Members i2c_slave_received_callback_t on_recv_done I2C slave receive done callback i2c_slave_received_callback_t on_recv_done I2C slave receive done callback i2c_slave_received_callback_t on_recv_done Header File This header file can be included with: #include "driver/i2c_types.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Structures struct i2c_master_event_data_t Data type used in I2C event callback. Public Members i2c_master_event_t event The I2C hardware event that I2C callback is called. i2c_master_event_t event The I2C hardware event that I2C callback is called. i2c_master_event_t event Type Definitions typedef int i2c_port_num_t I2C port number. typedef struct i2c_master_bus_t *i2c_master_bus_handle_t Type of I2C master bus handle. typedef struct i2c_master_dev_t *i2c_master_dev_handle_t Type of I2C master bus device handle. typedef struct i2c_slave_dev_t *i2c_slave_dev_handle_t Type of I2C slave device handle. typedef bool (*i2c_master_callback_t)(i2c_master_dev_handle_t i2c_dev, const i2c_master_event_data_t *evt_data, void *arg) An callback for I2C transaction. Param i2c_dev [in] Handle for I2C device. Param evt_data [out] I2C capture event data, fed by driver Param arg [in] User data, set in i2c_master_register_event_callbacks() Return Whether a high priority task has been waken up by this function Param i2c_dev [in] Handle for I2C device. Param evt_data [out] I2C capture event data, fed by driver Param arg [in] User data, set in i2c_master_register_event_callbacks() Return Whether a high priority task has been waken up by this function typedef bool (*i2c_slave_received_callback_t)(i2c_slave_dev_handle_t i2c_slave, const i2c_slave_rx_done_event_data_t *evt_data, void *arg) Callback signature for I2C slave. Param i2c_slave [in] Handle for I2C slave. Param evt_data [out] I2C capture event data, fed by driver Param arg [in] User data, set in i2c_slave_register_event_callbacks() Return Whether a high priority task has been waken up by this function Param i2c_slave [in] Handle for I2C slave. Param evt_data [out] I2C capture event data, fed by driver Param arg [in] User data, set in i2c_slave_register_event_callbacks() Return Whether a high priority task has been waken up by this function Enumerations enum i2c_master_status_t Enumeration for I2C fsm status. Values: enumerator I2C_STATUS_READ read status for current master command enumerator I2C_STATUS_READ read status for current master command enumerator I2C_STATUS_WRITE write status for current master command enumerator I2C_STATUS_WRITE write status for current master command enumerator I2C_STATUS_START Start status for current master command enumerator I2C_STATUS_START Start status for current master command enumerator I2C_STATUS_STOP stop status for current master command enumerator I2C_STATUS_STOP stop status for current master command enumerator I2C_STATUS_IDLE idle status for current master command enumerator I2C_STATUS_IDLE idle status for current master command enumerator I2C_STATUS_ACK_ERROR ack error status for current master command enumerator I2C_STATUS_ACK_ERROR ack error status for current master command enumerator I2C_STATUS_DONE I2C command done enumerator I2C_STATUS_DONE I2C command done enumerator I2C_STATUS_TIMEOUT I2C bus status error, and operation timeout enumerator I2C_STATUS_TIMEOUT I2C bus status error, and operation timeout enumerator I2C_STATUS_READ Header File This header file can be included with: #include "hal/i2c_types.h" Structures struct i2c_hal_clk_config_t Data structure for calculating I2C bus timing. Public Members uint16_t clkm_div I2C core clock devider uint16_t clkm_div I2C core clock devider uint16_t scl_low I2C scl low period uint16_t scl_low I2C scl low period uint16_t scl_high I2C scl hight period uint16_t scl_high I2C scl hight period uint16_t scl_wait_high I2C scl wait_high period uint16_t scl_wait_high I2C scl wait_high period uint16_t sda_hold I2C scl low period uint16_t sda_hold I2C scl low period uint16_t sda_sample I2C sda sample time uint16_t sda_sample I2C sda sample time uint16_t setup I2C start and stop condition setup period uint16_t setup I2C start and stop condition setup period uint16_t hold I2C start and stop condition hold period uint16_t hold I2C start and stop condition hold period uint16_t tout I2C bus timeout period uint16_t tout I2C bus timeout period uint16_t clkm_div Type Definitions typedef soc_periph_i2c_clk_src_t i2c_clock_source_t I2C group clock source. Enumerations enum i2c_port_t I2C port number, can be I2C_NUM_0 ~ (I2C_NUM_MAX-1). Values: enumerator I2C_NUM_0 I2C port 0 enumerator I2C_NUM_0 I2C port 0 enumerator I2C_NUM_1 I2C port 1 enumerator I2C_NUM_1 I2C port 1 enumerator I2C_NUM_MAX I2C port max enumerator I2C_NUM_MAX I2C port max enumerator I2C_NUM_0 enum i2c_addr_bit_len_t Enumeration for I2C device address bit length. Values: enumerator I2C_ADDR_BIT_LEN_7 i2c address bit length 7 enumerator I2C_ADDR_BIT_LEN_7 i2c address bit length 7 enumerator I2C_ADDR_BIT_LEN_7 enum i2c_mode_t Values: enumerator I2C_MODE_SLAVE I2C slave mode enumerator I2C_MODE_SLAVE I2C slave mode enumerator I2C_MODE_MASTER I2C master mode enumerator I2C_MODE_MASTER I2C master mode enumerator I2C_MODE_MAX enumerator I2C_MODE_MAX enumerator I2C_MODE_SLAVE enum i2c_rw_t Values: enumerator I2C_MASTER_WRITE I2C write data enumerator I2C_MASTER_WRITE I2C write data enumerator I2C_MASTER_READ I2C read data enumerator I2C_MASTER_READ I2C read data enumerator I2C_MASTER_WRITE enum i2c_trans_mode_t Values: enumerator I2C_DATA_MODE_MSB_FIRST I2C data msb first enumerator I2C_DATA_MODE_MSB_FIRST I2C data msb first enumerator I2C_DATA_MODE_LSB_FIRST I2C data lsb first enumerator I2C_DATA_MODE_LSB_FIRST I2C data lsb first enumerator I2C_DATA_MODE_MAX enumerator I2C_DATA_MODE_MAX enumerator I2C_DATA_MODE_MSB_FIRST enum i2c_addr_mode_t Values: enumerator I2C_ADDR_BIT_7 I2C 7bit address for slave mode enumerator I2C_ADDR_BIT_7 I2C 7bit address for slave mode enumerator I2C_ADDR_BIT_10 I2C 10bit address for slave mode enumerator I2C_ADDR_BIT_10 I2C 10bit address for slave mode enumerator I2C_ADDR_BIT_MAX enumerator I2C_ADDR_BIT_MAX enumerator I2C_ADDR_BIT_7 enum i2c_ack_type_t Values: enumerator I2C_MASTER_ACK I2C ack for each byte read enumerator I2C_MASTER_ACK I2C ack for each byte read enumerator I2C_MASTER_NACK I2C nack for each byte read enumerator I2C_MASTER_NACK I2C nack for each byte read enumerator I2C_MASTER_LAST_NACK I2C nack for the last byte enumerator I2C_MASTER_LAST_NACK I2C nack for the last byte enumerator I2C_MASTER_ACK_MAX enumerator I2C_MASTER_ACK_MAX enumerator I2C_MASTER_ACK enum i2c_slave_stretch_cause_t Enum for I2C slave stretch causes. Values: enumerator I2C_SLAVE_STRETCH_CAUSE_ADDRESS_MATCH Stretching SCL low when the slave is read by the master and the address just matched enumerator I2C_SLAVE_STRETCH_CAUSE_ADDRESS_MATCH Stretching SCL low when the slave is read by the master and the address just matched enumerator I2C_SLAVE_STRETCH_CAUSE_TX_EMPTY Stretching SCL low when TX FIFO is empty in slave mode enumerator I2C_SLAVE_STRETCH_CAUSE_TX_EMPTY Stretching SCL low when TX FIFO is empty in slave mode enumerator I2C_SLAVE_STRETCH_CAUSE_RX_FULL Stretching SCL low when RX FIFO is full in slave mode enumerator I2C_SLAVE_STRETCH_CAUSE_RX_FULL Stretching SCL low when RX FIFO is full in slave mode enumerator I2C_SLAVE_STRETCH_CAUSE_SENDING_ACK Stretching SCL low when slave sending ACK enumerator I2C_SLAVE_STRETCH_CAUSE_SENDING_ACK Stretching SCL low when slave sending ACK enumerator I2C_SLAVE_STRETCH_CAUSE_ADDRESS_MATCH
Inter-Integrated Circuit (I2C) Introduction I2C is a serial, synchronous, multi-device, half-duplex communication protocol that allows co-existence of multiple masters and slaves on the same bus. I2C uses two bidirectional open-drain lines: serial data line (SDA) and serial clock line (SCL), pulled up by resistors. ESP32 has 2 I2C controller (also called port), responsible for handling communication on the I2C bus. A single I2C controller can be a master or a slave. Typically, an I2C slave device has a 7-bit address or 10-bit address. ESP32 supports both I2C Standard-mode (Sm) and Fast-mode (Fm) which can go up to 100KHz and 400KHz respectively. Warning The clock frequency of SCL in master mode should not be larger than 400 KHz Note The frequency of SCL is influenced by both the pull-up resistor and the wire capacitance. Therefore, users are strongly recommended to choose appropriate pull-up resistors to make the frequency accurate. The recommended value for pull-up resistors usually ranges from 1K Ohms to 10K Ohms. Keep in mind that the higher the frequency, the smaller the pull-up resistor should be (but not less than 1 KOhms). Indeed, large resistors will decline the current, which will increase the clock switching time and reduce the frequency. We usually recommend a range of 2 KOhms to 5 KOhms, but users may also need to make some adjustments depending on their current draw requirements. I2C Clock Configuration i2c_clock_source_t::I2C_CLK_SRC_DEFAULT: Default I2C source clock. i2c_clock_source_t::I2C_CLK_SRC_APB: APB clock as I2C clock source. I2C File Structure Public headers that need to be included in the I2C application i2c.h: The header file of legacy I2C APIs (for apps using legacy driver). i2c_master.h: The header file that provides standard communication mode specific APIs (for apps using new driver with master mode). i2c_slave.h: The header file that provides standard communication mode specific APIs (for apps using new driver with slave mode). Note The legacy driver can't coexist with the new driver. Include i2c.h to use the legacy driver or the other two headers to use the new driver. Please keep in mind that the legacy driver is now deprecated and will be removed in future. Public headers that have been included in the headers above i2c_types_legacy.h: The legacy public types that only used in the legacy driver. i2c_types.h: The header file that provides public types. Functional Overview The I2C driver offers following services: Resource Allocation - covers how to allocate I2C bus with properly set of configurations. It also covers how to recycle the resources when they finished working. I2C Master Controller - covers behavior of I2C master controller. Introduce data transmit, data receive, and data transmit and receive. I2C Slave Controller - covers behavior of I2C slave controller. Involve data transmit and data receive. Power Management - describes how different source clock will affect power consumption. IRAM Safe - describes tips on how to make the I2C interrupt work better along with a disabled cache. Thread Safety - lists which APIs are guaranteed to be thread safe by the driver. Kconfig Options - lists the supported Kconfig options that can bring different effects to the driver. Resource Allocation Both I2C master bus and I2C slave bus, when supported, are represented by i2c_bus_handle_t in the driver. The available ports are managed in a resource pool that allocates a free port on request. Install I2C master bus and device The I2C master is designed based on bus-device model. So i2c_master_bus_config_t and i2c_device_config_t are required separately to allocate the I2C master bus instance and I2C device instance. I2C master bus requires the configuration that specified by i2c_master_bus_config_t: i2c_master_bus_config_t::i2c_portsets the I2C port used by the controller. i2c_master_bus_config_t::sda_io_numsets the GPIO number for the serial data bus (SDA). i2c_master_bus_config_t::scl_io_numsets the GPIO number for the serial clock bus (SCL). i2c_master_bus_config_t::clk_sourceselects the source clock for I2C bus. The available clocks are listed in i2c_clock_source_t. For the effect on power consumption of different clock source, please refer to Power Management section. i2c_master_bus_config_t::glitch_ignore_cntsets the glitch period of master bus, if the glitch period on the line is less than this value, it can be filtered out, typically value is 7. i2c_master_bus_config_t::intr_prioritySet the priority of the interrupt. If set to 0, then the driver will use a interrupt with low or medium priority (priority level may be one of 1,2 or 3), otherwise use the priority indicated by i2c_master_bus_config_t::intr_priorityPlease use the number form (1,2,3) , not the bitmask form ((1<<1),(1<<2),(1<<3)). i2c_master_bus_config_t::trans_queue_depthDepth of internal transfer queue. Only valid in asynchronous transaction. i2c_master_bus_config_t::enable_internal_pullupEnable internal pullups. Note: This is not strong enough to pullup buses under high-speed frequency. A suitable external pullup is recommended. If the configurations in i2c_master_bus_config_t is specified, users can call i2c_new_master_bus() to allocate and initialize an I2C master bus. This function will return an I2C bus handle if it runs correctly. Specifically, when there are no more I2C port available, this function will return ESP_ERR_NOT_FOUND error. I2C master device requires the configuration that specified by i2c_device_config_t: i2c_device_config_t::dev_addr_lengthconfigure the address bit length of the slave device. User can choose from enumerator I2C_ADDR_BIT_LEN_7or I2C_ADDR_BIT_LEN_10(if supported). i2c_device_config_t::device_addressI2C device raw address. Please parse the device address to this member directly. For example, the device address is 0x28, then parse 0x28 to i2c_device_config_t::device_address, don't carry a write/read bit. i2c_device_config_t::scl_speed_hzset the scl line frequency of this device. Once the i2c_device_config_t structure is populated with mandatory parameters, users can call i2c_master_bus_add_device() to allocate an I2C device instance and mounted to the master bus then. This function will return an I2C device handle if it runs correctly. Specifically, when the I2C bus is not initialized properly, calling this function will result in a ESP_ERR_INVALID_ARG error. #include "driver/i2c_master.h" i2c_master_bus_config_t i2c_mst_config = { .clk_source = I2C_CLK_SRC_DEFAULT, .i2c_port = TEST_I2C_PORT, .scl_io_num = I2C_MASTER_SCL_IO, .sda_io_num = I2C_MASTER_SDA_IO, .glitch_ignore_cnt = 7, .flags.enable_internal_pullup = true, }; i2c_master_bus_handle_t bus_handle; ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle)); i2c_device_config_t dev_cfg = { .dev_addr_length = I2C_ADDR_BIT_LEN_7, .device_address = 0x58, .scl_speed_hz = 100000, }; i2c_master_dev_handle_t dev_handle; ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle)); Uninstall I2C master bus and device If a previously installed I2C bus or device is no longer needed, it's recommended to recycle the resource by calling i2c_master_bus_rm_device() or i2c_del_master_bus(), so that to release the underlying hardware. Install I2C slave device I2C slave requires the configuration that specified by i2c_slave_config_t: i2c_slave_config_t::i2c_portsets the I2C port used by the controller. i2c_slave_config_t::sda_io_numsets the GPIO number for serial data bus (SDA). i2c_slave_config_t::scl_io_numsets the GPIO number for serial clock bus (SCL). i2c_slave_config_t::clk_sourceselects the source clock for I2C bus. The available clocks are listed in i2c_clock_source_t. For the effect on power consumption of different clock source, please refer to Power Management section. i2c_slave_config_t::send_buf_depthsets the sending buffer length. i2c_slave_config_t::slave_addrsets the slave address i2c_master_bus_config_t::intr_prioritySet the priority of the interrupt. If set to 0, then the driver will use a interrupt with low or medium priority (priority level may be one of 1,2 or 3), otherwise use the priority indicated by i2c_master_bus_config_t::intr_priorityPlease use the number form (1,2,3) , not the bitmask form ((1<<1),(1<<2),(1<<3)). Please pay attention that once the interrupt priority is set, it cannot be changed until i2c_del_master_bus()is called. i2c_slave_config_t::addr_bit_lensets true if you need the slave to have a 10-bit address. Once the i2c_slave_config_t structure is populated with mandatory parameters, users can call i2c_new_slave_device() to allocate and initialize an I2C master bus. This function will return an I2C bus handle if it runs correctly. Specifically, when there are no more I2C port available, this function will return ESP_ERR_NOT_FOUND error. i2c_slave_config_t i2c_slv_config = { .addr_bit_len = I2C_ADDR_BIT_LEN_7, .clk_source = I2C_CLK_SRC_DEFAULT, .i2c_port = TEST_I2C_PORT, .send_buf_depth = 256, .scl_io_num = I2C_SLAVE_SCL_IO, .sda_io_num = I2C_SLAVE_SDA_IO, .slave_addr = 0x58, }; i2c_slave_dev_handle_t slave_handle; ESP_ERROR_CHECK(i2c_new_slave_device(&i2c_slv_config, &slave_handle)); Uninstall I2C slave device If a previously installed I2C bus is no longer needed, it's recommended to recycle the resource by calling i2c_del_slave_device(), so that to release the underlying hardware. I2C Master Controller After installing the i2c master driver by i2c_new_master_bus(), ESP32 is ready to communicate with other I2C devices. I2C APIs allow the standard transactions. Like the wave as follows: I2C Master Write After installing I2C master bus successfully, you can simply call i2c_master_transmit() to write data to the slave device. The principle of this function can be explained by following chart. In order to organize the process, the driver uses a command link, that should be populated with a sequence of commands and then passed to I2C controller for execution. Simple example for writing data to slave: #define DATA_LENGTH 100 i2c_master_bus_config_t i2c_mst_config = { .clk_source = I2C_CLK_SRC_DEFAULT, .i2c_port = I2C_PORT_NUM_0, .scl_io_num = I2C_MASTER_SCL_IO, .sda_io_num = I2C_MASTER_SDA_IO, .glitch_ignore_cnt = 7, }; i2c_master_bus_handle_t bus_handle; ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle)); i2c_device_config_t dev_cfg = { .dev_addr_length = I2C_ADDR_BIT_LEN_7, .device_address = 0x58, .scl_speed_hz = 100000, }; i2c_master_dev_handle_t dev_handle; ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle)); ESP_ERROR_CHECK(i2c_master_transmit(dev_handle, data_wr, DATA_LENGTH, -1)); I2C Master Read After installing I2C master bus successfully, you can simply call i2c_master_receive() to read data from the slave device. The principle of this function can be explained by following chart. Simple example for reading data from slave: #define DATA_LENGTH 100 i2c_master_bus_config_t i2c_mst_config = { .clk_source = I2C_CLK_SRC_DEFAULT, .i2c_port = I2C_PORT_NUM_0, .scl_io_num = I2C_MASTER_SCL_IO, .sda_io_num = I2C_MASTER_SDA_IO, .glitch_ignore_cnt = 7, }; i2c_master_bus_handle_t bus_handle; ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle)); i2c_device_config_t dev_cfg = { .dev_addr_length = I2C_ADDR_BIT_LEN_7, .device_address = 0x58, .scl_speed_hz = 100000, }; i2c_master_dev_handle_t dev_handle; ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle)); i2c_master_receive(dev_handle, data_rd, DATA_LENGTH, -1); I2C Master Write and Read Some I2C device needs write configurations before reading data from it, therefore, an interface called i2c_master_transmit_receive() can help. The principle of this function can be explained by following chart. Simple example for writing and reading from slave: i2c_device_config_t dev_cfg = { .dev_addr_length = I2C_ADDR_BIT_LEN_7, .device_address = 0x58, .scl_speed_hz = 100000, }; i2c_master_dev_handle_t dev_handle; ESP_ERROR_CHECK(i2c_master_bus_add_device(I2C_PORT_NUM_0, &dev_cfg, &dev_handle)); uint8_t buf[20] = {0x20}; uint8_t buffer[2]; ESP_ERROR_CHECK(i2c_master_transmit_receive(i2c_bus_handle, buf, sizeof(buf), buffer, 2, -1)); I2C Master Probe I2C driver can use i2c_master_probe() to detect whether the specific device has been connected on I2C bus. If this function return ESP_OK, that means the device has been detected. Simple example for probing an I2C device: i2c_master_bus_config_t i2c_mst_config_1 = { .clk_source = I2C_CLK_SRC_DEFAULT, .i2c_port = TEST_I2C_PORT, .scl_io_num = I2C_MASTER_SCL_IO, .sda_io_num = I2C_MASTER_SDA_IO, .glitch_ignore_cnt = 7, .flags.enable_internal_pullup = true, }; i2c_master_bus_handle_t bus_handle; ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config_1, &bus_handle)); ESP_ERROR_CHECK(i2c_master_probe(bus_handle, 0x22, -1)); ESP_ERROR_CHECK(i2c_del_master_bus(bus_handle)); I2C Slave Controller After installing the i2c slave driver by i2c_new_slave_device(), ESP32 is ready to communicate with other I2C master as a slave. I2C Slave Write The send buffer of the I2C slave is used as a FIFO to store the data to be sent. The data will queue up until the master requests them. You can call i2c_slave_transmit() to transfer data. Simple example for writing data to FIFO: uint8_t *data_wr = (uint8_t *) malloc(DATA_LENGTH); i2c_slave_config_t i2c_slv_config = { .addr_bit_len = I2C_ADDR_BIT_LEN_7, // 7-bit address .clk_source = I2C_CLK_SRC_DEFAULT, // set the clock source .i2c_port = 0, // set I2C port number .send_buf_depth = 256, // set tx buffer length .scl_io_num = 2, // SCL gpio number .sda_io_num = 1, // SDA gpio number .slave_addr = 0x58, // slave address }; i2c_bus_handle_t i2c_bus_handle; ESP_ERROR_CHECK(i2c_new_slave_device(&i2c_slv_config, &i2c_bus_handle)); for (int i = 0; i < DATA_LENGTH; i++) { data_wr[i] = i; } ESP_ERROR_CHECK(i2c_slave_transmit(i2c_bus_handle, data_wr, DATA_LENGTH, 10000)); I2C Slave Read Whenever the master writes data to the slave, the slave will automatically store data in the receive buffer. This allows the slave application to call the function i2c_slave_receive() as its own discretion. As i2c_slave_receive() is designed as a non-blocking interface. So the user needs to register callback i2c_slave_register_event_callbacks() to know when the receive has finished. static IRAM_ATTR bool i2c_slave_rx_done_callback(i2c_slave_dev_handle_t channel, const i2c_slave_rx_done_event_data_t *edata, void *user_data) { BaseType_t high_task_wakeup = pdFALSE; QueueHandle_t receive_queue = (QueueHandle_t)user_data; xQueueSendFromISR(receive_queue, edata, &high_task_wakeup); return high_task_wakeup == pdTRUE; } uint8_t *data_rd = (uint8_t *) malloc(DATA_LENGTH); uint32_t size_rd = 0; i2c_slave_config_t i2c_slv_config = { .addr_bit_len = I2C_ADDR_BIT_LEN_7, .clk_source = I2C_CLK_SRC_DEFAULT, .i2c_port = TEST_I2C_PORT, .send_buf_depth = 256, .scl_io_num = I2C_SLAVE_SCL_IO, .sda_io_num = I2C_SLAVE_SDA_IO, .slave_addr = 0x58, }; i2c_slave_dev_handle_t slave_handle; ESP_ERROR_CHECK(i2c_new_slave_device(&i2c_slv_config, &slave_handle)); s_receive_queue = xQueueCreate(1, sizeof(i2c_slave_rx_done_event_data_t)); i2c_slave_event_callbacks_t cbs = { .on_recv_done = i2c_slave_rx_done_callback, }; ESP_ERROR_CHECK(i2c_slave_register_event_callbacks(slave_handle, &cbs, s_receive_queue)); i2c_slave_rx_done_event_data_t rx_data; ESP_ERROR_CHECK(i2c_slave_receive(slave_handle, data_rd, DATA_LENGTH)); xQueueReceive(s_receive_queue, &rx_data, pdMS_TO_TICKS(10000)); // Receive done. Register Event Callbacks I2C master callbacks When an I2C master bus triggers an interrupt, a specific event will be generated and notify the CPU. If you have some functions that need to be called when those events occurred, you can hook your functions to the ISR (Interrupt Service Routine) by calling i2c_master_register_event_callbacks(). Since the registered callback functions are called in the interrupt context, user should ensure the callback function doesn't attempt to block (e.g. by making sure that only FreeRTOS APIs with ISR suffix are called from within the function). The callback functions are required to return a boolean value, to tell the ISR whether a high priority task is woke up by it. I2C master event callbacks are listed in the i2c_master_event_callbacks_t. Although I2C is a synchronous communication protocol, we also support asynchronous behavior by registering above callback. In this way, I2C APIs will be non-blocking interface. But note that on the same bus, only one device can adopt asynchronous operation. Important I2C master asynchronous transaction is still an experimental feature. (The issue is when asynchronous transaction is very large, it will cause memory problem.) i2c_master_event_callbacks_t::on_recv_donesets a callback function for master "transaction-done" event. The function prototype is declared in i2c_master_callback_t. I2C slave callbacks When an I2C slave bus triggers an interrupt, a specific event will be generated and notify the CPU. If you have some function that needs to be called when those events occurred, you can hook your function to the ISR (Interrupt Service Routine) by calling i2c_slave_register_event_callbacks(). Since the registered callback functions are called in the interrupt context, user should ensure the callback function doesn't attempt to block (e.g. by making sure that only FreeRTOS APIs with ISR suffix are called from within the function). The callback function has a boolean return value, to tell the caller whether a high priority task is woke up by it. I2C slave event callbacks are listed in the i2c_slave_event_callbacks_t. i2c_slave_event_callbacks_t::on_recv_donesets a callback function for "receive-done" event. The function prototype is declared in i2c_slave_received_callback_t. Power Management When the power management is enabled (i.e. CONFIG_PM_ENABLE is on), the system will adjust or stop the source clock of I2C fifo before going into light sleep, thus potentially changing the I2C signals and leading to transmitting or receiving invalid data. However, the driver can prevent the system from changing APB frequency by acquiring a power management lock of type ESP_PM_APB_FREQ_MAX. Whenever user creates an I2C bus that has selected I2C_CLK_SRC_APB as the clock source, the driver will guarantee that the power management lock is acquired when I2C operations begin and release the lock automatically when I2C operations finish. IRAM Safe By default, the I2C interrupt will be deferred when the Cache is disabled for reasons like writing/erasing Flash. Thus the event callback functions will not get executed in time, which is not expected in a real-time application. There's a Kconfig option CONFIG_I2C_ISR_IRAM_SAFE that will: Enable the interrupt being serviced even when cache is disabled Place all functions that used by the ISR into IRAM Place driver object into DRAM (in case it's mapped to PSRAM by accident) This will allow the interrupt to run while the cache is disabled but will come at the cost of increased IRAM consumption. Thread Safety The factory function i2c_new_master_bus() and i2c_new_slave_device() are guaranteed to be thread safe by the driver, which means, user can call them from different RTOS tasks without protection by extra locks. Other public I2C APIs are not thread safe. which means the user should avoid calling them from multiple tasks, if user strongly needs to call them in multiple tasks, please add extra lock. Kconfig Options CONFIG_I2C_ISR_IRAM_SAFE controls whether the default ISR handler can work when cache is disabled, see also IRAM Safe for more information. CONFIG_I2C_ENABLE_DEBUG_LOG is used to enable the debug log at the cost of increased firmware binary size. API Reference Header File This header file can be included with: #include "driver/i2c_master.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t i2c_new_master_bus(const i2c_master_bus_config_t *bus_config, i2c_master_bus_handle_t *ret_bus_handle) Allocate an I2C master bus. - Parameters bus_config -- [in] I2C master bus configuration. ret_bus_handle -- [out] I2C bus handle - - Returns ESP_OK: I2C master bus initialized successfully. ESP_ERR_INVALID_ARG: I2C bus initialization failed because of invalid argument. ESP_ERR_NO_MEM: Create I2C bus failed because of out of memory. ESP_ERR_NOT_FOUND: No more free bus. - - esp_err_t i2c_master_bus_add_device(i2c_master_bus_handle_t bus_handle, const i2c_device_config_t *dev_config, i2c_master_dev_handle_t *ret_handle) Add I2C master BUS device. - Parameters bus_handle -- [in] I2C bus handle. dev_config -- [in] device config. ret_handle -- [out] device handle. - - Returns ESP_OK: Create I2C master device successfully. ESP_ERR_INVALID_ARG: I2C bus initialization failed because of invalid argument. ESP_ERR_NO_MEM: Create I2C bus failed because of out of memory. - - esp_err_t i2c_del_master_bus(i2c_master_bus_handle_t bus_handle) Deinitialize the I2C master bus and delete the handle. - Parameters bus_handle -- [in] I2C bus handle. - Returns ESP_OK: Delete I2C bus success, otherwise, failed. Otherwise: Some module delete failed. - - esp_err_t i2c_master_bus_rm_device(i2c_master_dev_handle_t handle) I2C master bus delete device. - Parameters handle -- i2c device handle - Returns ESP_OK: If device is successfully deleted. - - esp_err_t i2c_master_transmit(i2c_master_dev_handle_t i2c_dev, const uint8_t *write_buffer, size_t write_size, int xfer_timeout_ms) Perform a write transaction on the I2C bus. The transaction will be undergoing until it finishes or it reaches the timeout provided. Note If a callback was registered with i2c_master_register_event_callbacks, the transaction will be asynchronous, and thus, this function will return directly, without blocking. You will get finish information from callback. Besides, data buffer should always be completely prepared when callback is registered, otherwise, the data will get corrupt. - Parameters i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device. write_buffer -- [in] Data bytes to send on the I2C bus. write_size -- [in] Size, in bytes, of the write buffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. - - Returns ESP_OK: I2C master transmit success ESP_ERR_INVALID_ARG: I2C master transmit parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. - - esp_err_t i2c_master_transmit_receive(i2c_master_dev_handle_t i2c_dev, const uint8_t *write_buffer, size_t write_size, uint8_t *read_buffer, size_t read_size, int xfer_timeout_ms) Perform a write-read transaction on the I2C bus. The transaction will be undergoing until it finishes or it reaches the timeout provided. Note If a callback was registered with i2c_master_register_event_callbacks, the transaction will be asynchronous, and thus, this function will return directly, without blocking. You will get finish information from callback. Besides, data buffer should always be completely prepared when callback is registered, otherwise, the data will get corrupt. - Parameters i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device. write_buffer -- [in] Data bytes to send on the I2C bus. write_size -- [in] Size, in bytes, of the write buffer. read_buffer -- [out] Data bytes received from i2c bus. read_size -- [in] Size, in bytes, of the read buffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. - - Returns ESP_OK: I2C master transmit-receive success ESP_ERR_INVALID_ARG: I2C master transmit parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. - - esp_err_t i2c_master_receive(i2c_master_dev_handle_t i2c_dev, uint8_t *read_buffer, size_t read_size, int xfer_timeout_ms) Perform a read transaction on the I2C bus. The transaction will be undergoing until it finishes or it reaches the timeout provided. Note If a callback was registered with i2c_master_register_event_callbacks, the transaction will be asynchronous, and thus, this function will return directly, without blocking. You will get finish information from callback. Besides, data buffer should always be completely prepared when callback is registered, otherwise, the data will get corrupt. - Parameters i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device. read_buffer -- [out] Data bytes received from i2c bus. read_size -- [in] Size, in bytes, of the read buffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. - - Returns ESP_OK: I2C master receive success ESP_ERR_INVALID_ARG: I2C master receive parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. - - esp_err_t i2c_master_probe(i2c_master_bus_handle_t bus_handle, uint16_t address, int xfer_timeout_ms) Probe I2C address, if address is correct and ACK is received, this function will return ESP_OK. - Parameters bus_handle -- [in] I2C master device handle that created by i2c_master_bus_add_device. address -- [in] I2C device address that you want to probe. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever (Not recommended in this function). - - Returns ESP_OK: I2C device probe successfully ESP_ERR_NOT_FOUND: I2C probe failed, doesn't find the device with specific address you gave. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash. - - esp_err_t i2c_master_register_event_callbacks(i2c_master_dev_handle_t i2c_dev, const i2c_master_event_callbacks_t *cbs, void *user_data) Register I2C transaction callbacks for a master device. Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbsstructure to NULL. Note When CONFIG_I2C_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. The user_datashould also reside in SRAM. Note If the callback is used for helping asynchronous transaction. On the same bus, only one device can be used for performing asynchronous operation. - Parameters i2c_dev -- [in] I2C master device handle that created by i2c_master_bus_add_device. cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly - - Returns ESP_OK: Set I2C transaction callbacks successfully ESP_ERR_INVALID_ARG: Set I2C transaction callbacks failed because of invalid argument ESP_FAIL: Set I2C transaction callbacks failed because of other error - - esp_err_t i2c_master_bus_reset(i2c_master_bus_handle_t bus_handle) Reset the I2C master bus. - Parameters bus_handle -- I2C bus handle. - Returns ESP_OK: Reset succeed. ESP_ERR_INVALID_ARG: I2C master bus handle is not initialized. Otherwise: Reset failed. - - esp_err_t i2c_master_bus_wait_all_done(i2c_master_bus_handle_t bus_handle, int timeout_ms) Wait for all pending I2C transactions done. - Parameters bus_handle -- [in] I2C bus handle timeout_ms -- [in] Wait timeout, in ms. Specially, -1 means to wait forever. - - Returns ESP_OK: Flush transactions successfully ESP_ERR_INVALID_ARG: Flush transactions failed because of invalid argument ESP_ERR_TIMEOUT: Flush transactions failed because of timeout ESP_FAIL: Flush transactions failed because of other error - Structures - struct i2c_master_bus_config_t I2C master bus specific configurations. Public Members - i2c_port_num_t i2c_port I2C port number, -1for auto selecting - gpio_num_t sda_io_num GPIO number of I2C SDA signal, pulled-up internally - gpio_num_t scl_io_num GPIO number of I2C SCL signal, pulled-up internally - i2c_clock_source_t clk_source Clock source of I2C master bus, channels in the same group must use the same clock source - uint8_t glitch_ignore_cnt If the glitch period on the line is less than this value, it can be filtered out, typically value is 7 (unit: I2C module clock cycle) - int intr_priority I2C interrupt priority, if set to 0, driver will select the default priority (1,2,3). - size_t trans_queue_depth Depth of internal transfer queue, increase this value can support more transfers pending in the background, only valid in asynchronous transaction. (Typically max_device_num * per_transaction) - uint32_t enable_internal_pullup Enable internal pullups. Note: This is not strong enough to pullup buses under high-speed frequency. Recommend proper external pull-up if possible - struct i2c_master_bus_config_t::[anonymous] flags I2C master config flags - i2c_port_num_t i2c_port - struct i2c_device_config_t I2C device configuration. Public Members - i2c_addr_bit_len_t dev_addr_length Select the address length of the slave device. - uint16_t device_address I2C device raw address. (The 7/10 bit address without read/write bit) - uint32_t scl_speed_hz I2C SCL line frequency. - i2c_addr_bit_len_t dev_addr_length - struct i2c_master_event_callbacks_t Group of I2C master callbacks, can be used to get status during transaction or doing other small things. But take care potential concurrency issues. Note The callbacks are all running under ISR context Note When CONFIG_I2C_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. Public Members - i2c_master_callback_t on_trans_done I2C master transaction finish callback - i2c_master_callback_t on_trans_done Header File This header file can be included with: #include "driver/i2c_slave.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t i2c_new_slave_device(const i2c_slave_config_t *slave_config, i2c_slave_dev_handle_t *ret_handle) Initialize an I2C slave device. - Parameters slave_config -- [in] I2C slave device configurations ret_handle -- [out] Return a generic I2C device handle - - Returns ESP_OK: I2C slave device initialized successfully ESP_ERR_INVALID_ARG: I2C device initialization failed because of invalid argument. ESP_ERR_NO_MEM: Create I2C device failed because of out of memory. - - esp_err_t i2c_del_slave_device(i2c_slave_dev_handle_t i2c_slave) Deinitialize the I2C slave device. - Parameters i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device. - Returns ESP_OK: Delete I2C device successfully. ESP_ERR_INVALID_ARG: I2C device initialization failed because of invalid argument. - - esp_err_t i2c_slave_receive(i2c_slave_dev_handle_t i2c_slave, uint8_t *data, size_t buffer_size) Read bytes from I2C internal buffer. Start a job to receive I2C data. Note This function is non-blocking, it initiates a new receive job and then returns. User should check the received data from the on_recv_donecallback that registered by i2c_slave_register_event_callbacks(). - Parameters i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device. data -- [out] Buffer to store data from I2C fifo. Should be valid until on_recv_doneis triggered. buffer_size -- [in] Buffer size of data that provided by users. - - Returns ESP_OK: I2C slave receive success. ESP_ERR_INVALID_ARG: I2C slave receive parameter invalid. ESP_ERR_NOT_SUPPORTED: This function should be work in fifo mode, but I2C_SLAVE_NONFIFO mode is configured - - esp_err_t i2c_slave_transmit(i2c_slave_dev_handle_t i2c_slave, const uint8_t *data, int size, int xfer_timeout_ms) Write bytes to internal ringbuffer of the I2C slave data. When the TX fifo empty, the ISR will fill the hardware FIFO with the internal ringbuffer's data. Note If you connect this slave device to some master device, the data transaction direction is from slave device to master device. - Parameters i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device. data -- [in] Buffer to write to slave fifo, can pickup by master. Can be freed after this function returns. Equal or larger than size. size -- [in] In bytes, of databuffer. xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever. - - Returns ESP_OK: I2C slave transmit success. ESP_ERR_INVALID_ARG: I2C slave transmit parameter invalid. ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the device is busy or hardware crash. ESP_ERR_NOT_SUPPORTED: This function should be work in fifo mode, but I2C_SLAVE_NONFIFO mode is configured - - esp_err_t i2c_slave_register_event_callbacks(i2c_slave_dev_handle_t i2c_slave, const i2c_slave_event_callbacks_t *cbs, void *user_data) Set I2C slave event callbacks for I2C slave channel. Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbsstructure to NULL. Note When CONFIG_I2C_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. The user_datashould also reside in SRAM. - Parameters i2c_slave -- [in] I2C slave device handle that created by i2c_new_slave_device. cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly - - Returns ESP_OK: Set I2C transaction callbacks successfully ESP_ERR_INVALID_ARG: Set I2C transaction callbacks failed because of invalid argument ESP_FAIL: Set I2C transaction callbacks failed because of other error - Structures - struct i2c_slave_config_t I2C slave specific configurations. Public Members - i2c_port_num_t i2c_port I2C port number, -1for auto selecting - gpio_num_t sda_io_num SDA IO number used by I2C bus - gpio_num_t scl_io_num SCL IO number used by I2C bus - i2c_clock_source_t clk_source Clock source of I2C bus. - uint32_t send_buf_depth Depth of internal transfer ringbuffer, increase this value can support more transfers pending in the background - uint16_t slave_addr I2C slave address - i2c_addr_bit_len_t addr_bit_len I2C slave address in bit length - int intr_priority I2C interrupt priority, if set to 0, driver will select the default priority (1,2,3). - struct i2c_slave_config_t::[anonymous] flags I2C slave config flags - i2c_port_num_t i2c_port - struct i2c_slave_event_callbacks_t Group of I2C slave callbacks (e.g. get i2c slave stretch cause). But take care of potential concurrency issues. Note The callbacks are all running under ISR context Note When CONFIG_I2C_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. Public Members - i2c_slave_received_callback_t on_recv_done I2C slave receive done callback - i2c_slave_received_callback_t on_recv_done Header File This header file can be included with: #include "driver/i2c_types.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Structures - struct i2c_master_event_data_t Data type used in I2C event callback. Public Members - i2c_master_event_t event The I2C hardware event that I2C callback is called. - i2c_master_event_t event Type Definitions - typedef int i2c_port_num_t I2C port number. - typedef struct i2c_master_bus_t *i2c_master_bus_handle_t Type of I2C master bus handle. - typedef struct i2c_master_dev_t *i2c_master_dev_handle_t Type of I2C master bus device handle. - typedef struct i2c_slave_dev_t *i2c_slave_dev_handle_t Type of I2C slave device handle. - typedef bool (*i2c_master_callback_t)(i2c_master_dev_handle_t i2c_dev, const i2c_master_event_data_t *evt_data, void *arg) An callback for I2C transaction. - Param i2c_dev [in] Handle for I2C device. - Param evt_data [out] I2C capture event data, fed by driver - Param arg [in] User data, set in i2c_master_register_event_callbacks() - Return Whether a high priority task has been waken up by this function - typedef bool (*i2c_slave_received_callback_t)(i2c_slave_dev_handle_t i2c_slave, const i2c_slave_rx_done_event_data_t *evt_data, void *arg) Callback signature for I2C slave. - Param i2c_slave [in] Handle for I2C slave. - Param evt_data [out] I2C capture event data, fed by driver - Param arg [in] User data, set in i2c_slave_register_event_callbacks() - Return Whether a high priority task has been waken up by this function Enumerations - enum i2c_master_status_t Enumeration for I2C fsm status. Values: - enumerator I2C_STATUS_READ read status for current master command - enumerator I2C_STATUS_WRITE write status for current master command - enumerator I2C_STATUS_START Start status for current master command - enumerator I2C_STATUS_STOP stop status for current master command - enumerator I2C_STATUS_IDLE idle status for current master command - enumerator I2C_STATUS_ACK_ERROR ack error status for current master command - enumerator I2C_STATUS_DONE I2C command done - enumerator I2C_STATUS_TIMEOUT I2C bus status error, and operation timeout - enumerator I2C_STATUS_READ Header File This header file can be included with: #include "hal/i2c_types.h" Structures - struct i2c_hal_clk_config_t Data structure for calculating I2C bus timing. Public Members - uint16_t clkm_div I2C core clock devider - uint16_t scl_low I2C scl low period - uint16_t scl_high I2C scl hight period - uint16_t scl_wait_high I2C scl wait_high period - uint16_t sda_hold I2C scl low period - uint16_t sda_sample I2C sda sample time - uint16_t setup I2C start and stop condition setup period - uint16_t hold I2C start and stop condition hold period - uint16_t tout I2C bus timeout period - uint16_t clkm_div Type Definitions - typedef soc_periph_i2c_clk_src_t i2c_clock_source_t I2C group clock source. Enumerations - enum i2c_port_t I2C port number, can be I2C_NUM_0 ~ (I2C_NUM_MAX-1). Values: - enumerator I2C_NUM_0 I2C port 0 - enumerator I2C_NUM_1 I2C port 1 - enumerator I2C_NUM_MAX I2C port max - enumerator I2C_NUM_0 - enum i2c_addr_bit_len_t Enumeration for I2C device address bit length. Values: - enumerator I2C_ADDR_BIT_LEN_7 i2c address bit length 7 - enumerator I2C_ADDR_BIT_LEN_7 - enum i2c_mode_t Values: - enumerator I2C_MODE_SLAVE I2C slave mode - enumerator I2C_MODE_MASTER I2C master mode - enumerator I2C_MODE_MAX - enumerator I2C_MODE_SLAVE - enum i2c_rw_t Values: - enumerator I2C_MASTER_WRITE I2C write data - enumerator I2C_MASTER_READ I2C read data - enumerator I2C_MASTER_WRITE - enum i2c_trans_mode_t Values: - enumerator I2C_DATA_MODE_MSB_FIRST I2C data msb first - enumerator I2C_DATA_MODE_LSB_FIRST I2C data lsb first - enumerator I2C_DATA_MODE_MAX - enumerator I2C_DATA_MODE_MSB_FIRST - enum i2c_addr_mode_t Values: - enumerator I2C_ADDR_BIT_7 I2C 7bit address for slave mode - enumerator I2C_ADDR_BIT_10 I2C 10bit address for slave mode - enumerator I2C_ADDR_BIT_MAX - enumerator I2C_ADDR_BIT_7 - enum i2c_ack_type_t Values: - enumerator I2C_MASTER_ACK I2C ack for each byte read - enumerator I2C_MASTER_NACK I2C nack for each byte read - enumerator I2C_MASTER_LAST_NACK I2C nack for the last byte - enumerator I2C_MASTER_ACK_MAX - enumerator I2C_MASTER_ACK - enum i2c_slave_stretch_cause_t Enum for I2C slave stretch causes. Values: - enumerator I2C_SLAVE_STRETCH_CAUSE_ADDRESS_MATCH Stretching SCL low when the slave is read by the master and the address just matched - enumerator I2C_SLAVE_STRETCH_CAUSE_TX_EMPTY Stretching SCL low when TX FIFO is empty in slave mode - enumerator I2C_SLAVE_STRETCH_CAUSE_RX_FULL Stretching SCL low when RX FIFO is full in slave mode - enumerator I2C_SLAVE_STRETCH_CAUSE_SENDING_ACK Stretching SCL low when slave sending ACK - enumerator I2C_SLAVE_STRETCH_CAUSE_ADDRESS_MATCH
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/i2c.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Inter-IC Sound (I2S)
null
espressif.com
2016-01-01
945a9c3e3a5edbc9
null
null
Inter-IC Sound (I2S) Introduction I2S (Inter-IC Sound) is a synchronous serial communication protocol usually used for transmitting audio data between two digital audio devices. ESP32 contains two I2S peripheral(s). These peripherals can be configured to input and output sample data via the I2S driver. An I2S bus that communicates in standard or TDM mode consists of the following lines: MCLK: Master clock line. It is an optional signal depending on the slave side, mainly used for offering a reference clock to the I2S slave device. BCLK: Bit clock line. The bit clock for data line. WS: Word (Slot) select line. It is usually used to identify the vocal tract except PDM mode. DIN/DOUT: Serial data input/output line. Data will loopback internally if DIN and DOUT are set to a same GPIO. An I2S bus that communicates in PDM mode consists of the following lines: CLK: PDM clock line. DIN/DOUT: Serial data input/output line. Each I2S controller has the following features that can be configured by the I2S driver: Operation as system master or slave Capable of acting as transmitter or receiver DMA controller that allows stream sampling of data without requiring the CPU to copy each data sample Each controller supports single RX or TX simplex communication. As RX and TX channels share a clock, they can only be combined with the same configuration to establish a full-duplex communication. I2S File Structure Public headers that need to be included in the I2S application are as follows: i2s.h : The header file that provides legacy I2S APIs (for apps using legacy driver). i2s_std.h : The header file that provides standard communication mode specific APIs (for apps using new driver with standard mode). i2s_pdm.h : The header file that provides PDM communication mode specific APIs (for apps using new driver with PDM mode). i2s_tdm.h : The header file that provides TDM communication mode specific APIs (for apps using new driver with TDM mode). Note The legacy driver cannot coexist with the new driver. Include i2s.h to use the legacy driver, or include the other three headers to use the new driver. The legacy driver might be removed in future. Public headers that have been included in the headers above are as follows: i2s_types_legacy.h : The header file that provides legacy public types that are only used in the legacy driver. i2s_types.h : The header file that provides public types. i2s_common.h : The header file that provides common APIs for all communication modes. I2S Clock Clock Source i2s_clock_src_t::I2S_CLK_SRC_DEFAULT : Default PLL clock. i2s_clock_src_t::I2S_CLK_SRC_PLL_160M : 160 MHz PLL clock. i2s_clock_src_t::I2S_CLK_SRC_APLL : Audio PLL clock, which is more precise than I2S_CLK_SRC_PLL_160M in high sample rate applications. Its frequency is configurable according to the sample rate. However, if APLL has been occupied by EMAC or other channels, the APLL frequency cannot be changed, and the driver will try to work under this APLL frequency. If this frequency cannot meet the requirements of I2S, the clock configuration will fail. Clock Terminology Sample rate: The number of sampled data in one second per slot. SCLK: Source clock frequency. It is the frequency of the clock source. MCLK: Master clock frequency. BCLK is generated from this clock. The MCLK signal usually serves as a reference clock and is mostly needed to synchronize BCLK and WS between I2S master and slave roles. BCLK: Bit clock frequency. Every tick of this clock stands for one data bit on data pin. The slot bit width configured in i2s_std_slot_config_t::slot_bit_width is equal to the number of BCLK ticks, which means there will be 8/16/24/32 BCLK ticks in one slot. LRCK / WS: Left/right clock or word select clock. For non-PDM mode, its frequency is equal to the sample rate. Note Normally, MCLK should be the multiple of sample rate and BCLK at the same time. The field i2s_std_clk_config_t::mclk_multiple indicates the multiple of MCLK to the sample rate . In most cases, I2S_MCLK_MULTIPLE_256 should be enough. However, if slot_bit_width is set to I2S_SLOT_BIT_WIDTH_24BIT , to keep MCLK a multiple to the BCLK, i2s_std_clk_config_t::mclk_multiple should be set to multiples that are divisible by 3 such as I2S_MCLK_MULTIPLE_384 . Otherwise, WS will be inaccurate. I2S Communication Mode Overview of All Modes Target Standard PDM TX PDM RX TDM ADC/DAC LCD/Camera ESP32 I2S 0/1 I2S 0 I2S 0 none I2S 0 I2S 0 ESP32-S2 I2S 0 none none none none I2S 0 ESP32-C3 I2S 0 I2S 0 none I2S 0 none none ESP32-C6 I2S 0 I2S 0 none I2S 0 none none ESP32-S3 I2S 0/1 I2S 0 I2S 0 I2S 0/1 none none ESP32-H2 I2S 0 I2S 0 none I2S 0 none none ESP32-P4 I2S 0~2 I2S 0 I2S 0 I2S 0~2 none none Standard Mode In standard mode, there are always two sound channels, i.e., the left and right channels, which are called "slots". These slots support 8/16/24/32-bit width sample data. The communication format for the slots mainly includes the followings: Philips Format: Data signal has one-bit shift comparing to the WS signal, and the duty of WS signal is 50%. MSB Format: Basically the same as Philips format, but without data shift. PCM Short Format: Data has one-bit shift and meanwhile the WS signal becomes a pulse lasting for one BCLK cycle. PDM Mode (TX) PDM (Pulse-density Modulation) mode for the TX channel can convert PCM data into PDM format which always has left and right slots. PDM TX is only supported on I2S0 and it only supports 16-bit width sample data. It needs at least a CLK pin for clock signal and a DOUT pin for data signal (i.e., the WS and SD signal in the following figure; the BCK signal is an internal bit sampling clock, which is not needed between PDM devices). This mode allows users to configure the up-sampling parameters i2s_pdm_tx_clk_config_t::up_sample_fp and i2s_pdm_tx_clk_config_t::up_sample_fs . The up-sampling rate can be calculated by up_sample_rate = i2s_pdm_tx_clk_config_t::up_sample_fp / i2s_pdm_tx_clk_config_t::up_sample_fs . There are two up-sampling modes in PDM TX: Fixed Clock Frequency: In this mode, the up-sampling rate changes according to the sample rate. Setting fp = 960 and fs = sample_rate / 100 , then the clock frequency (Fpdm) on CLK pin will be fixed to 128 * 48 KHz = 6.144 MHz . Note that this frequency is not equal to the sample rate (Fpcm). Fixed Up-sampling Rate: In this mode, the up-sampling rate is fixed to 2. Setting fp = 960 and fs = 480 , then the clock frequency (Fpdm) on CLK pin will be 128 * sample_rate . PDM Mode (RX) PDM (Pulse-density Modulation) mode for RX channel can receive PDM-format data and convert the data into PCM format. PDM RX is only supported on I2S0, and it only supports 16-bit width sample data. PDM RX needs at least a CLK pin for clock signal and a DIN pin for data signal. This mode allows users to configure the down-sampling parameter i2s_pdm_rx_clk_config_t::dn_sample_mode . There are two down-sampling modes in PDM RX: i2s_pdm_dsr_t::I2S_PDM_DSR_8S : In this mode, the clock frequency (Fpdm) on the WS pin is sample_rate (Fpcm) * 64 . i2s_pdm_dsr_t::I2S_PDM_DSR_16S : In this mode, the clock frequency (Fpdm) on the WS pin is sample_rate (Fpcm) * 128 . LCD/Camera Mode LCD/Camera mode is only supported on I2S0 over a parallel bus. For LCD mode, I2S0 should work at master TX mode. For camera mode, I2S0 should work at slave RX mode. These two modes are not implemented by the I2S driver. Please refer to LCD for details about the LCD implementation. For more information, see ESP32 Technical Reference Manual > I2S Controller (I2S) > LCD Mode [PDF]. ADC/DAC Mode ADC and DAC modes only exist on ESP32 and are only supported on I2S0. Actually, they are two sub-modes of LCD/Camera mode. I2S0 can be routed directly to the internal analog-to-digital converter (ADC) and digital-to-analog converter (DAC). In other words, ADC and DAC peripherals can read or write continuously via I2S0 DMA. As they are not actual communication modes, the I2S driver does not implement them. Functional Overview The I2S driver offers the following services: Resource Management There are three levels of resources in the I2S driver: platform level : Resources of all I2S controllers in the current target. controller level : Resources in one I2S controller. channel level : Resources of TX or RX channel in one I2S controller. The public APIs are all channel-level APIs. The channel handle i2s_chan_handle_t can help users to manage the resources under a specific channel without considering the other two levels. The other two upper levels' resources are private and are managed by the driver automatically. Users can call i2s_new_channel() to allocate a channel handle and call i2s_del_channel() to delete it. Power Management When the power management is enabled (i.e., CONFIG_PM_ENABLE is on), the system will adjust or stop the source clock of I2S before entering Light-sleep, thus potentially changing the I2S signals and leading to transmitting or receiving invalid data. The I2S driver can prevent the system from changing or stopping the source clock by acquiring a power management lock. When the source clock is generated from APB, the lock type will be set to esp_pm_lock_type_t::ESP_PM_APB_FREQ_MAX and when the source clock is APLL (if supported), it will be set to esp_pm_lock_type_t::ESP_PM_NO_LIGHT_SLEEP . Whenever the user is reading or writing via I2S (i.e., calling i2s_channel_read() or i2s_channel_write() ), the driver guarantees that the power management lock is acquired. Likewise, the driver releases the lock after the reading or writing finishes. Finite State Machine There are three states for an I2S channel, namely, registered , ready , and running . Their relationship is shown in the following diagram: The <mode> in the diagram can be replaced by corresponding I2S communication modes, e.g., std for standard two-slot mode. For more information about communication modes, please refer to the I2S Communication Mode section. Data Transport The data transport of the I2S peripheral, including sending and receiving, is realized by DMA. Before transporting data, please call i2s_channel_enable() to enable the specific channel. When the sent or received data reaches the size of one DMA buffer, the I2S_OUT_EOF or I2S_IN_SUC_EOF interrupt will be triggered. Note that the DMA buffer size is not equal to i2s_chan_config_t::dma_frame_num . One frame here refers to all the sampled data in one WS circle. Therefore, dma_buffer_size = dma_frame_num * slot_num * slot_bit_width / 8 . For the data transmitting, users can input the data by calling i2s_channel_write() . This function helps users to copy the data from the source buffer to the DMA TX buffer and wait for the transmission to finish. Then it will repeat until the sent bytes reach the given size. For the data receiving, the function i2s_channel_read() waits to receive the message queue which contains the DMA buffer address. It helps users copy the data from the DMA RX buffer to the destination buffer. Both i2s_channel_write() and i2s_channel_read() are blocking functions. They keeps waiting until the whole source buffer is sent or the whole destination buffer is loaded, unless they exceed the max blocking time, where the error code ESP_ERR_TIMEOUT returns. To send or receive data asynchronously, callbacks can be registered by i2s_channel_register_event_callback() . Users are able to access the DMA buffer directly in the callback function instead of transmitting or receiving by the two blocking functions. However, please be aware that it is an interrupt callback, so do not add complex logic, run floating operation, or call non-reentrant functions in the callback. Configuration Users can initialize a channel by calling corresponding functions (i.e., i2s_channel_init_std_mode() , i2s_channel_init_pdm_rx_mode() , i2s_channel_init_pdm_tx_mode() , or i2s_channel_init_tdm_mode() ) to a specific mode. If the configurations need to be updated after initialization, users have to first call i2s_channel_disable() to ensure that the channel has stopped, and then call corresponding reconfig functions, like i2s_channel_reconfig_std_slot() , i2s_channel_reconfig_std_clock() , and i2s_channel_reconfig_std_gpio() . IRAM Safe By default, the I2S interrupt will be deferred when the cache is disabled for reasons like writing/erasing flash. Thus the EOF interrupt will not get executed in time. To avoid such case in real-time applications, you can enable the Kconfig option CONFIG_I2S_ISR_IRAM_SAFE that: Keeps the interrupt being serviced even when the cache is disabled. Places driver object into DRAM (in case it is linked to PSRAM by accident). This allows the interrupt to run while the cache is disabled, but comes at the cost of increased IRAM consumption. Thread Safety All the public I2S APIs are guaranteed to be thread safe by the driver, which means users can call them from different RTOS tasks without protection by extra locks. Notice that the I2S driver uses mutex lock to ensure the thread safety, thus these APIs are not allowed to be used in ISR. Kconfig Options CONFIG_I2S_ISR_IRAM_SAFE controls whether the default ISR handler can work when the cache is disabled. See IRAM Safe for more information. CONFIG_I2S_SUPPRESS_DEPRECATE_WARN controls whether to suppress the compiling warning message while using the legacy I2S driver. CONFIG_I2S_ENABLE_DEBUG_LOG is used to enable the debug log output. Enable this option increases the firmware binary size. Application Example The examples of the I2S driver can be found in the directory peripherals/i2s. Here are some simple usages of each mode: Standard TX/RX Usage Different slot communication formats can be generated by the following helper macros for standard mode. As described above, there are three formats in standard mode, and their helper macros are: The clock config helper macro is: Please refer to Standard Mode for information about STD API. And for more details, please refer to driver/i2s/include/driver/i2s_std.h. STD TX Mode Take 16-bit data width for example. When the data in a uint16_t writing buffer are: data 0 data 1 data 2 data 3 data 4 data 5 data 6 data 7 ... 0x0001 0x0002 0x0003 0x0004 0x0005 0x0006 0x0007 0x0008 ... Here is the table of the real data on the line with different i2s_std_slot_config_t::slot_mode and i2s_std_slot_config_t::slot_mask . data bit width slot mode slot mask WS low WS high WS low WS high WS low WS high WS low WS high 16 bit mono left 0x0002 0x0000 0x0001 0x0000 0x0004 0x0000 0x0003 0x0000 right 0x0000 0x0002 0x0000 0x0001 0x0000 0x0004 0x0000 0x0003 both 0x0002 0x0002 0x0001 0x0001 0x0004 0x0004 0x0003 0x0003 stereo left 0x0001 0x0001 0x0003 0x0003 0x0005 0x0005 0x0007 0x0007 right 0x0002 0x0002 0x0004 0x0004 0x0006 0x0006 0x0008 0x0008 both 0x0001 0x0002 0x0003 0x0004 0x0005 0x0006 0x0007 0x0008 Note It is similar when the data is 32-bit width, but take care when using 8-bit and 24-bit data width. For 8-bit width, the written buffer should still use uint16_t (i.e., align with 2 bytes), and only the high 8 bits are valid while the low 8 bits are dropped. For 24-bit width, the buffer is supposed to use uint32_t (i.e., align with 4 bytes), and only the high 24 bits are valid while the low 8 bits are dropped. Besides, for 8-bit and 16-bit mono modes, the real data on the line is swapped. To get the correct data sequence, the writing buffer needs to swap the data every two bytes. #include "driver/i2s_std.h" #include "driver/gpio.h" i2s_chan_handle_t tx_handle; /* Get the default channel configuration by the helper macro. * This helper macro is defined in `i2s_common.h` and shared by all the I2S communication modes. * It can help to specify the I2S role and port ID */ i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_AUTO, I2S_ROLE_MASTER); /* Allocate a new TX channel and get the handle of this channel */ i2s_new_channel(&chan_cfg, &tx_handle, NULL); /* Setting the configurations, the slot configuration and clock configuration can be generated by the macros * These two helper macros are defined in `i2s_std.h` which can only be used in STD mode. * They can help to specify the slot and clock configurations for initialization or updating */ i2s_std_config_t std_cfg = { .clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(48000), .slot_cfg = I2S_STD_MSB_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_STEREO), .gpio_cfg = { .mclk = I2S_GPIO_UNUSED, .bclk = GPIO_NUM_4, .ws = GPIO_NUM_5, .dout = GPIO_NUM_18, .din = I2S_GPIO_UNUSED, .invert_flags = { .mclk_inv = false, .bclk_inv = false, .ws_inv = false, }, }, }; /* Initialize the channel */ i2s_channel_init_std_mode(tx_handle, &std_cfg); /* Before writing data, start the TX channel first */ i2s_channel_enable(tx_handle); i2s_channel_write(tx_handle, src_buf, bytes_to_write, bytes_written, ticks_to_wait); /* If the configurations of slot or clock need to be updated, * stop the channel first and then update it */ // i2s_channel_disable(tx_handle); // std_cfg.slot_cfg.slot_mode = I2S_SLOT_MODE_MONO; // Default is stereo // i2s_channel_reconfig_std_slot(tx_handle, &std_cfg.slot_cfg); // std_cfg.clk_cfg.sample_rate_hz = 96000; // i2s_channel_reconfig_std_clock(tx_handle, &std_cfg.clk_cfg); /* Have to stop the channel before deleting it */ i2s_channel_disable(tx_handle); /* If the handle is not needed any more, delete it to release the channel resources */ i2s_del_channel(tx_handle); STD RX Mode Taking 16-bit data width for example, when the data on the line are: WS low WS high WS low WS high WS low WS high WS low WS high ... 0x0001 0x0002 0x0003 0x0004 0x0005 0x0006 0x0007 0x0008 ... Here is the table of the data received in the buffer with different i2s_std_slot_config_t::slot_mode and i2s_std_slot_config_t::slot_mask . data bit width slot mode slot mask data 0 data 1 data 2 data 3 data 4 data 5 data 6 data 7 16 bit mono left 0x0001 0x0000 0x0005 0x0003 0x0009 0x0007 0x000d 0x000b right 0x0002 0x0000 0x0006 0x0004 0x000a 0x0008 0x000e 0x000c stereo any 0x0001 0x0002 0x0003 0x0004 0x0005 0x0006 0x0007 0x0008 Note The receive case is a little bit complicated on ESP32. Firstly, when the data width is 8-bit or 24-bit, the received data will still align with two bytes or four bytes, which means that the valid data are put in the high 8 bits in every two bytes and high 24 bits in every four bytes. For example, the received data will be 0x5A00 when the data on the line is 0x5A in 8-bit width, and 0x0000 5A00 if the data on the line is 0x00 005A . Secondly, for the 8-bit or 16-bit mono case, the data in buffer is swapped every two data, so it may be necessary to manually swap the data back to the correct order. #include "driver/i2s_std.h" #include "driver/gpio.h" i2s_chan_handle_t rx_handle; /* Get the default channel configuration by helper macro. * This helper macro is defined in `i2s_common.h` and shared by all the I2S communication modes. * It can help to specify the I2S role and port ID */ i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_AUTO, I2S_ROLE_MASTER); /* Allocate a new RX channel and get the handle of this channel */ i2s_new_channel(&chan_cfg, NULL, &rx_handle); /* Setting the configurations, the slot configuration and clock configuration can be generated by the macros * These two helper macros are defined in `i2s_std.h` which can only be used in STD mode. * They can help to specify the slot and clock configurations for initialization or updating */ i2s_std_config_t std_cfg = { .clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(48000), .slot_cfg = I2S_STD_MSB_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_STEREO), .gpio_cfg = { .mclk = I2S_GPIO_UNUSED, .bclk = GPIO_NUM_4, .ws = GPIO_NUM_5, .dout = I2S_GPIO_UNUSED, .din = GPIO_NUM_19, .invert_flags = { .mclk_inv = false, .bclk_inv = false, .ws_inv = false, }, }, }; /* Initialize the channel */ i2s_channel_init_std_mode(rx_handle, &std_cfg); /* Before reading data, start the RX channel first */ i2s_channel_enable(rx_handle); i2s_channel_read(rx_handle, desc_buf, bytes_to_read, bytes_read, ticks_to_wait); /* Have to stop the channel before deleting it */ i2s_channel_disable(rx_handle); /* If the handle is not needed any more, delete it to release the channel resources */ i2s_del_channel(rx_handle); PDM TX Usage For PDM mode in TX channel, the slot configuration helper macro is: The clock configuration helper macro is: Please refer to PDM Mode for information about PDM TX API. And for more details, please refer to driver/i2s/include/driver/i2s_pdm.h. The PDM data width is fixed to 16-bit. When the data in an int16_t writing buffer is: data 0 data 1 data 2 data 3 data 4 data 5 data 6 data 7 ... 0x0001 0x0002 0x0003 0x0004 0x0005 0x0006 0x0007 0x0008 ... Here is the table of the real data on the line with different i2s_pdm_tx_slot_config_t::slot_mode and i2s_pdm_tx_slot_config_t::slot_mask (The PDM format on the line is transferred to PCM format for better comprehension). slot mode slot mask left right left right left right left right mono left 0x0001 0x0000 0x0002 0x0000 0x0003 0x0000 0x0004 0x0000 right 0x0000 0x0001 0x0000 0x0002 0x0000 0x0003 0x0000 0x0004 both 0x0001 0x0001 0x0002 0x0002 0x0003 0x0003 0x0004 0x0004 stereo left 0x0001 0x0001 0x0003 0x0003 0x0005 0x0005 0x0007 0x0007 right 0x0002 0x0002 0x0004 0x0004 0x0006 0x0006 0x0008 0x0008 both 0x0001 0x0002 0x0003 0x0004 0x0005 0x0006 0x0007 0x0008 #include "driver/i2s_pdm.h" #include "driver/gpio.h" /* Allocate an I2S TX channel */ i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER); i2s_new_channel(&chan_cfg, &tx_handle, NULL); /* Init the channel into PDM TX mode */ i2s_pdm_tx_config_t pdm_tx_cfg = { .clk_cfg = I2S_PDM_TX_CLK_DEFAULT_CONFIG(36000), .slot_cfg = I2S_PDM_TX_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_MONO), .gpio_cfg = { .clk = GPIO_NUM_5, .dout = GPIO_NUM_18, .invert_flags = { .clk_inv = false, }, }, }; i2s_channel_init_pdm_tx_mode(tx_handle, &pdm_tx_cfg); ... PDM RX Usage For PDM mode in RX channel, the slot configuration helper macro is: The clock configuration helper macro is: Please refer to PDM Mode for information about PDM RX API. And for more details, please refer to driver/i2s/include/driver/i2s_pdm.h. The PDM data width is fixed to 16-bit. When the data on the line (The PDM format on the line is transferred to PCM format for easier comprehension) is: left right left right left right left right ... 0x0001 0x0002 0x0003 0x0004 0x0005 0x0006 0x0007 0x0008 ... Here is the table of the data received in a int16_t buffer with different i2s_pdm_rx_slot_config_t::slot_mode and i2s_pdm_rx_slot_config_t::slot_mask . slot mode slot mask data 0 data 1 data 2 data 3 data 4 data 5 data 6 data 7 mono left 0x0001 0x0003 0x0005 0x0007 0x0009 0x000b 0x000d 0x000f right 0x0002 0x0004 0x0006 0x0008 0x000a 0x000c 0x000e 0x0010 stereo both 0x0001 0x0002 0x0003 0x0004 0x0005 0x0006 0x0007 0x0008 #include "driver/i2s_pdm.h" #include "driver/gpio.h" i2s_chan_handle_t rx_handle; /* Allocate an I2S RX channel */ i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER); i2s_new_channel(&chan_cfg, NULL, &rx_handle); /* Init the channel into PDM RX mode */ i2s_pdm_rx_config_t pdm_rx_cfg = { .clk_cfg = I2S_PDM_RX_CLK_DEFAULT_CONFIG(36000), .slot_cfg = I2S_PDM_RX_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_MONO), .gpio_cfg = { .clk = GPIO_NUM_5, .din = GPIO_NUM_19, .invert_flags = { .clk_inv = false, }, }, }; i2s_channel_init_pdm_rx_mode(rx_handle, &pdm_rx_cfg); ... Full-duplex Full-duplex mode registers TX and RX channel in an I2S port at the same time, and the channels share the BCLK and WS signals. Currently, STD and TDM communication modes supports full-duplex mode in the following way, but PDM full-duplex is not supported because due to different PDM TX and RX clocks. Note that one handle can only stand for one channel. Therefore, it is still necessary to configure the slot and clock for both TX and RX channels one by one. Here is an example of how to allocate a pair of full-duplex channels: #include "driver/i2s_std.h" #include "driver/gpio.h" i2s_chan_handle_t tx_handle; i2s_chan_handle_t rx_handle; /* Allocate a pair of I2S channel */ i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_AUTO, I2S_ROLE_MASTER); /* Allocate for TX and RX channel at the same time, then they will work in full-duplex mode */ i2s_new_channel(&chan_cfg, &tx_handle, &rx_handle); /* Set the configurations for BOTH TWO channels, since TX and RX channel have to be same in full-duplex mode */ i2s_std_config_t std_cfg = { .clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(32000), .slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_STEREO), .gpio_cfg = { .mclk = I2S_GPIO_UNUSED, .bclk = GPIO_NUM_4, .ws = GPIO_NUM_5, .dout = GPIO_NUM_18, .din = GPIO_NUM_19, .invert_flags = { .mclk_inv = false, .bclk_inv = false, .ws_inv = false, }, }, }; i2s_channel_init_std_mode(tx_handle, &std_cfg); i2s_channel_init_std_mode(rx_handle, &std_cfg); i2s_channel_enable(tx_handle); i2s_channel_enable(rx_handle); ... Simplex Mode To allocate a channel handle in simplex mode, i2s_new_channel() should be called for each channel. The clock and GPIO pins of TX/RX channel on ESP32 are not independent, so the TX and RX channel cannot coexist on the same I2S port in simplex mode. #include "driver/i2s_std.h" #include "driver/gpio.h" i2s_chan_handle_t tx_handle; i2s_chan_handle_t rx_handle; i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_AUTO, I2S_ROLE_MASTER); i2s_new_channel(&chan_cfg, &tx_handle, NULL); i2s_std_config_t std_tx_cfg = { .clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(48000), .slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_STEREO), .gpio_cfg = { .mclk = GPIO_NUM_0, .bclk = GPIO_NUM_4, .ws = GPIO_NUM_5, .dout = GPIO_NUM_18, .din = I2S_GPIO_UNUSED, .invert_flags = { .mclk_inv = false, .bclk_inv = false, .ws_inv = false, }, }, }; /* Initialize the channel */ i2s_channel_init_std_mode(tx_handle, &std_tx_cfg); i2s_channel_enable(tx_handle); /* RX channel will be registered on another I2S, if no other available I2S unit found * it will return ESP_ERR_NOT_FOUND */ i2s_new_channel(&chan_cfg, NULL, &rx_handle); i2s_std_config_t std_rx_cfg = { .clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(16000), .slot_cfg = I2S_STD_MSB_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_STEREO), .gpio_cfg = { .mclk = I2S_GPIO_UNUSED, .bclk = GPIO_NUM_6, .ws = GPIO_NUM_7, .dout = I2S_GPIO_UNUSED, .din = GPIO_NUM_19, .invert_flags = { .mclk_inv = false, .bclk_inv = false, .ws_inv = false, }, }, }; i2s_channel_init_std_mode(rx_handle, &std_rx_cfg); i2s_channel_enable(rx_handle); Application Notes How to Prevent Data Lost For applications that need a high frequency sample rate, the massive data throughput may cause data lost. Users can receive data lost event by registering the ISR callback function to receive the event queue: static IRAM_ATTR bool i2s_rx_queue_overflow_callback(i2s_chan_handle_t handle, i2s_event_data_t *event, void *user_ctx) { // handle RX queue overflow event ... return false; } i2s_event_callbacks_t cbs = { .on_recv = NULL, .on_recv_q_ovf = i2s_rx_queue_overflow_callback, .on_sent = NULL, .on_send_q_ovf = NULL, }; TEST_ESP_OK(i2s_channel_register_event_callback(rx_handle, &cbs, NULL)); Please follow these steps to prevent data lost: Determine the interrupt interval. Generally, when data lost happens, the bigger the interval, the better, which helps to reduce the interrupt times. This means dma_frame_num should be as big as possible while the DMA buffer size is below the maximum value of 4092. The relationships are: interrupt_interval(unit: sec) = dma_frame_num / sample_rate dma_buffer_size = dma_frame_num * slot_num * data_bit_width / 8 <= 4092 Determine dma_desc_num . dma_desc_num is decided by the maximum time of i2s_channel_read polling cycle. All the received data is supposed to be stored between two i2s_channel_read . This cycle can be measured by a timer or an outputting GPIO signal. The relationship is: dma_desc_num > polling_cycle / interrupt_interval Determine the receiving buffer size. The receiving buffer offered by users in i2s_channel_read should be able to take all the data in all DMA buffers, which means that it should be larger than the total size of all the DMA buffers: recv_buffer_size > dma_desc_num * dma_buffer_size For example, if there is an I2S application, and the known values are: sample_rate = 144000 Hz data_bit_width = 32 bits slot_num = 2 polling_cycle = 10 ms Then the parameters dma_frame_num , dma_desc_num , and recv_buf_size can be calculated as follows: dma_frame_num * slot_num * data_bit_width / 8 = dma_buffer_size <= 4092 dma_frame_num <= 511 interrupt_interval = dma_frame_num / sample_rate = 511 / 144000 = 0.003549 s = 3.549 ms dma_desc_num > polling_cycle / interrupt_interval = cell(10 / 3.549) = cell(2.818) = 3 recv_buffer_size > dma_desc_num * dma_buffer_size = 3 * 4092 = 12276 bytes API Reference Standard Mode Header File This header file can be included with: #include "driver/i2s_std.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t i2s_channel_init_std_mode(i2s_chan_handle_t handle, const i2s_std_config_t *std_cfg) Initialize I2S channel to standard mode. Note Only allowed to be called when the channel state is REGISTERED, (i.e., channel has been allocated, but not initialized) and the state will be updated to READY if initialization success, otherwise the state will return to REGISTERED. Parameters handle -- [in] I2S channel handler std_cfg -- [in] Configurations for standard mode, including clock, slot and GPIO The clock configuration can be generated by the helper macro I2S_STD_CLK_DEFAULT_CONFIG The slot configuration can be generated by the helper macro I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG , I2S_STD_PCM_SLOT_DEFAULT_CONFIG or I2S_STD_MSB_SLOT_DEFAULT_CONFIG handle -- [in] I2S channel handler std_cfg -- [in] Configurations for standard mode, including clock, slot and GPIO The clock configuration can be generated by the helper macro I2S_STD_CLK_DEFAULT_CONFIG The slot configuration can be generated by the helper macro I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG , I2S_STD_PCM_SLOT_DEFAULT_CONFIG or I2S_STD_MSB_SLOT_DEFAULT_CONFIG handle -- [in] I2S channel handler Returns ESP_OK Initialize successfully ESP_ERR_NO_MEM No memory for storing the channel information ESP_ERR_INVALID_ARG NULL pointer or invalid configuration ESP_ERR_INVALID_STATE This channel is not registered ESP_OK Initialize successfully ESP_ERR_NO_MEM No memory for storing the channel information ESP_ERR_INVALID_ARG NULL pointer or invalid configuration ESP_ERR_INVALID_STATE This channel is not registered ESP_OK Initialize successfully Parameters handle -- [in] I2S channel handler std_cfg -- [in] Configurations for standard mode, including clock, slot and GPIO The clock configuration can be generated by the helper macro I2S_STD_CLK_DEFAULT_CONFIG The slot configuration can be generated by the helper macro I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG , I2S_STD_PCM_SLOT_DEFAULT_CONFIG or I2S_STD_MSB_SLOT_DEFAULT_CONFIG Returns ESP_OK Initialize successfully ESP_ERR_NO_MEM No memory for storing the channel information ESP_ERR_INVALID_ARG NULL pointer or invalid configuration ESP_ERR_INVALID_STATE This channel is not registered esp_err_t i2s_channel_reconfig_std_clock(i2s_chan_handle_t handle, const i2s_std_clk_config_t *clk_cfg) Reconfigure the I2S clock for standard mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disable should be called before calling this function if I2S has started. Note The input channel handle has to be initialized to standard mode, i.e., i2s_channel_init_std_mode has been called before reconfiguring Parameters handle -- [in] I2S channel handler clk_cfg -- [in] Standard mode clock configuration, can be generated by I2S_STD_CLK_DEFAULT_CONFIG handle -- [in] I2S channel handler clk_cfg -- [in] Standard mode clock configuration, can be generated by I2S_STD_CLK_DEFAULT_CONFIG handle -- [in] I2S channel handler Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully Parameters handle -- [in] I2S channel handler clk_cfg -- [in] Standard mode clock configuration, can be generated by I2S_STD_CLK_DEFAULT_CONFIG Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped esp_err_t i2s_channel_reconfig_std_slot(i2s_chan_handle_t handle, const i2s_std_slot_config_t *slot_cfg) Reconfigure the I2S slot for standard mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disable should be called before calling this function if I2S has started. Note The input channel handle has to be initialized to standard mode, i.e., i2s_channel_init_std_mode has been called before reconfiguring Parameters handle -- [in] I2S channel handler slot_cfg -- [in] Standard mode slot configuration, can be generated by I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG , I2S_STD_PCM_SLOT_DEFAULT_CONFIG and I2S_STD_MSB_SLOT_DEFAULT_CONFIG . handle -- [in] I2S channel handler slot_cfg -- [in] Standard mode slot configuration, can be generated by I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG , I2S_STD_PCM_SLOT_DEFAULT_CONFIG and I2S_STD_MSB_SLOT_DEFAULT_CONFIG . handle -- [in] I2S channel handler Returns ESP_OK Set clock successfully ESP_ERR_NO_MEM No memory for DMA buffer ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully ESP_ERR_NO_MEM No memory for DMA buffer ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully Parameters handle -- [in] I2S channel handler slot_cfg -- [in] Standard mode slot configuration, can be generated by I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG , I2S_STD_PCM_SLOT_DEFAULT_CONFIG and I2S_STD_MSB_SLOT_DEFAULT_CONFIG . Returns ESP_OK Set clock successfully ESP_ERR_NO_MEM No memory for DMA buffer ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped esp_err_t i2s_channel_reconfig_std_gpio(i2s_chan_handle_t handle, const i2s_std_gpio_config_t *gpio_cfg) Reconfigure the I2S GPIO for standard mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disable should be called before calling this function if I2S has started. Note The input channel handle has to be initialized to standard mode, i.e., i2s_channel_init_std_mode has been called before reconfiguring Parameters handle -- [in] I2S channel handler gpio_cfg -- [in] Standard mode GPIO configuration, specified by user handle -- [in] I2S channel handler gpio_cfg -- [in] Standard mode GPIO configuration, specified by user handle -- [in] I2S channel handler Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully Parameters handle -- [in] I2S channel handler gpio_cfg -- [in] Standard mode GPIO configuration, specified by user Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped Structures struct i2s_std_slot_config_t I2S slot configuration for standard mode. Public Members i2s_data_bit_width_t data_bit_width I2S sample data bit width (valid data bits per sample) i2s_data_bit_width_t data_bit_width I2S sample data bit width (valid data bits per sample) i2s_slot_bit_width_t slot_bit_width I2S slot bit width (total bits per slot) i2s_slot_bit_width_t slot_bit_width I2S slot bit width (total bits per slot) i2s_slot_mode_t slot_mode Set mono or stereo mode with I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO In TX direction, mono means the written buffer contains only one slot data and stereo means the written buffer contains both left and right data i2s_slot_mode_t slot_mode Set mono or stereo mode with I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO In TX direction, mono means the written buffer contains only one slot data and stereo means the written buffer contains both left and right data i2s_std_slot_mask_t slot_mask Select the left, right or both slot i2s_std_slot_mask_t slot_mask Select the left, right or both slot uint32_t ws_width WS signal width (i.e. the number of BCLK ticks that WS signal is high) uint32_t ws_width WS signal width (i.e. the number of BCLK ticks that WS signal is high) bool ws_pol WS signal polarity, set true to enable high lever first bool ws_pol WS signal polarity, set true to enable high lever first bool bit_shift Set to enable bit shift in Philips mode bool bit_shift Set to enable bit shift in Philips mode bool msb_right Set to place right channel data at the MSB in the FIFO bool msb_right Set to place right channel data at the MSB in the FIFO i2s_data_bit_width_t data_bit_width struct i2s_std_clk_config_t I2S clock configuration for standard mode. Public Members uint32_t sample_rate_hz I2S sample rate uint32_t sample_rate_hz I2S sample rate i2s_clock_src_t clk_src Choose clock source, see soc_periph_i2s_clk_src_t for the supported clock sources. selected I2S_CLK_SRC_EXTERNAL (if supports) to enable the external source clock input via MCLK pin, i2s_clock_src_t clk_src Choose clock source, see soc_periph_i2s_clk_src_t for the supported clock sources. selected I2S_CLK_SRC_EXTERNAL (if supports) to enable the external source clock input via MCLK pin, i2s_mclk_multiple_t mclk_multiple The multiple of MCLK to the sample rate Default is 256 in the helper macro, it can satisfy most of cases, but please set this field a multiple of 3 (like 384) when using 24-bit data width, otherwise the sample rate might be inaccurate i2s_mclk_multiple_t mclk_multiple The multiple of MCLK to the sample rate Default is 256 in the helper macro, it can satisfy most of cases, but please set this field a multiple of 3 (like 384) when using 24-bit data width, otherwise the sample rate might be inaccurate uint32_t sample_rate_hz struct i2s_std_gpio_config_t I2S standard mode GPIO pins configuration. Public Members gpio_num_t mclk MCK pin, output by default, input if the clock source is selected to I2S_CLK_SRC_EXTERNAL gpio_num_t mclk MCK pin, output by default, input if the clock source is selected to I2S_CLK_SRC_EXTERNAL gpio_num_t bclk BCK pin, input in slave role, output in master role gpio_num_t bclk BCK pin, input in slave role, output in master role gpio_num_t ws WS pin, input in slave role, output in master role gpio_num_t ws WS pin, input in slave role, output in master role gpio_num_t dout DATA pin, output gpio_num_t dout DATA pin, output gpio_num_t din DATA pin, input gpio_num_t din DATA pin, input uint32_t mclk_inv Set 1 to invert the MCLK input/output uint32_t mclk_inv Set 1 to invert the MCLK input/output uint32_t bclk_inv Set 1 to invert the BCLK input/output uint32_t bclk_inv Set 1 to invert the BCLK input/output uint32_t ws_inv Set 1 to invert the WS input/output uint32_t ws_inv Set 1 to invert the WS input/output struct i2s_std_gpio_config_t::[anonymous] invert_flags GPIO pin invert flags struct i2s_std_gpio_config_t::[anonymous] invert_flags GPIO pin invert flags gpio_num_t mclk struct i2s_std_config_t I2S standard mode major configuration that including clock/slot/GPIO configuration. Public Members i2s_std_clk_config_t clk_cfg Standard mode clock configuration, can be generated by macro I2S_STD_CLK_DEFAULT_CONFIG i2s_std_clk_config_t clk_cfg Standard mode clock configuration, can be generated by macro I2S_STD_CLK_DEFAULT_CONFIG i2s_std_slot_config_t slot_cfg Standard mode slot configuration, can be generated by macros I2S_STD_[mode]_SLOT_DEFAULT_CONFIG, [mode] can be replaced with PHILIPS/MSB/PCM i2s_std_slot_config_t slot_cfg Standard mode slot configuration, can be generated by macros I2S_STD_[mode]_SLOT_DEFAULT_CONFIG, [mode] can be replaced with PHILIPS/MSB/PCM i2s_std_gpio_config_t gpio_cfg Standard mode GPIO configuration, specified by user i2s_std_gpio_config_t gpio_cfg Standard mode GPIO configuration, specified by user i2s_std_clk_config_t clk_cfg Macros I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(bits_per_sample, mono_or_stereo) Philips format in 2 slots. This file is specified for I2S standard communication mode Features: Philips/MSB/PCM are supported in standard mode Fixed to 2 slots Philips/MSB/PCM are supported in standard mode Fixed to 2 slots Parameters bits_per_sample -- I2S data bit width mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO bits_per_sample -- I2S data bit width mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO bits_per_sample -- I2S data bit width Parameters bits_per_sample -- I2S data bit width mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO Philips/MSB/PCM are supported in standard mode I2S_STD_PCM_SLOT_DEFAULT_CONFIG(bits_per_sample, mono_or_stereo) PCM(short) format in 2 slots. Note PCM(long) is same as Philips in 2 slots Parameters bits_per_sample -- I2S data bit width mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO bits_per_sample -- I2S data bit width mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO bits_per_sample -- I2S data bit width Parameters bits_per_sample -- I2S data bit width mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO I2S_STD_MSB_SLOT_DEFAULT_CONFIG(bits_per_sample, mono_or_stereo) MSB format in 2 slots. Parameters bits_per_sample -- I2S data bit width mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO bits_per_sample -- I2S data bit width mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO bits_per_sample -- I2S data bit width Parameters bits_per_sample -- I2S data bit width mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO I2S_STD_CLK_DEFAULT_CONFIG(rate) I2S default standard clock configuration. Note Please set the mclk_multiple to I2S_MCLK_MULTIPLE_384 while using 24 bits data width Otherwise the sample rate might be imprecise since the BCLK division is not a integer Parameters rate -- sample rate rate -- sample rate rate -- sample rate Parameters rate -- sample rate PDM Mode Header File This header file can be included with: #include "driver/i2s_pdm.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t i2s_channel_init_pdm_rx_mode(i2s_chan_handle_t handle, const i2s_pdm_rx_config_t *pdm_rx_cfg) Initialize I2S channel to PDM RX mode. Note Only allowed to be called when the channel state is REGISTERED, (i.e., channel has been allocated, but not initialized) and the state will be updated to READY if initialization success, otherwise the state will return to REGISTERED. Parameters handle -- [in] I2S RX channel handler pdm_rx_cfg -- [in] Configurations for PDM RX mode, including clock, slot and GPIO The clock configuration can be generated by the helper macro I2S_PDM_RX_CLK_DEFAULT_CONFIG The slot configuration can be generated by the helper macro I2S_PDM_RX_SLOT_DEFAULT_CONFIG handle -- [in] I2S RX channel handler pdm_rx_cfg -- [in] Configurations for PDM RX mode, including clock, slot and GPIO The clock configuration can be generated by the helper macro I2S_PDM_RX_CLK_DEFAULT_CONFIG The slot configuration can be generated by the helper macro I2S_PDM_RX_SLOT_DEFAULT_CONFIG handle -- [in] I2S RX channel handler Returns ESP_OK Initialize successfully ESP_ERR_NO_MEM No memory for storing the channel information ESP_ERR_INVALID_ARG NULL pointer or invalid configuration ESP_ERR_INVALID_STATE This channel is not registered ESP_OK Initialize successfully ESP_ERR_NO_MEM No memory for storing the channel information ESP_ERR_INVALID_ARG NULL pointer or invalid configuration ESP_ERR_INVALID_STATE This channel is not registered ESP_OK Initialize successfully Parameters handle -- [in] I2S RX channel handler pdm_rx_cfg -- [in] Configurations for PDM RX mode, including clock, slot and GPIO The clock configuration can be generated by the helper macro I2S_PDM_RX_CLK_DEFAULT_CONFIG The slot configuration can be generated by the helper macro I2S_PDM_RX_SLOT_DEFAULT_CONFIG Returns ESP_OK Initialize successfully ESP_ERR_NO_MEM No memory for storing the channel information ESP_ERR_INVALID_ARG NULL pointer or invalid configuration ESP_ERR_INVALID_STATE This channel is not registered esp_err_t i2s_channel_reconfig_pdm_rx_clock(i2s_chan_handle_t handle, const i2s_pdm_rx_clk_config_t *clk_cfg) Reconfigure the I2S clock for PDM RX mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disable should be called before calling this function if I2S has started. Note The input channel handle has to be initialized to PDM RX mode, i.e., i2s_channel_init_pdm_rx_mode has been called before reconfiguring Parameters handle -- [in] I2S RX channel handler clk_cfg -- [in] PDM RX mode clock configuration, can be generated by I2S_PDM_RX_CLK_DEFAULT_CONFIG handle -- [in] I2S RX channel handler clk_cfg -- [in] PDM RX mode clock configuration, can be generated by I2S_PDM_RX_CLK_DEFAULT_CONFIG handle -- [in] I2S RX channel handler Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully Parameters handle -- [in] I2S RX channel handler clk_cfg -- [in] PDM RX mode clock configuration, can be generated by I2S_PDM_RX_CLK_DEFAULT_CONFIG Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped esp_err_t i2s_channel_reconfig_pdm_rx_slot(i2s_chan_handle_t handle, const i2s_pdm_rx_slot_config_t *slot_cfg) Reconfigure the I2S slot for PDM RX mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disable should be called before calling this function if I2S has started. Note The input channel handle has to be initialized to PDM RX mode, i.e., i2s_channel_init_pdm_rx_mode has been called before reconfiguring Parameters handle -- [in] I2S RX channel handler slot_cfg -- [in] PDM RX mode slot configuration, can be generated by I2S_PDM_RX_SLOT_DEFAULT_CONFIG handle -- [in] I2S RX channel handler slot_cfg -- [in] PDM RX mode slot configuration, can be generated by I2S_PDM_RX_SLOT_DEFAULT_CONFIG handle -- [in] I2S RX channel handler Returns ESP_OK Set clock successfully ESP_ERR_NO_MEM No memory for DMA buffer ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully ESP_ERR_NO_MEM No memory for DMA buffer ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully Parameters handle -- [in] I2S RX channel handler slot_cfg -- [in] PDM RX mode slot configuration, can be generated by I2S_PDM_RX_SLOT_DEFAULT_CONFIG Returns ESP_OK Set clock successfully ESP_ERR_NO_MEM No memory for DMA buffer ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped esp_err_t i2s_channel_reconfig_pdm_rx_gpio(i2s_chan_handle_t handle, const i2s_pdm_rx_gpio_config_t *gpio_cfg) Reconfigure the I2S GPIO for PDM RX mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disable should be called before calling this function if I2S has started. Note The input channel handle has to be initialized to PDM RX mode, i.e., i2s_channel_init_pdm_rx_mode has been called before reconfiguring Parameters handle -- [in] I2S RX channel handler gpio_cfg -- [in] PDM RX mode GPIO configuration, specified by user handle -- [in] I2S RX channel handler gpio_cfg -- [in] PDM RX mode GPIO configuration, specified by user handle -- [in] I2S RX channel handler Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully Parameters handle -- [in] I2S RX channel handler gpio_cfg -- [in] PDM RX mode GPIO configuration, specified by user Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped esp_err_t i2s_channel_init_pdm_tx_mode(i2s_chan_handle_t handle, const i2s_pdm_tx_config_t *pdm_tx_cfg) Initialize I2S channel to PDM TX mode. Note Only allowed to be called when the channel state is REGISTERED, (i.e., channel has been allocated, but not initialized) and the state will be updated to READY if initialization success, otherwise the state will return to REGISTERED. Parameters handle -- [in] I2S TX channel handler pdm_tx_cfg -- [in] Configurations for PDM TX mode, including clock, slot and GPIO The clock configuration can be generated by the helper macro I2S_PDM_TX_CLK_DEFAULT_CONFIG The slot configuration can be generated by the helper macro I2S_PDM_TX_SLOT_DEFAULT_CONFIG handle -- [in] I2S TX channel handler pdm_tx_cfg -- [in] Configurations for PDM TX mode, including clock, slot and GPIO The clock configuration can be generated by the helper macro I2S_PDM_TX_CLK_DEFAULT_CONFIG The slot configuration can be generated by the helper macro I2S_PDM_TX_SLOT_DEFAULT_CONFIG handle -- [in] I2S TX channel handler Returns ESP_OK Initialize successfully ESP_ERR_NO_MEM No memory for storing the channel information ESP_ERR_INVALID_ARG NULL pointer or invalid configuration ESP_ERR_INVALID_STATE This channel is not registered ESP_OK Initialize successfully ESP_ERR_NO_MEM No memory for storing the channel information ESP_ERR_INVALID_ARG NULL pointer or invalid configuration ESP_ERR_INVALID_STATE This channel is not registered ESP_OK Initialize successfully Parameters handle -- [in] I2S TX channel handler pdm_tx_cfg -- [in] Configurations for PDM TX mode, including clock, slot and GPIO The clock configuration can be generated by the helper macro I2S_PDM_TX_CLK_DEFAULT_CONFIG The slot configuration can be generated by the helper macro I2S_PDM_TX_SLOT_DEFAULT_CONFIG Returns ESP_OK Initialize successfully ESP_ERR_NO_MEM No memory for storing the channel information ESP_ERR_INVALID_ARG NULL pointer or invalid configuration ESP_ERR_INVALID_STATE This channel is not registered esp_err_t i2s_channel_reconfig_pdm_tx_clock(i2s_chan_handle_t handle, const i2s_pdm_tx_clk_config_t *clk_cfg) Reconfigure the I2S clock for PDM TX mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disable should be called before calling this function if I2S has started. Note The input channel handle has to be initialized to PDM TX mode, i.e., i2s_channel_init_pdm_tx_mode has been called before reconfiguring Parameters handle -- [in] I2S TX channel handler clk_cfg -- [in] PDM TX mode clock configuration, can be generated by I2S_PDM_TX_CLK_DEFAULT_CONFIG handle -- [in] I2S TX channel handler clk_cfg -- [in] PDM TX mode clock configuration, can be generated by I2S_PDM_TX_CLK_DEFAULT_CONFIG handle -- [in] I2S TX channel handler Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully Parameters handle -- [in] I2S TX channel handler clk_cfg -- [in] PDM TX mode clock configuration, can be generated by I2S_PDM_TX_CLK_DEFAULT_CONFIG Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped esp_err_t i2s_channel_reconfig_pdm_tx_slot(i2s_chan_handle_t handle, const i2s_pdm_tx_slot_config_t *slot_cfg) Reconfigure the I2S slot for PDM TX mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disable should be called before calling this function if I2S has started. Note The input channel handle has to be initialized to PDM TX mode, i.e., i2s_channel_init_pdm_tx_mode has been called before reconfiguring Parameters handle -- [in] I2S TX channel handler slot_cfg -- [in] PDM TX mode slot configuration, can be generated by I2S_PDM_TX_SLOT_DEFAULT_CONFIG handle -- [in] I2S TX channel handler slot_cfg -- [in] PDM TX mode slot configuration, can be generated by I2S_PDM_TX_SLOT_DEFAULT_CONFIG handle -- [in] I2S TX channel handler Returns ESP_OK Set clock successfully ESP_ERR_NO_MEM No memory for DMA buffer ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully ESP_ERR_NO_MEM No memory for DMA buffer ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully Parameters handle -- [in] I2S TX channel handler slot_cfg -- [in] PDM TX mode slot configuration, can be generated by I2S_PDM_TX_SLOT_DEFAULT_CONFIG Returns ESP_OK Set clock successfully ESP_ERR_NO_MEM No memory for DMA buffer ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped esp_err_t i2s_channel_reconfig_pdm_tx_gpio(i2s_chan_handle_t handle, const i2s_pdm_tx_gpio_config_t *gpio_cfg) Reconfigure the I2S GPIO for PDM TX mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disable should be called before calling this function if I2S has started. Note The input channel handle has to be initialized to PDM TX mode, i.e., i2s_channel_init_pdm_tx_mode has been called before reconfiguring Parameters handle -- [in] I2S TX channel handler gpio_cfg -- [in] PDM TX mode GPIO configuration, specified by user handle -- [in] I2S TX channel handler gpio_cfg -- [in] PDM TX mode GPIO configuration, specified by user handle -- [in] I2S TX channel handler Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped ESP_OK Set clock successfully Parameters handle -- [in] I2S TX channel handler gpio_cfg -- [in] PDM TX mode GPIO configuration, specified by user Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped Structures struct i2s_pdm_rx_slot_config_t I2S slot configuration for PDM RX mode. Public Members i2s_data_bit_width_t data_bit_width I2S sample data bit width (valid data bits per sample), only support 16 bits for PDM mode i2s_data_bit_width_t data_bit_width I2S sample data bit width (valid data bits per sample), only support 16 bits for PDM mode i2s_slot_bit_width_t slot_bit_width I2S slot bit width (total bits per slot) , only support 16 bits for PDM mode i2s_slot_bit_width_t slot_bit_width I2S slot bit width (total bits per slot) , only support 16 bits for PDM mode i2s_slot_mode_t slot_mode Set mono or stereo mode with I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO i2s_slot_mode_t slot_mode Set mono or stereo mode with I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO i2s_pdm_slot_mask_t slot_mask Choose the slots to activate i2s_pdm_slot_mask_t slot_mask Choose the slots to activate i2s_data_bit_width_t data_bit_width struct i2s_pdm_rx_clk_config_t I2S clock configuration for PDM RX mode. Public Members uint32_t sample_rate_hz I2S sample rate uint32_t sample_rate_hz I2S sample rate i2s_clock_src_t clk_src Choose clock source i2s_clock_src_t clk_src Choose clock source i2s_mclk_multiple_t mclk_multiple The multiple of MCLK to the sample rate i2s_mclk_multiple_t mclk_multiple The multiple of MCLK to the sample rate i2s_pdm_dsr_t dn_sample_mode Down-sampling rate mode i2s_pdm_dsr_t dn_sample_mode Down-sampling rate mode uint32_t bclk_div The division from MCLK to BCLK. The typical and minimum value is I2S_PDM_RX_BCLK_DIV_MIN. It will be set to I2S_PDM_RX_BCLK_DIV_MIN by default if it is smaller than I2S_PDM_RX_BCLK_DIV_MIN uint32_t bclk_div The division from MCLK to BCLK. The typical and minimum value is I2S_PDM_RX_BCLK_DIV_MIN. It will be set to I2S_PDM_RX_BCLK_DIV_MIN by default if it is smaller than I2S_PDM_RX_BCLK_DIV_MIN uint32_t sample_rate_hz struct i2s_pdm_rx_gpio_config_t I2S PDM TX mode GPIO pins configuration. Public Members gpio_num_t clk PDM clk pin, output gpio_num_t clk PDM clk pin, output gpio_num_t din DATA pin 0, input gpio_num_t din DATA pin 0, input gpio_num_t dins[(1U)] DATA pins, input, only take effect when corresponding I2S_PDM_RX_LINEx_SLOT_xxx is enabled in i2s_pdm_rx_slot_config_t::slot_mask gpio_num_t dins[(1U)] DATA pins, input, only take effect when corresponding I2S_PDM_RX_LINEx_SLOT_xxx is enabled in i2s_pdm_rx_slot_config_t::slot_mask uint32_t clk_inv Set 1 to invert the clk output uint32_t clk_inv Set 1 to invert the clk output struct i2s_pdm_rx_gpio_config_t::[anonymous] invert_flags GPIO pin invert flags struct i2s_pdm_rx_gpio_config_t::[anonymous] invert_flags GPIO pin invert flags gpio_num_t clk struct i2s_pdm_rx_config_t I2S PDM RX mode major configuration that including clock/slot/GPIO configuration. Public Members i2s_pdm_rx_clk_config_t clk_cfg PDM RX clock configurations, can be generated by macro I2S_PDM_RX_CLK_DEFAULT_CONFIG i2s_pdm_rx_clk_config_t clk_cfg PDM RX clock configurations, can be generated by macro I2S_PDM_RX_CLK_DEFAULT_CONFIG i2s_pdm_rx_slot_config_t slot_cfg PDM RX slot configurations, can be generated by macro I2S_PDM_RX_SLOT_DEFAULT_CONFIG i2s_pdm_rx_slot_config_t slot_cfg PDM RX slot configurations, can be generated by macro I2S_PDM_RX_SLOT_DEFAULT_CONFIG i2s_pdm_rx_gpio_config_t gpio_cfg PDM RX slot configurations, specified by user i2s_pdm_rx_gpio_config_t gpio_cfg PDM RX slot configurations, specified by user i2s_pdm_rx_clk_config_t clk_cfg struct i2s_pdm_tx_slot_config_t I2S slot configuration for PDM TX mode. Public Members i2s_data_bit_width_t data_bit_width I2S sample data bit width (valid data bits per sample), only support 16 bits for PDM mode i2s_data_bit_width_t data_bit_width I2S sample data bit width (valid data bits per sample), only support 16 bits for PDM mode i2s_slot_bit_width_t slot_bit_width I2S slot bit width (total bits per slot), only support 16 bits for PDM mode i2s_slot_bit_width_t slot_bit_width I2S slot bit width (total bits per slot), only support 16 bits for PDM mode i2s_slot_mode_t slot_mode Set mono or stereo mode with I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO For PDM TX mode, mono means the data buffer only contains one slot data, Stereo means the data buffer contains two slots data i2s_slot_mode_t slot_mode Set mono or stereo mode with I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO For PDM TX mode, mono means the data buffer only contains one slot data, Stereo means the data buffer contains two slots data i2s_pdm_slot_mask_t slot_mask Slot mask to choose left or right slot i2s_pdm_slot_mask_t slot_mask Slot mask to choose left or right slot uint32_t sd_prescale Sigma-delta filter prescale uint32_t sd_prescale Sigma-delta filter prescale i2s_pdm_sig_scale_t sd_scale Sigma-delta filter scaling value i2s_pdm_sig_scale_t sd_scale Sigma-delta filter scaling value i2s_pdm_sig_scale_t hp_scale High pass filter scaling value i2s_pdm_sig_scale_t hp_scale High pass filter scaling value i2s_pdm_sig_scale_t lp_scale Low pass filter scaling value i2s_pdm_sig_scale_t lp_scale Low pass filter scaling value i2s_pdm_sig_scale_t sinc_scale Sinc filter scaling value i2s_pdm_sig_scale_t sinc_scale Sinc filter scaling value i2s_data_bit_width_t data_bit_width struct i2s_pdm_tx_clk_config_t I2S clock configuration for PDM TX mode. Public Members uint32_t sample_rate_hz I2S sample rate, not suggest to exceed 48000 Hz, otherwise more glitches and noise may appear uint32_t sample_rate_hz I2S sample rate, not suggest to exceed 48000 Hz, otherwise more glitches and noise may appear i2s_clock_src_t clk_src Choose clock source i2s_clock_src_t clk_src Choose clock source i2s_mclk_multiple_t mclk_multiple The multiple of MCLK to the sample rate i2s_mclk_multiple_t mclk_multiple The multiple of MCLK to the sample rate uint32_t up_sample_fp Up-sampling param fp uint32_t up_sample_fp Up-sampling param fp uint32_t up_sample_fs Up-sampling param fs, not allowed to be greater than 480 uint32_t up_sample_fs Up-sampling param fs, not allowed to be greater than 480 uint32_t bclk_div The division from MCLK to BCLK. The minimum value is I2S_PDM_TX_BCLK_DIV_MIN. It will be set to I2S_PDM_TX_BCLK_DIV_MIN by default if it is smaller than I2S_PDM_TX_BCLK_DIV_MIN uint32_t bclk_div The division from MCLK to BCLK. The minimum value is I2S_PDM_TX_BCLK_DIV_MIN. It will be set to I2S_PDM_TX_BCLK_DIV_MIN by default if it is smaller than I2S_PDM_TX_BCLK_DIV_MIN uint32_t sample_rate_hz struct i2s_pdm_tx_gpio_config_t I2S PDM TX mode GPIO pins configuration. Public Members gpio_num_t clk PDM clk pin, output gpio_num_t clk PDM clk pin, output gpio_num_t dout DATA pin, output gpio_num_t dout DATA pin, output uint32_t clk_inv Set 1 to invert the clk output uint32_t clk_inv Set 1 to invert the clk output struct i2s_pdm_tx_gpio_config_t::[anonymous] invert_flags GPIO pin invert flags struct i2s_pdm_tx_gpio_config_t::[anonymous] invert_flags GPIO pin invert flags gpio_num_t clk struct i2s_pdm_tx_config_t I2S PDM TX mode major configuration that including clock/slot/GPIO configuration. Public Members i2s_pdm_tx_clk_config_t clk_cfg PDM TX clock configurations, can be generated by macro I2S_PDM_TX_CLK_DEFAULT_CONFIG i2s_pdm_tx_clk_config_t clk_cfg PDM TX clock configurations, can be generated by macro I2S_PDM_TX_CLK_DEFAULT_CONFIG i2s_pdm_tx_slot_config_t slot_cfg PDM TX slot configurations, can be generated by macro I2S_PDM_TX_SLOT_DEFAULT_CONFIG i2s_pdm_tx_slot_config_t slot_cfg PDM TX slot configurations, can be generated by macro I2S_PDM_TX_SLOT_DEFAULT_CONFIG i2s_pdm_tx_gpio_config_t gpio_cfg PDM TX GPIO configurations, specified by user i2s_pdm_tx_gpio_config_t gpio_cfg PDM TX GPIO configurations, specified by user i2s_pdm_tx_clk_config_t clk_cfg Macros I2S_PDM_RX_SLOT_DEFAULT_CONFIG(bits_per_sample, mono_or_stereo) PDM format in 2 slots(RX) This file is specified for I2S PDM communication mode Features: Only support PDM TX/RX mode Fixed to 2 slots Data bit width only support 16 bits Only support PDM TX/RX mode Fixed to 2 slots Data bit width only support 16 bits Parameters bits_per_sample -- I2S data bit width, only support 16 bits for PDM mode mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO bits_per_sample -- I2S data bit width, only support 16 bits for PDM mode mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO bits_per_sample -- I2S data bit width, only support 16 bits for PDM mode Parameters bits_per_sample -- I2S data bit width, only support 16 bits for PDM mode mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO Only support PDM TX/RX mode I2S_PDM_RX_CLK_DEFAULT_CONFIG(rate) I2S default PDM RX clock configuration. Parameters rate -- sample rate rate -- sample rate rate -- sample rate Parameters rate -- sample rate I2S_PDM_TX_SLOT_DEFAULT_CONFIG(bits_per_sample, mono_or_stereo) PDM style in 2 slots(TX) for codec line mode. Parameters bits_per_sample -- I2S data bit width, only support 16 bits for PDM mode mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO bits_per_sample -- I2S data bit width, only support 16 bits for PDM mode mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO bits_per_sample -- I2S data bit width, only support 16 bits for PDM mode Parameters bits_per_sample -- I2S data bit width, only support 16 bits for PDM mode mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO I2S_PDM_TX_CLK_DEFAULT_CONFIG(rate) I2S default PDM TX clock configuration for codec line mode. Note TX PDM can only be set to the following two up-sampling rate configurations: 1: fp = 960, fs = sample_rate_hz / 100, in this case, Fpdm = 128*48000 2: fp = 960, fs = 480, in this case, Fpdm = 128*Fpcm = 128*sample_rate_hz If the PDM receiver do not care the PDM serial clock, it's recommended set Fpdm = 128*48000. Otherwise, the second configuration should be adopted. Parameters rate -- sample rate (not suggest to exceed 48000 Hz, otherwise more glitches and noise may appear) rate -- sample rate (not suggest to exceed 48000 Hz, otherwise more glitches and noise may appear) rate -- sample rate (not suggest to exceed 48000 Hz, otherwise more glitches and noise may appear) Parameters rate -- sample rate (not suggest to exceed 48000 Hz, otherwise more glitches and noise may appear) I2S_PDM_TX_CLK_DAC_DEFAULT_CONFIG(rate) I2S default PDM TX clock configuration for DAC line mode. Note TX PDM can only be set to the following two up-sampling rate configurations: 1: fp = 960, fs = sample_rate_hz / 100, in this case, Fpdm = 128*48000 2: fp = 960, fs = 480, in this case, Fpdm = 128*Fpcm = 128*sample_rate_hz If the PDM receiver do not care the PDM serial clock, it's recommended set Fpdm = 128*48000. Otherwise, the second configuration should be adopted. Note The noise might be different with different configurations, this macro provides a set of configurations that have relatively high SNR (Signal Noise Ratio), you can also adjust them to fit your case. Parameters rate -- sample rate (not suggest to exceed 48000 Hz, otherwise more glitches and noise may appear) rate -- sample rate (not suggest to exceed 48000 Hz, otherwise more glitches and noise may appear) rate -- sample rate (not suggest to exceed 48000 Hz, otherwise more glitches and noise may appear) Parameters rate -- sample rate (not suggest to exceed 48000 Hz, otherwise more glitches and noise may appear) I2S Driver Header File This header file can be included with: #include "driver/i2s_common.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t i2s_new_channel(const i2s_chan_config_t *chan_cfg, i2s_chan_handle_t *ret_tx_handle, i2s_chan_handle_t *ret_rx_handle) Allocate new I2S channel(s) Note The new created I2S channel handle will be REGISTERED state after it is allocated successfully. Note When the port id in channel configuration is I2S_NUM_AUTO, driver will allocate I2S port automatically on one of the I2S controller, otherwise driver will try to allocate the new channel on the selected port. Note If both tx_handle and rx_handle are not NULL, it means this I2S controller will work at full-duplex mode, the RX and TX channels will be allocated on a same I2S port in this case. Note that some configurations of TX/RX channel are shared on ESP32 and ESP32S2, so please make sure they are working at same condition and under same status(start/stop). Currently, full-duplex mode can't guarantee TX/RX channels write/read synchronously, they can only share the clock signals for now. Note If tx_handle OR rx_handle is NULL, it means this I2S controller will work at simplex mode. For ESP32 and ESP32S2, the whole I2S controller (i.e. both RX and TX channel) will be occupied, even if only one of RX or TX channel is registered. For the other targets, another channel on this controller will still available. Parameters chan_cfg -- [in] I2S controller channel configurations ret_tx_handle -- [out] I2S channel handler used for managing the sending channel(optional) ret_rx_handle -- [out] I2S channel handler used for managing the receiving channel(optional) chan_cfg -- [in] I2S controller channel configurations ret_tx_handle -- [out] I2S channel handler used for managing the sending channel(optional) ret_rx_handle -- [out] I2S channel handler used for managing the receiving channel(optional) chan_cfg -- [in] I2S controller channel configurations Returns ESP_OK Allocate new channel(s) success ESP_ERR_NOT_SUPPORTED The communication mode is not supported on the current chip ESP_ERR_INVALID_ARG NULL pointer or illegal parameter in i2s_chan_config_t ESP_ERR_NOT_FOUND No available I2S channel found ESP_OK Allocate new channel(s) success ESP_ERR_NOT_SUPPORTED The communication mode is not supported on the current chip ESP_ERR_INVALID_ARG NULL pointer or illegal parameter in i2s_chan_config_t ESP_ERR_NOT_FOUND No available I2S channel found ESP_OK Allocate new channel(s) success Parameters chan_cfg -- [in] I2S controller channel configurations ret_tx_handle -- [out] I2S channel handler used for managing the sending channel(optional) ret_rx_handle -- [out] I2S channel handler used for managing the receiving channel(optional) Returns ESP_OK Allocate new channel(s) success ESP_ERR_NOT_SUPPORTED The communication mode is not supported on the current chip ESP_ERR_INVALID_ARG NULL pointer or illegal parameter in i2s_chan_config_t ESP_ERR_NOT_FOUND No available I2S channel found esp_err_t i2s_del_channel(i2s_chan_handle_t handle) Delete the I2S channel. Note Only allowed to be called when the I2S channel is at REGISTERED or READY state (i.e., it should stop before deleting it). Note Resource will be free automatically if all channels in one port are deleted Parameters handle -- [in] I2S channel handler ESP_OK Delete successfully ESP_ERR_INVALID_ARG NULL pointer ESP_OK Delete successfully ESP_ERR_INVALID_ARG NULL pointer ESP_OK Delete successfully Parameters handle -- [in] I2S channel handler ESP_OK Delete successfully ESP_ERR_INVALID_ARG NULL pointer esp_err_t i2s_channel_get_info(i2s_chan_handle_t handle, i2s_chan_info_t *chan_info) Get I2S channel information. Parameters handle -- [in] I2S channel handler chan_info -- [out] I2S channel basic information handle -- [in] I2S channel handler chan_info -- [out] I2S channel basic information handle -- [in] I2S channel handler Returns ESP_OK Get I2S channel information success ESP_ERR_NOT_FOUND The input handle doesn't match any registered I2S channels, it may not an I2S channel handle or not available any more ESP_ERR_INVALID_ARG The input handle or chan_info pointer is NULL ESP_OK Get I2S channel information success ESP_ERR_NOT_FOUND The input handle doesn't match any registered I2S channels, it may not an I2S channel handle or not available any more ESP_ERR_INVALID_ARG The input handle or chan_info pointer is NULL ESP_OK Get I2S channel information success Parameters handle -- [in] I2S channel handler chan_info -- [out] I2S channel basic information Returns ESP_OK Get I2S channel information success ESP_ERR_NOT_FOUND The input handle doesn't match any registered I2S channels, it may not an I2S channel handle or not available any more ESP_ERR_INVALID_ARG The input handle or chan_info pointer is NULL esp_err_t i2s_channel_enable(i2s_chan_handle_t handle) Enable the I2S channel. Note Only allowed to be called when the channel state is READY, (i.e., channel has been initialized, but not started) the channel will enter RUNNING state once it is enabled successfully. Note Enable the channel can start the I2S communication on hardware. It will start outputting BCLK and WS signal. For MCLK signal, it will start to output when initialization is finished Parameters handle -- [in] I2S channel handler ESP_OK Start successfully ESP_ERR_INVALID_ARG NULL pointer ESP_ERR_INVALID_STATE This channel has not initialized or already started ESP_OK Start successfully ESP_ERR_INVALID_ARG NULL pointer ESP_ERR_INVALID_STATE This channel has not initialized or already started ESP_OK Start successfully Parameters handle -- [in] I2S channel handler ESP_OK Start successfully ESP_ERR_INVALID_ARG NULL pointer ESP_ERR_INVALID_STATE This channel has not initialized or already started esp_err_t i2s_channel_disable(i2s_chan_handle_t handle) Disable the I2S channel. Note Only allowed to be called when the channel state is RUNNING, (i.e., channel has been started) the channel will enter READY state once it is disabled successfully. Note Disable the channel can stop the I2S communication on hardware. It will stop BCLK and WS signal but not MCLK signal Parameters handle -- [in] I2S channel handler Returns ESP_OK Stop successfully ESP_ERR_INVALID_ARG NULL pointer ESP_ERR_INVALID_STATE This channel has not stated ESP_OK Stop successfully ESP_ERR_INVALID_ARG NULL pointer ESP_ERR_INVALID_STATE This channel has not stated ESP_OK Stop successfully Parameters handle -- [in] I2S channel handler Returns ESP_OK Stop successfully ESP_ERR_INVALID_ARG NULL pointer ESP_ERR_INVALID_STATE This channel has not stated esp_err_t i2s_channel_preload_data(i2s_chan_handle_t tx_handle, const void *src, size_t size, size_t *bytes_loaded) Preload the data into TX DMA buffer. Note Only allowed to be called when the channel state is READY, (i.e., channel has been initialized, but not started) Note As the initial DMA buffer has no data inside, it will transmit the empty buffer after enabled the channel, this function is used to preload the data into the DMA buffer, so that the valid data can be transmitted immediately after the channel is enabled. Note This function can be called multiple times before enabling the channel, the buffer that loaded later will be concatenated behind the former loaded buffer. But when all the DMA buffers have been loaded, no more data can be preload then, please check the bytes_loaded parameter to see how many bytes are loaded successfully, when the bytes_loaded is smaller than the size , it means the DMA buffers are full. Parameters tx_handle -- [in] I2S TX channel handler src -- [in] The pointer of the source buffer to be loaded size -- [in] The source buffer size bytes_loaded -- [out] The bytes that successfully been loaded into the TX DMA buffer tx_handle -- [in] I2S TX channel handler src -- [in] The pointer of the source buffer to be loaded size -- [in] The source buffer size bytes_loaded -- [out] The bytes that successfully been loaded into the TX DMA buffer tx_handle -- [in] I2S TX channel handler Returns ESP_OK Load data successful ESP_ERR_INVALID_ARG NULL pointer or not TX direction ESP_ERR_INVALID_STATE This channel has not stated ESP_OK Load data successful ESP_ERR_INVALID_ARG NULL pointer or not TX direction ESP_ERR_INVALID_STATE This channel has not stated ESP_OK Load data successful Parameters tx_handle -- [in] I2S TX channel handler src -- [in] The pointer of the source buffer to be loaded size -- [in] The source buffer size bytes_loaded -- [out] The bytes that successfully been loaded into the TX DMA buffer Returns ESP_OK Load data successful ESP_ERR_INVALID_ARG NULL pointer or not TX direction ESP_ERR_INVALID_STATE This channel has not stated esp_err_t i2s_channel_write(i2s_chan_handle_t handle, const void *src, size_t size, size_t *bytes_written, uint32_t timeout_ms) I2S write data. Note Only allowed to be called when the channel state is RUNNING, (i.e., TX channel has been started and is not writing now) but the RUNNING only stands for the software state, it doesn't mean there is no the signal transporting on line. Parameters handle -- [in] I2S channel handler src -- [in] The pointer of sent data buffer size -- [in] Max data buffer length bytes_written -- [out] Byte number that actually be sent, can be NULL if not needed timeout_ms -- [in] Max block time handle -- [in] I2S channel handler src -- [in] The pointer of sent data buffer size -- [in] Max data buffer length bytes_written -- [out] Byte number that actually be sent, can be NULL if not needed timeout_ms -- [in] Max block time handle -- [in] I2S channel handler Returns ESP_OK Write successfully ESP_ERR_INVALID_ARG NULL pointer or this handle is not TX handle ESP_ERR_TIMEOUT Writing timeout, no writing event received from ISR within ticks_to_wait ESP_ERR_INVALID_STATE I2S is not ready to write ESP_OK Write successfully ESP_ERR_INVALID_ARG NULL pointer or this handle is not TX handle ESP_ERR_TIMEOUT Writing timeout, no writing event received from ISR within ticks_to_wait ESP_ERR_INVALID_STATE I2S is not ready to write ESP_OK Write successfully Parameters handle -- [in] I2S channel handler src -- [in] The pointer of sent data buffer size -- [in] Max data buffer length bytes_written -- [out] Byte number that actually be sent, can be NULL if not needed timeout_ms -- [in] Max block time Returns ESP_OK Write successfully ESP_ERR_INVALID_ARG NULL pointer or this handle is not TX handle ESP_ERR_TIMEOUT Writing timeout, no writing event received from ISR within ticks_to_wait ESP_ERR_INVALID_STATE I2S is not ready to write esp_err_t i2s_channel_read(i2s_chan_handle_t handle, void *dest, size_t size, size_t *bytes_read, uint32_t timeout_ms) I2S read data. Note Only allowed to be called when the channel state is RUNNING but the RUNNING only stands for the software state, it doesn't mean there is no the signal transporting on line. Parameters handle -- [in] I2S channel handler dest -- [in] The pointer of receiving data buffer size -- [in] Max data buffer length bytes_read -- [out] Byte number that actually be read, can be NULL if not needed timeout_ms -- [in] Max block time handle -- [in] I2S channel handler dest -- [in] The pointer of receiving data buffer size -- [in] Max data buffer length bytes_read -- [out] Byte number that actually be read, can be NULL if not needed timeout_ms -- [in] Max block time handle -- [in] I2S channel handler Returns ESP_OK Read successfully ESP_ERR_INVALID_ARG NULL pointer or this handle is not RX handle ESP_ERR_TIMEOUT Reading timeout, no reading event received from ISR within ticks_to_wait ESP_ERR_INVALID_STATE I2S is not ready to read ESP_OK Read successfully ESP_ERR_INVALID_ARG NULL pointer or this handle is not RX handle ESP_ERR_TIMEOUT Reading timeout, no reading event received from ISR within ticks_to_wait ESP_ERR_INVALID_STATE I2S is not ready to read ESP_OK Read successfully Parameters handle -- [in] I2S channel handler dest -- [in] The pointer of receiving data buffer size -- [in] Max data buffer length bytes_read -- [out] Byte number that actually be read, can be NULL if not needed timeout_ms -- [in] Max block time Returns ESP_OK Read successfully ESP_ERR_INVALID_ARG NULL pointer or this handle is not RX handle ESP_ERR_TIMEOUT Reading timeout, no reading event received from ISR within ticks_to_wait ESP_ERR_INVALID_STATE I2S is not ready to read esp_err_t i2s_channel_register_event_callback(i2s_chan_handle_t handle, const i2s_event_callbacks_t *callbacks, void *user_data) Set event callbacks for I2S channel. Note Only allowed to be called when the channel state is REGISTERED / READY, (i.e., before channel starts) Note User can deregister a previously registered callback by calling this function and setting the callback member in the callbacks structure to NULL. Note When CONFIG_I2S_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. The user_data should also reside in SRAM or internal RAM as well. Parameters handle -- [in] I2S channel handler callbacks -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly handle -- [in] I2S channel handler callbacks -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly handle -- [in] I2S channel handler Returns ESP_OK Set event callbacks successfully ESP_ERR_INVALID_ARG Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE Set event callbacks failed because the current channel state is not REGISTERED or READY ESP_OK Set event callbacks successfully ESP_ERR_INVALID_ARG Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE Set event callbacks failed because the current channel state is not REGISTERED or READY ESP_OK Set event callbacks successfully Parameters handle -- [in] I2S channel handler callbacks -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly Returns ESP_OK Set event callbacks successfully ESP_ERR_INVALID_ARG Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE Set event callbacks failed because the current channel state is not REGISTERED or READY Structures struct i2s_event_callbacks_t Group of I2S callbacks. Note The callbacks are all running under ISR environment Note When CONFIG_I2S_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. Public Members i2s_isr_callback_t on_recv Callback of data received event, only for RX channel The event data includes DMA buffer address and size that just finished receiving data i2s_isr_callback_t on_recv Callback of data received event, only for RX channel The event data includes DMA buffer address and size that just finished receiving data i2s_isr_callback_t on_recv_q_ovf Callback of receiving queue overflowed event, only for RX channel The event data includes buffer size that has been overwritten i2s_isr_callback_t on_recv_q_ovf Callback of receiving queue overflowed event, only for RX channel The event data includes buffer size that has been overwritten i2s_isr_callback_t on_sent Callback of data sent event, only for TX channel The event data includes DMA buffer address and size that just finished sending data i2s_isr_callback_t on_sent Callback of data sent event, only for TX channel The event data includes DMA buffer address and size that just finished sending data i2s_isr_callback_t on_send_q_ovf Callback of sending queue overflowed event, only for TX channel The event data includes buffer size that has been overwritten i2s_isr_callback_t on_send_q_ovf Callback of sending queue overflowed event, only for TX channel The event data includes buffer size that has been overwritten i2s_isr_callback_t on_recv struct i2s_chan_config_t I2S controller channel configuration. Public Members i2s_port_t id I2S port id i2s_port_t id I2S port id i2s_role_t role I2S role, I2S_ROLE_MASTER or I2S_ROLE_SLAVE i2s_role_t role I2S role, I2S_ROLE_MASTER or I2S_ROLE_SLAVE uint32_t dma_desc_num I2S DMA buffer number, it is also the number of DMA descriptor uint32_t dma_desc_num I2S DMA buffer number, it is also the number of DMA descriptor uint32_t dma_frame_num I2S frame number in one DMA buffer. One frame means one-time sample data in all slots, it should be the multiple of 3 when the data bit width is 24. uint32_t dma_frame_num I2S frame number in one DMA buffer. One frame means one-time sample data in all slots, it should be the multiple of 3 when the data bit width is 24. bool auto_clear Set to auto clear DMA TX buffer, I2S will always send zero automatically if no data to send bool auto_clear Set to auto clear DMA TX buffer, I2S will always send zero automatically if no data to send int intr_priority I2S interrupt priority, range [0, 7], if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) int intr_priority I2S interrupt priority, range [0, 7], if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) i2s_port_t id struct i2s_chan_info_t I2S channel information. Public Members i2s_port_t id I2S port id i2s_port_t id I2S port id i2s_role_t role I2S role, I2S_ROLE_MASTER or I2S_ROLE_SLAVE i2s_role_t role I2S role, I2S_ROLE_MASTER or I2S_ROLE_SLAVE i2s_comm_mode_t mode I2S channel communication mode i2s_comm_mode_t mode I2S channel communication mode i2s_chan_handle_t pair_chan I2S pair channel handle in duplex mode, always NULL in simplex mode i2s_chan_handle_t pair_chan I2S pair channel handle in duplex mode, always NULL in simplex mode i2s_port_t id Macros I2S_CHANNEL_DEFAULT_CONFIG(i2s_num, i2s_role) get default I2S property I2S_GPIO_UNUSED Used in i2s_gpio_config_t for signals which are not used I2S Types Header File This header file can be included with: #include "driver/i2s_types.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Structures struct i2s_event_data_t Event structure used in I2S event queue. Public Members void *data The pointer of DMA buffer that just finished sending or receiving for on_recv and on_sent callback NULL for on_recv_q_ovf and on_send_q_ovf callback void *data The pointer of DMA buffer that just finished sending or receiving for on_recv and on_sent callback NULL for on_recv_q_ovf and on_send_q_ovf callback size_t size The buffer size of DMA buffer when success to send or receive, also the buffer size that dropped when queue overflow. It is related to the dma_frame_num and data_bit_width, typically it is fixed when data_bit_width is not changed. size_t size The buffer size of DMA buffer when success to send or receive, also the buffer size that dropped when queue overflow. It is related to the dma_frame_num and data_bit_width, typically it is fixed when data_bit_width is not changed. void *data Type Definitions typedef struct i2s_channel_obj_t *i2s_chan_handle_t I2S channel object handle, the control unit of the I2S driver typedef bool (*i2s_isr_callback_t)(i2s_chan_handle_t handle, i2s_event_data_t *event, void *user_ctx) I2S event callback. Param handle [in] I2S channel handle, created from i2s_new_channel() Param event [in] I2S event data Param user_ctx [in] User registered context, passed from i2s_channel_register_event_callback() Return Whether a high priority task has been waken up by this callback function Param handle [in] I2S channel handle, created from i2s_new_channel() Param event [in] I2S event data Param user_ctx [in] User registered context, passed from i2s_channel_register_event_callback() Return Whether a high priority task has been waken up by this callback function Enumerations enum i2s_port_t I2S controller port number, the max port number is (SOC_I2S_NUM -1). Values: enumerator I2S_NUM_0 I2S controller port 0 enumerator I2S_NUM_0 I2S controller port 0 enumerator I2S_NUM_1 I2S controller port 1 enumerator I2S_NUM_1 I2S controller port 1 enumerator I2S_NUM_AUTO Select whichever port is available enumerator I2S_NUM_AUTO Select whichever port is available enumerator I2S_NUM_0 enum i2s_comm_mode_t I2S controller communication mode. Values: enumerator I2S_COMM_MODE_STD I2S controller using standard communication mode, support Philips/MSB/PCM format enumerator I2S_COMM_MODE_STD I2S controller using standard communication mode, support Philips/MSB/PCM format enumerator I2S_COMM_MODE_PDM I2S controller using PDM communication mode, support PDM output or input enumerator I2S_COMM_MODE_PDM I2S controller using PDM communication mode, support PDM output or input enumerator I2S_COMM_MODE_NONE Unspecified I2S controller mode enumerator I2S_COMM_MODE_NONE Unspecified I2S controller mode enumerator I2S_COMM_MODE_STD enum i2s_mclk_multiple_t The multiple of MCLK to sample rate. Values: enumerator I2S_MCLK_MULTIPLE_128 MCLK = sample_rate * 128 enumerator I2S_MCLK_MULTIPLE_128 MCLK = sample_rate * 128 enumerator I2S_MCLK_MULTIPLE_256 MCLK = sample_rate * 256 enumerator I2S_MCLK_MULTIPLE_256 MCLK = sample_rate * 256 enumerator I2S_MCLK_MULTIPLE_384 MCLK = sample_rate * 384 enumerator I2S_MCLK_MULTIPLE_384 MCLK = sample_rate * 384 enumerator I2S_MCLK_MULTIPLE_512 MCLK = sample_rate * 512 enumerator I2S_MCLK_MULTIPLE_512 MCLK = sample_rate * 512 enumerator I2S_MCLK_MULTIPLE_128 Header File This header file can be included with: #include "hal/i2s_types.h" Type Definitions typedef soc_periph_i2s_clk_src_t i2s_clock_src_t I2S clock source Enumerations enum i2s_slot_mode_t I2S channel slot mode. Values: enumerator I2S_SLOT_MODE_MONO I2S channel slot format mono, transmit same data in all slots for tx mode, only receive the data in the first slots for rx mode. enumerator I2S_SLOT_MODE_MONO I2S channel slot format mono, transmit same data in all slots for tx mode, only receive the data in the first slots for rx mode. enumerator I2S_SLOT_MODE_STEREO I2S channel slot format stereo, transmit different data in different slots for tx mode, receive the data in all slots for rx mode. enumerator I2S_SLOT_MODE_STEREO I2S channel slot format stereo, transmit different data in different slots for tx mode, receive the data in all slots for rx mode. enumerator I2S_SLOT_MODE_MONO enum i2s_dir_t I2S channel direction. Values: enumerator I2S_DIR_RX I2S channel direction RX enumerator I2S_DIR_RX I2S channel direction RX enumerator I2S_DIR_TX I2S channel direction TX enumerator I2S_DIR_TX I2S channel direction TX enumerator I2S_DIR_RX enum i2s_role_t I2S controller role. Values: enumerator I2S_ROLE_MASTER I2S controller master role, bclk and ws signal will be set to output enumerator I2S_ROLE_MASTER I2S controller master role, bclk and ws signal will be set to output enumerator I2S_ROLE_SLAVE I2S controller slave role, bclk and ws signal will be set to input enumerator I2S_ROLE_SLAVE I2S controller slave role, bclk and ws signal will be set to input enumerator I2S_ROLE_MASTER enum i2s_data_bit_width_t Available data bit width in one slot. Values: enumerator I2S_DATA_BIT_WIDTH_8BIT I2S channel data bit-width: 8 enumerator I2S_DATA_BIT_WIDTH_8BIT I2S channel data bit-width: 8 enumerator I2S_DATA_BIT_WIDTH_16BIT I2S channel data bit-width: 16 enumerator I2S_DATA_BIT_WIDTH_16BIT I2S channel data bit-width: 16 enumerator I2S_DATA_BIT_WIDTH_24BIT I2S channel data bit-width: 24 enumerator I2S_DATA_BIT_WIDTH_24BIT I2S channel data bit-width: 24 enumerator I2S_DATA_BIT_WIDTH_32BIT I2S channel data bit-width: 32 enumerator I2S_DATA_BIT_WIDTH_32BIT I2S channel data bit-width: 32 enumerator I2S_DATA_BIT_WIDTH_8BIT enum i2s_slot_bit_width_t Total slot bit width in one slot. Values: enumerator I2S_SLOT_BIT_WIDTH_AUTO I2S channel slot bit-width equals to data bit-width enumerator I2S_SLOT_BIT_WIDTH_AUTO I2S channel slot bit-width equals to data bit-width enumerator I2S_SLOT_BIT_WIDTH_8BIT I2S channel slot bit-width: 8 enumerator I2S_SLOT_BIT_WIDTH_8BIT I2S channel slot bit-width: 8 enumerator I2S_SLOT_BIT_WIDTH_16BIT I2S channel slot bit-width: 16 enumerator I2S_SLOT_BIT_WIDTH_16BIT I2S channel slot bit-width: 16 enumerator I2S_SLOT_BIT_WIDTH_24BIT I2S channel slot bit-width: 24 enumerator I2S_SLOT_BIT_WIDTH_24BIT I2S channel slot bit-width: 24 enumerator I2S_SLOT_BIT_WIDTH_32BIT I2S channel slot bit-width: 32 enumerator I2S_SLOT_BIT_WIDTH_32BIT I2S channel slot bit-width: 32 enumerator I2S_SLOT_BIT_WIDTH_AUTO enum i2s_pdm_dsr_t I2S PDM RX down-sampling mode. Values: enumerator I2S_PDM_DSR_8S downsampling number is 8 for PDM RX mode enumerator I2S_PDM_DSR_8S downsampling number is 8 for PDM RX mode enumerator I2S_PDM_DSR_16S downsampling number is 16 for PDM RX mode enumerator I2S_PDM_DSR_16S downsampling number is 16 for PDM RX mode enumerator I2S_PDM_DSR_MAX enumerator I2S_PDM_DSR_MAX enumerator I2S_PDM_DSR_8S enum i2s_pdm_sig_scale_t pdm tx singnal scaling mode Values: enumerator I2S_PDM_SIG_SCALING_DIV_2 I2S TX PDM signal scaling: /2 enumerator I2S_PDM_SIG_SCALING_DIV_2 I2S TX PDM signal scaling: /2 enumerator I2S_PDM_SIG_SCALING_MUL_1 I2S TX PDM signal scaling: x1 enumerator I2S_PDM_SIG_SCALING_MUL_1 I2S TX PDM signal scaling: x1 enumerator I2S_PDM_SIG_SCALING_MUL_2 I2S TX PDM signal scaling: x2 enumerator I2S_PDM_SIG_SCALING_MUL_2 I2S TX PDM signal scaling: x2 enumerator I2S_PDM_SIG_SCALING_MUL_4 I2S TX PDM signal scaling: x4 enumerator I2S_PDM_SIG_SCALING_MUL_4 I2S TX PDM signal scaling: x4 enumerator I2S_PDM_SIG_SCALING_DIV_2 enum i2s_std_slot_mask_t I2S slot select in standard mode. Note It has different meanings in tx/rx/mono/stereo mode, and it may have differen behaviors on different targets For the details, please refer to the I2S API reference Values: enumerator I2S_STD_SLOT_LEFT I2S transmits or receives left slot enumerator I2S_STD_SLOT_LEFT I2S transmits or receives left slot enumerator I2S_STD_SLOT_RIGHT I2S transmits or receives right slot enumerator I2S_STD_SLOT_RIGHT I2S transmits or receives right slot enumerator I2S_STD_SLOT_BOTH I2S transmits or receives both left and right slot enumerator I2S_STD_SLOT_BOTH I2S transmits or receives both left and right slot enumerator I2S_STD_SLOT_LEFT enum i2s_pdm_slot_mask_t I2S slot select in PDM mode. Values: enumerator I2S_PDM_SLOT_RIGHT I2S PDM only transmits or receives the PDM device whose 'select' pin is pulled up enumerator I2S_PDM_SLOT_RIGHT I2S PDM only transmits or receives the PDM device whose 'select' pin is pulled up enumerator I2S_PDM_SLOT_LEFT I2S PDM only transmits or receives the PDM device whose 'select' pin is pulled down enumerator I2S_PDM_SLOT_LEFT I2S PDM only transmits or receives the PDM device whose 'select' pin is pulled down enumerator I2S_PDM_SLOT_BOTH I2S PDM transmits or receives both two slots enumerator I2S_PDM_SLOT_BOTH I2S PDM transmits or receives both two slots enumerator I2S_PDM_SLOT_RIGHT
Inter-IC Sound (I2S) Introduction I2S (Inter-IC Sound) is a synchronous serial communication protocol usually used for transmitting audio data between two digital audio devices. ESP32 contains two I2S peripheral(s). These peripherals can be configured to input and output sample data via the I2S driver. An I2S bus that communicates in standard or TDM mode consists of the following lines: MCLK: Master clock line. It is an optional signal depending on the slave side, mainly used for offering a reference clock to the I2S slave device. BCLK: Bit clock line. The bit clock for data line. WS: Word (Slot) select line. It is usually used to identify the vocal tract except PDM mode. DIN/DOUT: Serial data input/output line. Data will loopback internally if DIN and DOUT are set to a same GPIO. An I2S bus that communicates in PDM mode consists of the following lines: CLK: PDM clock line. DIN/DOUT: Serial data input/output line. Each I2S controller has the following features that can be configured by the I2S driver: Operation as system master or slave Capable of acting as transmitter or receiver DMA controller that allows stream sampling of data without requiring the CPU to copy each data sample Each controller supports single RX or TX simplex communication. As RX and TX channels share a clock, they can only be combined with the same configuration to establish a full-duplex communication. I2S File Structure Public headers that need to be included in the I2S application are as follows: i2s.h: The header file that provides legacy I2S APIs (for apps using legacy driver). i2s_std.h: The header file that provides standard communication mode specific APIs (for apps using new driver with standard mode). i2s_pdm.h: The header file that provides PDM communication mode specific APIs (for apps using new driver with PDM mode). i2s_tdm.h: The header file that provides TDM communication mode specific APIs (for apps using new driver with TDM mode). Note The legacy driver cannot coexist with the new driver. Include i2s.h to use the legacy driver, or include the other three headers to use the new driver. The legacy driver might be removed in future. Public headers that have been included in the headers above are as follows: i2s_types_legacy.h: The header file that provides legacy public types that are only used in the legacy driver. i2s_types.h: The header file that provides public types. i2s_common.h: The header file that provides common APIs for all communication modes. I2S Clock Clock Source i2s_clock_src_t::I2S_CLK_SRC_DEFAULT: Default PLL clock. i2s_clock_src_t::I2S_CLK_SRC_PLL_160M: 160 MHz PLL clock. i2s_clock_src_t::I2S_CLK_SRC_APLL: Audio PLL clock, which is more precise than I2S_CLK_SRC_PLL_160Min high sample rate applications. Its frequency is configurable according to the sample rate. However, if APLL has been occupied by EMAC or other channels, the APLL frequency cannot be changed, and the driver will try to work under this APLL frequency. If this frequency cannot meet the requirements of I2S, the clock configuration will fail. Clock Terminology Sample rate: The number of sampled data in one second per slot. SCLK: Source clock frequency. It is the frequency of the clock source. MCLK: Master clock frequency. BCLK is generated from this clock. The MCLK signal usually serves as a reference clock and is mostly needed to synchronize BCLK and WS between I2S master and slave roles. BCLK: Bit clock frequency. Every tick of this clock stands for one data bit on data pin. The slot bit width configured in i2s_std_slot_config_t::slot_bit_widthis equal to the number of BCLK ticks, which means there will be 8/16/24/32 BCLK ticks in one slot. LRCK / WS: Left/right clock or word select clock. For non-PDM mode, its frequency is equal to the sample rate. Note Normally, MCLK should be the multiple of sample rate and BCLK at the same time. The field i2s_std_clk_config_t::mclk_multiple indicates the multiple of MCLK to the sample rate. In most cases, I2S_MCLK_MULTIPLE_256 should be enough. However, if slot_bit_width is set to I2S_SLOT_BIT_WIDTH_24BIT, to keep MCLK a multiple to the BCLK, i2s_std_clk_config_t::mclk_multiple should be set to multiples that are divisible by 3 such as I2S_MCLK_MULTIPLE_384. Otherwise, WS will be inaccurate. I2S Communication Mode Overview of All Modes | Target | Standard | PDM TX | PDM RX | TDM | ADC/DAC | LCD/Camera | ESP32 | I2S 0/1 | I2S 0 | I2S 0 | none | I2S 0 | I2S 0 | ESP32-S2 | I2S 0 | none | none | none | none | I2S 0 | ESP32-C3 | I2S 0 | I2S 0 | none | I2S 0 | none | none | ESP32-C6 | I2S 0 | I2S 0 | none | I2S 0 | none | none | ESP32-S3 | I2S 0/1 | I2S 0 | I2S 0 | I2S 0/1 | none | none | ESP32-H2 | I2S 0 | I2S 0 | none | I2S 0 | none | none | ESP32-P4 | I2S 0~2 | I2S 0 | I2S 0 | I2S 0~2 | none | none Standard Mode In standard mode, there are always two sound channels, i.e., the left and right channels, which are called "slots". These slots support 8/16/24/32-bit width sample data. The communication format for the slots mainly includes the followings: Philips Format: Data signal has one-bit shift comparing to the WS signal, and the duty of WS signal is 50%. MSB Format: Basically the same as Philips format, but without data shift. PCM Short Format: Data has one-bit shift and meanwhile the WS signal becomes a pulse lasting for one BCLK cycle. PDM Mode (TX) PDM (Pulse-density Modulation) mode for the TX channel can convert PCM data into PDM format which always has left and right slots. PDM TX is only supported on I2S0 and it only supports 16-bit width sample data. It needs at least a CLK pin for clock signal and a DOUT pin for data signal (i.e., the WS and SD signal in the following figure; the BCK signal is an internal bit sampling clock, which is not needed between PDM devices). This mode allows users to configure the up-sampling parameters i2s_pdm_tx_clk_config_t::up_sample_fp and i2s_pdm_tx_clk_config_t::up_sample_fs. The up-sampling rate can be calculated by up_sample_rate = i2s_pdm_tx_clk_config_t::up_sample_fp / i2s_pdm_tx_clk_config_t::up_sample_fs. There are two up-sampling modes in PDM TX: Fixed Clock Frequency: In this mode, the up-sampling rate changes according to the sample rate. Setting fp = 960and fs = sample_rate / 100, then the clock frequency (Fpdm) on CLK pin will be fixed to 128 * 48 KHz = 6.144 MHz. Note that this frequency is not equal to the sample rate (Fpcm). Fixed Up-sampling Rate: In this mode, the up-sampling rate is fixed to 2. Setting fp = 960and fs = 480, then the clock frequency (Fpdm) on CLK pin will be 128 * sample_rate. PDM Mode (RX) PDM (Pulse-density Modulation) mode for RX channel can receive PDM-format data and convert the data into PCM format. PDM RX is only supported on I2S0, and it only supports 16-bit width sample data. PDM RX needs at least a CLK pin for clock signal and a DIN pin for data signal. This mode allows users to configure the down-sampling parameter i2s_pdm_rx_clk_config_t::dn_sample_mode. There are two down-sampling modes in PDM RX: i2s_pdm_dsr_t::I2S_PDM_DSR_8S: In this mode, the clock frequency (Fpdm) on the WS pin is sample_rate (Fpcm) * 64. i2s_pdm_dsr_t::I2S_PDM_DSR_16S: In this mode, the clock frequency (Fpdm) on the WS pin is sample_rate (Fpcm) * 128. LCD/Camera Mode LCD/Camera mode is only supported on I2S0 over a parallel bus. For LCD mode, I2S0 should work at master TX mode. For camera mode, I2S0 should work at slave RX mode. These two modes are not implemented by the I2S driver. Please refer to LCD for details about the LCD implementation. For more information, see ESP32 Technical Reference Manual > I2S Controller (I2S) > LCD Mode [PDF]. ADC/DAC Mode ADC and DAC modes only exist on ESP32 and are only supported on I2S0. Actually, they are two sub-modes of LCD/Camera mode. I2S0 can be routed directly to the internal analog-to-digital converter (ADC) and digital-to-analog converter (DAC). In other words, ADC and DAC peripherals can read or write continuously via I2S0 DMA. As they are not actual communication modes, the I2S driver does not implement them. Functional Overview The I2S driver offers the following services: Resource Management There are three levels of resources in the I2S driver: platform level: Resources of all I2S controllers in the current target. controller level: Resources in one I2S controller. channel level: Resources of TX or RX channel in one I2S controller. The public APIs are all channel-level APIs. The channel handle i2s_chan_handle_t can help users to manage the resources under a specific channel without considering the other two levels. The other two upper levels' resources are private and are managed by the driver automatically. Users can call i2s_new_channel() to allocate a channel handle and call i2s_del_channel() to delete it. Power Management When the power management is enabled (i.e., CONFIG_PM_ENABLE is on), the system will adjust or stop the source clock of I2S before entering Light-sleep, thus potentially changing the I2S signals and leading to transmitting or receiving invalid data. The I2S driver can prevent the system from changing or stopping the source clock by acquiring a power management lock. When the source clock is generated from APB, the lock type will be set to esp_pm_lock_type_t::ESP_PM_APB_FREQ_MAX and when the source clock is APLL (if supported), it will be set to esp_pm_lock_type_t::ESP_PM_NO_LIGHT_SLEEP. Whenever the user is reading or writing via I2S (i.e., calling i2s_channel_read() or i2s_channel_write()), the driver guarantees that the power management lock is acquired. Likewise, the driver releases the lock after the reading or writing finishes. Finite State Machine There are three states for an I2S channel, namely, registered, ready, and running. Their relationship is shown in the following diagram: The <mode> in the diagram can be replaced by corresponding I2S communication modes, e.g., std for standard two-slot mode. For more information about communication modes, please refer to the I2S Communication Mode section. Data Transport The data transport of the I2S peripheral, including sending and receiving, is realized by DMA. Before transporting data, please call i2s_channel_enable() to enable the specific channel. When the sent or received data reaches the size of one DMA buffer, the I2S_OUT_EOF or I2S_IN_SUC_EOF interrupt will be triggered. Note that the DMA buffer size is not equal to i2s_chan_config_t::dma_frame_num. One frame here refers to all the sampled data in one WS circle. Therefore, dma_buffer_size = dma_frame_num * slot_num * slot_bit_width / 8. For the data transmitting, users can input the data by calling i2s_channel_write(). This function helps users to copy the data from the source buffer to the DMA TX buffer and wait for the transmission to finish. Then it will repeat until the sent bytes reach the given size. For the data receiving, the function i2s_channel_read() waits to receive the message queue which contains the DMA buffer address. It helps users copy the data from the DMA RX buffer to the destination buffer. Both i2s_channel_write() and i2s_channel_read() are blocking functions. They keeps waiting until the whole source buffer is sent or the whole destination buffer is loaded, unless they exceed the max blocking time, where the error code ESP_ERR_TIMEOUT returns. To send or receive data asynchronously, callbacks can be registered by i2s_channel_register_event_callback(). Users are able to access the DMA buffer directly in the callback function instead of transmitting or receiving by the two blocking functions. However, please be aware that it is an interrupt callback, so do not add complex logic, run floating operation, or call non-reentrant functions in the callback. Configuration Users can initialize a channel by calling corresponding functions (i.e., i2s_channel_init_std_mode(), i2s_channel_init_pdm_rx_mode(), i2s_channel_init_pdm_tx_mode(), or i2s_channel_init_tdm_mode()) to a specific mode. If the configurations need to be updated after initialization, users have to first call i2s_channel_disable() to ensure that the channel has stopped, and then call corresponding reconfig functions, like i2s_channel_reconfig_std_slot(), i2s_channel_reconfig_std_clock(), and i2s_channel_reconfig_std_gpio(). IRAM Safe By default, the I2S interrupt will be deferred when the cache is disabled for reasons like writing/erasing flash. Thus the EOF interrupt will not get executed in time. To avoid such case in real-time applications, you can enable the Kconfig option CONFIG_I2S_ISR_IRAM_SAFE that: Keeps the interrupt being serviced even when the cache is disabled. Places driver object into DRAM (in case it is linked to PSRAM by accident). This allows the interrupt to run while the cache is disabled, but comes at the cost of increased IRAM consumption. Thread Safety All the public I2S APIs are guaranteed to be thread safe by the driver, which means users can call them from different RTOS tasks without protection by extra locks. Notice that the I2S driver uses mutex lock to ensure the thread safety, thus these APIs are not allowed to be used in ISR. Kconfig Options CONFIG_I2S_ISR_IRAM_SAFE controls whether the default ISR handler can work when the cache is disabled. See IRAM Safe for more information. CONFIG_I2S_SUPPRESS_DEPRECATE_WARN controls whether to suppress the compiling warning message while using the legacy I2S driver. CONFIG_I2S_ENABLE_DEBUG_LOG is used to enable the debug log output. Enable this option increases the firmware binary size. Application Example The examples of the I2S driver can be found in the directory peripherals/i2s. Here are some simple usages of each mode: Standard TX/RX Usage Different slot communication formats can be generated by the following helper macros for standard mode. As described above, there are three formats in standard mode, and their helper macros are: The clock config helper macro is: Please refer to Standard Mode for information about STD API. And for more details, please refer to driver/i2s/include/driver/i2s_std.h. STD TX Mode Take 16-bit data width for example. When the data in a uint16_t writing buffer are: | data 0 | data 1 | data 2 | data 3 | data 4 | data 5 | data 6 | data 7 | ... | 0x0001 | 0x0002 | 0x0003 | 0x0004 | 0x0005 | 0x0006 | 0x0007 | 0x0008 | ... Here is the table of the real data on the line with different i2s_std_slot_config_t::slot_mode and i2s_std_slot_config_t::slot_mask. | data bit width | slot mode | slot mask | WS low | WS high | WS low | WS high | WS low | WS high | WS low | WS high | 16 bit | mono | left | 0x0002 | 0x0000 | 0x0001 | 0x0000 | 0x0004 | 0x0000 | 0x0003 | 0x0000 | right | 0x0000 | 0x0002 | 0x0000 | 0x0001 | 0x0000 | 0x0004 | 0x0000 | 0x0003 | both | 0x0002 | 0x0002 | 0x0001 | 0x0001 | 0x0004 | 0x0004 | 0x0003 | 0x0003 | stereo | left | 0x0001 | 0x0001 | 0x0003 | 0x0003 | 0x0005 | 0x0005 | 0x0007 | 0x0007 | right | 0x0002 | 0x0002 | 0x0004 | 0x0004 | 0x0006 | 0x0006 | 0x0008 | 0x0008 | both | 0x0001 | 0x0002 | 0x0003 | 0x0004 | 0x0005 | 0x0006 | 0x0007 | 0x0008 Note It is similar when the data is 32-bit width, but take care when using 8-bit and 24-bit data width. For 8-bit width, the written buffer should still use uint16_t (i.e., align with 2 bytes), and only the high 8 bits are valid while the low 8 bits are dropped. For 24-bit width, the buffer is supposed to use uint32_t (i.e., align with 4 bytes), and only the high 24 bits are valid while the low 8 bits are dropped. Besides, for 8-bit and 16-bit mono modes, the real data on the line is swapped. To get the correct data sequence, the writing buffer needs to swap the data every two bytes. #include "driver/i2s_std.h" #include "driver/gpio.h" i2s_chan_handle_t tx_handle; /* Get the default channel configuration by the helper macro. * This helper macro is defined in `i2s_common.h` and shared by all the I2S communication modes. * It can help to specify the I2S role and port ID */ i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_AUTO, I2S_ROLE_MASTER); /* Allocate a new TX channel and get the handle of this channel */ i2s_new_channel(&chan_cfg, &tx_handle, NULL); /* Setting the configurations, the slot configuration and clock configuration can be generated by the macros * These two helper macros are defined in `i2s_std.h` which can only be used in STD mode. * They can help to specify the slot and clock configurations for initialization or updating */ i2s_std_config_t std_cfg = { .clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(48000), .slot_cfg = I2S_STD_MSB_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_STEREO), .gpio_cfg = { .mclk = I2S_GPIO_UNUSED, .bclk = GPIO_NUM_4, .ws = GPIO_NUM_5, .dout = GPIO_NUM_18, .din = I2S_GPIO_UNUSED, .invert_flags = { .mclk_inv = false, .bclk_inv = false, .ws_inv = false, }, }, }; /* Initialize the channel */ i2s_channel_init_std_mode(tx_handle, &std_cfg); /* Before writing data, start the TX channel first */ i2s_channel_enable(tx_handle); i2s_channel_write(tx_handle, src_buf, bytes_to_write, bytes_written, ticks_to_wait); /* If the configurations of slot or clock need to be updated, * stop the channel first and then update it */ // i2s_channel_disable(tx_handle); // std_cfg.slot_cfg.slot_mode = I2S_SLOT_MODE_MONO; // Default is stereo // i2s_channel_reconfig_std_slot(tx_handle, &std_cfg.slot_cfg); // std_cfg.clk_cfg.sample_rate_hz = 96000; // i2s_channel_reconfig_std_clock(tx_handle, &std_cfg.clk_cfg); /* Have to stop the channel before deleting it */ i2s_channel_disable(tx_handle); /* If the handle is not needed any more, delete it to release the channel resources */ i2s_del_channel(tx_handle); STD RX Mode Taking 16-bit data width for example, when the data on the line are: | WS low | WS high | WS low | WS high | WS low | WS high | WS low | WS high | ... | 0x0001 | 0x0002 | 0x0003 | 0x0004 | 0x0005 | 0x0006 | 0x0007 | 0x0008 | ... Here is the table of the data received in the buffer with different i2s_std_slot_config_t::slot_mode and i2s_std_slot_config_t::slot_mask. | data bit width | slot mode | slot mask | data 0 | data 1 | data 2 | data 3 | data 4 | data 5 | data 6 | data 7 | 16 bit | mono | left | 0x0001 | 0x0000 | 0x0005 | 0x0003 | 0x0009 | 0x0007 | 0x000d | 0x000b | right | 0x0002 | 0x0000 | 0x0006 | 0x0004 | 0x000a | 0x0008 | 0x000e | 0x000c | stereo | any | 0x0001 | 0x0002 | 0x0003 | 0x0004 | 0x0005 | 0x0006 | 0x0007 | 0x0008 Note The receive case is a little bit complicated on ESP32. Firstly, when the data width is 8-bit or 24-bit, the received data will still align with two bytes or four bytes, which means that the valid data are put in the high 8 bits in every two bytes and high 24 bits in every four bytes. For example, the received data will be 0x5A00 when the data on the line is 0x5A in 8-bit width, and 0x0000 5A00 if the data on the line is 0x00 005A. Secondly, for the 8-bit or 16-bit mono case, the data in buffer is swapped every two data, so it may be necessary to manually swap the data back to the correct order. #include "driver/i2s_std.h" #include "driver/gpio.h" i2s_chan_handle_t rx_handle; /* Get the default channel configuration by helper macro. * This helper macro is defined in `i2s_common.h` and shared by all the I2S communication modes. * It can help to specify the I2S role and port ID */ i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_AUTO, I2S_ROLE_MASTER); /* Allocate a new RX channel and get the handle of this channel */ i2s_new_channel(&chan_cfg, NULL, &rx_handle); /* Setting the configurations, the slot configuration and clock configuration can be generated by the macros * These two helper macros are defined in `i2s_std.h` which can only be used in STD mode. * They can help to specify the slot and clock configurations for initialization or updating */ i2s_std_config_t std_cfg = { .clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(48000), .slot_cfg = I2S_STD_MSB_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_STEREO), .gpio_cfg = { .mclk = I2S_GPIO_UNUSED, .bclk = GPIO_NUM_4, .ws = GPIO_NUM_5, .dout = I2S_GPIO_UNUSED, .din = GPIO_NUM_19, .invert_flags = { .mclk_inv = false, .bclk_inv = false, .ws_inv = false, }, }, }; /* Initialize the channel */ i2s_channel_init_std_mode(rx_handle, &std_cfg); /* Before reading data, start the RX channel first */ i2s_channel_enable(rx_handle); i2s_channel_read(rx_handle, desc_buf, bytes_to_read, bytes_read, ticks_to_wait); /* Have to stop the channel before deleting it */ i2s_channel_disable(rx_handle); /* If the handle is not needed any more, delete it to release the channel resources */ i2s_del_channel(rx_handle); PDM TX Usage For PDM mode in TX channel, the slot configuration helper macro is: The clock configuration helper macro is: Please refer to PDM Mode for information about PDM TX API. And for more details, please refer to driver/i2s/include/driver/i2s_pdm.h. The PDM data width is fixed to 16-bit. When the data in an int16_t writing buffer is: | data 0 | data 1 | data 2 | data 3 | data 4 | data 5 | data 6 | data 7 | ... | 0x0001 | 0x0002 | 0x0003 | 0x0004 | 0x0005 | 0x0006 | 0x0007 | 0x0008 | ... Here is the table of the real data on the line with different i2s_pdm_tx_slot_config_t::slot_mode and i2s_pdm_tx_slot_config_t::slot_mask (The PDM format on the line is transferred to PCM format for better comprehension). | slot mode | slot mask | left | right | left | right | left | right | left | right | mono | left | 0x0001 | 0x0000 | 0x0002 | 0x0000 | 0x0003 | 0x0000 | 0x0004 | 0x0000 | right | 0x0000 | 0x0001 | 0x0000 | 0x0002 | 0x0000 | 0x0003 | 0x0000 | 0x0004 | both | 0x0001 | 0x0001 | 0x0002 | 0x0002 | 0x0003 | 0x0003 | 0x0004 | 0x0004 | stereo | left | 0x0001 | 0x0001 | 0x0003 | 0x0003 | 0x0005 | 0x0005 | 0x0007 | 0x0007 | right | 0x0002 | 0x0002 | 0x0004 | 0x0004 | 0x0006 | 0x0006 | 0x0008 | 0x0008 | both | 0x0001 | 0x0002 | 0x0003 | 0x0004 | 0x0005 | 0x0006 | 0x0007 | 0x0008 #include "driver/i2s_pdm.h" #include "driver/gpio.h" /* Allocate an I2S TX channel */ i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER); i2s_new_channel(&chan_cfg, &tx_handle, NULL); /* Init the channel into PDM TX mode */ i2s_pdm_tx_config_t pdm_tx_cfg = { .clk_cfg = I2S_PDM_TX_CLK_DEFAULT_CONFIG(36000), .slot_cfg = I2S_PDM_TX_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_MONO), .gpio_cfg = { .clk = GPIO_NUM_5, .dout = GPIO_NUM_18, .invert_flags = { .clk_inv = false, }, }, }; i2s_channel_init_pdm_tx_mode(tx_handle, &pdm_tx_cfg); ... PDM RX Usage For PDM mode in RX channel, the slot configuration helper macro is: The clock configuration helper macro is: Please refer to PDM Mode for information about PDM RX API. And for more details, please refer to driver/i2s/include/driver/i2s_pdm.h. The PDM data width is fixed to 16-bit. When the data on the line (The PDM format on the line is transferred to PCM format for easier comprehension) is: | left | right | left | right | left | right | left | right | ... | 0x0001 | 0x0002 | 0x0003 | 0x0004 | 0x0005 | 0x0006 | 0x0007 | 0x0008 | ... Here is the table of the data received in a int16_t buffer with different i2s_pdm_rx_slot_config_t::slot_mode and i2s_pdm_rx_slot_config_t::slot_mask. | slot mode | slot mask | data 0 | data 1 | data 2 | data 3 | data 4 | data 5 | data 6 | data 7 | mono | left | 0x0001 | 0x0003 | 0x0005 | 0x0007 | 0x0009 | 0x000b | 0x000d | 0x000f | right | 0x0002 | 0x0004 | 0x0006 | 0x0008 | 0x000a | 0x000c | 0x000e | 0x0010 | stereo | both | 0x0001 | 0x0002 | 0x0003 | 0x0004 | 0x0005 | 0x0006 | 0x0007 | 0x0008 #include "driver/i2s_pdm.h" #include "driver/gpio.h" i2s_chan_handle_t rx_handle; /* Allocate an I2S RX channel */ i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER); i2s_new_channel(&chan_cfg, NULL, &rx_handle); /* Init the channel into PDM RX mode */ i2s_pdm_rx_config_t pdm_rx_cfg = { .clk_cfg = I2S_PDM_RX_CLK_DEFAULT_CONFIG(36000), .slot_cfg = I2S_PDM_RX_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_MONO), .gpio_cfg = { .clk = GPIO_NUM_5, .din = GPIO_NUM_19, .invert_flags = { .clk_inv = false, }, }, }; i2s_channel_init_pdm_rx_mode(rx_handle, &pdm_rx_cfg); ... Full-duplex Full-duplex mode registers TX and RX channel in an I2S port at the same time, and the channels share the BCLK and WS signals. Currently, STD and TDM communication modes supports full-duplex mode in the following way, but PDM full-duplex is not supported because due to different PDM TX and RX clocks. Note that one handle can only stand for one channel. Therefore, it is still necessary to configure the slot and clock for both TX and RX channels one by one. Here is an example of how to allocate a pair of full-duplex channels: #include "driver/i2s_std.h" #include "driver/gpio.h" i2s_chan_handle_t tx_handle; i2s_chan_handle_t rx_handle; /* Allocate a pair of I2S channel */ i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_AUTO, I2S_ROLE_MASTER); /* Allocate for TX and RX channel at the same time, then they will work in full-duplex mode */ i2s_new_channel(&chan_cfg, &tx_handle, &rx_handle); /* Set the configurations for BOTH TWO channels, since TX and RX channel have to be same in full-duplex mode */ i2s_std_config_t std_cfg = { .clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(32000), .slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_STEREO), .gpio_cfg = { .mclk = I2S_GPIO_UNUSED, .bclk = GPIO_NUM_4, .ws = GPIO_NUM_5, .dout = GPIO_NUM_18, .din = GPIO_NUM_19, .invert_flags = { .mclk_inv = false, .bclk_inv = false, .ws_inv = false, }, }, }; i2s_channel_init_std_mode(tx_handle, &std_cfg); i2s_channel_init_std_mode(rx_handle, &std_cfg); i2s_channel_enable(tx_handle); i2s_channel_enable(rx_handle); ... Simplex Mode To allocate a channel handle in simplex mode, i2s_new_channel() should be called for each channel. The clock and GPIO pins of TX/RX channel on ESP32 are not independent, so the TX and RX channel cannot coexist on the same I2S port in simplex mode. #include "driver/i2s_std.h" #include "driver/gpio.h" i2s_chan_handle_t tx_handle; i2s_chan_handle_t rx_handle; i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_AUTO, I2S_ROLE_MASTER); i2s_new_channel(&chan_cfg, &tx_handle, NULL); i2s_std_config_t std_tx_cfg = { .clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(48000), .slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_STEREO), .gpio_cfg = { .mclk = GPIO_NUM_0, .bclk = GPIO_NUM_4, .ws = GPIO_NUM_5, .dout = GPIO_NUM_18, .din = I2S_GPIO_UNUSED, .invert_flags = { .mclk_inv = false, .bclk_inv = false, .ws_inv = false, }, }, }; /* Initialize the channel */ i2s_channel_init_std_mode(tx_handle, &std_tx_cfg); i2s_channel_enable(tx_handle); /* RX channel will be registered on another I2S, if no other available I2S unit found * it will return ESP_ERR_NOT_FOUND */ i2s_new_channel(&chan_cfg, NULL, &rx_handle); i2s_std_config_t std_rx_cfg = { .clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(16000), .slot_cfg = I2S_STD_MSB_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_STEREO), .gpio_cfg = { .mclk = I2S_GPIO_UNUSED, .bclk = GPIO_NUM_6, .ws = GPIO_NUM_7, .dout = I2S_GPIO_UNUSED, .din = GPIO_NUM_19, .invert_flags = { .mclk_inv = false, .bclk_inv = false, .ws_inv = false, }, }, }; i2s_channel_init_std_mode(rx_handle, &std_rx_cfg); i2s_channel_enable(rx_handle); Application Notes How to Prevent Data Lost For applications that need a high frequency sample rate, the massive data throughput may cause data lost. Users can receive data lost event by registering the ISR callback function to receive the event queue: static IRAM_ATTR bool i2s_rx_queue_overflow_callback(i2s_chan_handle_t handle, i2s_event_data_t *event, void *user_ctx) { // handle RX queue overflow event ... return false; } i2s_event_callbacks_t cbs = { .on_recv = NULL, .on_recv_q_ovf = i2s_rx_queue_overflow_callback, .on_sent = NULL, .on_send_q_ovf = NULL, }; TEST_ESP_OK(i2s_channel_register_event_callback(rx_handle, &cbs, NULL)); Please follow these steps to prevent data lost: Determine the interrupt interval. Generally, when data lost happens, the bigger the interval, the better, which helps to reduce the interrupt times. This means dma_frame_numshould be as big as possible while the DMA buffer size is below the maximum value of 4092. The relationships are: interrupt_interval(unit: sec) = dma_frame_num / sample_rate dma_buffer_size = dma_frame_num * slot_num * data_bit_width / 8 <= 4092 Determine dma_desc_num. dma_desc_numis decided by the maximum time of i2s_channel_readpolling cycle. All the received data is supposed to be stored between two i2s_channel_read. This cycle can be measured by a timer or an outputting GPIO signal. The relationship is: dma_desc_num > polling_cycle / interrupt_interval Determine the receiving buffer size. The receiving buffer offered by users in i2s_channel_readshould be able to take all the data in all DMA buffers, which means that it should be larger than the total size of all the DMA buffers: recv_buffer_size > dma_desc_num * dma_buffer_size For example, if there is an I2S application, and the known values are: sample_rate = 144000 Hz data_bit_width = 32 bits slot_num = 2 polling_cycle = 10 ms Then the parameters dma_frame_num, dma_desc_num, and recv_buf_size can be calculated as follows: dma_frame_num * slot_num * data_bit_width / 8 = dma_buffer_size <= 4092 dma_frame_num <= 511 interrupt_interval = dma_frame_num / sample_rate = 511 / 144000 = 0.003549 s = 3.549 ms dma_desc_num > polling_cycle / interrupt_interval = cell(10 / 3.549) = cell(2.818) = 3 recv_buffer_size > dma_desc_num * dma_buffer_size = 3 * 4092 = 12276 bytes API Reference Standard Mode Header File This header file can be included with: #include "driver/i2s_std.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t i2s_channel_init_std_mode(i2s_chan_handle_t handle, const i2s_std_config_t *std_cfg) Initialize I2S channel to standard mode. Note Only allowed to be called when the channel state is REGISTERED, (i.e., channel has been allocated, but not initialized) and the state will be updated to READY if initialization success, otherwise the state will return to REGISTERED. - Parameters handle -- [in] I2S channel handler std_cfg -- [in] Configurations for standard mode, including clock, slot and GPIO The clock configuration can be generated by the helper macro I2S_STD_CLK_DEFAULT_CONFIGThe slot configuration can be generated by the helper macro I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG, I2S_STD_PCM_SLOT_DEFAULT_CONFIGor I2S_STD_MSB_SLOT_DEFAULT_CONFIG - - Returns ESP_OK Initialize successfully ESP_ERR_NO_MEM No memory for storing the channel information ESP_ERR_INVALID_ARG NULL pointer or invalid configuration ESP_ERR_INVALID_STATE This channel is not registered - - esp_err_t i2s_channel_reconfig_std_clock(i2s_chan_handle_t handle, const i2s_std_clk_config_t *clk_cfg) Reconfigure the I2S clock for standard mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disableshould be called before calling this function if I2S has started. Note The input channel handle has to be initialized to standard mode, i.e., i2s_channel_init_std_modehas been called before reconfiguring - Parameters handle -- [in] I2S channel handler clk_cfg -- [in] Standard mode clock configuration, can be generated by I2S_STD_CLK_DEFAULT_CONFIG - - Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped - - esp_err_t i2s_channel_reconfig_std_slot(i2s_chan_handle_t handle, const i2s_std_slot_config_t *slot_cfg) Reconfigure the I2S slot for standard mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disableshould be called before calling this function if I2S has started. Note The input channel handle has to be initialized to standard mode, i.e., i2s_channel_init_std_modehas been called before reconfiguring - Parameters handle -- [in] I2S channel handler slot_cfg -- [in] Standard mode slot configuration, can be generated by I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG, I2S_STD_PCM_SLOT_DEFAULT_CONFIGand I2S_STD_MSB_SLOT_DEFAULT_CONFIG. - - Returns ESP_OK Set clock successfully ESP_ERR_NO_MEM No memory for DMA buffer ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped - - esp_err_t i2s_channel_reconfig_std_gpio(i2s_chan_handle_t handle, const i2s_std_gpio_config_t *gpio_cfg) Reconfigure the I2S GPIO for standard mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disableshould be called before calling this function if I2S has started. Note The input channel handle has to be initialized to standard mode, i.e., i2s_channel_init_std_modehas been called before reconfiguring - Parameters handle -- [in] I2S channel handler gpio_cfg -- [in] Standard mode GPIO configuration, specified by user - - Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped - Structures - struct i2s_std_slot_config_t I2S slot configuration for standard mode. Public Members - i2s_data_bit_width_t data_bit_width I2S sample data bit width (valid data bits per sample) - i2s_slot_bit_width_t slot_bit_width I2S slot bit width (total bits per slot) - i2s_slot_mode_t slot_mode Set mono or stereo mode with I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO In TX direction, mono means the written buffer contains only one slot data and stereo means the written buffer contains both left and right data - i2s_std_slot_mask_t slot_mask Select the left, right or both slot - uint32_t ws_width WS signal width (i.e. the number of BCLK ticks that WS signal is high) - bool ws_pol WS signal polarity, set true to enable high lever first - bool bit_shift Set to enable bit shift in Philips mode - bool msb_right Set to place right channel data at the MSB in the FIFO - i2s_data_bit_width_t data_bit_width - struct i2s_std_clk_config_t I2S clock configuration for standard mode. Public Members - uint32_t sample_rate_hz I2S sample rate - i2s_clock_src_t clk_src Choose clock source, see soc_periph_i2s_clk_src_tfor the supported clock sources. selected I2S_CLK_SRC_EXTERNAL(if supports) to enable the external source clock input via MCLK pin, - i2s_mclk_multiple_t mclk_multiple The multiple of MCLK to the sample rate Default is 256 in the helper macro, it can satisfy most of cases, but please set this field a multiple of 3(like 384) when using 24-bit data width, otherwise the sample rate might be inaccurate - uint32_t sample_rate_hz - struct i2s_std_gpio_config_t I2S standard mode GPIO pins configuration. Public Members - gpio_num_t mclk MCK pin, output by default, input if the clock source is selected to I2S_CLK_SRC_EXTERNAL - gpio_num_t bclk BCK pin, input in slave role, output in master role - gpio_num_t ws WS pin, input in slave role, output in master role - gpio_num_t dout DATA pin, output - gpio_num_t din DATA pin, input - uint32_t mclk_inv Set 1 to invert the MCLK input/output - uint32_t bclk_inv Set 1 to invert the BCLK input/output - uint32_t ws_inv Set 1 to invert the WS input/output - struct i2s_std_gpio_config_t::[anonymous] invert_flags GPIO pin invert flags - gpio_num_t mclk - struct i2s_std_config_t I2S standard mode major configuration that including clock/slot/GPIO configuration. Public Members - i2s_std_clk_config_t clk_cfg Standard mode clock configuration, can be generated by macro I2S_STD_CLK_DEFAULT_CONFIG - i2s_std_slot_config_t slot_cfg Standard mode slot configuration, can be generated by macros I2S_STD_[mode]_SLOT_DEFAULT_CONFIG, [mode] can be replaced with PHILIPS/MSB/PCM - i2s_std_gpio_config_t gpio_cfg Standard mode GPIO configuration, specified by user - i2s_std_clk_config_t clk_cfg Macros - I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(bits_per_sample, mono_or_stereo) Philips format in 2 slots. This file is specified for I2S standard communication mode Features: Philips/MSB/PCM are supported in standard mode Fixed to 2 slots - Parameters bits_per_sample -- I2S data bit width mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO - - - I2S_STD_PCM_SLOT_DEFAULT_CONFIG(bits_per_sample, mono_or_stereo) PCM(short) format in 2 slots. Note PCM(long) is same as Philips in 2 slots - Parameters bits_per_sample -- I2S data bit width mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO - - I2S_STD_MSB_SLOT_DEFAULT_CONFIG(bits_per_sample, mono_or_stereo) MSB format in 2 slots. - Parameters bits_per_sample -- I2S data bit width mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO - - I2S_STD_CLK_DEFAULT_CONFIG(rate) I2S default standard clock configuration. Note Please set the mclk_multiple to I2S_MCLK_MULTIPLE_384 while using 24 bits data width Otherwise the sample rate might be imprecise since the BCLK division is not a integer - Parameters rate -- sample rate - PDM Mode Header File This header file can be included with: #include "driver/i2s_pdm.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t i2s_channel_init_pdm_rx_mode(i2s_chan_handle_t handle, const i2s_pdm_rx_config_t *pdm_rx_cfg) Initialize I2S channel to PDM RX mode. Note Only allowed to be called when the channel state is REGISTERED, (i.e., channel has been allocated, but not initialized) and the state will be updated to READY if initialization success, otherwise the state will return to REGISTERED. - Parameters handle -- [in] I2S RX channel handler pdm_rx_cfg -- [in] Configurations for PDM RX mode, including clock, slot and GPIO The clock configuration can be generated by the helper macro I2S_PDM_RX_CLK_DEFAULT_CONFIGThe slot configuration can be generated by the helper macro I2S_PDM_RX_SLOT_DEFAULT_CONFIG - - Returns ESP_OK Initialize successfully ESP_ERR_NO_MEM No memory for storing the channel information ESP_ERR_INVALID_ARG NULL pointer or invalid configuration ESP_ERR_INVALID_STATE This channel is not registered - - esp_err_t i2s_channel_reconfig_pdm_rx_clock(i2s_chan_handle_t handle, const i2s_pdm_rx_clk_config_t *clk_cfg) Reconfigure the I2S clock for PDM RX mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disableshould be called before calling this function if I2S has started. Note The input channel handle has to be initialized to PDM RX mode, i.e., i2s_channel_init_pdm_rx_modehas been called before reconfiguring - Parameters handle -- [in] I2S RX channel handler clk_cfg -- [in] PDM RX mode clock configuration, can be generated by I2S_PDM_RX_CLK_DEFAULT_CONFIG - - Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped - - esp_err_t i2s_channel_reconfig_pdm_rx_slot(i2s_chan_handle_t handle, const i2s_pdm_rx_slot_config_t *slot_cfg) Reconfigure the I2S slot for PDM RX mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disableshould be called before calling this function if I2S has started. Note The input channel handle has to be initialized to PDM RX mode, i.e., i2s_channel_init_pdm_rx_modehas been called before reconfiguring - Parameters handle -- [in] I2S RX channel handler slot_cfg -- [in] PDM RX mode slot configuration, can be generated by I2S_PDM_RX_SLOT_DEFAULT_CONFIG - - Returns ESP_OK Set clock successfully ESP_ERR_NO_MEM No memory for DMA buffer ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped - - esp_err_t i2s_channel_reconfig_pdm_rx_gpio(i2s_chan_handle_t handle, const i2s_pdm_rx_gpio_config_t *gpio_cfg) Reconfigure the I2S GPIO for PDM RX mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disableshould be called before calling this function if I2S has started. Note The input channel handle has to be initialized to PDM RX mode, i.e., i2s_channel_init_pdm_rx_modehas been called before reconfiguring - Parameters handle -- [in] I2S RX channel handler gpio_cfg -- [in] PDM RX mode GPIO configuration, specified by user - - Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped - - esp_err_t i2s_channel_init_pdm_tx_mode(i2s_chan_handle_t handle, const i2s_pdm_tx_config_t *pdm_tx_cfg) Initialize I2S channel to PDM TX mode. Note Only allowed to be called when the channel state is REGISTERED, (i.e., channel has been allocated, but not initialized) and the state will be updated to READY if initialization success, otherwise the state will return to REGISTERED. - Parameters handle -- [in] I2S TX channel handler pdm_tx_cfg -- [in] Configurations for PDM TX mode, including clock, slot and GPIO The clock configuration can be generated by the helper macro I2S_PDM_TX_CLK_DEFAULT_CONFIGThe slot configuration can be generated by the helper macro I2S_PDM_TX_SLOT_DEFAULT_CONFIG - - Returns ESP_OK Initialize successfully ESP_ERR_NO_MEM No memory for storing the channel information ESP_ERR_INVALID_ARG NULL pointer or invalid configuration ESP_ERR_INVALID_STATE This channel is not registered - - esp_err_t i2s_channel_reconfig_pdm_tx_clock(i2s_chan_handle_t handle, const i2s_pdm_tx_clk_config_t *clk_cfg) Reconfigure the I2S clock for PDM TX mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disableshould be called before calling this function if I2S has started. Note The input channel handle has to be initialized to PDM TX mode, i.e., i2s_channel_init_pdm_tx_modehas been called before reconfiguring - Parameters handle -- [in] I2S TX channel handler clk_cfg -- [in] PDM TX mode clock configuration, can be generated by I2S_PDM_TX_CLK_DEFAULT_CONFIG - - Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped - - esp_err_t i2s_channel_reconfig_pdm_tx_slot(i2s_chan_handle_t handle, const i2s_pdm_tx_slot_config_t *slot_cfg) Reconfigure the I2S slot for PDM TX mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disableshould be called before calling this function if I2S has started. Note The input channel handle has to be initialized to PDM TX mode, i.e., i2s_channel_init_pdm_tx_modehas been called before reconfiguring - Parameters handle -- [in] I2S TX channel handler slot_cfg -- [in] PDM TX mode slot configuration, can be generated by I2S_PDM_TX_SLOT_DEFAULT_CONFIG - - Returns ESP_OK Set clock successfully ESP_ERR_NO_MEM No memory for DMA buffer ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped - - esp_err_t i2s_channel_reconfig_pdm_tx_gpio(i2s_chan_handle_t handle, const i2s_pdm_tx_gpio_config_t *gpio_cfg) Reconfigure the I2S GPIO for PDM TX mode. Note Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state. i2s_channel_disableshould be called before calling this function if I2S has started. Note The input channel handle has to be initialized to PDM TX mode, i.e., i2s_channel_init_pdm_tx_modehas been called before reconfiguring - Parameters handle -- [in] I2S TX channel handler gpio_cfg -- [in] PDM TX mode GPIO configuration, specified by user - - Returns ESP_OK Set clock successfully ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode ESP_ERR_INVALID_STATE This channel is not initialized or not stopped - Structures - struct i2s_pdm_rx_slot_config_t I2S slot configuration for PDM RX mode. Public Members - i2s_data_bit_width_t data_bit_width I2S sample data bit width (valid data bits per sample), only support 16 bits for PDM mode - i2s_slot_bit_width_t slot_bit_width I2S slot bit width (total bits per slot) , only support 16 bits for PDM mode - i2s_slot_mode_t slot_mode Set mono or stereo mode with I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO - i2s_pdm_slot_mask_t slot_mask Choose the slots to activate - i2s_data_bit_width_t data_bit_width - struct i2s_pdm_rx_clk_config_t I2S clock configuration for PDM RX mode. Public Members - uint32_t sample_rate_hz I2S sample rate - i2s_clock_src_t clk_src Choose clock source - i2s_mclk_multiple_t mclk_multiple The multiple of MCLK to the sample rate - i2s_pdm_dsr_t dn_sample_mode Down-sampling rate mode - uint32_t bclk_div The division from MCLK to BCLK. The typical and minimum value is I2S_PDM_RX_BCLK_DIV_MIN. It will be set to I2S_PDM_RX_BCLK_DIV_MIN by default if it is smaller than I2S_PDM_RX_BCLK_DIV_MIN - uint32_t sample_rate_hz - struct i2s_pdm_rx_gpio_config_t I2S PDM TX mode GPIO pins configuration. Public Members - gpio_num_t clk PDM clk pin, output - gpio_num_t din DATA pin 0, input - gpio_num_t dins[(1U)] DATA pins, input, only take effect when corresponding I2S_PDM_RX_LINEx_SLOT_xxx is enabled in i2s_pdm_rx_slot_config_t::slot_mask - uint32_t clk_inv Set 1 to invert the clk output - struct i2s_pdm_rx_gpio_config_t::[anonymous] invert_flags GPIO pin invert flags - gpio_num_t clk - struct i2s_pdm_rx_config_t I2S PDM RX mode major configuration that including clock/slot/GPIO configuration. Public Members - i2s_pdm_rx_clk_config_t clk_cfg PDM RX clock configurations, can be generated by macro I2S_PDM_RX_CLK_DEFAULT_CONFIG - i2s_pdm_rx_slot_config_t slot_cfg PDM RX slot configurations, can be generated by macro I2S_PDM_RX_SLOT_DEFAULT_CONFIG - i2s_pdm_rx_gpio_config_t gpio_cfg PDM RX slot configurations, specified by user - i2s_pdm_rx_clk_config_t clk_cfg - struct i2s_pdm_tx_slot_config_t I2S slot configuration for PDM TX mode. Public Members - i2s_data_bit_width_t data_bit_width I2S sample data bit width (valid data bits per sample), only support 16 bits for PDM mode - i2s_slot_bit_width_t slot_bit_width I2S slot bit width (total bits per slot), only support 16 bits for PDM mode - i2s_slot_mode_t slot_mode Set mono or stereo mode with I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO For PDM TX mode, mono means the data buffer only contains one slot data, Stereo means the data buffer contains two slots data - i2s_pdm_slot_mask_t slot_mask Slot mask to choose left or right slot - uint32_t sd_prescale Sigma-delta filter prescale - i2s_pdm_sig_scale_t sd_scale Sigma-delta filter scaling value - i2s_pdm_sig_scale_t hp_scale High pass filter scaling value - i2s_pdm_sig_scale_t lp_scale Low pass filter scaling value - i2s_pdm_sig_scale_t sinc_scale Sinc filter scaling value - i2s_data_bit_width_t data_bit_width - struct i2s_pdm_tx_clk_config_t I2S clock configuration for PDM TX mode. Public Members - uint32_t sample_rate_hz I2S sample rate, not suggest to exceed 48000 Hz, otherwise more glitches and noise may appear - i2s_clock_src_t clk_src Choose clock source - i2s_mclk_multiple_t mclk_multiple The multiple of MCLK to the sample rate - uint32_t up_sample_fp Up-sampling param fp - uint32_t up_sample_fs Up-sampling param fs, not allowed to be greater than 480 - uint32_t bclk_div The division from MCLK to BCLK. The minimum value is I2S_PDM_TX_BCLK_DIV_MIN. It will be set to I2S_PDM_TX_BCLK_DIV_MIN by default if it is smaller than I2S_PDM_TX_BCLK_DIV_MIN - uint32_t sample_rate_hz - struct i2s_pdm_tx_gpio_config_t I2S PDM TX mode GPIO pins configuration. Public Members - gpio_num_t clk PDM clk pin, output - gpio_num_t dout DATA pin, output - uint32_t clk_inv Set 1 to invert the clk output - struct i2s_pdm_tx_gpio_config_t::[anonymous] invert_flags GPIO pin invert flags - gpio_num_t clk - struct i2s_pdm_tx_config_t I2S PDM TX mode major configuration that including clock/slot/GPIO configuration. Public Members - i2s_pdm_tx_clk_config_t clk_cfg PDM TX clock configurations, can be generated by macro I2S_PDM_TX_CLK_DEFAULT_CONFIG - i2s_pdm_tx_slot_config_t slot_cfg PDM TX slot configurations, can be generated by macro I2S_PDM_TX_SLOT_DEFAULT_CONFIG - i2s_pdm_tx_gpio_config_t gpio_cfg PDM TX GPIO configurations, specified by user - i2s_pdm_tx_clk_config_t clk_cfg Macros - I2S_PDM_RX_SLOT_DEFAULT_CONFIG(bits_per_sample, mono_or_stereo) PDM format in 2 slots(RX) This file is specified for I2S PDM communication mode Features: Only support PDM TX/RX mode Fixed to 2 slots Data bit width only support 16 bits - Parameters bits_per_sample -- I2S data bit width, only support 16 bits for PDM mode mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO - - - I2S_PDM_RX_CLK_DEFAULT_CONFIG(rate) I2S default PDM RX clock configuration. - Parameters rate -- sample rate - - I2S_PDM_TX_SLOT_DEFAULT_CONFIG(bits_per_sample, mono_or_stereo) PDM style in 2 slots(TX) for codec line mode. - Parameters bits_per_sample -- I2S data bit width, only support 16 bits for PDM mode mono_or_stereo -- I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO - - I2S_PDM_TX_CLK_DEFAULT_CONFIG(rate) I2S default PDM TX clock configuration for codec line mode. Note TX PDM can only be set to the following two up-sampling rate configurations: 1: fp = 960, fs = sample_rate_hz / 100, in this case, Fpdm = 128*48000 2: fp = 960, fs = 480, in this case, Fpdm = 128*Fpcm = 128*sample_rate_hz If the PDM receiver do not care the PDM serial clock, it's recommended set Fpdm = 128*48000. Otherwise, the second configuration should be adopted. - Parameters rate -- sample rate (not suggest to exceed 48000 Hz, otherwise more glitches and noise may appear) - - I2S_PDM_TX_CLK_DAC_DEFAULT_CONFIG(rate) I2S default PDM TX clock configuration for DAC line mode. Note TX PDM can only be set to the following two up-sampling rate configurations: 1: fp = 960, fs = sample_rate_hz / 100, in this case, Fpdm = 128*48000 2: fp = 960, fs = 480, in this case, Fpdm = 128*Fpcm = 128*sample_rate_hz If the PDM receiver do not care the PDM serial clock, it's recommended set Fpdm = 128*48000. Otherwise, the second configuration should be adopted. Note The noise might be different with different configurations, this macro provides a set of configurations that have relatively high SNR (Signal Noise Ratio), you can also adjust them to fit your case. - Parameters rate -- sample rate (not suggest to exceed 48000 Hz, otherwise more glitches and noise may appear) - I2S Driver Header File This header file can be included with: #include "driver/i2s_common.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t i2s_new_channel(const i2s_chan_config_t *chan_cfg, i2s_chan_handle_t *ret_tx_handle, i2s_chan_handle_t *ret_rx_handle) Allocate new I2S channel(s) Note The new created I2S channel handle will be REGISTERED state after it is allocated successfully. Note When the port id in channel configuration is I2S_NUM_AUTO, driver will allocate I2S port automatically on one of the I2S controller, otherwise driver will try to allocate the new channel on the selected port. Note If both tx_handle and rx_handle are not NULL, it means this I2S controller will work at full-duplex mode, the RX and TX channels will be allocated on a same I2S port in this case. Note that some configurations of TX/RX channel are shared on ESP32 and ESP32S2, so please make sure they are working at same condition and under same status(start/stop). Currently, full-duplex mode can't guarantee TX/RX channels write/read synchronously, they can only share the clock signals for now. Note If tx_handle OR rx_handle is NULL, it means this I2S controller will work at simplex mode. For ESP32 and ESP32S2, the whole I2S controller (i.e. both RX and TX channel) will be occupied, even if only one of RX or TX channel is registered. For the other targets, another channel on this controller will still available. - Parameters chan_cfg -- [in] I2S controller channel configurations ret_tx_handle -- [out] I2S channel handler used for managing the sending channel(optional) ret_rx_handle -- [out] I2S channel handler used for managing the receiving channel(optional) - - Returns ESP_OK Allocate new channel(s) success ESP_ERR_NOT_SUPPORTED The communication mode is not supported on the current chip ESP_ERR_INVALID_ARG NULL pointer or illegal parameter in i2s_chan_config_t ESP_ERR_NOT_FOUND No available I2S channel found - - esp_err_t i2s_del_channel(i2s_chan_handle_t handle) Delete the I2S channel. Note Only allowed to be called when the I2S channel is at REGISTERED or READY state (i.e., it should stop before deleting it). Note Resource will be free automatically if all channels in one port are deleted - Parameters handle -- [in] I2S channel handler ESP_OK Delete successfully ESP_ERR_INVALID_ARG NULL pointer - - esp_err_t i2s_channel_get_info(i2s_chan_handle_t handle, i2s_chan_info_t *chan_info) Get I2S channel information. - Parameters handle -- [in] I2S channel handler chan_info -- [out] I2S channel basic information - - Returns ESP_OK Get I2S channel information success ESP_ERR_NOT_FOUND The input handle doesn't match any registered I2S channels, it may not an I2S channel handle or not available any more ESP_ERR_INVALID_ARG The input handle or chan_info pointer is NULL - - esp_err_t i2s_channel_enable(i2s_chan_handle_t handle) Enable the I2S channel. Note Only allowed to be called when the channel state is READY, (i.e., channel has been initialized, but not started) the channel will enter RUNNING state once it is enabled successfully. Note Enable the channel can start the I2S communication on hardware. It will start outputting BCLK and WS signal. For MCLK signal, it will start to output when initialization is finished - Parameters handle -- [in] I2S channel handler ESP_OK Start successfully ESP_ERR_INVALID_ARG NULL pointer ESP_ERR_INVALID_STATE This channel has not initialized or already started - - esp_err_t i2s_channel_disable(i2s_chan_handle_t handle) Disable the I2S channel. Note Only allowed to be called when the channel state is RUNNING, (i.e., channel has been started) the channel will enter READY state once it is disabled successfully. Note Disable the channel can stop the I2S communication on hardware. It will stop BCLK and WS signal but not MCLK signal - Parameters handle -- [in] I2S channel handler - Returns ESP_OK Stop successfully ESP_ERR_INVALID_ARG NULL pointer ESP_ERR_INVALID_STATE This channel has not stated - - esp_err_t i2s_channel_preload_data(i2s_chan_handle_t tx_handle, const void *src, size_t size, size_t *bytes_loaded) Preload the data into TX DMA buffer. Note Only allowed to be called when the channel state is READY, (i.e., channel has been initialized, but not started) Note As the initial DMA buffer has no data inside, it will transmit the empty buffer after enabled the channel, this function is used to preload the data into the DMA buffer, so that the valid data can be transmitted immediately after the channel is enabled. Note This function can be called multiple times before enabling the channel, the buffer that loaded later will be concatenated behind the former loaded buffer. But when all the DMA buffers have been loaded, no more data can be preload then, please check the bytes_loadedparameter to see how many bytes are loaded successfully, when the bytes_loadedis smaller than the size, it means the DMA buffers are full. - Parameters tx_handle -- [in] I2S TX channel handler src -- [in] The pointer of the source buffer to be loaded size -- [in] The source buffer size bytes_loaded -- [out] The bytes that successfully been loaded into the TX DMA buffer - - Returns ESP_OK Load data successful ESP_ERR_INVALID_ARG NULL pointer or not TX direction ESP_ERR_INVALID_STATE This channel has not stated - - esp_err_t i2s_channel_write(i2s_chan_handle_t handle, const void *src, size_t size, size_t *bytes_written, uint32_t timeout_ms) I2S write data. Note Only allowed to be called when the channel state is RUNNING, (i.e., TX channel has been started and is not writing now) but the RUNNING only stands for the software state, it doesn't mean there is no the signal transporting on line. - Parameters handle -- [in] I2S channel handler src -- [in] The pointer of sent data buffer size -- [in] Max data buffer length bytes_written -- [out] Byte number that actually be sent, can be NULL if not needed timeout_ms -- [in] Max block time - - Returns ESP_OK Write successfully ESP_ERR_INVALID_ARG NULL pointer or this handle is not TX handle ESP_ERR_TIMEOUT Writing timeout, no writing event received from ISR within ticks_to_wait ESP_ERR_INVALID_STATE I2S is not ready to write - - esp_err_t i2s_channel_read(i2s_chan_handle_t handle, void *dest, size_t size, size_t *bytes_read, uint32_t timeout_ms) I2S read data. Note Only allowed to be called when the channel state is RUNNING but the RUNNING only stands for the software state, it doesn't mean there is no the signal transporting on line. - Parameters handle -- [in] I2S channel handler dest -- [in] The pointer of receiving data buffer size -- [in] Max data buffer length bytes_read -- [out] Byte number that actually be read, can be NULL if not needed timeout_ms -- [in] Max block time - - Returns ESP_OK Read successfully ESP_ERR_INVALID_ARG NULL pointer or this handle is not RX handle ESP_ERR_TIMEOUT Reading timeout, no reading event received from ISR within ticks_to_wait ESP_ERR_INVALID_STATE I2S is not ready to read - - esp_err_t i2s_channel_register_event_callback(i2s_chan_handle_t handle, const i2s_event_callbacks_t *callbacks, void *user_data) Set event callbacks for I2S channel. Note Only allowed to be called when the channel state is REGISTERED / READY, (i.e., before channel starts) Note User can deregister a previously registered callback by calling this function and setting the callback member in the callbacksstructure to NULL. Note When CONFIG_I2S_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. The user_datashould also reside in SRAM or internal RAM as well. - Parameters handle -- [in] I2S channel handler callbacks -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly - - Returns ESP_OK Set event callbacks successfully ESP_ERR_INVALID_ARG Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE Set event callbacks failed because the current channel state is not REGISTERED or READY - Structures - struct i2s_event_callbacks_t Group of I2S callbacks. Note The callbacks are all running under ISR environment Note When CONFIG_I2S_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. Public Members - i2s_isr_callback_t on_recv Callback of data received event, only for RX channel The event data includes DMA buffer address and size that just finished receiving data - i2s_isr_callback_t on_recv_q_ovf Callback of receiving queue overflowed event, only for RX channel The event data includes buffer size that has been overwritten - i2s_isr_callback_t on_sent Callback of data sent event, only for TX channel The event data includes DMA buffer address and size that just finished sending data - i2s_isr_callback_t on_send_q_ovf Callback of sending queue overflowed event, only for TX channel The event data includes buffer size that has been overwritten - i2s_isr_callback_t on_recv - struct i2s_chan_config_t I2S controller channel configuration. Public Members - i2s_port_t id I2S port id - i2s_role_t role I2S role, I2S_ROLE_MASTER or I2S_ROLE_SLAVE - uint32_t dma_desc_num I2S DMA buffer number, it is also the number of DMA descriptor - uint32_t dma_frame_num I2S frame number in one DMA buffer. One frame means one-time sample data in all slots, it should be the multiple of 3when the data bit width is 24. - bool auto_clear Set to auto clear DMA TX buffer, I2S will always send zero automatically if no data to send - int intr_priority I2S interrupt priority, range [0, 7], if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) - i2s_port_t id - struct i2s_chan_info_t I2S channel information. Public Members - i2s_port_t id I2S port id - i2s_role_t role I2S role, I2S_ROLE_MASTER or I2S_ROLE_SLAVE - i2s_comm_mode_t mode I2S channel communication mode - i2s_chan_handle_t pair_chan I2S pair channel handle in duplex mode, always NULL in simplex mode - i2s_port_t id Macros - I2S_CHANNEL_DEFAULT_CONFIG(i2s_num, i2s_role) get default I2S property - I2S_GPIO_UNUSED Used in i2s_gpio_config_t for signals which are not used I2S Types Header File This header file can be included with: #include "driver/i2s_types.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Structures - struct i2s_event_data_t Event structure used in I2S event queue. Public Members - void *data The pointer of DMA buffer that just finished sending or receiving for on_recvand on_sentcallback NULL for on_recv_q_ovfand on_send_q_ovfcallback - size_t size The buffer size of DMA buffer when success to send or receive, also the buffer size that dropped when queue overflow. It is related to the dma_frame_num and data_bit_width, typically it is fixed when data_bit_width is not changed. - void *data Type Definitions - typedef struct i2s_channel_obj_t *i2s_chan_handle_t I2S channel object handle, the control unit of the I2S driver - typedef bool (*i2s_isr_callback_t)(i2s_chan_handle_t handle, i2s_event_data_t *event, void *user_ctx) I2S event callback. - Param handle [in] I2S channel handle, created from i2s_new_channel() - Param event [in] I2S event data - Param user_ctx [in] User registered context, passed from i2s_channel_register_event_callback() - Return Whether a high priority task has been waken up by this callback function Enumerations - enum i2s_port_t I2S controller port number, the max port number is (SOC_I2S_NUM -1). Values: - enumerator I2S_NUM_0 I2S controller port 0 - enumerator I2S_NUM_1 I2S controller port 1 - enumerator I2S_NUM_AUTO Select whichever port is available - enumerator I2S_NUM_0 - enum i2s_comm_mode_t I2S controller communication mode. Values: - enumerator I2S_COMM_MODE_STD I2S controller using standard communication mode, support Philips/MSB/PCM format - enumerator I2S_COMM_MODE_PDM I2S controller using PDM communication mode, support PDM output or input - enumerator I2S_COMM_MODE_NONE Unspecified I2S controller mode - enumerator I2S_COMM_MODE_STD - enum i2s_mclk_multiple_t The multiple of MCLK to sample rate. Values: - enumerator I2S_MCLK_MULTIPLE_128 MCLK = sample_rate * 128 - enumerator I2S_MCLK_MULTIPLE_256 MCLK = sample_rate * 256 - enumerator I2S_MCLK_MULTIPLE_384 MCLK = sample_rate * 384 - enumerator I2S_MCLK_MULTIPLE_512 MCLK = sample_rate * 512 - enumerator I2S_MCLK_MULTIPLE_128 Header File This header file can be included with: #include "hal/i2s_types.h" Type Definitions - typedef soc_periph_i2s_clk_src_t i2s_clock_src_t I2S clock source Enumerations - enum i2s_slot_mode_t I2S channel slot mode. Values: - enumerator I2S_SLOT_MODE_MONO I2S channel slot format mono, transmit same data in all slots for tx mode, only receive the data in the first slots for rx mode. - enumerator I2S_SLOT_MODE_STEREO I2S channel slot format stereo, transmit different data in different slots for tx mode, receive the data in all slots for rx mode. - enumerator I2S_SLOT_MODE_MONO - enum i2s_dir_t I2S channel direction. Values: - enumerator I2S_DIR_RX I2S channel direction RX - enumerator I2S_DIR_TX I2S channel direction TX - enumerator I2S_DIR_RX - enum i2s_role_t I2S controller role. Values: - enumerator I2S_ROLE_MASTER I2S controller master role, bclk and ws signal will be set to output - enumerator I2S_ROLE_SLAVE I2S controller slave role, bclk and ws signal will be set to input - enumerator I2S_ROLE_MASTER - enum i2s_data_bit_width_t Available data bit width in one slot. Values: - enumerator I2S_DATA_BIT_WIDTH_8BIT I2S channel data bit-width: 8 - enumerator I2S_DATA_BIT_WIDTH_16BIT I2S channel data bit-width: 16 - enumerator I2S_DATA_BIT_WIDTH_24BIT I2S channel data bit-width: 24 - enumerator I2S_DATA_BIT_WIDTH_32BIT I2S channel data bit-width: 32 - enumerator I2S_DATA_BIT_WIDTH_8BIT - enum i2s_slot_bit_width_t Total slot bit width in one slot. Values: - enumerator I2S_SLOT_BIT_WIDTH_AUTO I2S channel slot bit-width equals to data bit-width - enumerator I2S_SLOT_BIT_WIDTH_8BIT I2S channel slot bit-width: 8 - enumerator I2S_SLOT_BIT_WIDTH_16BIT I2S channel slot bit-width: 16 - enumerator I2S_SLOT_BIT_WIDTH_24BIT I2S channel slot bit-width: 24 - enumerator I2S_SLOT_BIT_WIDTH_32BIT I2S channel slot bit-width: 32 - enumerator I2S_SLOT_BIT_WIDTH_AUTO - enum i2s_pdm_dsr_t I2S PDM RX down-sampling mode. Values: - enumerator I2S_PDM_DSR_8S downsampling number is 8 for PDM RX mode - enumerator I2S_PDM_DSR_16S downsampling number is 16 for PDM RX mode - enumerator I2S_PDM_DSR_MAX - enumerator I2S_PDM_DSR_8S - enum i2s_pdm_sig_scale_t pdm tx singnal scaling mode Values: - enumerator I2S_PDM_SIG_SCALING_DIV_2 I2S TX PDM signal scaling: /2 - enumerator I2S_PDM_SIG_SCALING_MUL_1 I2S TX PDM signal scaling: x1 - enumerator I2S_PDM_SIG_SCALING_MUL_2 I2S TX PDM signal scaling: x2 - enumerator I2S_PDM_SIG_SCALING_MUL_4 I2S TX PDM signal scaling: x4 - enumerator I2S_PDM_SIG_SCALING_DIV_2 - enum i2s_std_slot_mask_t I2S slot select in standard mode. Note It has different meanings in tx/rx/mono/stereo mode, and it may have differen behaviors on different targets For the details, please refer to the I2S API reference Values: - enumerator I2S_STD_SLOT_LEFT I2S transmits or receives left slot - enumerator I2S_STD_SLOT_RIGHT I2S transmits or receives right slot - enumerator I2S_STD_SLOT_BOTH I2S transmits or receives both left and right slot - enumerator I2S_STD_SLOT_LEFT - enum i2s_pdm_slot_mask_t I2S slot select in PDM mode. Values: - enumerator I2S_PDM_SLOT_RIGHT I2S PDM only transmits or receives the PDM device whose 'select' pin is pulled up - enumerator I2S_PDM_SLOT_LEFT I2S PDM only transmits or receives the PDM device whose 'select' pin is pulled down - enumerator I2S_PDM_SLOT_BOTH I2S PDM transmits or receives both two slots - enumerator I2S_PDM_SLOT_RIGHT
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/i2s.html
ESP-IDF Programming Guide v5.2.1 documentation
null
LCD
null
espressif.com
2016-01-01
8e895c98ae1fd0d9
null
null
LCD Introduction ESP chips can generate various kinds of timings that needed by common LCDs on the market, like SPI LCD, I80 LCD (a.k.a Intel 8080 parallel LCD), RGB/SRGB LCD, I2C LCD, etc. The esp_lcd component is officially to support those LCDs with a group of universal APIs across chips. Functional Overview In esp_lcd , an LCD panel is represented by esp_lcd_panel_handle_t , which plays the role of an abstract frame buffer, regardless of the frame memory is allocated inside ESP chip or in external LCD controller. Based on the location of the frame buffer and the hardware connection interface, the LCD panel drivers are mainly grouped into the following categories: Controller based LCD driver involves multiple steps to get a panel handle, like bus allocation, IO device registration and controller driver install. The frame buffer is located in the controller's internal GRAM (Graphical RAM). ESP-IDF provides only a limited number of LCD controller drivers out of the box (e.g., ST7789, SSD1306), More Controller Based LCD Drivers are maintained in the Espressif Component Registry. SPI Interfaced LCD describes the steps to install the SPI LCD IO driver and then get the panel handle. I2C Interfaced LCD describes the steps to install the I2C LCD IO driver and then get the panel handle. I80 Interfaced LCD describes the steps to install the I80 LCD IO driver and then get the panel handle. LCD Panel IO Operations - provides a set of APIs to operate the LCD panel, like turning on/off the display, setting the orientation, etc. These operations are common for either controller-based LCD panel driver or RGB LCD panel driver. SPI Interfaced LCD Create an SPI bus. Please refer to SPI Master API doc for more details. spi_bus_config_t buscfg = { .sclk_io_num = EXAMPLE_PIN_NUM_SCLK, .mosi_io_num = EXAMPLE_PIN_NUM_MOSI, .miso_io_num = EXAMPLE_PIN_NUM_MISO, .quadwp_io_num = -1, // Quad SPI LCD driver is not yet supported .quadhd_io_num = -1, // Quad SPI LCD driver is not yet supported .max_transfer_sz = EXAMPLE_LCD_H_RES * 80 * sizeof(uint16_t), // transfer 80 lines of pixels (assume pixel is RGB565) at most in one SPI transaction }; ESP_ERROR_CHECK(spi_bus_initialize(LCD_HOST, &buscfg, SPI_DMA_CH_AUTO)); // Enable the DMA feature Allocate an LCD IO device handle from the SPI bus. In this step, you need to provide the following information: esp_lcd_panel_io_spi_config_t::dc_gpio_num : Sets the gpio number for the DC signal line (some LCD calls this RS line). The LCD driver uses this GPIO to switch between sending command and sending data. esp_lcd_panel_io_spi_config_t::cs_gpio_num : Sets the gpio number for the CS signal line. The LCD driver uses this GPIO to select the LCD chip. If the SPI bus only has one device attached (i.e., this LCD), you can set the gpio number to -1 to occupy the bus exclusively. esp_lcd_panel_io_spi_config_t::pclk_hz sets the frequency of the pixel clock, in Hz. The value should not exceed the range recommended in the LCD spec. esp_lcd_panel_io_spi_config_t::spi_mode sets the SPI mode. The LCD driver uses this mode to communicate with the LCD. For the meaning of the SPI mode, please refer to the SPI Master API doc. esp_lcd_panel_io_spi_config_t::lcd_cmd_bits and esp_lcd_panel_io_spi_config_t::lcd_param_bits set the bit width of the command and parameter that recognized by the LCD controller chip. This is chip specific, you should refer to your LCD spec in advance. esp_lcd_panel_io_spi_config_t::trans_queue_depth sets the depth of the SPI transaction queue. A bigger value means more transactions can be queued up, but it also consumes more memory. esp_lcd_panel_io_spi_config_t::dc_gpio_num : Sets the gpio number for the DC signal line (some LCD calls this RS line). The LCD driver uses this GPIO to switch between sending command and sending data. esp_lcd_panel_io_spi_config_t::cs_gpio_num : Sets the gpio number for the CS signal line. The LCD driver uses this GPIO to select the LCD chip. If the SPI bus only has one device attached (i.e., this LCD), you can set the gpio number to -1 to occupy the bus exclusively. esp_lcd_panel_io_spi_config_t::pclk_hz sets the frequency of the pixel clock, in Hz. The value should not exceed the range recommended in the LCD spec. esp_lcd_panel_io_spi_config_t::spi_mode sets the SPI mode. The LCD driver uses this mode to communicate with the LCD. For the meaning of the SPI mode, please refer to the SPI Master API doc. esp_lcd_panel_io_spi_config_t::lcd_cmd_bits and esp_lcd_panel_io_spi_config_t::lcd_param_bits set the bit width of the command and parameter that recognized by the LCD controller chip. This is chip specific, you should refer to your LCD spec in advance. esp_lcd_panel_io_spi_config_t::trans_queue_depth sets the depth of the SPI transaction queue. A bigger value means more transactions can be queued up, but it also consumes more memory. esp_lcd_panel_io_handle_t io_handle = NULL; esp_lcd_panel_io_spi_config_t io_config = { .dc_gpio_num = EXAMPLE_PIN_NUM_LCD_DC, .cs_gpio_num = EXAMPLE_PIN_NUM_LCD_CS, .pclk_hz = EXAMPLE_LCD_PIXEL_CLOCK_HZ, .lcd_cmd_bits = EXAMPLE_LCD_CMD_BITS, .lcd_param_bits = EXAMPLE_LCD_PARAM_BITS, .spi_mode = 0, .trans_queue_depth = 10, }; // Attach the LCD to the SPI bus ESP_ERROR_CHECK(esp_lcd_new_panel_io_spi((esp_lcd_spi_bus_handle_t)LCD_HOST, &io_config, &io_handle)); esp_lcd_panel_io_spi_config_t::dc_gpio_num : Sets the gpio number for the DC signal line (some LCD calls this RS line). The LCD driver uses this GPIO to switch between sending command and sending data. Install the LCD controller driver. The LCD controller driver is responsible for sending the commands and parameters to the LCD controller chip. In this step, you need to specify the SPI IO device handle that allocated in the last step, and some panel specific configurations: esp_lcd_panel_dev_config_t::reset_gpio_num sets the LCD's hardware reset GPIO number. If the LCD does not have a hardware reset pin, set this to -1 . esp_lcd_panel_dev_config_t::rgb_ele_order sets the R-G-B element order of each color data. esp_lcd_panel_dev_config_t::bits_per_pixel sets the bit width of the pixel color data. The LCD driver uses this value to calculate the number of bytes to send to the LCD controller chip. esp_lcd_panel_dev_config_t::data_endian specifies the data endian to be transmitted to the screen. No need to specify for color data within 1 byte, like RGB232. For drivers that do not support specifying data endian, this field would be ignored. esp_lcd_panel_dev_config_t::reset_gpio_num sets the LCD's hardware reset GPIO number. If the LCD does not have a hardware reset pin, set this to -1 . esp_lcd_panel_dev_config_t::rgb_ele_order sets the R-G-B element order of each color data. esp_lcd_panel_dev_config_t::bits_per_pixel sets the bit width of the pixel color data. The LCD driver uses this value to calculate the number of bytes to send to the LCD controller chip. esp_lcd_panel_dev_config_t::data_endian specifies the data endian to be transmitted to the screen. No need to specify for color data within 1 byte, like RGB232. For drivers that do not support specifying data endian, this field would be ignored. esp_lcd_panel_handle_t panel_handle = NULL; esp_lcd_panel_dev_config_t panel_config = { .reset_gpio_num = EXAMPLE_PIN_NUM_RST, .rgb_ele_order = LCD_RGB_ELEMENT_ORDER_BGR, .bits_per_pixel = 16, }; // Create LCD panel handle for ST7789, with the SPI IO device handle ESP_ERROR_CHECK(esp_lcd_new_panel_st7789(io_handle, &panel_config, &panel_handle)); esp_lcd_panel_dev_config_t::reset_gpio_num sets the LCD's hardware reset GPIO number. If the LCD does not have a hardware reset pin, set this to -1 . I2C Interfaced LCD Create I2C bus. Please refer to I2C API doc for more details. i2c_master_bus_handle_t i2c_bus = NULL; i2c_master_bus_config_t bus_config = { .clk_source = I2C_CLK_SRC_DEFAULT, .glitch_ignore_cnt = 7, .i2c_port = I2C_BUS_PORT, .sda_io_num = EXAMPLE_PIN_NUM_SDA, .scl_io_num = EXAMPLE_PIN_NUM_SCL, .flags.enable_internal_pullup = true, }; ESP_ERROR_CHECK(i2c_new_master_bus(&bus_config, &i2c_bus)); Allocate an LCD IO device handle from the I2C bus. In this step, you need to provide the following information: esp_lcd_panel_io_i2c_config_t::dev_addr sets the I2C device address of the LCD controller chip. The LCD driver uses this address to communicate with the LCD controller chip. esp_lcd_panel_io_i2c_config_t::scl_speed_hz sets the I2C clock frequency in Hz. The value should not exceed the range recommended in the LCD spec. esp_lcd_panel_io_i2c_config_t::lcd_cmd_bits and esp_lcd_panel_io_i2c_config_t::lcd_param_bits set the bit width of the command and parameter that recognized by the LCD controller chip. This is chip specific, you should refer to your LCD spec in advance. esp_lcd_panel_io_i2c_config_t::dev_addr sets the I2C device address of the LCD controller chip. The LCD driver uses this address to communicate with the LCD controller chip. esp_lcd_panel_io_i2c_config_t::scl_speed_hz sets the I2C clock frequency in Hz. The value should not exceed the range recommended in the LCD spec. esp_lcd_panel_io_i2c_config_t::lcd_cmd_bits and esp_lcd_panel_io_i2c_config_t::lcd_param_bits set the bit width of the command and parameter that recognized by the LCD controller chip. This is chip specific, you should refer to your LCD spec in advance. esp_lcd_panel_io_handle_t io_handle = NULL; esp_lcd_panel_io_i2c_config_t io_config = { .dev_addr = EXAMPLE_I2C_HW_ADDR, .scl_speed_hz = EXAMPLE_LCD_PIXEL_CLOCK_HZ, .control_phase_bytes = 1, // refer to LCD spec .dc_bit_offset = 6, // refer to LCD spec .lcd_cmd_bits = EXAMPLE_LCD_CMD_BITS, .lcd_param_bits = EXAMPLE_LCD_CMD_BITS, }; ESP_ERROR_CHECK(esp_lcd_new_panel_io_i2c(i2c_bus, &io_config, &io_handle)); esp_lcd_panel_io_i2c_config_t::dev_addr sets the I2C device address of the LCD controller chip. The LCD driver uses this address to communicate with the LCD controller chip. Install the LCD controller driver. The LCD controller driver is responsible for sending the commands and parameters to the LCD controller chip. In this step, you need to specify the I2C IO device handle that allocated in the last step, and some panel specific configurations: esp_lcd_panel_dev_config_t::reset_gpio_num sets the LCD's hardware reset GPIO number. If the LCD does not have a hardware reset pin, set this to -1 . esp_lcd_panel_dev_config_t::bits_per_pixel sets the bit width of the pixel color data. The LCD driver uses this value to calculate the number of bytes to send to the LCD controller chip. esp_lcd_panel_dev_config_t::reset_gpio_num sets the LCD's hardware reset GPIO number. If the LCD does not have a hardware reset pin, set this to -1 . esp_lcd_panel_dev_config_t::bits_per_pixel sets the bit width of the pixel color data. The LCD driver uses this value to calculate the number of bytes to send to the LCD controller chip. esp_lcd_panel_handle_t panel_handle = NULL; esp_lcd_panel_dev_config_t panel_config = { .bits_per_pixel = 1, .reset_gpio_num = EXAMPLE_PIN_NUM_RST, }; ESP_ERROR_CHECK(esp_lcd_new_panel_ssd1306(io_handle, &panel_config, &panel_handle)); esp_lcd_panel_dev_config_t::reset_gpio_num sets the LCD's hardware reset GPIO number. If the LCD does not have a hardware reset pin, set this to -1 . I80 Interfaced LCD Create I80 bus by esp_lcd_new_i80_bus() . You need to set up the following parameters for an Intel 8080 parallel bus: esp_lcd_i80_bus_config_t::clk_src sets the clock source of the I80 bus. Note, the default clock source may be different between ESP targets. esp_lcd_i80_bus_config_t::wr_gpio_num sets the GPIO number of the pixel clock (also referred as WR in some LCD spec) esp_lcd_i80_bus_config_t::dc_gpio_num sets the GPIO number of the data/command select pin (also referred as RS in some LCD spec) esp_lcd_i80_bus_config_t::bus_width sets the bit width of the data bus (only support 8 or 16 ) esp_lcd_i80_bus_config_t::data_gpio_nums is the array of the GPIO number of the data bus. The number of GPIOs should be equal to the esp_lcd_i80_bus_config_t::bus_width value. esp_lcd_i80_bus_config_t::max_transfer_bytes sets the maximum number of bytes that can be transferred in one transaction. esp_lcd_i80_bus_config_t::clk_src sets the clock source of the I80 bus. Note, the default clock source may be different between ESP targets. esp_lcd_i80_bus_config_t::wr_gpio_num sets the GPIO number of the pixel clock (also referred as WR in some LCD spec) esp_lcd_i80_bus_config_t::dc_gpio_num sets the GPIO number of the data/command select pin (also referred as RS in some LCD spec) esp_lcd_i80_bus_config_t::bus_width sets the bit width of the data bus (only support 8 or 16 ) esp_lcd_i80_bus_config_t::data_gpio_nums is the array of the GPIO number of the data bus. The number of GPIOs should be equal to the esp_lcd_i80_bus_config_t::bus_width value. esp_lcd_i80_bus_config_t::max_transfer_bytes sets the maximum number of bytes that can be transferred in one transaction. esp_lcd_i80_bus_handle_t i80_bus = NULL; esp_lcd_i80_bus_config_t bus_config = { .clk_src = LCD_CLK_SRC_DEFAULT, .dc_gpio_num = EXAMPLE_PIN_NUM_DC, .wr_gpio_num = EXAMPLE_PIN_NUM_PCLK, .data_gpio_nums = { EXAMPLE_PIN_NUM_DATA0, EXAMPLE_PIN_NUM_DATA1, EXAMPLE_PIN_NUM_DATA2, EXAMPLE_PIN_NUM_DATA3, EXAMPLE_PIN_NUM_DATA4, EXAMPLE_PIN_NUM_DATA5, EXAMPLE_PIN_NUM_DATA6, EXAMPLE_PIN_NUM_DATA7, }, .bus_width = 8, .max_transfer_bytes = EXAMPLE_LCD_H_RES * 100 * sizeof(uint16_t), // transfer 100 lines of pixels (assume pixel is RGB565) at most in one transaction .psram_trans_align = EXAMPLE_PSRAM_DATA_ALIGNMENT, .sram_trans_align = 4, }; ESP_ERROR_CHECK(esp_lcd_new_i80_bus(&bus_config, &i80_bus)); esp_lcd_i80_bus_config_t::clk_src sets the clock source of the I80 bus. Note, the default clock source may be different between ESP targets. Allocate an LCD IO device handle from the I80 bus. In this step, you need to provide the following information: esp_lcd_panel_io_i80_config_t::cs_gpio_num sets the GPIO number of the chip select pin. esp_lcd_panel_io_i80_config_t::pclk_hz sets the pixel clock frequency in Hz. Higher pixel clock frequency results in higher refresh rate, but may cause flickering if the DMA bandwidth is not sufficient or the LCD controller chip does not support high pixel clock frequency. esp_lcd_panel_io_i80_config_t::lcd_cmd_bits and esp_lcd_panel_io_i80_config_t::lcd_param_bits set the bit width of the command and parameter that recognized by the LCD controller chip. This is chip specific, you should refer to your LCD spec in advance. esp_lcd_panel_io_i80_config_t::trans_queue_depth sets the maximum number of transactions that can be queued in the LCD IO device. A bigger value means more transactions can be queued up, but it also consumes more memory. esp_lcd_panel_io_i80_config_t::cs_gpio_num sets the GPIO number of the chip select pin. esp_lcd_panel_io_i80_config_t::pclk_hz sets the pixel clock frequency in Hz. Higher pixel clock frequency results in higher refresh rate, but may cause flickering if the DMA bandwidth is not sufficient or the LCD controller chip does not support high pixel clock frequency. esp_lcd_panel_io_i80_config_t::lcd_cmd_bits and esp_lcd_panel_io_i80_config_t::lcd_param_bits set the bit width of the command and parameter that recognized by the LCD controller chip. This is chip specific, you should refer to your LCD spec in advance. esp_lcd_panel_io_i80_config_t::trans_queue_depth sets the maximum number of transactions that can be queued in the LCD IO device. A bigger value means more transactions can be queued up, but it also consumes more memory. esp_lcd_panel_io_handle_t io_handle = NULL; esp_lcd_panel_io_i80_config_t io_config = { .cs_gpio_num = EXAMPLE_PIN_NUM_CS, .pclk_hz = EXAMPLE_LCD_PIXEL_CLOCK_HZ, .trans_queue_depth = 10, .dc_levels = { .dc_idle_level = 0, .dc_cmd_level = 0, .dc_dummy_level = 0, .dc_data_level = 1, }, .lcd_cmd_bits = EXAMPLE_LCD_CMD_BITS, .lcd_param_bits = EXAMPLE_LCD_PARAM_BITS, }; ESP_ERROR_CHECK(esp_lcd_new_panel_io_i80(i80_bus, &io_config, &io_handle)); esp_lcd_panel_io_i80_config_t::cs_gpio_num sets the GPIO number of the chip select pin. Install the LCD controller driver. The LCD controller driver is responsible for sending the commands and parameters to the LCD controller chip. In this step, you need to specify the I80 IO device handle that allocated in the last step, and some panel specific configurations: esp_lcd_panel_dev_config_t::bits_per_pixel sets the bit width of the pixel color data. The LCD driver uses this value to calculate the number of bytes to send to the LCD controller chip. esp_lcd_panel_dev_config_t::reset_gpio_num sets the GPIO number of the reset pin. If the LCD controller chip does not have a reset pin, you can set this value to -1 . esp_lcd_panel_dev_config_t::rgb_ele_order sets the color order the pixel color data. esp_lcd_panel_dev_config_t::bits_per_pixel sets the bit width of the pixel color data. The LCD driver uses this value to calculate the number of bytes to send to the LCD controller chip. esp_lcd_panel_dev_config_t::reset_gpio_num sets the GPIO number of the reset pin. If the LCD controller chip does not have a reset pin, you can set this value to -1 . esp_lcd_panel_dev_config_t::rgb_ele_order sets the color order the pixel color data. esp_lcd_panel_dev_config_t panel_config = { .reset_gpio_num = EXAMPLE_PIN_NUM_RST, .rgb_ele_order = LCD_RGB_ELEMENT_ORDER_RGB, .bits_per_pixel = 16, }; ESP_ERROR_CHECK(esp_lcd_new_panel_st7789(io_handle, &panel_config, &panel_handle)); esp_lcd_panel_dev_config_t::bits_per_pixel sets the bit width of the pixel color data. The LCD driver uses this value to calculate the number of bytes to send to the LCD controller chip. More Controller Based LCD Drivers More LCD panel drivers and touch drivers are available in ESP-IDF Component Registry. The list of available and planned drivers with links is in this table. LCD Panel IO Operations esp_lcd_panel_reset() can reset the LCD panel. esp_lcd_panel_init() performs a basic initialization of the panel. To perform more manufacture specific initialization, please go to Steps to Add Manufacture Specific Initialization. Through combined use of esp_lcd_panel_swap_xy() and esp_lcd_panel_mirror() , you can rotate the LCD screen. esp_lcd_panel_disp_on_off() can turn on or off the LCD screen by cutting down the output path from the frame buffer to the LCD screen. esp_lcd_panel_disp_sleep() can reduce the power consumption of the LCD screen by entering the sleep mode. The internal frame buffer is still retained. esp_lcd_panel_draw_bitmap() is the most significant function, which does the magic to draw the user provided color buffer to the LCD screen, where the draw window is also configurable. Steps to Add Manufacture Specific Initialization The LCD controller drivers (e.g., st7789) in esp-idf only provide basic initialization in the esp_lcd_panel_init() , leaving the vast majority of settings to the default values. Some LCD modules needs to set a bunch of manufacture specific configurations before it can display normally. These configurations usually include gamma, power voltage and so on. If you want to add manufacture specific initialization, please follow the steps below: esp_lcd_panel_reset(panel_handle); esp_lcd_panel_init(panel_handle); // set extra configurations e.g., gamma control // with the underlying IO handle // please consult your manufacture for special commands and corresponding values esp_lcd_panel_io_tx_param(io_handle, GAMMA_CMD, (uint8_t[]) { GAMMA_ARRAY }, N); // turn on the display esp_lcd_panel_disp_on_off(panel_handle, true); Application Example LCD examples are located under: peripherals/lcd: Universal SPI LCD example with SPI touch - peripherals/lcd/spi_lcd_touch Jpeg decoding and LCD display - peripherals/lcd/tjpgd i80 controller based LCD and LVGL animation UI - peripherals/lcd/i80_controller I2C interfaced OLED display scrolling text - peripherals/lcd/i2c_oled API Reference Header File This header file can be included with: #include "hal/lcd_types.h" Macros LCD_RGB_ENDIAN_RGB LCD_RGB_ENDIAN_BGR Type Definitions typedef soc_periph_lcd_clk_src_t lcd_clock_source_t LCD clock source. typedef lcd_rgb_element_order_t lcd_color_rgb_endian_t for backward compatible Enumerations enum lcd_rgb_element_order_t RGB color endian. Values: enumerator LCD_RGB_ELEMENT_ORDER_RGB RGB element order: RGB enumerator LCD_RGB_ELEMENT_ORDER_RGB RGB element order: RGB enumerator LCD_RGB_ELEMENT_ORDER_BGR RGB element order: BGR enumerator LCD_RGB_ELEMENT_ORDER_BGR RGB element order: BGR enumerator LCD_RGB_ELEMENT_ORDER_RGB enum lcd_rgb_data_endian_t RGB data endian. Values: enumerator LCD_RGB_DATA_ENDIAN_BIG RGB data endian: MSB first enumerator LCD_RGB_DATA_ENDIAN_BIG RGB data endian: MSB first enumerator LCD_RGB_DATA_ENDIAN_LITTLE RGB data endian: LSB first enumerator LCD_RGB_DATA_ENDIAN_LITTLE RGB data endian: LSB first enumerator LCD_RGB_DATA_ENDIAN_BIG enum lcd_color_space_t LCD color space. Values: enumerator LCD_COLOR_SPACE_RGB Color space: RGB enumerator LCD_COLOR_SPACE_RGB Color space: RGB enumerator LCD_COLOR_SPACE_YUV Color space: YUV enumerator LCD_COLOR_SPACE_YUV Color space: YUV enumerator LCD_COLOR_SPACE_RGB enum lcd_color_range_t LCD color range. Values: enumerator LCD_COLOR_RANGE_LIMIT Limited color range enumerator LCD_COLOR_RANGE_LIMIT Limited color range enumerator LCD_COLOR_RANGE_FULL Full color range enumerator LCD_COLOR_RANGE_FULL Full color range enumerator LCD_COLOR_RANGE_LIMIT enum lcd_yuv_sample_t YUV sampling method. Values: enumerator LCD_YUV_SAMPLE_422 YUV 4:2:2 sampling enumerator LCD_YUV_SAMPLE_422 YUV 4:2:2 sampling enumerator LCD_YUV_SAMPLE_420 YUV 4:2:0 sampling enumerator LCD_YUV_SAMPLE_420 YUV 4:2:0 sampling enumerator LCD_YUV_SAMPLE_411 YUV 4:1:1 sampling enumerator LCD_YUV_SAMPLE_411 YUV 4:1:1 sampling enumerator LCD_YUV_SAMPLE_422 Header File This header file can be included with: #include "esp_lcd_types.h" This header file is a part of the API provided by the esp_lcd component. To declare that your component depends on esp_lcd , add the following to your CMakeLists.txt: REQUIRES esp_lcd or PRIV_REQUIRES esp_lcd Type Definitions typedef struct esp_lcd_panel_io_t *esp_lcd_panel_io_handle_t Type of LCD panel IO handle typedef struct esp_lcd_panel_t *esp_lcd_panel_handle_t Type of LCD panel handle Header File This header file can be included with: #include "esp_lcd_panel_io.h" This header file is a part of the API provided by the esp_lcd component. To declare that your component depends on esp_lcd , add the following to your CMakeLists.txt: REQUIRES esp_lcd or PRIV_REQUIRES esp_lcd Functions esp_err_t esp_lcd_panel_io_rx_param(esp_lcd_panel_io_handle_t io, int lcd_cmd, void *param, size_t param_size) Transmit LCD command and receive corresponding parameters. Note Commands sent by this function are short, so they are sent using polling transactions. The function does not return before the command transfer is completed. If any queued transactions sent by esp_lcd_panel_io_tx_color() are still pending when this function is called, this function will wait until they are finished and the queue is empty before sending the command(s). Parameters io -- [in] LCD panel IO handle, which is created by other factory API like esp_lcd_new_panel_io_spi() lcd_cmd -- [in] The specific LCD command, set to -1 if no command needed param -- [out] Buffer for the command data param_size -- [in] Size of param buffer io -- [in] LCD panel IO handle, which is created by other factory API like esp_lcd_new_panel_io_spi() lcd_cmd -- [in] The specific LCD command, set to -1 if no command needed param -- [out] Buffer for the command data param_size -- [in] Size of param buffer io -- [in] LCD panel IO handle, which is created by other factory API like esp_lcd_new_panel_io_spi() Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if read is not supported by transport ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if read is not supported by transport ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters io -- [in] LCD panel IO handle, which is created by other factory API like esp_lcd_new_panel_io_spi() lcd_cmd -- [in] The specific LCD command, set to -1 if no command needed param -- [out] Buffer for the command data param_size -- [in] Size of param buffer Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if read is not supported by transport ESP_OK on success esp_err_t esp_lcd_panel_io_tx_param(esp_lcd_panel_io_handle_t io, int lcd_cmd, const void *param, size_t param_size) Transmit LCD command and corresponding parameters. Note Commands sent by this function are short, so they are sent using polling transactions. The function does not return before the command transfer is completed. If any queued transactions sent by esp_lcd_panel_io_tx_color() are still pending when this function is called, this function will wait until they are finished and the queue is empty before sending the command(s). Parameters io -- [in] LCD panel IO handle, which is created by other factory API like esp_lcd_new_panel_io_spi() lcd_cmd -- [in] The specific LCD command, set to -1 if no command needed param -- [in] Buffer that holds the command specific parameters, set to NULL if no parameter is needed for the command param_size -- [in] Size of param in memory, in bytes, set to zero if no parameter is needed for the command io -- [in] LCD panel IO handle, which is created by other factory API like esp_lcd_new_panel_io_spi() lcd_cmd -- [in] The specific LCD command, set to -1 if no command needed param -- [in] Buffer that holds the command specific parameters, set to NULL if no parameter is needed for the command param_size -- [in] Size of param in memory, in bytes, set to zero if no parameter is needed for the command io -- [in] LCD panel IO handle, which is created by other factory API like esp_lcd_new_panel_io_spi() Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters io -- [in] LCD panel IO handle, which is created by other factory API like esp_lcd_new_panel_io_spi() lcd_cmd -- [in] The specific LCD command, set to -1 if no command needed param -- [in] Buffer that holds the command specific parameters, set to NULL if no parameter is needed for the command param_size -- [in] Size of param in memory, in bytes, set to zero if no parameter is needed for the command Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success esp_err_t esp_lcd_panel_io_tx_color(esp_lcd_panel_io_handle_t io, int lcd_cmd, const void *color, size_t color_size) Transmit LCD RGB data. Note This function will package the command and RGB data into a transaction, and push into a queue. The real transmission is performed in the background (DMA+interrupt). The caller should take care of the lifecycle of the color buffer. Recycling of color buffer should be done in the callback on_color_trans_done() . Parameters io -- [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() lcd_cmd -- [in] The specific LCD command, set to -1 if no command needed color -- [in] Buffer that holds the RGB color data color_size -- [in] Size of color in memory, in bytes io -- [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() lcd_cmd -- [in] The specific LCD command, set to -1 if no command needed color -- [in] Buffer that holds the RGB color data color_size -- [in] Size of color in memory, in bytes io -- [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters io -- [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() lcd_cmd -- [in] The specific LCD command, set to -1 if no command needed color -- [in] Buffer that holds the RGB color data color_size -- [in] Size of color in memory, in bytes Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success esp_err_t esp_lcd_panel_io_del(esp_lcd_panel_io_handle_t io) Destroy LCD panel IO handle (deinitialize panel and free all corresponding resource) Parameters io -- [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters io -- [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success esp_err_t esp_lcd_panel_io_register_event_callbacks(esp_lcd_panel_io_handle_t io, const esp_lcd_panel_io_callbacks_t *cbs, void *user_ctx) Register LCD panel IO callbacks. Parameters io -- [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() cbs -- [in] structure with all LCD panel IO callbacks user_ctx -- [in] User private data, passed directly to callback's user_ctx io -- [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() cbs -- [in] structure with all LCD panel IO callbacks user_ctx -- [in] User private data, passed directly to callback's user_ctx io -- [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters io -- [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() cbs -- [in] structure with all LCD panel IO callbacks user_ctx -- [in] User private data, passed directly to callback's user_ctx Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success esp_err_t esp_lcd_new_panel_io_spi(esp_lcd_spi_bus_handle_t bus, const esp_lcd_panel_io_spi_config_t *io_config, esp_lcd_panel_io_handle_t *ret_io) Create LCD panel IO handle, for SPI interface. Parameters bus -- [in] SPI bus handle io_config -- [in] IO configuration, for SPI interface ret_io -- [out] Returned IO handle bus -- [in] SPI bus handle io_config -- [in] IO configuration, for SPI interface ret_io -- [out] Returned IO handle bus -- [in] SPI bus handle Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters bus -- [in] SPI bus handle io_config -- [in] IO configuration, for SPI interface ret_io -- [out] Returned IO handle Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success esp_err_t esp_lcd_new_panel_io_i2c_v1(uint32_t bus, const esp_lcd_panel_io_i2c_config_t *io_config, esp_lcd_panel_io_handle_t *ret_io) Create LCD panel IO handle, for I2C interface in legacy implementation. Note Please don't call this function in your project directly. Please call esp_lcd_new_panel_to_i2c instead. Parameters bus -- [in] I2C bus handle, (in uint32_t) io_config -- [in] IO configuration, for I2C interface ret_io -- [out] Returned IO handle bus -- [in] I2C bus handle, (in uint32_t) io_config -- [in] IO configuration, for I2C interface ret_io -- [out] Returned IO handle bus -- [in] I2C bus handle, (in uint32_t) Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters bus -- [in] I2C bus handle, (in uint32_t) io_config -- [in] IO configuration, for I2C interface ret_io -- [out] Returned IO handle Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success esp_err_t esp_lcd_new_panel_io_i2c_v2(i2c_master_bus_handle_t bus, const esp_lcd_panel_io_i2c_config_t *io_config, esp_lcd_panel_io_handle_t *ret_io) Create LCD panel IO handle, for I2C interface in new implementation. Note Please don't call this function in your project directly. Please call esp_lcd_new_panel_to_i2c instead. Parameters bus -- [in] I2C bus handle, (in i2c_master_dev_handle_t) io_config -- [in] IO configuration, for I2C interface ret_io -- [out] Returned IO handle bus -- [in] I2C bus handle, (in i2c_master_dev_handle_t) io_config -- [in] IO configuration, for I2C interface ret_io -- [out] Returned IO handle bus -- [in] I2C bus handle, (in i2c_master_dev_handle_t) Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters bus -- [in] I2C bus handle, (in i2c_master_dev_handle_t) io_config -- [in] IO configuration, for I2C interface ret_io -- [out] Returned IO handle Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success esp_err_t esp_lcd_new_i80_bus(const esp_lcd_i80_bus_config_t *bus_config, esp_lcd_i80_bus_handle_t *ret_bus) Create Intel 8080 bus handle. Parameters bus_config -- [in] Bus configuration ret_bus -- [out] Returned bus handle bus_config -- [in] Bus configuration ret_bus -- [out] Returned bus handle bus_config -- [in] Bus configuration Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_ERR_NOT_FOUND if no free bus is available ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_ERR_NOT_FOUND if no free bus is available ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters bus_config -- [in] Bus configuration ret_bus -- [out] Returned bus handle Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_ERR_NOT_FOUND if no free bus is available ESP_OK on success esp_err_t esp_lcd_del_i80_bus(esp_lcd_i80_bus_handle_t bus) Destroy Intel 8080 bus handle. Parameters bus -- [in] Intel 8080 bus handle, created by esp_lcd_new_i80_bus() Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if there still be some device attached to the bus ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if there still be some device attached to the bus ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters bus -- [in] Intel 8080 bus handle, created by esp_lcd_new_i80_bus() Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if there still be some device attached to the bus ESP_OK on success esp_err_t esp_lcd_new_panel_io_i80(esp_lcd_i80_bus_handle_t bus, const esp_lcd_panel_io_i80_config_t *io_config, esp_lcd_panel_io_handle_t *ret_io) Create LCD panel IO, for Intel 8080 interface. Parameters bus -- [in] Intel 8080 bus handle, created by esp_lcd_new_i80_bus() io_config -- [in] IO configuration, for i80 interface ret_io -- [out] Returned panel IO handle bus -- [in] Intel 8080 bus handle, created by esp_lcd_new_i80_bus() io_config -- [in] IO configuration, for i80 interface ret_io -- [out] Returned panel IO handle bus -- [in] Intel 8080 bus handle, created by esp_lcd_new_i80_bus() Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if some configuration can't be satisfied, e.g. pixel clock out of the range ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if some configuration can't be satisfied, e.g. pixel clock out of the range ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters bus -- [in] Intel 8080 bus handle, created by esp_lcd_new_i80_bus() io_config -- [in] IO configuration, for i80 interface ret_io -- [out] Returned panel IO handle Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if some configuration can't be satisfied, e.g. pixel clock out of the range ESP_ERR_NO_MEM if out of memory ESP_OK on success Structures struct esp_lcd_panel_io_event_data_t Type of LCD panel IO event data. struct esp_lcd_panel_io_callbacks_t Type of LCD panel IO callbacks. Public Members esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done Callback invoked when color data transfer has finished esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done Callback invoked when color data transfer has finished esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done struct esp_lcd_panel_io_spi_config_t Panel IO configuration structure, for SPI interface. Public Members int cs_gpio_num GPIO used for CS line int cs_gpio_num GPIO used for CS line int dc_gpio_num GPIO used to select the D/C line, set this to -1 if the D/C line is not used int dc_gpio_num GPIO used to select the D/C line, set this to -1 if the D/C line is not used int spi_mode Traditional SPI mode (0~3) int spi_mode Traditional SPI mode (0~3) unsigned int pclk_hz Frequency of pixel clock unsigned int pclk_hz Frequency of pixel clock size_t trans_queue_depth Size of internal transaction queue size_t trans_queue_depth Size of internal transaction queue esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done Callback invoked when color data transfer has finished esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done Callback invoked when color data transfer has finished void *user_ctx User private data, passed directly to on_color_trans_done's user_ctx void *user_ctx User private data, passed directly to on_color_trans_done's user_ctx int lcd_cmd_bits Bit-width of LCD command int lcd_cmd_bits Bit-width of LCD command int lcd_param_bits Bit-width of LCD parameter int lcd_param_bits Bit-width of LCD parameter unsigned int dc_high_on_cmd If enabled, DC level = 1 indicates command transfer unsigned int dc_high_on_cmd If enabled, DC level = 1 indicates command transfer unsigned int dc_low_on_data If enabled, DC level = 0 indicates color data transfer unsigned int dc_low_on_data If enabled, DC level = 0 indicates color data transfer unsigned int dc_low_on_param If enabled, DC level = 0 indicates parameter transfer unsigned int dc_low_on_param If enabled, DC level = 0 indicates parameter transfer unsigned int octal_mode transmit with octal mode (8 data lines), this mode is used to simulate Intel 8080 timing unsigned int octal_mode transmit with octal mode (8 data lines), this mode is used to simulate Intel 8080 timing unsigned int quad_mode transmit with quad mode (4 data lines), this mode is useful when transmitting LCD parameters (Only use one line for command) unsigned int quad_mode transmit with quad mode (4 data lines), this mode is useful when transmitting LCD parameters (Only use one line for command) unsigned int sio_mode Read and write through a single data line (MOSI) unsigned int sio_mode Read and write through a single data line (MOSI) unsigned int lsb_first transmit LSB bit first unsigned int lsb_first transmit LSB bit first unsigned int cs_high_active CS line is high active unsigned int cs_high_active CS line is high active struct esp_lcd_panel_io_spi_config_t::[anonymous] flags Extra flags to fine-tune the SPI device struct esp_lcd_panel_io_spi_config_t::[anonymous] flags Extra flags to fine-tune the SPI device int cs_gpio_num struct esp_lcd_panel_io_i2c_config_t Panel IO configuration structure, for I2C interface. Public Members uint32_t dev_addr I2C device address uint32_t dev_addr I2C device address esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done Callback invoked when color data transfer has finished esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done Callback invoked when color data transfer has finished void *user_ctx User private data, passed directly to on_color_trans_done's user_ctx void *user_ctx User private data, passed directly to on_color_trans_done's user_ctx size_t control_phase_bytes I2C LCD panel will encode control information (e.g. D/C selection) into control phase, in several bytes size_t control_phase_bytes I2C LCD panel will encode control information (e.g. D/C selection) into control phase, in several bytes unsigned int dc_bit_offset Offset of the D/C selection bit in control phase unsigned int dc_bit_offset Offset of the D/C selection bit in control phase int lcd_cmd_bits Bit-width of LCD command int lcd_cmd_bits Bit-width of LCD command int lcd_param_bits Bit-width of LCD parameter int lcd_param_bits Bit-width of LCD parameter unsigned int dc_low_on_data If this flag is enabled, DC line = 0 means transfer data, DC line = 1 means transfer command; vice versa unsigned int dc_low_on_data If this flag is enabled, DC line = 0 means transfer data, DC line = 1 means transfer command; vice versa unsigned int disable_control_phase If this flag is enabled, the control phase isn't used unsigned int disable_control_phase If this flag is enabled, the control phase isn't used struct esp_lcd_panel_io_i2c_config_t::[anonymous] flags Extra flags to fine-tune the I2C device struct esp_lcd_panel_io_i2c_config_t::[anonymous] flags Extra flags to fine-tune the I2C device uint32_t scl_speed_hz I2C LCD SCL frequency (hz) uint32_t scl_speed_hz I2C LCD SCL frequency (hz) uint32_t dev_addr struct esp_lcd_i80_bus_config_t LCD Intel 8080 bus configuration structure. Public Members int dc_gpio_num GPIO used for D/C line int dc_gpio_num GPIO used for D/C line int wr_gpio_num GPIO used for WR line int wr_gpio_num GPIO used for WR line lcd_clock_source_t clk_src Clock source for the I80 LCD peripheral lcd_clock_source_t clk_src Clock source for the I80 LCD peripheral int data_gpio_nums[(24)] GPIOs used for data lines int data_gpio_nums[(24)] GPIOs used for data lines size_t bus_width Number of data lines, 8 or 16 size_t bus_width Number of data lines, 8 or 16 size_t max_transfer_bytes Maximum transfer size, this determines the length of internal DMA link size_t max_transfer_bytes Maximum transfer size, this determines the length of internal DMA link size_t psram_trans_align DMA transfer alignment for data allocated from PSRAM size_t psram_trans_align DMA transfer alignment for data allocated from PSRAM size_t sram_trans_align DMA transfer alignment for data allocated from SRAM size_t sram_trans_align DMA transfer alignment for data allocated from SRAM int dc_gpio_num struct esp_lcd_panel_io_i80_config_t Panel IO configuration structure, for intel 8080 interface. Public Members int cs_gpio_num GPIO used for CS line, set to -1 will declaim exclusively use of I80 bus int cs_gpio_num GPIO used for CS line, set to -1 will declaim exclusively use of I80 bus uint32_t pclk_hz Frequency of pixel clock uint32_t pclk_hz Frequency of pixel clock size_t trans_queue_depth Transaction queue size, larger queue, higher throughput size_t trans_queue_depth Transaction queue size, larger queue, higher throughput esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done Callback invoked when color data was transferred done esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done Callback invoked when color data was transferred done void *user_ctx User private data, passed directly to on_color_trans_done's user_ctx void *user_ctx User private data, passed directly to on_color_trans_done's user_ctx int lcd_cmd_bits Bit-width of LCD command int lcd_cmd_bits Bit-width of LCD command int lcd_param_bits Bit-width of LCD parameter int lcd_param_bits Bit-width of LCD parameter unsigned int dc_idle_level Level of DC line in IDLE phase unsigned int dc_idle_level Level of DC line in IDLE phase unsigned int dc_cmd_level Level of DC line in CMD phase unsigned int dc_cmd_level Level of DC line in CMD phase unsigned int dc_dummy_level Level of DC line in DUMMY phase unsigned int dc_dummy_level Level of DC line in DUMMY phase unsigned int dc_data_level Level of DC line in DATA phase unsigned int dc_data_level Level of DC line in DATA phase struct esp_lcd_panel_io_i80_config_t::[anonymous] dc_levels Each i80 device might have its own D/C control logic struct esp_lcd_panel_io_i80_config_t::[anonymous] dc_levels Each i80 device might have its own D/C control logic unsigned int cs_active_high If set, a high level of CS line will select the device, otherwise, CS line is low level active unsigned int cs_active_high If set, a high level of CS line will select the device, otherwise, CS line is low level active unsigned int reverse_color_bits Reverse the data bits, D[N:0] -> D[0:N] unsigned int reverse_color_bits Reverse the data bits, D[N:0] -> D[0:N] unsigned int swap_color_bytes Swap adjacent two color bytes unsigned int swap_color_bytes Swap adjacent two color bytes unsigned int pclk_active_neg The display will write data lines when there's a falling edge on WR signal (a.k.a the PCLK) unsigned int pclk_active_neg The display will write data lines when there's a falling edge on WR signal (a.k.a the PCLK) unsigned int pclk_idle_low The WR signal (a.k.a the PCLK) stays at low level in IDLE phase unsigned int pclk_idle_low The WR signal (a.k.a the PCLK) stays at low level in IDLE phase struct esp_lcd_panel_io_i80_config_t::[anonymous] flags Panel IO config flags struct esp_lcd_panel_io_i80_config_t::[anonymous] flags Panel IO config flags int cs_gpio_num Macros esp_lcd_new_panel_io_i2c(bus, io_config, ret_io) Create LCD panel IO handle. Parameters bus -- [in] I2C bus handle io_config -- [in] IO configuration, for I2C interface ret_io -- [out] Returned IO handle bus -- [in] I2C bus handle io_config -- [in] IO configuration, for I2C interface ret_io -- [out] Returned IO handle bus -- [in] I2C bus handle Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters bus -- [in] I2C bus handle io_config -- [in] IO configuration, for I2C interface ret_io -- [out] Returned IO handle Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success Type Definitions typedef void *esp_lcd_spi_bus_handle_t Type of LCD SPI bus handle typedef uint32_t esp_lcd_i2c_bus_handle_t Type of LCD I2C bus handle typedef struct esp_lcd_i80_bus_t *esp_lcd_i80_bus_handle_t Type of LCD intel 8080 bus handle typedef bool (*esp_lcd_panel_io_color_trans_done_cb_t)(esp_lcd_panel_io_handle_t panel_io, esp_lcd_panel_io_event_data_t *edata, void *user_ctx) Declare the prototype of the function that will be invoked when panel IO finishes transferring color data. Param panel_io [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() Param edata [in] Panel IO event data, fed by driver Param user_ctx [in] User data, passed from esp_lcd_panel_io_xxx_config_t Return Whether a high priority task has been waken up by this function Param panel_io [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() Param edata [in] Panel IO event data, fed by driver Param user_ctx [in] User data, passed from esp_lcd_panel_io_xxx_config_t Return Whether a high priority task has been waken up by this function Header File This header file can be included with: #include "esp_lcd_panel_ops.h" This header file is a part of the API provided by the esp_lcd component. To declare that your component depends on esp_lcd , add the following to your CMakeLists.txt: REQUIRES esp_lcd or PRIV_REQUIRES esp_lcd Functions esp_err_t esp_lcd_panel_reset(esp_lcd_panel_handle_t panel) Reset LCD panel. Note Panel reset must be called before attempting to initialize the panel using esp_lcd_panel_init() . Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() Returns ESP_OK on success ESP_OK on success ESP_OK on success Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() Returns ESP_OK on success esp_err_t esp_lcd_panel_init(esp_lcd_panel_handle_t panel) Initialize LCD panel. Note Before calling this function, make sure the LCD panel has finished the reset stage by esp_lcd_panel_reset() . Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() Returns ESP_OK on success ESP_OK on success ESP_OK on success Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() Returns ESP_OK on success esp_err_t esp_lcd_panel_del(esp_lcd_panel_handle_t panel) Deinitialize the LCD panel. Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() Returns ESP_OK on success ESP_OK on success ESP_OK on success Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() Returns ESP_OK on success esp_err_t esp_lcd_panel_draw_bitmap(esp_lcd_panel_handle_t panel, int x_start, int y_start, int x_end, int y_end, const void *color_data) Draw bitmap on LCD panel. Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() x_start -- [in] Start index on x-axis (x_start included) y_start -- [in] Start index on y-axis (y_start included) x_end -- [in] End index on x-axis (x_end not included) y_end -- [in] End index on y-axis (y_end not included) color_data -- [in] RGB color data that will be dumped to the specific window range panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() x_start -- [in] Start index on x-axis (x_start included) y_start -- [in] Start index on y-axis (y_start included) x_end -- [in] End index on x-axis (x_end not included) y_end -- [in] End index on y-axis (y_end not included) color_data -- [in] RGB color data that will be dumped to the specific window range panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() Returns ESP_OK on success ESP_OK on success ESP_OK on success Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() x_start -- [in] Start index on x-axis (x_start included) y_start -- [in] Start index on y-axis (y_start included) x_end -- [in] End index on x-axis (x_end not included) y_end -- [in] End index on y-axis (y_end not included) color_data -- [in] RGB color data that will be dumped to the specific window range Returns ESP_OK on success esp_err_t esp_lcd_panel_mirror(esp_lcd_panel_handle_t panel, bool mirror_x, bool mirror_y) Mirror the LCD panel on specific axis. Note Combined with esp_lcd_panel_swap_xy() , one can realize screen rotation Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() mirror_x -- [in] Whether the panel will be mirrored about the x axis mirror_y -- [in] Whether the panel will be mirrored about the y axis panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() mirror_x -- [in] Whether the panel will be mirrored about the x axis mirror_y -- [in] Whether the panel will be mirrored about the y axis panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel ESP_OK on success Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() mirror_x -- [in] Whether the panel will be mirrored about the x axis mirror_y -- [in] Whether the panel will be mirrored about the y axis Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel esp_err_t esp_lcd_panel_swap_xy(esp_lcd_panel_handle_t panel, bool swap_axes) Swap/Exchange x and y axis. Note Combined with esp_lcd_panel_mirror() , one can realize screen rotation Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() swap_axes -- [in] Whether to swap the x and y axis panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() swap_axes -- [in] Whether to swap the x and y axis panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel ESP_OK on success Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() swap_axes -- [in] Whether to swap the x and y axis Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel esp_err_t esp_lcd_panel_set_gap(esp_lcd_panel_handle_t panel, int x_gap, int y_gap) Set extra gap in x and y axis. The gap is the space (in pixels) between the left/top sides of the LCD panel and the first row/column respectively of the actual contents displayed. Note Setting a gap is useful when positioning or centering a frame that is smaller than the LCD. Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() x_gap -- [in] Extra gap on x axis, in pixels y_gap -- [in] Extra gap on y axis, in pixels panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() x_gap -- [in] Extra gap on x axis, in pixels y_gap -- [in] Extra gap on y axis, in pixels panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() Returns ESP_OK on success ESP_OK on success ESP_OK on success Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() x_gap -- [in] Extra gap on x axis, in pixels y_gap -- [in] Extra gap on y axis, in pixels Returns ESP_OK on success esp_err_t esp_lcd_panel_invert_color(esp_lcd_panel_handle_t panel, bool invert_color_data) Invert the color (bit-wise invert the color data line) Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() invert_color_data -- [in] Whether to invert the color data panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() invert_color_data -- [in] Whether to invert the color data panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() Returns ESP_OK on success ESP_OK on success ESP_OK on success Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() invert_color_data -- [in] Whether to invert the color data Returns ESP_OK on success esp_err_t esp_lcd_panel_disp_on_off(esp_lcd_panel_handle_t panel, bool on_off) Turn on or off the display. Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() on_off -- [in] True to turns on display, False to turns off display panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() on_off -- [in] True to turns on display, False to turns off display panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel ESP_OK on success Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() on_off -- [in] True to turns on display, False to turns off display Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel esp_err_t esp_lcd_panel_disp_off(esp_lcd_panel_handle_t panel, bool off) Turn off the display. Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() off -- [in] Whether to turn off the screen panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() off -- [in] Whether to turn off the screen panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel ESP_OK on success Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() off -- [in] Whether to turn off the screen Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel esp_err_t esp_lcd_panel_disp_sleep(esp_lcd_panel_handle_t panel, bool sleep) Enter or exit sleep mode. Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() sleep -- [in] True to enter sleep mode, False to wake up panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() sleep -- [in] True to enter sleep mode, False to wake up panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel ESP_OK on success Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() sleep -- [in] True to enter sleep mode, False to wake up Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel Header File This header file can be included with: #include "esp_lcd_panel_rgb.h" This header file is a part of the API provided by the esp_lcd component. To declare that your component depends on esp_lcd , add the following to your CMakeLists.txt: REQUIRES esp_lcd or PRIV_REQUIRES esp_lcd Header File This header file can be included with: #include "esp_lcd_panel_vendor.h" This header file is a part of the API provided by the esp_lcd component. To declare that your component depends on esp_lcd , add the following to your CMakeLists.txt: REQUIRES esp_lcd or PRIV_REQUIRES esp_lcd Functions esp_err_t esp_lcd_new_panel_st7789(const esp_lcd_panel_io_handle_t io, const esp_lcd_panel_dev_config_t *panel_dev_config, esp_lcd_panel_handle_t *ret_panel) Create LCD panel for model ST7789. Parameters io -- [in] LCD panel IO handle panel_dev_config -- [in] general panel device configuration ret_panel -- [out] Returned LCD panel handle io -- [in] LCD panel IO handle panel_dev_config -- [in] general panel device configuration ret_panel -- [out] Returned LCD panel handle io -- [in] LCD panel IO handle Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters io -- [in] LCD panel IO handle panel_dev_config -- [in] general panel device configuration ret_panel -- [out] Returned LCD panel handle Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success esp_err_t esp_lcd_new_panel_nt35510(const esp_lcd_panel_io_handle_t io, const esp_lcd_panel_dev_config_t *panel_dev_config, esp_lcd_panel_handle_t *ret_panel) Create LCD panel for model NT35510. Parameters io -- [in] LCD panel IO handle panel_dev_config -- [in] general panel device configuration ret_panel -- [out] Returned LCD panel handle io -- [in] LCD panel IO handle panel_dev_config -- [in] general panel device configuration ret_panel -- [out] Returned LCD panel handle io -- [in] LCD panel IO handle Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters io -- [in] LCD panel IO handle panel_dev_config -- [in] general panel device configuration ret_panel -- [out] Returned LCD panel handle Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success esp_err_t esp_lcd_new_panel_ssd1306(const esp_lcd_panel_io_handle_t io, const esp_lcd_panel_dev_config_t *panel_dev_config, esp_lcd_panel_handle_t *ret_panel) Create LCD panel for model SSD1306. Parameters io -- [in] LCD panel IO handle panel_dev_config -- [in] general panel device configuration ret_panel -- [out] Returned LCD panel handle io -- [in] LCD panel IO handle panel_dev_config -- [in] general panel device configuration ret_panel -- [out] Returned LCD panel handle io -- [in] LCD panel IO handle Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters io -- [in] LCD panel IO handle panel_dev_config -- [in] general panel device configuration ret_panel -- [out] Returned LCD panel handle Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success Structures struct esp_lcd_panel_dev_config_t Configuration structure for panel device. Public Members int reset_gpio_num GPIO used to reset the LCD panel, set to -1 if it's not used int reset_gpio_num GPIO used to reset the LCD panel, set to -1 if it's not used lcd_rgb_element_order_t color_space Deprecated: Set RGB color space, please use rgb_ele_order instead Deprecated: Set RGB color space, please use rgb_ele_order instead lcd_rgb_element_order_t color_space Deprecated: Set RGB color space, please use rgb_ele_order instead lcd_rgb_element_order_t rgb_endian Deprecated: Set RGB data endian, please use rgb_ele_order instead Deprecated: Set RGB data endian, please use rgb_ele_order instead lcd_rgb_element_order_t rgb_endian Deprecated: Set RGB data endian, please use rgb_ele_order instead lcd_rgb_element_order_t rgb_ele_order Set RGB element order, RGB or BGR lcd_rgb_element_order_t rgb_ele_order Set RGB element order, RGB or BGR lcd_rgb_data_endian_t data_endian Set the data endian for color data larger than 1 byte lcd_rgb_data_endian_t data_endian Set the data endian for color data larger than 1 byte unsigned int bits_per_pixel Color depth, in bpp unsigned int bits_per_pixel Color depth, in bpp unsigned int reset_active_high Setting this if the panel reset is high level active unsigned int reset_active_high Setting this if the panel reset is high level active struct esp_lcd_panel_dev_config_t::[anonymous] flags LCD panel config flags struct esp_lcd_panel_dev_config_t::[anonymous] flags LCD panel config flags void *vendor_config vendor specific configuration, optional, left as NULL if not used void *vendor_config vendor specific configuration, optional, left as NULL if not used int reset_gpio_num
LCD Introduction ESP chips can generate various kinds of timings that needed by common LCDs on the market, like SPI LCD, I80 LCD (a.k.a Intel 8080 parallel LCD), RGB/SRGB LCD, I2C LCD, etc. The esp_lcd component is officially to support those LCDs with a group of universal APIs across chips. Functional Overview In esp_lcd, an LCD panel is represented by esp_lcd_panel_handle_t, which plays the role of an abstract frame buffer, regardless of the frame memory is allocated inside ESP chip or in external LCD controller. Based on the location of the frame buffer and the hardware connection interface, the LCD panel drivers are mainly grouped into the following categories: Controller based LCD driver involves multiple steps to get a panel handle, like bus allocation, IO device registration and controller driver install. The frame buffer is located in the controller's internal GRAM (Graphical RAM). ESP-IDF provides only a limited number of LCD controller drivers out of the box (e.g., ST7789, SSD1306), More Controller Based LCD Drivers are maintained in the Espressif Component Registry. SPI Interfaced LCD describes the steps to install the SPI LCD IO driver and then get the panel handle. I2C Interfaced LCD describes the steps to install the I2C LCD IO driver and then get the panel handle. I80 Interfaced LCD describes the steps to install the I80 LCD IO driver and then get the panel handle. LCD Panel IO Operations - provides a set of APIs to operate the LCD panel, like turning on/off the display, setting the orientation, etc. These operations are common for either controller-based LCD panel driver or RGB LCD panel driver. SPI Interfaced LCD Create an SPI bus. Please refer to SPI Master API doc for more details. spi_bus_config_t buscfg = { .sclk_io_num = EXAMPLE_PIN_NUM_SCLK, .mosi_io_num = EXAMPLE_PIN_NUM_MOSI, .miso_io_num = EXAMPLE_PIN_NUM_MISO, .quadwp_io_num = -1, // Quad SPI LCD driver is not yet supported .quadhd_io_num = -1, // Quad SPI LCD driver is not yet supported .max_transfer_sz = EXAMPLE_LCD_H_RES * 80 * sizeof(uint16_t), // transfer 80 lines of pixels (assume pixel is RGB565) at most in one SPI transaction }; ESP_ERROR_CHECK(spi_bus_initialize(LCD_HOST, &buscfg, SPI_DMA_CH_AUTO)); // Enable the DMA feature Allocate an LCD IO device handle from the SPI bus. In this step, you need to provide the following information: esp_lcd_panel_io_spi_config_t::dc_gpio_num: Sets the gpio number for the DC signal line (some LCD calls this RSline). The LCD driver uses this GPIO to switch between sending command and sending data. esp_lcd_panel_io_spi_config_t::cs_gpio_num: Sets the gpio number for the CS signal line. The LCD driver uses this GPIO to select the LCD chip. If the SPI bus only has one device attached (i.e., this LCD), you can set the gpio number to -1to occupy the bus exclusively. esp_lcd_panel_io_spi_config_t::pclk_hzsets the frequency of the pixel clock, in Hz. The value should not exceed the range recommended in the LCD spec. esp_lcd_panel_io_spi_config_t::spi_modesets the SPI mode. The LCD driver uses this mode to communicate with the LCD. For the meaning of the SPI mode, please refer to the SPI Master API doc. esp_lcd_panel_io_spi_config_t::lcd_cmd_bitsand esp_lcd_panel_io_spi_config_t::lcd_param_bitsset the bit width of the command and parameter that recognized by the LCD controller chip. This is chip specific, you should refer to your LCD spec in advance. esp_lcd_panel_io_spi_config_t::trans_queue_depthsets the depth of the SPI transaction queue. A bigger value means more transactions can be queued up, but it also consumes more memory. esp_lcd_panel_io_handle_t io_handle = NULL; esp_lcd_panel_io_spi_config_t io_config = { .dc_gpio_num = EXAMPLE_PIN_NUM_LCD_DC, .cs_gpio_num = EXAMPLE_PIN_NUM_LCD_CS, .pclk_hz = EXAMPLE_LCD_PIXEL_CLOCK_HZ, .lcd_cmd_bits = EXAMPLE_LCD_CMD_BITS, .lcd_param_bits = EXAMPLE_LCD_PARAM_BITS, .spi_mode = 0, .trans_queue_depth = 10, }; // Attach the LCD to the SPI bus ESP_ERROR_CHECK(esp_lcd_new_panel_io_spi((esp_lcd_spi_bus_handle_t)LCD_HOST, &io_config, &io_handle)); - Install the LCD controller driver. The LCD controller driver is responsible for sending the commands and parameters to the LCD controller chip. In this step, you need to specify the SPI IO device handle that allocated in the last step, and some panel specific configurations: esp_lcd_panel_dev_config_t::reset_gpio_numsets the LCD's hardware reset GPIO number. If the LCD does not have a hardware reset pin, set this to -1. esp_lcd_panel_dev_config_t::rgb_ele_ordersets the R-G-B element order of each color data. esp_lcd_panel_dev_config_t::bits_per_pixelsets the bit width of the pixel color data. The LCD driver uses this value to calculate the number of bytes to send to the LCD controller chip. esp_lcd_panel_dev_config_t::data_endianspecifies the data endian to be transmitted to the screen. No need to specify for color data within 1 byte, like RGB232. For drivers that do not support specifying data endian, this field would be ignored. esp_lcd_panel_handle_t panel_handle = NULL; esp_lcd_panel_dev_config_t panel_config = { .reset_gpio_num = EXAMPLE_PIN_NUM_RST, .rgb_ele_order = LCD_RGB_ELEMENT_ORDER_BGR, .bits_per_pixel = 16, }; // Create LCD panel handle for ST7789, with the SPI IO device handle ESP_ERROR_CHECK(esp_lcd_new_panel_st7789(io_handle, &panel_config, &panel_handle)); - I2C Interfaced LCD Create I2C bus. Please refer to I2C API doc for more details. i2c_master_bus_handle_t i2c_bus = NULL; i2c_master_bus_config_t bus_config = { .clk_source = I2C_CLK_SRC_DEFAULT, .glitch_ignore_cnt = 7, .i2c_port = I2C_BUS_PORT, .sda_io_num = EXAMPLE_PIN_NUM_SDA, .scl_io_num = EXAMPLE_PIN_NUM_SCL, .flags.enable_internal_pullup = true, }; ESP_ERROR_CHECK(i2c_new_master_bus(&bus_config, &i2c_bus)); Allocate an LCD IO device handle from the I2C bus. In this step, you need to provide the following information: esp_lcd_panel_io_i2c_config_t::dev_addrsets the I2C device address of the LCD controller chip. The LCD driver uses this address to communicate with the LCD controller chip. esp_lcd_panel_io_i2c_config_t::scl_speed_hzsets the I2C clock frequency in Hz. The value should not exceed the range recommended in the LCD spec. esp_lcd_panel_io_i2c_config_t::lcd_cmd_bitsand esp_lcd_panel_io_i2c_config_t::lcd_param_bitsset the bit width of the command and parameter that recognized by the LCD controller chip. This is chip specific, you should refer to your LCD spec in advance. esp_lcd_panel_io_handle_t io_handle = NULL; esp_lcd_panel_io_i2c_config_t io_config = { .dev_addr = EXAMPLE_I2C_HW_ADDR, .scl_speed_hz = EXAMPLE_LCD_PIXEL_CLOCK_HZ, .control_phase_bytes = 1, // refer to LCD spec .dc_bit_offset = 6, // refer to LCD spec .lcd_cmd_bits = EXAMPLE_LCD_CMD_BITS, .lcd_param_bits = EXAMPLE_LCD_CMD_BITS, }; ESP_ERROR_CHECK(esp_lcd_new_panel_io_i2c(i2c_bus, &io_config, &io_handle)); - Install the LCD controller driver. The LCD controller driver is responsible for sending the commands and parameters to the LCD controller chip. In this step, you need to specify the I2C IO device handle that allocated in the last step, and some panel specific configurations: esp_lcd_panel_dev_config_t::reset_gpio_numsets the LCD's hardware reset GPIO number. If the LCD does not have a hardware reset pin, set this to -1. esp_lcd_panel_dev_config_t::bits_per_pixelsets the bit width of the pixel color data. The LCD driver uses this value to calculate the number of bytes to send to the LCD controller chip. esp_lcd_panel_handle_t panel_handle = NULL; esp_lcd_panel_dev_config_t panel_config = { .bits_per_pixel = 1, .reset_gpio_num = EXAMPLE_PIN_NUM_RST, }; ESP_ERROR_CHECK(esp_lcd_new_panel_ssd1306(io_handle, &panel_config, &panel_handle)); - I80 Interfaced LCD Create I80 bus by esp_lcd_new_i80_bus(). You need to set up the following parameters for an Intel 8080 parallel bus: esp_lcd_i80_bus_config_t::clk_srcsets the clock source of the I80 bus. Note, the default clock source may be different between ESP targets. esp_lcd_i80_bus_config_t::wr_gpio_numsets the GPIO number of the pixel clock (also referred as WRin some LCD spec) esp_lcd_i80_bus_config_t::dc_gpio_numsets the GPIO number of the data/command select pin (also referred as RSin some LCD spec) esp_lcd_i80_bus_config_t::bus_widthsets the bit width of the data bus (only support 8or 16) esp_lcd_i80_bus_config_t::data_gpio_numsis the array of the GPIO number of the data bus. The number of GPIOs should be equal to the esp_lcd_i80_bus_config_t::bus_widthvalue. esp_lcd_i80_bus_config_t::max_transfer_bytessets the maximum number of bytes that can be transferred in one transaction. esp_lcd_i80_bus_handle_t i80_bus = NULL; esp_lcd_i80_bus_config_t bus_config = { .clk_src = LCD_CLK_SRC_DEFAULT, .dc_gpio_num = EXAMPLE_PIN_NUM_DC, .wr_gpio_num = EXAMPLE_PIN_NUM_PCLK, .data_gpio_nums = { EXAMPLE_PIN_NUM_DATA0, EXAMPLE_PIN_NUM_DATA1, EXAMPLE_PIN_NUM_DATA2, EXAMPLE_PIN_NUM_DATA3, EXAMPLE_PIN_NUM_DATA4, EXAMPLE_PIN_NUM_DATA5, EXAMPLE_PIN_NUM_DATA6, EXAMPLE_PIN_NUM_DATA7, }, .bus_width = 8, .max_transfer_bytes = EXAMPLE_LCD_H_RES * 100 * sizeof(uint16_t), // transfer 100 lines of pixels (assume pixel is RGB565) at most in one transaction .psram_trans_align = EXAMPLE_PSRAM_DATA_ALIGNMENT, .sram_trans_align = 4, }; ESP_ERROR_CHECK(esp_lcd_new_i80_bus(&bus_config, &i80_bus)); - Allocate an LCD IO device handle from the I80 bus. In this step, you need to provide the following information: esp_lcd_panel_io_i80_config_t::cs_gpio_numsets the GPIO number of the chip select pin. esp_lcd_panel_io_i80_config_t::pclk_hzsets the pixel clock frequency in Hz. Higher pixel clock frequency results in higher refresh rate, but may cause flickering if the DMA bandwidth is not sufficient or the LCD controller chip does not support high pixel clock frequency. esp_lcd_panel_io_i80_config_t::lcd_cmd_bitsand esp_lcd_panel_io_i80_config_t::lcd_param_bitsset the bit width of the command and parameter that recognized by the LCD controller chip. This is chip specific, you should refer to your LCD spec in advance. esp_lcd_panel_io_i80_config_t::trans_queue_depthsets the maximum number of transactions that can be queued in the LCD IO device. A bigger value means more transactions can be queued up, but it also consumes more memory. esp_lcd_panel_io_handle_t io_handle = NULL; esp_lcd_panel_io_i80_config_t io_config = { .cs_gpio_num = EXAMPLE_PIN_NUM_CS, .pclk_hz = EXAMPLE_LCD_PIXEL_CLOCK_HZ, .trans_queue_depth = 10, .dc_levels = { .dc_idle_level = 0, .dc_cmd_level = 0, .dc_dummy_level = 0, .dc_data_level = 1, }, .lcd_cmd_bits = EXAMPLE_LCD_CMD_BITS, .lcd_param_bits = EXAMPLE_LCD_PARAM_BITS, }; ESP_ERROR_CHECK(esp_lcd_new_panel_io_i80(i80_bus, &io_config, &io_handle)); - Install the LCD controller driver. The LCD controller driver is responsible for sending the commands and parameters to the LCD controller chip. In this step, you need to specify the I80 IO device handle that allocated in the last step, and some panel specific configurations: esp_lcd_panel_dev_config_t::bits_per_pixelsets the bit width of the pixel color data. The LCD driver uses this value to calculate the number of bytes to send to the LCD controller chip. esp_lcd_panel_dev_config_t::reset_gpio_numsets the GPIO number of the reset pin. If the LCD controller chip does not have a reset pin, you can set this value to -1. esp_lcd_panel_dev_config_t::rgb_ele_ordersets the color order the pixel color data. esp_lcd_panel_dev_config_t panel_config = { .reset_gpio_num = EXAMPLE_PIN_NUM_RST, .rgb_ele_order = LCD_RGB_ELEMENT_ORDER_RGB, .bits_per_pixel = 16, }; ESP_ERROR_CHECK(esp_lcd_new_panel_st7789(io_handle, &panel_config, &panel_handle)); - More Controller Based LCD Drivers More LCD panel drivers and touch drivers are available in ESP-IDF Component Registry. The list of available and planned drivers with links is in this table. LCD Panel IO Operations esp_lcd_panel_reset()can reset the LCD panel. esp_lcd_panel_init()performs a basic initialization of the panel. To perform more manufacture specific initialization, please go to Steps to Add Manufacture Specific Initialization. Through combined use of esp_lcd_panel_swap_xy()and esp_lcd_panel_mirror(), you can rotate the LCD screen. esp_lcd_panel_disp_on_off()can turn on or off the LCD screen by cutting down the output path from the frame buffer to the LCD screen. esp_lcd_panel_disp_sleep()can reduce the power consumption of the LCD screen by entering the sleep mode. The internal frame buffer is still retained. esp_lcd_panel_draw_bitmap()is the most significant function, which does the magic to draw the user provided color buffer to the LCD screen, where the draw window is also configurable. Steps to Add Manufacture Specific Initialization The LCD controller drivers (e.g., st7789) in esp-idf only provide basic initialization in the esp_lcd_panel_init(), leaving the vast majority of settings to the default values. Some LCD modules needs to set a bunch of manufacture specific configurations before it can display normally. These configurations usually include gamma, power voltage and so on. If you want to add manufacture specific initialization, please follow the steps below: esp_lcd_panel_reset(panel_handle); esp_lcd_panel_init(panel_handle); // set extra configurations e.g., gamma control // with the underlying IO handle // please consult your manufacture for special commands and corresponding values esp_lcd_panel_io_tx_param(io_handle, GAMMA_CMD, (uint8_t[]) { GAMMA_ARRAY }, N); // turn on the display esp_lcd_panel_disp_on_off(panel_handle, true); Application Example LCD examples are located under: peripherals/lcd: Universal SPI LCD example with SPI touch - peripherals/lcd/spi_lcd_touch Jpeg decoding and LCD display - peripherals/lcd/tjpgd i80 controller based LCD and LVGL animation UI - peripherals/lcd/i80_controller I2C interfaced OLED display scrolling text - peripherals/lcd/i2c_oled API Reference Header File This header file can be included with: #include "hal/lcd_types.h" Macros - LCD_RGB_ENDIAN_RGB - LCD_RGB_ENDIAN_BGR Type Definitions - typedef soc_periph_lcd_clk_src_t lcd_clock_source_t LCD clock source. - typedef lcd_rgb_element_order_t lcd_color_rgb_endian_t for backward compatible Enumerations - enum lcd_rgb_element_order_t RGB color endian. Values: - enumerator LCD_RGB_ELEMENT_ORDER_RGB RGB element order: RGB - enumerator LCD_RGB_ELEMENT_ORDER_BGR RGB element order: BGR - enumerator LCD_RGB_ELEMENT_ORDER_RGB - enum lcd_rgb_data_endian_t RGB data endian. Values: - enumerator LCD_RGB_DATA_ENDIAN_BIG RGB data endian: MSB first - enumerator LCD_RGB_DATA_ENDIAN_LITTLE RGB data endian: LSB first - enumerator LCD_RGB_DATA_ENDIAN_BIG - enum lcd_color_space_t LCD color space. Values: - enumerator LCD_COLOR_SPACE_RGB Color space: RGB - enumerator LCD_COLOR_SPACE_YUV Color space: YUV - enumerator LCD_COLOR_SPACE_RGB - enum lcd_color_range_t LCD color range. Values: - enumerator LCD_COLOR_RANGE_LIMIT Limited color range - enumerator LCD_COLOR_RANGE_FULL Full color range - enumerator LCD_COLOR_RANGE_LIMIT - enum lcd_yuv_sample_t YUV sampling method. Values: - enumerator LCD_YUV_SAMPLE_422 YUV 4:2:2 sampling - enumerator LCD_YUV_SAMPLE_420 YUV 4:2:0 sampling - enumerator LCD_YUV_SAMPLE_411 YUV 4:1:1 sampling - enumerator LCD_YUV_SAMPLE_422 Header File This header file can be included with: #include "esp_lcd_types.h" This header file is a part of the API provided by the esp_lcdcomponent. To declare that your component depends on esp_lcd, add the following to your CMakeLists.txt: REQUIRES esp_lcd or PRIV_REQUIRES esp_lcd Type Definitions - typedef struct esp_lcd_panel_io_t *esp_lcd_panel_io_handle_t Type of LCD panel IO handle - typedef struct esp_lcd_panel_t *esp_lcd_panel_handle_t Type of LCD panel handle Header File This header file can be included with: #include "esp_lcd_panel_io.h" This header file is a part of the API provided by the esp_lcdcomponent. To declare that your component depends on esp_lcd, add the following to your CMakeLists.txt: REQUIRES esp_lcd or PRIV_REQUIRES esp_lcd Functions - esp_err_t esp_lcd_panel_io_rx_param(esp_lcd_panel_io_handle_t io, int lcd_cmd, void *param, size_t param_size) Transmit LCD command and receive corresponding parameters. Note Commands sent by this function are short, so they are sent using polling transactions. The function does not return before the command transfer is completed. If any queued transactions sent by esp_lcd_panel_io_tx_color()are still pending when this function is called, this function will wait until they are finished and the queue is empty before sending the command(s). - Parameters io -- [in] LCD panel IO handle, which is created by other factory API like esp_lcd_new_panel_io_spi() lcd_cmd -- [in] The specific LCD command, set to -1 if no command needed param -- [out] Buffer for the command data param_size -- [in] Size of parambuffer - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if read is not supported by transport ESP_OK on success - - esp_err_t esp_lcd_panel_io_tx_param(esp_lcd_panel_io_handle_t io, int lcd_cmd, const void *param, size_t param_size) Transmit LCD command and corresponding parameters. Note Commands sent by this function are short, so they are sent using polling transactions. The function does not return before the command transfer is completed. If any queued transactions sent by esp_lcd_panel_io_tx_color()are still pending when this function is called, this function will wait until they are finished and the queue is empty before sending the command(s). - Parameters io -- [in] LCD panel IO handle, which is created by other factory API like esp_lcd_new_panel_io_spi() lcd_cmd -- [in] The specific LCD command, set to -1 if no command needed param -- [in] Buffer that holds the command specific parameters, set to NULL if no parameter is needed for the command param_size -- [in] Size of paramin memory, in bytes, set to zero if no parameter is needed for the command - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success - - esp_err_t esp_lcd_panel_io_tx_color(esp_lcd_panel_io_handle_t io, int lcd_cmd, const void *color, size_t color_size) Transmit LCD RGB data. Note This function will package the command and RGB data into a transaction, and push into a queue. The real transmission is performed in the background (DMA+interrupt). The caller should take care of the lifecycle of the colorbuffer. Recycling of color buffer should be done in the callback on_color_trans_done(). - Parameters io -- [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() lcd_cmd -- [in] The specific LCD command, set to -1 if no command needed color -- [in] Buffer that holds the RGB color data color_size -- [in] Size of colorin memory, in bytes - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success - - esp_err_t esp_lcd_panel_io_del(esp_lcd_panel_io_handle_t io) Destroy LCD panel IO handle (deinitialize panel and free all corresponding resource) - Parameters io -- [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success - - esp_err_t esp_lcd_panel_io_register_event_callbacks(esp_lcd_panel_io_handle_t io, const esp_lcd_panel_io_callbacks_t *cbs, void *user_ctx) Register LCD panel IO callbacks. - Parameters io -- [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() cbs -- [in] structure with all LCD panel IO callbacks user_ctx -- [in] User private data, passed directly to callback's user_ctx - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success - - esp_err_t esp_lcd_new_panel_io_spi(esp_lcd_spi_bus_handle_t bus, const esp_lcd_panel_io_spi_config_t *io_config, esp_lcd_panel_io_handle_t *ret_io) Create LCD panel IO handle, for SPI interface. - Parameters bus -- [in] SPI bus handle io_config -- [in] IO configuration, for SPI interface ret_io -- [out] Returned IO handle - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success - - esp_err_t esp_lcd_new_panel_io_i2c_v1(uint32_t bus, const esp_lcd_panel_io_i2c_config_t *io_config, esp_lcd_panel_io_handle_t *ret_io) Create LCD panel IO handle, for I2C interface in legacy implementation. Note Please don't call this function in your project directly. Please call esp_lcd_new_panel_to_i2cinstead. - Parameters bus -- [in] I2C bus handle, (in uint32_t) io_config -- [in] IO configuration, for I2C interface ret_io -- [out] Returned IO handle - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success - - esp_err_t esp_lcd_new_panel_io_i2c_v2(i2c_master_bus_handle_t bus, const esp_lcd_panel_io_i2c_config_t *io_config, esp_lcd_panel_io_handle_t *ret_io) Create LCD panel IO handle, for I2C interface in new implementation. Note Please don't call this function in your project directly. Please call esp_lcd_new_panel_to_i2cinstead. - Parameters bus -- [in] I2C bus handle, (in i2c_master_dev_handle_t) io_config -- [in] IO configuration, for I2C interface ret_io -- [out] Returned IO handle - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success - - esp_err_t esp_lcd_new_i80_bus(const esp_lcd_i80_bus_config_t *bus_config, esp_lcd_i80_bus_handle_t *ret_bus) Create Intel 8080 bus handle. - Parameters bus_config -- [in] Bus configuration ret_bus -- [out] Returned bus handle - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_ERR_NOT_FOUND if no free bus is available ESP_OK on success - - esp_err_t esp_lcd_del_i80_bus(esp_lcd_i80_bus_handle_t bus) Destroy Intel 8080 bus handle. - Parameters bus -- [in] Intel 8080 bus handle, created by esp_lcd_new_i80_bus() - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if there still be some device attached to the bus ESP_OK on success - - esp_err_t esp_lcd_new_panel_io_i80(esp_lcd_i80_bus_handle_t bus, const esp_lcd_panel_io_i80_config_t *io_config, esp_lcd_panel_io_handle_t *ret_io) Create LCD panel IO, for Intel 8080 interface. - Parameters bus -- [in] Intel 8080 bus handle, created by esp_lcd_new_i80_bus() io_config -- [in] IO configuration, for i80 interface ret_io -- [out] Returned panel IO handle - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if some configuration can't be satisfied, e.g. pixel clock out of the range ESP_ERR_NO_MEM if out of memory ESP_OK on success - Structures - struct esp_lcd_panel_io_event_data_t Type of LCD panel IO event data. - struct esp_lcd_panel_io_callbacks_t Type of LCD panel IO callbacks. Public Members - esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done Callback invoked when color data transfer has finished - esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done - struct esp_lcd_panel_io_spi_config_t Panel IO configuration structure, for SPI interface. Public Members - int cs_gpio_num GPIO used for CS line - int dc_gpio_num GPIO used to select the D/C line, set this to -1 if the D/C line is not used - int spi_mode Traditional SPI mode (0~3) - unsigned int pclk_hz Frequency of pixel clock - size_t trans_queue_depth Size of internal transaction queue - esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done Callback invoked when color data transfer has finished - void *user_ctx User private data, passed directly to on_color_trans_done's user_ctx - int lcd_cmd_bits Bit-width of LCD command - int lcd_param_bits Bit-width of LCD parameter - unsigned int dc_high_on_cmd If enabled, DC level = 1 indicates command transfer - unsigned int dc_low_on_data If enabled, DC level = 0 indicates color data transfer - unsigned int dc_low_on_param If enabled, DC level = 0 indicates parameter transfer - unsigned int octal_mode transmit with octal mode (8 data lines), this mode is used to simulate Intel 8080 timing - unsigned int quad_mode transmit with quad mode (4 data lines), this mode is useful when transmitting LCD parameters (Only use one line for command) - unsigned int sio_mode Read and write through a single data line (MOSI) - unsigned int lsb_first transmit LSB bit first - unsigned int cs_high_active CS line is high active - struct esp_lcd_panel_io_spi_config_t::[anonymous] flags Extra flags to fine-tune the SPI device - int cs_gpio_num - struct esp_lcd_panel_io_i2c_config_t Panel IO configuration structure, for I2C interface. Public Members - uint32_t dev_addr I2C device address - esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done Callback invoked when color data transfer has finished - void *user_ctx User private data, passed directly to on_color_trans_done's user_ctx - size_t control_phase_bytes I2C LCD panel will encode control information (e.g. D/C selection) into control phase, in several bytes - unsigned int dc_bit_offset Offset of the D/C selection bit in control phase - int lcd_cmd_bits Bit-width of LCD command - int lcd_param_bits Bit-width of LCD parameter - unsigned int dc_low_on_data If this flag is enabled, DC line = 0 means transfer data, DC line = 1 means transfer command; vice versa - unsigned int disable_control_phase If this flag is enabled, the control phase isn't used - struct esp_lcd_panel_io_i2c_config_t::[anonymous] flags Extra flags to fine-tune the I2C device - uint32_t scl_speed_hz I2C LCD SCL frequency (hz) - uint32_t dev_addr - struct esp_lcd_i80_bus_config_t LCD Intel 8080 bus configuration structure. Public Members - int dc_gpio_num GPIO used for D/C line - int wr_gpio_num GPIO used for WR line - lcd_clock_source_t clk_src Clock source for the I80 LCD peripheral - int data_gpio_nums[(24)] GPIOs used for data lines - size_t bus_width Number of data lines, 8 or 16 - size_t max_transfer_bytes Maximum transfer size, this determines the length of internal DMA link - size_t psram_trans_align DMA transfer alignment for data allocated from PSRAM - size_t sram_trans_align DMA transfer alignment for data allocated from SRAM - int dc_gpio_num - struct esp_lcd_panel_io_i80_config_t Panel IO configuration structure, for intel 8080 interface. Public Members - int cs_gpio_num GPIO used for CS line, set to -1 will declaim exclusively use of I80 bus - uint32_t pclk_hz Frequency of pixel clock - size_t trans_queue_depth Transaction queue size, larger queue, higher throughput - esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done Callback invoked when color data was transferred done - void *user_ctx User private data, passed directly to on_color_trans_done's user_ctx - int lcd_cmd_bits Bit-width of LCD command - int lcd_param_bits Bit-width of LCD parameter - unsigned int dc_idle_level Level of DC line in IDLE phase - unsigned int dc_cmd_level Level of DC line in CMD phase - unsigned int dc_dummy_level Level of DC line in DUMMY phase - unsigned int dc_data_level Level of DC line in DATA phase - struct esp_lcd_panel_io_i80_config_t::[anonymous] dc_levels Each i80 device might have its own D/C control logic - unsigned int cs_active_high If set, a high level of CS line will select the device, otherwise, CS line is low level active - unsigned int reverse_color_bits Reverse the data bits, D[N:0] -> D[0:N] - unsigned int swap_color_bytes Swap adjacent two color bytes - unsigned int pclk_active_neg The display will write data lines when there's a falling edge on WR signal (a.k.a the PCLK) - unsigned int pclk_idle_low The WR signal (a.k.a the PCLK) stays at low level in IDLE phase - struct esp_lcd_panel_io_i80_config_t::[anonymous] flags Panel IO config flags - int cs_gpio_num Macros - esp_lcd_new_panel_io_i2c(bus, io_config, ret_io) Create LCD panel IO handle. - Parameters bus -- [in] I2C bus handle io_config -- [in] IO configuration, for I2C interface ret_io -- [out] Returned IO handle - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success - Type Definitions - typedef void *esp_lcd_spi_bus_handle_t Type of LCD SPI bus handle - typedef uint32_t esp_lcd_i2c_bus_handle_t Type of LCD I2C bus handle - typedef struct esp_lcd_i80_bus_t *esp_lcd_i80_bus_handle_t Type of LCD intel 8080 bus handle - typedef bool (*esp_lcd_panel_io_color_trans_done_cb_t)(esp_lcd_panel_io_handle_t panel_io, esp_lcd_panel_io_event_data_t *edata, void *user_ctx) Declare the prototype of the function that will be invoked when panel IO finishes transferring color data. - Param panel_io [in] LCD panel IO handle, which is created by factory API like esp_lcd_new_panel_io_spi() - Param edata [in] Panel IO event data, fed by driver - Param user_ctx [in] User data, passed from esp_lcd_panel_io_xxx_config_t - Return Whether a high priority task has been waken up by this function Header File This header file can be included with: #include "esp_lcd_panel_ops.h" This header file is a part of the API provided by the esp_lcdcomponent. To declare that your component depends on esp_lcd, add the following to your CMakeLists.txt: REQUIRES esp_lcd or PRIV_REQUIRES esp_lcd Functions - esp_err_t esp_lcd_panel_reset(esp_lcd_panel_handle_t panel) Reset LCD panel. Note Panel reset must be called before attempting to initialize the panel using esp_lcd_panel_init(). - Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() - Returns ESP_OK on success - - esp_err_t esp_lcd_panel_init(esp_lcd_panel_handle_t panel) Initialize LCD panel. Note Before calling this function, make sure the LCD panel has finished the resetstage by esp_lcd_panel_reset(). - Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() - Returns ESP_OK on success - - esp_err_t esp_lcd_panel_del(esp_lcd_panel_handle_t panel) Deinitialize the LCD panel. - Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() - Returns ESP_OK on success - - esp_err_t esp_lcd_panel_draw_bitmap(esp_lcd_panel_handle_t panel, int x_start, int y_start, int x_end, int y_end, const void *color_data) Draw bitmap on LCD panel. - Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() x_start -- [in] Start index on x-axis (x_start included) y_start -- [in] Start index on y-axis (y_start included) x_end -- [in] End index on x-axis (x_end not included) y_end -- [in] End index on y-axis (y_end not included) color_data -- [in] RGB color data that will be dumped to the specific window range - - Returns ESP_OK on success - - esp_err_t esp_lcd_panel_mirror(esp_lcd_panel_handle_t panel, bool mirror_x, bool mirror_y) Mirror the LCD panel on specific axis. Note Combined with esp_lcd_panel_swap_xy(), one can realize screen rotation - Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() mirror_x -- [in] Whether the panel will be mirrored about the x axis mirror_y -- [in] Whether the panel will be mirrored about the y axis - - Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel - - esp_err_t esp_lcd_panel_swap_xy(esp_lcd_panel_handle_t panel, bool swap_axes) Swap/Exchange x and y axis. Note Combined with esp_lcd_panel_mirror(), one can realize screen rotation - Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() swap_axes -- [in] Whether to swap the x and y axis - - Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel - - esp_err_t esp_lcd_panel_set_gap(esp_lcd_panel_handle_t panel, int x_gap, int y_gap) Set extra gap in x and y axis. The gap is the space (in pixels) between the left/top sides of the LCD panel and the first row/column respectively of the actual contents displayed. Note Setting a gap is useful when positioning or centering a frame that is smaller than the LCD. - Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() x_gap -- [in] Extra gap on x axis, in pixels y_gap -- [in] Extra gap on y axis, in pixels - - Returns ESP_OK on success - - esp_err_t esp_lcd_panel_invert_color(esp_lcd_panel_handle_t panel, bool invert_color_data) Invert the color (bit-wise invert the color data line) - Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() invert_color_data -- [in] Whether to invert the color data - - Returns ESP_OK on success - - esp_err_t esp_lcd_panel_disp_on_off(esp_lcd_panel_handle_t panel, bool on_off) Turn on or off the display. - Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() on_off -- [in] True to turns on display, False to turns off display - - Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel - - esp_err_t esp_lcd_panel_disp_off(esp_lcd_panel_handle_t panel, bool off) Turn off the display. - Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() off -- [in] Whether to turn off the screen - - Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel - - esp_err_t esp_lcd_panel_disp_sleep(esp_lcd_panel_handle_t panel, bool sleep) Enter or exit sleep mode. - Parameters panel -- [in] LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() sleep -- [in] True to enter sleep mode, False to wake up - - Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel - Header File This header file can be included with: #include "esp_lcd_panel_rgb.h" This header file is a part of the API provided by the esp_lcdcomponent. To declare that your component depends on esp_lcd, add the following to your CMakeLists.txt: REQUIRES esp_lcd or PRIV_REQUIRES esp_lcd Header File This header file can be included with: #include "esp_lcd_panel_vendor.h" This header file is a part of the API provided by the esp_lcdcomponent. To declare that your component depends on esp_lcd, add the following to your CMakeLists.txt: REQUIRES esp_lcd or PRIV_REQUIRES esp_lcd Functions - esp_err_t esp_lcd_new_panel_st7789(const esp_lcd_panel_io_handle_t io, const esp_lcd_panel_dev_config_t *panel_dev_config, esp_lcd_panel_handle_t *ret_panel) Create LCD panel for model ST7789. - Parameters io -- [in] LCD panel IO handle panel_dev_config -- [in] general panel device configuration ret_panel -- [out] Returned LCD panel handle - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success - - esp_err_t esp_lcd_new_panel_nt35510(const esp_lcd_panel_io_handle_t io, const esp_lcd_panel_dev_config_t *panel_dev_config, esp_lcd_panel_handle_t *ret_panel) Create LCD panel for model NT35510. - Parameters io -- [in] LCD panel IO handle panel_dev_config -- [in] general panel device configuration ret_panel -- [out] Returned LCD panel handle - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success - - esp_err_t esp_lcd_new_panel_ssd1306(const esp_lcd_panel_io_handle_t io, const esp_lcd_panel_dev_config_t *panel_dev_config, esp_lcd_panel_handle_t *ret_panel) Create LCD panel for model SSD1306. - Parameters io -- [in] LCD panel IO handle panel_dev_config -- [in] general panel device configuration ret_panel -- [out] Returned LCD panel handle - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NO_MEM if out of memory ESP_OK on success - Structures - struct esp_lcd_panel_dev_config_t Configuration structure for panel device. Public Members - int reset_gpio_num GPIO used to reset the LCD panel, set to -1 if it's not used - lcd_rgb_element_order_t color_space - Deprecated: Set RGB color space, please use rgb_ele_order instead - lcd_rgb_element_order_t rgb_endian - Deprecated: Set RGB data endian, please use rgb_ele_order instead - lcd_rgb_element_order_t rgb_ele_order Set RGB element order, RGB or BGR - lcd_rgb_data_endian_t data_endian Set the data endian for color data larger than 1 byte - unsigned int bits_per_pixel Color depth, in bpp - unsigned int reset_active_high Setting this if the panel reset is high level active - struct esp_lcd_panel_dev_config_t::[anonymous] flags LCD panel config flags - void *vendor_config vendor specific configuration, optional, left as NULL if not used - int reset_gpio_num
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/lcd.html
ESP-IDF Programming Guide v5.2.1 documentation
null
LED Control (LEDC)
null
espressif.com
2016-01-01
940698e61a0ccf8d
null
null
LED Control (LEDC) Introduction The LED control (LEDC) peripheral is primarily designed to control the intensity of LEDs, although it can also be used to generate PWM signals for other purposes. It has 8 channels which can generate independent waveforms that can be used, for example, to drive RGB LED devices. LEDC channels are divided into two groups of 8 channels each. One group of LEDC channels operates in high speed mode. This mode is implemented in hardware and offers automatic and glitch-free changing of the PWM duty cycle. The other group of channels operate in low speed mode, the PWM duty cycle must be changed by the driver in software. Each group of channels is also able to use different clock sources. The PWM controller can automatically increase or decrease the duty cycle gradually, allowing for fades without any processor interference. Functionality Overview Setting up a channel of the LEDC in either high or low speed mode is done in three steps: Timer Configuration by specifying the PWM signal's frequency and duty cycle resolution. Channel Configuration by associating it with the timer and GPIO to output the PWM signal. Change PWM Signal that drives the output in order to change LED's intensity. This can be done under the full control of software or with hardware fading functions. As an optional step, it is also possible to set up an interrupt on fade end. Note For an initial setup, it is recommended to configure for the timers first (by calling ledc_timer_config() ), and then for the channels (by calling ledc_channel_config() ). This ensures the PWM frequency is at the desired value since the appearance of the PWM signal from the IO pad. Timer Configuration Setting the timer is done by calling the function ledc_timer_config() and passing the data structure ledc_timer_config_t that contains the following configuration settings: Speed mode ledc_mode_t Timer number ledc_timer_t PWM signal frequency in Hz Resolution of PWM duty Source clock ledc_clk_cfg_t The frequency and the duty resolution are interdependent. The higher the PWM frequency, the lower the duty resolution which is available, and vice versa. This relationship might be important if you are planning to use this API for purposes other than changing the intensity of LEDs. For more details, see Section Supported Range of Frequency and Duty Resolutions. The source clock can also limit the PWM frequency. The higher the source clock frequency, the higher the maximum PWM frequency can be configured. Clock name Clock freq Speed mode Clock capabilities APB_CLK 80 MHz High / Low / REF_TICK 1 MHz High / Low Dynamic Frequency Scaling compatible RC_FAST_CLK ~ 8 MHz Low Dynamic Frequency Scaling compatible, Light sleep compatible Note On ESP32, if RC_FAST_CLK is chosen as the LEDC clock source, an internal calibration will be performed to get the exact frequency of the clock. This ensures the accuracy of output PWM signal frequency. The LEDC driver offers a helper function ledc_find_suitable_duty_resolution() to find the maximum possible resolution for the timer, given the source clock frequency and the desired PWM signal frequency. When a timer is no longer needed by any channel, it can be deconfigured by calling the same function ledc_timer_config() . The configuration structure ledc_timer_config_t passes in should be: ledc_timer_config_t::speed_mode The speed mode of the timer which wants to be deconfigured belongs to ( ledc_mode_t ) ledc_timer_config_t::timer_num The ID of the timers which wants to be deconfigured ( ledc_timer_t ) ledc_timer_config_t::deconfigure Set this to true so that the timer specified can be deconfigured Channel Configuration When the timer is set up, configure the desired channel (one out of ledc_channel_t ). This is done by calling the function ledc_channel_config() . Similar to the timer configuration, the channel setup function should be passed a structure ledc_channel_config_t that contains the channel's configuration parameters. At this point, the channel should start operating and generating the PWM signal on the selected GPIO, as configured in ledc_channel_config_t , with the frequency specified in the timer settings and the given duty cycle. The channel operation (signal generation) can be suspended at any time by calling the function ledc_stop() . Change PWM Signal Once the channel starts operating and generating the PWM signal with the constant duty cycle and frequency, there are a couple of ways to change this signal. When driving LEDs, primarily the duty cycle is changed to vary the light intensity. The following two sections describe how to change the duty cycle using software and hardware fading. If required, the signal's frequency can also be changed; it is covered in Section Change PWM Frequency. Change PWM Duty Cycle Using Software To set the duty cycle, use the dedicated function ledc_set_duty() . After that, call ledc_update_duty() to activate the changes. To check the currently set value, use the corresponding _get_ function ledc_get_duty() . Another way to set the duty cycle, as well as some other channel parameters, is by calling ledc_channel_config() covered in Section Channel Configuration. The range of the duty cycle values passed to functions depends on selected duty_resolution and should be from 0 to (2 ** duty_resolution) . For example, if the selected duty resolution is 10, then the duty cycle values can range from 0 to 1024. This provides the resolution of ~ 0.1%. Warning On ESP32, when channel's binded timer selects its maximum duty resolution, the duty cycle value cannot be set to (2 ** duty_resolution) . Otherwise, the internal duty counter in the hardware will overflow and be messed up. Change PWM Duty Cycle Using Hardware The LEDC hardware provides the means to gradually transition from one duty cycle value to another. To use this functionality, enable fading with ledc_fade_func_install() and then configure it by calling one of the available fading functions: Start fading with ledc_fade_start() . A fade can be operated in blocking or non-blocking mode, please check ledc_fade_mode_t for the difference between the two available fade modes. Note that with either fade mode, the next fade or fixed-duty update will not take effect until the last fade finishes. Due to hardware limitations, there is no way to stop a fade before it reaches its target duty. To get a notification about the completion of a fade operation, a fade end callback function can be registered for each channel by calling ledc_cb_register() after the fade service being installed. The fade end callback prototype is defined in ledc_cb_t , where you should return a boolean value from the callback function, indicating whether a high priority task is woken up by this callback function. It is worth mentioning, the callback and the function invoked by itself should be placed in IRAM, as the interrupt service routine is in IRAM. ledc_cb_register() will print a warning message if it finds the addresses of callback and user context are incorrect. If not required anymore, fading and an associated interrupt can be disabled with ledc_fade_func_uninstall() . Change PWM Frequency The LEDC API provides several ways to change the PWM frequency "on the fly": Set the frequency by calling ledc_set_freq() . There is a corresponding function ledc_get_freq() to check the current frequency. Change the frequency and the duty resolution by calling ledc_bind_channel_timer() to bind some other timer to the channel. Change the channel's timer by calling ledc_channel_config() . More Control Over PWM There are several lower level timer-specific functions that can be used to change PWM settings: The first two functions are called "behind the scenes" by ledc_channel_config() to provide a startup of a timer after it is configured. Use Interrupts When configuring an LEDC channel, one of the parameters selected within ledc_channel_config_t is ledc_intr_type_t which triggers an interrupt on fade completion. For registration of a handler to address this interrupt, call ledc_isr_register() . LEDC High and Low Speed Mode High speed mode enables a glitch-free changeover of timer settings. This means that if the timer settings are modified, the changes will be applied automatically on the next overflow interrupt of the timer. In contrast, when updating the low-speed timer, the change of settings should be explicitly triggered by software. The LEDC driver handles it in the background, e.g., when ledc_timer_config() or ledc_timer_set() is called. For additional details regarding speed modes, see ESP32 Technical Reference Manual > LED PWM Controller (LEDC) [PDF]. Supported Range of Frequency and Duty Resolutions The LED PWM Controller is designed primarily to drive LEDs. It provides a large flexibility of PWM duty cycle settings. For instance, the PWM frequency of 5 kHz can have the maximum duty resolution of 13 bits. This means that the duty can be set anywhere from 0 to 100% with a resolution of ~ 0.012% (2 ** 13 = 8192 discrete levels of the LED intensity). Note, however, that these parameters depend on the clock signal clocking the LED PWM Controller timer which in turn clocks the channel (see timer configuration and the ESP32 Technical Reference Manual > LED PWM Controller (LEDC) [PDF]). The LEDC can be used for generating signals at much higher frequencies that are sufficient enough to clock other devices, e.g., a digital camera module. In this case, the maximum available frequency is 40 MHz with duty resolution of 1 bit. This means that the duty cycle is fixed at 50% and cannot be adjusted. The LEDC API is designed to report an error when trying to set a frequency and a duty resolution that exceed the range of LEDC's hardware. For example, an attempt to set the frequency to 20 MHz and the duty resolution to 3 bits results in the following error reported on a serial monitor: E (196) ledc: requested frequency and duty resolution cannot be achieved, try reducing freq_hz or duty_resolution. div_param=128 In such a situation, either the duty resolution or the frequency must be reduced. For example, setting the duty resolution to 2 resolves this issue and makes it possible to set the duty cycle at 25% steps, i.e., at 25%, 50% or 75%. The LEDC driver also captures and reports attempts to configure frequency/duty resolution combinations that are below the supported minimum, e.g.,: E (196) ledc: requested frequency and duty resolution cannot be achieved, try increasing freq_hz or duty_resolution. div_param=128000000 The duty resolution is normally set using ledc_timer_bit_t . This enumeration covers the range from 10 to 15 bits. If a smaller duty resolution is required (from 10 down to 1), enter the equivalent numeric values directly. Application Example The LEDC basic example: peripherals/ledc/ledc_basic. The LEDC change duty cycle and fading control example: peripherals/ledc/ledc_fade. API Reference Header File This header file can be included with: #include "driver/ledc.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t ledc_channel_config(const ledc_channel_config_t *ledc_conf) LEDC channel configuration Configure LEDC channel with the given channel/output gpio_num/interrupt/source timer/frequency(Hz)/LEDC duty. Parameters ledc_conf -- Pointer of LEDC channel configure struct Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters ledc_conf -- Pointer of LEDC channel configure struct Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error uint32_t ledc_find_suitable_duty_resolution(uint32_t src_clk_freq, uint32_t timer_freq) Helper function to find the maximum possible duty resolution in bits for ledc_timer_config() Parameters src_clk_freq -- LEDC timer source clock frequency (Hz) (See doxygen comments of ledc_clk_cfg_t or get from esp_clk_tree_src_get_freq_hz ) timer_freq -- Desired LEDC timer frequency (Hz) src_clk_freq -- LEDC timer source clock frequency (Hz) (See doxygen comments of ledc_clk_cfg_t or get from esp_clk_tree_src_get_freq_hz ) timer_freq -- Desired LEDC timer frequency (Hz) src_clk_freq -- LEDC timer source clock frequency (Hz) (See doxygen comments of ledc_clk_cfg_t or get from esp_clk_tree_src_get_freq_hz ) Returns 0 The timer frequency cannot be achieved Others The largest duty resolution value to be set 0 The timer frequency cannot be achieved Others The largest duty resolution value to be set 0 The timer frequency cannot be achieved Parameters src_clk_freq -- LEDC timer source clock frequency (Hz) (See doxygen comments of ledc_clk_cfg_t or get from esp_clk_tree_src_get_freq_hz ) timer_freq -- Desired LEDC timer frequency (Hz) Returns 0 The timer frequency cannot be achieved Others The largest duty resolution value to be set esp_err_t ledc_timer_config(const ledc_timer_config_t *timer_conf) LEDC timer configuration Configure LEDC timer with the given source timer/frequency(Hz)/duty_resolution. Parameters timer_conf -- Pointer of LEDC timer configure struct Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Can not find a proper pre-divider number base on the given frequency and the current duty_resolution. ESP_ERR_INVALID_STATE Timer cannot be de-configured because timer is not configured or is not paused ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Can not find a proper pre-divider number base on the given frequency and the current duty_resolution. ESP_ERR_INVALID_STATE Timer cannot be de-configured because timer is not configured or is not paused ESP_OK Success Parameters timer_conf -- Pointer of LEDC timer configure struct Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Can not find a proper pre-divider number base on the given frequency and the current duty_resolution. ESP_ERR_INVALID_STATE Timer cannot be de-configured because timer is not configured or is not paused esp_err_t ledc_update_duty(ledc_mode_t speed_mode, ledc_channel_t channel) LEDC update channel parameters. Note Call this function to activate the LEDC updated parameters. After ledc_set_duty, we need to call this function to update the settings. And the new LEDC parameters don't take effect until the next PWM cycle. Note ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_duty_and_update Note If CONFIG_LEDC_CTRL_FUNC_IN_IRAM is enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Cache is disabled. Note This function is allowed to run within ISR context. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t ledc_set_pin(int gpio_num, ledc_mode_t speed_mode, ledc_channel_t ledc_channel) Set LEDC output gpio. Note This function only routes the LEDC signal to GPIO through matrix, other LEDC resources initialization are not involved. Please use ledc_channel_config() instead to fully configure a LEDC channel. Parameters gpio_num -- The LEDC output gpio speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. ledc_channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t gpio_num -- The LEDC output gpio speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. ledc_channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t gpio_num -- The LEDC output gpio Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters gpio_num -- The LEDC output gpio speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. ledc_channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t ledc_stop(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t idle_level) LEDC stop. Disable LEDC output, and set idle level. Note If CONFIG_LEDC_CTRL_FUNC_IN_IRAM is enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Cache is disabled. Note This function is allowed to run within ISR context. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t idle_level -- Set output idle level after LEDC stops. speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t idle_level -- Set output idle level after LEDC stops. speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t idle_level -- Set output idle level after LEDC stops. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t ledc_set_freq(ledc_mode_t speed_mode, ledc_timer_t timer_num, uint32_t freq_hz) LEDC set channel frequency (Hz) Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_num -- LEDC timer index (0-3), select from ledc_timer_t freq_hz -- Set the LEDC frequency speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_num -- LEDC timer index (0-3), select from ledc_timer_t freq_hz -- Set the LEDC frequency speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Can not find a proper pre-divider number base on the given frequency and the current duty_resolution. ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Can not find a proper pre-divider number base on the given frequency and the current duty_resolution. ESP_OK Success Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_num -- LEDC timer index (0-3), select from ledc_timer_t freq_hz -- Set the LEDC frequency Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Can not find a proper pre-divider number base on the given frequency and the current duty_resolution. uint32_t ledc_get_freq(ledc_mode_t speed_mode, ledc_timer_t timer_num) LEDC get channel frequency (Hz) Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_num -- LEDC timer index (0-3), select from ledc_timer_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_num -- LEDC timer index (0-3), select from ledc_timer_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns 0 error Others Current LEDC frequency 0 error Others Current LEDC frequency 0 error Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_num -- LEDC timer index (0-3), select from ledc_timer_t Returns 0 error Others Current LEDC frequency esp_err_t ledc_set_duty_with_hpoint(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty, uint32_t hpoint) LEDC set duty and hpoint value Only after calling ledc_update_duty will the duty update. Note ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_duty_and_update Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)] hpoint -- Set the LEDC hpoint value, the range is [0, (2**duty_resolution)-1] speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)] hpoint -- Set the LEDC hpoint value, the range is [0, (2**duty_resolution)-1] speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)] hpoint -- Set the LEDC hpoint value, the range is [0, (2**duty_resolution)-1] Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error int ledc_get_hpoint(ledc_mode_t speed_mode, ledc_channel_t channel) LEDC get hpoint value, the counter value when the output is set high level. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns LEDC_ERR_VAL if parameter error Others Current hpoint value of LEDC channel LEDC_ERR_VAL if parameter error Others Current hpoint value of LEDC channel LEDC_ERR_VAL if parameter error Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t Returns LEDC_ERR_VAL if parameter error Others Current hpoint value of LEDC channel esp_err_t ledc_set_duty(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty) LEDC set duty This function do not change the hpoint value of this channel. if needed, please call ledc_set_duty_with_hpoint. only after calling ledc_update_duty will the duty update. Note ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_duty_and_update. Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)] speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)] speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)] Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error uint32_t ledc_get_duty(ledc_mode_t speed_mode, ledc_channel_t channel) LEDC get duty This function returns the duty at the present PWM cycle. You shouldn't expect the function to return the new duty in the same cycle of calling ledc_update_duty, because duty update doesn't take effect until the next cycle. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns LEDC_ERR_DUTY if parameter error Others Current LEDC duty LEDC_ERR_DUTY if parameter error Others Current LEDC duty LEDC_ERR_DUTY if parameter error Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t Returns LEDC_ERR_DUTY if parameter error Others Current LEDC duty esp_err_t ledc_set_fade(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty, ledc_duty_direction_t fade_direction, uint32_t step_num, uint32_t duty_cycle_num, uint32_t duty_scale) LEDC set gradient Set LEDC gradient, After the function calls the ledc_update_duty function, the function can take effect. Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the start of the gradient duty, the range of duty setting is [0, (2**duty_resolution)] fade_direction -- Set the direction of the gradient step_num -- Set the number of the gradient duty_cycle_num -- Set how many LEDC tick each time the gradient lasts duty_scale -- Set gradient change amplitude speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the start of the gradient duty, the range of duty setting is [0, (2**duty_resolution)] fade_direction -- Set the direction of the gradient step_num -- Set the number of the gradient duty_cycle_num -- Set how many LEDC tick each time the gradient lasts duty_scale -- Set gradient change amplitude speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the start of the gradient duty, the range of duty setting is [0, (2**duty_resolution)] fade_direction -- Set the direction of the gradient step_num -- Set the number of the gradient duty_cycle_num -- Set how many LEDC tick each time the gradient lasts duty_scale -- Set gradient change amplitude Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t ledc_isr_register(void (*fn)(void*), void *arg, int intr_alloc_flags, ledc_isr_handle_t *handle) Register LEDC interrupt handler, the handler is an ISR. The handler will be attached to the same CPU core that this function is running on. Parameters fn -- Interrupt handler function. arg -- User-supplied argument passed to the handler function. intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. handle -- Pointer to return handle. If non-NULL, a handle for the interrupt will be returned here. fn -- Interrupt handler function. arg -- User-supplied argument passed to the handler function. intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. handle -- Pointer to return handle. If non-NULL, a handle for the interrupt will be returned here. fn -- Interrupt handler function. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_NOT_FOUND Failed to find available interrupt source ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_NOT_FOUND Failed to find available interrupt source ESP_OK Success Parameters fn -- Interrupt handler function. arg -- User-supplied argument passed to the handler function. intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. handle -- Pointer to return handle. If non-NULL, a handle for the interrupt will be returned here. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_NOT_FOUND Failed to find available interrupt source esp_err_t ledc_timer_set(ledc_mode_t speed_mode, ledc_timer_t timer_sel, uint32_t clock_divider, uint32_t duty_resolution, ledc_clk_src_t clk_src) Configure LEDC settings. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- Timer index (0-3), there are 4 timers in LEDC module clock_divider -- Timer clock divide value, the timer clock is divided from the selected clock source duty_resolution -- Resolution of duty setting in number of bits. The range is [1, SOC_LEDC_TIMER_BIT_WIDTH] clk_src -- Select LEDC source clock. speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- Timer index (0-3), there are 4 timers in LEDC module clock_divider -- Timer clock divide value, the timer clock is divided from the selected clock source duty_resolution -- Resolution of duty setting in number of bits. The range is [1, SOC_LEDC_TIMER_BIT_WIDTH] clk_src -- Select LEDC source clock. speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns (-1) Parameter error Other Current LEDC duty (-1) Parameter error Other Current LEDC duty (-1) Parameter error Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- Timer index (0-3), there are 4 timers in LEDC module clock_divider -- Timer clock divide value, the timer clock is divided from the selected clock source duty_resolution -- Resolution of duty setting in number of bits. The range is [1, SOC_LEDC_TIMER_BIT_WIDTH] clk_src -- Select LEDC source clock. Returns (-1) Parameter error Other Current LEDC duty esp_err_t ledc_timer_rst(ledc_mode_t speed_mode, ledc_timer_t timer_sel) Reset LEDC timer. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- LEDC timer index (0-3), select from ledc_timer_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- LEDC timer index (0-3), select from ledc_timer_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- LEDC timer index (0-3), select from ledc_timer_t Returns ESP_ERR_INVALID_ARG Parameter error ESP_OK Success esp_err_t ledc_timer_pause(ledc_mode_t speed_mode, ledc_timer_t timer_sel) Pause LEDC timer counter. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- LEDC timer index (0-3), select from ledc_timer_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- LEDC timer index (0-3), select from ledc_timer_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- LEDC timer index (0-3), select from ledc_timer_t Returns ESP_ERR_INVALID_ARG Parameter error ESP_OK Success esp_err_t ledc_timer_resume(ledc_mode_t speed_mode, ledc_timer_t timer_sel) Resume LEDC timer. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- LEDC timer index (0-3), select from ledc_timer_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- LEDC timer index (0-3), select from ledc_timer_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- LEDC timer index (0-3), select from ledc_timer_t Returns ESP_ERR_INVALID_ARG Parameter error ESP_OK Success esp_err_t ledc_bind_channel_timer(ledc_mode_t speed_mode, ledc_channel_t channel, ledc_timer_t timer_sel) Bind LEDC channel with the selected timer. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t timer_sel -- LEDC timer index (0-3), select from ledc_timer_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t timer_sel -- LEDC timer index (0-3), select from ledc_timer_t speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t timer_sel -- LEDC timer index (0-3), select from ledc_timer_t Returns ESP_ERR_INVALID_ARG Parameter error ESP_OK Success esp_err_t ledc_set_fade_with_step(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, uint32_t scale, uint32_t cycle_num) Set LEDC fade function. Note Call ledc_fade_func_install() once before calling this function. Call ledc_fade_start() after this to start fading. Note ledc_set_fade_with_step, ledc_set_fade_with_time and ledc_fade_start are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_fade_step_and_start Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] scale -- Controls the increase or decrease step scale. cycle_num -- increase or decrease the duty every cycle_num cycles speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] scale -- Controls the increase or decrease step scale. cycle_num -- increase or decrease the duty every cycle_num cycles speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error ESP_OK Success Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] scale -- Controls the increase or decrease step scale. cycle_num -- increase or decrease the duty every cycle_num cycles Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error esp_err_t ledc_set_fade_with_time(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, int max_fade_time_ms) Set LEDC fade function, with a limited time. Note Call ledc_fade_func_install() once before calling this function. Call ledc_fade_start() after this to start fading. Note ledc_set_fade_with_step, ledc_set_fade_with_time and ledc_fade_start are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_fade_step_and_start Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] max_fade_time_ms -- The maximum time of the fading ( ms ). speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] max_fade_time_ms -- The maximum time of the fading ( ms ). speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error ESP_OK Success Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] max_fade_time_ms -- The maximum time of the fading ( ms ). Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error esp_err_t ledc_fade_func_install(int intr_alloc_flags) Install LEDC fade function. This function will occupy interrupt of LEDC module. Parameters intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. Returns ESP_OK Success ESP_ERR_INVALID_ARG Intr flag error ESP_ERR_NOT_FOUND Failed to find available interrupt source ESP_ERR_INVALID_STATE Fade function already installed ESP_OK Success ESP_ERR_INVALID_ARG Intr flag error ESP_ERR_NOT_FOUND Failed to find available interrupt source ESP_ERR_INVALID_STATE Fade function already installed ESP_OK Success Parameters intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. Returns ESP_OK Success ESP_ERR_INVALID_ARG Intr flag error ESP_ERR_NOT_FOUND Failed to find available interrupt source ESP_ERR_INVALID_STATE Fade function already installed void ledc_fade_func_uninstall(void) Uninstall LEDC fade function. esp_err_t ledc_fade_start(ledc_mode_t speed_mode, ledc_channel_t channel, ledc_fade_mode_t fade_mode) Start LEDC fading. Note Call ledc_fade_func_install() once before calling this function. Call this API right after ledc_set_fade_with_time or ledc_set_fade_with_step before to start fading. Note Starting fade operation with this API is not thread-safe, use with care. Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel number fade_mode -- Whether to block until fading done. See ledc_types.h ledc_fade_mode_t for more info. Note that this function will not return until fading to the target duty if LEDC_FADE_WAIT_DONE mode is selected. speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel number fade_mode -- Whether to block until fading done. See ledc_types.h ledc_fade_mode_t for more info. Note that this function will not return until fading to the target duty if LEDC_FADE_WAIT_DONE mode is selected. speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_OK Success ESP_ERR_INVALID_STATE Channel not initialized or fade function not installed. ESP_ERR_INVALID_ARG Parameter error. ESP_OK Success ESP_ERR_INVALID_STATE Channel not initialized or fade function not installed. ESP_ERR_INVALID_ARG Parameter error. ESP_OK Success Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel number fade_mode -- Whether to block until fading done. See ledc_types.h ledc_fade_mode_t for more info. Note that this function will not return until fading to the target duty if LEDC_FADE_WAIT_DONE mode is selected. Returns ESP_OK Success ESP_ERR_INVALID_STATE Channel not initialized or fade function not installed. ESP_ERR_INVALID_ARG Parameter error. esp_err_t ledc_set_duty_and_update(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty, uint32_t hpoint) A thread-safe API to set duty for LEDC channel and return when duty updated. Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)] hpoint -- Set the LEDC hpoint value, the range is [0, (2**duty_resolution)-1] speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)] hpoint -- Set the LEDC hpoint value, the range is [0, (2**duty_resolution)-1] speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_OK Success ESP_ERR_INVALID_STATE Channel not initialized ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Fade function init error ESP_OK Success ESP_ERR_INVALID_STATE Channel not initialized ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Fade function init error ESP_OK Success Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)] hpoint -- Set the LEDC hpoint value, the range is [0, (2**duty_resolution)-1] Returns ESP_OK Success ESP_ERR_INVALID_STATE Channel not initialized ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Fade function init error esp_err_t ledc_set_fade_time_and_start(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, uint32_t max_fade_time_ms, ledc_fade_mode_t fade_mode) A thread-safe API to set and start LEDC fade function, with a limited time. Note Call ledc_fade_func_install() once, before calling this function. Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] max_fade_time_ms -- The maximum time of the fading ( ms ). fade_mode -- choose blocking or non-blocking mode speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] max_fade_time_ms -- The maximum time of the fading ( ms ). fade_mode -- choose blocking or non-blocking mode speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error ESP_OK Success Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] max_fade_time_ms -- The maximum time of the fading ( ms ). fade_mode -- choose blocking or non-blocking mode Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error esp_err_t ledc_set_fade_step_and_start(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, uint32_t scale, uint32_t cycle_num, ledc_fade_mode_t fade_mode) A thread-safe API to set and start LEDC fade function. Note Call ledc_fade_func_install() once before calling this function. Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] scale -- Controls the increase or decrease step scale. cycle_num -- increase or decrease the duty every cycle_num cycles fade_mode -- choose blocking or non-blocking mode speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] scale -- Controls the increase or decrease step scale. cycle_num -- increase or decrease the duty every cycle_num cycles fade_mode -- choose blocking or non-blocking mode speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error ESP_OK Success Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] scale -- Controls the increase or decrease step scale. cycle_num -- increase or decrease the duty every cycle_num cycles fade_mode -- choose blocking or non-blocking mode Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error esp_err_t ledc_cb_register(ledc_mode_t speed_mode, ledc_channel_t channel, ledc_cbs_t *cbs, void *user_arg) LEDC callback registration function. Note The callback is called from an ISR, it must never attempt to block, and any FreeRTOS API called must be ISR capable. Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t cbs -- Group of LEDC callback functions user_arg -- user registered data for the callback function speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t cbs -- Group of LEDC callback functions user_arg -- user registered data for the callback function speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error ESP_OK Success Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t cbs -- Group of LEDC callback functions user_arg -- user registered data for the callback function Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error Structures struct ledc_channel_config_t Configuration parameters of LEDC channel for ledc_channel_config function. Public Members int gpio_num the LEDC output gpio_num, if you want to use gpio16, gpio_num = 16 int gpio_num the LEDC output gpio_num, if you want to use gpio16, gpio_num = 16 ledc_mode_t speed_mode LEDC speed speed_mode, high-speed mode (only exists on esp32) or low-speed mode ledc_mode_t speed_mode LEDC speed speed_mode, high-speed mode (only exists on esp32) or low-speed mode ledc_channel_t channel LEDC channel (0 - LEDC_CHANNEL_MAX-1) ledc_channel_t channel LEDC channel (0 - LEDC_CHANNEL_MAX-1) ledc_intr_type_t intr_type configure interrupt, Fade interrupt enable or Fade interrupt disable ledc_intr_type_t intr_type configure interrupt, Fade interrupt enable or Fade interrupt disable ledc_timer_t timer_sel Select the timer source of channel (0 - LEDC_TIMER_MAX-1) ledc_timer_t timer_sel Select the timer source of channel (0 - LEDC_TIMER_MAX-1) uint32_t duty LEDC channel duty, the range of duty setting is [0, (2**duty_resolution)] uint32_t duty LEDC channel duty, the range of duty setting is [0, (2**duty_resolution)] int hpoint LEDC channel hpoint value, the range is [0, (2**duty_resolution)-1] int hpoint LEDC channel hpoint value, the range is [0, (2**duty_resolution)-1] unsigned int output_invert Enable (1) or disable (0) gpio output invert unsigned int output_invert Enable (1) or disable (0) gpio output invert struct ledc_channel_config_t::[anonymous] flags LEDC flags struct ledc_channel_config_t::[anonymous] flags LEDC flags int gpio_num struct ledc_timer_config_t Configuration parameters of LEDC timer for ledc_timer_config function. Public Members ledc_mode_t speed_mode LEDC speed speed_mode, high-speed mode (only exists on esp32) or low-speed mode ledc_mode_t speed_mode LEDC speed speed_mode, high-speed mode (only exists on esp32) or low-speed mode ledc_timer_bit_t duty_resolution LEDC channel duty resolution ledc_timer_bit_t duty_resolution LEDC channel duty resolution ledc_timer_t timer_num The timer source of channel (0 - LEDC_TIMER_MAX-1) ledc_timer_t timer_num The timer source of channel (0 - LEDC_TIMER_MAX-1) uint32_t freq_hz LEDC timer frequency (Hz) uint32_t freq_hz LEDC timer frequency (Hz) ledc_clk_cfg_t clk_cfg Configure LEDC source clock from ledc_clk_cfg_t. Note that LEDC_USE_RC_FAST_CLK and LEDC_USE_XTAL_CLK are non-timer-specific clock sources. You can not have one LEDC timer uses RC_FAST_CLK as the clock source and have another LEDC timer uses XTAL_CLK as its clock source. All chips except esp32 and esp32s2 do not have timer-specific clock sources, which means clock source for all timers must be the same one. ledc_clk_cfg_t clk_cfg Configure LEDC source clock from ledc_clk_cfg_t. Note that LEDC_USE_RC_FAST_CLK and LEDC_USE_XTAL_CLK are non-timer-specific clock sources. You can not have one LEDC timer uses RC_FAST_CLK as the clock source and have another LEDC timer uses XTAL_CLK as its clock source. All chips except esp32 and esp32s2 do not have timer-specific clock sources, which means clock source for all timers must be the same one. bool deconfigure Set this field to de-configure a LEDC timer which has been configured before Note that it will not check whether the timer wants to be de-configured is binded to any channel. Also, the timer has to be paused first before it can be de-configured. When this field is set, duty_resolution, freq_hz, clk_cfg fields are ignored. bool deconfigure Set this field to de-configure a LEDC timer which has been configured before Note that it will not check whether the timer wants to be de-configured is binded to any channel. Also, the timer has to be paused first before it can be de-configured. When this field is set, duty_resolution, freq_hz, clk_cfg fields are ignored. ledc_mode_t speed_mode struct ledc_cb_param_t LEDC callback parameter. Public Members ledc_cb_event_t event Event name ledc_cb_event_t event Event name uint32_t speed_mode Speed mode of the LEDC channel group uint32_t speed_mode Speed mode of the LEDC channel group uint32_t channel LEDC channel (0 - LEDC_CHANNEL_MAX-1) uint32_t channel LEDC channel (0 - LEDC_CHANNEL_MAX-1) uint32_t duty LEDC current duty of the channel, the range of duty is [0, (2**duty_resolution)] uint32_t duty LEDC current duty of the channel, the range of duty is [0, (2**duty_resolution)] ledc_cb_event_t event struct ledc_cbs_t Group of supported LEDC callbacks. Note The callbacks are all running under ISR environment Macros LEDC_APB_CLK_HZ Frequency of one of the LEDC peripheral clock sources, APB_CLK. Note This macro should have no use in your application, we keep it here only for backward compatible LEDC_REF_CLK_HZ Frequency of one of the LEDC peripheral clock sources, REF_TICK. Note This macro should have no use in your application, we keep it here only for backward compatible LEDC_ERR_DUTY LEDC_ERR_VAL Type Definitions typedef intr_handle_t ledc_isr_handle_t typedef bool (*ledc_cb_t)(const ledc_cb_param_t *param, void *user_arg) Type of LEDC event callback. Param param LEDC callback parameter Param user_arg User registered data Return Whether a high priority task has been waken up by this function Param param LEDC callback parameter Param user_arg User registered data Return Whether a high priority task has been waken up by this function Enumerations Header File This header file can be included with: #include "hal/ledc_types.h" Type Definitions typedef soc_periph_ledc_clk_src_legacy_t ledc_clk_cfg_t LEDC clock source configuration struct. In theory, the following enumeration shall be placed in LEDC driver's header. However, as the next enumeration, ledc_clk_src_t , makes the use of some of these values and to avoid mutual inclusion of the headers, we must define it here. Enumerations enum ledc_mode_t Values: enumerator LEDC_HIGH_SPEED_MODE LEDC high speed speed_mode enumerator LEDC_HIGH_SPEED_MODE LEDC high speed speed_mode enumerator LEDC_LOW_SPEED_MODE LEDC low speed speed_mode enumerator LEDC_LOW_SPEED_MODE LEDC low speed speed_mode enumerator LEDC_SPEED_MODE_MAX LEDC speed limit enumerator LEDC_SPEED_MODE_MAX LEDC speed limit enumerator LEDC_HIGH_SPEED_MODE enum ledc_intr_type_t Values: enumerator LEDC_INTR_DISABLE Disable LEDC interrupt enumerator LEDC_INTR_DISABLE Disable LEDC interrupt enumerator LEDC_INTR_FADE_END Enable LEDC interrupt enumerator LEDC_INTR_FADE_END Enable LEDC interrupt enumerator LEDC_INTR_MAX enumerator LEDC_INTR_MAX enumerator LEDC_INTR_DISABLE enum ledc_duty_direction_t Values: enumerator LEDC_DUTY_DIR_DECREASE LEDC duty decrease direction enumerator LEDC_DUTY_DIR_DECREASE LEDC duty decrease direction enumerator LEDC_DUTY_DIR_INCREASE LEDC duty increase direction enumerator LEDC_DUTY_DIR_INCREASE LEDC duty increase direction enumerator LEDC_DUTY_DIR_MAX enumerator LEDC_DUTY_DIR_MAX enumerator LEDC_DUTY_DIR_DECREASE enum ledc_slow_clk_sel_t LEDC global clock sources. Values: enumerator LEDC_SLOW_CLK_RC_FAST LEDC low speed timer clock source is RC_FAST clock enumerator LEDC_SLOW_CLK_RC_FAST LEDC low speed timer clock source is RC_FAST clock enumerator LEDC_SLOW_CLK_APB LEDC low speed timer clock source is 80MHz APB clock enumerator LEDC_SLOW_CLK_APB LEDC low speed timer clock source is 80MHz APB clock enumerator LEDC_SLOW_CLK_RTC8M Alias of 'LEDC_SLOW_CLK_RC_FAST' enumerator LEDC_SLOW_CLK_RTC8M Alias of 'LEDC_SLOW_CLK_RC_FAST' enumerator LEDC_SLOW_CLK_RC_FAST enum ledc_clk_src_t LEDC timer-specific clock sources. Note: Setting numeric values to match ledc_clk_cfg_t values are a hack to avoid collision with LEDC_AUTO_CLK in the driver, as these enums have very similar names and user may pass one of these by mistake. Values: enumerator LEDC_REF_TICK LEDC timer clock divided from reference tick (1Mhz) enumerator LEDC_REF_TICK LEDC timer clock divided from reference tick (1Mhz) enumerator LEDC_APB_CLK LEDC timer clock divided from APB clock (80Mhz) enumerator LEDC_APB_CLK LEDC timer clock divided from APB clock (80Mhz) enumerator LEDC_SCLK Selecting this value for LEDC_TICK_SEL_TIMER let the hardware take its source clock from LEDC_APB_CLK_SEL enumerator LEDC_SCLK Selecting this value for LEDC_TICK_SEL_TIMER let the hardware take its source clock from LEDC_APB_CLK_SEL enumerator LEDC_REF_TICK enum ledc_timer_t Values: enumerator LEDC_TIMER_0 LEDC timer 0 enumerator LEDC_TIMER_0 LEDC timer 0 enumerator LEDC_TIMER_1 LEDC timer 1 enumerator LEDC_TIMER_1 LEDC timer 1 enumerator LEDC_TIMER_2 LEDC timer 2 enumerator LEDC_TIMER_2 LEDC timer 2 enumerator LEDC_TIMER_3 LEDC timer 3 enumerator LEDC_TIMER_3 LEDC timer 3 enumerator LEDC_TIMER_MAX enumerator LEDC_TIMER_MAX enumerator LEDC_TIMER_0 enum ledc_channel_t Values: enumerator LEDC_CHANNEL_0 LEDC channel 0 enumerator LEDC_CHANNEL_0 LEDC channel 0 enumerator LEDC_CHANNEL_1 LEDC channel 1 enumerator LEDC_CHANNEL_1 LEDC channel 1 enumerator LEDC_CHANNEL_2 LEDC channel 2 enumerator LEDC_CHANNEL_2 LEDC channel 2 enumerator LEDC_CHANNEL_3 LEDC channel 3 enumerator LEDC_CHANNEL_3 LEDC channel 3 enumerator LEDC_CHANNEL_4 LEDC channel 4 enumerator LEDC_CHANNEL_4 LEDC channel 4 enumerator LEDC_CHANNEL_5 LEDC channel 5 enumerator LEDC_CHANNEL_5 LEDC channel 5 enumerator LEDC_CHANNEL_6 LEDC channel 6 enumerator LEDC_CHANNEL_6 LEDC channel 6 enumerator LEDC_CHANNEL_7 LEDC channel 7 enumerator LEDC_CHANNEL_7 LEDC channel 7 enumerator LEDC_CHANNEL_MAX enumerator LEDC_CHANNEL_MAX enumerator LEDC_CHANNEL_0 enum ledc_timer_bit_t Values: enumerator LEDC_TIMER_1_BIT LEDC PWM duty resolution of 1 bits enumerator LEDC_TIMER_1_BIT LEDC PWM duty resolution of 1 bits enumerator LEDC_TIMER_2_BIT LEDC PWM duty resolution of 2 bits enumerator LEDC_TIMER_2_BIT LEDC PWM duty resolution of 2 bits enumerator LEDC_TIMER_3_BIT LEDC PWM duty resolution of 3 bits enumerator LEDC_TIMER_3_BIT LEDC PWM duty resolution of 3 bits enumerator LEDC_TIMER_4_BIT LEDC PWM duty resolution of 4 bits enumerator LEDC_TIMER_4_BIT LEDC PWM duty resolution of 4 bits enumerator LEDC_TIMER_5_BIT LEDC PWM duty resolution of 5 bits enumerator LEDC_TIMER_5_BIT LEDC PWM duty resolution of 5 bits enumerator LEDC_TIMER_6_BIT LEDC PWM duty resolution of 6 bits enumerator LEDC_TIMER_6_BIT LEDC PWM duty resolution of 6 bits enumerator LEDC_TIMER_7_BIT LEDC PWM duty resolution of 7 bits enumerator LEDC_TIMER_7_BIT LEDC PWM duty resolution of 7 bits enumerator LEDC_TIMER_8_BIT LEDC PWM duty resolution of 8 bits enumerator LEDC_TIMER_8_BIT LEDC PWM duty resolution of 8 bits enumerator LEDC_TIMER_9_BIT LEDC PWM duty resolution of 9 bits enumerator LEDC_TIMER_9_BIT LEDC PWM duty resolution of 9 bits enumerator LEDC_TIMER_10_BIT LEDC PWM duty resolution of 10 bits enumerator LEDC_TIMER_10_BIT LEDC PWM duty resolution of 10 bits enumerator LEDC_TIMER_11_BIT LEDC PWM duty resolution of 11 bits enumerator LEDC_TIMER_11_BIT LEDC PWM duty resolution of 11 bits enumerator LEDC_TIMER_12_BIT LEDC PWM duty resolution of 12 bits enumerator LEDC_TIMER_12_BIT LEDC PWM duty resolution of 12 bits enumerator LEDC_TIMER_13_BIT LEDC PWM duty resolution of 13 bits enumerator LEDC_TIMER_13_BIT LEDC PWM duty resolution of 13 bits enumerator LEDC_TIMER_14_BIT LEDC PWM duty resolution of 14 bits enumerator LEDC_TIMER_14_BIT LEDC PWM duty resolution of 14 bits enumerator LEDC_TIMER_15_BIT LEDC PWM duty resolution of 15 bits enumerator LEDC_TIMER_15_BIT LEDC PWM duty resolution of 15 bits enumerator LEDC_TIMER_16_BIT LEDC PWM duty resolution of 16 bits enumerator LEDC_TIMER_16_BIT LEDC PWM duty resolution of 16 bits enumerator LEDC_TIMER_17_BIT LEDC PWM duty resolution of 17 bits enumerator LEDC_TIMER_17_BIT LEDC PWM duty resolution of 17 bits enumerator LEDC_TIMER_18_BIT LEDC PWM duty resolution of 18 bits enumerator LEDC_TIMER_18_BIT LEDC PWM duty resolution of 18 bits enumerator LEDC_TIMER_19_BIT LEDC PWM duty resolution of 19 bits enumerator LEDC_TIMER_19_BIT LEDC PWM duty resolution of 19 bits enumerator LEDC_TIMER_20_BIT LEDC PWM duty resolution of 20 bits enumerator LEDC_TIMER_20_BIT LEDC PWM duty resolution of 20 bits enumerator LEDC_TIMER_BIT_MAX enumerator LEDC_TIMER_BIT_MAX enumerator LEDC_TIMER_1_BIT
LED Control (LEDC) Introduction The LED control (LEDC) peripheral is primarily designed to control the intensity of LEDs, although it can also be used to generate PWM signals for other purposes. It has 8 channels which can generate independent waveforms that can be used, for example, to drive RGB LED devices. LEDC channels are divided into two groups of 8 channels each. One group of LEDC channels operates in high speed mode. This mode is implemented in hardware and offers automatic and glitch-free changing of the PWM duty cycle. The other group of channels operate in low speed mode, the PWM duty cycle must be changed by the driver in software. Each group of channels is also able to use different clock sources. The PWM controller can automatically increase or decrease the duty cycle gradually, allowing for fades without any processor interference. Functionality Overview Setting up a channel of the LEDC in either high or low speed mode is done in three steps: Timer Configuration by specifying the PWM signal's frequency and duty cycle resolution. Channel Configuration by associating it with the timer and GPIO to output the PWM signal. Change PWM Signal that drives the output in order to change LED's intensity. This can be done under the full control of software or with hardware fading functions. As an optional step, it is also possible to set up an interrupt on fade end. Note For an initial setup, it is recommended to configure for the timers first (by calling ledc_timer_config()), and then for the channels (by calling ledc_channel_config()). This ensures the PWM frequency is at the desired value since the appearance of the PWM signal from the IO pad. Timer Configuration Setting the timer is done by calling the function ledc_timer_config() and passing the data structure ledc_timer_config_t that contains the following configuration settings: Speed mode ledc_mode_t Timer number ledc_timer_t PWM signal frequency in Hz Resolution of PWM duty Source clock ledc_clk_cfg_t The frequency and the duty resolution are interdependent. The higher the PWM frequency, the lower the duty resolution which is available, and vice versa. This relationship might be important if you are planning to use this API for purposes other than changing the intensity of LEDs. For more details, see Section Supported Range of Frequency and Duty Resolutions. The source clock can also limit the PWM frequency. The higher the source clock frequency, the higher the maximum PWM frequency can be configured. | Clock name | Clock freq | Speed mode | Clock capabilities | APB_CLK | 80 MHz | High / Low | / | REF_TICK | 1 MHz | High / Low | Dynamic Frequency Scaling compatible | RC_FAST_CLK | ~ 8 MHz | Low | Dynamic Frequency Scaling compatible, Light sleep compatible Note On ESP32, if RC_FAST_CLK is chosen as the LEDC clock source, an internal calibration will be performed to get the exact frequency of the clock. This ensures the accuracy of output PWM signal frequency. The LEDC driver offers a helper function ledc_find_suitable_duty_resolution() to find the maximum possible resolution for the timer, given the source clock frequency and the desired PWM signal frequency. When a timer is no longer needed by any channel, it can be deconfigured by calling the same function ledc_timer_config(). The configuration structure ledc_timer_config_t passes in should be: ledc_timer_config_t::speed_modeThe speed mode of the timer which wants to be deconfigured belongs to ( ledc_mode_t) ledc_timer_config_t::timer_numThe ID of the timers which wants to be deconfigured ( ledc_timer_t) ledc_timer_config_t::deconfigureSet this to true so that the timer specified can be deconfigured Channel Configuration When the timer is set up, configure the desired channel (one out of ledc_channel_t). This is done by calling the function ledc_channel_config(). Similar to the timer configuration, the channel setup function should be passed a structure ledc_channel_config_t that contains the channel's configuration parameters. At this point, the channel should start operating and generating the PWM signal on the selected GPIO, as configured in ledc_channel_config_t, with the frequency specified in the timer settings and the given duty cycle. The channel operation (signal generation) can be suspended at any time by calling the function ledc_stop(). Change PWM Signal Once the channel starts operating and generating the PWM signal with the constant duty cycle and frequency, there are a couple of ways to change this signal. When driving LEDs, primarily the duty cycle is changed to vary the light intensity. The following two sections describe how to change the duty cycle using software and hardware fading. If required, the signal's frequency can also be changed; it is covered in Section Change PWM Frequency. Change PWM Duty Cycle Using Software To set the duty cycle, use the dedicated function ledc_set_duty(). After that, call ledc_update_duty() to activate the changes. To check the currently set value, use the corresponding _get_ function ledc_get_duty(). Another way to set the duty cycle, as well as some other channel parameters, is by calling ledc_channel_config() covered in Section Channel Configuration. The range of the duty cycle values passed to functions depends on selected duty_resolution and should be from 0 to (2 ** duty_resolution). For example, if the selected duty resolution is 10, then the duty cycle values can range from 0 to 1024. This provides the resolution of ~ 0.1%. Warning On ESP32, when channel's binded timer selects its maximum duty resolution, the duty cycle value cannot be set to (2 ** duty_resolution). Otherwise, the internal duty counter in the hardware will overflow and be messed up. Change PWM Duty Cycle Using Hardware The LEDC hardware provides the means to gradually transition from one duty cycle value to another. To use this functionality, enable fading with ledc_fade_func_install() and then configure it by calling one of the available fading functions: Start fading with ledc_fade_start(). A fade can be operated in blocking or non-blocking mode, please check ledc_fade_mode_t for the difference between the two available fade modes. Note that with either fade mode, the next fade or fixed-duty update will not take effect until the last fade finishes. Due to hardware limitations, there is no way to stop a fade before it reaches its target duty. To get a notification about the completion of a fade operation, a fade end callback function can be registered for each channel by calling ledc_cb_register() after the fade service being installed. The fade end callback prototype is defined in ledc_cb_t, where you should return a boolean value from the callback function, indicating whether a high priority task is woken up by this callback function. It is worth mentioning, the callback and the function invoked by itself should be placed in IRAM, as the interrupt service routine is in IRAM. ledc_cb_register() will print a warning message if it finds the addresses of callback and user context are incorrect. If not required anymore, fading and an associated interrupt can be disabled with ledc_fade_func_uninstall(). Change PWM Frequency The LEDC API provides several ways to change the PWM frequency "on the fly": - Set the frequency by calling ledc_set_freq(). There is a corresponding function ledc_get_freq()to check the current frequency. - Change the frequency and the duty resolution by calling ledc_bind_channel_timer()to bind some other timer to the channel. - Change the channel's timer by calling ledc_channel_config(). More Control Over PWM There are several lower level timer-specific functions that can be used to change PWM settings: The first two functions are called "behind the scenes" by ledc_channel_config() to provide a startup of a timer after it is configured. Use Interrupts When configuring an LEDC channel, one of the parameters selected within ledc_channel_config_t is ledc_intr_type_t which triggers an interrupt on fade completion. For registration of a handler to address this interrupt, call ledc_isr_register(). LEDC High and Low Speed Mode High speed mode enables a glitch-free changeover of timer settings. This means that if the timer settings are modified, the changes will be applied automatically on the next overflow interrupt of the timer. In contrast, when updating the low-speed timer, the change of settings should be explicitly triggered by software. The LEDC driver handles it in the background, e.g., when ledc_timer_config() or ledc_timer_set() is called. For additional details regarding speed modes, see ESP32 Technical Reference Manual > LED PWM Controller (LEDC) [PDF]. Supported Range of Frequency and Duty Resolutions The LED PWM Controller is designed primarily to drive LEDs. It provides a large flexibility of PWM duty cycle settings. For instance, the PWM frequency of 5 kHz can have the maximum duty resolution of 13 bits. This means that the duty can be set anywhere from 0 to 100% with a resolution of ~ 0.012% (2 ** 13 = 8192 discrete levels of the LED intensity). Note, however, that these parameters depend on the clock signal clocking the LED PWM Controller timer which in turn clocks the channel (see timer configuration and the ESP32 Technical Reference Manual > LED PWM Controller (LEDC) [PDF]). The LEDC can be used for generating signals at much higher frequencies that are sufficient enough to clock other devices, e.g., a digital camera module. In this case, the maximum available frequency is 40 MHz with duty resolution of 1 bit. This means that the duty cycle is fixed at 50% and cannot be adjusted. The LEDC API is designed to report an error when trying to set a frequency and a duty resolution that exceed the range of LEDC's hardware. For example, an attempt to set the frequency to 20 MHz and the duty resolution to 3 bits results in the following error reported on a serial monitor: E (196) ledc: requested frequency and duty resolution cannot be achieved, try reducing freq_hz or duty_resolution. div_param=128 In such a situation, either the duty resolution or the frequency must be reduced. For example, setting the duty resolution to 2 resolves this issue and makes it possible to set the duty cycle at 25% steps, i.e., at 25%, 50% or 75%. The LEDC driver also captures and reports attempts to configure frequency/duty resolution combinations that are below the supported minimum, e.g.,: E (196) ledc: requested frequency and duty resolution cannot be achieved, try increasing freq_hz or duty_resolution. div_param=128000000 The duty resolution is normally set using ledc_timer_bit_t. This enumeration covers the range from 10 to 15 bits. If a smaller duty resolution is required (from 10 down to 1), enter the equivalent numeric values directly. Application Example The LEDC basic example: peripherals/ledc/ledc_basic. The LEDC change duty cycle and fading control example: peripherals/ledc/ledc_fade. API Reference Header File This header file can be included with: #include "driver/ledc.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t ledc_channel_config(const ledc_channel_config_t *ledc_conf) LEDC channel configuration Configure LEDC channel with the given channel/output gpio_num/interrupt/source timer/frequency(Hz)/LEDC duty. - Parameters ledc_conf -- Pointer of LEDC channel configure struct - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - uint32_t ledc_find_suitable_duty_resolution(uint32_t src_clk_freq, uint32_t timer_freq) Helper function to find the maximum possible duty resolution in bits for ledc_timer_config() - Parameters src_clk_freq -- LEDC timer source clock frequency (Hz) (See doxygen comments of ledc_clk_cfg_tor get from esp_clk_tree_src_get_freq_hz) timer_freq -- Desired LEDC timer frequency (Hz) - - Returns 0 The timer frequency cannot be achieved Others The largest duty resolution value to be set - - esp_err_t ledc_timer_config(const ledc_timer_config_t *timer_conf) LEDC timer configuration Configure LEDC timer with the given source timer/frequency(Hz)/duty_resolution. - Parameters timer_conf -- Pointer of LEDC timer configure struct - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Can not find a proper pre-divider number base on the given frequency and the current duty_resolution. ESP_ERR_INVALID_STATE Timer cannot be de-configured because timer is not configured or is not paused - - esp_err_t ledc_update_duty(ledc_mode_t speed_mode, ledc_channel_t channel) LEDC update channel parameters. Note Call this function to activate the LEDC updated parameters. After ledc_set_duty, we need to call this function to update the settings. And the new LEDC parameters don't take effect until the next PWM cycle. Note ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_duty_and_update Note If CONFIG_LEDC_CTRL_FUNC_IN_IRAMis enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Cache is disabled. Note This function is allowed to run within ISR context. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t ledc_set_pin(int gpio_num, ledc_mode_t speed_mode, ledc_channel_t ledc_channel) Set LEDC output gpio. Note This function only routes the LEDC signal to GPIO through matrix, other LEDC resources initialization are not involved. Please use ledc_channel_config()instead to fully configure a LEDC channel. - Parameters gpio_num -- The LEDC output gpio speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. ledc_channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t ledc_stop(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t idle_level) LEDC stop. Disable LEDC output, and set idle level. Note If CONFIG_LEDC_CTRL_FUNC_IN_IRAMis enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Cache is disabled. Note This function is allowed to run within ISR context. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t idle_level -- Set output idle level after LEDC stops. - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t ledc_set_freq(ledc_mode_t speed_mode, ledc_timer_t timer_num, uint32_t freq_hz) LEDC set channel frequency (Hz) - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_num -- LEDC timer index (0-3), select from ledc_timer_t freq_hz -- Set the LEDC frequency - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Can not find a proper pre-divider number base on the given frequency and the current duty_resolution. - - uint32_t ledc_get_freq(ledc_mode_t speed_mode, ledc_timer_t timer_num) LEDC get channel frequency (Hz) - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_num -- LEDC timer index (0-3), select from ledc_timer_t - - Returns 0 error Others Current LEDC frequency - - esp_err_t ledc_set_duty_with_hpoint(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty, uint32_t hpoint) LEDC set duty and hpoint value Only after calling ledc_update_duty will the duty update. Note ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_duty_and_update Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)] hpoint -- Set the LEDC hpoint value, the range is [0, (2**duty_resolution)-1] - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - int ledc_get_hpoint(ledc_mode_t speed_mode, ledc_channel_t channel) LEDC get hpoint value, the counter value when the output is set high level. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t - - Returns LEDC_ERR_VAL if parameter error Others Current hpoint value of LEDC channel - - esp_err_t ledc_set_duty(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty) LEDC set duty This function do not change the hpoint value of this channel. if needed, please call ledc_set_duty_with_hpoint. only after calling ledc_update_duty will the duty update. Note ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_duty_and_update. Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)] - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - uint32_t ledc_get_duty(ledc_mode_t speed_mode, ledc_channel_t channel) LEDC get duty This function returns the duty at the present PWM cycle. You shouldn't expect the function to return the new duty in the same cycle of calling ledc_update_duty, because duty update doesn't take effect until the next cycle. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t - - Returns LEDC_ERR_DUTY if parameter error Others Current LEDC duty - - esp_err_t ledc_set_fade(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty, ledc_duty_direction_t fade_direction, uint32_t step_num, uint32_t duty_cycle_num, uint32_t duty_scale) LEDC set gradient Set LEDC gradient, After the function calls the ledc_update_duty function, the function can take effect. Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the start of the gradient duty, the range of duty setting is [0, (2**duty_resolution)] fade_direction -- Set the direction of the gradient step_num -- Set the number of the gradient duty_cycle_num -- Set how many LEDC tick each time the gradient lasts duty_scale -- Set gradient change amplitude - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t ledc_isr_register(void (*fn)(void*), void *arg, int intr_alloc_flags, ledc_isr_handle_t *handle) Register LEDC interrupt handler, the handler is an ISR. The handler will be attached to the same CPU core that this function is running on. - Parameters fn -- Interrupt handler function. arg -- User-supplied argument passed to the handler function. intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. handle -- Pointer to return handle. If non-NULL, a handle for the interrupt will be returned here. - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_NOT_FOUND Failed to find available interrupt source - - esp_err_t ledc_timer_set(ledc_mode_t speed_mode, ledc_timer_t timer_sel, uint32_t clock_divider, uint32_t duty_resolution, ledc_clk_src_t clk_src) Configure LEDC settings. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- Timer index (0-3), there are 4 timers in LEDC module clock_divider -- Timer clock divide value, the timer clock is divided from the selected clock source duty_resolution -- Resolution of duty setting in number of bits. The range is [1, SOC_LEDC_TIMER_BIT_WIDTH] clk_src -- Select LEDC source clock. - - Returns (-1) Parameter error Other Current LEDC duty - - esp_err_t ledc_timer_rst(ledc_mode_t speed_mode, ledc_timer_t timer_sel) Reset LEDC timer. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- LEDC timer index (0-3), select from ledc_timer_t - - Returns ESP_ERR_INVALID_ARG Parameter error ESP_OK Success - - esp_err_t ledc_timer_pause(ledc_mode_t speed_mode, ledc_timer_t timer_sel) Pause LEDC timer counter. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- LEDC timer index (0-3), select from ledc_timer_t - - Returns ESP_ERR_INVALID_ARG Parameter error ESP_OK Success - - esp_err_t ledc_timer_resume(ledc_mode_t speed_mode, ledc_timer_t timer_sel) Resume LEDC timer. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. timer_sel -- LEDC timer index (0-3), select from ledc_timer_t - - Returns ESP_ERR_INVALID_ARG Parameter error ESP_OK Success - - esp_err_t ledc_bind_channel_timer(ledc_mode_t speed_mode, ledc_channel_t channel, ledc_timer_t timer_sel) Bind LEDC channel with the selected timer. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t timer_sel -- LEDC timer index (0-3), select from ledc_timer_t - - Returns ESP_ERR_INVALID_ARG Parameter error ESP_OK Success - - esp_err_t ledc_set_fade_with_step(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, uint32_t scale, uint32_t cycle_num) Set LEDC fade function. Note Call ledc_fade_func_install() once before calling this function. Call ledc_fade_start() after this to start fading. Note ledc_set_fade_with_step, ledc_set_fade_with_time and ledc_fade_start are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_fade_step_and_start Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] scale -- Controls the increase or decrease step scale. cycle_num -- increase or decrease the duty every cycle_num cycles - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error - - esp_err_t ledc_set_fade_with_time(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, int max_fade_time_ms) Set LEDC fade function, with a limited time. Note Call ledc_fade_func_install() once before calling this function. Call ledc_fade_start() after this to start fading. Note ledc_set_fade_with_step, ledc_set_fade_with_time and ledc_fade_start are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_fade_step_and_start Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] max_fade_time_ms -- The maximum time of the fading ( ms ). - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error - - esp_err_t ledc_fade_func_install(int intr_alloc_flags) Install LEDC fade function. This function will occupy interrupt of LEDC module. - Parameters intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. - Returns ESP_OK Success ESP_ERR_INVALID_ARG Intr flag error ESP_ERR_NOT_FOUND Failed to find available interrupt source ESP_ERR_INVALID_STATE Fade function already installed - - void ledc_fade_func_uninstall(void) Uninstall LEDC fade function. - esp_err_t ledc_fade_start(ledc_mode_t speed_mode, ledc_channel_t channel, ledc_fade_mode_t fade_mode) Start LEDC fading. Note Call ledc_fade_func_install() once before calling this function. Call this API right after ledc_set_fade_with_time or ledc_set_fade_with_step before to start fading. Note Starting fade operation with this API is not thread-safe, use with care. Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel number fade_mode -- Whether to block until fading done. See ledc_types.h ledc_fade_mode_t for more info. Note that this function will not return until fading to the target duty if LEDC_FADE_WAIT_DONE mode is selected. - - Returns ESP_OK Success ESP_ERR_INVALID_STATE Channel not initialized or fade function not installed. ESP_ERR_INVALID_ARG Parameter error. - - esp_err_t ledc_set_duty_and_update(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty, uint32_t hpoint) A thread-safe API to set duty for LEDC channel and return when duty updated. Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)] hpoint -- Set the LEDC hpoint value, the range is [0, (2**duty_resolution)-1] - - Returns ESP_OK Success ESP_ERR_INVALID_STATE Channel not initialized ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Fade function init error - - esp_err_t ledc_set_fade_time_and_start(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, uint32_t max_fade_time_ms, ledc_fade_mode_t fade_mode) A thread-safe API to set and start LEDC fade function, with a limited time. Note Call ledc_fade_func_install() once, before calling this function. Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] max_fade_time_ms -- The maximum time of the fading ( ms ). fade_mode -- choose blocking or non-blocking mode - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error - - esp_err_t ledc_set_fade_step_and_start(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, uint32_t scale, uint32_t cycle_num, ledc_fade_mode_t fade_mode) A thread-safe API to set and start LEDC fade function. Note Call ledc_fade_func_install() once before calling this function. Note For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t target_duty -- Target duty of fading [0, (2**duty_resolution)] scale -- Controls the increase or decrease step scale. cycle_num -- increase or decrease the duty every cycle_num cycles fade_mode -- choose blocking or non-blocking mode - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error - - esp_err_t ledc_cb_register(ledc_mode_t speed_mode, ledc_channel_t channel, ledc_cbs_t *cbs, void *user_arg) LEDC callback registration function. Note The callback is called from an ISR, it must never attempt to block, and any FreeRTOS API called must be ISR capable. - Parameters speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t cbs -- Group of LEDC callback functions user_arg -- user registered data for the callback function - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Channel not initialized ESP_FAIL Fade function init error - Structures - struct ledc_channel_config_t Configuration parameters of LEDC channel for ledc_channel_config function. Public Members - int gpio_num the LEDC output gpio_num, if you want to use gpio16, gpio_num = 16 - ledc_mode_t speed_mode LEDC speed speed_mode, high-speed mode (only exists on esp32) or low-speed mode - ledc_channel_t channel LEDC channel (0 - LEDC_CHANNEL_MAX-1) - ledc_intr_type_t intr_type configure interrupt, Fade interrupt enable or Fade interrupt disable - ledc_timer_t timer_sel Select the timer source of channel (0 - LEDC_TIMER_MAX-1) - uint32_t duty LEDC channel duty, the range of duty setting is [0, (2**duty_resolution)] - int hpoint LEDC channel hpoint value, the range is [0, (2**duty_resolution)-1] - unsigned int output_invert Enable (1) or disable (0) gpio output invert - struct ledc_channel_config_t::[anonymous] flags LEDC flags - int gpio_num - struct ledc_timer_config_t Configuration parameters of LEDC timer for ledc_timer_config function. Public Members - ledc_mode_t speed_mode LEDC speed speed_mode, high-speed mode (only exists on esp32) or low-speed mode - ledc_timer_bit_t duty_resolution LEDC channel duty resolution - ledc_timer_t timer_num The timer source of channel (0 - LEDC_TIMER_MAX-1) - uint32_t freq_hz LEDC timer frequency (Hz) - ledc_clk_cfg_t clk_cfg Configure LEDC source clock from ledc_clk_cfg_t. Note that LEDC_USE_RC_FAST_CLK and LEDC_USE_XTAL_CLK are non-timer-specific clock sources. You can not have one LEDC timer uses RC_FAST_CLK as the clock source and have another LEDC timer uses XTAL_CLK as its clock source. All chips except esp32 and esp32s2 do not have timer-specific clock sources, which means clock source for all timers must be the same one. - bool deconfigure Set this field to de-configure a LEDC timer which has been configured before Note that it will not check whether the timer wants to be de-configured is binded to any channel. Also, the timer has to be paused first before it can be de-configured. When this field is set, duty_resolution, freq_hz, clk_cfg fields are ignored. - ledc_mode_t speed_mode - struct ledc_cb_param_t LEDC callback parameter. Public Members - ledc_cb_event_t event Event name - uint32_t speed_mode Speed mode of the LEDC channel group - uint32_t channel LEDC channel (0 - LEDC_CHANNEL_MAX-1) - uint32_t duty LEDC current duty of the channel, the range of duty is [0, (2**duty_resolution)] - ledc_cb_event_t event - struct ledc_cbs_t Group of supported LEDC callbacks. Note The callbacks are all running under ISR environment Macros - LEDC_APB_CLK_HZ Frequency of one of the LEDC peripheral clock sources, APB_CLK. Note This macro should have no use in your application, we keep it here only for backward compatible - LEDC_REF_CLK_HZ Frequency of one of the LEDC peripheral clock sources, REF_TICK. Note This macro should have no use in your application, we keep it here only for backward compatible - LEDC_ERR_DUTY - LEDC_ERR_VAL Type Definitions - typedef intr_handle_t ledc_isr_handle_t - typedef bool (*ledc_cb_t)(const ledc_cb_param_t *param, void *user_arg) Type of LEDC event callback. - Param param LEDC callback parameter - Param user_arg User registered data - Return Whether a high priority task has been waken up by this function Enumerations Header File This header file can be included with: #include "hal/ledc_types.h" Type Definitions - typedef soc_periph_ledc_clk_src_legacy_t ledc_clk_cfg_t LEDC clock source configuration struct. In theory, the following enumeration shall be placed in LEDC driver's header. However, as the next enumeration, ledc_clk_src_t, makes the use of some of these values and to avoid mutual inclusion of the headers, we must define it here. Enumerations - enum ledc_mode_t Values: - enumerator LEDC_HIGH_SPEED_MODE LEDC high speed speed_mode - enumerator LEDC_LOW_SPEED_MODE LEDC low speed speed_mode - enumerator LEDC_SPEED_MODE_MAX LEDC speed limit - enumerator LEDC_HIGH_SPEED_MODE - enum ledc_intr_type_t Values: - enumerator LEDC_INTR_DISABLE Disable LEDC interrupt - enumerator LEDC_INTR_FADE_END Enable LEDC interrupt - enumerator LEDC_INTR_MAX - enumerator LEDC_INTR_DISABLE - enum ledc_duty_direction_t Values: - enumerator LEDC_DUTY_DIR_DECREASE LEDC duty decrease direction - enumerator LEDC_DUTY_DIR_INCREASE LEDC duty increase direction - enumerator LEDC_DUTY_DIR_MAX - enumerator LEDC_DUTY_DIR_DECREASE - enum ledc_slow_clk_sel_t LEDC global clock sources. Values: - enumerator LEDC_SLOW_CLK_RC_FAST LEDC low speed timer clock source is RC_FAST clock - enumerator LEDC_SLOW_CLK_APB LEDC low speed timer clock source is 80MHz APB clock - enumerator LEDC_SLOW_CLK_RTC8M Alias of 'LEDC_SLOW_CLK_RC_FAST' - enumerator LEDC_SLOW_CLK_RC_FAST - enum ledc_clk_src_t LEDC timer-specific clock sources. Note: Setting numeric values to match ledc_clk_cfg_t values are a hack to avoid collision with LEDC_AUTO_CLK in the driver, as these enums have very similar names and user may pass one of these by mistake. Values: - enumerator LEDC_REF_TICK LEDC timer clock divided from reference tick (1Mhz) - enumerator LEDC_APB_CLK LEDC timer clock divided from APB clock (80Mhz) - enumerator LEDC_SCLK Selecting this value for LEDC_TICK_SEL_TIMER let the hardware take its source clock from LEDC_APB_CLK_SEL - enumerator LEDC_REF_TICK - enum ledc_timer_t Values: - enumerator LEDC_TIMER_0 LEDC timer 0 - enumerator LEDC_TIMER_1 LEDC timer 1 - enumerator LEDC_TIMER_2 LEDC timer 2 - enumerator LEDC_TIMER_3 LEDC timer 3 - enumerator LEDC_TIMER_MAX - enumerator LEDC_TIMER_0 - enum ledc_channel_t Values: - enumerator LEDC_CHANNEL_0 LEDC channel 0 - enumerator LEDC_CHANNEL_1 LEDC channel 1 - enumerator LEDC_CHANNEL_2 LEDC channel 2 - enumerator LEDC_CHANNEL_3 LEDC channel 3 - enumerator LEDC_CHANNEL_4 LEDC channel 4 - enumerator LEDC_CHANNEL_5 LEDC channel 5 - enumerator LEDC_CHANNEL_6 LEDC channel 6 - enumerator LEDC_CHANNEL_7 LEDC channel 7 - enumerator LEDC_CHANNEL_MAX - enumerator LEDC_CHANNEL_0 - enum ledc_timer_bit_t Values: - enumerator LEDC_TIMER_1_BIT LEDC PWM duty resolution of 1 bits - enumerator LEDC_TIMER_2_BIT LEDC PWM duty resolution of 2 bits - enumerator LEDC_TIMER_3_BIT LEDC PWM duty resolution of 3 bits - enumerator LEDC_TIMER_4_BIT LEDC PWM duty resolution of 4 bits - enumerator LEDC_TIMER_5_BIT LEDC PWM duty resolution of 5 bits - enumerator LEDC_TIMER_6_BIT LEDC PWM duty resolution of 6 bits - enumerator LEDC_TIMER_7_BIT LEDC PWM duty resolution of 7 bits - enumerator LEDC_TIMER_8_BIT LEDC PWM duty resolution of 8 bits - enumerator LEDC_TIMER_9_BIT LEDC PWM duty resolution of 9 bits - enumerator LEDC_TIMER_10_BIT LEDC PWM duty resolution of 10 bits - enumerator LEDC_TIMER_11_BIT LEDC PWM duty resolution of 11 bits - enumerator LEDC_TIMER_12_BIT LEDC PWM duty resolution of 12 bits - enumerator LEDC_TIMER_13_BIT LEDC PWM duty resolution of 13 bits - enumerator LEDC_TIMER_14_BIT LEDC PWM duty resolution of 14 bits - enumerator LEDC_TIMER_15_BIT LEDC PWM duty resolution of 15 bits - enumerator LEDC_TIMER_16_BIT LEDC PWM duty resolution of 16 bits - enumerator LEDC_TIMER_17_BIT LEDC PWM duty resolution of 17 bits - enumerator LEDC_TIMER_18_BIT LEDC PWM duty resolution of 18 bits - enumerator LEDC_TIMER_19_BIT LEDC PWM duty resolution of 19 bits - enumerator LEDC_TIMER_20_BIT LEDC PWM duty resolution of 20 bits - enumerator LEDC_TIMER_BIT_MAX - enumerator LEDC_TIMER_1_BIT
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/ledc.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Motor Control Pulse Width Modulator (MCPWM)
null
espressif.com
2016-01-01
2f2c1d93b23c9da1
null
null
Motor Control Pulse Width Modulator (MCPWM) The MCPWM peripheral is a versatile PWM generator, which contains various submodules to make it a key element in power electronic applications like motor control, digital power, and so on. Typically, the MCPWM peripheral can be used in the following scenarios: Digital motor control, e.g., brushed/brushless DC motor, RC servo motor Switch mode-based digital power conversion Power DAC, where the duty cycle is equivalent to a DAC analog value Calculate external pulse width, and convert it into other analog values like speed, distance Generate Space Vector PWM (SVPWM) signals for Field Oriented Control (FOC) The main submodules are listed in the following diagram: MCPWM Timer: The time base of the final PWM signal. It also determines the event timing of other submodules. MCPWM Operator: The key module that is responsible for generating the PWM waveforms. It consists of other submodules, like comparator, PWM generator, dead time, and carrier modulator. MCPWM Comparator: The compare module takes the time-base count value as input, and continuously compares it to the threshold value configured. When the timer is equal to any of the threshold values, a compare event will be generated and the MCPWM generator can update its level accordingly. MCPWM Generator: One MCPWM generator can generate a pair of PWM waves, complementarily or independently, based on various events triggered by other submodules like MCPWM Timer and MCPWM Comparator. MCPWM Fault: The fault module is used to detect the fault condition from outside, mainly via the GPIO matrix. Once the fault signal is active, MCPWM Operator will force all the generators into a predefined state to protect the system from damage. MCPWM Sync: The sync module is used to synchronize the MCPWM timers, so that the final PWM signals generated by different MCPWM generators can have a fixed phase difference. The sync signal can be routed from the GPIO matrix or from an MCPWM Timer event. Dead Time: This submodule is used to insert extra delay to the existing PWM edges generated in the previous steps. Carrier Modulation: The carrier submodule can modulate a high-frequency carrier signal into PWM waveforms by the generator and dead time submodules. This capability is mandatory for controlling the power-switching elements. Brake: MCPWM operator can set how to brake the generators when a particular fault is detected. You can shut down the PWM output immediately or regulate the PWM output cycle by cycle, depending on how critical the fault is. MCPWM Capture: This is a standalone submodule that can work even without the above MCPWM operators. The capture consists one dedicated timer and several independent channels, with each channel connected to the GPIO. A pulse on the GPIO triggers the capture timer to store the time-base count value and then notify you by an interrupt. Using this feature, you can measure a pulse width precisely. What is more, the capture timer can also be synchronized by the MCPWM Sync submodule. Functional Overview Description of the MCPWM functionality is divided into the following sections: Resource Allocation and Initialization - covers how to allocate various MCPWM objects, like timers, operators, comparators, generators and so on. These objects are the basis of the following IO setting and control functions. Timer Operations and Events - describes control functions and event callbacks supported by the MCPWM timer. Comparator Operations and Events - describes control functions and event callbacks supported by the MCPWM comparator. Generator Actions on Events - describes how to set actions for MCPWM generators on particular events that are generated by the MCPWM timer and comparators. Generator Configurations for Classical PWM Waveforms - demonstrates some classical PWM waveforms that can be achieved by configuring generator actions. Dead Time - describes how to set dead time for MCPWM generators. Dead Time Configurations for Classical PWM Waveforms - demonstrates some classical PWM waveforms that can be achieved by configuring dead time. Carrier Modulation - describes how to set and modulate a high frequency onto the final PWM waveforms. Faults and Brake Actions - describes how to set brake actions for MCPWM operators on particular fault events. Generator Force Actions - describes how to control the generator output level asynchronously in a forceful way. Synchronization - describes how to synchronize the MCPWM timers and get a fixed phase difference between the generated PWM signals. Capture - describes how to use the MCPWM capture module to measure the pulse width of a signal. Power Management - describes how different source clocks affects power consumption. IRAM Safe - describes tips on how to make the RMT interrupt work better along with a disabled cache. Thread Safety - lists which APIs are guaranteed to be thread-safe by the driver. Kconfig Options - lists the supported Kconfig options that can bring different effects to the driver. Resource Allocation and Initialization As displayed in the diagram above, the MCPWM peripheral consists of several submodules. Each submodule has its own resource allocation, which is described in the following sections. MCPWM Timers You can allocate a MCPWM timer object by calling mcpwm_new_timer() function, with a configuration structure mcpwm_timer_config_t as the parameter. The configuration structure is defined as: mcpwm_timer_config_t::group_id specifies the MCPWM group ID. The ID should belong to [0, SOC_MCPWM_GROUPS - 1] range. Please note, timers located in different groups are totally independent. mcpwm_timer_config_t::intr_priority sets the priority of the interrupt. If it is set to 0 , the driver will allocate an interrupt with a default priority. Otherwise, the driver will use the given priority. mcpwm_timer_config_t::clk_src sets the clock source of the timer. mcpwm_timer_config_t::resolution_hz sets the expected resolution of the timer. The driver internally sets a proper divider based on the clock source and the resolution. mcpwm_timer_config_t::count_mode sets the count mode of the timer. mcpwm_timer_config_t::period_ticks sets the period of the timer, in ticks (the tick resolution is set in the mcpwm_timer_config_t::resolution_hz ). mcpwm_timer_config_t::update_period_on_empty sets whether to update the period value when the timer counts to zero. mcpwm_timer_config_t::update_period_on_sync sets whether to update the period value when the timer takes a sync signal. The mcpwm_new_timer() will return a pointer to the allocated timer object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free timers in the MCPWM group, this function will return the ESP_ERR_NOT_FOUND error. 1 On the contrary, calling the mcpwm_del_timer() function will free the allocated timer object. MCPWM Operators You can allocate a MCPWM operator object by calling mcpwm_new_operator()() function, with a configuration structure mcpwm_operator_config_t as the parameter. The configuration structure is defined as: mcpwm_operator_config_t::group_id specifies the MCPWM group ID. The ID should belong to [0, SOC_MCPWM_GROUPS - 1] range. Please note, operators located in different groups are totally independent. mcpwm_operator_config_t::intr_priority sets the priority of the interrupt. If it is set to 0 , the driver will allocate an interrupt with a default priority. Otherwise, the driver will use the given priority. mcpwm_operator_config_t::update_gen_action_on_tez sets whether to update the generator action when the timer counts to zero. Here and below, the timer refers to the one that is connected to the operator by mcpwm_operator_connect_timer() . mcpwm_operator_config_t::update_gen_action_on_tep sets whether to update the generator action when the timer counts to peak. mcpwm_operator_config_t::update_gen_action_on_sync sets whether to update the generator action when the timer takes a sync signal. mcpwm_operator_config_t::update_dead_time_on_tez sets whether to update the dead time when the timer counts to zero. mcpwm_operator_config_t::update_dead_time_on_tep sets whether to update the dead time when the timer counts to the peak. mcpwm_operator_config_t::update_dead_time_on_sync sets whether to update the dead time when the timer takes a sync signal. The mcpwm_new_operator()() will return a pointer to the allocated operator object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free operators in the MCPWM group, this function will return the ESP_ERR_NOT_FOUND error. 1 On the contrary, calling mcpwm_del_operator()() function will free the allocated operator object. MCPWM Comparators You can allocate a MCPWM comparator object by calling the mcpwm_new_comparator() function, with a MCPWM operator handle and configuration structure mcpwm_comparator_config_t as the parameter. The operator handle is created by mcpwm_new_operator()() . The configuration structure is defined as: mcpwm_comparator_config_t::intr_priority sets the priority of the interrupt. If it is set to 0 , the driver will allocate an interrupt with a default priority. Otherwise, the driver will use the given priority. mcpwm_comparator_config_t::update_cmp_on_tez sets whether to update the compare threshold when the timer counts to zero. mcpwm_comparator_config_t::update_cmp_on_tep sets whether to update the compare threshold when the timer counts to the peak. mcpwm_comparator_config_t::update_cmp_on_sync sets whether to update the compare threshold when the timer takes a sync signal. The mcpwm_new_comparator() will return a pointer to the allocated comparator object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free comparators in the MCPWM operator, this function will return the ESP_ERR_NOT_FOUND error. 1 On the contrary, calling the mcpwm_del_comparator() function will free the allocated comparator object. MCPWM Generators You can allocate a MCPWM generator object by calling the mcpwm_new_generator() function, with a MCPWM operator handle and configuration structure mcpwm_generator_config_t as the parameter. The operator handle is created by mcpwm_new_operator()() . The configuration structure is defined as: mcpwm_generator_config_t::gen_gpio_num sets the GPIO number used by the generator. mcpwm_generator_config_t::invert_pwm sets whether to invert the PWM signal. mcpwm_generator_config_t::io_loop_back sets whether to enable the Loop-back mode. It is for debugging purposes only. It enables both the GPIO's input and output ability through the GPIO matrix peripheral. mcpwm_generator_config_t::io_od_mode configures the PWM GPIO as open-drain output. mcpwm_generator_config_t::pull_up and mcpwm_generator_config_t::pull_down controls whether to enable the internal pull-up and pull-down resistors accordingly. The mcpwm_new_generator() will return a pointer to the allocated generator object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free generators in the MCPWM operator, this function will return the ESP_ERR_NOT_FOUND error. 1 On the contrary, calling the mcpwm_del_generator() function will free the allocated generator object. MCPWM Faults There are two types of faults: A fault signal reflected from the GPIO and a fault generated by software. To allocate a GPIO fault object, you can call the mcpwm_new_gpio_fault() function, with the configuration structure mcpwm_gpio_fault_config_t as the parameter. The configuration structure is defined as: mcpwm_gpio_fault_config_t::group_id sets the MCPWM group ID. The ID should belong to [0, SOC_MCPWM_GROUPS - 1] range. Please note, GPIO faults located in different groups are totally independent, i.e., GPIO faults in group 0 can not be detected by the operator in group 1. mcpwm_gpio_fault_config_t::intr_priority sets the priority of the interrupt. If it is set to 0 , the driver will allocate an interrupt with a default priority. Otherwise, the driver will use the given priority. mcpwm_gpio_fault_config_t::gpio_num sets the GPIO number used by the fault. mcpwm_gpio_fault_config_t::active_level sets the active level of the fault signal. mcpwm_gpio_fault_config_t::pull_up and mcpwm_gpio_fault_config_t::pull_down set whether to pull up and/or pull down the GPIO internally. mcpwm_gpio_fault_config_t::io_loop_back sets whether to enable the loopback mode. It is for debugging purposes only. It enables both the GPIO's input and output ability through the GPIO matrix peripheral. The mcpwm_new_gpio_fault() will return a pointer to the allocated fault object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free GPIO faults in the MCPWM group, this function will return the ESP_ERR_NOT_FOUND error. 1 Software fault object can be used to trigger a fault by calling the function mcpwm_soft_fault_activate() instead of waiting for a real fault signal on the GPIO. A software fault object can be allocated by calling the mcpwm_new_soft_fault() function, with configuration structure mcpwm_soft_fault_config_t as the parameter. Currently, this configuration structure is left for future purposes. The mcpwm_new_soft_fault() function will return a pointer to the allocated fault object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there is no memory left for the fault object, this function will return the ESP_ERR_NO_MEM error. Although the software fault and GPIO fault are of different types, the returned fault handle is of the same type. On the contrary, calling the mcpwm_del_fault() function will free the allocated fault object, this function works for both software and GPIO fault. MCPWM Sync Sources The sync source is what can be used to synchronize the MCPWM timer and MCPWM capture timer. There are three types of sync sources: a sync source reflected from the GPIO, a sync source generated by software, and a sync source generated by an MCPWM timer event. To allocate a GPIO sync source, you can call the mcpwm_new_gpio_sync_src() function, with configuration structure mcpwm_gpio_sync_src_config_t as the parameter. The configuration structure is defined as: mcpwm_gpio_sync_src_config_t::group_id sets the MCPWM group ID. The ID should belong to [0, SOC_MCPWM_GROUPS - 1] range. Please note, the GPIO sync sources located in different groups are totally independent, i.e., GPIO sync source in group 0 can not be detected by the timers in group 1. mcpwm_gpio_sync_src_config_t::gpio_num sets the GPIO number used by the sync source. mcpwm_gpio_sync_src_config_t::active_neg sets whether the sync signal is active on falling edges. mcpwm_gpio_sync_src_config_t::pull_up and mcpwm_gpio_sync_src_config_t::pull_down set whether to pull up and/or pull down the GPIO internally. mcpwm_gpio_sync_src_config_t::io_loop_back sets whether to enable the Loop-back mode. It is for debugging purposes only. It enables both the GPIO's input and output ability through the GPIO matrix peripheral. The mcpwm_new_gpio_sync_src() will return a pointer to the allocated sync source object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free GPIO sync sources in the MCPWM group, this function will return the ESP_ERR_NOT_FOUND error. 1 To allocate a timer event sync source, you can call the mcpwm_new_timer_sync_src() function, with configuration structure mcpwm_timer_sync_src_config_t as the parameter. The configuration structure is defined as: mcpwm_timer_sync_src_config_t::timer_event specifies on what timer event to generate the sync signal. mcpwm_timer_sync_src_config_t::propagate_input_sync sets whether to propagate the input sync signal (i.e., the input sync signal will be routed to its sync output). The mcpwm_new_timer_sync_src() will return a pointer to the allocated sync source object if the allocation succeeds. Otherwise, it will return an error code. Specifically, if a sync source has been allocated from the same timer before, this function will return the ESP_ERR_INVALID_STATE error. Last but not least, to allocate a software sync source, you can call the mcpwm_new_soft_sync_src() function, with configuration structure mcpwm_soft_sync_config_t as the parameter. Currently, this configuration structure is left for future purposes. mcpwm_new_soft_sync_src() will return a pointer to the allocated sync source object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there is no memory left for the sync source object, this function will return the ESP_ERR_NO_MEM error. Please note, to make a software sync source take effect, do not forget to call mcpwm_soft_sync_activate() . On the contrary, calling the mcpwm_del_sync_src() function will free the allocated sync source object. This function works for all types of sync sources. MCPWM Capture Timer and Channels The MCPWM group has a dedicated timer which is used to capture the timestamp when a specific event occurred. The capture timer is connected to several independent channels, each channel is assigned a GPIO. To allocate a capture timer, you can call the mcpwm_new_capture_timer() function, with configuration structure mcpwm_capture_timer_config_t as the parameter. The configuration structure is defined as: mcpwm_capture_timer_config_t::group_id sets the MCPWM group ID. The ID should belong to [0, SOC_MCPWM_GROUPS - 1] range. mcpwm_capture_timer_config_t::clk_src sets the clock source of the capture timer. mcpwm_capture_timer_config_t::resolution_hz The driver internally will set a proper divider based on the clock source and the resolution. If it is set to 0 , the driver will pick an appropriate resolution on its own, and you can subsequently view the current timer resolution via mcpwm_capture_timer_get_resolution() . Note In ESP32, mcpwm_capture_timer_config_t::resolution_hz parameter is invalid, the capture timer resolution is always equal to the MCPWM_CAPTURE_CLK_SRC_APB . The mcpwm_new_capture_timer() will return a pointer to the allocated capture timer object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there is no free capture timer left in the MCPWM group, this function will return the ESP_ERR_NOT_FOUND error. 1 Next, to allocate a capture channel, you can call the mcpwm_new_capture_channel() function, with a capture timer handle and configuration structure mcpwm_capture_channel_config_t as the parameter. The configuration structure is defined as: mcpwm_capture_channel_config_t::intr_priority sets the priority of the interrupt. If it is set to 0 , the driver will allocate an interrupt with a default priority. Otherwise, the driver will use the given priority. mcpwm_capture_channel_config_t::gpio_num sets the GPIO number used by the capture channel. mcpwm_capture_channel_config_t::prescale sets the prescaler of the input signal. mcpwm_capture_channel_config_t::pos_edge and mcpwm_capture_channel_config_t::neg_edge set whether to capture on the positive and/or falling edge of the input signal. mcpwm_capture_channel_config_t::pull_up and mcpwm_capture_channel_config_t::pull_down set whether to pull up and/or pull down the GPIO internally. mcpwm_capture_channel_config_t::invert_cap_signal sets whether to invert the capture signal. mcpwm_capture_channel_config_t::io_loop_back sets whether to enable the Loop-back mode. It is for debugging purposes only. It enables both the GPIO's input and output ability through the GPIO matrix peripheral. The mcpwm_new_capture_channel() will return a pointer to the allocated capture channel object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there is no free capture channel left in the capture timer, this function will return the ESP_ERR_NOT_FOUND error. On the contrary, calling mcpwm_del_capture_channel() and mcpwm_del_capture_timer() will free the allocated capture channel and timer object accordingly. MCPWM Interrupt Priority MCPWM allows configuring interrupts separately for timer, operator, comparator, fault, and capture events. The interrupt priority is determined by the respective config_t::intr_priority . Additionally, events within the same MCPWM group share a common interrupt source. When registering multiple interrupt events, the interrupt priorities need to remain consistent. Note When registering multiple interrupt events within an MCPWM group, the driver will use the interrupt priority of the first registered event as the MCPWM group's interrupt priority. Timer Operations and Events Update Period The timer period is initialized by the mcpwm_timer_config_t::period_ticks parameter in mcpwm_timer_config_t . You can update the period at runtime by calling mcpwm_timer_set_period() function. The new period will take effect based on how you set the mcpwm_timer_config_t::update_period_on_empty and mcpwm_timer_config_t::update_period_on_sync parameters in mcpwm_timer_config_t . If none of them are set, the timer period will take effect immediately. Register Timer Event Callbacks The MCPWM timer can generate different events at runtime. If you have some function that should be called when a particular event happens, you should hook your function to the interrupt service routine by calling mcpwm_timer_register_event_callbacks() . The callback function prototype is declared in mcpwm_timer_event_cb_t . All supported event callbacks are listed in the mcpwm_timer_event_callbacks_t : mcpwm_timer_event_callbacks_t::on_full sets the callback function for the timer when it counts to peak value. mcpwm_timer_event_callbacks_t::on_empty sets the callback function for the timer when it counts to zero. mcpwm_timer_event_callbacks_t::on_stop sets the callback function for the timer when it is stopped. The callback functions above are called within the ISR context, so they should not attempt to block. For example, you may make sure that only FreeRTOS APIs with the ISR suffix are called within the function. The parameter user_data of the mcpwm_timer_register_event_callbacks() function is used to save your own context. It is passed to each callback function directly. This function will lazy the install interrupt service for the MCPWM timer without enabling it. It is only allowed to be called before mcpwm_timer_enable() , otherwise the ESP_ERR_INVALID_STATE error will be returned. See also Enable and Disable timer for more information. Enable and Disable Timer Before doing IO control to the timer, you need to enable the timer first, by calling mcpwm_timer_enable() . This function: switches the timer state from init to enable. enables the interrupt service if it has been lazy installed by mcpwm_timer_register_event_callbacks() . acquire a proper power management lock if a specific clock source (e.g., PLL_160M clock) is selected. See also Power management for more information. On the contrary, calling mcpwm_timer_disable() will put the timer driver back to the init state, disable the interrupt service and release the power management lock. Start and Stop Timer The basic IO operation of a timer is to start and stop. Calling mcpwm_timer_start_stop() with different mcpwm_timer_start_stop_cmd_t commands can start the timer immediately or stop the timer at a specific event. What is more, you can even start the timer for only one round, which means, the timer will count to peak value or zero, and then stop itself. Connect Timer with Operator The allocated MCPWM timer should be connected with an MCPWM operator by calling mcpwm_operator_connect_timer() , so that the operator can take that timer as its time base, and generate the required PWM waves. Please make sure the MCPWM timer and operator are in the same group. Otherwise, this function will return the ESP_ERR_INVALID_ARG error. Comparator Operations and Events Register Comparator Event Callbacks The MCPWM comparator can inform you when the timer counter equals the compare value. If you have some function that should be called when this event happens, you should hook your function to the interrupt service routine by calling mcpwm_comparator_register_event_callbacks() . The callback function prototype is declared in mcpwm_compare_event_cb_t . All supported event callbacks are listed in the mcpwm_comparator_event_callbacks_t : mcpwm_comparator_event_callbacks_t::on_reach sets the callback function for the comparator when the timer counter equals the compare value. The callback function provides event-specific data of type mcpwm_compare_event_data_t to you. The callback function is called within the ISR context, so it should not attempt to block. For example, you may make sure that only FreeRTOS APIs with the ISR suffix are called within the function. The parameter user_data of mcpwm_comparator_register_event_callbacks() function is used to save your own context. It is passed to the callback function directly. This function will lazy the installation of interrupt service for the MCPWM comparator, whereas the service can only be removed in mcpwm_del_comparator . Set Compare Value You can set the compare value for the MCPWM comparator at runtime by calling mcpwm_comparator_set_compare_value() . There are a few points to note: A new compare value might not take effect immediately. The update time for the compare value is set by mcpwm_comparator_config_t::update_cmp_on_tez or mcpwm_comparator_config_t::update_cmp_on_tep or mcpwm_comparator_config_t::update_cmp_on_sync . Make sure the operator has connected to one MCPWM timer already by mcpwm_operator_connect_timer() . Otherwise, it will return the error code ESP_ERR_INVALID_STATE . The compare value should not exceed the timer's count peak, otherwise, the compare event will never get triggered. Generator Actions on Events Set Generator Action on Timer Event One generator can set multiple actions on different timer events, by calling mcpwm_generator_set_actions_on_timer_event() with a variable number of action configurations. The action configuration is defined in mcpwm_gen_timer_event_action_t : mcpwm_gen_timer_event_action_t::direction specifies the timer direction. The supported directions are listed in mcpwm_timer_direction_t . mcpwm_gen_timer_event_action_t::event specifies the timer event. The supported timer events are listed in mcpwm_timer_event_t . mcpwm_gen_timer_event_action_t::action specifies the generator action to be taken. The supported actions are listed in mcpwm_generator_action_t . There is a helper macro MCPWM_GEN_TIMER_EVENT_ACTION to simplify the construction of a timer event action entry. Please note, the argument list of mcpwm_generator_set_actions_on_timer_event() must be terminated by MCPWM_GEN_TIMER_EVENT_ACTION_END . You can also set the timer action one by one by calling mcpwm_generator_set_action_on_timer_event() without varargs. Set Generator Action on Compare Event One generator can set multiple actions on different compare events, by calling mcpwm_generator_set_actions_on_compare_event() with a variable number of action configurations. The action configuration is defined in mcpwm_gen_compare_event_action_t : mcpwm_gen_compare_event_action_t::direction specifies the timer direction. The supported directions are listed in mcpwm_timer_direction_t . mcpwm_gen_compare_event_action_t::comparator specifies the comparator handle. See MCPWM Comparators for how to allocate a comparator. mcpwm_gen_compare_event_action_t::action specifies the generator action to be taken. The supported actions are listed in mcpwm_generator_action_t . There is a helper macro MCPWM_GEN_COMPARE_EVENT_ACTION to simplify the construction of a compare event action entry. Please note, the argument list of mcpwm_generator_set_actions_on_compare_event() must be terminated by MCPWM_GEN_COMPARE_EVENT_ACTION_END . You can also set the compare action one by one by calling mcpwm_generator_set_action_on_compare_event() without varargs. Set Generator Action on Fault Event One generator can set action on fault based trigger events, by calling mcpwm_generator_set_action_on_fault_event() with an action configurations. The action configuration is defined in mcpwm_gen_fault_event_action_t : mcpwm_gen_fault_event_action_t::direction specifies the timer direction. The supported directions are listed in mcpwm_timer_direction_t . mcpwm_gen_fault_event_action_t::fault specifies the fault used for the trigger. See MCPWM Faults for how to allocate a fault. mcpwm_gen_fault_event_action_t::action specifies the generator action to be taken. The supported actions are listed in mcpwm_generator_action_t . When no free trigger slot is left in the operator to which the generator belongs, this function will return the ESP_ERR_NOT_FOUND error. 1 The trigger only support GPIO fault. when the input is not a GPIO fault, this function will return the ESP_ERR_NOT_SUPPORTED error. There is a helper macro MCPWM_GEN_FAULT_EVENT_ACTION to simplify the construction of a trigger event action entry. Please note, fault event does not have variadic function like mcpwm_generator_set_actions_on_fault_event() . Set Generator Action on Sync Event One generator can set action on sync based trigger events, by calling mcpwm_generator_set_action_on_sync_event() with an action configurations. The action configuration is defined in mcpwm_gen_sync_event_action_t : mcpwm_gen_sync_event_action_t::direction specifies the timer direction. The supported directions are listed in mcpwm_timer_direction_t . mcpwm_gen_sync_event_action_t::sync specifies the sync source used for the trigger. See MCPWM Sync Sources for how to allocate a sync source. mcpwm_gen_sync_event_action_t::action specifies the generator action to be taken. The supported actions are listed in mcpwm_generator_action_t . When no free trigger slot is left in the operator to which the generator belongs, this function will return the ESP_ERR_NOT_FOUND error. 1 The trigger only support one sync action, regardless of the kinds. When set sync actions more than once, this function will return the ESP_ERR_INVALID_STATE error. There is a helper macro MCPWM_GEN_SYNC_EVENT_ACTION to simplify the construction of a trigger event action entry. Please note, sync event does not have variadic function like mcpwm_generator_set_actions_on_sync_event() . Generator Configurations for Classical PWM Waveforms This section will demonstrate the classical PWM waveforms that can be generated by the pair of generators. The code snippet that is used to generate the waveforms is also provided below the diagram. Some general summary: The Symmetric or Asymmetric of the waveforms is determined by the count mode of the MCPWM timer. The active level of the waveform pair is determined by the level of the PWM with a smaller duty cycle. The period of the PWM waveform is determined by the timer's period and count mode. The duty cycle of the PWM waveform is determined by the generator's various action combinations. Single Edge Asymmetric Waveform - Active High static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(genb, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(genb, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_LOW))); } Single Edge Asymmetric Waveform - Active Low static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_FULL, MCPWM_GEN_ACTION_LOW))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(genb, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_FULL, MCPWM_GEN_ACTION_LOW))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(genb, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_HIGH))); } Pulse Placement Asymmetric Waveform static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_HIGH), MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_LOW), MCPWM_GEN_COMPARE_EVENT_ACTION_END())); ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_timer_event(genb, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_TOGGLE), MCPWM_GEN_TIMER_EVENT_ACTION_END())); } Dual Edge Asymmetric Waveform - Active Low static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_HIGH), MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_DOWN, cmpb, MCPWM_GEN_ACTION_LOW), MCPWM_GEN_COMPARE_EVENT_ACTION_END())); ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_timer_event(genb, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_LOW), MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_DOWN, MCPWM_TIMER_EVENT_FULL, MCPWM_GEN_ACTION_HIGH), MCPWM_GEN_TIMER_EVENT_ACTION_END())); } Dual Edge Symmetric Waveform - Active Low static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_HIGH), MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_DOWN, cmpa, MCPWM_GEN_ACTION_LOW), MCPWM_GEN_COMPARE_EVENT_ACTION_END())); ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_compare_event(genb, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_HIGH), MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_DOWN, cmpb, MCPWM_GEN_ACTION_LOW), MCPWM_GEN_COMPARE_EVENT_ACTION_END())); } Dual Edge Symmetric Waveform - Complementary static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_HIGH), MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_DOWN, cmpa, MCPWM_GEN_ACTION_LOW), MCPWM_GEN_COMPARE_EVENT_ACTION_END())); ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_compare_event(genb, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_LOW), MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_DOWN, cmpb, MCPWM_GEN_ACTION_HIGH), MCPWM_GEN_COMPARE_EVENT_ACTION_END())); } Dead Time In power electronics, the rectifier and inverter are commonly used. This requires the use of a rectifier bridge and an inverter bridge. Each bridge arm has two power electronic devices, such as MOSFET, IGBT, etc. The two MOSFETs on the same arm can not conduct at the same time, otherwise there will be a short circuit. The fact is that, although the PWM wave shows it is turning off the switch, the MOSFET still needs a small time window to make that happen. This requires an extra delay to be added to the existing PWM wave generated by setting Generator Actions on Events. The dead time driver works like a decorator. This is also reflected in the function parameters of mcpwm_generator_set_dead_time() , where it takes the primary generator handle ( in_generator ), and returns a new generator ( out_generator ) after applying the dead time. Please note, if the out_generator and in_generator are the same, it means you are adding the time delay to the PWM waveform in an "in-place" fashion. In turn, if the out_generator and in_generator are different, it means you are deriving a new PWM waveform from the existing in_generator . Dead time specific configuration is listed in the mcpwm_dead_time_config_t structure: mcpwm_dead_time_config_t::posedge_delay_ticks and mcpwm_dead_time_config_t::negedge_delay_ticks set the number of ticks to delay the PWM waveform on the rising and falling edge. Specifically, setting both of them to zero means bypassing the dead time module. The resolution of the dead time tick is the same as the timer that is connected with the operator by mcpwm_operator_connect_timer() . mcpwm_dead_time_config_t::invert_output sets whether to invert the signal after applying the dead time, which can be used to control the delay edge polarity. Warning Due to the hardware limitation, one delay module (either posedge delay or negedge delay ) can not be applied to multiple MCPWM generators at the same time. e.g., the following configuration is invalid: mcpwm_dead_time_config_t dt_config = { .posedge_delay_ticks = 10, }; // Set posedge delay to generator A mcpwm_generator_set_dead_time(mcpwm_gen_a, mcpwm_gen_a, &dt_config); // NOTE: This is invalid, you can not apply the posedge delay to another generator mcpwm_generator_set_dead_time(mcpwm_gen_b, mcpwm_gen_b, &dt_config); However, you can apply posedge delay to generator A and negedge delay to generator B. You can also set both posedge delay and negedge delay for generator A, while letting generator B bypass the dead time module. Note It is also possible to generate the required dead time by setting Generator Actions on Events, especially by controlling edge placement using different comparators. However, if the more classical edge delay-based dead time with polarity control is required, then the dead time submodule should be used. Dead Time Configurations for Classical PWM Waveforms This section demonstrates the classical PWM waveforms that can be generated by the dead time submodule. The code snippet that is used to generate the waveforms is also provided below the diagram. Active High Complementary static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); } static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb) { mcpwm_dead_time_config_t dead_time_config = { .posedge_delay_ticks = 50, .negedge_delay_ticks = 0 }; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config)); dead_time_config.posedge_delay_ticks = 0; dead_time_config.negedge_delay_ticks = 100; dead_time_config.flags.invert_output = true; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, genb, &dead_time_config)); } Active Low Complementary static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); } static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb) { mcpwm_dead_time_config_t dead_time_config = { .posedge_delay_ticks = 50, .negedge_delay_ticks = 0, .flags.invert_output = true }; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config)); dead_time_config.posedge_delay_ticks = 0; dead_time_config.negedge_delay_ticks = 100; dead_time_config.flags.invert_output = false; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, genb, &dead_time_config)); } Active High static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); } static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb) { mcpwm_dead_time_config_t dead_time_config = { .posedge_delay_ticks = 50, .negedge_delay_ticks = 0, }; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config)); dead_time_config.posedge_delay_ticks = 0; dead_time_config.negedge_delay_ticks = 100; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, genb, &dead_time_config)); } Active Low static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); } static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb) { mcpwm_dead_time_config_t dead_time_config = { .posedge_delay_ticks = 50, .negedge_delay_ticks = 0, .flags.invert_output = true }; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config)); dead_time_config.posedge_delay_ticks = 0; dead_time_config.negedge_delay_ticks = 100; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, genb, &dead_time_config)); } Rising Delay on PWMA and Bypass Dead Time for PWMB static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(genb, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(genb, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_LOW))); } static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb) { mcpwm_dead_time_config_t dead_time_config = { .posedge_delay_ticks = 50, .negedge_delay_ticks = 0, }; // apply deadtime to generator_a ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config)); // bypass deadtime module for generator_b dead_time_config.posedge_delay_ticks = 0; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(genb, genb, &dead_time_config)); } Falling Delay on PWMB and Bypass Dead Time for PWMA static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(genb, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(genb, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_LOW))); } static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb) { mcpwm_dead_time_config_t dead_time_config = { .posedge_delay_ticks = 0, .negedge_delay_ticks = 0, }; // generator_a bypass the deadtime module (no delay) ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config)); // apply dead time to generator_b dead_time_config.negedge_delay_ticks = 50; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(genb, genb, &dead_time_config)); } Rising and Falling Delay on PWMB and Bypass Dead Time for PWMA static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(genb, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(genb, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_LOW))); } static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb) { mcpwm_dead_time_config_t dead_time_config = { .posedge_delay_ticks = 0, .negedge_delay_ticks = 0, }; // generator_a bypass the deadtime module (no delay) ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config)); // apply dead time on both edge for generator_b dead_time_config.negedge_delay_ticks = 50; dead_time_config.posedge_delay_ticks = 50; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(genb, genb, &dead_time_config)); } Carrier Modulation The MCPWM operator has a carrier submodule that can be used if galvanic isolation from the motor driver is required (e.g., isolated digital power application) by passing the PWM output signals through transformers. Any of the PWM output signals may be at 100% duty and not changing whenever a motor is required to run steadily at the full load. Coupling with non-alternating signals with a transformer is problematic, so the signals are modulated by the carrier submodule to create an AC waveform, to make the coupling possible. To configure the carrier submodule, you can call mcpwm_operator_apply_carrier() , and provide configuration structure mcpwm_carrier_config_t : mcpwm_carrier_config_t::clk_src sets the clock source of the carrier. mcpwm_carrier_config_t::frequency_hz indicates carrier frequency in Hz. mcpwm_carrier_config_t::duty_cycle indicates the duty cycle of the carrier. Note that, the supported choices of the duty cycle are discrete, the driver searches for the nearest one based on your configuration. mcpwm_carrier_config_t::first_pulse_duration_us indicates the duration of the first pulse in microseconds. The resolution of the first pulse duration is determined by the carrier frequency you set in the mcpwm_carrier_config_t::frequency_hz . The first pulse duration can not be zero, and it has to be at least one period of the carrier. A longer pulse width can help conduct the inductance quicker. mcpwm_carrier_config_t::invert_before_modulate and mcpwm_carrier_config_t::invert_after_modulate set whether to invert the carrier output before and after modulation. Specifically, the carrier submodule can be disabled by calling mcpwm_operator_apply_carrier() with a NULL configuration. Faults and Brake Actions The MCPWM operator is able to sense external signals with information about the failure of the motor, the power driver or any other device connected. These failure signals are encapsulated into MCPWM fault objects. You should determine possible failure modes of the motor and what action should be performed on detection of a particular fault, e.g., drive all outputs low for a brushed motor, lock current state for a stepper motor, etc. Because of this action, the motor should be put into a safe state to reduce the likelihood of damage caused by the fault. Set Operator Brake Mode on Fault The way that MCPWM operator reacts to the fault is called Brake. The MCPWM operator can be configured to perform different brake modes for each fault object by calling mcpwm_operator_set_brake_on_fault() . Specific brake configuration is passed as a structure mcpwm_brake_config_t : mcpwm_brake_config_t::fault sets which fault the operator should react to. mcpwm_brake_config_t::brake_mode sets the brake mode that should be used for the fault. The supported brake modes are listed in the mcpwm_operator_brake_mode_t . For MCPWM_OPER_BRAKE_MODE_CBC mode, the operator recovers itself automatically as long as the fault disappears. You can specify the recovery time in mcpwm_brake_config_t::cbc_recover_on_tez and mcpwm_brake_config_t::cbc_recover_on_tep . For MCPWM_OPER_BRAKE_MODE_OST mode, the operator can not recover even though the fault disappears. You have to call mcpwm_operator_recover_from_fault() to manually recover it. Set Generator Action on Brake Event One generator can set multiple actions on different brake events, by calling mcpwm_generator_set_actions_on_brake_event() with a variable number of action configurations. The action configuration is defined in mcpwm_gen_brake_event_action_t : mcpwm_gen_brake_event_action_t::direction specifies the timer direction. The supported directions are listed in mcpwm_timer_direction_t . mcpwm_gen_brake_event_action_t::brake_mode specifies the brake mode. The supported brake modes are listed in the mcpwm_operator_brake_mode_t . mcpwm_gen_brake_event_action_t::action specifies the generator action to be taken. The supported actions are listed in mcpwm_generator_action_t . There is a helper macro MCPWM_GEN_BRAKE_EVENT_ACTION to simplify the construction of a brake event action entry. Please note, the argument list of mcpwm_generator_set_actions_on_brake_event() must be terminated by MCPWM_GEN_BRAKE_EVENT_ACTION_END . You can also set the brake action one by one by calling mcpwm_generator_set_action_on_brake_event() without varargs. Register Fault Event Callbacks The MCPWM fault detector can inform you when it detects a valid fault or a fault signal disappears. If you have some function that should be called when such an event happens, you should hook your function to the interrupt service routine by calling mcpwm_fault_register_event_callbacks() . The callback function prototype is declared in mcpwm_fault_event_cb_t . All supported event callbacks are listed in the mcpwm_fault_event_callbacks_t : mcpwm_fault_event_callbacks_t::on_fault_enter sets the callback function that will be called when a fault is detected. mcpwm_fault_event_callbacks_t::on_fault_exit sets the callback function that will be called when a fault is cleared. The callback function is called within the ISR context, so it should not attempt to block. For example, you may make sure that only FreeRTOS APIs with the ISR suffix are called within the function. The parameter user_data of mcpwm_fault_register_event_callbacks() function is used to save your own context. It is passed to the callback function directly. This function will lazy the install interrupt service for the MCPWM fault, whereas the service can only be removed in mcpwm_del_fault . Register Brake Event Callbacks The MCPWM operator can inform you when it is going to take a brake action. If you have some function that should be called when this event happens, you should hook your function to the interrupt service routine by calling mcpwm_operator_register_event_callbacks() . The callback function prototype is declared in mcpwm_brake_event_cb_t . All supported event callbacks are listed in the mcpwm_operator_event_callbacks_t : mcpwm_operator_event_callbacks_t::on_brake_cbc sets the callback function that will be called when the operator is going to take a CBC action. mcpwm_operator_event_callbacks_t::on_brake_ost sets the callback function that will be called when the operator is going to take an OST action. The callback function is called within the ISR context, so it should not attempt to block. For example, you may make sure that only FreeRTOS APIs with the ISR suffix are called within the function. The parameter user_data of the mcpwm_operator_register_event_callbacks() function is used to save your own context. It will be passed to the callback function directly. This function will lazy the install interrupt service for the MCPWM operator, whereas the service can only be removed in mcpwm_del_operator . Generator Force Actions Software can override generator output level at runtime, by calling mcpwm_generator_set_force_level() . The software force level always has a higher priority than other event actions set in e.g., mcpwm_generator_set_actions_on_timer_event() . Set the level to -1 means to disable the force action, and the generator's output level will be controlled by the event actions again. Set the hold_on to true, and the force output level will keep alive until it is removed by assigning level to -1. Set the hole_on to false, the force output level will only be active for a short time, and any upcoming event can override it. Synchronization When a sync signal is taken by the MCPWM timer, the timer will be forced into a predefined phase, where the phase is determined by count value and count direction. You can set the sync phase by calling mcpwm_timer_set_phase_on_sync() . The sync phase configuration is defined in mcpwm_timer_sync_phase_config_t structure: mcpwm_timer_sync_phase_config_t::sync_src sets the sync signal source. See MCPWM Sync Sources for how to create a sync source object. Specifically, if this is set to NULL , the driver will disable the sync feature for the MCPWM timer. mcpwm_timer_sync_phase_config_t::count_value sets the count value to load when the sync signal is taken. mcpwm_timer_sync_phase_config_t::direction sets the count direction when the sync signal is taken. Likewise, the MCPWM Capture Timer can be synced as well. You can set the sync phase for the capture timer by calling mcpwm_capture_timer_set_phase_on_sync() . The sync phase configuration is defined in mcpwm_capture_timer_sync_phase_config_t structure: mcpwm_capture_timer_sync_phase_config_t::sync_src sets the sync signal source. See MCPWM Sync Sources for how to create a sync source object. Specifically, if this is set to NULL , the driver will disable the sync feature for the MCPWM capture timer. mcpwm_capture_timer_sync_phase_config_t::count_value sets the count value to load when the sync signal is taken. mcpwm_capture_timer_sync_phase_config_t::direction sets the count direction when the sync signal is taken. Note that, different from MCPWM Timer, the capture timer can only support one count direction: MCPWM_TIMER_DIRECTION_UP . Sync Timers by GPIO static void example_setup_sync_strategy(mcpwm_timer_handle_t timers[]) { mcpwm_sync_handle_t gpio_sync_source = NULL; mcpwm_gpio_sync_src_config_t gpio_sync_config = { .group_id = 0, // GPIO fault should be in the same group of the above timers .gpio_num = EXAMPLE_SYNC_GPIO, .flags.pull_down = true, .flags.active_neg = false, // By default, a posedge pulse can trigger a sync event }; ESP_ERROR_CHECK(mcpwm_new_gpio_sync_src(&gpio_sync_config, &gpio_sync_source)); mcpwm_timer_sync_phase_config_t sync_phase_config = { .count_value = 0, // sync phase: target count value .direction = MCPWM_TIMER_DIRECTION_UP, // sync phase: count direction .sync_src = gpio_sync_source, // sync source }; for (int i = 0; i < 3; i++) { ESP_ERROR_CHECK(mcpwm_timer_set_phase_on_sync(timers[i], &sync_phase_config)); } } Capture The basic functionality of MCPWM capture is to record the time when any pulse edge of the capture signal turns active. Then you can get the pulse width and convert it into other physical quantities like distance or speed in the capture callback function. For example, in the BLDC (Brushless DC, see figure below) scenario, you can use the capture submodule to sense the rotor position from the Hall sensor. The capture timer is usually connected to several capture channels. Please refer to MCPWM Capture Timer and Channels for more information about resource allocation. Register Capture Event Callbacks The MCPWM capture channel can inform you when there is a valid edge detected on the signal. You have to register a callback function to get the timer count value of the captured moment, by calling mcpwm_capture_channel_register_event_callbacks() . The callback function prototype is declared in mcpwm_capture_event_cb_t . All supported capture callbacks are listed in the mcpwm_capture_event_callbacks_t : mcpwm_capture_event_callbacks_t::on_cap sets the callback function for the capture channel when a valid edge is detected. The callback function provides event-specific data of type mcpwm_capture_event_data_t , so that you can get the edge of the capture signal in mcpwm_capture_event_data_t::cap_edge and the count value of that moment in mcpwm_capture_event_data_t::cap_value . To convert the capture count into a timestamp, you need to know the resolution of the capture timer by calling mcpwm_capture_timer_get_resolution() . The callback function is called within the ISR context, so it should not attempt to block. For example, you may make sure that only FreeRTOS APIs with the ISR suffix are called within the function. The parameter user_data of mcpwm_capture_channel_register_event_callbacks() function is used to save your context. It is passed to the callback function directly. This function will lazy install interrupt service for the MCPWM capture channel, whereas the service can only be removed in mcpwm_del_capture_channel . Enable and Disable Capture Channel The capture channel is not enabled after allocation by mcpwm_new_capture_channel() . You should call mcpwm_capture_channel_enable() and mcpwm_capture_channel_disable() accordingly to enable or disable the channel. If the interrupt service is lazy installed during registering event callbacks for the channel in mcpwm_capture_channel_register_event_callbacks() , mcpwm_capture_channel_enable() will enable the interrupt service as well. Enable and Disable Capture Timer Before doing IO control to the capture timer, you need to enable the timer first, by calling mcpwm_capture_timer_enable() . Internally, this function: switches the capture timer state from init to enable. acquires a proper power management lock if a specific clock source (e.g., APB clock) is selected. See also Power management for more information. On the contrary, calling mcpwm_capture_timer_disable() will put the timer driver back to init state, and release the power management lock. Start and Stop Capture Timer The basic IO operation of a capture timer is to start and stop. Calling mcpwm_capture_timer_start() can start the timer and calling mcpwm_capture_timer_stop() can stop the timer immediately. Trigger a Software Capture Event Sometimes, the software also wants to trigger a "fake" capture event. The mcpwm_capture_channel_trigger_soft_catch() is provided for that purpose. Please note that, even though it is a "fake" capture event, it can still cause an interrupt, thus your capture event callback function gets invoked as well. Power Management When power management is enabled (i.e., CONFIG_PM_ENABLE is on), the system will adjust the PLL and APB frequency before going into Light-sleep, thus potentially changing the period of an MCPWM timers' counting step and leading to inaccurate time-keeping. However, the driver can prevent the system from changing APB frequency by acquiring a power management lock of type ESP_PM_APB_FREQ_MAX . Whenever the driver creates an MCPWM timer instance that has selected MCPWM_TIMER_CLK_SRC_PLL160M as its clock source, the driver guarantees that the power management lock is acquired when enabling the timer by mcpwm_timer_enable() . On the contrary, the driver releases the lock when mcpwm_timer_disable() is called for that timer. Likewise, whenever the driver creates an MCPWM capture timer instance that has selected MCPWM_CAPTURE_CLK_SRC_APB as its clock source, the driver guarantees that the power management lock is acquired when enabling the timer by mcpwm_capture_timer_enable() . And releases the lock in mcpwm_capture_timer_disable() . IRAM Safe By default, the MCPWM interrupt will be deferred when the Cache is disabled for reasons like writing/erasing Flash. Thus the event callback functions will not get executed in time, which is not expected in a real-time application. There is a Kconfig option CONFIG_MCPWM_ISR_IRAM_SAFE that: enables the interrupt to be serviced even when the cache is disabled places all functions used by the ISR into IRAM 2 places the driver object into DRAM (in case it is mapped to PSRAM by accident) This allows the interrupt to run while the cache is disabled but comes at the cost of increased IRAM consumption. There is another Kconfig option CONFIG_MCPWM_CTRL_FUNC_IN_IRAM that can put commonly used IO control functions into IRAM as well. So, these functions can also be executable when the cache is disabled. The IO control function is as follows: Thread Safety The factory functions like mcpwm_new_timer() are guaranteed to be thread-safe by the driver, which means, you can call it from different RTOS tasks without protection by extra locks. The following function is allowed to run under the ISR context, as the driver uses a critical section to prevent them from being called concurrently in the task and ISR. Other functions that are not related to Resource Allocation and Initialization, are not thread-safe. Thus, you should avoid calling them in different tasks without mutex protection. Kconfig Options CONFIG_MCPWM_ISR_IRAM_SAFE controls whether the default ISR handler can work when the cache is disabled, see IRAM Safe for more information. CONFIG_MCPWM_CTRL_FUNC_IN_IRAM controls where to place the MCPWM control functions (IRAM or flash), see IRAM Safe for more information. CONFIG_MCPWM_ENABLE_DEBUG_LOG is used to enable the debug log output. Enabling this option will increase the firmware binary size. Application Examples Brushed DC motor speed control by PID algorithm: peripherals/mcpwm/mcpwm_bdc_speed_control BLDC motor control with hall sensor feedback: peripherals/mcpwm/mcpwm_bldc_hall_control Ultrasonic sensor (HC-SR04) distance measurement: peripherals/mcpwm/mcpwm_capture_hc_sr04 Servo motor angle control: peripherals/mcpwm/mcpwm_servo_control MCPWM synchronization between timers: peripherals/mcpwm/mcpwm_sync API Reference Header File This header file can be included with: #include "driver/mcpwm_timer.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t mcpwm_new_timer(const mcpwm_timer_config_t *config, mcpwm_timer_handle_t *ret_timer) Create MCPWM timer. Parameters config -- [in] MCPWM timer configuration ret_timer -- [out] Returned MCPWM timer handle config -- [in] MCPWM timer configuration ret_timer -- [out] Returned MCPWM timer handle config -- [in] MCPWM timer configuration Returns ESP_OK: Create MCPWM timer successfully ESP_ERR_INVALID_ARG: Create MCPWM timer failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM timer failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM timer failed because all hardware timers are used up and no more free one ESP_FAIL: Create MCPWM timer failed because of other error ESP_OK: Create MCPWM timer successfully ESP_ERR_INVALID_ARG: Create MCPWM timer failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM timer failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM timer failed because all hardware timers are used up and no more free one ESP_FAIL: Create MCPWM timer failed because of other error ESP_OK: Create MCPWM timer successfully Parameters config -- [in] MCPWM timer configuration ret_timer -- [out] Returned MCPWM timer handle Returns ESP_OK: Create MCPWM timer successfully ESP_ERR_INVALID_ARG: Create MCPWM timer failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM timer failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM timer failed because all hardware timers are used up and no more free one ESP_FAIL: Create MCPWM timer failed because of other error esp_err_t mcpwm_del_timer(mcpwm_timer_handle_t timer) Delete MCPWM timer. Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() Returns ESP_OK: Delete MCPWM timer successfully ESP_ERR_INVALID_ARG: Delete MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Delete MCPWM timer failed because timer is not in init state ESP_FAIL: Delete MCPWM timer failed because of other error ESP_OK: Delete MCPWM timer successfully ESP_ERR_INVALID_ARG: Delete MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Delete MCPWM timer failed because timer is not in init state ESP_FAIL: Delete MCPWM timer failed because of other error ESP_OK: Delete MCPWM timer successfully Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() Returns ESP_OK: Delete MCPWM timer successfully ESP_ERR_INVALID_ARG: Delete MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Delete MCPWM timer failed because timer is not in init state ESP_FAIL: Delete MCPWM timer failed because of other error esp_err_t mcpwm_timer_set_period(mcpwm_timer_handle_t timer, uint32_t period_ticks) Set a new period for MCPWM timer. Note If mcpwm_timer_config_t::update_period_on_empty and mcpwm_timer_config_t::update_period_on_sync are not set, the new period will take effect immediately. Otherwise, the new period will take effect when timer counts to zero or on sync event. Note You may need to use mcpwm_comparator_set_compare_value to set a new compare value for MCPWM comparator in order to keep the same PWM duty cycle. Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer period_ticks -- [in] New period in count ticks timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer period_ticks -- [in] New period in count ticks timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer Returns ESP_OK: Set new period for MCPWM timer successfully ESP_ERR_INVALID_ARG: Set new period for MCPWM timer failed because of invalid argument ESP_FAIL: Set new period for MCPWM timer failed because of other error ESP_OK: Set new period for MCPWM timer successfully ESP_ERR_INVALID_ARG: Set new period for MCPWM timer failed because of invalid argument ESP_FAIL: Set new period for MCPWM timer failed because of other error ESP_OK: Set new period for MCPWM timer successfully Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer period_ticks -- [in] New period in count ticks Returns ESP_OK: Set new period for MCPWM timer successfully ESP_ERR_INVALID_ARG: Set new period for MCPWM timer failed because of invalid argument ESP_FAIL: Set new period for MCPWM timer failed because of other error esp_err_t mcpwm_timer_enable(mcpwm_timer_handle_t timer) Enable MCPWM timer. Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() Returns ESP_OK: Enable MCPWM timer successfully ESP_ERR_INVALID_ARG: Enable MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Enable MCPWM timer failed because timer is enabled already ESP_FAIL: Enable MCPWM timer failed because of other error ESP_OK: Enable MCPWM timer successfully ESP_ERR_INVALID_ARG: Enable MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Enable MCPWM timer failed because timer is enabled already ESP_FAIL: Enable MCPWM timer failed because of other error ESP_OK: Enable MCPWM timer successfully Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() Returns ESP_OK: Enable MCPWM timer successfully ESP_ERR_INVALID_ARG: Enable MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Enable MCPWM timer failed because timer is enabled already ESP_FAIL: Enable MCPWM timer failed because of other error esp_err_t mcpwm_timer_disable(mcpwm_timer_handle_t timer) Disable MCPWM timer. Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() Returns ESP_OK: Disable MCPWM timer successfully ESP_ERR_INVALID_ARG: Disable MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Disable MCPWM timer failed because timer is disabled already ESP_FAIL: Disable MCPWM timer failed because of other error ESP_OK: Disable MCPWM timer successfully ESP_ERR_INVALID_ARG: Disable MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Disable MCPWM timer failed because timer is disabled already ESP_FAIL: Disable MCPWM timer failed because of other error ESP_OK: Disable MCPWM timer successfully Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() Returns ESP_OK: Disable MCPWM timer successfully ESP_ERR_INVALID_ARG: Disable MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Disable MCPWM timer failed because timer is disabled already ESP_FAIL: Disable MCPWM timer failed because of other error esp_err_t mcpwm_timer_start_stop(mcpwm_timer_handle_t timer, mcpwm_timer_start_stop_cmd_t command) Send specific start/stop commands to MCPWM timer. Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() command -- [in] Supported command list for MCPWM timer timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() command -- [in] Supported command list for MCPWM timer timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() Returns ESP_OK: Start or stop MCPWM timer successfully ESP_ERR_INVALID_ARG: Start or stop MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Start or stop MCPWM timer failed because timer is not enabled ESP_FAIL: Start or stop MCPWM timer failed because of other error ESP_OK: Start or stop MCPWM timer successfully ESP_ERR_INVALID_ARG: Start or stop MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Start or stop MCPWM timer failed because timer is not enabled ESP_FAIL: Start or stop MCPWM timer failed because of other error ESP_OK: Start or stop MCPWM timer successfully Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() command -- [in] Supported command list for MCPWM timer Returns ESP_OK: Start or stop MCPWM timer successfully ESP_ERR_INVALID_ARG: Start or stop MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Start or stop MCPWM timer failed because timer is not enabled ESP_FAIL: Start or stop MCPWM timer failed because of other error esp_err_t mcpwm_timer_register_event_callbacks(mcpwm_timer_handle_t timer, const mcpwm_timer_event_callbacks_t *cbs, void *user_data) Set event callbacks for MCPWM timer. Note The first call to this function needs to be before the call to mcpwm_timer_enable Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbs structure to NULL. Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because timer is not in init state ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because timer is not in init state ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because timer is not in init state ESP_FAIL: Set event callbacks failed because of other error esp_err_t mcpwm_timer_set_phase_on_sync(mcpwm_timer_handle_t timer, const mcpwm_timer_sync_phase_config_t *config) Set sync phase for MCPWM timer. Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() config -- [in] MCPWM timer sync phase configuration timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() config -- [in] MCPWM timer sync phase configuration timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() Returns ESP_OK: Set sync phase for MCPWM timer successfully ESP_ERR_INVALID_ARG: Set sync phase for MCPWM timer failed because of invalid argument ESP_FAIL: Set sync phase for MCPWM timer failed because of other error ESP_OK: Set sync phase for MCPWM timer successfully ESP_ERR_INVALID_ARG: Set sync phase for MCPWM timer failed because of invalid argument ESP_FAIL: Set sync phase for MCPWM timer failed because of other error ESP_OK: Set sync phase for MCPWM timer successfully Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() config -- [in] MCPWM timer sync phase configuration Returns ESP_OK: Set sync phase for MCPWM timer successfully ESP_ERR_INVALID_ARG: Set sync phase for MCPWM timer failed because of invalid argument ESP_FAIL: Set sync phase for MCPWM timer failed because of other error Structures struct mcpwm_timer_event_callbacks_t Group of supported MCPWM timer event callbacks. Note The callbacks are all running under ISR environment Public Members mcpwm_timer_event_cb_t on_full callback function when MCPWM timer counts to peak value mcpwm_timer_event_cb_t on_full callback function when MCPWM timer counts to peak value mcpwm_timer_event_cb_t on_empty callback function when MCPWM timer counts to zero mcpwm_timer_event_cb_t on_empty callback function when MCPWM timer counts to zero mcpwm_timer_event_cb_t on_stop callback function when MCPWM timer stops mcpwm_timer_event_cb_t on_stop callback function when MCPWM timer stops mcpwm_timer_event_cb_t on_full struct mcpwm_timer_config_t MCPWM timer configuration. Public Members int group_id Specify from which group to allocate the MCPWM timer int group_id Specify from which group to allocate the MCPWM timer mcpwm_timer_clock_source_t clk_src MCPWM timer clock source mcpwm_timer_clock_source_t clk_src MCPWM timer clock source uint32_t resolution_hz Counter resolution in Hz The step size of each count tick equals to (1 / resolution_hz) seconds uint32_t resolution_hz Counter resolution in Hz The step size of each count tick equals to (1 / resolution_hz) seconds mcpwm_timer_count_mode_t count_mode Count mode mcpwm_timer_count_mode_t count_mode Count mode uint32_t period_ticks Number of count ticks within a period uint32_t period_ticks Number of count ticks within a period int intr_priority MCPWM timer interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) int intr_priority MCPWM timer interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) uint32_t update_period_on_empty Whether to update period when timer counts to zero uint32_t update_period_on_empty Whether to update period when timer counts to zero uint32_t update_period_on_sync Whether to update period on sync event uint32_t update_period_on_sync Whether to update period on sync event struct mcpwm_timer_config_t::[anonymous] flags Extra configuration flags for timer struct mcpwm_timer_config_t::[anonymous] flags Extra configuration flags for timer int group_id struct mcpwm_timer_sync_phase_config_t MCPWM Timer sync phase configuration. Public Members mcpwm_sync_handle_t sync_src The sync event source. Set to NULL will disable the timer being synced by others mcpwm_sync_handle_t sync_src The sync event source. Set to NULL will disable the timer being synced by others uint32_t count_value The count value that should lock to upon sync event uint32_t count_value The count value that should lock to upon sync event mcpwm_timer_direction_t direction The count direction that should lock to upon sync event mcpwm_timer_direction_t direction The count direction that should lock to upon sync event mcpwm_sync_handle_t sync_src Header File This header file can be included with: #include "driver/mcpwm_oper.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t mcpwm_new_operator(const mcpwm_operator_config_t *config, mcpwm_oper_handle_t *ret_oper) Create MCPWM operator. Parameters config -- [in] MCPWM operator configuration ret_oper -- [out] Returned MCPWM operator handle config -- [in] MCPWM operator configuration ret_oper -- [out] Returned MCPWM operator handle config -- [in] MCPWM operator configuration Returns ESP_OK: Create MCPWM operator successfully ESP_ERR_INVALID_ARG: Create MCPWM operator failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM operator failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM operator failed because can't find free resource ESP_FAIL: Create MCPWM operator failed because of other error ESP_OK: Create MCPWM operator successfully ESP_ERR_INVALID_ARG: Create MCPWM operator failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM operator failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM operator failed because can't find free resource ESP_FAIL: Create MCPWM operator failed because of other error ESP_OK: Create MCPWM operator successfully Parameters config -- [in] MCPWM operator configuration ret_oper -- [out] Returned MCPWM operator handle Returns ESP_OK: Create MCPWM operator successfully ESP_ERR_INVALID_ARG: Create MCPWM operator failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM operator failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM operator failed because can't find free resource ESP_FAIL: Create MCPWM operator failed because of other error esp_err_t mcpwm_del_operator(mcpwm_oper_handle_t oper) Delete MCPWM operator. Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() Returns ESP_OK: Delete MCPWM operator successfully ESP_ERR_INVALID_ARG: Delete MCPWM operator failed because of invalid argument ESP_FAIL: Delete MCPWM operator failed because of other error ESP_OK: Delete MCPWM operator successfully ESP_ERR_INVALID_ARG: Delete MCPWM operator failed because of invalid argument ESP_FAIL: Delete MCPWM operator failed because of other error ESP_OK: Delete MCPWM operator successfully Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() Returns ESP_OK: Delete MCPWM operator successfully ESP_ERR_INVALID_ARG: Delete MCPWM operator failed because of invalid argument ESP_FAIL: Delete MCPWM operator failed because of other error esp_err_t mcpwm_operator_connect_timer(mcpwm_oper_handle_t oper, mcpwm_timer_handle_t timer) Connect MCPWM operator and timer, so that the operator can be driven by the timer. Parameters oper -- [in] MCPWM operator handle, allocated by mcpwm_new_operator() timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() oper -- [in] MCPWM operator handle, allocated by mcpwm_new_operator() timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() oper -- [in] MCPWM operator handle, allocated by mcpwm_new_operator() Returns ESP_OK: Connect MCPWM operator and timer successfully ESP_ERR_INVALID_ARG: Connect MCPWM operator and timer failed because of invalid argument ESP_FAIL: Connect MCPWM operator and timer failed because of other error ESP_OK: Connect MCPWM operator and timer successfully ESP_ERR_INVALID_ARG: Connect MCPWM operator and timer failed because of invalid argument ESP_FAIL: Connect MCPWM operator and timer failed because of other error ESP_OK: Connect MCPWM operator and timer successfully Parameters oper -- [in] MCPWM operator handle, allocated by mcpwm_new_operator() timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() Returns ESP_OK: Connect MCPWM operator and timer successfully ESP_ERR_INVALID_ARG: Connect MCPWM operator and timer failed because of invalid argument ESP_FAIL: Connect MCPWM operator and timer failed because of other error esp_err_t mcpwm_operator_set_brake_on_fault(mcpwm_oper_handle_t oper, const mcpwm_brake_config_t *config) Set brake method for MCPWM operator. Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() config -- [in] MCPWM brake configuration oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() config -- [in] MCPWM brake configuration oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() Returns ESP_OK: Set trip for operator successfully ESP_ERR_INVALID_ARG: Set trip for operator failed because of invalid argument ESP_FAIL: Set trip for operator failed because of other error ESP_OK: Set trip for operator successfully ESP_ERR_INVALID_ARG: Set trip for operator failed because of invalid argument ESP_FAIL: Set trip for operator failed because of other error ESP_OK: Set trip for operator successfully Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() config -- [in] MCPWM brake configuration Returns ESP_OK: Set trip for operator successfully ESP_ERR_INVALID_ARG: Set trip for operator failed because of invalid argument ESP_FAIL: Set trip for operator failed because of other error esp_err_t mcpwm_operator_recover_from_fault(mcpwm_oper_handle_t oper, mcpwm_fault_handle_t fault) Try to make the operator recover from fault. Note To recover from fault or escape from trip, you make sure the fault signal has dissappeared already. Otherwise the recovery can't succeed. Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() fault -- [in] MCPWM fault handle oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() fault -- [in] MCPWM fault handle oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() Returns ESP_OK: Recover from fault successfully ESP_ERR_INVALID_ARG: Recover from fault failed because of invalid argument ESP_ERR_INVALID_STATE: Recover from fault failed because the fault source is still active ESP_FAIL: Recover from fault failed because of other error ESP_OK: Recover from fault successfully ESP_ERR_INVALID_ARG: Recover from fault failed because of invalid argument ESP_ERR_INVALID_STATE: Recover from fault failed because the fault source is still active ESP_FAIL: Recover from fault failed because of other error ESP_OK: Recover from fault successfully Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() fault -- [in] MCPWM fault handle Returns ESP_OK: Recover from fault successfully ESP_ERR_INVALID_ARG: Recover from fault failed because of invalid argument ESP_ERR_INVALID_STATE: Recover from fault failed because the fault source is still active ESP_FAIL: Recover from fault failed because of other error esp_err_t mcpwm_operator_register_event_callbacks(mcpwm_oper_handle_t oper, const mcpwm_operator_event_callbacks_t *cbs, void *user_data) Set event callbacks for MCPWM operator. Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbs structure to NULL. Parameters oper -- [in] MCPWM operator handle, allocated by mcpwm_new_operator() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly oper -- [in] MCPWM operator handle, allocated by mcpwm_new_operator() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly oper -- [in] MCPWM operator handle, allocated by mcpwm_new_operator() Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully Parameters oper -- [in] MCPWM operator handle, allocated by mcpwm_new_operator() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error esp_err_t mcpwm_operator_apply_carrier(mcpwm_oper_handle_t oper, const mcpwm_carrier_config_t *config) Apply carrier feature for MCPWM operator. Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() config -- [in] MCPWM carrier specific configuration oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() config -- [in] MCPWM carrier specific configuration oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() Returns ESP_OK: Set carrier for operator successfully ESP_ERR_INVALID_ARG: Set carrier for operator failed because of invalid argument ESP_FAIL: Set carrier for operator failed because of other error ESP_OK: Set carrier for operator successfully ESP_ERR_INVALID_ARG: Set carrier for operator failed because of invalid argument ESP_FAIL: Set carrier for operator failed because of other error ESP_OK: Set carrier for operator successfully Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() config -- [in] MCPWM carrier specific configuration Returns ESP_OK: Set carrier for operator successfully ESP_ERR_INVALID_ARG: Set carrier for operator failed because of invalid argument ESP_FAIL: Set carrier for operator failed because of other error Structures struct mcpwm_operator_config_t MCPWM operator configuration. Public Members int group_id Specify from which group to allocate the MCPWM operator int group_id Specify from which group to allocate the MCPWM operator int intr_priority MCPWM operator interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) int intr_priority MCPWM operator interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) uint32_t update_gen_action_on_tez Whether to update generator action when timer counts to zero uint32_t update_gen_action_on_tez Whether to update generator action when timer counts to zero uint32_t update_gen_action_on_tep Whether to update generator action when timer counts to peak uint32_t update_gen_action_on_tep Whether to update generator action when timer counts to peak uint32_t update_gen_action_on_sync Whether to update generator action on sync event uint32_t update_gen_action_on_sync Whether to update generator action on sync event uint32_t update_dead_time_on_tez Whether to update dead time when timer counts to zero uint32_t update_dead_time_on_tez Whether to update dead time when timer counts to zero uint32_t update_dead_time_on_tep Whether to update dead time when timer counts to peak uint32_t update_dead_time_on_tep Whether to update dead time when timer counts to peak uint32_t update_dead_time_on_sync Whether to update dead time on sync event uint32_t update_dead_time_on_sync Whether to update dead time on sync event struct mcpwm_operator_config_t::[anonymous] flags Extra configuration flags for operator struct mcpwm_operator_config_t::[anonymous] flags Extra configuration flags for operator int group_id struct mcpwm_brake_config_t MCPWM brake configuration structure. Public Members mcpwm_fault_handle_t fault Which fault causes the operator to brake mcpwm_fault_handle_t fault Which fault causes the operator to brake mcpwm_operator_brake_mode_t brake_mode Brake mode mcpwm_operator_brake_mode_t brake_mode Brake mode uint32_t cbc_recover_on_tez Recovery CBC brake state on tez event uint32_t cbc_recover_on_tez Recovery CBC brake state on tez event uint32_t cbc_recover_on_tep Recovery CBC brake state on tep event uint32_t cbc_recover_on_tep Recovery CBC brake state on tep event struct mcpwm_brake_config_t::[anonymous] flags Extra flags for brake configuration struct mcpwm_brake_config_t::[anonymous] flags Extra flags for brake configuration mcpwm_fault_handle_t fault struct mcpwm_operator_event_callbacks_t Group of supported MCPWM operator event callbacks. Note The callbacks are all running under ISR environment Public Members mcpwm_brake_event_cb_t on_brake_cbc callback function when mcpwm operator brakes in CBC mcpwm_brake_event_cb_t on_brake_cbc callback function when mcpwm operator brakes in CBC mcpwm_brake_event_cb_t on_brake_ost callback function when mcpwm operator brakes in OST mcpwm_brake_event_cb_t on_brake_ost callback function when mcpwm operator brakes in OST mcpwm_brake_event_cb_t on_brake_cbc struct mcpwm_carrier_config_t MCPWM carrier configuration structure. Public Members mcpwm_carrier_clock_source_t clk_src MCPWM carrier clock source mcpwm_carrier_clock_source_t clk_src MCPWM carrier clock source uint32_t frequency_hz Carrier frequency in Hz uint32_t frequency_hz Carrier frequency in Hz uint32_t first_pulse_duration_us The duration of the first PWM pulse, in us uint32_t first_pulse_duration_us The duration of the first PWM pulse, in us float duty_cycle Carrier duty cycle float duty_cycle Carrier duty cycle uint32_t invert_before_modulate Invert the raw signal uint32_t invert_before_modulate Invert the raw signal uint32_t invert_after_modulate Invert the modulated signal uint32_t invert_after_modulate Invert the modulated signal struct mcpwm_carrier_config_t::[anonymous] flags Extra flags for carrier configuration struct mcpwm_carrier_config_t::[anonymous] flags Extra flags for carrier configuration mcpwm_carrier_clock_source_t clk_src Header File This header file can be included with: #include "driver/mcpwm_cmpr.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t mcpwm_new_comparator(mcpwm_oper_handle_t oper, const mcpwm_comparator_config_t *config, mcpwm_cmpr_handle_t *ret_cmpr) Create MCPWM comparator. Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() , the new comparator will be allocated from this operator config -- [in] MCPWM comparator configuration ret_cmpr -- [out] Returned MCPWM comparator oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() , the new comparator will be allocated from this operator config -- [in] MCPWM comparator configuration ret_cmpr -- [out] Returned MCPWM comparator oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() , the new comparator will be allocated from this operator Returns ESP_OK: Create MCPWM comparator successfully ESP_ERR_INVALID_ARG: Create MCPWM comparator failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM comparator failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM comparator failed because can't find free resource ESP_FAIL: Create MCPWM comparator failed because of other error ESP_OK: Create MCPWM comparator successfully ESP_ERR_INVALID_ARG: Create MCPWM comparator failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM comparator failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM comparator failed because can't find free resource ESP_FAIL: Create MCPWM comparator failed because of other error ESP_OK: Create MCPWM comparator successfully Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() , the new comparator will be allocated from this operator config -- [in] MCPWM comparator configuration ret_cmpr -- [out] Returned MCPWM comparator Returns ESP_OK: Create MCPWM comparator successfully ESP_ERR_INVALID_ARG: Create MCPWM comparator failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM comparator failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM comparator failed because can't find free resource ESP_FAIL: Create MCPWM comparator failed because of other error esp_err_t mcpwm_del_comparator(mcpwm_cmpr_handle_t cmpr) Delete MCPWM comparator. Parameters cmpr -- [in] MCPWM comparator handle, allocated by mcpwm_new_comparator() Returns ESP_OK: Delete MCPWM comparator successfully ESP_ERR_INVALID_ARG: Delete MCPWM comparator failed because of invalid argument ESP_FAIL: Delete MCPWM comparator failed because of other error ESP_OK: Delete MCPWM comparator successfully ESP_ERR_INVALID_ARG: Delete MCPWM comparator failed because of invalid argument ESP_FAIL: Delete MCPWM comparator failed because of other error ESP_OK: Delete MCPWM comparator successfully Parameters cmpr -- [in] MCPWM comparator handle, allocated by mcpwm_new_comparator() Returns ESP_OK: Delete MCPWM comparator successfully ESP_ERR_INVALID_ARG: Delete MCPWM comparator failed because of invalid argument ESP_FAIL: Delete MCPWM comparator failed because of other error esp_err_t mcpwm_comparator_register_event_callbacks(mcpwm_cmpr_handle_t cmpr, const mcpwm_comparator_event_callbacks_t *cbs, void *user_data) Set event callbacks for MCPWM comparator. Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbs structure to NULL. Parameters cmpr -- [in] MCPWM comparator handle, allocated by mcpwm_new_comparator() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly cmpr -- [in] MCPWM comparator handle, allocated by mcpwm_new_comparator() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly cmpr -- [in] MCPWM comparator handle, allocated by mcpwm_new_comparator() Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully Parameters cmpr -- [in] MCPWM comparator handle, allocated by mcpwm_new_comparator() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error esp_err_t mcpwm_comparator_set_compare_value(mcpwm_cmpr_handle_t cmpr, uint32_t cmp_ticks) Set MCPWM comparator's compare value. Parameters cmpr -- [in] MCPWM comparator handle, allocated by mcpwm_new_comparator() cmp_ticks -- [in] The new compare value cmpr -- [in] MCPWM comparator handle, allocated by mcpwm_new_comparator() cmp_ticks -- [in] The new compare value cmpr -- [in] MCPWM comparator handle, allocated by mcpwm_new_comparator() Returns ESP_OK: Set MCPWM compare value successfully ESP_ERR_INVALID_ARG: Set MCPWM compare value failed because of invalid argument (e.g. the cmp_ticks is out of range) ESP_ERR_INVALID_STATE: Set MCPWM compare value failed because the operator doesn't have a timer connected ESP_FAIL: Set MCPWM compare value failed because of other error ESP_OK: Set MCPWM compare value successfully ESP_ERR_INVALID_ARG: Set MCPWM compare value failed because of invalid argument (e.g. the cmp_ticks is out of range) ESP_ERR_INVALID_STATE: Set MCPWM compare value failed because the operator doesn't have a timer connected ESP_FAIL: Set MCPWM compare value failed because of other error ESP_OK: Set MCPWM compare value successfully Parameters cmpr -- [in] MCPWM comparator handle, allocated by mcpwm_new_comparator() cmp_ticks -- [in] The new compare value Returns ESP_OK: Set MCPWM compare value successfully ESP_ERR_INVALID_ARG: Set MCPWM compare value failed because of invalid argument (e.g. the cmp_ticks is out of range) ESP_ERR_INVALID_STATE: Set MCPWM compare value failed because the operator doesn't have a timer connected ESP_FAIL: Set MCPWM compare value failed because of other error Structures struct mcpwm_comparator_config_t MCPWM comparator configuration. Public Members int intr_priority MCPWM comparator interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) int intr_priority MCPWM comparator interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) uint32_t update_cmp_on_tez Whether to update compare value when timer count equals to zero (tez) uint32_t update_cmp_on_tez Whether to update compare value when timer count equals to zero (tez) uint32_t update_cmp_on_tep Whether to update compare value when timer count equals to peak (tep) uint32_t update_cmp_on_tep Whether to update compare value when timer count equals to peak (tep) uint32_t update_cmp_on_sync Whether to update compare value on sync event uint32_t update_cmp_on_sync Whether to update compare value on sync event struct mcpwm_comparator_config_t::[anonymous] flags Extra configuration flags for comparator struct mcpwm_comparator_config_t::[anonymous] flags Extra configuration flags for comparator int intr_priority struct mcpwm_comparator_event_callbacks_t Group of supported MCPWM compare event callbacks. Note The callbacks are all running under ISR environment Public Members mcpwm_compare_event_cb_t on_reach ISR callback function which would be invoked when counter reaches compare value mcpwm_compare_event_cb_t on_reach ISR callback function which would be invoked when counter reaches compare value mcpwm_compare_event_cb_t on_reach Header File This header file can be included with: #include "driver/mcpwm_gen.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t mcpwm_new_generator(mcpwm_oper_handle_t oper, const mcpwm_generator_config_t *config, mcpwm_gen_handle_t *ret_gen) Allocate MCPWM generator from given operator. Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() config -- [in] MCPWM generator configuration ret_gen -- [out] Returned MCPWM generator oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() config -- [in] MCPWM generator configuration ret_gen -- [out] Returned MCPWM generator oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() Returns ESP_OK: Create MCPWM generator successfully ESP_ERR_INVALID_ARG: Create MCPWM generator failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM generator failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM generator failed because can't find free resource ESP_FAIL: Create MCPWM generator failed because of other error ESP_OK: Create MCPWM generator successfully ESP_ERR_INVALID_ARG: Create MCPWM generator failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM generator failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM generator failed because can't find free resource ESP_FAIL: Create MCPWM generator failed because of other error ESP_OK: Create MCPWM generator successfully Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() config -- [in] MCPWM generator configuration ret_gen -- [out] Returned MCPWM generator Returns ESP_OK: Create MCPWM generator successfully ESP_ERR_INVALID_ARG: Create MCPWM generator failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM generator failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM generator failed because can't find free resource ESP_FAIL: Create MCPWM generator failed because of other error esp_err_t mcpwm_del_generator(mcpwm_gen_handle_t gen) Delete MCPWM generator. Parameters gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() Returns ESP_OK: Delete MCPWM generator successfully ESP_ERR_INVALID_ARG: Delete MCPWM generator failed because of invalid argument ESP_FAIL: Delete MCPWM generator failed because of other error ESP_OK: Delete MCPWM generator successfully ESP_ERR_INVALID_ARG: Delete MCPWM generator failed because of invalid argument ESP_FAIL: Delete MCPWM generator failed because of other error ESP_OK: Delete MCPWM generator successfully Parameters gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() Returns ESP_OK: Delete MCPWM generator successfully ESP_ERR_INVALID_ARG: Delete MCPWM generator failed because of invalid argument ESP_FAIL: Delete MCPWM generator failed because of other error esp_err_t mcpwm_generator_set_force_level(mcpwm_gen_handle_t gen, int level, bool hold_on) Set force level for MCPWM generator. Note The force level will be applied to the generator immediately, regardless any other events that would change the generator's behaviour. Note If the hold_on is true, the force level will retain forever, until user removes the force level by setting the force level to -1 . Note If the hold_on is false, the force level can be overridden by the next event action. Note The force level set by this function can be inverted by GPIO matrix or dead-time module. So the level set here doesn't equal to the final output level. Parameters gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() level -- [in] GPIO level to be applied to MCPWM generator, specially, -1 means to remove the force level hold_on -- [in] Whether the forced PWM level should retain (i.e. will remain unchanged until manually remove the force level) gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() level -- [in] GPIO level to be applied to MCPWM generator, specially, -1 means to remove the force level hold_on -- [in] Whether the forced PWM level should retain (i.e. will remain unchanged until manually remove the force level) gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() Returns ESP_OK: Set force level for MCPWM generator successfully ESP_ERR_INVALID_ARG: Set force level for MCPWM generator failed because of invalid argument ESP_FAIL: Set force level for MCPWM generator failed because of other error ESP_OK: Set force level for MCPWM generator successfully ESP_ERR_INVALID_ARG: Set force level for MCPWM generator failed because of invalid argument ESP_FAIL: Set force level for MCPWM generator failed because of other error ESP_OK: Set force level for MCPWM generator successfully Parameters gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() level -- [in] GPIO level to be applied to MCPWM generator, specially, -1 means to remove the force level hold_on -- [in] Whether the forced PWM level should retain (i.e. will remain unchanged until manually remove the force level) Returns ESP_OK: Set force level for MCPWM generator successfully ESP_ERR_INVALID_ARG: Set force level for MCPWM generator failed because of invalid argument ESP_FAIL: Set force level for MCPWM generator failed because of other error esp_err_t mcpwm_generator_set_action_on_timer_event(mcpwm_gen_handle_t gen, mcpwm_gen_timer_event_action_t ev_act) Set generator action on MCPWM timer event. Parameters gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM timer event action, can be constructed by MCPWM_GEN_TIMER_EVENT_ACTION helper macro gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM timer event action, can be constructed by MCPWM_GEN_TIMER_EVENT_ACTION helper macro gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() Returns ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_ERR_INVALID_STATE: Set generator action failed because of timer is not connected to operator ESP_FAIL: Set generator action failed because of other error ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_ERR_INVALID_STATE: Set generator action failed because of timer is not connected to operator ESP_FAIL: Set generator action failed because of other error ESP_OK: Set generator action successfully Parameters gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM timer event action, can be constructed by MCPWM_GEN_TIMER_EVENT_ACTION helper macro Returns ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_ERR_INVALID_STATE: Set generator action failed because of timer is not connected to operator ESP_FAIL: Set generator action failed because of other error esp_err_t mcpwm_generator_set_actions_on_timer_event(mcpwm_gen_handle_t gen, mcpwm_gen_timer_event_action_t ev_act, ...) Set generator actions on multiple MCPWM timer events. Note This is an aggregation version of mcpwm_generator_set_action_on_timer_event , which allows user to set multiple actions in one call. Parameters gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM timer event action list, must be terminated by MCPWM_GEN_TIMER_EVENT_ACTION_END() gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM timer event action list, must be terminated by MCPWM_GEN_TIMER_EVENT_ACTION_END() gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() Returns ESP_OK: Set generator actions successfully ESP_ERR_INVALID_ARG: Set generator actions failed because of invalid argument ESP_ERR_INVALID_STATE: Set generator actions failed because of timer is not connected to operator ESP_FAIL: Set generator actions failed because of other error ESP_OK: Set generator actions successfully ESP_ERR_INVALID_ARG: Set generator actions failed because of invalid argument ESP_ERR_INVALID_STATE: Set generator actions failed because of timer is not connected to operator ESP_FAIL: Set generator actions failed because of other error ESP_OK: Set generator actions successfully Parameters gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM timer event action list, must be terminated by MCPWM_GEN_TIMER_EVENT_ACTION_END() Returns ESP_OK: Set generator actions successfully ESP_ERR_INVALID_ARG: Set generator actions failed because of invalid argument ESP_ERR_INVALID_STATE: Set generator actions failed because of timer is not connected to operator ESP_FAIL: Set generator actions failed because of other error esp_err_t mcpwm_generator_set_action_on_compare_event(mcpwm_gen_handle_t generator, mcpwm_gen_compare_event_action_t ev_act) Set generator action on MCPWM compare event. Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM compare event action, can be constructed by MCPWM_GEN_COMPARE_EVENT_ACTION helper macro generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM compare event action, can be constructed by MCPWM_GEN_COMPARE_EVENT_ACTION helper macro generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() Returns ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error ESP_OK: Set generator action successfully Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM compare event action, can be constructed by MCPWM_GEN_COMPARE_EVENT_ACTION helper macro Returns ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error esp_err_t mcpwm_generator_set_actions_on_compare_event(mcpwm_gen_handle_t generator, mcpwm_gen_compare_event_action_t ev_act, ...) Set generator actions on multiple MCPWM compare events. Note This is an aggregation version of mcpwm_generator_set_action_on_compare_event , which allows user to set multiple actions in one call. Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM compare event action list, must be terminated by MCPWM_GEN_COMPARE_EVENT_ACTION_END() generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM compare event action list, must be terminated by MCPWM_GEN_COMPARE_EVENT_ACTION_END() generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() Returns ESP_OK: Set generator actions successfully ESP_ERR_INVALID_ARG: Set generator actions failed because of invalid argument ESP_FAIL: Set generator actions failed because of other error ESP_OK: Set generator actions successfully ESP_ERR_INVALID_ARG: Set generator actions failed because of invalid argument ESP_FAIL: Set generator actions failed because of other error ESP_OK: Set generator actions successfully Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM compare event action list, must be terminated by MCPWM_GEN_COMPARE_EVENT_ACTION_END() Returns ESP_OK: Set generator actions successfully ESP_ERR_INVALID_ARG: Set generator actions failed because of invalid argument ESP_FAIL: Set generator actions failed because of other error esp_err_t mcpwm_generator_set_action_on_brake_event(mcpwm_gen_handle_t generator, mcpwm_gen_brake_event_action_t ev_act) Set generator action on MCPWM brake event. Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM brake event action, can be constructed by MCPWM_GEN_BRAKE_EVENT_ACTION helper macro generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM brake event action, can be constructed by MCPWM_GEN_BRAKE_EVENT_ACTION helper macro generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() Returns ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error ESP_OK: Set generator action successfully Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM brake event action, can be constructed by MCPWM_GEN_BRAKE_EVENT_ACTION helper macro Returns ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error esp_err_t mcpwm_generator_set_actions_on_brake_event(mcpwm_gen_handle_t generator, mcpwm_gen_brake_event_action_t ev_act, ...) Set generator actions on multiple MCPWM brake events. Note This is an aggregation version of mcpwm_generator_set_action_on_brake_event , which allows user to set multiple actions in one call. Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM brake event action list, must be terminated by MCPWM_GEN_BRAKE_EVENT_ACTION_END() generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM brake event action list, must be terminated by MCPWM_GEN_BRAKE_EVENT_ACTION_END() generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() Returns ESP_OK: Set generator actions successfully ESP_ERR_INVALID_ARG: Set generator actions failed because of invalid argument ESP_FAIL: Set generator actions failed because of other error ESP_OK: Set generator actions successfully ESP_ERR_INVALID_ARG: Set generator actions failed because of invalid argument ESP_FAIL: Set generator actions failed because of other error ESP_OK: Set generator actions successfully Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM brake event action list, must be terminated by MCPWM_GEN_BRAKE_EVENT_ACTION_END() Returns ESP_OK: Set generator actions successfully ESP_ERR_INVALID_ARG: Set generator actions failed because of invalid argument ESP_FAIL: Set generator actions failed because of other error esp_err_t mcpwm_generator_set_action_on_fault_event(mcpwm_gen_handle_t generator, mcpwm_gen_fault_event_action_t ev_act) Set generator action on MCPWM Fault event. Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM trigger event action, can be constructed by MCPWM_GEN_FAULT_EVENT_ACTION helper macro generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM trigger event action, can be constructed by MCPWM_GEN_FAULT_EVENT_ACTION helper macro generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() Returns ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error ESP_OK: Set generator action successfully Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM trigger event action, can be constructed by MCPWM_GEN_FAULT_EVENT_ACTION helper macro Returns ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error esp_err_t mcpwm_generator_set_action_on_sync_event(mcpwm_gen_handle_t generator, mcpwm_gen_sync_event_action_t ev_act) Set generator action on MCPWM Sync event. Note The trigger only support one sync action, regardless of the kinds. Should not call this function more than once. Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM trigger event action, can be constructed by MCPWM_GEN_SYNC_EVENT_ACTION helper macro generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM trigger event action, can be constructed by MCPWM_GEN_SYNC_EVENT_ACTION helper macro generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() Returns ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error ESP_OK: Set generator action successfully Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM trigger event action, can be constructed by MCPWM_GEN_SYNC_EVENT_ACTION helper macro Returns ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error esp_err_t mcpwm_generator_set_dead_time(mcpwm_gen_handle_t in_generator, mcpwm_gen_handle_t out_generator, const mcpwm_dead_time_config_t *config) Set dead time for MCPWM generator. Note Due to a hardware limitation, you can't set rising edge delay for both MCPWM generator 0 and 1 at the same time, otherwise, there will be a conflict inside the dead time module. The same goes for the falling edge setting. But you can set both the rising edge and falling edge delay for the same MCPWM generator. Parameters in_generator -- [in] MCPWM generator, before adding the dead time out_generator -- [in] MCPWM generator, after adding the dead time config -- [in] MCPWM dead time configuration in_generator -- [in] MCPWM generator, before adding the dead time out_generator -- [in] MCPWM generator, after adding the dead time config -- [in] MCPWM dead time configuration in_generator -- [in] MCPWM generator, before adding the dead time Returns ESP_OK: Set dead time for MCPWM generator successfully ESP_ERR_INVALID_ARG: Set dead time for MCPWM generator failed because of invalid argument ESP_ERR_INVALID_STATE: Set dead time for MCPWM generator failed because of invalid state (e.g. delay module is already in use by other generator) ESP_FAIL: Set dead time for MCPWM generator failed because of other error ESP_OK: Set dead time for MCPWM generator successfully ESP_ERR_INVALID_ARG: Set dead time for MCPWM generator failed because of invalid argument ESP_ERR_INVALID_STATE: Set dead time for MCPWM generator failed because of invalid state (e.g. delay module is already in use by other generator) ESP_FAIL: Set dead time for MCPWM generator failed because of other error ESP_OK: Set dead time for MCPWM generator successfully Parameters in_generator -- [in] MCPWM generator, before adding the dead time out_generator -- [in] MCPWM generator, after adding the dead time config -- [in] MCPWM dead time configuration Returns ESP_OK: Set dead time for MCPWM generator successfully ESP_ERR_INVALID_ARG: Set dead time for MCPWM generator failed because of invalid argument ESP_ERR_INVALID_STATE: Set dead time for MCPWM generator failed because of invalid state (e.g. delay module is already in use by other generator) ESP_FAIL: Set dead time for MCPWM generator failed because of other error Structures struct mcpwm_generator_config_t MCPWM generator configuration. Public Members int gen_gpio_num The GPIO number used to output the PWM signal int gen_gpio_num The GPIO number used to output the PWM signal uint32_t invert_pwm Whether to invert the PWM signal (done by GPIO matrix) uint32_t invert_pwm Whether to invert the PWM signal (done by GPIO matrix) uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well uint32_t io_od_mode Configure the GPIO as open-drain mode uint32_t io_od_mode Configure the GPIO as open-drain mode uint32_t pull_up Whether to pull up internally uint32_t pull_up Whether to pull up internally uint32_t pull_down Whether to pull down internally uint32_t pull_down Whether to pull down internally struct mcpwm_generator_config_t::[anonymous] flags Extra configuration flags for generator struct mcpwm_generator_config_t::[anonymous] flags Extra configuration flags for generator int gen_gpio_num struct mcpwm_gen_timer_event_action_t Generator action on specific timer event. Public Members mcpwm_timer_direction_t direction Timer direction mcpwm_timer_direction_t direction Timer direction mcpwm_timer_event_t event Timer event mcpwm_timer_event_t event Timer event mcpwm_generator_action_t action Generator action should perform mcpwm_generator_action_t action Generator action should perform mcpwm_timer_direction_t direction struct mcpwm_gen_compare_event_action_t Generator action on specific comparator event. Public Members mcpwm_timer_direction_t direction Timer direction mcpwm_timer_direction_t direction Timer direction mcpwm_cmpr_handle_t comparator Comparator handle mcpwm_cmpr_handle_t comparator Comparator handle mcpwm_generator_action_t action Generator action should perform mcpwm_generator_action_t action Generator action should perform mcpwm_timer_direction_t direction struct mcpwm_gen_brake_event_action_t Generator action on specific brake event. Public Members mcpwm_timer_direction_t direction Timer direction mcpwm_timer_direction_t direction Timer direction mcpwm_operator_brake_mode_t brake_mode Brake mode mcpwm_operator_brake_mode_t brake_mode Brake mode mcpwm_generator_action_t action Generator action should perform mcpwm_generator_action_t action Generator action should perform mcpwm_timer_direction_t direction struct mcpwm_gen_fault_event_action_t Generator action on specific fault event. Public Members mcpwm_timer_direction_t direction Timer direction mcpwm_timer_direction_t direction Timer direction mcpwm_fault_handle_t fault Which fault as the trigger. Only support GPIO fault mcpwm_fault_handle_t fault Which fault as the trigger. Only support GPIO fault mcpwm_generator_action_t action Generator action should perform mcpwm_generator_action_t action Generator action should perform mcpwm_timer_direction_t direction struct mcpwm_gen_sync_event_action_t Generator action on specific sync event. Public Members mcpwm_timer_direction_t direction Timer direction mcpwm_timer_direction_t direction Timer direction mcpwm_sync_handle_t sync Which sync as the trigger mcpwm_sync_handle_t sync Which sync as the trigger mcpwm_generator_action_t action Generator action should perform mcpwm_generator_action_t action Generator action should perform mcpwm_timer_direction_t direction struct mcpwm_dead_time_config_t MCPWM dead time configuration structure. Public Members uint32_t posedge_delay_ticks delay time applied to rising edge, 0 means no rising delay time uint32_t posedge_delay_ticks delay time applied to rising edge, 0 means no rising delay time uint32_t negedge_delay_ticks delay time applied to falling edge, 0 means no falling delay time uint32_t negedge_delay_ticks delay time applied to falling edge, 0 means no falling delay time uint32_t invert_output Invert the signal after applied the dead time uint32_t invert_output Invert the signal after applied the dead time struct mcpwm_dead_time_config_t::[anonymous] flags Extra flags for dead time configuration struct mcpwm_dead_time_config_t::[anonymous] flags Extra flags for dead time configuration uint32_t posedge_delay_ticks Macros MCPWM_GEN_TIMER_EVENT_ACTION(dir, ev, act) Help macros to construct a mcpwm_gen_timer_event_action_t entry. MCPWM_GEN_TIMER_EVENT_ACTION_END() MCPWM_GEN_COMPARE_EVENT_ACTION(dir, cmp, act) Help macros to construct a mcpwm_gen_compare_event_action_t entry. MCPWM_GEN_COMPARE_EVENT_ACTION_END() MCPWM_GEN_BRAKE_EVENT_ACTION(dir, mode, act) Help macros to construct a mcpwm_gen_brake_event_action_t entry. MCPWM_GEN_BRAKE_EVENT_ACTION_END() MCPWM_GEN_FAULT_EVENT_ACTION(dir, flt, act) Help macros to construct a mcpwm_gen_fault_event_action_t entry. MCPWM_GEN_SYNC_EVENT_ACTION(dir, syn, act) Help macros to construct a mcpwm_gen_sync_event_action_t entry. Header File This header file can be included with: #include "driver/mcpwm_fault.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t mcpwm_new_gpio_fault(const mcpwm_gpio_fault_config_t *config, mcpwm_fault_handle_t *ret_fault) Create MCPWM GPIO fault. Parameters config -- [in] MCPWM GPIO fault configuration ret_fault -- [out] Returned GPIO fault handle config -- [in] MCPWM GPIO fault configuration ret_fault -- [out] Returned GPIO fault handle config -- [in] MCPWM GPIO fault configuration Returns ESP_OK: Create MCPWM GPIO fault successfully ESP_ERR_INVALID_ARG: Create MCPWM GPIO fault failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM GPIO fault failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM GPIO fault failed because can't find free resource ESP_FAIL: Create MCPWM GPIO fault failed because of other error ESP_OK: Create MCPWM GPIO fault successfully ESP_ERR_INVALID_ARG: Create MCPWM GPIO fault failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM GPIO fault failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM GPIO fault failed because can't find free resource ESP_FAIL: Create MCPWM GPIO fault failed because of other error ESP_OK: Create MCPWM GPIO fault successfully Parameters config -- [in] MCPWM GPIO fault configuration ret_fault -- [out] Returned GPIO fault handle Returns ESP_OK: Create MCPWM GPIO fault successfully ESP_ERR_INVALID_ARG: Create MCPWM GPIO fault failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM GPIO fault failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM GPIO fault failed because can't find free resource ESP_FAIL: Create MCPWM GPIO fault failed because of other error esp_err_t mcpwm_new_soft_fault(const mcpwm_soft_fault_config_t *config, mcpwm_fault_handle_t *ret_fault) Create MCPWM software fault. Parameters config -- [in] MCPWM software fault configuration ret_fault -- [out] Returned software fault handle config -- [in] MCPWM software fault configuration ret_fault -- [out] Returned software fault handle config -- [in] MCPWM software fault configuration Returns ESP_OK: Create MCPWM software fault successfully ESP_ERR_INVALID_ARG: Create MCPWM software fault failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM software fault failed because out of memory ESP_FAIL: Create MCPWM software fault failed because of other error ESP_OK: Create MCPWM software fault successfully ESP_ERR_INVALID_ARG: Create MCPWM software fault failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM software fault failed because out of memory ESP_FAIL: Create MCPWM software fault failed because of other error ESP_OK: Create MCPWM software fault successfully Parameters config -- [in] MCPWM software fault configuration ret_fault -- [out] Returned software fault handle Returns ESP_OK: Create MCPWM software fault successfully ESP_ERR_INVALID_ARG: Create MCPWM software fault failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM software fault failed because out of memory ESP_FAIL: Create MCPWM software fault failed because of other error esp_err_t mcpwm_del_fault(mcpwm_fault_handle_t fault) Delete MCPWM fault. Parameters fault -- [in] MCPWM fault handle allocated by mcpwm_new_gpio_fault() or mcpwm_new_soft_fault() Returns ESP_OK: Delete MCPWM fault successfully ESP_ERR_INVALID_ARG: Delete MCPWM fault failed because of invalid argument ESP_FAIL: Delete MCPWM fault failed because of other error ESP_OK: Delete MCPWM fault successfully ESP_ERR_INVALID_ARG: Delete MCPWM fault failed because of invalid argument ESP_FAIL: Delete MCPWM fault failed because of other error ESP_OK: Delete MCPWM fault successfully Parameters fault -- [in] MCPWM fault handle allocated by mcpwm_new_gpio_fault() or mcpwm_new_soft_fault() Returns ESP_OK: Delete MCPWM fault successfully ESP_ERR_INVALID_ARG: Delete MCPWM fault failed because of invalid argument ESP_FAIL: Delete MCPWM fault failed because of other error esp_err_t mcpwm_soft_fault_activate(mcpwm_fault_handle_t fault) Activate the software fault, trigger the fault event for once. Parameters fault -- [in] MCPWM soft fault, allocated by mcpwm_new_soft_fault() Returns ESP_OK: Trigger MCPWM software fault event successfully ESP_ERR_INVALID_ARG: Trigger MCPWM software fault event failed because of invalid argument ESP_FAIL: Trigger MCPWM software fault event failed because of other error ESP_OK: Trigger MCPWM software fault event successfully ESP_ERR_INVALID_ARG: Trigger MCPWM software fault event failed because of invalid argument ESP_FAIL: Trigger MCPWM software fault event failed because of other error ESP_OK: Trigger MCPWM software fault event successfully Parameters fault -- [in] MCPWM soft fault, allocated by mcpwm_new_soft_fault() Returns ESP_OK: Trigger MCPWM software fault event successfully ESP_ERR_INVALID_ARG: Trigger MCPWM software fault event failed because of invalid argument ESP_FAIL: Trigger MCPWM software fault event failed because of other error esp_err_t mcpwm_fault_register_event_callbacks(mcpwm_fault_handle_t fault, const mcpwm_fault_event_callbacks_t *cbs, void *user_data) Set event callbacks for MCPWM fault. Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbs structure to NULL. Parameters fault -- [in] MCPWM GPIO fault handle, allocated by mcpwm_new_gpio_fault() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly fault -- [in] MCPWM GPIO fault handle, allocated by mcpwm_new_gpio_fault() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly fault -- [in] MCPWM GPIO fault handle, allocated by mcpwm_new_gpio_fault() Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully Parameters fault -- [in] MCPWM GPIO fault handle, allocated by mcpwm_new_gpio_fault() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error Structures struct mcpwm_gpio_fault_config_t MCPWM GPIO fault configuration structure. Public Members int group_id In which MCPWM group that the GPIO fault belongs to int group_id In which MCPWM group that the GPIO fault belongs to int intr_priority MCPWM GPIO fault interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) int intr_priority MCPWM GPIO fault interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) int gpio_num GPIO used by the fault signal int gpio_num GPIO used by the fault signal uint32_t active_level On which level the fault signal is treated as active uint32_t active_level On which level the fault signal is treated as active uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well uint32_t pull_up Whether to pull up internally uint32_t pull_up Whether to pull up internally uint32_t pull_down Whether to pull down internally uint32_t pull_down Whether to pull down internally struct mcpwm_gpio_fault_config_t::[anonymous] flags Extra configuration flags for GPIO fault struct mcpwm_gpio_fault_config_t::[anonymous] flags Extra configuration flags for GPIO fault int group_id struct mcpwm_soft_fault_config_t MCPWM software fault configuration structure. struct mcpwm_fault_event_callbacks_t Group of supported MCPWM fault event callbacks. Note The callbacks are all running under ISR environment Public Members mcpwm_fault_event_cb_t on_fault_enter ISR callback function that would be invoked when fault signal becomes active mcpwm_fault_event_cb_t on_fault_enter ISR callback function that would be invoked when fault signal becomes active mcpwm_fault_event_cb_t on_fault_exit ISR callback function that would be invoked when fault signal becomes inactive mcpwm_fault_event_cb_t on_fault_exit ISR callback function that would be invoked when fault signal becomes inactive mcpwm_fault_event_cb_t on_fault_enter Header File This header file can be included with: #include "driver/mcpwm_sync.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t mcpwm_new_timer_sync_src(mcpwm_timer_handle_t timer, const mcpwm_timer_sync_src_config_t *config, mcpwm_sync_handle_t *ret_sync) Create MCPWM timer sync source. Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() config -- [in] MCPWM timer sync source configuration ret_sync -- [out] Returned MCPWM sync handle timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() config -- [in] MCPWM timer sync source configuration ret_sync -- [out] Returned MCPWM sync handle timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() Returns ESP_OK: Create MCPWM timer sync source successfully ESP_ERR_INVALID_ARG: Create MCPWM timer sync source failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM timer sync source failed because out of memory ESP_ERR_INVALID_STATE: Create MCPWM timer sync source failed because the timer has created a sync source before ESP_FAIL: Create MCPWM timer sync source failed because of other error ESP_OK: Create MCPWM timer sync source successfully ESP_ERR_INVALID_ARG: Create MCPWM timer sync source failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM timer sync source failed because out of memory ESP_ERR_INVALID_STATE: Create MCPWM timer sync source failed because the timer has created a sync source before ESP_FAIL: Create MCPWM timer sync source failed because of other error ESP_OK: Create MCPWM timer sync source successfully Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() config -- [in] MCPWM timer sync source configuration ret_sync -- [out] Returned MCPWM sync handle Returns ESP_OK: Create MCPWM timer sync source successfully ESP_ERR_INVALID_ARG: Create MCPWM timer sync source failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM timer sync source failed because out of memory ESP_ERR_INVALID_STATE: Create MCPWM timer sync source failed because the timer has created a sync source before ESP_FAIL: Create MCPWM timer sync source failed because of other error esp_err_t mcpwm_new_gpio_sync_src(const mcpwm_gpio_sync_src_config_t *config, mcpwm_sync_handle_t *ret_sync) Create MCPWM GPIO sync source. Parameters config -- [in] MCPWM GPIO sync source configuration ret_sync -- [out] Returned MCPWM GPIO sync handle config -- [in] MCPWM GPIO sync source configuration ret_sync -- [out] Returned MCPWM GPIO sync handle config -- [in] MCPWM GPIO sync source configuration Returns ESP_OK: Create MCPWM GPIO sync source successfully ESP_ERR_INVALID_ARG: Create MCPWM GPIO sync source failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM GPIO sync source failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM GPIO sync source failed because can't find free resource ESP_FAIL: Create MCPWM GPIO sync source failed because of other error ESP_OK: Create MCPWM GPIO sync source successfully ESP_ERR_INVALID_ARG: Create MCPWM GPIO sync source failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM GPIO sync source failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM GPIO sync source failed because can't find free resource ESP_FAIL: Create MCPWM GPIO sync source failed because of other error ESP_OK: Create MCPWM GPIO sync source successfully Parameters config -- [in] MCPWM GPIO sync source configuration ret_sync -- [out] Returned MCPWM GPIO sync handle Returns ESP_OK: Create MCPWM GPIO sync source successfully ESP_ERR_INVALID_ARG: Create MCPWM GPIO sync source failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM GPIO sync source failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM GPIO sync source failed because can't find free resource ESP_FAIL: Create MCPWM GPIO sync source failed because of other error esp_err_t mcpwm_new_soft_sync_src(const mcpwm_soft_sync_config_t *config, mcpwm_sync_handle_t *ret_sync) Create MCPWM software sync source. Parameters config -- [in] MCPWM software sync source configuration ret_sync -- [out] Returned software sync handle config -- [in] MCPWM software sync source configuration ret_sync -- [out] Returned software sync handle config -- [in] MCPWM software sync source configuration Returns ESP_OK: Create MCPWM software sync successfully ESP_ERR_INVALID_ARG: Create MCPWM software sync failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM software sync failed because out of memory ESP_FAIL: Create MCPWM software sync failed because of other error ESP_OK: Create MCPWM software sync successfully ESP_ERR_INVALID_ARG: Create MCPWM software sync failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM software sync failed because out of memory ESP_FAIL: Create MCPWM software sync failed because of other error ESP_OK: Create MCPWM software sync successfully Parameters config -- [in] MCPWM software sync source configuration ret_sync -- [out] Returned software sync handle Returns ESP_OK: Create MCPWM software sync successfully ESP_ERR_INVALID_ARG: Create MCPWM software sync failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM software sync failed because out of memory ESP_FAIL: Create MCPWM software sync failed because of other error esp_err_t mcpwm_del_sync_src(mcpwm_sync_handle_t sync) Delete MCPWM sync source. Parameters sync -- [in] MCPWM sync handle, allocated by mcpwm_new_timer_sync_src() or mcpwm_new_gpio_sync_src() or mcpwm_new_soft_sync_src() Returns ESP_OK: Delete MCPWM sync source successfully ESP_ERR_INVALID_ARG: Delete MCPWM sync source failed because of invalid argument ESP_FAIL: Delete MCPWM sync source failed because of other error ESP_OK: Delete MCPWM sync source successfully ESP_ERR_INVALID_ARG: Delete MCPWM sync source failed because of invalid argument ESP_FAIL: Delete MCPWM sync source failed because of other error ESP_OK: Delete MCPWM sync source successfully Parameters sync -- [in] MCPWM sync handle, allocated by mcpwm_new_timer_sync_src() or mcpwm_new_gpio_sync_src() or mcpwm_new_soft_sync_src() Returns ESP_OK: Delete MCPWM sync source successfully ESP_ERR_INVALID_ARG: Delete MCPWM sync source failed because of invalid argument ESP_FAIL: Delete MCPWM sync source failed because of other error esp_err_t mcpwm_soft_sync_activate(mcpwm_sync_handle_t sync) Activate the software sync, trigger the sync event for once. Parameters sync -- [in] MCPWM soft sync handle, allocated by mcpwm_new_soft_sync_src() Returns ESP_OK: Trigger MCPWM software sync event successfully ESP_ERR_INVALID_ARG: Trigger MCPWM software sync event failed because of invalid argument ESP_FAIL: Trigger MCPWM software sync event failed because of other error ESP_OK: Trigger MCPWM software sync event successfully ESP_ERR_INVALID_ARG: Trigger MCPWM software sync event failed because of invalid argument ESP_FAIL: Trigger MCPWM software sync event failed because of other error ESP_OK: Trigger MCPWM software sync event successfully Parameters sync -- [in] MCPWM soft sync handle, allocated by mcpwm_new_soft_sync_src() Returns ESP_OK: Trigger MCPWM software sync event successfully ESP_ERR_INVALID_ARG: Trigger MCPWM software sync event failed because of invalid argument ESP_FAIL: Trigger MCPWM software sync event failed because of other error Structures struct mcpwm_timer_sync_src_config_t MCPWM timer sync source configuration. Public Members mcpwm_timer_event_t timer_event Timer event, upon which MCPWM timer will generate the sync signal mcpwm_timer_event_t timer_event Timer event, upon which MCPWM timer will generate the sync signal uint32_t propagate_input_sync The input sync signal would be routed to its sync output uint32_t propagate_input_sync The input sync signal would be routed to its sync output struct mcpwm_timer_sync_src_config_t::[anonymous] flags Extra configuration flags for timer sync source struct mcpwm_timer_sync_src_config_t::[anonymous] flags Extra configuration flags for timer sync source mcpwm_timer_event_t timer_event struct mcpwm_gpio_sync_src_config_t MCPWM GPIO sync source configuration. Public Members int group_id MCPWM group ID int group_id MCPWM group ID int gpio_num GPIO used by sync source int gpio_num GPIO used by sync source uint32_t active_neg Whether the sync signal is active on negedge, by default, the sync signal's posedge is treated as active uint32_t active_neg Whether the sync signal is active on negedge, by default, the sync signal's posedge is treated as active uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well uint32_t pull_up Whether to pull up internally uint32_t pull_up Whether to pull up internally uint32_t pull_down Whether to pull down internally uint32_t pull_down Whether to pull down internally struct mcpwm_gpio_sync_src_config_t::[anonymous] flags Extra configuration flags for GPIO sync source struct mcpwm_gpio_sync_src_config_t::[anonymous] flags Extra configuration flags for GPIO sync source int group_id struct mcpwm_soft_sync_config_t MCPWM software sync configuration structure. Header File This header file can be included with: #include "driver/mcpwm_cap.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t mcpwm_new_capture_timer(const mcpwm_capture_timer_config_t *config, mcpwm_cap_timer_handle_t *ret_cap_timer) Create MCPWM capture timer. Parameters config -- [in] MCPWM capture timer configuration ret_cap_timer -- [out] Returned MCPWM capture timer handle config -- [in] MCPWM capture timer configuration ret_cap_timer -- [out] Returned MCPWM capture timer handle config -- [in] MCPWM capture timer configuration Returns ESP_OK: Create MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Create MCPWM capture timer failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM capture timer failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM capture timer failed because can't find free resource ESP_FAIL: Create MCPWM capture timer failed because of other error ESP_OK: Create MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Create MCPWM capture timer failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM capture timer failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM capture timer failed because can't find free resource ESP_FAIL: Create MCPWM capture timer failed because of other error ESP_OK: Create MCPWM capture timer successfully Parameters config -- [in] MCPWM capture timer configuration ret_cap_timer -- [out] Returned MCPWM capture timer handle Returns ESP_OK: Create MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Create MCPWM capture timer failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM capture timer failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM capture timer failed because can't find free resource ESP_FAIL: Create MCPWM capture timer failed because of other error esp_err_t mcpwm_del_capture_timer(mcpwm_cap_timer_handle_t cap_timer) Delete MCPWM capture timer. Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() Returns ESP_OK: Delete MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Delete MCPWM capture timer failed because of invalid argument ESP_FAIL: Delete MCPWM capture timer failed because of other error ESP_OK: Delete MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Delete MCPWM capture timer failed because of invalid argument ESP_FAIL: Delete MCPWM capture timer failed because of other error ESP_OK: Delete MCPWM capture timer successfully Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() Returns ESP_OK: Delete MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Delete MCPWM capture timer failed because of invalid argument ESP_FAIL: Delete MCPWM capture timer failed because of other error esp_err_t mcpwm_capture_timer_enable(mcpwm_cap_timer_handle_t cap_timer) Enable MCPWM capture timer. Parameters cap_timer -- [in] MCPWM capture timer handle, allocated by mcpwm_new_capture_timer() Returns ESP_OK: Enable MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Enable MCPWM capture timer failed because of invalid argument ESP_ERR_INVALID_STATE: Enable MCPWM capture timer failed because timer is enabled already ESP_FAIL: Enable MCPWM capture timer failed because of other error ESP_OK: Enable MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Enable MCPWM capture timer failed because of invalid argument ESP_ERR_INVALID_STATE: Enable MCPWM capture timer failed because timer is enabled already ESP_FAIL: Enable MCPWM capture timer failed because of other error ESP_OK: Enable MCPWM capture timer successfully Parameters cap_timer -- [in] MCPWM capture timer handle, allocated by mcpwm_new_capture_timer() Returns ESP_OK: Enable MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Enable MCPWM capture timer failed because of invalid argument ESP_ERR_INVALID_STATE: Enable MCPWM capture timer failed because timer is enabled already ESP_FAIL: Enable MCPWM capture timer failed because of other error esp_err_t mcpwm_capture_timer_disable(mcpwm_cap_timer_handle_t cap_timer) Disable MCPWM capture timer. Parameters cap_timer -- [in] MCPWM capture timer handle, allocated by mcpwm_new_capture_timer() Returns ESP_OK: Disable MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Disable MCPWM capture timer failed because of invalid argument ESP_ERR_INVALID_STATE: Disable MCPWM capture timer failed because timer is disabled already ESP_FAIL: Disable MCPWM capture timer failed because of other error ESP_OK: Disable MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Disable MCPWM capture timer failed because of invalid argument ESP_ERR_INVALID_STATE: Disable MCPWM capture timer failed because timer is disabled already ESP_FAIL: Disable MCPWM capture timer failed because of other error ESP_OK: Disable MCPWM capture timer successfully Parameters cap_timer -- [in] MCPWM capture timer handle, allocated by mcpwm_new_capture_timer() Returns ESP_OK: Disable MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Disable MCPWM capture timer failed because of invalid argument ESP_ERR_INVALID_STATE: Disable MCPWM capture timer failed because timer is disabled already ESP_FAIL: Disable MCPWM capture timer failed because of other error esp_err_t mcpwm_capture_timer_start(mcpwm_cap_timer_handle_t cap_timer) Start MCPWM capture timer. Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() Returns ESP_OK: Start MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Start MCPWM capture timer failed because of invalid argument ESP_FAIL: Start MCPWM capture timer failed because of other error ESP_OK: Start MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Start MCPWM capture timer failed because of invalid argument ESP_FAIL: Start MCPWM capture timer failed because of other error ESP_OK: Start MCPWM capture timer successfully Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() Returns ESP_OK: Start MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Start MCPWM capture timer failed because of invalid argument ESP_FAIL: Start MCPWM capture timer failed because of other error esp_err_t mcpwm_capture_timer_stop(mcpwm_cap_timer_handle_t cap_timer) Start MCPWM capture timer. Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() Returns ESP_OK: Stop MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Stop MCPWM capture timer failed because of invalid argument ESP_FAIL: Stop MCPWM capture timer failed because of other error ESP_OK: Stop MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Stop MCPWM capture timer failed because of invalid argument ESP_FAIL: Stop MCPWM capture timer failed because of other error ESP_OK: Stop MCPWM capture timer successfully Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() Returns ESP_OK: Stop MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Stop MCPWM capture timer failed because of invalid argument ESP_FAIL: Stop MCPWM capture timer failed because of other error esp_err_t mcpwm_capture_timer_get_resolution(mcpwm_cap_timer_handle_t cap_timer, uint32_t *out_resolution) Get MCPWM capture timer resolution, in Hz. Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() out_resolution -- [out] Returned capture timer resolution, in Hz cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() out_resolution -- [out] Returned capture timer resolution, in Hz cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() Returns ESP_OK: Get capture timer resolution successfully ESP_ERR_INVALID_ARG: Get capture timer resolution failed because of invalid argument ESP_FAIL: Get capture timer resolution failed because of other error ESP_OK: Get capture timer resolution successfully ESP_ERR_INVALID_ARG: Get capture timer resolution failed because of invalid argument ESP_FAIL: Get capture timer resolution failed because of other error ESP_OK: Get capture timer resolution successfully Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() out_resolution -- [out] Returned capture timer resolution, in Hz Returns ESP_OK: Get capture timer resolution successfully ESP_ERR_INVALID_ARG: Get capture timer resolution failed because of invalid argument ESP_FAIL: Get capture timer resolution failed because of other error esp_err_t mcpwm_capture_timer_set_phase_on_sync(mcpwm_cap_timer_handle_t cap_timer, const mcpwm_capture_timer_sync_phase_config_t *config) Set sync phase for MCPWM capture timer. Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() config -- [in] MCPWM capture timer sync phase configuration cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() config -- [in] MCPWM capture timer sync phase configuration cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() Returns ESP_OK: Set sync phase for MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Set sync phase for MCPWM capture timer failed because of invalid argument ESP_FAIL: Set sync phase for MCPWM capture timer failed because of other error ESP_OK: Set sync phase for MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Set sync phase for MCPWM capture timer failed because of invalid argument ESP_FAIL: Set sync phase for MCPWM capture timer failed because of other error ESP_OK: Set sync phase for MCPWM capture timer successfully Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() config -- [in] MCPWM capture timer sync phase configuration Returns ESP_OK: Set sync phase for MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Set sync phase for MCPWM capture timer failed because of invalid argument ESP_FAIL: Set sync phase for MCPWM capture timer failed because of other error esp_err_t mcpwm_new_capture_channel(mcpwm_cap_timer_handle_t cap_timer, const mcpwm_capture_channel_config_t *config, mcpwm_cap_channel_handle_t *ret_cap_channel) Create MCPWM capture channel. Note The created capture channel won't be enabled until calling mcpwm_capture_channel_enable Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() , will be connected to the new capture channel config -- [in] MCPWM capture channel configuration ret_cap_channel -- [out] Returned MCPWM capture channel cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() , will be connected to the new capture channel config -- [in] MCPWM capture channel configuration ret_cap_channel -- [out] Returned MCPWM capture channel cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() , will be connected to the new capture channel Returns ESP_OK: Create MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Create MCPWM capture channel failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM capture channel failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM capture channel failed because can't find free resource ESP_FAIL: Create MCPWM capture channel failed because of other error ESP_OK: Create MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Create MCPWM capture channel failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM capture channel failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM capture channel failed because can't find free resource ESP_FAIL: Create MCPWM capture channel failed because of other error ESP_OK: Create MCPWM capture channel successfully Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() , will be connected to the new capture channel config -- [in] MCPWM capture channel configuration ret_cap_channel -- [out] Returned MCPWM capture channel Returns ESP_OK: Create MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Create MCPWM capture channel failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM capture channel failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM capture channel failed because can't find free resource ESP_FAIL: Create MCPWM capture channel failed because of other error esp_err_t mcpwm_del_capture_channel(mcpwm_cap_channel_handle_t cap_channel) Delete MCPWM capture channel. Parameters cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() Returns ESP_OK: Delete MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Delete MCPWM capture channel failed because of invalid argument ESP_FAIL: Delete MCPWM capture channel failed because of other error ESP_OK: Delete MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Delete MCPWM capture channel failed because of invalid argument ESP_FAIL: Delete MCPWM capture channel failed because of other error ESP_OK: Delete MCPWM capture channel successfully Parameters cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() Returns ESP_OK: Delete MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Delete MCPWM capture channel failed because of invalid argument ESP_FAIL: Delete MCPWM capture channel failed because of other error esp_err_t mcpwm_capture_channel_enable(mcpwm_cap_channel_handle_t cap_channel) Enable MCPWM capture channel. Note This function will transit the channel state from init to enable. Note This function will enable the interrupt service, if it's lazy installed in mcpwm_capture_channel_register_event_callbacks() . Parameters cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() Returns ESP_OK: Enable MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Enable MCPWM capture channel failed because of invalid argument ESP_ERR_INVALID_STATE: Enable MCPWM capture channel failed because the channel is already enabled ESP_FAIL: Enable MCPWM capture channel failed because of other error ESP_OK: Enable MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Enable MCPWM capture channel failed because of invalid argument ESP_ERR_INVALID_STATE: Enable MCPWM capture channel failed because the channel is already enabled ESP_FAIL: Enable MCPWM capture channel failed because of other error ESP_OK: Enable MCPWM capture channel successfully Parameters cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() Returns ESP_OK: Enable MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Enable MCPWM capture channel failed because of invalid argument ESP_ERR_INVALID_STATE: Enable MCPWM capture channel failed because the channel is already enabled ESP_FAIL: Enable MCPWM capture channel failed because of other error esp_err_t mcpwm_capture_channel_disable(mcpwm_cap_channel_handle_t cap_channel) Disable MCPWM capture channel. Parameters cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() Returns ESP_OK: Disable MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Disable MCPWM capture channel failed because of invalid argument ESP_ERR_INVALID_STATE: Disable MCPWM capture channel failed because the channel is not enabled yet ESP_FAIL: Disable MCPWM capture channel failed because of other error ESP_OK: Disable MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Disable MCPWM capture channel failed because of invalid argument ESP_ERR_INVALID_STATE: Disable MCPWM capture channel failed because the channel is not enabled yet ESP_FAIL: Disable MCPWM capture channel failed because of other error ESP_OK: Disable MCPWM capture channel successfully Parameters cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() Returns ESP_OK: Disable MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Disable MCPWM capture channel failed because of invalid argument ESP_ERR_INVALID_STATE: Disable MCPWM capture channel failed because the channel is not enabled yet ESP_FAIL: Disable MCPWM capture channel failed because of other error esp_err_t mcpwm_capture_channel_register_event_callbacks(mcpwm_cap_channel_handle_t cap_channel, const mcpwm_capture_event_callbacks_t *cbs, void *user_data) Set event callbacks for MCPWM capture channel. Note The first call to this function needs to be before the call to mcpwm_capture_channel_enable Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbs structure to NULL. Parameters cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because the channel is not in init state ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because the channel is not in init state ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully Parameters cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because the channel is not in init state ESP_FAIL: Set event callbacks failed because of other error esp_err_t mcpwm_capture_channel_trigger_soft_catch(mcpwm_cap_channel_handle_t cap_channel) Trigger a catch by software. Parameters cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() Returns ESP_OK: Trigger software catch successfully ESP_ERR_INVALID_ARG: Trigger software catch failed because of invalid argument ESP_ERR_INVALID_STATE: Trigger software catch failed because the channel is not enabled yet ESP_FAIL: Trigger software catch failed because of other error ESP_OK: Trigger software catch successfully ESP_ERR_INVALID_ARG: Trigger software catch failed because of invalid argument ESP_ERR_INVALID_STATE: Trigger software catch failed because the channel is not enabled yet ESP_FAIL: Trigger software catch failed because of other error ESP_OK: Trigger software catch successfully Parameters cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() Returns ESP_OK: Trigger software catch successfully ESP_ERR_INVALID_ARG: Trigger software catch failed because of invalid argument ESP_ERR_INVALID_STATE: Trigger software catch failed because the channel is not enabled yet ESP_FAIL: Trigger software catch failed because of other error Structures struct mcpwm_capture_timer_config_t MCPWM capture timer configuration structure. Public Members int group_id Specify from which group to allocate the capture timer int group_id Specify from which group to allocate the capture timer mcpwm_capture_clock_source_t clk_src MCPWM capture timer clock source mcpwm_capture_clock_source_t clk_src MCPWM capture timer clock source uint32_t resolution_hz Resolution of capture timer uint32_t resolution_hz Resolution of capture timer int group_id struct mcpwm_capture_timer_sync_phase_config_t MCPWM Capture timer sync phase configuration. Public Members mcpwm_sync_handle_t sync_src The sync event source mcpwm_sync_handle_t sync_src The sync event source uint32_t count_value The count value that should lock to upon sync event uint32_t count_value The count value that should lock to upon sync event mcpwm_timer_direction_t direction The count direction that should lock to upon sync event mcpwm_timer_direction_t direction The count direction that should lock to upon sync event mcpwm_sync_handle_t sync_src struct mcpwm_capture_channel_config_t MCPWM capture channel configuration structure. Public Members int gpio_num GPIO used capturing input signal int gpio_num GPIO used capturing input signal int intr_priority MCPWM capture interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) int intr_priority MCPWM capture interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) uint32_t prescale Prescale of input signal, effective frequency = cap_input_clk/prescale uint32_t prescale Prescale of input signal, effective frequency = cap_input_clk/prescale uint32_t pos_edge Whether to capture on positive edge uint32_t pos_edge Whether to capture on positive edge uint32_t neg_edge Whether to capture on negative edge uint32_t neg_edge Whether to capture on negative edge uint32_t pull_up Whether to pull up internally uint32_t pull_up Whether to pull up internally uint32_t pull_down Whether to pull down internally uint32_t pull_down Whether to pull down internally uint32_t invert_cap_signal Invert the input capture signal uint32_t invert_cap_signal Invert the input capture signal uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well uint32_t keep_io_conf_at_exit For debug/test, whether to keep the GPIO configuration when capture channel is deleted. By default, driver will reset the GPIO pin at exit. uint32_t keep_io_conf_at_exit For debug/test, whether to keep the GPIO configuration when capture channel is deleted. By default, driver will reset the GPIO pin at exit. struct mcpwm_capture_channel_config_t::[anonymous] flags Extra configuration flags for capture channel struct mcpwm_capture_channel_config_t::[anonymous] flags Extra configuration flags for capture channel int gpio_num struct mcpwm_capture_event_callbacks_t Group of supported MCPWM capture event callbacks. Note The callbacks are all running under ISR environment Public Members mcpwm_capture_event_cb_t on_cap Callback function that would be invoked when capture event occurred mcpwm_capture_event_cb_t on_cap Callback function that would be invoked when capture event occurred mcpwm_capture_event_cb_t on_cap Header File This header file can be included with: #include "driver/mcpwm_etm.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t mcpwm_comparator_new_etm_event(mcpwm_cmpr_handle_t cmpr, const mcpwm_cmpr_etm_event_config_t *config, esp_etm_event_handle_t *out_event) Get the ETM event for MCPWM comparator. Note The created ETM event object can be deleted later by calling esp_etm_del_event Parameters cmpr -- [in] MCPWM comparator, allocated by mcpwm_new_comparator() or mcpwm_new_event_comparator() config -- [in] MCPWM ETM comparator event configuration out_event -- [out] Returned ETM event handle cmpr -- [in] MCPWM comparator, allocated by mcpwm_new_comparator() or mcpwm_new_event_comparator() config -- [in] MCPWM ETM comparator event configuration out_event -- [out] Returned ETM event handle cmpr -- [in] MCPWM comparator, allocated by mcpwm_new_comparator() or mcpwm_new_event_comparator() Returns ESP_OK: Get ETM event successfully ESP_ERR_INVALID_ARG: Get ETM event failed because of invalid argument ESP_FAIL: Get ETM event failed because of other error ESP_OK: Get ETM event successfully ESP_ERR_INVALID_ARG: Get ETM event failed because of invalid argument ESP_FAIL: Get ETM event failed because of other error ESP_OK: Get ETM event successfully Parameters cmpr -- [in] MCPWM comparator, allocated by mcpwm_new_comparator() or mcpwm_new_event_comparator() config -- [in] MCPWM ETM comparator event configuration out_event -- [out] Returned ETM event handle Returns ESP_OK: Get ETM event successfully ESP_ERR_INVALID_ARG: Get ETM event failed because of invalid argument ESP_FAIL: Get ETM event failed because of other error Structures struct mcpwm_cmpr_etm_event_config_t MCPWM event comparator ETM event configuration. Public Members mcpwm_comparator_etm_event_type_t event_type MCPWM comparator ETM event type mcpwm_comparator_etm_event_type_t event_type MCPWM comparator ETM event type mcpwm_comparator_etm_event_type_t event_type Header File This header file can be included with: #include "driver/mcpwm_types.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Structures struct mcpwm_timer_event_data_t MCPWM timer event data. Public Members uint32_t count_value MCPWM timer count value uint32_t count_value MCPWM timer count value mcpwm_timer_direction_t direction MCPWM timer count direction mcpwm_timer_direction_t direction MCPWM timer count direction uint32_t count_value struct mcpwm_brake_event_data_t MCPWM brake event data. struct mcpwm_fault_event_data_t MCPWM fault event data. struct mcpwm_compare_event_data_t MCPWM compare event data. Public Members uint32_t compare_ticks Compare value uint32_t compare_ticks Compare value mcpwm_timer_direction_t direction Count direction mcpwm_timer_direction_t direction Count direction uint32_t compare_ticks struct mcpwm_capture_event_data_t MCPWM capture event data. Public Members uint32_t cap_value Captured value uint32_t cap_value Captured value mcpwm_capture_edge_t cap_edge Capture edge mcpwm_capture_edge_t cap_edge Capture edge uint32_t cap_value Type Definitions typedef struct mcpwm_timer_t *mcpwm_timer_handle_t Type of MCPWM timer handle. typedef struct mcpwm_oper_t *mcpwm_oper_handle_t Type of MCPWM operator handle. typedef struct mcpwm_cmpr_t *mcpwm_cmpr_handle_t Type of MCPWM comparator handle. typedef struct mcpwm_gen_t *mcpwm_gen_handle_t Type of MCPWM generator handle. typedef struct mcpwm_fault_t *mcpwm_fault_handle_t Type of MCPWM fault handle. typedef struct mcpwm_sync_t *mcpwm_sync_handle_t Type of MCPWM sync handle. typedef struct mcpwm_cap_timer_t *mcpwm_cap_timer_handle_t Type of MCPWM capture timer handle. typedef struct mcpwm_cap_channel_t *mcpwm_cap_channel_handle_t Type of MCPWM capture channel handle. typedef bool (*mcpwm_timer_event_cb_t)(mcpwm_timer_handle_t timer, const mcpwm_timer_event_data_t *edata, void *user_ctx) MCPWM timer event callback function. Param timer [in] MCPWM timer handle Param edata [in] MCPWM timer event data, fed by driver Param user_ctx [in] User data, set in mcpwm_timer_register_event_callbacks() Return Whether a high priority task has been waken up by this function Param timer [in] MCPWM timer handle Param edata [in] MCPWM timer event data, fed by driver Param user_ctx [in] User data, set in mcpwm_timer_register_event_callbacks() Return Whether a high priority task has been waken up by this function typedef bool (*mcpwm_brake_event_cb_t)(mcpwm_oper_handle_t oper, const mcpwm_brake_event_data_t *edata, void *user_ctx) MCPWM operator brake event callback function. Param oper [in] MCPWM operator handle Param edata [in] MCPWM brake event data, fed by driver Param user_ctx [in] User data, set in mcpwm_operator_register_event_callbacks() Return Whether a high priority task has been waken up by this function Param oper [in] MCPWM operator handle Param edata [in] MCPWM brake event data, fed by driver Param user_ctx [in] User data, set in mcpwm_operator_register_event_callbacks() Return Whether a high priority task has been waken up by this function typedef bool (*mcpwm_fault_event_cb_t)(mcpwm_fault_handle_t fault, const mcpwm_fault_event_data_t *edata, void *user_ctx) MCPWM fault event callback function. Param fault MCPWM fault handle Param edata MCPWM fault event data, fed by driver Param user_ctx User data, set in mcpwm_fault_register_event_callbacks() Return whether a task switch is needed after the callback returns Param fault MCPWM fault handle Param edata MCPWM fault event data, fed by driver Param user_ctx User data, set in mcpwm_fault_register_event_callbacks() Return whether a task switch is needed after the callback returns typedef bool (*mcpwm_compare_event_cb_t)(mcpwm_cmpr_handle_t comparator, const mcpwm_compare_event_data_t *edata, void *user_ctx) MCPWM comparator event callback function. Param comparator MCPWM comparator handle Param edata MCPWM comparator event data, fed by driver Param user_ctx User data, set in mcpwm_comparator_register_event_callbacks() Return Whether a high priority task has been waken up by this function Param comparator MCPWM comparator handle Param edata MCPWM comparator event data, fed by driver Param user_ctx User data, set in mcpwm_comparator_register_event_callbacks() Return Whether a high priority task has been waken up by this function typedef bool (*mcpwm_capture_event_cb_t)(mcpwm_cap_channel_handle_t cap_channel, const mcpwm_capture_event_data_t *edata, void *user_ctx) MCPWM capture event callback function. Param cap_channel MCPWM capture channel handle Param edata MCPWM capture event data, fed by driver Param user_ctx User data, set in mcpwm_capture_channel_register_event_callbacks() Return Whether a high priority task has been waken up by this function Param cap_channel MCPWM capture channel handle Param edata MCPWM capture event data, fed by driver Param user_ctx User data, set in mcpwm_capture_channel_register_event_callbacks() Return Whether a high priority task has been waken up by this function Header File This header file can be included with: #include "hal/mcpwm_types.h" Type Definitions typedef soc_periph_mcpwm_timer_clk_src_t mcpwm_timer_clock_source_t MCPWM timer clock source. typedef soc_periph_mcpwm_capture_clk_src_t mcpwm_capture_clock_source_t MCPWM capture clock source. typedef soc_periph_mcpwm_carrier_clk_src_t mcpwm_carrier_clock_source_t MCPWM carrier clock source. Enumerations enum mcpwm_timer_direction_t MCPWM timer count direction. Values: enumerator MCPWM_TIMER_DIRECTION_UP Counting direction: Increase enumerator MCPWM_TIMER_DIRECTION_UP Counting direction: Increase enumerator MCPWM_TIMER_DIRECTION_DOWN Counting direction: Decrease enumerator MCPWM_TIMER_DIRECTION_DOWN Counting direction: Decrease enumerator MCPWM_TIMER_DIRECTION_UP enum mcpwm_timer_event_t MCPWM timer events. Values: enumerator MCPWM_TIMER_EVENT_EMPTY MCPWM timer counts to zero (i.e. counter is empty) enumerator MCPWM_TIMER_EVENT_EMPTY MCPWM timer counts to zero (i.e. counter is empty) enumerator MCPWM_TIMER_EVENT_FULL MCPWM timer counts to peak (i.e. counter is full) enumerator MCPWM_TIMER_EVENT_FULL MCPWM timer counts to peak (i.e. counter is full) enumerator MCPWM_TIMER_EVENT_INVALID MCPWM timer invalid event enumerator MCPWM_TIMER_EVENT_INVALID MCPWM timer invalid event enumerator MCPWM_TIMER_EVENT_EMPTY enum mcpwm_timer_count_mode_t MCPWM timer count modes. Values: enumerator MCPWM_TIMER_COUNT_MODE_PAUSE MCPWM timer paused enumerator MCPWM_TIMER_COUNT_MODE_PAUSE MCPWM timer paused enumerator MCPWM_TIMER_COUNT_MODE_UP MCPWM timer counting up enumerator MCPWM_TIMER_COUNT_MODE_UP MCPWM timer counting up enumerator MCPWM_TIMER_COUNT_MODE_DOWN MCPWM timer counting down enumerator MCPWM_TIMER_COUNT_MODE_DOWN MCPWM timer counting down enumerator MCPWM_TIMER_COUNT_MODE_UP_DOWN MCPWM timer counting up and down enumerator MCPWM_TIMER_COUNT_MODE_UP_DOWN MCPWM timer counting up and down enumerator MCPWM_TIMER_COUNT_MODE_PAUSE enum mcpwm_timer_start_stop_cmd_t MCPWM timer commands, specify the way to start or stop the timer. Values: enumerator MCPWM_TIMER_STOP_EMPTY MCPWM timer stops when next count reaches zero enumerator MCPWM_TIMER_STOP_EMPTY MCPWM timer stops when next count reaches zero enumerator MCPWM_TIMER_STOP_FULL MCPWM timer stops when next count reaches peak enumerator MCPWM_TIMER_STOP_FULL MCPWM timer stops when next count reaches peak enumerator MCPWM_TIMER_START_NO_STOP MCPWM timer starts couting, and don't stop until received stop command enumerator MCPWM_TIMER_START_NO_STOP MCPWM timer starts couting, and don't stop until received stop command enumerator MCPWM_TIMER_START_STOP_EMPTY MCPWM timer starts counting and stops when next count reaches zero enumerator MCPWM_TIMER_START_STOP_EMPTY MCPWM timer starts counting and stops when next count reaches zero enumerator MCPWM_TIMER_START_STOP_FULL MCPWM timer starts counting and stops when next count reaches peak enumerator MCPWM_TIMER_START_STOP_FULL MCPWM timer starts counting and stops when next count reaches peak enumerator MCPWM_TIMER_STOP_EMPTY enum mcpwm_generator_action_t MCPWM generator actions. Values: enumerator MCPWM_GEN_ACTION_KEEP Generator action: Keep the same level enumerator MCPWM_GEN_ACTION_KEEP Generator action: Keep the same level enumerator MCPWM_GEN_ACTION_LOW Generator action: Force to low level enumerator MCPWM_GEN_ACTION_LOW Generator action: Force to low level enumerator MCPWM_GEN_ACTION_HIGH Generator action: Force to high level enumerator MCPWM_GEN_ACTION_HIGH Generator action: Force to high level enumerator MCPWM_GEN_ACTION_TOGGLE Generator action: Toggle level enumerator MCPWM_GEN_ACTION_TOGGLE Generator action: Toggle level enumerator MCPWM_GEN_ACTION_KEEP enum mcpwm_operator_brake_mode_t MCPWM operator brake mode. Values: enumerator MCPWM_OPER_BRAKE_MODE_CBC Brake mode: CBC (cycle by cycle) enumerator MCPWM_OPER_BRAKE_MODE_CBC Brake mode: CBC (cycle by cycle) enumerator MCPWM_OPER_BRAKE_MODE_OST Brake mode: OST (one shot) enumerator MCPWM_OPER_BRAKE_MODE_OST Brake mode: OST (one shot) enumerator MCPWM_OPER_BRAKE_MODE_INVALID MCPWM operator invalid brake mode enumerator MCPWM_OPER_BRAKE_MODE_INVALID MCPWM operator invalid brake mode enumerator MCPWM_OPER_BRAKE_MODE_CBC enum mcpwm_capture_edge_t MCPWM capture edge. Values: enumerator MCPWM_CAP_EDGE_POS Capture on the positive edge enumerator MCPWM_CAP_EDGE_POS Capture on the positive edge enumerator MCPWM_CAP_EDGE_NEG Capture on the negative edge enumerator MCPWM_CAP_EDGE_NEG Capture on the negative edge enumerator MCPWM_CAP_EDGE_POS enum mcpwm_comparator_etm_event_type_t MCPWM comparator specific events that supported by the ETM module. Values: enumerator MCPWM_CMPR_ETM_EVENT_EQUAL The count value equals the value of comparator enumerator MCPWM_CMPR_ETM_EVENT_EQUAL The count value equals the value of comparator enumerator MCPWM_CMPR_ETM_EVENT_MAX Maximum number of comparator events enumerator MCPWM_CMPR_ETM_EVENT_MAX Maximum number of comparator events enumerator MCPWM_CMPR_ETM_EVENT_EQUAL 1(1,2,3,4,5,6,7,8,9) Different ESP chip series might have a different number of MCPWM resources (e.g., groups, timers, comparators, operators, generators, triggers and so on). Please refer to the [TRM] for details. The driver does not forbid you from applying for more MCPWM resources, but it returns an error when there are no hardware resources available. Please always check the return value when doing Resource Allocation and Initialization. 2 The callback function and the sub-functions invoked by itself should also be placed in IRAM. You need to take care of this by yourself.
Motor Control Pulse Width Modulator (MCPWM) The MCPWM peripheral is a versatile PWM generator, which contains various submodules to make it a key element in power electronic applications like motor control, digital power, and so on. Typically, the MCPWM peripheral can be used in the following scenarios: Digital motor control, e.g., brushed/brushless DC motor, RC servo motor Switch mode-based digital power conversion Power DAC, where the duty cycle is equivalent to a DAC analog value Calculate external pulse width, and convert it into other analog values like speed, distance Generate Space Vector PWM (SVPWM) signals for Field Oriented Control (FOC) The main submodules are listed in the following diagram: MCPWM Timer: The time base of the final PWM signal. It also determines the event timing of other submodules. MCPWM Operator: The key module that is responsible for generating the PWM waveforms. It consists of other submodules, like comparator, PWM generator, dead time, and carrier modulator. MCPWM Comparator: The compare module takes the time-base count value as input, and continuously compares it to the threshold value configured. When the timer is equal to any of the threshold values, a compare event will be generated and the MCPWM generator can update its level accordingly. MCPWM Generator: One MCPWM generator can generate a pair of PWM waves, complementarily or independently, based on various events triggered by other submodules like MCPWM Timer and MCPWM Comparator. MCPWM Fault: The fault module is used to detect the fault condition from outside, mainly via the GPIO matrix. Once the fault signal is active, MCPWM Operator will force all the generators into a predefined state to protect the system from damage. MCPWM Sync: The sync module is used to synchronize the MCPWM timers, so that the final PWM signals generated by different MCPWM generators can have a fixed phase difference. The sync signal can be routed from the GPIO matrix or from an MCPWM Timer event. Dead Time: This submodule is used to insert extra delay to the existing PWM edges generated in the previous steps. Carrier Modulation: The carrier submodule can modulate a high-frequency carrier signal into PWM waveforms by the generator and dead time submodules. This capability is mandatory for controlling the power-switching elements. Brake: MCPWM operator can set how to brake the generators when a particular fault is detected. You can shut down the PWM output immediately or regulate the PWM output cycle by cycle, depending on how critical the fault is. MCPWM Capture: This is a standalone submodule that can work even without the above MCPWM operators. The capture consists one dedicated timer and several independent channels, with each channel connected to the GPIO. A pulse on the GPIO triggers the capture timer to store the time-base count value and then notify you by an interrupt. Using this feature, you can measure a pulse width precisely. What is more, the capture timer can also be synchronized by the MCPWM Sync submodule. Functional Overview Description of the MCPWM functionality is divided into the following sections: Resource Allocation and Initialization - covers how to allocate various MCPWM objects, like timers, operators, comparators, generators and so on. These objects are the basis of the following IO setting and control functions. Timer Operations and Events - describes control functions and event callbacks supported by the MCPWM timer. Comparator Operations and Events - describes control functions and event callbacks supported by the MCPWM comparator. Generator Actions on Events - describes how to set actions for MCPWM generators on particular events that are generated by the MCPWM timer and comparators. Generator Configurations for Classical PWM Waveforms - demonstrates some classical PWM waveforms that can be achieved by configuring generator actions. Dead Time - describes how to set dead time for MCPWM generators. Dead Time Configurations for Classical PWM Waveforms - demonstrates some classical PWM waveforms that can be achieved by configuring dead time. Carrier Modulation - describes how to set and modulate a high frequency onto the final PWM waveforms. Faults and Brake Actions - describes how to set brake actions for MCPWM operators on particular fault events. Generator Force Actions - describes how to control the generator output level asynchronously in a forceful way. Synchronization - describes how to synchronize the MCPWM timers and get a fixed phase difference between the generated PWM signals. Capture - describes how to use the MCPWM capture module to measure the pulse width of a signal. Power Management - describes how different source clocks affects power consumption. IRAM Safe - describes tips on how to make the RMT interrupt work better along with a disabled cache. Thread Safety - lists which APIs are guaranteed to be thread-safe by the driver. Kconfig Options - lists the supported Kconfig options that can bring different effects to the driver. Resource Allocation and Initialization As displayed in the diagram above, the MCPWM peripheral consists of several submodules. Each submodule has its own resource allocation, which is described in the following sections. MCPWM Timers You can allocate a MCPWM timer object by calling mcpwm_new_timer() function, with a configuration structure mcpwm_timer_config_t as the parameter. The configuration structure is defined as: mcpwm_timer_config_t::group_idspecifies the MCPWM group ID. The ID should belong to [0, SOC_MCPWM_GROUPS- 1] range. Please note, timers located in different groups are totally independent. mcpwm_timer_config_t::intr_prioritysets the priority of the interrupt. If it is set to 0, the driver will allocate an interrupt with a default priority. Otherwise, the driver will use the given priority. mcpwm_timer_config_t::clk_srcsets the clock source of the timer. mcpwm_timer_config_t::resolution_hzsets the expected resolution of the timer. The driver internally sets a proper divider based on the clock source and the resolution. mcpwm_timer_config_t::count_modesets the count mode of the timer. mcpwm_timer_config_t::period_tickssets the period of the timer, in ticks (the tick resolution is set in the mcpwm_timer_config_t::resolution_hz). mcpwm_timer_config_t::update_period_on_emptysets whether to update the period value when the timer counts to zero. mcpwm_timer_config_t::update_period_on_syncsets whether to update the period value when the timer takes a sync signal. The mcpwm_new_timer() will return a pointer to the allocated timer object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free timers in the MCPWM group, this function will return the ESP_ERR_NOT_FOUND error. 1 On the contrary, calling the mcpwm_del_timer() function will free the allocated timer object. MCPWM Operators You can allocate a MCPWM operator object by calling mcpwm_new_operator()() function, with a configuration structure mcpwm_operator_config_t as the parameter. The configuration structure is defined as: mcpwm_operator_config_t::group_idspecifies the MCPWM group ID. The ID should belong to [0, SOC_MCPWM_GROUPS- 1] range. Please note, operators located in different groups are totally independent. mcpwm_operator_config_t::intr_prioritysets the priority of the interrupt. If it is set to 0, the driver will allocate an interrupt with a default priority. Otherwise, the driver will use the given priority. mcpwm_operator_config_t::update_gen_action_on_tezsets whether to update the generator action when the timer counts to zero. Here and below, the timer refers to the one that is connected to the operator by mcpwm_operator_connect_timer(). mcpwm_operator_config_t::update_gen_action_on_tepsets whether to update the generator action when the timer counts to peak. mcpwm_operator_config_t::update_gen_action_on_syncsets whether to update the generator action when the timer takes a sync signal. mcpwm_operator_config_t::update_dead_time_on_tezsets whether to update the dead time when the timer counts to zero. mcpwm_operator_config_t::update_dead_time_on_tepsets whether to update the dead time when the timer counts to the peak. mcpwm_operator_config_t::update_dead_time_on_syncsets whether to update the dead time when the timer takes a sync signal. The mcpwm_new_operator()() will return a pointer to the allocated operator object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free operators in the MCPWM group, this function will return the ESP_ERR_NOT_FOUND error. 1 On the contrary, calling mcpwm_del_operator()() function will free the allocated operator object. MCPWM Comparators You can allocate a MCPWM comparator object by calling the mcpwm_new_comparator() function, with a MCPWM operator handle and configuration structure mcpwm_comparator_config_t as the parameter. The operator handle is created by mcpwm_new_operator()(). The configuration structure is defined as: mcpwm_comparator_config_t::intr_prioritysets the priority of the interrupt. If it is set to 0, the driver will allocate an interrupt with a default priority. Otherwise, the driver will use the given priority. mcpwm_comparator_config_t::update_cmp_on_tezsets whether to update the compare threshold when the timer counts to zero. mcpwm_comparator_config_t::update_cmp_on_tepsets whether to update the compare threshold when the timer counts to the peak. mcpwm_comparator_config_t::update_cmp_on_syncsets whether to update the compare threshold when the timer takes a sync signal. The mcpwm_new_comparator() will return a pointer to the allocated comparator object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free comparators in the MCPWM operator, this function will return the ESP_ERR_NOT_FOUND error. 1 On the contrary, calling the mcpwm_del_comparator() function will free the allocated comparator object. MCPWM Generators You can allocate a MCPWM generator object by calling the mcpwm_new_generator() function, with a MCPWM operator handle and configuration structure mcpwm_generator_config_t as the parameter. The operator handle is created by mcpwm_new_operator()(). The configuration structure is defined as: mcpwm_generator_config_t::gen_gpio_numsets the GPIO number used by the generator. mcpwm_generator_config_t::invert_pwmsets whether to invert the PWM signal. mcpwm_generator_config_t::io_loop_backsets whether to enable the Loop-back mode. It is for debugging purposes only. It enables both the GPIO's input and output ability through the GPIO matrix peripheral. mcpwm_generator_config_t::io_od_modeconfigures the PWM GPIO as open-drain output. mcpwm_generator_config_t::pull_upand mcpwm_generator_config_t::pull_downcontrols whether to enable the internal pull-up and pull-down resistors accordingly. The mcpwm_new_generator() will return a pointer to the allocated generator object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free generators in the MCPWM operator, this function will return the ESP_ERR_NOT_FOUND error. 1 On the contrary, calling the mcpwm_del_generator() function will free the allocated generator object. MCPWM Faults There are two types of faults: A fault signal reflected from the GPIO and a fault generated by software. To allocate a GPIO fault object, you can call the mcpwm_new_gpio_fault() function, with the configuration structure mcpwm_gpio_fault_config_t as the parameter. The configuration structure is defined as: mcpwm_gpio_fault_config_t::group_idsets the MCPWM group ID. The ID should belong to [0, SOC_MCPWM_GROUPS- 1] range. Please note, GPIO faults located in different groups are totally independent, i.e., GPIO faults in group 0 can not be detected by the operator in group 1. mcpwm_gpio_fault_config_t::intr_prioritysets the priority of the interrupt. If it is set to 0, the driver will allocate an interrupt with a default priority. Otherwise, the driver will use the given priority. mcpwm_gpio_fault_config_t::gpio_numsets the GPIO number used by the fault. mcpwm_gpio_fault_config_t::active_levelsets the active level of the fault signal. mcpwm_gpio_fault_config_t::pull_upand mcpwm_gpio_fault_config_t::pull_downset whether to pull up and/or pull down the GPIO internally. mcpwm_gpio_fault_config_t::io_loop_backsets whether to enable the loopback mode. It is for debugging purposes only. It enables both the GPIO's input and output ability through the GPIO matrix peripheral. The mcpwm_new_gpio_fault() will return a pointer to the allocated fault object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free GPIO faults in the MCPWM group, this function will return the ESP_ERR_NOT_FOUND error. 1 Software fault object can be used to trigger a fault by calling the function mcpwm_soft_fault_activate() instead of waiting for a real fault signal on the GPIO. A software fault object can be allocated by calling the mcpwm_new_soft_fault() function, with configuration structure mcpwm_soft_fault_config_t as the parameter. Currently, this configuration structure is left for future purposes. The mcpwm_new_soft_fault() function will return a pointer to the allocated fault object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there is no memory left for the fault object, this function will return the ESP_ERR_NO_MEM error. Although the software fault and GPIO fault are of different types, the returned fault handle is of the same type. On the contrary, calling the mcpwm_del_fault() function will free the allocated fault object, this function works for both software and GPIO fault. MCPWM Sync Sources The sync source is what can be used to synchronize the MCPWM timer and MCPWM capture timer. There are three types of sync sources: a sync source reflected from the GPIO, a sync source generated by software, and a sync source generated by an MCPWM timer event. To allocate a GPIO sync source, you can call the mcpwm_new_gpio_sync_src() function, with configuration structure mcpwm_gpio_sync_src_config_t as the parameter. The configuration structure is defined as: mcpwm_gpio_sync_src_config_t::group_idsets the MCPWM group ID. The ID should belong to [0, SOC_MCPWM_GROUPS- 1] range. Please note, the GPIO sync sources located in different groups are totally independent, i.e., GPIO sync source in group 0 can not be detected by the timers in group 1. mcpwm_gpio_sync_src_config_t::gpio_numsets the GPIO number used by the sync source. mcpwm_gpio_sync_src_config_t::active_negsets whether the sync signal is active on falling edges. mcpwm_gpio_sync_src_config_t::pull_upand mcpwm_gpio_sync_src_config_t::pull_downset whether to pull up and/or pull down the GPIO internally. mcpwm_gpio_sync_src_config_t::io_loop_backsets whether to enable the Loop-back mode. It is for debugging purposes only. It enables both the GPIO's input and output ability through the GPIO matrix peripheral. The mcpwm_new_gpio_sync_src() will return a pointer to the allocated sync source object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free GPIO sync sources in the MCPWM group, this function will return the ESP_ERR_NOT_FOUND error. 1 To allocate a timer event sync source, you can call the mcpwm_new_timer_sync_src() function, with configuration structure mcpwm_timer_sync_src_config_t as the parameter. The configuration structure is defined as: mcpwm_timer_sync_src_config_t::timer_eventspecifies on what timer event to generate the sync signal. mcpwm_timer_sync_src_config_t::propagate_input_syncsets whether to propagate the input sync signal (i.e., the input sync signal will be routed to its sync output). The mcpwm_new_timer_sync_src() will return a pointer to the allocated sync source object if the allocation succeeds. Otherwise, it will return an error code. Specifically, if a sync source has been allocated from the same timer before, this function will return the ESP_ERR_INVALID_STATE error. Last but not least, to allocate a software sync source, you can call the mcpwm_new_soft_sync_src() function, with configuration structure mcpwm_soft_sync_config_t as the parameter. Currently, this configuration structure is left for future purposes. mcpwm_new_soft_sync_src() will return a pointer to the allocated sync source object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there is no memory left for the sync source object, this function will return the ESP_ERR_NO_MEM error. Please note, to make a software sync source take effect, do not forget to call mcpwm_soft_sync_activate(). On the contrary, calling the mcpwm_del_sync_src() function will free the allocated sync source object. This function works for all types of sync sources. MCPWM Capture Timer and Channels The MCPWM group has a dedicated timer which is used to capture the timestamp when a specific event occurred. The capture timer is connected to several independent channels, each channel is assigned a GPIO. To allocate a capture timer, you can call the mcpwm_new_capture_timer() function, with configuration structure mcpwm_capture_timer_config_t as the parameter. The configuration structure is defined as: mcpwm_capture_timer_config_t::group_idsets the MCPWM group ID. The ID should belong to [0, SOC_MCPWM_GROUPS- 1] range. mcpwm_capture_timer_config_t::clk_srcsets the clock source of the capture timer. mcpwm_capture_timer_config_t::resolution_hzThe driver internally will set a proper divider based on the clock source and the resolution. If it is set to 0, the driver will pick an appropriate resolution on its own, and you can subsequently view the current timer resolution via mcpwm_capture_timer_get_resolution(). Note In ESP32, mcpwm_capture_timer_config_t::resolution_hz parameter is invalid, the capture timer resolution is always equal to the MCPWM_CAPTURE_CLK_SRC_APB. The mcpwm_new_capture_timer() will return a pointer to the allocated capture timer object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there is no free capture timer left in the MCPWM group, this function will return the ESP_ERR_NOT_FOUND error. 1 Next, to allocate a capture channel, you can call the mcpwm_new_capture_channel() function, with a capture timer handle and configuration structure mcpwm_capture_channel_config_t as the parameter. The configuration structure is defined as: mcpwm_capture_channel_config_t::intr_prioritysets the priority of the interrupt. If it is set to 0, the driver will allocate an interrupt with a default priority. Otherwise, the driver will use the given priority. mcpwm_capture_channel_config_t::gpio_numsets the GPIO number used by the capture channel. mcpwm_capture_channel_config_t::prescalesets the prescaler of the input signal. mcpwm_capture_channel_config_t::pos_edgeand mcpwm_capture_channel_config_t::neg_edgeset whether to capture on the positive and/or falling edge of the input signal. mcpwm_capture_channel_config_t::pull_upand mcpwm_capture_channel_config_t::pull_downset whether to pull up and/or pull down the GPIO internally. mcpwm_capture_channel_config_t::invert_cap_signalsets whether to invert the capture signal. mcpwm_capture_channel_config_t::io_loop_backsets whether to enable the Loop-back mode. It is for debugging purposes only. It enables both the GPIO's input and output ability through the GPIO matrix peripheral. The mcpwm_new_capture_channel() will return a pointer to the allocated capture channel object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there is no free capture channel left in the capture timer, this function will return the ESP_ERR_NOT_FOUND error. On the contrary, calling mcpwm_del_capture_channel() and mcpwm_del_capture_timer() will free the allocated capture channel and timer object accordingly. MCPWM Interrupt Priority MCPWM allows configuring interrupts separately for timer, operator, comparator, fault, and capture events. The interrupt priority is determined by the respective config_t::intr_priority. Additionally, events within the same MCPWM group share a common interrupt source. When registering multiple interrupt events, the interrupt priorities need to remain consistent. Note When registering multiple interrupt events within an MCPWM group, the driver will use the interrupt priority of the first registered event as the MCPWM group's interrupt priority. Timer Operations and Events Update Period The timer period is initialized by the mcpwm_timer_config_t::period_ticks parameter in mcpwm_timer_config_t. You can update the period at runtime by calling mcpwm_timer_set_period() function. The new period will take effect based on how you set the mcpwm_timer_config_t::update_period_on_empty and mcpwm_timer_config_t::update_period_on_sync parameters in mcpwm_timer_config_t. If none of them are set, the timer period will take effect immediately. Register Timer Event Callbacks The MCPWM timer can generate different events at runtime. If you have some function that should be called when a particular event happens, you should hook your function to the interrupt service routine by calling mcpwm_timer_register_event_callbacks(). The callback function prototype is declared in mcpwm_timer_event_cb_t. All supported event callbacks are listed in the mcpwm_timer_event_callbacks_t: mcpwm_timer_event_callbacks_t::on_fullsets the callback function for the timer when it counts to peak value. mcpwm_timer_event_callbacks_t::on_emptysets the callback function for the timer when it counts to zero. mcpwm_timer_event_callbacks_t::on_stopsets the callback function for the timer when it is stopped. The callback functions above are called within the ISR context, so they should not attempt to block. For example, you may make sure that only FreeRTOS APIs with the ISR suffix are called within the function. The parameter user_data of the mcpwm_timer_register_event_callbacks() function is used to save your own context. It is passed to each callback function directly. This function will lazy the install interrupt service for the MCPWM timer without enabling it. It is only allowed to be called before mcpwm_timer_enable(), otherwise the ESP_ERR_INVALID_STATE error will be returned. See also Enable and Disable timer for more information. Enable and Disable Timer Before doing IO control to the timer, you need to enable the timer first, by calling mcpwm_timer_enable(). This function: switches the timer state from init to enable. enables the interrupt service if it has been lazy installed by mcpwm_timer_register_event_callbacks(). acquire a proper power management lock if a specific clock source (e.g., PLL_160M clock) is selected. See also Power management for more information. On the contrary, calling mcpwm_timer_disable() will put the timer driver back to the init state, disable the interrupt service and release the power management lock. Start and Stop Timer The basic IO operation of a timer is to start and stop. Calling mcpwm_timer_start_stop() with different mcpwm_timer_start_stop_cmd_t commands can start the timer immediately or stop the timer at a specific event. What is more, you can even start the timer for only one round, which means, the timer will count to peak value or zero, and then stop itself. Connect Timer with Operator The allocated MCPWM timer should be connected with an MCPWM operator by calling mcpwm_operator_connect_timer(), so that the operator can take that timer as its time base, and generate the required PWM waves. Please make sure the MCPWM timer and operator are in the same group. Otherwise, this function will return the ESP_ERR_INVALID_ARG error. Comparator Operations and Events Register Comparator Event Callbacks The MCPWM comparator can inform you when the timer counter equals the compare value. If you have some function that should be called when this event happens, you should hook your function to the interrupt service routine by calling mcpwm_comparator_register_event_callbacks(). The callback function prototype is declared in mcpwm_compare_event_cb_t. All supported event callbacks are listed in the mcpwm_comparator_event_callbacks_t: mcpwm_comparator_event_callbacks_t::on_reachsets the callback function for the comparator when the timer counter equals the compare value. The callback function provides event-specific data of type mcpwm_compare_event_data_t to you. The callback function is called within the ISR context, so it should not attempt to block. For example, you may make sure that only FreeRTOS APIs with the ISR suffix are called within the function. The parameter user_data of mcpwm_comparator_register_event_callbacks() function is used to save your own context. It is passed to the callback function directly. This function will lazy the installation of interrupt service for the MCPWM comparator, whereas the service can only be removed in mcpwm_del_comparator. Set Compare Value You can set the compare value for the MCPWM comparator at runtime by calling mcpwm_comparator_set_compare_value(). There are a few points to note: A new compare value might not take effect immediately. The update time for the compare value is set by mcpwm_comparator_config_t::update_cmp_on_tezor mcpwm_comparator_config_t::update_cmp_on_tepor mcpwm_comparator_config_t::update_cmp_on_sync. Make sure the operator has connected to one MCPWM timer already by mcpwm_operator_connect_timer(). Otherwise, it will return the error code ESP_ERR_INVALID_STATE. The compare value should not exceed the timer's count peak, otherwise, the compare event will never get triggered. Generator Actions on Events Set Generator Action on Timer Event One generator can set multiple actions on different timer events, by calling mcpwm_generator_set_actions_on_timer_event() with a variable number of action configurations. The action configuration is defined in mcpwm_gen_timer_event_action_t: mcpwm_gen_timer_event_action_t::directionspecifies the timer direction. The supported directions are listed in mcpwm_timer_direction_t. mcpwm_gen_timer_event_action_t::eventspecifies the timer event. The supported timer events are listed in mcpwm_timer_event_t. mcpwm_gen_timer_event_action_t::actionspecifies the generator action to be taken. The supported actions are listed in mcpwm_generator_action_t. There is a helper macro MCPWM_GEN_TIMER_EVENT_ACTION to simplify the construction of a timer event action entry. Please note, the argument list of mcpwm_generator_set_actions_on_timer_event() must be terminated by MCPWM_GEN_TIMER_EVENT_ACTION_END. You can also set the timer action one by one by calling mcpwm_generator_set_action_on_timer_event() without varargs. Set Generator Action on Compare Event One generator can set multiple actions on different compare events, by calling mcpwm_generator_set_actions_on_compare_event() with a variable number of action configurations. The action configuration is defined in mcpwm_gen_compare_event_action_t: mcpwm_gen_compare_event_action_t::directionspecifies the timer direction. The supported directions are listed in mcpwm_timer_direction_t. mcpwm_gen_compare_event_action_t::comparatorspecifies the comparator handle. See MCPWM Comparators for how to allocate a comparator. mcpwm_gen_compare_event_action_t::actionspecifies the generator action to be taken. The supported actions are listed in mcpwm_generator_action_t. There is a helper macro MCPWM_GEN_COMPARE_EVENT_ACTION to simplify the construction of a compare event action entry. Please note, the argument list of mcpwm_generator_set_actions_on_compare_event() must be terminated by MCPWM_GEN_COMPARE_EVENT_ACTION_END. You can also set the compare action one by one by calling mcpwm_generator_set_action_on_compare_event() without varargs. Set Generator Action on Fault Event One generator can set action on fault based trigger events, by calling mcpwm_generator_set_action_on_fault_event() with an action configurations. The action configuration is defined in mcpwm_gen_fault_event_action_t: mcpwm_gen_fault_event_action_t::directionspecifies the timer direction. The supported directions are listed in mcpwm_timer_direction_t. mcpwm_gen_fault_event_action_t::faultspecifies the fault used for the trigger. See MCPWM Faults for how to allocate a fault. mcpwm_gen_fault_event_action_t::actionspecifies the generator action to be taken. The supported actions are listed in mcpwm_generator_action_t. When no free trigger slot is left in the operator to which the generator belongs, this function will return the ESP_ERR_NOT_FOUND error. 1 The trigger only support GPIO fault. when the input is not a GPIO fault, this function will return the ESP_ERR_NOT_SUPPORTED error. There is a helper macro MCPWM_GEN_FAULT_EVENT_ACTION to simplify the construction of a trigger event action entry. Please note, fault event does not have variadic function like mcpwm_generator_set_actions_on_fault_event(). Set Generator Action on Sync Event One generator can set action on sync based trigger events, by calling mcpwm_generator_set_action_on_sync_event() with an action configurations. The action configuration is defined in mcpwm_gen_sync_event_action_t: mcpwm_gen_sync_event_action_t::directionspecifies the timer direction. The supported directions are listed in mcpwm_timer_direction_t. mcpwm_gen_sync_event_action_t::syncspecifies the sync source used for the trigger. See MCPWM Sync Sources for how to allocate a sync source. mcpwm_gen_sync_event_action_t::actionspecifies the generator action to be taken. The supported actions are listed in mcpwm_generator_action_t. When no free trigger slot is left in the operator to which the generator belongs, this function will return the ESP_ERR_NOT_FOUND error. 1 The trigger only support one sync action, regardless of the kinds. When set sync actions more than once, this function will return the ESP_ERR_INVALID_STATE error. There is a helper macro MCPWM_GEN_SYNC_EVENT_ACTION to simplify the construction of a trigger event action entry. Please note, sync event does not have variadic function like mcpwm_generator_set_actions_on_sync_event(). Generator Configurations for Classical PWM Waveforms This section will demonstrate the classical PWM waveforms that can be generated by the pair of generators. The code snippet that is used to generate the waveforms is also provided below the diagram. Some general summary: The Symmetric or Asymmetric of the waveforms is determined by the count mode of the MCPWM timer. The active level of the waveform pair is determined by the level of the PWM with a smaller duty cycle. The period of the PWM waveform is determined by the timer's period and count mode. The duty cycle of the PWM waveform is determined by the generator's various action combinations. Single Edge Asymmetric Waveform - Active High static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(genb, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(genb, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_LOW))); } Single Edge Asymmetric Waveform - Active Low static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_FULL, MCPWM_GEN_ACTION_LOW))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(genb, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_FULL, MCPWM_GEN_ACTION_LOW))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(genb, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_HIGH))); } Pulse Placement Asymmetric Waveform static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_HIGH), MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_LOW), MCPWM_GEN_COMPARE_EVENT_ACTION_END())); ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_timer_event(genb, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_TOGGLE), MCPWM_GEN_TIMER_EVENT_ACTION_END())); } Dual Edge Asymmetric Waveform - Active Low static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_HIGH), MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_DOWN, cmpb, MCPWM_GEN_ACTION_LOW), MCPWM_GEN_COMPARE_EVENT_ACTION_END())); ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_timer_event(genb, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_LOW), MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_DOWN, MCPWM_TIMER_EVENT_FULL, MCPWM_GEN_ACTION_HIGH), MCPWM_GEN_TIMER_EVENT_ACTION_END())); } Dual Edge Symmetric Waveform - Active Low static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_HIGH), MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_DOWN, cmpa, MCPWM_GEN_ACTION_LOW), MCPWM_GEN_COMPARE_EVENT_ACTION_END())); ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_compare_event(genb, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_HIGH), MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_DOWN, cmpb, MCPWM_GEN_ACTION_LOW), MCPWM_GEN_COMPARE_EVENT_ACTION_END())); } Dual Edge Symmetric Waveform - Complementary static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_HIGH), MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_DOWN, cmpa, MCPWM_GEN_ACTION_LOW), MCPWM_GEN_COMPARE_EVENT_ACTION_END())); ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_compare_event(genb, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_LOW), MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_DOWN, cmpb, MCPWM_GEN_ACTION_HIGH), MCPWM_GEN_COMPARE_EVENT_ACTION_END())); } Dead Time In power electronics, the rectifier and inverter are commonly used. This requires the use of a rectifier bridge and an inverter bridge. Each bridge arm has two power electronic devices, such as MOSFET, IGBT, etc. The two MOSFETs on the same arm can not conduct at the same time, otherwise there will be a short circuit. The fact is that, although the PWM wave shows it is turning off the switch, the MOSFET still needs a small time window to make that happen. This requires an extra delay to be added to the existing PWM wave generated by setting Generator Actions on Events. The dead time driver works like a decorator. This is also reflected in the function parameters of mcpwm_generator_set_dead_time(), where it takes the primary generator handle ( in_generator), and returns a new generator ( out_generator) after applying the dead time. Please note, if the out_generator and in_generator are the same, it means you are adding the time delay to the PWM waveform in an "in-place" fashion. In turn, if the out_generator and in_generator are different, it means you are deriving a new PWM waveform from the existing in_generator. Dead time specific configuration is listed in the mcpwm_dead_time_config_t structure: mcpwm_dead_time_config_t::posedge_delay_ticksand mcpwm_dead_time_config_t::negedge_delay_ticksset the number of ticks to delay the PWM waveform on the rising and falling edge. Specifically, setting both of them to zero means bypassing the dead time module. The resolution of the dead time tick is the same as the timer that is connected with the operator by mcpwm_operator_connect_timer(). mcpwm_dead_time_config_t::invert_outputsets whether to invert the signal after applying the dead time, which can be used to control the delay edge polarity. Warning Due to the hardware limitation, one delay module (either posedge delay or negedge delay) can not be applied to multiple MCPWM generators at the same time. e.g., the following configuration is invalid: mcpwm_dead_time_config_t dt_config = { .posedge_delay_ticks = 10, }; // Set posedge delay to generator A mcpwm_generator_set_dead_time(mcpwm_gen_a, mcpwm_gen_a, &dt_config); // NOTE: This is invalid, you can not apply the posedge delay to another generator mcpwm_generator_set_dead_time(mcpwm_gen_b, mcpwm_gen_b, &dt_config); However, you can apply posedge delay to generator A and negedge delay to generator B. You can also set both posedge delay and negedge delay for generator A, while letting generator B bypass the dead time module. Note It is also possible to generate the required dead time by setting Generator Actions on Events, especially by controlling edge placement using different comparators. However, if the more classical edge delay-based dead time with polarity control is required, then the dead time submodule should be used. Dead Time Configurations for Classical PWM Waveforms This section demonstrates the classical PWM waveforms that can be generated by the dead time submodule. The code snippet that is used to generate the waveforms is also provided below the diagram. Active High Complementary static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); } static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb) { mcpwm_dead_time_config_t dead_time_config = { .posedge_delay_ticks = 50, .negedge_delay_ticks = 0 }; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config)); dead_time_config.posedge_delay_ticks = 0; dead_time_config.negedge_delay_ticks = 100; dead_time_config.flags.invert_output = true; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, genb, &dead_time_config)); } Active Low Complementary static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); } static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb) { mcpwm_dead_time_config_t dead_time_config = { .posedge_delay_ticks = 50, .negedge_delay_ticks = 0, .flags.invert_output = true }; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config)); dead_time_config.posedge_delay_ticks = 0; dead_time_config.negedge_delay_ticks = 100; dead_time_config.flags.invert_output = false; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, genb, &dead_time_config)); } Active High static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); } static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb) { mcpwm_dead_time_config_t dead_time_config = { .posedge_delay_ticks = 50, .negedge_delay_ticks = 0, }; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config)); dead_time_config.posedge_delay_ticks = 0; dead_time_config.negedge_delay_ticks = 100; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, genb, &dead_time_config)); } Active Low static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); } static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb) { mcpwm_dead_time_config_t dead_time_config = { .posedge_delay_ticks = 50, .negedge_delay_ticks = 0, .flags.invert_output = true }; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config)); dead_time_config.posedge_delay_ticks = 0; dead_time_config.negedge_delay_ticks = 100; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, genb, &dead_time_config)); } Rising Delay on PWMA and Bypass Dead Time for PWMB static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(genb, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(genb, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_LOW))); } static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb) { mcpwm_dead_time_config_t dead_time_config = { .posedge_delay_ticks = 50, .negedge_delay_ticks = 0, }; // apply deadtime to generator_a ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config)); // bypass deadtime module for generator_b dead_time_config.posedge_delay_ticks = 0; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(genb, genb, &dead_time_config)); } Falling Delay on PWMB and Bypass Dead Time for PWMA static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(genb, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(genb, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_LOW))); } static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb) { mcpwm_dead_time_config_t dead_time_config = { .posedge_delay_ticks = 0, .negedge_delay_ticks = 0, }; // generator_a bypass the deadtime module (no delay) ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config)); // apply dead time to generator_b dead_time_config.negedge_delay_ticks = 50; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(genb, genb, &dead_time_config)); } Rising and Falling Delay on PWMB and Bypass Dead Time for PWMA static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb) { ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(genb, MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH))); ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(genb, MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_LOW))); } static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb) { mcpwm_dead_time_config_t dead_time_config = { .posedge_delay_ticks = 0, .negedge_delay_ticks = 0, }; // generator_a bypass the deadtime module (no delay) ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config)); // apply dead time on both edge for generator_b dead_time_config.negedge_delay_ticks = 50; dead_time_config.posedge_delay_ticks = 50; ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(genb, genb, &dead_time_config)); } Carrier Modulation The MCPWM operator has a carrier submodule that can be used if galvanic isolation from the motor driver is required (e.g., isolated digital power application) by passing the PWM output signals through transformers. Any of the PWM output signals may be at 100% duty and not changing whenever a motor is required to run steadily at the full load. Coupling with non-alternating signals with a transformer is problematic, so the signals are modulated by the carrier submodule to create an AC waveform, to make the coupling possible. To configure the carrier submodule, you can call mcpwm_operator_apply_carrier(), and provide configuration structure mcpwm_carrier_config_t: mcpwm_carrier_config_t::clk_srcsets the clock source of the carrier. mcpwm_carrier_config_t::frequency_hzindicates carrier frequency in Hz. mcpwm_carrier_config_t::duty_cycleindicates the duty cycle of the carrier. Note that, the supported choices of the duty cycle are discrete, the driver searches for the nearest one based on your configuration. mcpwm_carrier_config_t::first_pulse_duration_usindicates the duration of the first pulse in microseconds. The resolution of the first pulse duration is determined by the carrier frequency you set in the mcpwm_carrier_config_t::frequency_hz. The first pulse duration can not be zero, and it has to be at least one period of the carrier. A longer pulse width can help conduct the inductance quicker. mcpwm_carrier_config_t::invert_before_modulateand mcpwm_carrier_config_t::invert_after_modulateset whether to invert the carrier output before and after modulation. Specifically, the carrier submodule can be disabled by calling mcpwm_operator_apply_carrier() with a NULL configuration. Faults and Brake Actions The MCPWM operator is able to sense external signals with information about the failure of the motor, the power driver or any other device connected. These failure signals are encapsulated into MCPWM fault objects. You should determine possible failure modes of the motor and what action should be performed on detection of a particular fault, e.g., drive all outputs low for a brushed motor, lock current state for a stepper motor, etc. Because of this action, the motor should be put into a safe state to reduce the likelihood of damage caused by the fault. Set Operator Brake Mode on Fault The way that MCPWM operator reacts to the fault is called Brake. The MCPWM operator can be configured to perform different brake modes for each fault object by calling mcpwm_operator_set_brake_on_fault(). Specific brake configuration is passed as a structure mcpwm_brake_config_t: mcpwm_brake_config_t::faultsets which fault the operator should react to. mcpwm_brake_config_t::brake_modesets the brake mode that should be used for the fault. The supported brake modes are listed in the mcpwm_operator_brake_mode_t. For MCPWM_OPER_BRAKE_MODE_CBCmode, the operator recovers itself automatically as long as the fault disappears. You can specify the recovery time in mcpwm_brake_config_t::cbc_recover_on_tezand mcpwm_brake_config_t::cbc_recover_on_tep. For MCPWM_OPER_BRAKE_MODE_OSTmode, the operator can not recover even though the fault disappears. You have to call mcpwm_operator_recover_from_fault()to manually recover it. Set Generator Action on Brake Event One generator can set multiple actions on different brake events, by calling mcpwm_generator_set_actions_on_brake_event() with a variable number of action configurations. The action configuration is defined in mcpwm_gen_brake_event_action_t: mcpwm_gen_brake_event_action_t::directionspecifies the timer direction. The supported directions are listed in mcpwm_timer_direction_t. mcpwm_gen_brake_event_action_t::brake_modespecifies the brake mode. The supported brake modes are listed in the mcpwm_operator_brake_mode_t. mcpwm_gen_brake_event_action_t::actionspecifies the generator action to be taken. The supported actions are listed in mcpwm_generator_action_t. There is a helper macro MCPWM_GEN_BRAKE_EVENT_ACTION to simplify the construction of a brake event action entry. Please note, the argument list of mcpwm_generator_set_actions_on_brake_event() must be terminated by MCPWM_GEN_BRAKE_EVENT_ACTION_END. You can also set the brake action one by one by calling mcpwm_generator_set_action_on_brake_event() without varargs. Register Fault Event Callbacks The MCPWM fault detector can inform you when it detects a valid fault or a fault signal disappears. If you have some function that should be called when such an event happens, you should hook your function to the interrupt service routine by calling mcpwm_fault_register_event_callbacks(). The callback function prototype is declared in mcpwm_fault_event_cb_t. All supported event callbacks are listed in the mcpwm_fault_event_callbacks_t: mcpwm_fault_event_callbacks_t::on_fault_entersets the callback function that will be called when a fault is detected. mcpwm_fault_event_callbacks_t::on_fault_exitsets the callback function that will be called when a fault is cleared. The callback function is called within the ISR context, so it should not attempt to block. For example, you may make sure that only FreeRTOS APIs with the ISR suffix are called within the function. The parameter user_data of mcpwm_fault_register_event_callbacks() function is used to save your own context. It is passed to the callback function directly. This function will lazy the install interrupt service for the MCPWM fault, whereas the service can only be removed in mcpwm_del_fault. Register Brake Event Callbacks The MCPWM operator can inform you when it is going to take a brake action. If you have some function that should be called when this event happens, you should hook your function to the interrupt service routine by calling mcpwm_operator_register_event_callbacks(). The callback function prototype is declared in mcpwm_brake_event_cb_t. All supported event callbacks are listed in the mcpwm_operator_event_callbacks_t: mcpwm_operator_event_callbacks_t::on_brake_cbcsets the callback function that will be called when the operator is going to take a CBC action. mcpwm_operator_event_callbacks_t::on_brake_ostsets the callback function that will be called when the operator is going to take an OST action. The callback function is called within the ISR context, so it should not attempt to block. For example, you may make sure that only FreeRTOS APIs with the ISR suffix are called within the function. The parameter user_data of the mcpwm_operator_register_event_callbacks() function is used to save your own context. It will be passed to the callback function directly. This function will lazy the install interrupt service for the MCPWM operator, whereas the service can only be removed in mcpwm_del_operator. Generator Force Actions Software can override generator output level at runtime, by calling mcpwm_generator_set_force_level(). The software force level always has a higher priority than other event actions set in e.g., mcpwm_generator_set_actions_on_timer_event(). Set the levelto -1 means to disable the force action, and the generator's output level will be controlled by the event actions again. Set the hold_onto true, and the force output level will keep alive until it is removed by assigning levelto -1. Set the hole_onto false, the force output level will only be active for a short time, and any upcoming event can override it. Synchronization When a sync signal is taken by the MCPWM timer, the timer will be forced into a predefined phase, where the phase is determined by count value and count direction. You can set the sync phase by calling mcpwm_timer_set_phase_on_sync(). The sync phase configuration is defined in mcpwm_timer_sync_phase_config_t structure: mcpwm_timer_sync_phase_config_t::sync_srcsets the sync signal source. See MCPWM Sync Sources for how to create a sync source object. Specifically, if this is set to NULL, the driver will disable the sync feature for the MCPWM timer. mcpwm_timer_sync_phase_config_t::count_valuesets the count value to load when the sync signal is taken. mcpwm_timer_sync_phase_config_t::directionsets the count direction when the sync signal is taken. Likewise, the MCPWM Capture Timer can be synced as well. You can set the sync phase for the capture timer by calling mcpwm_capture_timer_set_phase_on_sync(). The sync phase configuration is defined in mcpwm_capture_timer_sync_phase_config_t structure: mcpwm_capture_timer_sync_phase_config_t::sync_srcsets the sync signal source. See MCPWM Sync Sources for how to create a sync source object. Specifically, if this is set to NULL, the driver will disable the sync feature for the MCPWM capture timer. mcpwm_capture_timer_sync_phase_config_t::count_valuesets the count value to load when the sync signal is taken. mcpwm_capture_timer_sync_phase_config_t::directionsets the count direction when the sync signal is taken. Note that, different from MCPWM Timer, the capture timer can only support one count direction: MCPWM_TIMER_DIRECTION_UP. Sync Timers by GPIO static void example_setup_sync_strategy(mcpwm_timer_handle_t timers[]) { mcpwm_sync_handle_t gpio_sync_source = NULL; mcpwm_gpio_sync_src_config_t gpio_sync_config = { .group_id = 0, // GPIO fault should be in the same group of the above timers .gpio_num = EXAMPLE_SYNC_GPIO, .flags.pull_down = true, .flags.active_neg = false, // By default, a posedge pulse can trigger a sync event }; ESP_ERROR_CHECK(mcpwm_new_gpio_sync_src(&gpio_sync_config, &gpio_sync_source)); mcpwm_timer_sync_phase_config_t sync_phase_config = { .count_value = 0, // sync phase: target count value .direction = MCPWM_TIMER_DIRECTION_UP, // sync phase: count direction .sync_src = gpio_sync_source, // sync source }; for (int i = 0; i < 3; i++) { ESP_ERROR_CHECK(mcpwm_timer_set_phase_on_sync(timers[i], &sync_phase_config)); } } Capture The basic functionality of MCPWM capture is to record the time when any pulse edge of the capture signal turns active. Then you can get the pulse width and convert it into other physical quantities like distance or speed in the capture callback function. For example, in the BLDC (Brushless DC, see figure below) scenario, you can use the capture submodule to sense the rotor position from the Hall sensor. The capture timer is usually connected to several capture channels. Please refer to MCPWM Capture Timer and Channels for more information about resource allocation. Register Capture Event Callbacks The MCPWM capture channel can inform you when there is a valid edge detected on the signal. You have to register a callback function to get the timer count value of the captured moment, by calling mcpwm_capture_channel_register_event_callbacks(). The callback function prototype is declared in mcpwm_capture_event_cb_t. All supported capture callbacks are listed in the mcpwm_capture_event_callbacks_t: mcpwm_capture_event_callbacks_t::on_capsets the callback function for the capture channel when a valid edge is detected. The callback function provides event-specific data of type mcpwm_capture_event_data_t, so that you can get the edge of the capture signal in mcpwm_capture_event_data_t::cap_edge and the count value of that moment in mcpwm_capture_event_data_t::cap_value. To convert the capture count into a timestamp, you need to know the resolution of the capture timer by calling mcpwm_capture_timer_get_resolution(). The callback function is called within the ISR context, so it should not attempt to block. For example, you may make sure that only FreeRTOS APIs with the ISR suffix are called within the function. The parameter user_data of mcpwm_capture_channel_register_event_callbacks() function is used to save your context. It is passed to the callback function directly. This function will lazy install interrupt service for the MCPWM capture channel, whereas the service can only be removed in mcpwm_del_capture_channel. Enable and Disable Capture Channel The capture channel is not enabled after allocation by mcpwm_new_capture_channel(). You should call mcpwm_capture_channel_enable() and mcpwm_capture_channel_disable() accordingly to enable or disable the channel. If the interrupt service is lazy installed during registering event callbacks for the channel in mcpwm_capture_channel_register_event_callbacks(), mcpwm_capture_channel_enable() will enable the interrupt service as well. Enable and Disable Capture Timer Before doing IO control to the capture timer, you need to enable the timer first, by calling mcpwm_capture_timer_enable(). Internally, this function: switches the capture timer state from init to enable. acquires a proper power management lock if a specific clock source (e.g., APB clock) is selected. See also Power management for more information. On the contrary, calling mcpwm_capture_timer_disable() will put the timer driver back to init state, and release the power management lock. Start and Stop Capture Timer The basic IO operation of a capture timer is to start and stop. Calling mcpwm_capture_timer_start() can start the timer and calling mcpwm_capture_timer_stop() can stop the timer immediately. Trigger a Software Capture Event Sometimes, the software also wants to trigger a "fake" capture event. The mcpwm_capture_channel_trigger_soft_catch() is provided for that purpose. Please note that, even though it is a "fake" capture event, it can still cause an interrupt, thus your capture event callback function gets invoked as well. Power Management When power management is enabled (i.e., CONFIG_PM_ENABLE is on), the system will adjust the PLL and APB frequency before going into Light-sleep, thus potentially changing the period of an MCPWM timers' counting step and leading to inaccurate time-keeping. However, the driver can prevent the system from changing APB frequency by acquiring a power management lock of type ESP_PM_APB_FREQ_MAX. Whenever the driver creates an MCPWM timer instance that has selected MCPWM_TIMER_CLK_SRC_PLL160M as its clock source, the driver guarantees that the power management lock is acquired when enabling the timer by mcpwm_timer_enable(). On the contrary, the driver releases the lock when mcpwm_timer_disable() is called for that timer. Likewise, whenever the driver creates an MCPWM capture timer instance that has selected MCPWM_CAPTURE_CLK_SRC_APB as its clock source, the driver guarantees that the power management lock is acquired when enabling the timer by mcpwm_capture_timer_enable(). And releases the lock in mcpwm_capture_timer_disable(). IRAM Safe By default, the MCPWM interrupt will be deferred when the Cache is disabled for reasons like writing/erasing Flash. Thus the event callback functions will not get executed in time, which is not expected in a real-time application. There is a Kconfig option CONFIG_MCPWM_ISR_IRAM_SAFE that: enables the interrupt to be serviced even when the cache is disabled places all functions used by the ISR into IRAM 2 places the driver object into DRAM (in case it is mapped to PSRAM by accident) This allows the interrupt to run while the cache is disabled but comes at the cost of increased IRAM consumption. There is another Kconfig option CONFIG_MCPWM_CTRL_FUNC_IN_IRAM that can put commonly used IO control functions into IRAM as well. So, these functions can also be executable when the cache is disabled. The IO control function is as follows: Thread Safety The factory functions like mcpwm_new_timer() are guaranteed to be thread-safe by the driver, which means, you can call it from different RTOS tasks without protection by extra locks. The following function is allowed to run under the ISR context, as the driver uses a critical section to prevent them from being called concurrently in the task and ISR. Other functions that are not related to Resource Allocation and Initialization, are not thread-safe. Thus, you should avoid calling them in different tasks without mutex protection. Kconfig Options CONFIG_MCPWM_ISR_IRAM_SAFE controls whether the default ISR handler can work when the cache is disabled, see IRAM Safe for more information. CONFIG_MCPWM_CTRL_FUNC_IN_IRAM controls where to place the MCPWM control functions (IRAM or flash), see IRAM Safe for more information. CONFIG_MCPWM_ENABLE_DEBUG_LOG is used to enable the debug log output. Enabling this option will increase the firmware binary size. Application Examples Brushed DC motor speed control by PID algorithm: peripherals/mcpwm/mcpwm_bdc_speed_control BLDC motor control with hall sensor feedback: peripherals/mcpwm/mcpwm_bldc_hall_control Ultrasonic sensor (HC-SR04) distance measurement: peripherals/mcpwm/mcpwm_capture_hc_sr04 Servo motor angle control: peripherals/mcpwm/mcpwm_servo_control MCPWM synchronization between timers: peripherals/mcpwm/mcpwm_sync API Reference Header File This header file can be included with: #include "driver/mcpwm_timer.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t mcpwm_new_timer(const mcpwm_timer_config_t *config, mcpwm_timer_handle_t *ret_timer) Create MCPWM timer. - Parameters config -- [in] MCPWM timer configuration ret_timer -- [out] Returned MCPWM timer handle - - Returns ESP_OK: Create MCPWM timer successfully ESP_ERR_INVALID_ARG: Create MCPWM timer failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM timer failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM timer failed because all hardware timers are used up and no more free one ESP_FAIL: Create MCPWM timer failed because of other error - - esp_err_t mcpwm_del_timer(mcpwm_timer_handle_t timer) Delete MCPWM timer. - Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() - Returns ESP_OK: Delete MCPWM timer successfully ESP_ERR_INVALID_ARG: Delete MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Delete MCPWM timer failed because timer is not in init state ESP_FAIL: Delete MCPWM timer failed because of other error - - esp_err_t mcpwm_timer_set_period(mcpwm_timer_handle_t timer, uint32_t period_ticks) Set a new period for MCPWM timer. Note If mcpwm_timer_config_t::update_period_on_emptyand mcpwm_timer_config_t::update_period_on_syncare not set, the new period will take effect immediately. Otherwise, the new period will take effect when timer counts to zero or on sync event. Note You may need to use mcpwm_comparator_set_compare_valueto set a new compare value for MCPWM comparator in order to keep the same PWM duty cycle. - Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer period_ticks -- [in] New period in count ticks - - Returns ESP_OK: Set new period for MCPWM timer successfully ESP_ERR_INVALID_ARG: Set new period for MCPWM timer failed because of invalid argument ESP_FAIL: Set new period for MCPWM timer failed because of other error - - esp_err_t mcpwm_timer_enable(mcpwm_timer_handle_t timer) Enable MCPWM timer. - Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() - Returns ESP_OK: Enable MCPWM timer successfully ESP_ERR_INVALID_ARG: Enable MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Enable MCPWM timer failed because timer is enabled already ESP_FAIL: Enable MCPWM timer failed because of other error - - esp_err_t mcpwm_timer_disable(mcpwm_timer_handle_t timer) Disable MCPWM timer. - Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() - Returns ESP_OK: Disable MCPWM timer successfully ESP_ERR_INVALID_ARG: Disable MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Disable MCPWM timer failed because timer is disabled already ESP_FAIL: Disable MCPWM timer failed because of other error - - esp_err_t mcpwm_timer_start_stop(mcpwm_timer_handle_t timer, mcpwm_timer_start_stop_cmd_t command) Send specific start/stop commands to MCPWM timer. - Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() command -- [in] Supported command list for MCPWM timer - - Returns ESP_OK: Start or stop MCPWM timer successfully ESP_ERR_INVALID_ARG: Start or stop MCPWM timer failed because of invalid argument ESP_ERR_INVALID_STATE: Start or stop MCPWM timer failed because timer is not enabled ESP_FAIL: Start or stop MCPWM timer failed because of other error - - esp_err_t mcpwm_timer_register_event_callbacks(mcpwm_timer_handle_t timer, const mcpwm_timer_event_callbacks_t *cbs, void *user_data) Set event callbacks for MCPWM timer. Note The first call to this function needs to be before the call to mcpwm_timer_enable Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbsstructure to NULL. - Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly - - Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because timer is not in init state ESP_FAIL: Set event callbacks failed because of other error - - esp_err_t mcpwm_timer_set_phase_on_sync(mcpwm_timer_handle_t timer, const mcpwm_timer_sync_phase_config_t *config) Set sync phase for MCPWM timer. - Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() config -- [in] MCPWM timer sync phase configuration - - Returns ESP_OK: Set sync phase for MCPWM timer successfully ESP_ERR_INVALID_ARG: Set sync phase for MCPWM timer failed because of invalid argument ESP_FAIL: Set sync phase for MCPWM timer failed because of other error - Structures - struct mcpwm_timer_event_callbacks_t Group of supported MCPWM timer event callbacks. Note The callbacks are all running under ISR environment Public Members - mcpwm_timer_event_cb_t on_full callback function when MCPWM timer counts to peak value - mcpwm_timer_event_cb_t on_empty callback function when MCPWM timer counts to zero - mcpwm_timer_event_cb_t on_stop callback function when MCPWM timer stops - mcpwm_timer_event_cb_t on_full - struct mcpwm_timer_config_t MCPWM timer configuration. Public Members - int group_id Specify from which group to allocate the MCPWM timer - mcpwm_timer_clock_source_t clk_src MCPWM timer clock source - uint32_t resolution_hz Counter resolution in Hz The step size of each count tick equals to (1 / resolution_hz) seconds - mcpwm_timer_count_mode_t count_mode Count mode - uint32_t period_ticks Number of count ticks within a period - int intr_priority MCPWM timer interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) - uint32_t update_period_on_empty Whether to update period when timer counts to zero - uint32_t update_period_on_sync Whether to update period on sync event - struct mcpwm_timer_config_t::[anonymous] flags Extra configuration flags for timer - int group_id - struct mcpwm_timer_sync_phase_config_t MCPWM Timer sync phase configuration. Public Members - mcpwm_sync_handle_t sync_src The sync event source. Set to NULL will disable the timer being synced by others - uint32_t count_value The count value that should lock to upon sync event - mcpwm_timer_direction_t direction The count direction that should lock to upon sync event - mcpwm_sync_handle_t sync_src Header File This header file can be included with: #include "driver/mcpwm_oper.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t mcpwm_new_operator(const mcpwm_operator_config_t *config, mcpwm_oper_handle_t *ret_oper) Create MCPWM operator. - Parameters config -- [in] MCPWM operator configuration ret_oper -- [out] Returned MCPWM operator handle - - Returns ESP_OK: Create MCPWM operator successfully ESP_ERR_INVALID_ARG: Create MCPWM operator failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM operator failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM operator failed because can't find free resource ESP_FAIL: Create MCPWM operator failed because of other error - - esp_err_t mcpwm_del_operator(mcpwm_oper_handle_t oper) Delete MCPWM operator. - Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() - Returns ESP_OK: Delete MCPWM operator successfully ESP_ERR_INVALID_ARG: Delete MCPWM operator failed because of invalid argument ESP_FAIL: Delete MCPWM operator failed because of other error - - esp_err_t mcpwm_operator_connect_timer(mcpwm_oper_handle_t oper, mcpwm_timer_handle_t timer) Connect MCPWM operator and timer, so that the operator can be driven by the timer. - Parameters oper -- [in] MCPWM operator handle, allocated by mcpwm_new_operator() timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() - - Returns ESP_OK: Connect MCPWM operator and timer successfully ESP_ERR_INVALID_ARG: Connect MCPWM operator and timer failed because of invalid argument ESP_FAIL: Connect MCPWM operator and timer failed because of other error - - esp_err_t mcpwm_operator_set_brake_on_fault(mcpwm_oper_handle_t oper, const mcpwm_brake_config_t *config) Set brake method for MCPWM operator. - Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() config -- [in] MCPWM brake configuration - - Returns ESP_OK: Set trip for operator successfully ESP_ERR_INVALID_ARG: Set trip for operator failed because of invalid argument ESP_FAIL: Set trip for operator failed because of other error - - esp_err_t mcpwm_operator_recover_from_fault(mcpwm_oper_handle_t oper, mcpwm_fault_handle_t fault) Try to make the operator recover from fault. Note To recover from fault or escape from trip, you make sure the fault signal has dissappeared already. Otherwise the recovery can't succeed. - Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() fault -- [in] MCPWM fault handle - - Returns ESP_OK: Recover from fault successfully ESP_ERR_INVALID_ARG: Recover from fault failed because of invalid argument ESP_ERR_INVALID_STATE: Recover from fault failed because the fault source is still active ESP_FAIL: Recover from fault failed because of other error - - esp_err_t mcpwm_operator_register_event_callbacks(mcpwm_oper_handle_t oper, const mcpwm_operator_event_callbacks_t *cbs, void *user_data) Set event callbacks for MCPWM operator. Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbsstructure to NULL. - Parameters oper -- [in] MCPWM operator handle, allocated by mcpwm_new_operator() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly - - Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error - - esp_err_t mcpwm_operator_apply_carrier(mcpwm_oper_handle_t oper, const mcpwm_carrier_config_t *config) Apply carrier feature for MCPWM operator. - Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() config -- [in] MCPWM carrier specific configuration - - Returns ESP_OK: Set carrier for operator successfully ESP_ERR_INVALID_ARG: Set carrier for operator failed because of invalid argument ESP_FAIL: Set carrier for operator failed because of other error - Structures - struct mcpwm_operator_config_t MCPWM operator configuration. Public Members - int group_id Specify from which group to allocate the MCPWM operator - int intr_priority MCPWM operator interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) - uint32_t update_gen_action_on_tez Whether to update generator action when timer counts to zero - uint32_t update_gen_action_on_tep Whether to update generator action when timer counts to peak - uint32_t update_gen_action_on_sync Whether to update generator action on sync event - uint32_t update_dead_time_on_tez Whether to update dead time when timer counts to zero - uint32_t update_dead_time_on_tep Whether to update dead time when timer counts to peak - uint32_t update_dead_time_on_sync Whether to update dead time on sync event - struct mcpwm_operator_config_t::[anonymous] flags Extra configuration flags for operator - int group_id - struct mcpwm_brake_config_t MCPWM brake configuration structure. Public Members - mcpwm_fault_handle_t fault Which fault causes the operator to brake - mcpwm_operator_brake_mode_t brake_mode Brake mode - uint32_t cbc_recover_on_tez Recovery CBC brake state on tez event - uint32_t cbc_recover_on_tep Recovery CBC brake state on tep event - struct mcpwm_brake_config_t::[anonymous] flags Extra flags for brake configuration - mcpwm_fault_handle_t fault - struct mcpwm_operator_event_callbacks_t Group of supported MCPWM operator event callbacks. Note The callbacks are all running under ISR environment Public Members - mcpwm_brake_event_cb_t on_brake_cbc callback function when mcpwm operator brakes in CBC - mcpwm_brake_event_cb_t on_brake_ost callback function when mcpwm operator brakes in OST - mcpwm_brake_event_cb_t on_brake_cbc - struct mcpwm_carrier_config_t MCPWM carrier configuration structure. Public Members - mcpwm_carrier_clock_source_t clk_src MCPWM carrier clock source - uint32_t frequency_hz Carrier frequency in Hz - uint32_t first_pulse_duration_us The duration of the first PWM pulse, in us - float duty_cycle Carrier duty cycle - uint32_t invert_before_modulate Invert the raw signal - uint32_t invert_after_modulate Invert the modulated signal - struct mcpwm_carrier_config_t::[anonymous] flags Extra flags for carrier configuration - mcpwm_carrier_clock_source_t clk_src Header File This header file can be included with: #include "driver/mcpwm_cmpr.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t mcpwm_new_comparator(mcpwm_oper_handle_t oper, const mcpwm_comparator_config_t *config, mcpwm_cmpr_handle_t *ret_cmpr) Create MCPWM comparator. - Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator(), the new comparator will be allocated from this operator config -- [in] MCPWM comparator configuration ret_cmpr -- [out] Returned MCPWM comparator - - Returns ESP_OK: Create MCPWM comparator successfully ESP_ERR_INVALID_ARG: Create MCPWM comparator failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM comparator failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM comparator failed because can't find free resource ESP_FAIL: Create MCPWM comparator failed because of other error - - esp_err_t mcpwm_del_comparator(mcpwm_cmpr_handle_t cmpr) Delete MCPWM comparator. - Parameters cmpr -- [in] MCPWM comparator handle, allocated by mcpwm_new_comparator() - Returns ESP_OK: Delete MCPWM comparator successfully ESP_ERR_INVALID_ARG: Delete MCPWM comparator failed because of invalid argument ESP_FAIL: Delete MCPWM comparator failed because of other error - - esp_err_t mcpwm_comparator_register_event_callbacks(mcpwm_cmpr_handle_t cmpr, const mcpwm_comparator_event_callbacks_t *cbs, void *user_data) Set event callbacks for MCPWM comparator. Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbsstructure to NULL. - Parameters cmpr -- [in] MCPWM comparator handle, allocated by mcpwm_new_comparator() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly - - Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error - - esp_err_t mcpwm_comparator_set_compare_value(mcpwm_cmpr_handle_t cmpr, uint32_t cmp_ticks) Set MCPWM comparator's compare value. - Parameters cmpr -- [in] MCPWM comparator handle, allocated by mcpwm_new_comparator() cmp_ticks -- [in] The new compare value - - Returns ESP_OK: Set MCPWM compare value successfully ESP_ERR_INVALID_ARG: Set MCPWM compare value failed because of invalid argument (e.g. the cmp_ticks is out of range) ESP_ERR_INVALID_STATE: Set MCPWM compare value failed because the operator doesn't have a timer connected ESP_FAIL: Set MCPWM compare value failed because of other error - Structures - struct mcpwm_comparator_config_t MCPWM comparator configuration. Public Members - int intr_priority MCPWM comparator interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) - uint32_t update_cmp_on_tez Whether to update compare value when timer count equals to zero (tez) - uint32_t update_cmp_on_tep Whether to update compare value when timer count equals to peak (tep) - uint32_t update_cmp_on_sync Whether to update compare value on sync event - struct mcpwm_comparator_config_t::[anonymous] flags Extra configuration flags for comparator - int intr_priority - struct mcpwm_comparator_event_callbacks_t Group of supported MCPWM compare event callbacks. Note The callbacks are all running under ISR environment Public Members - mcpwm_compare_event_cb_t on_reach ISR callback function which would be invoked when counter reaches compare value - mcpwm_compare_event_cb_t on_reach Header File This header file can be included with: #include "driver/mcpwm_gen.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t mcpwm_new_generator(mcpwm_oper_handle_t oper, const mcpwm_generator_config_t *config, mcpwm_gen_handle_t *ret_gen) Allocate MCPWM generator from given operator. - Parameters oper -- [in] MCPWM operator, allocated by mcpwm_new_operator() config -- [in] MCPWM generator configuration ret_gen -- [out] Returned MCPWM generator - - Returns ESP_OK: Create MCPWM generator successfully ESP_ERR_INVALID_ARG: Create MCPWM generator failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM generator failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM generator failed because can't find free resource ESP_FAIL: Create MCPWM generator failed because of other error - - esp_err_t mcpwm_del_generator(mcpwm_gen_handle_t gen) Delete MCPWM generator. - Parameters gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() - Returns ESP_OK: Delete MCPWM generator successfully ESP_ERR_INVALID_ARG: Delete MCPWM generator failed because of invalid argument ESP_FAIL: Delete MCPWM generator failed because of other error - - esp_err_t mcpwm_generator_set_force_level(mcpwm_gen_handle_t gen, int level, bool hold_on) Set force level for MCPWM generator. Note The force level will be applied to the generator immediately, regardless any other events that would change the generator's behaviour. Note If the hold_onis true, the force level will retain forever, until user removes the force level by setting the force level to -1. Note If the hold_onis false, the force level can be overridden by the next event action. Note The force level set by this function can be inverted by GPIO matrix or dead-time module. So the level set here doesn't equal to the final output level. - Parameters gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() level -- [in] GPIO level to be applied to MCPWM generator, specially, -1 means to remove the force level hold_on -- [in] Whether the forced PWM level should retain (i.e. will remain unchanged until manually remove the force level) - - Returns ESP_OK: Set force level for MCPWM generator successfully ESP_ERR_INVALID_ARG: Set force level for MCPWM generator failed because of invalid argument ESP_FAIL: Set force level for MCPWM generator failed because of other error - - esp_err_t mcpwm_generator_set_action_on_timer_event(mcpwm_gen_handle_t gen, mcpwm_gen_timer_event_action_t ev_act) Set generator action on MCPWM timer event. - Parameters gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM timer event action, can be constructed by MCPWM_GEN_TIMER_EVENT_ACTIONhelper macro - - Returns ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_ERR_INVALID_STATE: Set generator action failed because of timer is not connected to operator ESP_FAIL: Set generator action failed because of other error - - esp_err_t mcpwm_generator_set_actions_on_timer_event(mcpwm_gen_handle_t gen, mcpwm_gen_timer_event_action_t ev_act, ...) Set generator actions on multiple MCPWM timer events. Note This is an aggregation version of mcpwm_generator_set_action_on_timer_event, which allows user to set multiple actions in one call. - Parameters gen -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM timer event action list, must be terminated by MCPWM_GEN_TIMER_EVENT_ACTION_END() - - Returns ESP_OK: Set generator actions successfully ESP_ERR_INVALID_ARG: Set generator actions failed because of invalid argument ESP_ERR_INVALID_STATE: Set generator actions failed because of timer is not connected to operator ESP_FAIL: Set generator actions failed because of other error - - esp_err_t mcpwm_generator_set_action_on_compare_event(mcpwm_gen_handle_t generator, mcpwm_gen_compare_event_action_t ev_act) Set generator action on MCPWM compare event. - Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM compare event action, can be constructed by MCPWM_GEN_COMPARE_EVENT_ACTIONhelper macro - - Returns ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error - - esp_err_t mcpwm_generator_set_actions_on_compare_event(mcpwm_gen_handle_t generator, mcpwm_gen_compare_event_action_t ev_act, ...) Set generator actions on multiple MCPWM compare events. Note This is an aggregation version of mcpwm_generator_set_action_on_compare_event, which allows user to set multiple actions in one call. - Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM compare event action list, must be terminated by MCPWM_GEN_COMPARE_EVENT_ACTION_END() - - Returns ESP_OK: Set generator actions successfully ESP_ERR_INVALID_ARG: Set generator actions failed because of invalid argument ESP_FAIL: Set generator actions failed because of other error - - esp_err_t mcpwm_generator_set_action_on_brake_event(mcpwm_gen_handle_t generator, mcpwm_gen_brake_event_action_t ev_act) Set generator action on MCPWM brake event. - Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM brake event action, can be constructed by MCPWM_GEN_BRAKE_EVENT_ACTIONhelper macro - - Returns ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error - - esp_err_t mcpwm_generator_set_actions_on_brake_event(mcpwm_gen_handle_t generator, mcpwm_gen_brake_event_action_t ev_act, ...) Set generator actions on multiple MCPWM brake events. Note This is an aggregation version of mcpwm_generator_set_action_on_brake_event, which allows user to set multiple actions in one call. - Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM brake event action list, must be terminated by MCPWM_GEN_BRAKE_EVENT_ACTION_END() - - Returns ESP_OK: Set generator actions successfully ESP_ERR_INVALID_ARG: Set generator actions failed because of invalid argument ESP_FAIL: Set generator actions failed because of other error - - esp_err_t mcpwm_generator_set_action_on_fault_event(mcpwm_gen_handle_t generator, mcpwm_gen_fault_event_action_t ev_act) Set generator action on MCPWM Fault event. - Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM trigger event action, can be constructed by MCPWM_GEN_FAULT_EVENT_ACTIONhelper macro - - Returns ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error - - esp_err_t mcpwm_generator_set_action_on_sync_event(mcpwm_gen_handle_t generator, mcpwm_gen_sync_event_action_t ev_act) Set generator action on MCPWM Sync event. Note The trigger only support one sync action, regardless of the kinds. Should not call this function more than once. - Parameters generator -- [in] MCPWM generator handle, allocated by mcpwm_new_generator() ev_act -- [in] MCPWM trigger event action, can be constructed by MCPWM_GEN_SYNC_EVENT_ACTIONhelper macro - - Returns ESP_OK: Set generator action successfully ESP_ERR_INVALID_ARG: Set generator action failed because of invalid argument ESP_FAIL: Set generator action failed because of other error - - esp_err_t mcpwm_generator_set_dead_time(mcpwm_gen_handle_t in_generator, mcpwm_gen_handle_t out_generator, const mcpwm_dead_time_config_t *config) Set dead time for MCPWM generator. Note Due to a hardware limitation, you can't set rising edge delay for both MCPWM generator 0 and 1 at the same time, otherwise, there will be a conflict inside the dead time module. The same goes for the falling edge setting. But you can set both the rising edge and falling edge delay for the same MCPWM generator. - Parameters in_generator -- [in] MCPWM generator, before adding the dead time out_generator -- [in] MCPWM generator, after adding the dead time config -- [in] MCPWM dead time configuration - - Returns ESP_OK: Set dead time for MCPWM generator successfully ESP_ERR_INVALID_ARG: Set dead time for MCPWM generator failed because of invalid argument ESP_ERR_INVALID_STATE: Set dead time for MCPWM generator failed because of invalid state (e.g. delay module is already in use by other generator) ESP_FAIL: Set dead time for MCPWM generator failed because of other error - Structures - struct mcpwm_generator_config_t MCPWM generator configuration. Public Members - int gen_gpio_num The GPIO number used to output the PWM signal - uint32_t invert_pwm Whether to invert the PWM signal (done by GPIO matrix) - uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well - uint32_t io_od_mode Configure the GPIO as open-drain mode - uint32_t pull_up Whether to pull up internally - uint32_t pull_down Whether to pull down internally - struct mcpwm_generator_config_t::[anonymous] flags Extra configuration flags for generator - int gen_gpio_num - struct mcpwm_gen_timer_event_action_t Generator action on specific timer event. Public Members - mcpwm_timer_direction_t direction Timer direction - mcpwm_timer_event_t event Timer event - mcpwm_generator_action_t action Generator action should perform - mcpwm_timer_direction_t direction - struct mcpwm_gen_compare_event_action_t Generator action on specific comparator event. Public Members - mcpwm_timer_direction_t direction Timer direction - mcpwm_cmpr_handle_t comparator Comparator handle - mcpwm_generator_action_t action Generator action should perform - mcpwm_timer_direction_t direction - struct mcpwm_gen_brake_event_action_t Generator action on specific brake event. Public Members - mcpwm_timer_direction_t direction Timer direction - mcpwm_operator_brake_mode_t brake_mode Brake mode - mcpwm_generator_action_t action Generator action should perform - mcpwm_timer_direction_t direction - struct mcpwm_gen_fault_event_action_t Generator action on specific fault event. Public Members - mcpwm_timer_direction_t direction Timer direction - mcpwm_fault_handle_t fault Which fault as the trigger. Only support GPIO fault - mcpwm_generator_action_t action Generator action should perform - mcpwm_timer_direction_t direction - struct mcpwm_gen_sync_event_action_t Generator action on specific sync event. Public Members - mcpwm_timer_direction_t direction Timer direction - mcpwm_sync_handle_t sync Which sync as the trigger - mcpwm_generator_action_t action Generator action should perform - mcpwm_timer_direction_t direction - struct mcpwm_dead_time_config_t MCPWM dead time configuration structure. Public Members - uint32_t posedge_delay_ticks delay time applied to rising edge, 0 means no rising delay time - uint32_t negedge_delay_ticks delay time applied to falling edge, 0 means no falling delay time - uint32_t invert_output Invert the signal after applied the dead time - struct mcpwm_dead_time_config_t::[anonymous] flags Extra flags for dead time configuration - uint32_t posedge_delay_ticks Macros - MCPWM_GEN_TIMER_EVENT_ACTION(dir, ev, act) Help macros to construct a mcpwm_gen_timer_event_action_t entry. - MCPWM_GEN_TIMER_EVENT_ACTION_END() - MCPWM_GEN_COMPARE_EVENT_ACTION(dir, cmp, act) Help macros to construct a mcpwm_gen_compare_event_action_t entry. - MCPWM_GEN_COMPARE_EVENT_ACTION_END() - MCPWM_GEN_BRAKE_EVENT_ACTION(dir, mode, act) Help macros to construct a mcpwm_gen_brake_event_action_t entry. - MCPWM_GEN_BRAKE_EVENT_ACTION_END() - MCPWM_GEN_FAULT_EVENT_ACTION(dir, flt, act) Help macros to construct a mcpwm_gen_fault_event_action_t entry. - MCPWM_GEN_SYNC_EVENT_ACTION(dir, syn, act) Help macros to construct a mcpwm_gen_sync_event_action_t entry. Header File This header file can be included with: #include "driver/mcpwm_fault.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t mcpwm_new_gpio_fault(const mcpwm_gpio_fault_config_t *config, mcpwm_fault_handle_t *ret_fault) Create MCPWM GPIO fault. - Parameters config -- [in] MCPWM GPIO fault configuration ret_fault -- [out] Returned GPIO fault handle - - Returns ESP_OK: Create MCPWM GPIO fault successfully ESP_ERR_INVALID_ARG: Create MCPWM GPIO fault failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM GPIO fault failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM GPIO fault failed because can't find free resource ESP_FAIL: Create MCPWM GPIO fault failed because of other error - - esp_err_t mcpwm_new_soft_fault(const mcpwm_soft_fault_config_t *config, mcpwm_fault_handle_t *ret_fault) Create MCPWM software fault. - Parameters config -- [in] MCPWM software fault configuration ret_fault -- [out] Returned software fault handle - - Returns ESP_OK: Create MCPWM software fault successfully ESP_ERR_INVALID_ARG: Create MCPWM software fault failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM software fault failed because out of memory ESP_FAIL: Create MCPWM software fault failed because of other error - - esp_err_t mcpwm_del_fault(mcpwm_fault_handle_t fault) Delete MCPWM fault. - Parameters fault -- [in] MCPWM fault handle allocated by mcpwm_new_gpio_fault()or mcpwm_new_soft_fault() - Returns ESP_OK: Delete MCPWM fault successfully ESP_ERR_INVALID_ARG: Delete MCPWM fault failed because of invalid argument ESP_FAIL: Delete MCPWM fault failed because of other error - - esp_err_t mcpwm_soft_fault_activate(mcpwm_fault_handle_t fault) Activate the software fault, trigger the fault event for once. - Parameters fault -- [in] MCPWM soft fault, allocated by mcpwm_new_soft_fault() - Returns ESP_OK: Trigger MCPWM software fault event successfully ESP_ERR_INVALID_ARG: Trigger MCPWM software fault event failed because of invalid argument ESP_FAIL: Trigger MCPWM software fault event failed because of other error - - esp_err_t mcpwm_fault_register_event_callbacks(mcpwm_fault_handle_t fault, const mcpwm_fault_event_callbacks_t *cbs, void *user_data) Set event callbacks for MCPWM fault. Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbsstructure to NULL. - Parameters fault -- [in] MCPWM GPIO fault handle, allocated by mcpwm_new_gpio_fault() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly - - Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error - Structures - struct mcpwm_gpio_fault_config_t MCPWM GPIO fault configuration structure. Public Members - int group_id In which MCPWM group that the GPIO fault belongs to - int intr_priority MCPWM GPIO fault interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) - int gpio_num GPIO used by the fault signal - uint32_t active_level On which level the fault signal is treated as active - uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well - uint32_t pull_up Whether to pull up internally - uint32_t pull_down Whether to pull down internally - struct mcpwm_gpio_fault_config_t::[anonymous] flags Extra configuration flags for GPIO fault - int group_id - struct mcpwm_soft_fault_config_t MCPWM software fault configuration structure. - struct mcpwm_fault_event_callbacks_t Group of supported MCPWM fault event callbacks. Note The callbacks are all running under ISR environment Public Members - mcpwm_fault_event_cb_t on_fault_enter ISR callback function that would be invoked when fault signal becomes active - mcpwm_fault_event_cb_t on_fault_exit ISR callback function that would be invoked when fault signal becomes inactive - mcpwm_fault_event_cb_t on_fault_enter Header File This header file can be included with: #include "driver/mcpwm_sync.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t mcpwm_new_timer_sync_src(mcpwm_timer_handle_t timer, const mcpwm_timer_sync_src_config_t *config, mcpwm_sync_handle_t *ret_sync) Create MCPWM timer sync source. - Parameters timer -- [in] MCPWM timer handle, allocated by mcpwm_new_timer() config -- [in] MCPWM timer sync source configuration ret_sync -- [out] Returned MCPWM sync handle - - Returns ESP_OK: Create MCPWM timer sync source successfully ESP_ERR_INVALID_ARG: Create MCPWM timer sync source failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM timer sync source failed because out of memory ESP_ERR_INVALID_STATE: Create MCPWM timer sync source failed because the timer has created a sync source before ESP_FAIL: Create MCPWM timer sync source failed because of other error - - esp_err_t mcpwm_new_gpio_sync_src(const mcpwm_gpio_sync_src_config_t *config, mcpwm_sync_handle_t *ret_sync) Create MCPWM GPIO sync source. - Parameters config -- [in] MCPWM GPIO sync source configuration ret_sync -- [out] Returned MCPWM GPIO sync handle - - Returns ESP_OK: Create MCPWM GPIO sync source successfully ESP_ERR_INVALID_ARG: Create MCPWM GPIO sync source failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM GPIO sync source failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM GPIO sync source failed because can't find free resource ESP_FAIL: Create MCPWM GPIO sync source failed because of other error - - esp_err_t mcpwm_new_soft_sync_src(const mcpwm_soft_sync_config_t *config, mcpwm_sync_handle_t *ret_sync) Create MCPWM software sync source. - Parameters config -- [in] MCPWM software sync source configuration ret_sync -- [out] Returned software sync handle - - Returns ESP_OK: Create MCPWM software sync successfully ESP_ERR_INVALID_ARG: Create MCPWM software sync failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM software sync failed because out of memory ESP_FAIL: Create MCPWM software sync failed because of other error - - esp_err_t mcpwm_del_sync_src(mcpwm_sync_handle_t sync) Delete MCPWM sync source. - Parameters sync -- [in] MCPWM sync handle, allocated by mcpwm_new_timer_sync_src()or mcpwm_new_gpio_sync_src()or mcpwm_new_soft_sync_src() - Returns ESP_OK: Delete MCPWM sync source successfully ESP_ERR_INVALID_ARG: Delete MCPWM sync source failed because of invalid argument ESP_FAIL: Delete MCPWM sync source failed because of other error - - esp_err_t mcpwm_soft_sync_activate(mcpwm_sync_handle_t sync) Activate the software sync, trigger the sync event for once. - Parameters sync -- [in] MCPWM soft sync handle, allocated by mcpwm_new_soft_sync_src() - Returns ESP_OK: Trigger MCPWM software sync event successfully ESP_ERR_INVALID_ARG: Trigger MCPWM software sync event failed because of invalid argument ESP_FAIL: Trigger MCPWM software sync event failed because of other error - Structures - struct mcpwm_timer_sync_src_config_t MCPWM timer sync source configuration. Public Members - mcpwm_timer_event_t timer_event Timer event, upon which MCPWM timer will generate the sync signal - uint32_t propagate_input_sync The input sync signal would be routed to its sync output - struct mcpwm_timer_sync_src_config_t::[anonymous] flags Extra configuration flags for timer sync source - mcpwm_timer_event_t timer_event - struct mcpwm_gpio_sync_src_config_t MCPWM GPIO sync source configuration. Public Members - int group_id MCPWM group ID - int gpio_num GPIO used by sync source - uint32_t active_neg Whether the sync signal is active on negedge, by default, the sync signal's posedge is treated as active - uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well - uint32_t pull_up Whether to pull up internally - uint32_t pull_down Whether to pull down internally - struct mcpwm_gpio_sync_src_config_t::[anonymous] flags Extra configuration flags for GPIO sync source - int group_id - struct mcpwm_soft_sync_config_t MCPWM software sync configuration structure. Header File This header file can be included with: #include "driver/mcpwm_cap.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t mcpwm_new_capture_timer(const mcpwm_capture_timer_config_t *config, mcpwm_cap_timer_handle_t *ret_cap_timer) Create MCPWM capture timer. - Parameters config -- [in] MCPWM capture timer configuration ret_cap_timer -- [out] Returned MCPWM capture timer handle - - Returns ESP_OK: Create MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Create MCPWM capture timer failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM capture timer failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM capture timer failed because can't find free resource ESP_FAIL: Create MCPWM capture timer failed because of other error - - esp_err_t mcpwm_del_capture_timer(mcpwm_cap_timer_handle_t cap_timer) Delete MCPWM capture timer. - Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() - Returns ESP_OK: Delete MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Delete MCPWM capture timer failed because of invalid argument ESP_FAIL: Delete MCPWM capture timer failed because of other error - - esp_err_t mcpwm_capture_timer_enable(mcpwm_cap_timer_handle_t cap_timer) Enable MCPWM capture timer. - Parameters cap_timer -- [in] MCPWM capture timer handle, allocated by mcpwm_new_capture_timer() - Returns ESP_OK: Enable MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Enable MCPWM capture timer failed because of invalid argument ESP_ERR_INVALID_STATE: Enable MCPWM capture timer failed because timer is enabled already ESP_FAIL: Enable MCPWM capture timer failed because of other error - - esp_err_t mcpwm_capture_timer_disable(mcpwm_cap_timer_handle_t cap_timer) Disable MCPWM capture timer. - Parameters cap_timer -- [in] MCPWM capture timer handle, allocated by mcpwm_new_capture_timer() - Returns ESP_OK: Disable MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Disable MCPWM capture timer failed because of invalid argument ESP_ERR_INVALID_STATE: Disable MCPWM capture timer failed because timer is disabled already ESP_FAIL: Disable MCPWM capture timer failed because of other error - - esp_err_t mcpwm_capture_timer_start(mcpwm_cap_timer_handle_t cap_timer) Start MCPWM capture timer. - Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() - Returns ESP_OK: Start MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Start MCPWM capture timer failed because of invalid argument ESP_FAIL: Start MCPWM capture timer failed because of other error - - esp_err_t mcpwm_capture_timer_stop(mcpwm_cap_timer_handle_t cap_timer) Start MCPWM capture timer. - Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() - Returns ESP_OK: Stop MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Stop MCPWM capture timer failed because of invalid argument ESP_FAIL: Stop MCPWM capture timer failed because of other error - - esp_err_t mcpwm_capture_timer_get_resolution(mcpwm_cap_timer_handle_t cap_timer, uint32_t *out_resolution) Get MCPWM capture timer resolution, in Hz. - Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() out_resolution -- [out] Returned capture timer resolution, in Hz - - Returns ESP_OK: Get capture timer resolution successfully ESP_ERR_INVALID_ARG: Get capture timer resolution failed because of invalid argument ESP_FAIL: Get capture timer resolution failed because of other error - - esp_err_t mcpwm_capture_timer_set_phase_on_sync(mcpwm_cap_timer_handle_t cap_timer, const mcpwm_capture_timer_sync_phase_config_t *config) Set sync phase for MCPWM capture timer. - Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer() config -- [in] MCPWM capture timer sync phase configuration - - Returns ESP_OK: Set sync phase for MCPWM capture timer successfully ESP_ERR_INVALID_ARG: Set sync phase for MCPWM capture timer failed because of invalid argument ESP_FAIL: Set sync phase for MCPWM capture timer failed because of other error - - esp_err_t mcpwm_new_capture_channel(mcpwm_cap_timer_handle_t cap_timer, const mcpwm_capture_channel_config_t *config, mcpwm_cap_channel_handle_t *ret_cap_channel) Create MCPWM capture channel. Note The created capture channel won't be enabled until calling mcpwm_capture_channel_enable - Parameters cap_timer -- [in] MCPWM capture timer, allocated by mcpwm_new_capture_timer(), will be connected to the new capture channel config -- [in] MCPWM capture channel configuration ret_cap_channel -- [out] Returned MCPWM capture channel - - Returns ESP_OK: Create MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Create MCPWM capture channel failed because of invalid argument ESP_ERR_NO_MEM: Create MCPWM capture channel failed because out of memory ESP_ERR_NOT_FOUND: Create MCPWM capture channel failed because can't find free resource ESP_FAIL: Create MCPWM capture channel failed because of other error - - esp_err_t mcpwm_del_capture_channel(mcpwm_cap_channel_handle_t cap_channel) Delete MCPWM capture channel. - Parameters cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() - Returns ESP_OK: Delete MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Delete MCPWM capture channel failed because of invalid argument ESP_FAIL: Delete MCPWM capture channel failed because of other error - - esp_err_t mcpwm_capture_channel_enable(mcpwm_cap_channel_handle_t cap_channel) Enable MCPWM capture channel. Note This function will transit the channel state from init to enable. Note This function will enable the interrupt service, if it's lazy installed in mcpwm_capture_channel_register_event_callbacks(). - Parameters cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() - Returns ESP_OK: Enable MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Enable MCPWM capture channel failed because of invalid argument ESP_ERR_INVALID_STATE: Enable MCPWM capture channel failed because the channel is already enabled ESP_FAIL: Enable MCPWM capture channel failed because of other error - - esp_err_t mcpwm_capture_channel_disable(mcpwm_cap_channel_handle_t cap_channel) Disable MCPWM capture channel. - Parameters cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() - Returns ESP_OK: Disable MCPWM capture channel successfully ESP_ERR_INVALID_ARG: Disable MCPWM capture channel failed because of invalid argument ESP_ERR_INVALID_STATE: Disable MCPWM capture channel failed because the channel is not enabled yet ESP_FAIL: Disable MCPWM capture channel failed because of other error - - esp_err_t mcpwm_capture_channel_register_event_callbacks(mcpwm_cap_channel_handle_t cap_channel, const mcpwm_capture_event_callbacks_t *cbs, void *user_data) Set event callbacks for MCPWM capture channel. Note The first call to this function needs to be before the call to mcpwm_capture_channel_enable Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbsstructure to NULL. - Parameters cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly - - Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because the channel is not in init state ESP_FAIL: Set event callbacks failed because of other error - - esp_err_t mcpwm_capture_channel_trigger_soft_catch(mcpwm_cap_channel_handle_t cap_channel) Trigger a catch by software. - Parameters cap_channel -- [in] MCPWM capture channel handle, allocated by mcpwm_new_capture_channel() - Returns ESP_OK: Trigger software catch successfully ESP_ERR_INVALID_ARG: Trigger software catch failed because of invalid argument ESP_ERR_INVALID_STATE: Trigger software catch failed because the channel is not enabled yet ESP_FAIL: Trigger software catch failed because of other error - Structures - struct mcpwm_capture_timer_config_t MCPWM capture timer configuration structure. Public Members - int group_id Specify from which group to allocate the capture timer - mcpwm_capture_clock_source_t clk_src MCPWM capture timer clock source - uint32_t resolution_hz Resolution of capture timer - int group_id - struct mcpwm_capture_timer_sync_phase_config_t MCPWM Capture timer sync phase configuration. Public Members - mcpwm_sync_handle_t sync_src The sync event source - uint32_t count_value The count value that should lock to upon sync event - mcpwm_timer_direction_t direction The count direction that should lock to upon sync event - mcpwm_sync_handle_t sync_src - struct mcpwm_capture_channel_config_t MCPWM capture channel configuration structure. Public Members - int gpio_num GPIO used capturing input signal - int intr_priority MCPWM capture interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) - uint32_t prescale Prescale of input signal, effective frequency = cap_input_clk/prescale - uint32_t pos_edge Whether to capture on positive edge - uint32_t neg_edge Whether to capture on negative edge - uint32_t pull_up Whether to pull up internally - uint32_t pull_down Whether to pull down internally - uint32_t invert_cap_signal Invert the input capture signal - uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well - uint32_t keep_io_conf_at_exit For debug/test, whether to keep the GPIO configuration when capture channel is deleted. By default, driver will reset the GPIO pin at exit. - struct mcpwm_capture_channel_config_t::[anonymous] flags Extra configuration flags for capture channel - int gpio_num - struct mcpwm_capture_event_callbacks_t Group of supported MCPWM capture event callbacks. Note The callbacks are all running under ISR environment Public Members - mcpwm_capture_event_cb_t on_cap Callback function that would be invoked when capture event occurred - mcpwm_capture_event_cb_t on_cap Header File This header file can be included with: #include "driver/mcpwm_etm.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t mcpwm_comparator_new_etm_event(mcpwm_cmpr_handle_t cmpr, const mcpwm_cmpr_etm_event_config_t *config, esp_etm_event_handle_t *out_event) Get the ETM event for MCPWM comparator. Note The created ETM event object can be deleted later by calling esp_etm_del_event - Parameters cmpr -- [in] MCPWM comparator, allocated by mcpwm_new_comparator()or mcpwm_new_event_comparator() config -- [in] MCPWM ETM comparator event configuration out_event -- [out] Returned ETM event handle - - Returns ESP_OK: Get ETM event successfully ESP_ERR_INVALID_ARG: Get ETM event failed because of invalid argument ESP_FAIL: Get ETM event failed because of other error - Structures - struct mcpwm_cmpr_etm_event_config_t MCPWM event comparator ETM event configuration. Public Members - mcpwm_comparator_etm_event_type_t event_type MCPWM comparator ETM event type - mcpwm_comparator_etm_event_type_t event_type Header File This header file can be included with: #include "driver/mcpwm_types.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Structures - struct mcpwm_timer_event_data_t MCPWM timer event data. Public Members - uint32_t count_value MCPWM timer count value - mcpwm_timer_direction_t direction MCPWM timer count direction - uint32_t count_value - struct mcpwm_brake_event_data_t MCPWM brake event data. - struct mcpwm_fault_event_data_t MCPWM fault event data. - struct mcpwm_compare_event_data_t MCPWM compare event data. Public Members - uint32_t compare_ticks Compare value - mcpwm_timer_direction_t direction Count direction - uint32_t compare_ticks - struct mcpwm_capture_event_data_t MCPWM capture event data. Public Members - uint32_t cap_value Captured value - mcpwm_capture_edge_t cap_edge Capture edge - uint32_t cap_value Type Definitions - typedef struct mcpwm_timer_t *mcpwm_timer_handle_t Type of MCPWM timer handle. - typedef struct mcpwm_oper_t *mcpwm_oper_handle_t Type of MCPWM operator handle. - typedef struct mcpwm_cmpr_t *mcpwm_cmpr_handle_t Type of MCPWM comparator handle. - typedef struct mcpwm_gen_t *mcpwm_gen_handle_t Type of MCPWM generator handle. - typedef struct mcpwm_fault_t *mcpwm_fault_handle_t Type of MCPWM fault handle. - typedef struct mcpwm_sync_t *mcpwm_sync_handle_t Type of MCPWM sync handle. - typedef struct mcpwm_cap_timer_t *mcpwm_cap_timer_handle_t Type of MCPWM capture timer handle. - typedef struct mcpwm_cap_channel_t *mcpwm_cap_channel_handle_t Type of MCPWM capture channel handle. - typedef bool (*mcpwm_timer_event_cb_t)(mcpwm_timer_handle_t timer, const mcpwm_timer_event_data_t *edata, void *user_ctx) MCPWM timer event callback function. - Param timer [in] MCPWM timer handle - Param edata [in] MCPWM timer event data, fed by driver - Param user_ctx [in] User data, set in mcpwm_timer_register_event_callbacks() - Return Whether a high priority task has been waken up by this function - typedef bool (*mcpwm_brake_event_cb_t)(mcpwm_oper_handle_t oper, const mcpwm_brake_event_data_t *edata, void *user_ctx) MCPWM operator brake event callback function. - Param oper [in] MCPWM operator handle - Param edata [in] MCPWM brake event data, fed by driver - Param user_ctx [in] User data, set in mcpwm_operator_register_event_callbacks() - Return Whether a high priority task has been waken up by this function - typedef bool (*mcpwm_fault_event_cb_t)(mcpwm_fault_handle_t fault, const mcpwm_fault_event_data_t *edata, void *user_ctx) MCPWM fault event callback function. - Param fault MCPWM fault handle - Param edata MCPWM fault event data, fed by driver - Param user_ctx User data, set in mcpwm_fault_register_event_callbacks() - Return whether a task switch is needed after the callback returns - typedef bool (*mcpwm_compare_event_cb_t)(mcpwm_cmpr_handle_t comparator, const mcpwm_compare_event_data_t *edata, void *user_ctx) MCPWM comparator event callback function. - Param comparator MCPWM comparator handle - Param edata MCPWM comparator event data, fed by driver - Param user_ctx User data, set in mcpwm_comparator_register_event_callbacks() - Return Whether a high priority task has been waken up by this function - typedef bool (*mcpwm_capture_event_cb_t)(mcpwm_cap_channel_handle_t cap_channel, const mcpwm_capture_event_data_t *edata, void *user_ctx) MCPWM capture event callback function. - Param cap_channel MCPWM capture channel handle - Param edata MCPWM capture event data, fed by driver - Param user_ctx User data, set in mcpwm_capture_channel_register_event_callbacks() - Return Whether a high priority task has been waken up by this function Header File This header file can be included with: #include "hal/mcpwm_types.h" Type Definitions - typedef soc_periph_mcpwm_timer_clk_src_t mcpwm_timer_clock_source_t MCPWM timer clock source. - typedef soc_periph_mcpwm_capture_clk_src_t mcpwm_capture_clock_source_t MCPWM capture clock source. - typedef soc_periph_mcpwm_carrier_clk_src_t mcpwm_carrier_clock_source_t MCPWM carrier clock source. Enumerations - enum mcpwm_timer_direction_t MCPWM timer count direction. Values: - enumerator MCPWM_TIMER_DIRECTION_UP Counting direction: Increase - enumerator MCPWM_TIMER_DIRECTION_DOWN Counting direction: Decrease - enumerator MCPWM_TIMER_DIRECTION_UP - enum mcpwm_timer_event_t MCPWM timer events. Values: - enumerator MCPWM_TIMER_EVENT_EMPTY MCPWM timer counts to zero (i.e. counter is empty) - enumerator MCPWM_TIMER_EVENT_FULL MCPWM timer counts to peak (i.e. counter is full) - enumerator MCPWM_TIMER_EVENT_INVALID MCPWM timer invalid event - enumerator MCPWM_TIMER_EVENT_EMPTY - enum mcpwm_timer_count_mode_t MCPWM timer count modes. Values: - enumerator MCPWM_TIMER_COUNT_MODE_PAUSE MCPWM timer paused - enumerator MCPWM_TIMER_COUNT_MODE_UP MCPWM timer counting up - enumerator MCPWM_TIMER_COUNT_MODE_DOWN MCPWM timer counting down - enumerator MCPWM_TIMER_COUNT_MODE_UP_DOWN MCPWM timer counting up and down - enumerator MCPWM_TIMER_COUNT_MODE_PAUSE - enum mcpwm_timer_start_stop_cmd_t MCPWM timer commands, specify the way to start or stop the timer. Values: - enumerator MCPWM_TIMER_STOP_EMPTY MCPWM timer stops when next count reaches zero - enumerator MCPWM_TIMER_STOP_FULL MCPWM timer stops when next count reaches peak - enumerator MCPWM_TIMER_START_NO_STOP MCPWM timer starts couting, and don't stop until received stop command - enumerator MCPWM_TIMER_START_STOP_EMPTY MCPWM timer starts counting and stops when next count reaches zero - enumerator MCPWM_TIMER_START_STOP_FULL MCPWM timer starts counting and stops when next count reaches peak - enumerator MCPWM_TIMER_STOP_EMPTY - enum mcpwm_generator_action_t MCPWM generator actions. Values: - enumerator MCPWM_GEN_ACTION_KEEP Generator action: Keep the same level - enumerator MCPWM_GEN_ACTION_LOW Generator action: Force to low level - enumerator MCPWM_GEN_ACTION_HIGH Generator action: Force to high level - enumerator MCPWM_GEN_ACTION_TOGGLE Generator action: Toggle level - enumerator MCPWM_GEN_ACTION_KEEP - enum mcpwm_operator_brake_mode_t MCPWM operator brake mode. Values: - enumerator MCPWM_OPER_BRAKE_MODE_CBC Brake mode: CBC (cycle by cycle) - enumerator MCPWM_OPER_BRAKE_MODE_OST Brake mode: OST (one shot) - enumerator MCPWM_OPER_BRAKE_MODE_INVALID MCPWM operator invalid brake mode - enumerator MCPWM_OPER_BRAKE_MODE_CBC - enum mcpwm_capture_edge_t MCPWM capture edge. Values: - enumerator MCPWM_CAP_EDGE_POS Capture on the positive edge - enumerator MCPWM_CAP_EDGE_NEG Capture on the negative edge - enumerator MCPWM_CAP_EDGE_POS - enum mcpwm_comparator_etm_event_type_t MCPWM comparator specific events that supported by the ETM module. Values: - enumerator MCPWM_CMPR_ETM_EVENT_EQUAL The count value equals the value of comparator - enumerator MCPWM_CMPR_ETM_EVENT_MAX Maximum number of comparator events - enumerator MCPWM_CMPR_ETM_EVENT_EQUAL - 1(1,2,3,4,5,6,7,8,9) Different ESP chip series might have a different number of MCPWM resources (e.g., groups, timers, comparators, operators, generators, triggers and so on). Please refer to the [TRM] for details. The driver does not forbid you from applying for more MCPWM resources, but it returns an error when there are no hardware resources available. Please always check the return value when doing Resource Allocation and Initialization. - 2 The callback function and the sub-functions invoked by itself should also be placed in IRAM. You need to take care of this by yourself.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/mcpwm.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Pulse Counter (PCNT)
null
espressif.com
2016-01-01
2c4e3c91246e9be9
null
null
Pulse Counter (PCNT) Introduction The PCNT (Pulse Counter) module is designed to count the number of rising and/or falling edges of input signals. The ESP32 contains multiple pulse counter units in the module. 1 Each unit is in effect an independent counter with multiple channels, where each channel can increment/decrement the counter on a rising/falling edge. Furthermore, each channel can be configured separately. PCNT channels can react to signals of edge type and level type, however for simple applications, detecting the edge signal is usually sufficient. PCNT channels can be configured react to both pulse edges (i.e., rising and falling edge), and can be configured to increase, decrease or do nothing to the unit's counter on each edge. The level signal is the so-called control signal, which is used to control the counting mode of the edge signals that are attached to the same channel. By combining the usage of both edge and level signals, a PCNT unit can act as a quadrature decoder. Besides that, PCNT unit is equipped with a separate glitch filter, which is helpful to remove noise from the signal. Typically, a PCNT module can be used in scenarios like: Calculate periodic signal's frequency by counting the pulse numbers within a time slice Decode quadrature signals into speed and direction Functional Overview Description of the PCNT functionality is divided into the following sections: Resource Allocation - covers how to allocate PCNT units and channels with properly set of configurations. It also covers how to recycle the resources when they finished working. Set Up Channel Actions - covers how to configure the PCNT channel to behave on different signal edges and levels. Watch Points - describes how to configure PCNT watch points (i.e., tell PCNT unit to trigger an event when the count reaches a certain value). Register Event Callbacks - describes how to hook your specific code to the watch point event callback function. Set Glitch Filter - describes how to enable and set the timing parameters for the internal glitch filter. Enable and Disable Unit - describes how to enable and disable the PCNT unit. Unit IO Control - describes IO control functions of PCNT unit, like enable glitch filter, start and stop unit, get and clear count value. Power Management - describes what functionality will prevent the chip from going into low power mode. IRAM Safe - describes tips on how to make the PCNT interrupt and IO control functions work better along with a disabled cache. Thread Safety - lists which APIs are guaranteed to be thread safe by the driver. Kconfig Options - lists the supported Kconfig options that can be used to make a different effect on driver behavior. Resource Allocation The PCNT unit and channel are represented by pcnt_unit_handle_t and pcnt_channel_handle_t respectively. All available units and channels are maintained by the driver in a resource pool, so you do not need to know the exact underlying instance ID. Install PCNT Unit To install a PCNT unit, there is a configuration structure that needs to be given in advance: pcnt_unit_config_t : pcnt_unit_config_t::low_limit and pcnt_unit_config_t::high_limit specify the range for the internal hardware counter. The counter will reset to zero automatically when it crosses either the high or low limit. pcnt_unit_config_t::accum_count sets whether to create an internal accumulator for the counter. This is helpful when you want to extend the counter's width, which by default is 16 bit at most, defined in the hardware. See also Compensate Overflow Loss for how to use this feature to compensate the overflow loss. pcnt_unit_config_t::intr_priority sets the priority of the interrupt. If it is set to 0 , the driver will allocate an interrupt with a default priority. Otherwise, the driver will use the given priority. Note Since all PCNT units share the same interrupt source, when installing multiple PCNT units make sure that the interrupt priority pcnt_unit_config_t::intr_priority is the same for each unit. Unit allocation and initialization is done by calling a function pcnt_new_unit() with pcnt_unit_config_t as an input parameter. The function will return a PCNT unit handle only when it runs correctly. Specifically, when there are no more free PCNT units in the pool (i.e., unit resources have been used up), then this function will return ESP_ERR_NOT_FOUND error. The total number of available PCNT units is recorded by SOC_PCNT_UNITS_PER_GROUP for reference. If a previously created PCNT unit is no longer needed, it is recommended to recycle the resource by calling pcnt_del_unit() . Which in return allows the underlying unit hardware to be used for other purposes. Before deleting a PCNT unit, one should ensure the following prerequisites: The unit is in the init state, in other words, the unit is either disabled by pcnt_unit_disable() or not enabled yet. The attached PCNT channels are all removed by pcnt_del_channel() . #define EXAMPLE_PCNT_HIGH_LIMIT 100 #define EXAMPLE_PCNT_LOW_LIMIT -100 pcnt_unit_config_t unit_config = { .high_limit = EXAMPLE_PCNT_HIGH_LIMIT, .low_limit = EXAMPLE_PCNT_LOW_LIMIT, }; pcnt_unit_handle_t pcnt_unit = NULL; ESP_ERROR_CHECK(pcnt_new_unit(&unit_config, &pcnt_unit)); Install PCNT Channel To install a PCNT channel, you must initialize a pcnt_chan_config_t structure in advance, and then call pcnt_new_channel() . The configuration fields of the pcnt_chan_config_t structure are described below: pcnt_chan_config_t::edge_gpio_num and pcnt_chan_config_t::level_gpio_num specify the GPIO numbers used by edge type signal and level type signal. Please note, either of them can be assigned to -1 if it is not actually used, and thus it will become a virtual IO. For some simple pulse counting applications where one of the level/edge signals is fixed (i.e., never changes), you can reclaim a GPIO by setting the signal as a virtual IO on channel allocation. Setting the level/edge signal as a virtual IO causes that signal to be internally routed to a fixed High/Low logic level, thus allowing you to save a GPIO for other purposes. pcnt_chan_config_t::virt_edge_io_level and pcnt_chan_config_t::virt_level_io_level specify the virtual IO level for edge and level input signal, to ensure a deterministic state for such control signal. Please note, they are only valid when either pcnt_chan_config_t::edge_gpio_num or pcnt_chan_config_t::level_gpio_num is assigned to -1 . pcnt_chan_config_t::invert_edge_input and pcnt_chan_config_t::invert_level_input are used to decide whether to invert the input signals before they going into PCNT hardware. The invert is done by GPIO matrix instead of PCNT hardware. pcnt_chan_config_t::io_loop_back is for debug only, which enables both the GPIO's input and output paths. This can help to simulate the pulse signals by function gpio_set_level() on the same GPIO. Channel allocating and initialization is done by calling a function pcnt_new_channel() with the above pcnt_chan_config_t as an input parameter plus a PCNT unit handle returned from pcnt_new_unit() . This function will return a PCNT channel handle if it runs correctly. Specifically, when there are no more free PCNT channel within the unit (i.e., channel resources have been used up), then this function will return ESP_ERR_NOT_FOUND error. The total number of available PCNT channels within the unit is recorded by SOC_PCNT_CHANNELS_PER_UNIT for reference. Note that, when install a PCNT channel for a specific unit, one should ensure the unit is in the init state, otherwise this function will return ESP_ERR_INVALID_STATE error. If a previously created PCNT channel is no longer needed, it is recommended to recycle the resources by calling pcnt_del_channel() . Which in return allows the underlying channel hardware to be used for other purposes. #define EXAMPLE_CHAN_GPIO_A 0 #define EXAMPLE_CHAN_GPIO_B 2 pcnt_chan_config_t chan_config = { .edge_gpio_num = EXAMPLE_CHAN_GPIO_A, .level_gpio_num = EXAMPLE_CHAN_GPIO_B, }; pcnt_channel_handle_t pcnt_chan = NULL; ESP_ERROR_CHECK(pcnt_new_channel(pcnt_unit, &chan_config, &pcnt_chan)); Set Up Channel Actions The PCNT will increase/decrease/hold its internal count value when the input pulse signal toggles. You can set different actions for edge signal and/or level signal. pcnt_channel_set_edge_action() function is to set specific actions for rising and falling edge of the signal attached to the pcnt_chan_config_t::edge_gpio_num . Supported actions are listed in pcnt_channel_edge_action_t . pcnt_channel_set_level_action() function is to set specific actions for high and low level of the signal attached to the pcnt_chan_config_t::level_gpio_num . Supported actions are listed in pcnt_channel_level_action_t . This function is not mandatory if the pcnt_chan_config_t::level_gpio_num is set to -1 when allocating PCNT channel by pcnt_new_channel() . // decrease the counter on rising edge, increase the counter on falling edge ESP_ERROR_CHECK(pcnt_channel_set_edge_action(pcnt_chan, PCNT_CHANNEL_EDGE_ACTION_DECREASE, PCNT_CHANNEL_EDGE_ACTION_INCREASE)); // keep the counting mode when the control signal is high level, and reverse the counting mode when the control signal is low level ESP_ERROR_CHECK(pcnt_channel_set_level_action(pcnt_chan, PCNT_CHANNEL_LEVEL_ACTION_KEEP, PCNT_CHANNEL_LEVEL_ACTION_INVERSE)); Watch Points Each PCNT unit can be configured to watch several different values that you are interested in. The value to be watched is also called Watch Point. The watch point itself can not exceed the range set in pcnt_unit_config_t by pcnt_unit_config_t::low_limit and pcnt_unit_config_t::high_limit . When the counter reaches either watch point, a watch event will be triggered and notify you by interrupt if any watch event callback has ever registered in pcnt_unit_register_event_callbacks() . See Register Event Callbacks for how to register event callbacks. The watch point can be added and removed by pcnt_unit_add_watch_point() and pcnt_unit_remove_watch_point() . The commonly-used watch points are: zero cross, maximum/minimum count and other threshold values. The number of available watch point is limited, pcnt_unit_add_watch_point() will return error ESP_ERR_NOT_FOUND if it can not find any free hardware resource to save the watch point. You can not add the same watch point for multiple times, otherwise it will return error ESP_ERR_INVALID_STATE . It is recommended to remove the unused watch point by pcnt_unit_remove_watch_point() to recycle the watch point resources. // add zero across watch point ESP_ERROR_CHECK(pcnt_unit_add_watch_point(pcnt_unit, 0)); // add high limit watch point ESP_ERROR_CHECK(pcnt_unit_add_watch_point(pcnt_unit, EXAMPLE_PCNT_HIGH_LIMIT)); Note Due to the hardware limitation, after adding a watch point, you should call pcnt_unit_clear_count() to make it take effect. Register Event Callbacks When PCNT unit reaches any enabled watch point, specific event will be generated and notify the CPU by interrupt. If you have some function that want to get executed when event happens, you should hook your function to the interrupt service routine by calling pcnt_unit_register_event_callbacks() . All supported event callbacks are listed in the pcnt_event_callbacks_t : pcnt_event_callbacks_t::on_reach sets a callback function for watch point event. As this function is called within the ISR context, you must ensure that the function does not attempt to block (e.g., by making sure that only FreeRTOS APIs with ISR suffix are called from within the function). The function prototype is declared in pcnt_watch_cb_t . You can save their own context to pcnt_unit_register_event_callbacks() as well, via the parameter user_ctx . This user data will be directly passed to the callback functions. In the callback function, the driver will fill in the event data of specific event. For example, the watch point event data is declared as pcnt_watch_event_data_t : pcnt_watch_event_data_t::watch_point_value saves the watch point value that triggers the event. pcnt_watch_event_data_t::zero_cross_mode saves how the PCNT unit crosses the zero point in the latest time. The possible zero cross modes are listed in the pcnt_unit_zero_cross_mode_t . Usually different zero cross mode means different counting direction and counting step size. Registering callback function results in lazy installation of interrupt service, thus this function should only be called before the unit is enabled by pcnt_unit_enable() . Otherwise, it can return ESP_ERR_INVALID_STATE error. static bool example_pcnt_on_reach(pcnt_unit_handle_t unit, const pcnt_watch_event_data_t *edata, void *user_ctx) { BaseType_t high_task_wakeup; QueueHandle_t queue = (QueueHandle_t)user_ctx; // send watch point to queue, from this interrupt callback xQueueSendFromISR(queue, &(edata->watch_point_value), &high_task_wakeup); // return whether a high priority task has been waken up by this function return (high_task_wakeup == pdTRUE); } pcnt_event_callbacks_t cbs = { .on_reach = example_pcnt_on_reach, }; QueueHandle_t queue = xQueueCreate(10, sizeof(int)); ESP_ERROR_CHECK(pcnt_unit_register_event_callbacks(pcnt_unit, &cbs, queue)); Set Glitch Filter The PCNT unit features filters to ignore possible short glitches in the signals. The parameters that can be configured for the glitch filter are listed in pcnt_glitch_filter_config_t : pcnt_glitch_filter_config_t::max_glitch_ns sets the maximum glitch width, in nano seconds. If a signal pulse's width is smaller than this value, then it will be treated as noise and will not increase/decrease the internal counter. You can enable the glitch filter for PCNT unit by calling pcnt_unit_set_glitch_filter() with the filter configuration provided above. Particularly, you can disable the glitch filter later by calling pcnt_unit_set_glitch_filter() with a NULL filter configuration. This function should be called when the unit is in the init state. Otherwise, it will return ESP_ERR_INVALID_STATE error. Note The glitch filter is clocked from APB. For the counter not to miss any pulses, the maximum glitch width should be longer than one APB_CLK cycle (usually 12.5 ns if APB equals 80 MHz). As the APB frequency would be changed after DFS (Dynamic Frequency Scaling) enabled, which means the filter does not work as expect in that case. So the driver installs a PM lock for PCNT unit during the first time you enable the glitch filter. For more information related to power management strategy used in PCNT driver, please see Power Management. pcnt_glitch_filter_config_t filter_config = { .max_glitch_ns = 1000, }; ESP_ERROR_CHECK(pcnt_unit_set_glitch_filter(pcnt_unit, &filter_config)); Enable and Disable Unit Before doing IO control to the PCNT unit, you need to enable it first, by calling pcnt_unit_enable() . Internally, this function: switches the PCNT driver state from init to enable. enables the interrupt service if it has been lazy installed in pcnt_unit_register_event_callbacks() . acquires a proper power management lock if it has been lazy installed in pcnt_unit_set_glitch_filter() . See also Power Management for more information. On the contrary, calling pcnt_unit_disable() will do the opposite, that is, put the PCNT driver back to the init state, disable the interrupts service and release the power management lock. Unit IO Control Start/Stop and Clear Calling pcnt_unit_start() makes the PCNT unit start to work, increase or decrease counter according to pulse signals. On the contrary, calling pcnt_unit_stop() will stop the PCNT unit but retain current count value. Instead, clearing counter can only be done by calling pcnt_unit_clear_count() . Note, pcnt_unit_start() and pcnt_unit_stop() should be called when the unit has been enabled by pcnt_unit_enable() . Otherwise, it will return ESP_ERR_INVALID_STATE error. Get Count Value You can read current count value at any time by calling pcnt_unit_get_count() . The returned count value is a signed integer, where the sign can be used to reflect the direction. int pulse_count = 0; ESP_ERROR_CHECK(pcnt_unit_get_count(pcnt_unit, &pulse_count)); Compensate Overflow Loss The internal hardware counter will be cleared to zero automatically when it reaches high or low limit. If you want to compensate for that count loss and extend the counter's bit-width, you can: Enable pcnt_unit_config_t::accum_count when installing the PCNT unit. Add the high/low limit as the Watch Points. Now, the returned count value from the pcnt_unit_get_count() function not only reflects the hardware's count value, but also accumulates the high/low overflow loss to it. Note pcnt_unit_clear_count() resets the accumulated count value as well. Power Management When power management is enabled (i.e., CONFIG_PM_ENABLE is on), the system will adjust the APB frequency before going into light sleep, thus potentially changing the behavior of PCNT glitch filter and leading to valid signal being treated as noise. However, the driver can prevent the system from changing APB frequency by acquiring a power management lock of type ESP_PM_APB_FREQ_MAX . Whenever you enable the glitch filter by pcnt_unit_set_glitch_filter() , the driver guarantees that the power management lock is acquired after the PCNT unit is enabled by pcnt_unit_enable() . Likewise, the driver releases the lock after pcnt_unit_disable() is called. IRAM Safe By default, the PCNT interrupt will be deferred when the Cache is disabled for reasons like writing/erasing Flash. Thus the alarm interrupt will not get executed in time, which is not expected in a real-time application. There is a Kconfig option CONFIG_PCNT_ISR_IRAM_SAFE that: Enables the interrupt being serviced even when cache is disabled Places all functions that used by the ISR into IRAM 2 Places driver object into DRAM (in case it is mapped to PSRAM by accident) This allows the interrupt to run while the cache is disabled but comes at the cost of increased IRAM consumption. There is another Kconfig option CONFIG_PCNT_CTRL_FUNC_IN_IRAM that can put commonly used IO control functions into IRAM as well. So that these functions can also be executable when the cache is disabled. These IO control functions are as follows: Thread Safety The factory functions pcnt_new_unit() and pcnt_new_channel() are guaranteed to be thread safe by the driver, which means, you can call them from different RTOS tasks without protection by extra locks. The following functions are allowed to run under ISR context, the driver uses a critical section to prevent them being called concurrently in both task and ISR. Other functions that take the pcnt_unit_handle_t and pcnt_channel_handle_t as the first positional parameter, are not treated as thread safe. This means you should avoid calling them from multiple tasks. Kconfig Options CONFIG_PCNT_CTRL_FUNC_IN_IRAM controls where to place the PCNT control functions (IRAM or Flash), see IRAM Safe for more information. CONFIG_PCNT_ISR_IRAM_SAFE controls whether the default ISR handler can work when cache is disabled, see IRAM Safe for more information. CONFIG_PCNT_ENABLE_DEBUG_LOG is used to enabled the debug log output. Enabling this option increases the firmware binary size. Application Examples Decode the quadrature signals from rotary encoder: peripherals/pcnt/rotary_encoder. API Reference Header File This header file can be included with: #include "driver/pulse_cnt.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t pcnt_new_unit(const pcnt_unit_config_t *config, pcnt_unit_handle_t *ret_unit) Create a new PCNT unit, and return the handle. Note The newly created PCNT unit is put in the init state. Parameters config -- [in] PCNT unit configuration ret_unit -- [out] Returned PCNT unit handle config -- [in] PCNT unit configuration ret_unit -- [out] Returned PCNT unit handle config -- [in] PCNT unit configuration Returns ESP_OK: Create PCNT unit successfully ESP_ERR_INVALID_ARG: Create PCNT unit failed because of invalid argument (e.g. high/low limit value out of the range) ESP_ERR_NO_MEM: Create PCNT unit failed because out of memory ESP_ERR_NOT_FOUND: Create PCNT unit failed because all PCNT units are used up and no more free one ESP_FAIL: Create PCNT unit failed because of other error ESP_OK: Create PCNT unit successfully ESP_ERR_INVALID_ARG: Create PCNT unit failed because of invalid argument (e.g. high/low limit value out of the range) ESP_ERR_NO_MEM: Create PCNT unit failed because out of memory ESP_ERR_NOT_FOUND: Create PCNT unit failed because all PCNT units are used up and no more free one ESP_FAIL: Create PCNT unit failed because of other error ESP_OK: Create PCNT unit successfully Parameters config -- [in] PCNT unit configuration ret_unit -- [out] Returned PCNT unit handle Returns ESP_OK: Create PCNT unit successfully ESP_ERR_INVALID_ARG: Create PCNT unit failed because of invalid argument (e.g. high/low limit value out of the range) ESP_ERR_NO_MEM: Create PCNT unit failed because out of memory ESP_ERR_NOT_FOUND: Create PCNT unit failed because all PCNT units are used up and no more free one ESP_FAIL: Create PCNT unit failed because of other error esp_err_t pcnt_del_unit(pcnt_unit_handle_t unit) Delete the PCNT unit handle. Note A PCNT unit can't be in the enable state when this function is invoked. See also pcnt_unit_disable() for how to disable a unit. Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Delete the PCNT unit successfully ESP_ERR_INVALID_ARG: Delete the PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Delete the PCNT unit failed because the unit is not in init state or some PCNT channel is still in working ESP_FAIL: Delete the PCNT unit failed because of other error ESP_OK: Delete the PCNT unit successfully ESP_ERR_INVALID_ARG: Delete the PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Delete the PCNT unit failed because the unit is not in init state or some PCNT channel is still in working ESP_FAIL: Delete the PCNT unit failed because of other error ESP_OK: Delete the PCNT unit successfully Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Delete the PCNT unit successfully ESP_ERR_INVALID_ARG: Delete the PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Delete the PCNT unit failed because the unit is not in init state or some PCNT channel is still in working ESP_FAIL: Delete the PCNT unit failed because of other error esp_err_t pcnt_unit_set_glitch_filter(pcnt_unit_handle_t unit, const pcnt_glitch_filter_config_t *config) Set glitch filter for PCNT unit. Note The glitch filter module is clocked from APB, and APB frequency can be changed during DFS, which in return make the filter out of action. So this function will lazy-install a PM lock internally when the power management is enabled. With this lock, the APB frequency won't be changed. The PM lock can be uninstalled in pcnt_del_unit() . Note This function should be called when the PCNT unit is in the init state (i.e. before calling pcnt_unit_enable() ) Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() config -- [in] PCNT filter configuration, set config to NULL means disabling the filter function unit -- [in] PCNT unit handle created by pcnt_new_unit() config -- [in] PCNT filter configuration, set config to NULL means disabling the filter function unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Set glitch filter successfully ESP_ERR_INVALID_ARG: Set glitch filter failed because of invalid argument (e.g. glitch width is too big) ESP_ERR_INVALID_STATE: Set glitch filter failed because the unit is not in the init state ESP_FAIL: Set glitch filter failed because of other error ESP_OK: Set glitch filter successfully ESP_ERR_INVALID_ARG: Set glitch filter failed because of invalid argument (e.g. glitch width is too big) ESP_ERR_INVALID_STATE: Set glitch filter failed because the unit is not in the init state ESP_FAIL: Set glitch filter failed because of other error ESP_OK: Set glitch filter successfully Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() config -- [in] PCNT filter configuration, set config to NULL means disabling the filter function Returns ESP_OK: Set glitch filter successfully ESP_ERR_INVALID_ARG: Set glitch filter failed because of invalid argument (e.g. glitch width is too big) ESP_ERR_INVALID_STATE: Set glitch filter failed because the unit is not in the init state ESP_FAIL: Set glitch filter failed because of other error esp_err_t pcnt_unit_enable(pcnt_unit_handle_t unit) Enable the PCNT unit. Note This function will transit the unit state from init to enable. Note This function will enable the interrupt service, if it's lazy installed in pcnt_unit_register_event_callbacks() . Note This function will acquire the PM lock if it's lazy installed in pcnt_unit_set_glitch_filter() . Note Enable a PCNT unit doesn't mean to start it. See also pcnt_unit_start() for how to start the PCNT counter. Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Enable PCNT unit successfully ESP_ERR_INVALID_ARG: Enable PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Enable PCNT unit failed because the unit is already enabled ESP_FAIL: Enable PCNT unit failed because of other error ESP_OK: Enable PCNT unit successfully ESP_ERR_INVALID_ARG: Enable PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Enable PCNT unit failed because the unit is already enabled ESP_FAIL: Enable PCNT unit failed because of other error ESP_OK: Enable PCNT unit successfully Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Enable PCNT unit successfully ESP_ERR_INVALID_ARG: Enable PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Enable PCNT unit failed because the unit is already enabled ESP_FAIL: Enable PCNT unit failed because of other error esp_err_t pcnt_unit_disable(pcnt_unit_handle_t unit) Disable the PCNT unit. Note This function will do the opposite work to the pcnt_unit_enable() Note Disable a PCNT unit doesn't mean to stop it. See also pcnt_unit_stop() for how to stop the PCNT counter. Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Disable PCNT unit successfully ESP_ERR_INVALID_ARG: Disable PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Disable PCNT unit failed because the unit is not enabled yet ESP_FAIL: Disable PCNT unit failed because of other error ESP_OK: Disable PCNT unit successfully ESP_ERR_INVALID_ARG: Disable PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Disable PCNT unit failed because the unit is not enabled yet ESP_FAIL: Disable PCNT unit failed because of other error ESP_OK: Disable PCNT unit successfully Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Disable PCNT unit successfully ESP_ERR_INVALID_ARG: Disable PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Disable PCNT unit failed because the unit is not enabled yet ESP_FAIL: Disable PCNT unit failed because of other error esp_err_t pcnt_unit_start(pcnt_unit_handle_t unit) Start the PCNT unit, the counter will start to count according to the edge and/or level input signals. Note This function should be called when the unit is in the enable state (i.e. after calling pcnt_unit_enable() ) Note This function is allowed to run within ISR context Note This function will be placed into IRAM if CONFIG_PCNT_CTRL_FUNC_IN_IRAM is on, so that it's allowed to be executed when Cache is disabled Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Start PCNT unit successfully ESP_ERR_INVALID_ARG: Start PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Start PCNT unit failed because the unit is not enabled yet ESP_FAIL: Start PCNT unit failed because of other error ESP_OK: Start PCNT unit successfully ESP_ERR_INVALID_ARG: Start PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Start PCNT unit failed because the unit is not enabled yet ESP_FAIL: Start PCNT unit failed because of other error ESP_OK: Start PCNT unit successfully Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Start PCNT unit successfully ESP_ERR_INVALID_ARG: Start PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Start PCNT unit failed because the unit is not enabled yet ESP_FAIL: Start PCNT unit failed because of other error esp_err_t pcnt_unit_stop(pcnt_unit_handle_t unit) Stop PCNT from counting. Note This function should be called when the unit is in the enable state (i.e. after calling pcnt_unit_enable() ) Note The stop operation won't clear the counter. Also see pcnt_unit_clear_count() for how to clear pulse count value. Note This function is allowed to run within ISR context Note This function will be placed into IRAM if CONFIG_PCNT_CTRL_FUNC_IN_IRAM , so that it is allowed to be executed when Cache is disabled Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Stop PCNT unit successfully ESP_ERR_INVALID_ARG: Stop PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Stop PCNT unit failed because the unit is not enabled yet ESP_FAIL: Stop PCNT unit failed because of other error ESP_OK: Stop PCNT unit successfully ESP_ERR_INVALID_ARG: Stop PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Stop PCNT unit failed because the unit is not enabled yet ESP_FAIL: Stop PCNT unit failed because of other error ESP_OK: Stop PCNT unit successfully Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Stop PCNT unit successfully ESP_ERR_INVALID_ARG: Stop PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Stop PCNT unit failed because the unit is not enabled yet ESP_FAIL: Stop PCNT unit failed because of other error esp_err_t pcnt_unit_clear_count(pcnt_unit_handle_t unit) Clear PCNT pulse count value to zero. Note It's recommended to call this function after adding a watch point by pcnt_unit_add_watch_point() , so that the newly added watch point is effective immediately. Note This function is allowed to run within ISR context Note This function will be placed into IRAM if CONFIG_PCNT_CTRL_FUNC_IN_IRAM , so that it's allowed to be executed when Cache is disabled Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Clear PCNT pulse count successfully ESP_ERR_INVALID_ARG: Clear PCNT pulse count failed because of invalid argument ESP_FAIL: Clear PCNT pulse count failed because of other error ESP_OK: Clear PCNT pulse count successfully ESP_ERR_INVALID_ARG: Clear PCNT pulse count failed because of invalid argument ESP_FAIL: Clear PCNT pulse count failed because of other error ESP_OK: Clear PCNT pulse count successfully Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Clear PCNT pulse count successfully ESP_ERR_INVALID_ARG: Clear PCNT pulse count failed because of invalid argument ESP_FAIL: Clear PCNT pulse count failed because of other error esp_err_t pcnt_unit_get_count(pcnt_unit_handle_t unit, int *value) Get PCNT count value. Note This function is allowed to run within ISR context Note This function will be placed into IRAM if CONFIG_PCNT_CTRL_FUNC_IN_IRAM , so that it's allowed to be executed when Cache is disabled Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() value -- [out] Returned count value unit -- [in] PCNT unit handle created by pcnt_new_unit() value -- [out] Returned count value unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Get PCNT pulse count successfully ESP_ERR_INVALID_ARG: Get PCNT pulse count failed because of invalid argument ESP_FAIL: Get PCNT pulse count failed because of other error ESP_OK: Get PCNT pulse count successfully ESP_ERR_INVALID_ARG: Get PCNT pulse count failed because of invalid argument ESP_FAIL: Get PCNT pulse count failed because of other error ESP_OK: Get PCNT pulse count successfully Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() value -- [out] Returned count value Returns ESP_OK: Get PCNT pulse count successfully ESP_ERR_INVALID_ARG: Get PCNT pulse count failed because of invalid argument ESP_FAIL: Get PCNT pulse count failed because of other error esp_err_t pcnt_unit_register_event_callbacks(pcnt_unit_handle_t unit, const pcnt_event_callbacks_t *cbs, void *user_data) Set event callbacks for PCNT unit. Note User registered callbacks are expected to be runnable within ISR context Note The first call to this function needs to be before the call to pcnt_unit_enable Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbs structure to NULL. Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly unit -- [in] PCNT unit handle created by pcnt_new_unit() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because the unit is not in init state ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because the unit is not in init state ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because the unit is not in init state ESP_FAIL: Set event callbacks failed because of other error esp_err_t pcnt_unit_add_watch_point(pcnt_unit_handle_t unit, int watch_point) Add a watch point for PCNT unit, PCNT will generate an event when the counter value reaches the watch point value. Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() watch_point -- [in] Value to be watched unit -- [in] PCNT unit handle created by pcnt_new_unit() watch_point -- [in] Value to be watched unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Add watch point successfully ESP_ERR_INVALID_ARG: Add watch point failed because of invalid argument (e.g. the value to be watched is out of the limitation set in pcnt_unit_config_t ) ESP_ERR_INVALID_STATE: Add watch point failed because the same watch point has already been added ESP_ERR_NOT_FOUND: Add watch point failed because no more hardware watch point can be configured ESP_FAIL: Add watch point failed because of other error ESP_OK: Add watch point successfully ESP_ERR_INVALID_ARG: Add watch point failed because of invalid argument (e.g. the value to be watched is out of the limitation set in pcnt_unit_config_t ) ESP_ERR_INVALID_STATE: Add watch point failed because the same watch point has already been added ESP_ERR_NOT_FOUND: Add watch point failed because no more hardware watch point can be configured ESP_FAIL: Add watch point failed because of other error ESP_OK: Add watch point successfully Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() watch_point -- [in] Value to be watched Returns ESP_OK: Add watch point successfully ESP_ERR_INVALID_ARG: Add watch point failed because of invalid argument (e.g. the value to be watched is out of the limitation set in pcnt_unit_config_t ) ESP_ERR_INVALID_STATE: Add watch point failed because the same watch point has already been added ESP_ERR_NOT_FOUND: Add watch point failed because no more hardware watch point can be configured ESP_FAIL: Add watch point failed because of other error esp_err_t pcnt_unit_remove_watch_point(pcnt_unit_handle_t unit, int watch_point) Remove a watch point for PCNT unit. Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() watch_point -- [in] Watch point value unit -- [in] PCNT unit handle created by pcnt_new_unit() watch_point -- [in] Watch point value unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Remove watch point successfully ESP_ERR_INVALID_ARG: Remove watch point failed because of invalid argument ESP_ERR_INVALID_STATE: Remove watch point failed because the watch point was not added by pcnt_unit_add_watch_point() yet ESP_FAIL: Remove watch point failed because of other error ESP_OK: Remove watch point successfully ESP_ERR_INVALID_ARG: Remove watch point failed because of invalid argument ESP_ERR_INVALID_STATE: Remove watch point failed because the watch point was not added by pcnt_unit_add_watch_point() yet ESP_FAIL: Remove watch point failed because of other error ESP_OK: Remove watch point successfully Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() watch_point -- [in] Watch point value Returns ESP_OK: Remove watch point successfully ESP_ERR_INVALID_ARG: Remove watch point failed because of invalid argument ESP_ERR_INVALID_STATE: Remove watch point failed because the watch point was not added by pcnt_unit_add_watch_point() yet ESP_FAIL: Remove watch point failed because of other error esp_err_t pcnt_new_channel(pcnt_unit_handle_t unit, const pcnt_chan_config_t *config, pcnt_channel_handle_t *ret_chan) Create PCNT channel for specific unit, each PCNT has several channels associated with it. Note This function should be called when the unit is in init state (i.e. before calling pcnt_unit_enable() ) Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() config -- [in] PCNT channel configuration ret_chan -- [out] Returned channel handle unit -- [in] PCNT unit handle created by pcnt_new_unit() config -- [in] PCNT channel configuration ret_chan -- [out] Returned channel handle unit -- [in] PCNT unit handle created by pcnt_new_unit() Returns ESP_OK: Create PCNT channel successfully ESP_ERR_INVALID_ARG: Create PCNT channel failed because of invalid argument ESP_ERR_NO_MEM: Create PCNT channel failed because of insufficient memory ESP_ERR_NOT_FOUND: Create PCNT channel failed because all PCNT channels are used up and no more free one ESP_ERR_INVALID_STATE: Create PCNT channel failed because the unit is not in the init state ESP_FAIL: Create PCNT channel failed because of other error ESP_OK: Create PCNT channel successfully ESP_ERR_INVALID_ARG: Create PCNT channel failed because of invalid argument ESP_ERR_NO_MEM: Create PCNT channel failed because of insufficient memory ESP_ERR_NOT_FOUND: Create PCNT channel failed because all PCNT channels are used up and no more free one ESP_ERR_INVALID_STATE: Create PCNT channel failed because the unit is not in the init state ESP_FAIL: Create PCNT channel failed because of other error ESP_OK: Create PCNT channel successfully Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() config -- [in] PCNT channel configuration ret_chan -- [out] Returned channel handle Returns ESP_OK: Create PCNT channel successfully ESP_ERR_INVALID_ARG: Create PCNT channel failed because of invalid argument ESP_ERR_NO_MEM: Create PCNT channel failed because of insufficient memory ESP_ERR_NOT_FOUND: Create PCNT channel failed because all PCNT channels are used up and no more free one ESP_ERR_INVALID_STATE: Create PCNT channel failed because the unit is not in the init state ESP_FAIL: Create PCNT channel failed because of other error esp_err_t pcnt_del_channel(pcnt_channel_handle_t chan) Delete the PCNT channel. Parameters chan -- [in] PCNT channel handle created by pcnt_new_channel() Returns ESP_OK: Delete the PCNT channel successfully ESP_ERR_INVALID_ARG: Delete the PCNT channel failed because of invalid argument ESP_FAIL: Delete the PCNT channel failed because of other error ESP_OK: Delete the PCNT channel successfully ESP_ERR_INVALID_ARG: Delete the PCNT channel failed because of invalid argument ESP_FAIL: Delete the PCNT channel failed because of other error ESP_OK: Delete the PCNT channel successfully Parameters chan -- [in] PCNT channel handle created by pcnt_new_channel() Returns ESP_OK: Delete the PCNT channel successfully ESP_ERR_INVALID_ARG: Delete the PCNT channel failed because of invalid argument ESP_FAIL: Delete the PCNT channel failed because of other error esp_err_t pcnt_channel_set_edge_action(pcnt_channel_handle_t chan, pcnt_channel_edge_action_t pos_act, pcnt_channel_edge_action_t neg_act) Set channel actions when edge signal changes (e.g. falling or rising edge occurred). The edge signal is input from the edge_gpio_num configured in pcnt_chan_config_t . We use these actions to control when and how to change the counter value. Parameters chan -- [in] PCNT channel handle created by pcnt_new_channel() pos_act -- [in] Action on posedge signal neg_act -- [in] Action on negedge signal chan -- [in] PCNT channel handle created by pcnt_new_channel() pos_act -- [in] Action on posedge signal neg_act -- [in] Action on negedge signal chan -- [in] PCNT channel handle created by pcnt_new_channel() Returns ESP_OK: Set edge action for PCNT channel successfully ESP_ERR_INVALID_ARG: Set edge action for PCNT channel failed because of invalid argument ESP_FAIL: Set edge action for PCNT channel failed because of other error ESP_OK: Set edge action for PCNT channel successfully ESP_ERR_INVALID_ARG: Set edge action for PCNT channel failed because of invalid argument ESP_FAIL: Set edge action for PCNT channel failed because of other error ESP_OK: Set edge action for PCNT channel successfully Parameters chan -- [in] PCNT channel handle created by pcnt_new_channel() pos_act -- [in] Action on posedge signal neg_act -- [in] Action on negedge signal Returns ESP_OK: Set edge action for PCNT channel successfully ESP_ERR_INVALID_ARG: Set edge action for PCNT channel failed because of invalid argument ESP_FAIL: Set edge action for PCNT channel failed because of other error esp_err_t pcnt_channel_set_level_action(pcnt_channel_handle_t chan, pcnt_channel_level_action_t high_act, pcnt_channel_level_action_t low_act) Set channel actions when level signal changes (e.g. signal level goes from high to low). The level signal is input from the level_gpio_num configured in pcnt_chan_config_t . We use these actions to control when and how to change the counting mode. Parameters chan -- [in] PCNT channel handle created by pcnt_new_channel() high_act -- [in] Action on high level signal low_act -- [in] Action on low level signal chan -- [in] PCNT channel handle created by pcnt_new_channel() high_act -- [in] Action on high level signal low_act -- [in] Action on low level signal chan -- [in] PCNT channel handle created by pcnt_new_channel() Returns ESP_OK: Set level action for PCNT channel successfully ESP_ERR_INVALID_ARG: Set level action for PCNT channel failed because of invalid argument ESP_FAIL: Set level action for PCNT channel failed because of other error ESP_OK: Set level action for PCNT channel successfully ESP_ERR_INVALID_ARG: Set level action for PCNT channel failed because of invalid argument ESP_FAIL: Set level action for PCNT channel failed because of other error ESP_OK: Set level action for PCNT channel successfully Parameters chan -- [in] PCNT channel handle created by pcnt_new_channel() high_act -- [in] Action on high level signal low_act -- [in] Action on low level signal Returns ESP_OK: Set level action for PCNT channel successfully ESP_ERR_INVALID_ARG: Set level action for PCNT channel failed because of invalid argument ESP_FAIL: Set level action for PCNT channel failed because of other error Structures struct pcnt_watch_event_data_t PCNT watch event data. Public Members int watch_point_value Watch point value that triggered the event int watch_point_value Watch point value that triggered the event pcnt_unit_zero_cross_mode_t zero_cross_mode Zero cross mode pcnt_unit_zero_cross_mode_t zero_cross_mode Zero cross mode int watch_point_value struct pcnt_event_callbacks_t Group of supported PCNT callbacks. Note The callbacks are all running under ISR environment Note When CONFIG_PCNT_ISR_IRAM_SAFE is enabled, the callback itself and functions callbed by it should be placed in IRAM. Public Members pcnt_watch_cb_t on_reach Called when PCNT unit counter reaches any watch point pcnt_watch_cb_t on_reach Called when PCNT unit counter reaches any watch point pcnt_watch_cb_t on_reach struct pcnt_unit_config_t PCNT unit configuration. Public Members int low_limit Low limitation of the count unit, should be lower than 0 int low_limit Low limitation of the count unit, should be lower than 0 int high_limit High limitation of the count unit, should be higher than 0 int high_limit High limitation of the count unit, should be higher than 0 int intr_priority PCNT interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) int intr_priority PCNT interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) uint32_t accum_count Whether to accumulate the count value when overflows at the high/low limit uint32_t accum_count Whether to accumulate the count value when overflows at the high/low limit struct pcnt_unit_config_t::[anonymous] flags Extra flags struct pcnt_unit_config_t::[anonymous] flags Extra flags int low_limit struct pcnt_chan_config_t PCNT channel configuration. Public Members int edge_gpio_num GPIO number used by the edge signal, input mode with pull up enabled. Set to -1 if unused int edge_gpio_num GPIO number used by the edge signal, input mode with pull up enabled. Set to -1 if unused int level_gpio_num GPIO number used by the level signal, input mode with pull up enabled. Set to -1 if unused int level_gpio_num GPIO number used by the level signal, input mode with pull up enabled. Set to -1 if unused uint32_t invert_edge_input Invert the input edge signal uint32_t invert_edge_input Invert the input edge signal uint32_t invert_level_input Invert the input level signal uint32_t invert_level_input Invert the input level signal uint32_t virt_edge_io_level Virtual edge IO level, 0: low, 1: high. Only valid when edge_gpio_num is set to -1 uint32_t virt_edge_io_level Virtual edge IO level, 0: low, 1: high. Only valid when edge_gpio_num is set to -1 uint32_t virt_level_io_level Virtual level IO level, 0: low, 1: high. Only valid when level_gpio_num is set to -1 uint32_t virt_level_io_level Virtual level IO level, 0: low, 1: high. Only valid when level_gpio_num is set to -1 uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well struct pcnt_chan_config_t::[anonymous] flags Channel config flags struct pcnt_chan_config_t::[anonymous] flags Channel config flags int edge_gpio_num Type Definitions typedef struct pcnt_unit_t *pcnt_unit_handle_t Type of PCNT unit handle. typedef struct pcnt_chan_t *pcnt_channel_handle_t Type of PCNT channel handle. typedef bool (*pcnt_watch_cb_t)(pcnt_unit_handle_t unit, const pcnt_watch_event_data_t *edata, void *user_ctx) PCNT watch event callback prototype. Note The callback function is invoked from an ISR context, so it should meet the restrictions of not calling any blocking APIs when implementing the callback. e.g. must use ISR version of FreeRTOS APIs. Param unit [in] PCNT unit handle Param edata [in] PCNT event data, fed by the driver Param user_ctx [in] User data, passed from pcnt_unit_register_event_callbacks() Return Whether a high priority task has been woken up by this function Param unit [in] PCNT unit handle Param edata [in] PCNT event data, fed by the driver Param user_ctx [in] User data, passed from pcnt_unit_register_event_callbacks() Return Whether a high priority task has been woken up by this function Header File This header file can be included with: #include "hal/pcnt_types.h" Enumerations enum pcnt_channel_level_action_t PCNT channel action on control level. Values: enumerator PCNT_CHANNEL_LEVEL_ACTION_KEEP Keep current count mode enumerator PCNT_CHANNEL_LEVEL_ACTION_KEEP Keep current count mode enumerator PCNT_CHANNEL_LEVEL_ACTION_INVERSE Invert current count mode (increase -> decrease, decrease -> increase) enumerator PCNT_CHANNEL_LEVEL_ACTION_INVERSE Invert current count mode (increase -> decrease, decrease -> increase) enumerator PCNT_CHANNEL_LEVEL_ACTION_HOLD Hold current count value enumerator PCNT_CHANNEL_LEVEL_ACTION_HOLD Hold current count value enumerator PCNT_CHANNEL_LEVEL_ACTION_KEEP enum pcnt_channel_edge_action_t PCNT channel action on signal edge. Values: enumerator PCNT_CHANNEL_EDGE_ACTION_HOLD Hold current count value enumerator PCNT_CHANNEL_EDGE_ACTION_HOLD Hold current count value enumerator PCNT_CHANNEL_EDGE_ACTION_INCREASE Increase count value enumerator PCNT_CHANNEL_EDGE_ACTION_INCREASE Increase count value enumerator PCNT_CHANNEL_EDGE_ACTION_DECREASE Decrease count value enumerator PCNT_CHANNEL_EDGE_ACTION_DECREASE Decrease count value enumerator PCNT_CHANNEL_EDGE_ACTION_HOLD enum pcnt_unit_zero_cross_mode_t PCNT unit zero cross mode. Values: enumerator PCNT_UNIT_ZERO_CROSS_POS_ZERO start from positive value, end to zero, i.e. +N->0 enumerator PCNT_UNIT_ZERO_CROSS_POS_ZERO start from positive value, end to zero, i.e. +N->0 enumerator PCNT_UNIT_ZERO_CROSS_NEG_ZERO start from negative value, end to zero, i.e. -N->0 enumerator PCNT_UNIT_ZERO_CROSS_NEG_ZERO start from negative value, end to zero, i.e. -N->0 enumerator PCNT_UNIT_ZERO_CROSS_NEG_POS start from negative value, end to positive value, i.e. -N->+M enumerator PCNT_UNIT_ZERO_CROSS_NEG_POS start from negative value, end to positive value, i.e. -N->+M enumerator PCNT_UNIT_ZERO_CROSS_POS_NEG start from positive value, end to negative value, i.e. +N->-M enumerator PCNT_UNIT_ZERO_CROSS_POS_NEG start from positive value, end to negative value, i.e. +N->-M enumerator PCNT_UNIT_ZERO_CROSS_POS_ZERO 1 Different ESP chip series might have different number of PCNT units and channels. Please refer to the [TRM] for details. The driver does not forbid you from applying for more PCNT units and channels, but it returns error when all available hardware resources are used up. Please always check the return value when doing resource allocation (e.g., pcnt_new_unit() ). 2 pcnt_event_callbacks_t::on_reach callback and the functions invoked by itself should also be placed in IRAM, you need to take care of them by themselves.
Pulse Counter (PCNT) Introduction The PCNT (Pulse Counter) module is designed to count the number of rising and/or falling edges of input signals. The ESP32 contains multiple pulse counter units in the module. 1 Each unit is in effect an independent counter with multiple channels, where each channel can increment/decrement the counter on a rising/falling edge. Furthermore, each channel can be configured separately. PCNT channels can react to signals of edge type and level type, however for simple applications, detecting the edge signal is usually sufficient. PCNT channels can be configured react to both pulse edges (i.e., rising and falling edge), and can be configured to increase, decrease or do nothing to the unit's counter on each edge. The level signal is the so-called control signal, which is used to control the counting mode of the edge signals that are attached to the same channel. By combining the usage of both edge and level signals, a PCNT unit can act as a quadrature decoder. Besides that, PCNT unit is equipped with a separate glitch filter, which is helpful to remove noise from the signal. Typically, a PCNT module can be used in scenarios like: Calculate periodic signal's frequency by counting the pulse numbers within a time slice Decode quadrature signals into speed and direction Functional Overview Description of the PCNT functionality is divided into the following sections: Resource Allocation - covers how to allocate PCNT units and channels with properly set of configurations. It also covers how to recycle the resources when they finished working. Set Up Channel Actions - covers how to configure the PCNT channel to behave on different signal edges and levels. Watch Points - describes how to configure PCNT watch points (i.e., tell PCNT unit to trigger an event when the count reaches a certain value). Register Event Callbacks - describes how to hook your specific code to the watch point event callback function. Set Glitch Filter - describes how to enable and set the timing parameters for the internal glitch filter. Enable and Disable Unit - describes how to enable and disable the PCNT unit. Unit IO Control - describes IO control functions of PCNT unit, like enable glitch filter, start and stop unit, get and clear count value. Power Management - describes what functionality will prevent the chip from going into low power mode. IRAM Safe - describes tips on how to make the PCNT interrupt and IO control functions work better along with a disabled cache. Thread Safety - lists which APIs are guaranteed to be thread safe by the driver. Kconfig Options - lists the supported Kconfig options that can be used to make a different effect on driver behavior. Resource Allocation The PCNT unit and channel are represented by pcnt_unit_handle_t and pcnt_channel_handle_t respectively. All available units and channels are maintained by the driver in a resource pool, so you do not need to know the exact underlying instance ID. Install PCNT Unit To install a PCNT unit, there is a configuration structure that needs to be given in advance: pcnt_unit_config_t: pcnt_unit_config_t::low_limitand pcnt_unit_config_t::high_limitspecify the range for the internal hardware counter. The counter will reset to zero automatically when it crosses either the high or low limit. pcnt_unit_config_t::accum_countsets whether to create an internal accumulator for the counter. This is helpful when you want to extend the counter's width, which by default is 16 bit at most, defined in the hardware. See also Compensate Overflow Loss for how to use this feature to compensate the overflow loss. pcnt_unit_config_t::intr_prioritysets the priority of the interrupt. If it is set to 0, the driver will allocate an interrupt with a default priority. Otherwise, the driver will use the given priority. Note Since all PCNT units share the same interrupt source, when installing multiple PCNT units make sure that the interrupt priority pcnt_unit_config_t::intr_priority is the same for each unit. Unit allocation and initialization is done by calling a function pcnt_new_unit() with pcnt_unit_config_t as an input parameter. The function will return a PCNT unit handle only when it runs correctly. Specifically, when there are no more free PCNT units in the pool (i.e., unit resources have been used up), then this function will return ESP_ERR_NOT_FOUND error. The total number of available PCNT units is recorded by SOC_PCNT_UNITS_PER_GROUP for reference. If a previously created PCNT unit is no longer needed, it is recommended to recycle the resource by calling pcnt_del_unit(). Which in return allows the underlying unit hardware to be used for other purposes. Before deleting a PCNT unit, one should ensure the following prerequisites: The unit is in the init state, in other words, the unit is either disabled by pcnt_unit_disable()or not enabled yet. The attached PCNT channels are all removed by pcnt_del_channel(). #define EXAMPLE_PCNT_HIGH_LIMIT 100 #define EXAMPLE_PCNT_LOW_LIMIT -100 pcnt_unit_config_t unit_config = { .high_limit = EXAMPLE_PCNT_HIGH_LIMIT, .low_limit = EXAMPLE_PCNT_LOW_LIMIT, }; pcnt_unit_handle_t pcnt_unit = NULL; ESP_ERROR_CHECK(pcnt_new_unit(&unit_config, &pcnt_unit)); Install PCNT Channel To install a PCNT channel, you must initialize a pcnt_chan_config_t structure in advance, and then call pcnt_new_channel(). The configuration fields of the pcnt_chan_config_t structure are described below: pcnt_chan_config_t::edge_gpio_numand pcnt_chan_config_t::level_gpio_numspecify the GPIO numbers used by edge type signal and level type signal. Please note, either of them can be assigned to -1if it is not actually used, and thus it will become a virtual IO. For some simple pulse counting applications where one of the level/edge signals is fixed (i.e., never changes), you can reclaim a GPIO by setting the signal as a virtual IO on channel allocation. Setting the level/edge signal as a virtual IO causes that signal to be internally routed to a fixed High/Low logic level, thus allowing you to save a GPIO for other purposes. pcnt_chan_config_t::virt_edge_io_leveland pcnt_chan_config_t::virt_level_io_levelspecify the virtual IO level for edge and level input signal, to ensure a deterministic state for such control signal. Please note, they are only valid when either pcnt_chan_config_t::edge_gpio_numor pcnt_chan_config_t::level_gpio_numis assigned to -1. pcnt_chan_config_t::invert_edge_inputand pcnt_chan_config_t::invert_level_inputare used to decide whether to invert the input signals before they going into PCNT hardware. The invert is done by GPIO matrix instead of PCNT hardware. pcnt_chan_config_t::io_loop_backis for debug only, which enables both the GPIO's input and output paths. This can help to simulate the pulse signals by function gpio_set_level()on the same GPIO. Channel allocating and initialization is done by calling a function pcnt_new_channel() with the above pcnt_chan_config_t as an input parameter plus a PCNT unit handle returned from pcnt_new_unit(). This function will return a PCNT channel handle if it runs correctly. Specifically, when there are no more free PCNT channel within the unit (i.e., channel resources have been used up), then this function will return ESP_ERR_NOT_FOUND error. The total number of available PCNT channels within the unit is recorded by SOC_PCNT_CHANNELS_PER_UNIT for reference. Note that, when install a PCNT channel for a specific unit, one should ensure the unit is in the init state, otherwise this function will return ESP_ERR_INVALID_STATE error. If a previously created PCNT channel is no longer needed, it is recommended to recycle the resources by calling pcnt_del_channel(). Which in return allows the underlying channel hardware to be used for other purposes. #define EXAMPLE_CHAN_GPIO_A 0 #define EXAMPLE_CHAN_GPIO_B 2 pcnt_chan_config_t chan_config = { .edge_gpio_num = EXAMPLE_CHAN_GPIO_A, .level_gpio_num = EXAMPLE_CHAN_GPIO_B, }; pcnt_channel_handle_t pcnt_chan = NULL; ESP_ERROR_CHECK(pcnt_new_channel(pcnt_unit, &chan_config, &pcnt_chan)); Set Up Channel Actions The PCNT will increase/decrease/hold its internal count value when the input pulse signal toggles. You can set different actions for edge signal and/or level signal. pcnt_channel_set_edge_action()function is to set specific actions for rising and falling edge of the signal attached to the pcnt_chan_config_t::edge_gpio_num. Supported actions are listed in pcnt_channel_edge_action_t. pcnt_channel_set_level_action()function is to set specific actions for high and low level of the signal attached to the pcnt_chan_config_t::level_gpio_num. Supported actions are listed in pcnt_channel_level_action_t. This function is not mandatory if the pcnt_chan_config_t::level_gpio_numis set to -1when allocating PCNT channel by pcnt_new_channel(). // decrease the counter on rising edge, increase the counter on falling edge ESP_ERROR_CHECK(pcnt_channel_set_edge_action(pcnt_chan, PCNT_CHANNEL_EDGE_ACTION_DECREASE, PCNT_CHANNEL_EDGE_ACTION_INCREASE)); // keep the counting mode when the control signal is high level, and reverse the counting mode when the control signal is low level ESP_ERROR_CHECK(pcnt_channel_set_level_action(pcnt_chan, PCNT_CHANNEL_LEVEL_ACTION_KEEP, PCNT_CHANNEL_LEVEL_ACTION_INVERSE)); Watch Points Each PCNT unit can be configured to watch several different values that you are interested in. The value to be watched is also called Watch Point. The watch point itself can not exceed the range set in pcnt_unit_config_t by pcnt_unit_config_t::low_limit and pcnt_unit_config_t::high_limit. When the counter reaches either watch point, a watch event will be triggered and notify you by interrupt if any watch event callback has ever registered in pcnt_unit_register_event_callbacks(). See Register Event Callbacks for how to register event callbacks. The watch point can be added and removed by pcnt_unit_add_watch_point() and pcnt_unit_remove_watch_point(). The commonly-used watch points are: zero cross, maximum/minimum count and other threshold values. The number of available watch point is limited, pcnt_unit_add_watch_point() will return error ESP_ERR_NOT_FOUND if it can not find any free hardware resource to save the watch point. You can not add the same watch point for multiple times, otherwise it will return error ESP_ERR_INVALID_STATE. It is recommended to remove the unused watch point by pcnt_unit_remove_watch_point() to recycle the watch point resources. // add zero across watch point ESP_ERROR_CHECK(pcnt_unit_add_watch_point(pcnt_unit, 0)); // add high limit watch point ESP_ERROR_CHECK(pcnt_unit_add_watch_point(pcnt_unit, EXAMPLE_PCNT_HIGH_LIMIT)); Note Due to the hardware limitation, after adding a watch point, you should call pcnt_unit_clear_count() to make it take effect. Register Event Callbacks When PCNT unit reaches any enabled watch point, specific event will be generated and notify the CPU by interrupt. If you have some function that want to get executed when event happens, you should hook your function to the interrupt service routine by calling pcnt_unit_register_event_callbacks(). All supported event callbacks are listed in the pcnt_event_callbacks_t: pcnt_event_callbacks_t::on_reachsets a callback function for watch point event. As this function is called within the ISR context, you must ensure that the function does not attempt to block (e.g., by making sure that only FreeRTOS APIs with ISRsuffix are called from within the function). The function prototype is declared in pcnt_watch_cb_t. You can save their own context to pcnt_unit_register_event_callbacks() as well, via the parameter user_ctx. This user data will be directly passed to the callback functions. In the callback function, the driver will fill in the event data of specific event. For example, the watch point event data is declared as pcnt_watch_event_data_t: pcnt_watch_event_data_t::watch_point_valuesaves the watch point value that triggers the event. pcnt_watch_event_data_t::zero_cross_modesaves how the PCNT unit crosses the zero point in the latest time. The possible zero cross modes are listed in the pcnt_unit_zero_cross_mode_t. Usually different zero cross mode means different counting direction and counting step size. Registering callback function results in lazy installation of interrupt service, thus this function should only be called before the unit is enabled by pcnt_unit_enable(). Otherwise, it can return ESP_ERR_INVALID_STATE error. static bool example_pcnt_on_reach(pcnt_unit_handle_t unit, const pcnt_watch_event_data_t *edata, void *user_ctx) { BaseType_t high_task_wakeup; QueueHandle_t queue = (QueueHandle_t)user_ctx; // send watch point to queue, from this interrupt callback xQueueSendFromISR(queue, &(edata->watch_point_value), &high_task_wakeup); // return whether a high priority task has been waken up by this function return (high_task_wakeup == pdTRUE); } pcnt_event_callbacks_t cbs = { .on_reach = example_pcnt_on_reach, }; QueueHandle_t queue = xQueueCreate(10, sizeof(int)); ESP_ERROR_CHECK(pcnt_unit_register_event_callbacks(pcnt_unit, &cbs, queue)); Set Glitch Filter The PCNT unit features filters to ignore possible short glitches in the signals. The parameters that can be configured for the glitch filter are listed in pcnt_glitch_filter_config_t: pcnt_glitch_filter_config_t::max_glitch_nssets the maximum glitch width, in nano seconds. If a signal pulse's width is smaller than this value, then it will be treated as noise and will not increase/decrease the internal counter. You can enable the glitch filter for PCNT unit by calling pcnt_unit_set_glitch_filter() with the filter configuration provided above. Particularly, you can disable the glitch filter later by calling pcnt_unit_set_glitch_filter() with a NULL filter configuration. This function should be called when the unit is in the init state. Otherwise, it will return ESP_ERR_INVALID_STATE error. Note The glitch filter is clocked from APB. For the counter not to miss any pulses, the maximum glitch width should be longer than one APB_CLK cycle (usually 12.5 ns if APB equals 80 MHz). As the APB frequency would be changed after DFS (Dynamic Frequency Scaling) enabled, which means the filter does not work as expect in that case. So the driver installs a PM lock for PCNT unit during the first time you enable the glitch filter. For more information related to power management strategy used in PCNT driver, please see Power Management. pcnt_glitch_filter_config_t filter_config = { .max_glitch_ns = 1000, }; ESP_ERROR_CHECK(pcnt_unit_set_glitch_filter(pcnt_unit, &filter_config)); Enable and Disable Unit Before doing IO control to the PCNT unit, you need to enable it first, by calling pcnt_unit_enable(). Internally, this function: switches the PCNT driver state from init to enable. enables the interrupt service if it has been lazy installed in pcnt_unit_register_event_callbacks(). acquires a proper power management lock if it has been lazy installed in pcnt_unit_set_glitch_filter(). See also Power Management for more information. On the contrary, calling pcnt_unit_disable() will do the opposite, that is, put the PCNT driver back to the init state, disable the interrupts service and release the power management lock. Unit IO Control Start/Stop and Clear Calling pcnt_unit_start() makes the PCNT unit start to work, increase or decrease counter according to pulse signals. On the contrary, calling pcnt_unit_stop() will stop the PCNT unit but retain current count value. Instead, clearing counter can only be done by calling pcnt_unit_clear_count(). Note, pcnt_unit_start() and pcnt_unit_stop() should be called when the unit has been enabled by pcnt_unit_enable(). Otherwise, it will return ESP_ERR_INVALID_STATE error. Get Count Value You can read current count value at any time by calling pcnt_unit_get_count(). The returned count value is a signed integer, where the sign can be used to reflect the direction. int pulse_count = 0; ESP_ERROR_CHECK(pcnt_unit_get_count(pcnt_unit, &pulse_count)); Compensate Overflow Loss The internal hardware counter will be cleared to zero automatically when it reaches high or low limit. If you want to compensate for that count loss and extend the counter's bit-width, you can: - Enable pcnt_unit_config_t::accum_countwhen installing the PCNT unit. - Add the high/low limit as the Watch Points. - Now, the returned count value from the pcnt_unit_get_count()function not only reflects the hardware's count value, but also accumulates the high/low overflow loss to it. Note pcnt_unit_clear_count() resets the accumulated count value as well. Power Management When power management is enabled (i.e., CONFIG_PM_ENABLE is on), the system will adjust the APB frequency before going into light sleep, thus potentially changing the behavior of PCNT glitch filter and leading to valid signal being treated as noise. However, the driver can prevent the system from changing APB frequency by acquiring a power management lock of type ESP_PM_APB_FREQ_MAX. Whenever you enable the glitch filter by pcnt_unit_set_glitch_filter(), the driver guarantees that the power management lock is acquired after the PCNT unit is enabled by pcnt_unit_enable(). Likewise, the driver releases the lock after pcnt_unit_disable() is called. IRAM Safe By default, the PCNT interrupt will be deferred when the Cache is disabled for reasons like writing/erasing Flash. Thus the alarm interrupt will not get executed in time, which is not expected in a real-time application. There is a Kconfig option CONFIG_PCNT_ISR_IRAM_SAFE that: Enables the interrupt being serviced even when cache is disabled Places all functions that used by the ISR into IRAM 2 Places driver object into DRAM (in case it is mapped to PSRAM by accident) This allows the interrupt to run while the cache is disabled but comes at the cost of increased IRAM consumption. There is another Kconfig option CONFIG_PCNT_CTRL_FUNC_IN_IRAM that can put commonly used IO control functions into IRAM as well. So that these functions can also be executable when the cache is disabled. These IO control functions are as follows: Thread Safety The factory functions pcnt_new_unit() and pcnt_new_channel() are guaranteed to be thread safe by the driver, which means, you can call them from different RTOS tasks without protection by extra locks. The following functions are allowed to run under ISR context, the driver uses a critical section to prevent them being called concurrently in both task and ISR. Other functions that take the pcnt_unit_handle_t and pcnt_channel_handle_t as the first positional parameter, are not treated as thread safe. This means you should avoid calling them from multiple tasks. Kconfig Options CONFIG_PCNT_CTRL_FUNC_IN_IRAM controls where to place the PCNT control functions (IRAM or Flash), see IRAM Safe for more information. CONFIG_PCNT_ISR_IRAM_SAFE controls whether the default ISR handler can work when cache is disabled, see IRAM Safe for more information. CONFIG_PCNT_ENABLE_DEBUG_LOG is used to enabled the debug log output. Enabling this option increases the firmware binary size. Application Examples Decode the quadrature signals from rotary encoder: peripherals/pcnt/rotary_encoder. API Reference Header File This header file can be included with: #include "driver/pulse_cnt.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t pcnt_new_unit(const pcnt_unit_config_t *config, pcnt_unit_handle_t *ret_unit) Create a new PCNT unit, and return the handle. Note The newly created PCNT unit is put in the init state. - Parameters config -- [in] PCNT unit configuration ret_unit -- [out] Returned PCNT unit handle - - Returns ESP_OK: Create PCNT unit successfully ESP_ERR_INVALID_ARG: Create PCNT unit failed because of invalid argument (e.g. high/low limit value out of the range) ESP_ERR_NO_MEM: Create PCNT unit failed because out of memory ESP_ERR_NOT_FOUND: Create PCNT unit failed because all PCNT units are used up and no more free one ESP_FAIL: Create PCNT unit failed because of other error - - esp_err_t pcnt_del_unit(pcnt_unit_handle_t unit) Delete the PCNT unit handle. Note A PCNT unit can't be in the enable state when this function is invoked. See also pcnt_unit_disable()for how to disable a unit. - Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() - Returns ESP_OK: Delete the PCNT unit successfully ESP_ERR_INVALID_ARG: Delete the PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Delete the PCNT unit failed because the unit is not in init state or some PCNT channel is still in working ESP_FAIL: Delete the PCNT unit failed because of other error - - esp_err_t pcnt_unit_set_glitch_filter(pcnt_unit_handle_t unit, const pcnt_glitch_filter_config_t *config) Set glitch filter for PCNT unit. Note The glitch filter module is clocked from APB, and APB frequency can be changed during DFS, which in return make the filter out of action. So this function will lazy-install a PM lock internally when the power management is enabled. With this lock, the APB frequency won't be changed. The PM lock can be uninstalled in pcnt_del_unit(). Note This function should be called when the PCNT unit is in the init state (i.e. before calling pcnt_unit_enable()) - Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() config -- [in] PCNT filter configuration, set config to NULL means disabling the filter function - - Returns ESP_OK: Set glitch filter successfully ESP_ERR_INVALID_ARG: Set glitch filter failed because of invalid argument (e.g. glitch width is too big) ESP_ERR_INVALID_STATE: Set glitch filter failed because the unit is not in the init state ESP_FAIL: Set glitch filter failed because of other error - - esp_err_t pcnt_unit_enable(pcnt_unit_handle_t unit) Enable the PCNT unit. Note This function will transit the unit state from init to enable. Note This function will enable the interrupt service, if it's lazy installed in pcnt_unit_register_event_callbacks(). Note This function will acquire the PM lock if it's lazy installed in pcnt_unit_set_glitch_filter(). Note Enable a PCNT unit doesn't mean to start it. See also pcnt_unit_start()for how to start the PCNT counter. - Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() - Returns ESP_OK: Enable PCNT unit successfully ESP_ERR_INVALID_ARG: Enable PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Enable PCNT unit failed because the unit is already enabled ESP_FAIL: Enable PCNT unit failed because of other error - - esp_err_t pcnt_unit_disable(pcnt_unit_handle_t unit) Disable the PCNT unit. Note This function will do the opposite work to the pcnt_unit_enable() Note Disable a PCNT unit doesn't mean to stop it. See also pcnt_unit_stop()for how to stop the PCNT counter. - Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() - Returns ESP_OK: Disable PCNT unit successfully ESP_ERR_INVALID_ARG: Disable PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Disable PCNT unit failed because the unit is not enabled yet ESP_FAIL: Disable PCNT unit failed because of other error - - esp_err_t pcnt_unit_start(pcnt_unit_handle_t unit) Start the PCNT unit, the counter will start to count according to the edge and/or level input signals. Note This function should be called when the unit is in the enable state (i.e. after calling pcnt_unit_enable()) Note This function is allowed to run within ISR context Note This function will be placed into IRAM if CONFIG_PCNT_CTRL_FUNC_IN_IRAMis on, so that it's allowed to be executed when Cache is disabled - Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() - Returns ESP_OK: Start PCNT unit successfully ESP_ERR_INVALID_ARG: Start PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Start PCNT unit failed because the unit is not enabled yet ESP_FAIL: Start PCNT unit failed because of other error - - esp_err_t pcnt_unit_stop(pcnt_unit_handle_t unit) Stop PCNT from counting. Note This function should be called when the unit is in the enable state (i.e. after calling pcnt_unit_enable()) Note The stop operation won't clear the counter. Also see pcnt_unit_clear_count()for how to clear pulse count value. Note This function is allowed to run within ISR context Note This function will be placed into IRAM if CONFIG_PCNT_CTRL_FUNC_IN_IRAM, so that it is allowed to be executed when Cache is disabled - Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() - Returns ESP_OK: Stop PCNT unit successfully ESP_ERR_INVALID_ARG: Stop PCNT unit failed because of invalid argument ESP_ERR_INVALID_STATE: Stop PCNT unit failed because the unit is not enabled yet ESP_FAIL: Stop PCNT unit failed because of other error - - esp_err_t pcnt_unit_clear_count(pcnt_unit_handle_t unit) Clear PCNT pulse count value to zero. Note It's recommended to call this function after adding a watch point by pcnt_unit_add_watch_point(), so that the newly added watch point is effective immediately. Note This function is allowed to run within ISR context Note This function will be placed into IRAM if CONFIG_PCNT_CTRL_FUNC_IN_IRAM, so that it's allowed to be executed when Cache is disabled - Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() - Returns ESP_OK: Clear PCNT pulse count successfully ESP_ERR_INVALID_ARG: Clear PCNT pulse count failed because of invalid argument ESP_FAIL: Clear PCNT pulse count failed because of other error - - esp_err_t pcnt_unit_get_count(pcnt_unit_handle_t unit, int *value) Get PCNT count value. Note This function is allowed to run within ISR context Note This function will be placed into IRAM if CONFIG_PCNT_CTRL_FUNC_IN_IRAM, so that it's allowed to be executed when Cache is disabled - Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() value -- [out] Returned count value - - Returns ESP_OK: Get PCNT pulse count successfully ESP_ERR_INVALID_ARG: Get PCNT pulse count failed because of invalid argument ESP_FAIL: Get PCNT pulse count failed because of other error - - esp_err_t pcnt_unit_register_event_callbacks(pcnt_unit_handle_t unit, const pcnt_event_callbacks_t *cbs, void *user_data) Set event callbacks for PCNT unit. Note User registered callbacks are expected to be runnable within ISR context Note The first call to this function needs to be before the call to pcnt_unit_enable Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbsstructure to NULL. - Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly - - Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_ERR_INVALID_STATE: Set event callbacks failed because the unit is not in init state ESP_FAIL: Set event callbacks failed because of other error - - esp_err_t pcnt_unit_add_watch_point(pcnt_unit_handle_t unit, int watch_point) Add a watch point for PCNT unit, PCNT will generate an event when the counter value reaches the watch point value. - Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() watch_point -- [in] Value to be watched - - Returns ESP_OK: Add watch point successfully ESP_ERR_INVALID_ARG: Add watch point failed because of invalid argument (e.g. the value to be watched is out of the limitation set in pcnt_unit_config_t) ESP_ERR_INVALID_STATE: Add watch point failed because the same watch point has already been added ESP_ERR_NOT_FOUND: Add watch point failed because no more hardware watch point can be configured ESP_FAIL: Add watch point failed because of other error - - esp_err_t pcnt_unit_remove_watch_point(pcnt_unit_handle_t unit, int watch_point) Remove a watch point for PCNT unit. - Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() watch_point -- [in] Watch point value - - Returns ESP_OK: Remove watch point successfully ESP_ERR_INVALID_ARG: Remove watch point failed because of invalid argument ESP_ERR_INVALID_STATE: Remove watch point failed because the watch point was not added by pcnt_unit_add_watch_point()yet ESP_FAIL: Remove watch point failed because of other error - - esp_err_t pcnt_new_channel(pcnt_unit_handle_t unit, const pcnt_chan_config_t *config, pcnt_channel_handle_t *ret_chan) Create PCNT channel for specific unit, each PCNT has several channels associated with it. Note This function should be called when the unit is in init state (i.e. before calling pcnt_unit_enable()) - Parameters unit -- [in] PCNT unit handle created by pcnt_new_unit() config -- [in] PCNT channel configuration ret_chan -- [out] Returned channel handle - - Returns ESP_OK: Create PCNT channel successfully ESP_ERR_INVALID_ARG: Create PCNT channel failed because of invalid argument ESP_ERR_NO_MEM: Create PCNT channel failed because of insufficient memory ESP_ERR_NOT_FOUND: Create PCNT channel failed because all PCNT channels are used up and no more free one ESP_ERR_INVALID_STATE: Create PCNT channel failed because the unit is not in the init state ESP_FAIL: Create PCNT channel failed because of other error - - esp_err_t pcnt_del_channel(pcnt_channel_handle_t chan) Delete the PCNT channel. - Parameters chan -- [in] PCNT channel handle created by pcnt_new_channel() - Returns ESP_OK: Delete the PCNT channel successfully ESP_ERR_INVALID_ARG: Delete the PCNT channel failed because of invalid argument ESP_FAIL: Delete the PCNT channel failed because of other error - - esp_err_t pcnt_channel_set_edge_action(pcnt_channel_handle_t chan, pcnt_channel_edge_action_t pos_act, pcnt_channel_edge_action_t neg_act) Set channel actions when edge signal changes (e.g. falling or rising edge occurred). The edge signal is input from the edge_gpio_numconfigured in pcnt_chan_config_t. We use these actions to control when and how to change the counter value. - Parameters chan -- [in] PCNT channel handle created by pcnt_new_channel() pos_act -- [in] Action on posedge signal neg_act -- [in] Action on negedge signal - - Returns ESP_OK: Set edge action for PCNT channel successfully ESP_ERR_INVALID_ARG: Set edge action for PCNT channel failed because of invalid argument ESP_FAIL: Set edge action for PCNT channel failed because of other error - - esp_err_t pcnt_channel_set_level_action(pcnt_channel_handle_t chan, pcnt_channel_level_action_t high_act, pcnt_channel_level_action_t low_act) Set channel actions when level signal changes (e.g. signal level goes from high to low). The level signal is input from the level_gpio_numconfigured in pcnt_chan_config_t. We use these actions to control when and how to change the counting mode. - Parameters chan -- [in] PCNT channel handle created by pcnt_new_channel() high_act -- [in] Action on high level signal low_act -- [in] Action on low level signal - - Returns ESP_OK: Set level action for PCNT channel successfully ESP_ERR_INVALID_ARG: Set level action for PCNT channel failed because of invalid argument ESP_FAIL: Set level action for PCNT channel failed because of other error - Structures - struct pcnt_watch_event_data_t PCNT watch event data. Public Members - int watch_point_value Watch point value that triggered the event - pcnt_unit_zero_cross_mode_t zero_cross_mode Zero cross mode - int watch_point_value - struct pcnt_event_callbacks_t Group of supported PCNT callbacks. Note The callbacks are all running under ISR environment Note When CONFIG_PCNT_ISR_IRAM_SAFE is enabled, the callback itself and functions callbed by it should be placed in IRAM. Public Members - pcnt_watch_cb_t on_reach Called when PCNT unit counter reaches any watch point - pcnt_watch_cb_t on_reach - struct pcnt_unit_config_t PCNT unit configuration. Public Members - int low_limit Low limitation of the count unit, should be lower than 0 - int high_limit High limitation of the count unit, should be higher than 0 - int intr_priority PCNT interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) - uint32_t accum_count Whether to accumulate the count value when overflows at the high/low limit - struct pcnt_unit_config_t::[anonymous] flags Extra flags - int low_limit - struct pcnt_chan_config_t PCNT channel configuration. Public Members - int edge_gpio_num GPIO number used by the edge signal, input mode with pull up enabled. Set to -1 if unused - int level_gpio_num GPIO number used by the level signal, input mode with pull up enabled. Set to -1 if unused - uint32_t invert_edge_input Invert the input edge signal - uint32_t invert_level_input Invert the input level signal - uint32_t virt_edge_io_level Virtual edge IO level, 0: low, 1: high. Only valid when edge_gpio_num is set to -1 - uint32_t virt_level_io_level Virtual level IO level, 0: low, 1: high. Only valid when level_gpio_num is set to -1 - uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well - struct pcnt_chan_config_t::[anonymous] flags Channel config flags - int edge_gpio_num Type Definitions - typedef struct pcnt_unit_t *pcnt_unit_handle_t Type of PCNT unit handle. - typedef struct pcnt_chan_t *pcnt_channel_handle_t Type of PCNT channel handle. - typedef bool (*pcnt_watch_cb_t)(pcnt_unit_handle_t unit, const pcnt_watch_event_data_t *edata, void *user_ctx) PCNT watch event callback prototype. Note The callback function is invoked from an ISR context, so it should meet the restrictions of not calling any blocking APIs when implementing the callback. e.g. must use ISR version of FreeRTOS APIs. - Param unit [in] PCNT unit handle - Param edata [in] PCNT event data, fed by the driver - Param user_ctx [in] User data, passed from pcnt_unit_register_event_callbacks() - Return Whether a high priority task has been woken up by this function Header File This header file can be included with: #include "hal/pcnt_types.h" Enumerations - enum pcnt_channel_level_action_t PCNT channel action on control level. Values: - enumerator PCNT_CHANNEL_LEVEL_ACTION_KEEP Keep current count mode - enumerator PCNT_CHANNEL_LEVEL_ACTION_INVERSE Invert current count mode (increase -> decrease, decrease -> increase) - enumerator PCNT_CHANNEL_LEVEL_ACTION_HOLD Hold current count value - enumerator PCNT_CHANNEL_LEVEL_ACTION_KEEP - enum pcnt_channel_edge_action_t PCNT channel action on signal edge. Values: - enumerator PCNT_CHANNEL_EDGE_ACTION_HOLD Hold current count value - enumerator PCNT_CHANNEL_EDGE_ACTION_INCREASE Increase count value - enumerator PCNT_CHANNEL_EDGE_ACTION_DECREASE Decrease count value - enumerator PCNT_CHANNEL_EDGE_ACTION_HOLD - enum pcnt_unit_zero_cross_mode_t PCNT unit zero cross mode. Values: - enumerator PCNT_UNIT_ZERO_CROSS_POS_ZERO start from positive value, end to zero, i.e. +N->0 - enumerator PCNT_UNIT_ZERO_CROSS_NEG_ZERO start from negative value, end to zero, i.e. -N->0 - enumerator PCNT_UNIT_ZERO_CROSS_NEG_POS start from negative value, end to positive value, i.e. -N->+M - enumerator PCNT_UNIT_ZERO_CROSS_POS_NEG start from positive value, end to negative value, i.e. +N->-M - enumerator PCNT_UNIT_ZERO_CROSS_POS_ZERO - 1 Different ESP chip series might have different number of PCNT units and channels. Please refer to the [TRM] for details. The driver does not forbid you from applying for more PCNT units and channels, but it returns error when all available hardware resources are used up. Please always check the return value when doing resource allocation (e.g., pcnt_new_unit()). - 2 pcnt_event_callbacks_t::on_reachcallback and the functions invoked by itself should also be placed in IRAM, you need to take care of them by themselves.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/pcnt.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Remote Control Transceiver (RMT)
null
espressif.com
2016-01-01
244ebc93381e10e1
null
null
Remote Control Transceiver (RMT) Introduction The RMT (Remote Control Transceiver) peripheral was designed to act as an infrared transceiver. However, due to the flexibility of its data format, RMT can be extended to a versatile and general-purpose transceiver, transmitting or receiving many other types of signals. From the perspective of network layering, the RMT hardware contains both physical and data link layers. The physical layer defines the communication media and bit signal representation. The data link layer defines the format of an RMT frame. The minimal data unit in the frame is called the RMT symbol, which is represented by rmt_symbol_word_t in the driver. ESP32 contains multiple channels in the RMT peripheral 1. Each channel can be independently configured as either transmitter or receiver. Typically, the RMT peripheral can be used in the following scenarios: Transmit or receive infrared signals, with any IR protocols, e.g., NEC General-purpose sequence generator Transmit signals in a hardware-controlled loop, with a finite or infinite number of times Multi-channel simultaneous transmission Modulate the carrier to the output signal or demodulate the carrier from the input signal Layout of RMT Symbols The RMT hardware defines data in its own pattern -- the RMT symbol. The diagram below illustrates the bit fields of an RMT symbol. Each symbol consists of two pairs of two values. The first value in the pair is a 15-bit value representing the signal's duration in units of RMT ticks. The second in the pair is a 1-bit value representing the signal's logic level, i.e., high or low. RMT Transmitter Overview The data path and control path of an RMT TX channel is illustrated in the figure below: The driver encodes the user's data into RMT data format, then the RMT transmitter can generate the waveforms according to the encoding artifacts. It is also possible to modulate a high-frequency carrier signal before being routed to a GPIO pad. RMT Receiver Overview The data path and control path of an RMT RX channel is illustrated in the figure below: The RMT receiver can sample incoming signals into RMT data format, and store the data in memory. It is also possible to tell the receiver the basic characteristics of the incoming signal, so that the signal's stop condition can be recognized, and signal glitches and noise can be filtered out. The RMT peripheral also supports demodulating the high-frequency carrier from the base signal. Functional Overview The description of the RMT functionality is divided into the following sections: Resource Allocation - covers how to allocate and properly configure RMT channels. It also covers how to recycle channels and other resources when they are no longer used. Carrier Modulation and Demodulation - describes how to modulate and demodulate the carrier signals for TX and RX channels respectively. Register Event Callbacks - covers how to register user-provided event callbacks to receive RMT channel events. Enable and Disable Channel - shows how to enable and disable the RMT channel. Initiate TX Transaction - describes the steps to initiate a transaction for a TX channel. Initiate RX Transaction - describes the steps to initiate a transaction for an RX channel. Multiple Channels Simultaneous Transmission - describes how to collect multiple channels into a sync group so that their transmissions can be started simultaneously. RMT Encoder - focuses on how to write a customized encoder by combining multiple primitive encoders that are provided by the driver. Power Management - describes how different clock sources affects power consumption. IRAM Safe - describes how disabling the cache affects the RMT driver, and tips to mitigate it. Thread Safety - lists which APIs are guaranteed to be thread-safe by the driver. Kconfig Options - describes the various Kconfig options supported by the RMT driver. Resource Allocation Both RMT TX and RX channels are represented by rmt_channel_handle_t in the driver. The driver internally manages which channels are available and hands out a free channel on request. Install RMT TX Channel To install an RMT TX channel, there is a configuration structure that needs to be given in advance rmt_tx_channel_config_t . The following list describes each member of the configuration structure. rmt_tx_channel_config_t::gpio_num sets the GPIO number used by the transmitter. rmt_tx_channel_config_t::clk_src selects the source clock for the RMT channel. The available clocks are listed in rmt_clock_source_t . Note that, the selected clock is also used by other channels, which means the user should ensure this configuration is the same when allocating other channels, regardless of TX or RX. For the effect on the power consumption of different clock sources, please refer to the Power Management section. rmt_tx_channel_config_t::resolution_hz sets the resolution of the internal tick counter. The timing parameter of the RMT signal is calculated based on this tick. rmt_tx_channel_config_t::mem_block_symbols has a slightly different meaning based on if the DMA backend is enabled or not. If the DMA is enabled via rmt_tx_channel_config_t::with_dma , then this field controls the size of the internal DMA buffer. To achieve a better throughput and smaller CPU overhead, you can set a larger value, e.g., 1024 . If DMA is not used, this field controls the size of the dedicated memory block owned by the channel, which should be at least 64. If the DMA is enabled via rmt_tx_channel_config_t::with_dma , then this field controls the size of the internal DMA buffer. To achieve a better throughput and smaller CPU overhead, you can set a larger value, e.g., 1024 . If DMA is not used, this field controls the size of the dedicated memory block owned by the channel, which should be at least 64. If the DMA is enabled via rmt_tx_channel_config_t::with_dma , then this field controls the size of the internal DMA buffer. To achieve a better throughput and smaller CPU overhead, you can set a larger value, e.g., 1024 . rmt_tx_channel_config_t::trans_queue_depth sets the depth of the internal transaction queue, the deeper the queue, the more transactions can be prepared in the backlog. rmt_tx_channel_config_t::invert_out is used to decide whether to invert the RMT signal before sending it to the GPIO pad. rmt_tx_channel_config_t::with_dma enables the DMA backend for the channel. Using the DMA allows a significant amount of the channel's workload to be offloaded from the CPU. However, the DMA backend is not available on all ESP chips, please refer to [TRM] before you enable this option. Or you might encounter a ESP_ERR_NOT_SUPPORTED error. rmt_tx_channel_config_t::io_loop_back enables both input and output capabilities on the channel's assigned GPIO. Thus, by binding a TX and RX channel to the same GPIO, loopback can be achieved. rmt_tx_channel_config_t::io_od_mode configures the channel's assigned GPIO as open-drain. When combined with rmt_tx_channel_config_t::io_loop_back , a bi-directional bus (e.g., 1-wire) can be achieved. rmt_tx_channel_config_t::intr_priority Set the priority of the interrupt. If set to 0 , then the driver will use a interrupt with low or medium priority (priority level may be one of 1,2 or 3), otherwise use the priority indicated by rmt_tx_channel_config_t::intr_priority . Please use the number form (1,2,3) , not the bitmask form ((1<<1),(1<<2),(1<<3)). Please pay attention that once the interrupt priority is set, it cannot be changed until rmt_del_channel() is called. Once the rmt_tx_channel_config_t structure is populated with mandatory parameters, users can call rmt_new_tx_channel() to allocate and initialize a TX channel. This function returns an RMT channel handle if it runs correctly. Specifically, when there are no more free channels in the RMT resource pool, this function returns ESP_ERR_NOT_FOUND error. If some feature (e.g., DMA backend) is not supported by the hardware, it returns ESP_ERR_NOT_SUPPORTED error. rmt_channel_handle_t tx_chan = NULL; rmt_tx_channel_config_t tx_chan_config = { .clk_src = RMT_CLK_SRC_DEFAULT, // select source clock .gpio_num = 0, // GPIO number .mem_block_symbols = 64, // memory block size, 64 * 4 = 256 Bytes .resolution_hz = 1 * 1000 * 1000, // 1 MHz tick resolution, i.e., 1 tick = 1 µs .trans_queue_depth = 4, // set the number of transactions that can pend in the background .flags.invert_out = false, // do not invert output signal .flags.with_dma = false, // do not need DMA backend }; ESP_ERROR_CHECK(rmt_new_tx_channel(&tx_chan_config, &tx_chan)); Install RMT RX Channel To install an RMT RX channel, there is a configuration structure that needs to be given in advance rmt_rx_channel_config_t . The following list describes each member of the configuration structure. rmt_rx_channel_config_t::gpio_num sets the GPIO number used by the receiver. rmt_rx_channel_config_t::clk_src selects the source clock for the RMT channel. The available clocks are listed in rmt_clock_source_t . Note that, the selected clock is also used by other channels, which means the user should ensure this configuration is the same when allocating other channels, regardless of TX or RX. For the effect on the power consumption of different clock sources, please refer to the Power Management section. rmt_rx_channel_config_t::resolution_hz sets the resolution of the internal tick counter. The timing parameter of the RMT signal is calculated based on this tick. rmt_rx_channel_config_t::mem_block_symbols has a slightly different meaning based on whether the DMA backend is enabled. If the DMA is enabled via rmt_rx_channel_config_t::with_dma , this field controls the maximum size of the DMA buffer. If DMA is not used, this field controls the size of the dedicated memory block owned by the channel, which should be at least 64. If the DMA is enabled via rmt_rx_channel_config_t::with_dma , this field controls the maximum size of the DMA buffer. If DMA is not used, this field controls the size of the dedicated memory block owned by the channel, which should be at least 64. If the DMA is enabled via rmt_rx_channel_config_t::with_dma , this field controls the maximum size of the DMA buffer. rmt_rx_channel_config_t::invert_in is used to invert the input signals before it is passed to the RMT receiver. The inversion is done by the GPIO matrix instead of by the RMT peripheral. rmt_rx_channel_config_t::with_dma enables the DMA backend for the channel. Using the DMA allows a significant amount of the channel's workload to be offloaded from the CPU. However, the DMA backend is not available on all ESP chips, please refer to [TRM] before you enable this option. Or you might encounter a ESP_ERR_NOT_SUPPORTED error. rmt_rx_channel_config_t::io_loop_back enables both input and output capabilities on the channel's assigned GPIO. Thus, by binding a TX and RX channel to the same GPIO, loopback can be achieved. rmt_rx_channel_config_t::intr_priority Set the priority of the interrupt. If set to 0 , then the driver will use a interrupt with low or medium priority (priority level may be one of 1,2 or 3), otherwise use the priority indicated by rmt_rx_channel_config_t::intr_priority . Please use the number form (1,2,3) , not the bitmask form ((1<<1),(1<<2),(1<<3)). Please pay attention that once the interrupt priority is set, it cannot be changed until rmt_del_channel() is called. Once the rmt_rx_channel_config_t structure is populated with mandatory parameters, users can call rmt_new_rx_channel() to allocate and initialize an RX channel. This function returns an RMT channel handle if it runs correctly. Specifically, when there are no more free channels in the RMT resource pool, this function returns ESP_ERR_NOT_FOUND error. If some feature (e.g., DMA backend) is not supported by the hardware, it returns ESP_ERR_NOT_SUPPORTED error. rmt_channel_handle_t rx_chan = NULL; rmt_rx_channel_config_t rx_chan_config = { .clk_src = RMT_CLK_SRC_DEFAULT, // select source clock .resolution_hz = 1 * 1000 * 1000, // 1 MHz tick resolution, i.e., 1 tick = 1 µs .mem_block_symbols = 64, // memory block size, 64 * 4 = 256 Bytes .gpio_num = 2, // GPIO number .flags.invert_in = false, // do not invert input signal .flags.with_dma = false, // do not need DMA backend }; ESP_ERROR_CHECK(rmt_new_rx_channel(&rx_chan_config, &rx_chan)); Note Due to a software limitation in the GPIO driver, when both TX and RX channels are bound to the same GPIO, ensure the RX Channel is initialized before the TX Channel. If the TX Channel was set up first, then during the RX Channel setup, the previous RMT TX Channel signal will be overridden by the GPIO control signal. Uninstall RMT Channel If a previously installed RMT channel is no longer needed, it is recommended to recycle the resources by calling rmt_del_channel() , which in return allows the underlying software and hardware resources to be reused for other purposes. Carrier Modulation and Demodulation The RMT transmitter can generate a carrier wave and modulate it onto the message signal. Compared to the message signal, the carrier signal's frequency is significantly higher. In addition, the user can only set the frequency and duty cycle for the carrier signal. The RMT receiver can demodulate the carrier signal from the incoming signal. Note that, carrier modulation and demodulation are not supported on all ESP chips, please refer to [TRM] before configuring the carrier, or you might encounter a ESP_ERR_NOT_SUPPORTED error. Carrier-related configurations lie in rmt_carrier_config_t : rmt_carrier_config_t::frequency_hz sets the carrier frequency, in Hz. rmt_carrier_config_t::duty_cycle sets the carrier duty cycle. rmt_carrier_config_t::polarity_active_low sets the carrier polarity, i.e., on which level the carrier is applied. rmt_carrier_config_t::always_on sets whether to output the carrier even when the data transmission has finished. This configuration is only valid for the TX channel. Note For the RX channel, we should not set the carrier frequency exactly to the theoretical value. It is recommended to leave a tolerance for the carrier frequency. For example, in the snippet below, we set the frequency to 25 KHz, instead of the 38 KHz configured on the TX side. The reason is that reflection and refraction occur when a signal travels through the air, leading to distortion on the receiver side. rmt_carrier_config_t tx_carrier_cfg = { .duty_cycle = 0.33, // duty cycle 33% .frequency_hz = 38000, // 38 KHz .flags.polarity_active_low = false, // carrier should be modulated to high level }; // modulate carrier to TX channel ESP_ERROR_CHECK(rmt_apply_carrier(tx_chan, &tx_carrier_cfg)); rmt_carrier_config_t rx_carrier_cfg = { .duty_cycle = 0.33, // duty cycle 33% .frequency_hz = 25000, // 25 KHz carrier, should be smaller than the transmitter's carrier frequency .flags.polarity_active_low = false, // the carrier is modulated to high level }; // demodulate carrier from RX channel ESP_ERROR_CHECK(rmt_apply_carrier(rx_chan, &rx_carrier_cfg)); Register Event Callbacks When an event occurs on an RMT channel (e.g., transmission or receiving is completed), the CPU is notified of this event via an interrupt. If you have some function that needs to be called when a particular events occur, you can register a callback for that event to the RMT driver's ISR (Interrupt Service Routine) by calling rmt_tx_register_event_callbacks() and rmt_rx_register_event_callbacks() for TX and RX channel respectively. Since the registered callback functions are called in the interrupt context, the user should ensure the callback function does not block, e.g., by making sure that only FreeRTOS APIs with the FromISR suffix are called from within the function. The callback function has a boolean return value used to indicate whether a higher priority task has been unblocked by the callback. The TX channel-supported event callbacks are listed in the rmt_tx_event_callbacks_t : rmt_tx_event_callbacks_t::on_trans_done sets a callback function for the "trans-done" event. The function prototype is declared in rmt_tx_done_callback_t . The RX channel-supported event callbacks are listed in the rmt_rx_event_callbacks_t : rmt_rx_event_callbacks_t::on_recv_done sets a callback function for "receive-done" event. The function prototype is declared in rmt_rx_done_callback_t . Users can save their own context in rmt_tx_register_event_callbacks() and rmt_rx_register_event_callbacks() as well, via the parameter user_data . The user data is directly passed to each callback function. In the callback function, users can fetch the event-specific data that is filled by the driver in the edata . Note that the edata pointer is only valid during the callback. The TX-done event data is defined in rmt_tx_done_event_data_t : rmt_tx_done_event_data_t::num_symbols indicates the number of transmitted RMT symbols. This also reflects the size of the encoding artifacts. Please note, this value accounts for the EOF symbol as well, which is appended by the driver to mark the end of one transaction. The RX-complete event data is defined in rmt_rx_done_event_data_t : rmt_rx_done_event_data_t::received_symbols points to the received RMT symbols. These symbols are saved in the buffer parameter of the rmt_receive() function. Users should not free this receive buffer before the callback returns. rmt_rx_done_event_data_t::num_symbols indicates the number of received RMT symbols. This value is not larger than the buffer_size parameter of rmt_receive() function. If the buffer_size is not sufficient to accommodate all the received RMT symbols, the driver only keeps the maximum number of symbols that the buffer can hold, and excess symbols are discarded or ignored. Enable and Disable Channel rmt_enable() must be called in advance before transmitting or receiving RMT symbols. For TX channels, enabling a channel enables a specific interrupt and prepares the hardware to dispatch transactions. For RX channels, enabling a channel enables an interrupt, but the receiver is not started during this time, as the characteristics of the incoming signal have yet to be specified. The receiver is started in rmt_receive() . rmt_disable() does the opposite by disabling the interrupt and clearing any pending interrupts. The transmitter and receiver are disabled as well. ESP_ERROR_CHECK(rmt_enable(tx_chan)); ESP_ERROR_CHECK(rmt_enable(rx_chan)); Initiate TX Transaction RMT is a special communication peripheral, as it is unable to transmit raw byte streams like SPI and I2C. RMT can only send data in its own format rmt_symbol_word_t . However, the hardware does not help to convert the user data into RMT symbols, this can only be done in software by the so-called RMT Encoder. The encoder is responsible for encoding user data into RMT symbols and then writing to the RMT memory block or the DMA buffer. For how to create an RMT encoder, please refer to RMT Encoder. Once you created an encoder, you can initiate a TX transaction by calling rmt_transmit() . This function takes several positional parameters like channel handle, encoder handle, and payload buffer. Besides, you also need to provide a transmission-specific configuration in rmt_transmit_config_t : rmt_transmit_config_t::loop_count sets the number of transmission loops. After the transmitter has finished one round of transmission, it can restart the same transmission again if this value is not set to zero. As the loop is controlled by hardware, the RMT channel can be used to generate many periodic sequences with minimal CPU intervention. Setting rmt_transmit_config_t::loop_count to -1 means an infinite loop transmission. In this case, the channel does not stop until rmt_disable() is called. The "trans-done" event is not generated as well. Setting rmt_transmit_config_t::loop_count to a positive number means finite number of iterations. In this case, the "trans-done" event is when the specified number of iterations have completed. Setting rmt_transmit_config_t::loop_count to -1 means an infinite loop transmission. In this case, the channel does not stop until rmt_disable() is called. The "trans-done" event is not generated as well. Setting rmt_transmit_config_t::loop_count to a positive number means finite number of iterations. In this case, the "trans-done" event is when the specified number of iterations have completed. Note The loop transmit feature is not supported on all ESP chips, please refer to [TRM] before you configure this option, or you might encounter ESP_ERR_NOT_SUPPORTED error. Setting rmt_transmit_config_t::loop_count to -1 means an infinite loop transmission. In this case, the channel does not stop until rmt_disable() is called. The "trans-done" event is not generated as well. rmt_transmit_config_t::eot_level sets the output level when the transmitter finishes working or stops working by calling rmt_disable() . rmt_transmit_config_t::queue_nonblocking sets whether to wait for a free slot in the transaction queue when it is full. If this value is set to true , then the function will return with an error code ESP_ERR_INVALID_STATE when the queue is full. Otherwise, the function will block until a free slot is available in the queue. Note There is a limitation in the transmission size if the rmt_transmit_config_t::loop_count is set to non-zero, i.e., to enable the loop feature. The encoded RMT symbols should not exceed the capacity of the RMT hardware memory block size, or you might see an error message like encoding artifacts can't exceed hw memory block for loop transmission . If you have to start a large transaction by loop, you can try either of the following methods. Increase the rmt_tx_channel_config_t::mem_block_symbols . This approach does not work if the DMA backend is also enabled. Customize an encoder and construct an infinite loop in the encoding function. See also RMT Encoder. Internally, rmt_transmit() constructs a transaction descriptor and sends it to a job queue, which is dispatched in the ISR. So it is possible that the transaction is not started yet when rmt_transmit() returns. To ensure all pending transactions to complete, the user can use rmt_tx_wait_all_done() . Multiple Channels Simultaneous Transmission In some real-time control applications (e.g., to make two robotic arms move simultaneously), you do not want any time drift between different channels. The RMT driver can help to manage this by creating a so-called Sync Manager. The sync manager is represented by rmt_sync_manager_handle_t in the driver. The procedure of RMT sync transmission is shown as follows: Install RMT Sync Manager To create a sync manager, the user needs to tell which channels are going to be managed in the rmt_sync_manager_config_t : rmt_sync_manager_config_t::tx_channel_array points to the array of TX channels to be managed. rmt_sync_manager_config_t::array_size sets the number of channels to be managed. rmt_new_sync_manager() can return a manager handle on success. This function could also fail due to various errors such as invalid arguments, etc. Especially, when the sync manager has been installed before, and there are no hardware resources to create another manager, this function reports ESP_ERR_NOT_FOUND error. In addition, if the sync manager is not supported by the hardware, it reports a ESP_ERR_NOT_SUPPORTED error. Please refer to [TRM] before using the sync manager feature. Start Transmission Simultaneously For any managed TX channel, it does not start the machine until rmt_transmit() has been called on all channels in rmt_sync_manager_config_t::tx_channel_array . Before that, the channel is just put in a waiting state. TX channels will usually complete their transactions at different times due to differing transactions, thus resulting in a loss of sync. So before restarting a simultaneous transmission, the user needs to call rmt_sync_reset() to synchronize all channels again. Calling rmt_del_sync_manager() can recycle the sync manager and enable the channels to initiate transactions independently afterward. rmt_channel_handle_t tx_channels[2] = {NULL}; // declare two channels int tx_gpio_number[2] = {0, 2}; // install channels one by one for (int i = 0; i < 2; i++) { rmt_tx_channel_config_t tx_chan_config = { .clk_src = RMT_CLK_SRC_DEFAULT, // select source clock .gpio_num = tx_gpio_number[i], // GPIO number .mem_block_symbols = 64, // memory block size, 64 * 4 = 256 Bytes .resolution_hz = 1 * 1000 * 1000, // 1 MHz resolution .trans_queue_depth = 1, // set the number of transactions that can pend in the background }; ESP_ERROR_CHECK(rmt_new_tx_channel(&tx_chan_config, &tx_channels[i])); } // install sync manager rmt_sync_manager_handle_t synchro = NULL; rmt_sync_manager_config_t synchro_config = { .tx_channel_array = tx_channels, .array_size = sizeof(tx_channels) / sizeof(tx_channels[0]), }; ESP_ERROR_CHECK(rmt_new_sync_manager(&synchro_config, &synchro)); ESP_ERROR_CHECK(rmt_transmit(tx_channels[0], led_strip_encoders[0], led_data, led_num * 3, &transmit_config)); // tx_channels[0] does not start transmission until call of `rmt_transmit()` for tx_channels[1] returns ESP_ERROR_CHECK(rmt_transmit(tx_channels[1], led_strip_encoders[1], led_data, led_num * 3, &transmit_config)); Initiate RX Transaction As also discussed in the Enable and Disable Channel, calling rmt_enable() does not prepare an RX to receive RMT symbols. The user needs to specify the basic characteristics of the incoming signals in rmt_receive_config_t : rmt_receive_config_t::signal_range_min_ns specifies the minimal valid pulse duration in either high or low logic levels. A pulse width that is smaller than this value is treated as a glitch, and ignored by the hardware. rmt_receive_config_t::signal_range_max_ns specifies the maximum valid pulse duration in either high or low logic levels. A pulse width that is bigger than this value is treated as Stop Signal, and the receiver generates receive-complete event immediately. The RMT receiver starts the RX machine after the user calls rmt_receive() with the provided configuration above. Note that, this configuration is transaction specific, which means, to start a new round of reception, the user needs to set the rmt_receive_config_t again. The receiver saves the incoming signals into its internal memory block or DMA buffer, in the format of rmt_symbol_word_t . Due to the limited size of the memory block, the RMT receiver can only save short frames whose length is not longer than the memory block capacity. Long frames are truncated by the hardware, and the driver reports an error message: hw buffer too small, received symbols truncated . The copy destination should be provided in the buffer parameter of rmt_receive() function. If this buffer overlfows due to an insufficient buffer size, the receiver can continue to work, but overflowed symbols are dropped and the following error message is reported: user buffer too small, received symbols truncated . Please take care of the lifecycle of the buffer parameter, ensuring that the buffer is not recycled before the receiver is finished or stopped. The receiver is stopped by the driver when it finishes working, i.e., receive a signal whose duration is bigger than rmt_receive_config_t::signal_range_max_ns . The user needs to call rmt_receive() again to restart the receiver, if necessary. The user can get the received data in the rmt_rx_event_callbacks_t::on_recv_done callback. See also Register Event Callbacks for more information. static bool example_rmt_rx_done_callback(rmt_channel_handle_t channel, const rmt_rx_done_event_data_t *edata, void *user_data) { BaseType_t high_task_wakeup = pdFALSE; QueueHandle_t receive_queue = (QueueHandle_t)user_data; // send the received RMT symbols to the parser task xQueueSendFromISR(receive_queue, edata, &high_task_wakeup); // return whether any task is woken up return high_task_wakeup == pdTRUE; } QueueHandle_t receive_queue = xQueueCreate(1, sizeof(rmt_rx_done_event_data_t)); rmt_rx_event_callbacks_t cbs = { .on_recv_done = example_rmt_rx_done_callback, }; ESP_ERROR_CHECK(rmt_rx_register_event_callbacks(rx_channel, &cbs, receive_queue)); // the following timing requirement is based on NEC protocol rmt_receive_config_t receive_config = { .signal_range_min_ns = 1250, // the shortest duration for NEC signal is 560 µs, 1250 ns < 560 µs, valid signal is not treated as noise .signal_range_max_ns = 12000000, // the longest duration for NEC signal is 9000 µs, 12000000 ns > 9000 µs, the receive does not stop early }; rmt_symbol_word_t raw_symbols[64]; // 64 symbols should be sufficient for a standard NEC frame // ready to receive ESP_ERROR_CHECK(rmt_receive(rx_channel, raw_symbols, sizeof(raw_symbols), &receive_config)); // wait for the RX-done signal rmt_rx_done_event_data_t rx_data; xQueueReceive(receive_queue, &rx_data, portMAX_DELAY); // parse the received symbols example_parse_nec_frame(rx_data.received_symbols, rx_data.num_symbols); RMT Encoder An RMT encoder is part of the RMT TX transaction, whose responsibility is to generate and write the correct RMT symbols into hardware memory or DMA buffer at a specific time. There are some special restrictions for an encoding function: During a single transaction, the encoding function may be called multiple times. This is necessary because the target RMT memory block cannot hold all the artifacts at once. To overcome this limitation, the driver utilizes a ping-pong approach, where the encoding session is divided into multiple parts. This means that the encoder needs to keep track of its state to continue encoding from where it left off in the previous part. The encoding function is running in the ISR context. To speed up the encoding session, it is highly recommended to put the encoding function into IRAM. This can also avoid the cache miss during encoding. To help get started with the RMT driver faster, some commonly used encoders are provided out-of-the-box. They can either work alone or be chained together into a new encoder. See also Composite Pattern for the principle behind it. The driver has defined the encoder interface in rmt_encoder_t , it contains the following functions: rmt_encoder_t::encode is the fundamental function of an encoder. This is where the encoding session happens. The function might be called multiple times within a single transaction. The encode function should return the state of the current encoding session. The supported states are listed in the rmt_encode_state_t . If the result contains RMT_ENCODING_COMPLETE , it means the current encoder has finished work. If the result contains RMT_ENCODING_MEM_FULL , the program needs to yield from the current session, as there is no space to save more encoding artifacts. The function might be called multiple times within a single transaction. The encode function should return the state of the current encoding session. The supported states are listed in the rmt_encode_state_t . If the result contains RMT_ENCODING_COMPLETE , it means the current encoder has finished work. If the result contains RMT_ENCODING_MEM_FULL , the program needs to yield from the current session, as there is no space to save more encoding artifacts. The function might be called multiple times within a single transaction. The encode function should return the state of the current encoding session. rmt_encoder_t::reset should reset the encoder state back to the initial state (the RMT encoder is stateful). If the RMT transmitter is manually stopped without resetting its corresponding encoder, subsequent encoding session can be erroneous. This function is also called implicitly in rmt_disable() . If the RMT transmitter is manually stopped without resetting its corresponding encoder, subsequent encoding session can be erroneous. This function is also called implicitly in rmt_disable() . If the RMT transmitter is manually stopped without resetting its corresponding encoder, subsequent encoding session can be erroneous. rmt_encoder_t::del should free the resources allocated by the encoder. Copy Encoder A copy encoder is created by calling rmt_new_copy_encoder() . A copy encoder's main functionality is to copy the RMT symbols from user space into the driver layer. It is usually used to encode const data, i.e., data does not change at runtime after initialization such as the leading code in the IR protocol. A configuration structure rmt_copy_encoder_config_t should be provided in advance before calling rmt_new_copy_encoder() . Currently, this configuration is reserved for future expansion, and has no specific use or setting items for now. Bytes Encoder A bytes encoder is created by calling rmt_new_bytes_encoder() . The bytes encoder's main functionality is to convert the user space byte stream into RMT symbols dynamically. It is usually used to encode dynamic data, e.g., the address and command fields in the IR protocol. A configuration structure rmt_bytes_encoder_config_t should be provided in advance before calling rmt_new_bytes_encoder() : rmt_bytes_encoder_config_t::bit0 and rmt_bytes_encoder_config_t::bit1 are necessary to specify the encoder how to represent bit zero and bit one in the format of rmt_symbol_word_t . rmt_bytes_encoder_config_t::msb_first sets the bit endianess of each byte. If it is set to true, the encoder encodes the Most Significant Bit first. Otherwise, it encodes the Least Significant Bit first. Besides the primitive encoders provided by the driver, the user can implement his own encoder by chaining the existing encoders together. A common encoder chain is shown as follows: Customize RMT Encoder for NEC Protocol This section demonstrates how to write an NEC encoder. The NEC IR protocol uses pulse distance encoding of the message bits. Each pulse burst is 562.5 µs in length, logical bits are transmitted as follows. It is worth mentioning that the least significant bit of each byte is sent first. Logical 0 : a 562.5 µs pulse burst followed by a 562.5 µs space, with a total transmit time of 1.125 ms Logical 1 : a 562.5 µs pulse burst followed by a 1.6875 ms space, with a total transmit time of 2.25 ms When a key is pressed on the remote controller, the transmitted message includes the following elements in the specified order: 9 ms leading pulse burst, also called the "AGC pulse" 4.5 ms space 8-bit address for the receiving device 8-bit logical inverse of the address 8-bit command 8-bit logical inverse of the command a final 562.5 µs pulse burst to signify the end of message transmission Then you can construct the NEC rmt_encoder_t::encode function in the same order, for example: // IR NEC scan code representation typedef struct { uint16_t address; uint16_t command; } ir_nec_scan_code_t; // construct an encoder by combining primitive encoders typedef struct { rmt_encoder_t base; // the base "class" declares the standard encoder interface rmt_encoder_t *copy_encoder; // use the copy_encoder to encode the leading and ending pulse rmt_encoder_t *bytes_encoder; // use the bytes_encoder to encode the address and command data rmt_symbol_word_t nec_leading_symbol; // NEC leading code with RMT representation rmt_symbol_word_t nec_ending_symbol; // NEC ending code with RMT representation int state; // record the current encoding state, i.e., we are in which encoding phase } rmt_ir_nec_encoder_t; static size_t rmt_encode_ir_nec(rmt_encoder_t *encoder, rmt_channel_handle_t channel, const void *primary_data, size_t data_size, rmt_encode_state_t *ret_state) { rmt_ir_nec_encoder_t *nec_encoder = __containerof(encoder, rmt_ir_nec_encoder_t, base); rmt_encode_state_t session_state = RMT_ENCODING_RESET; rmt_encode_state_t state = RMT_ENCODING_RESET; size_t encoded_symbols = 0; ir_nec_scan_code_t *scan_code = (ir_nec_scan_code_t *)primary_data; rmt_encoder_handle_t copy_encoder = nec_encoder->copy_encoder; rmt_encoder_handle_t bytes_encoder = nec_encoder->bytes_encoder; switch (nec_encoder->state) { case 0: // send leading code encoded_symbols += copy_encoder->encode(copy_encoder, channel, &nec_encoder->nec_leading_symbol, sizeof(rmt_symbol_word_t), &session_state); if (session_state & RMT_ENCODING_COMPLETE) { nec_encoder->state = 1; // we can only switch to the next state when the current encoder finished } if (session_state & RMT_ENCODING_MEM_FULL) { state |= RMT_ENCODING_MEM_FULL; goto out; // yield if there is no free space to put other encoding artifacts } // fall-through case 1: // send address encoded_symbols += bytes_encoder->encode(bytes_encoder, channel, &scan_code->address, sizeof(uint16_t), &session_state); if (session_state & RMT_ENCODING_COMPLETE) { nec_encoder->state = 2; // we can only switch to the next state when the current encoder finished } if (session_state & RMT_ENCODING_MEM_FULL) { state |= RMT_ENCODING_MEM_FULL; goto out; // yield if there is no free space to put other encoding artifacts } // fall-through case 2: // send command encoded_symbols += bytes_encoder->encode(bytes_encoder, channel, &scan_code->command, sizeof(uint16_t), &session_state); if (session_state & RMT_ENCODING_COMPLETE) { nec_encoder->state = 3; // we can only switch to the next state when the current encoder finished } if (session_state & RMT_ENCODING_MEM_FULL) { state |= RMT_ENCODING_MEM_FULL; goto out; // yield if there is no free space to put other encoding artifacts } // fall-through case 3: // send ending code encoded_symbols += copy_encoder->encode(copy_encoder, channel, &nec_encoder->nec_ending_symbol, sizeof(rmt_symbol_word_t), &session_state); if (session_state & RMT_ENCODING_COMPLETE) { nec_encoder->state = RMT_ENCODING_RESET; // back to the initial encoding session state |= RMT_ENCODING_COMPLETE; // telling the caller the NEC encoding has finished } if (session_state & RMT_ENCODING_MEM_FULL) { state |= RMT_ENCODING_MEM_FULL; goto out; // yield if there is no free space to put other encoding artifacts } } out: *ret_state = state; return encoded_symbols; } A full sample code can be found in peripherals/rmt/ir_nec_transceiver. In the above snippet, we use a switch-case and several goto statements to implement a Finite-state machine . With this pattern, users can construct much more complex IR protocols. Power Management When power management is enabled, i.e., CONFIG_PM_ENABLE is on, the system adjusts the APB frequency before going into Light-sleep, thus potentially changing the resolution of the RMT internal counter. However, the driver can prevent the system from changing APB frequency by acquiring a power management lock of type ESP_PM_APB_FREQ_MAX . Whenever the user creates an RMT channel that has selected RMT_CLK_SRC_APB as the clock source, the driver guarantees that the power management lock is acquired after the channel enabled by rmt_enable() . Likewise, the driver releases the lock after rmt_disable() is called for the same channel. This also reveals that the rmt_enable() and rmt_disable() should appear in pairs. If the channel clock source is selected to others like RMT_CLK_SRC_XTAL , then the driver does not install a power management lock for it, which is more suitable for a low-power application as long as the source clock can still provide sufficient resolution. IRAM Safe By default, the RMT interrupt is deferred when the Cache is disabled for reasons like writing or erasing the main Flash. Thus the transaction-done interrupt does not get handled in time, which is not acceptable in a real-time application. What is worse, when the RMT transaction relies on ping-pong interrupt to successively encode or copy RMT symbols, a delayed interrupt can lead to an unpredictable result. There is a Kconfig option CONFIG_RMT_ISR_IRAM_SAFE that has the following features: Enable the interrupt being serviced even when the cache is disabled Place all functions used by the ISR into IRAM 2 Place the driver object into DRAM in case it is mapped to PSRAM by accident This Kconfig option allows the interrupt handler to run while the cache is disabled but comes at the cost of increased IRAM consumption. Another Kconfig option CONFIG_RMT_RECV_FUNC_IN_IRAM can place rmt_receive() into the IRAM as well. So that the receive function can be used even when the flash cache is disabled. Thread Safety The factory function rmt_new_tx_channel() , rmt_new_rx_channel() and rmt_new_sync_manager() are guaranteed to be thread-safe by the driver, which means, user can call them from different RTOS tasks without protection by extra locks. Other functions that take the rmt_channel_handle_t and rmt_sync_manager_handle_t as the first positional parameter, are not thread-safe. which means the user should avoid calling them from multiple tasks. The following functions are allowed to use under ISR context as well. Kconfig Options CONFIG_RMT_ISR_IRAM_SAFE controls whether the default ISR handler can work when cache is disabled, see also IRAM Safe for more information. CONFIG_RMT_ENABLE_DEBUG_LOG is used to enable the debug log at the cost of increased firmware binary size. CONFIG_RMT_RECV_FUNC_IN_IRAM controls where to place the RMT receive function (IRAM or Flash), see IRAM Safe for more information. Application Examples RMT-based RGB LED strip customized encoder: peripherals/rmt/led_strip RMT IR NEC protocol encoding and decoding: peripherals/rmt/ir_nec_transceiver RMT transactions in queue: peripherals/rmt/musical_buzzer RMT-based stepper motor with S-curve algorithm: : peripherals/rmt/stepper_motor RMT infinite loop for driving DShot ESC: peripherals/rmt/dshot_esc RMT simulate 1-wire protocol (take DS18B20 as example): peripherals/rmt/onewire FAQ Why the RMT encoder results in more data than expected? The RMT encoding takes place in the ISR context. If your RMT encoding session takes a long time (e.g., by logging debug information) or the encoding session is deferred somehow because of interrupt latency, then it is possible the transmitting becomes faster than the encoding. As a result, the encoder can not prepare the next data in time, leading to the transmitter sending the previous data again. There is no way to ask the transmitter to stop and wait. You can mitigate the issue by combining the following ways: Increase the rmt_tx_channel_config_t::mem_block_symbols , in steps of 64. Place the encoding function in the IRAM. Enables the rmt_tx_channel_config_t::with_dma if it is available for your chip. API Reference Header File This header file can be included with: #include "driver/rmt_tx.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t rmt_new_tx_channel(const rmt_tx_channel_config_t *config, rmt_channel_handle_t *ret_chan) Create a RMT TX channel. Parameters config -- [in] TX channel configurations ret_chan -- [out] Returned generic RMT channel handle config -- [in] TX channel configurations ret_chan -- [out] Returned generic RMT channel handle config -- [in] TX channel configurations Returns ESP_OK: Create RMT TX channel successfully ESP_ERR_INVALID_ARG: Create RMT TX channel failed because of invalid argument ESP_ERR_NO_MEM: Create RMT TX channel failed because out of memory ESP_ERR_NOT_FOUND: Create RMT TX channel failed because all RMT channels are used up and no more free one ESP_ERR_NOT_SUPPORTED: Create RMT TX channel failed because some feature is not supported by hardware, e.g. DMA feature is not supported by hardware ESP_FAIL: Create RMT TX channel failed because of other error ESP_OK: Create RMT TX channel successfully ESP_ERR_INVALID_ARG: Create RMT TX channel failed because of invalid argument ESP_ERR_NO_MEM: Create RMT TX channel failed because out of memory ESP_ERR_NOT_FOUND: Create RMT TX channel failed because all RMT channels are used up and no more free one ESP_ERR_NOT_SUPPORTED: Create RMT TX channel failed because some feature is not supported by hardware, e.g. DMA feature is not supported by hardware ESP_FAIL: Create RMT TX channel failed because of other error ESP_OK: Create RMT TX channel successfully Parameters config -- [in] TX channel configurations ret_chan -- [out] Returned generic RMT channel handle Returns ESP_OK: Create RMT TX channel successfully ESP_ERR_INVALID_ARG: Create RMT TX channel failed because of invalid argument ESP_ERR_NO_MEM: Create RMT TX channel failed because out of memory ESP_ERR_NOT_FOUND: Create RMT TX channel failed because all RMT channels are used up and no more free one ESP_ERR_NOT_SUPPORTED: Create RMT TX channel failed because some feature is not supported by hardware, e.g. DMA feature is not supported by hardware ESP_FAIL: Create RMT TX channel failed because of other error esp_err_t rmt_transmit(rmt_channel_handle_t tx_channel, rmt_encoder_handle_t encoder, const void *payload, size_t payload_bytes, const rmt_transmit_config_t *config) Transmit data by RMT TX channel. Note This function constructs a transaction descriptor then pushes to a queue. The transaction will not start immediately if there's another one under processing. Based on the setting of rmt_transmit_config_t::queue_nonblocking , if there're too many transactions pending in the queue, this function can block until it has free slot, otherwise just return quickly. Note The data to be transmitted will be encoded into RMT symbols by the specific encoder . Parameters tx_channel -- [in] RMT TX channel that created by rmt_new_tx_channel() encoder -- [in] RMT encoder that created by various factory APIs like rmt_new_bytes_encoder() payload -- [in] The raw data to be encoded into RMT symbols payload_bytes -- [in] Size of the payload in bytes config -- [in] Transmission specific configuration tx_channel -- [in] RMT TX channel that created by rmt_new_tx_channel() encoder -- [in] RMT encoder that created by various factory APIs like rmt_new_bytes_encoder() payload -- [in] The raw data to be encoded into RMT symbols payload_bytes -- [in] Size of the payload in bytes config -- [in] Transmission specific configuration tx_channel -- [in] RMT TX channel that created by rmt_new_tx_channel() Returns ESP_OK: Transmit data successfully ESP_ERR_INVALID_ARG: Transmit data failed because of invalid argument ESP_ERR_INVALID_STATE: Transmit data failed because channel is not enabled ESP_ERR_NOT_SUPPORTED: Transmit data failed because some feature is not supported by hardware, e.g. unsupported loop count ESP_FAIL: Transmit data failed because of other error ESP_OK: Transmit data successfully ESP_ERR_INVALID_ARG: Transmit data failed because of invalid argument ESP_ERR_INVALID_STATE: Transmit data failed because channel is not enabled ESP_ERR_NOT_SUPPORTED: Transmit data failed because some feature is not supported by hardware, e.g. unsupported loop count ESP_FAIL: Transmit data failed because of other error ESP_OK: Transmit data successfully Parameters tx_channel -- [in] RMT TX channel that created by rmt_new_tx_channel() encoder -- [in] RMT encoder that created by various factory APIs like rmt_new_bytes_encoder() payload -- [in] The raw data to be encoded into RMT symbols payload_bytes -- [in] Size of the payload in bytes config -- [in] Transmission specific configuration Returns ESP_OK: Transmit data successfully ESP_ERR_INVALID_ARG: Transmit data failed because of invalid argument ESP_ERR_INVALID_STATE: Transmit data failed because channel is not enabled ESP_ERR_NOT_SUPPORTED: Transmit data failed because some feature is not supported by hardware, e.g. unsupported loop count ESP_FAIL: Transmit data failed because of other error esp_err_t rmt_tx_wait_all_done(rmt_channel_handle_t tx_channel, int timeout_ms) Wait for all pending TX transactions done. Note This function will block forever if the pending transaction can't be finished within a limited time (e.g. an infinite loop transaction). See also rmt_disable() for how to terminate a working channel. Parameters tx_channel -- [in] RMT TX channel that created by rmt_new_tx_channel() timeout_ms -- [in] Wait timeout, in ms. Specially, -1 means to wait forever. tx_channel -- [in] RMT TX channel that created by rmt_new_tx_channel() timeout_ms -- [in] Wait timeout, in ms. Specially, -1 means to wait forever. tx_channel -- [in] RMT TX channel that created by rmt_new_tx_channel() Returns ESP_OK: Flush transactions successfully ESP_ERR_INVALID_ARG: Flush transactions failed because of invalid argument ESP_ERR_TIMEOUT: Flush transactions failed because of timeout ESP_FAIL: Flush transactions failed because of other error ESP_OK: Flush transactions successfully ESP_ERR_INVALID_ARG: Flush transactions failed because of invalid argument ESP_ERR_TIMEOUT: Flush transactions failed because of timeout ESP_FAIL: Flush transactions failed because of other error ESP_OK: Flush transactions successfully Parameters tx_channel -- [in] RMT TX channel that created by rmt_new_tx_channel() timeout_ms -- [in] Wait timeout, in ms. Specially, -1 means to wait forever. Returns ESP_OK: Flush transactions successfully ESP_ERR_INVALID_ARG: Flush transactions failed because of invalid argument ESP_ERR_TIMEOUT: Flush transactions failed because of timeout ESP_FAIL: Flush transactions failed because of other error esp_err_t rmt_tx_register_event_callbacks(rmt_channel_handle_t tx_channel, const rmt_tx_event_callbacks_t *cbs, void *user_data) Set event callbacks for RMT TX channel. Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbs structure to NULL. Note When CONFIG_RMT_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. The user_data should also reside in SRAM. Parameters tx_channel -- [in] RMT generic channel that created by rmt_new_tx_channel() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly tx_channel -- [in] RMT generic channel that created by rmt_new_tx_channel() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly tx_channel -- [in] RMT generic channel that created by rmt_new_tx_channel() Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully Parameters tx_channel -- [in] RMT generic channel that created by rmt_new_tx_channel() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error esp_err_t rmt_new_sync_manager(const rmt_sync_manager_config_t *config, rmt_sync_manager_handle_t *ret_synchro) Create a synchronization manager for multiple TX channels, so that the managed channel can start transmitting at the same time. Note All the channels to be managed should be enabled by rmt_enable() before put them into sync manager. Parameters config -- [in] Synchronization manager configuration ret_synchro -- [out] Returned synchronization manager handle config -- [in] Synchronization manager configuration ret_synchro -- [out] Returned synchronization manager handle config -- [in] Synchronization manager configuration Returns ESP_OK: Create sync manager successfully ESP_ERR_INVALID_ARG: Create sync manager failed because of invalid argument ESP_ERR_NOT_SUPPORTED: Create sync manager failed because it is not supported by hardware ESP_ERR_INVALID_STATE: Create sync manager failed because not all channels are enabled ESP_ERR_NO_MEM: Create sync manager failed because out of memory ESP_ERR_NOT_FOUND: Create sync manager failed because all sync controllers are used up and no more free one ESP_FAIL: Create sync manager failed because of other error ESP_OK: Create sync manager successfully ESP_ERR_INVALID_ARG: Create sync manager failed because of invalid argument ESP_ERR_NOT_SUPPORTED: Create sync manager failed because it is not supported by hardware ESP_ERR_INVALID_STATE: Create sync manager failed because not all channels are enabled ESP_ERR_NO_MEM: Create sync manager failed because out of memory ESP_ERR_NOT_FOUND: Create sync manager failed because all sync controllers are used up and no more free one ESP_FAIL: Create sync manager failed because of other error ESP_OK: Create sync manager successfully Parameters config -- [in] Synchronization manager configuration ret_synchro -- [out] Returned synchronization manager handle Returns ESP_OK: Create sync manager successfully ESP_ERR_INVALID_ARG: Create sync manager failed because of invalid argument ESP_ERR_NOT_SUPPORTED: Create sync manager failed because it is not supported by hardware ESP_ERR_INVALID_STATE: Create sync manager failed because not all channels are enabled ESP_ERR_NO_MEM: Create sync manager failed because out of memory ESP_ERR_NOT_FOUND: Create sync manager failed because all sync controllers are used up and no more free one ESP_FAIL: Create sync manager failed because of other error esp_err_t rmt_del_sync_manager(rmt_sync_manager_handle_t synchro) Delete synchronization manager. Parameters synchro -- [in] Synchronization manager handle returned from rmt_new_sync_manager() Returns ESP_OK: Delete the synchronization manager successfully ESP_ERR_INVALID_ARG: Delete the synchronization manager failed because of invalid argument ESP_FAIL: Delete the synchronization manager failed because of other error ESP_OK: Delete the synchronization manager successfully ESP_ERR_INVALID_ARG: Delete the synchronization manager failed because of invalid argument ESP_FAIL: Delete the synchronization manager failed because of other error ESP_OK: Delete the synchronization manager successfully Parameters synchro -- [in] Synchronization manager handle returned from rmt_new_sync_manager() Returns ESP_OK: Delete the synchronization manager successfully ESP_ERR_INVALID_ARG: Delete the synchronization manager failed because of invalid argument ESP_FAIL: Delete the synchronization manager failed because of other error esp_err_t rmt_sync_reset(rmt_sync_manager_handle_t synchro) Reset synchronization manager. Parameters synchro -- [in] Synchronization manager handle returned from rmt_new_sync_manager() Returns ESP_OK: Reset the synchronization manager successfully ESP_ERR_INVALID_ARG: Reset the synchronization manager failed because of invalid argument ESP_FAIL: Reset the synchronization manager failed because of other error ESP_OK: Reset the synchronization manager successfully ESP_ERR_INVALID_ARG: Reset the synchronization manager failed because of invalid argument ESP_FAIL: Reset the synchronization manager failed because of other error ESP_OK: Reset the synchronization manager successfully Parameters synchro -- [in] Synchronization manager handle returned from rmt_new_sync_manager() Returns ESP_OK: Reset the synchronization manager successfully ESP_ERR_INVALID_ARG: Reset the synchronization manager failed because of invalid argument ESP_FAIL: Reset the synchronization manager failed because of other error Structures struct rmt_tx_event_callbacks_t Group of RMT TX callbacks. Note The callbacks are all running under ISR environment Note When CONFIG_RMT_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. Public Members rmt_tx_done_callback_t on_trans_done Event callback, invoked when transmission is finished rmt_tx_done_callback_t on_trans_done Event callback, invoked when transmission is finished rmt_tx_done_callback_t on_trans_done struct rmt_tx_channel_config_t RMT TX channel specific configuration. Public Members gpio_num_t gpio_num GPIO number used by RMT TX channel. Set to -1 if unused gpio_num_t gpio_num GPIO number used by RMT TX channel. Set to -1 if unused rmt_clock_source_t clk_src Clock source of RMT TX channel, channels in the same group must use the same clock source rmt_clock_source_t clk_src Clock source of RMT TX channel, channels in the same group must use the same clock source uint32_t resolution_hz Channel clock resolution, in Hz uint32_t resolution_hz Channel clock resolution, in Hz size_t mem_block_symbols Size of memory block, in number of rmt_symbol_word_t , must be an even. In the DMA mode, this field controls the DMA buffer size, it can be set to a large value; In the normal mode, this field controls the number of RMT memory block that will be used by the channel. size_t mem_block_symbols Size of memory block, in number of rmt_symbol_word_t , must be an even. In the DMA mode, this field controls the DMA buffer size, it can be set to a large value; In the normal mode, this field controls the number of RMT memory block that will be used by the channel. size_t trans_queue_depth Depth of internal transfer queue, increase this value can support more transfers pending in the background size_t trans_queue_depth Depth of internal transfer queue, increase this value can support more transfers pending in the background int intr_priority RMT interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) int intr_priority RMT interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) uint32_t invert_out Whether to invert the RMT channel signal before output to GPIO pad uint32_t invert_out Whether to invert the RMT channel signal before output to GPIO pad uint32_t with_dma If set, the driver will allocate an RMT channel with DMA capability uint32_t with_dma If set, the driver will allocate an RMT channel with DMA capability uint32_t io_loop_back The signal output from the GPIO will be fed to the input path as well uint32_t io_loop_back The signal output from the GPIO will be fed to the input path as well uint32_t io_od_mode Configure the GPIO as open-drain mode uint32_t io_od_mode Configure the GPIO as open-drain mode struct rmt_tx_channel_config_t::[anonymous] flags TX channel config flags struct rmt_tx_channel_config_t::[anonymous] flags TX channel config flags gpio_num_t gpio_num struct rmt_transmit_config_t RMT transmit specific configuration. Public Members int loop_count Specify the times of transmission in a loop, -1 means transmitting in an infinite loop int loop_count Specify the times of transmission in a loop, -1 means transmitting in an infinite loop uint32_t eot_level Set the output level for the "End Of Transmission" uint32_t eot_level Set the output level for the "End Of Transmission" uint32_t queue_nonblocking If set, when the transaction queue is full, driver will not block the thread but return directly uint32_t queue_nonblocking If set, when the transaction queue is full, driver will not block the thread but return directly struct rmt_transmit_config_t::[anonymous] flags Transmit specific config flags struct rmt_transmit_config_t::[anonymous] flags Transmit specific config flags int loop_count struct rmt_sync_manager_config_t Synchronous manager configuration. Public Members const rmt_channel_handle_t *tx_channel_array Array of TX channels that are about to be managed by a synchronous controller const rmt_channel_handle_t *tx_channel_array Array of TX channels that are about to be managed by a synchronous controller size_t array_size Size of the tx_channel_array size_t array_size Size of the tx_channel_array const rmt_channel_handle_t *tx_channel_array Header File This header file can be included with: #include "driver/rmt_rx.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t rmt_new_rx_channel(const rmt_rx_channel_config_t *config, rmt_channel_handle_t *ret_chan) Create a RMT RX channel. Parameters config -- [in] RX channel configurations ret_chan -- [out] Returned generic RMT channel handle config -- [in] RX channel configurations ret_chan -- [out] Returned generic RMT channel handle config -- [in] RX channel configurations Returns ESP_OK: Create RMT RX channel successfully ESP_ERR_INVALID_ARG: Create RMT RX channel failed because of invalid argument ESP_ERR_NO_MEM: Create RMT RX channel failed because out of memory ESP_ERR_NOT_FOUND: Create RMT RX channel failed because all RMT channels are used up and no more free one ESP_ERR_NOT_SUPPORTED: Create RMT RX channel failed because some feature is not supported by hardware, e.g. DMA feature is not supported by hardware ESP_FAIL: Create RMT RX channel failed because of other error ESP_OK: Create RMT RX channel successfully ESP_ERR_INVALID_ARG: Create RMT RX channel failed because of invalid argument ESP_ERR_NO_MEM: Create RMT RX channel failed because out of memory ESP_ERR_NOT_FOUND: Create RMT RX channel failed because all RMT channels are used up and no more free one ESP_ERR_NOT_SUPPORTED: Create RMT RX channel failed because some feature is not supported by hardware, e.g. DMA feature is not supported by hardware ESP_FAIL: Create RMT RX channel failed because of other error ESP_OK: Create RMT RX channel successfully Parameters config -- [in] RX channel configurations ret_chan -- [out] Returned generic RMT channel handle Returns ESP_OK: Create RMT RX channel successfully ESP_ERR_INVALID_ARG: Create RMT RX channel failed because of invalid argument ESP_ERR_NO_MEM: Create RMT RX channel failed because out of memory ESP_ERR_NOT_FOUND: Create RMT RX channel failed because all RMT channels are used up and no more free one ESP_ERR_NOT_SUPPORTED: Create RMT RX channel failed because some feature is not supported by hardware, e.g. DMA feature is not supported by hardware ESP_FAIL: Create RMT RX channel failed because of other error esp_err_t rmt_receive(rmt_channel_handle_t rx_channel, void *buffer, size_t buffer_size, const rmt_receive_config_t *config) Initiate a receive job for RMT RX channel. Note This function is non-blocking, it initiates a new receive job and then returns. User should check the received data from the on_recv_done callback that registered by rmt_rx_register_event_callbacks() . Note This function can also be called in ISR context. Note If you want this function to work even when the flash cache is disabled, please enable the CONFIG_RMT_RECV_FUNC_IN_IRAM option. Parameters rx_channel -- [in] RMT RX channel that created by rmt_new_rx_channel() buffer -- [in] The buffer to store the received RMT symbols buffer_size -- [in] size of the buffer , in bytes config -- [in] Receive specific configurations rx_channel -- [in] RMT RX channel that created by rmt_new_rx_channel() buffer -- [in] The buffer to store the received RMT symbols buffer_size -- [in] size of the buffer , in bytes config -- [in] Receive specific configurations rx_channel -- [in] RMT RX channel that created by rmt_new_rx_channel() Returns ESP_OK: Initiate receive job successfully ESP_ERR_INVALID_ARG: Initiate receive job failed because of invalid argument ESP_ERR_INVALID_STATE: Initiate receive job failed because channel is not enabled ESP_FAIL: Initiate receive job failed because of other error ESP_OK: Initiate receive job successfully ESP_ERR_INVALID_ARG: Initiate receive job failed because of invalid argument ESP_ERR_INVALID_STATE: Initiate receive job failed because channel is not enabled ESP_FAIL: Initiate receive job failed because of other error ESP_OK: Initiate receive job successfully Parameters rx_channel -- [in] RMT RX channel that created by rmt_new_rx_channel() buffer -- [in] The buffer to store the received RMT symbols buffer_size -- [in] size of the buffer , in bytes config -- [in] Receive specific configurations Returns ESP_OK: Initiate receive job successfully ESP_ERR_INVALID_ARG: Initiate receive job failed because of invalid argument ESP_ERR_INVALID_STATE: Initiate receive job failed because channel is not enabled ESP_FAIL: Initiate receive job failed because of other error esp_err_t rmt_rx_register_event_callbacks(rmt_channel_handle_t rx_channel, const rmt_rx_event_callbacks_t *cbs, void *user_data) Set callbacks for RMT RX channel. Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbs structure to NULL. Note When CONFIG_RMT_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. The user_data should also reside in SRAM. Parameters rx_channel -- [in] RMT generic channel that created by rmt_new_rx_channel() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly rx_channel -- [in] RMT generic channel that created by rmt_new_rx_channel() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly rx_channel -- [in] RMT generic channel that created by rmt_new_rx_channel() Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error ESP_OK: Set event callbacks successfully Parameters rx_channel -- [in] RMT generic channel that created by rmt_new_rx_channel() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error Structures struct rmt_rx_event_callbacks_t Group of RMT RX callbacks. Note The callbacks are all running under ISR environment Note When CONFIG_RMT_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. Public Members rmt_rx_done_callback_t on_recv_done Event callback, invoked when one RMT channel receiving transaction completes rmt_rx_done_callback_t on_recv_done Event callback, invoked when one RMT channel receiving transaction completes rmt_rx_done_callback_t on_recv_done struct rmt_rx_channel_config_t RMT RX channel specific configuration. Public Members gpio_num_t gpio_num GPIO number used by RMT RX channel. Set to -1 if unused gpio_num_t gpio_num GPIO number used by RMT RX channel. Set to -1 if unused rmt_clock_source_t clk_src Clock source of RMT RX channel, channels in the same group must use the same clock source rmt_clock_source_t clk_src Clock source of RMT RX channel, channels in the same group must use the same clock source uint32_t resolution_hz Channel clock resolution, in Hz uint32_t resolution_hz Channel clock resolution, in Hz size_t mem_block_symbols Size of memory block, in number of rmt_symbol_word_t , must be an even. In the DMA mode, this field controls the DMA buffer size, it can be set to a large value (e.g. 1024); In the normal mode, this field controls the number of RMT memory block that will be used by the channel. size_t mem_block_symbols Size of memory block, in number of rmt_symbol_word_t , must be an even. In the DMA mode, this field controls the DMA buffer size, it can be set to a large value (e.g. 1024); In the normal mode, this field controls the number of RMT memory block that will be used by the channel. uint32_t invert_in Whether to invert the incoming RMT channel signal uint32_t invert_in Whether to invert the incoming RMT channel signal uint32_t with_dma If set, the driver will allocate an RMT channel with DMA capability uint32_t with_dma If set, the driver will allocate an RMT channel with DMA capability uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well struct rmt_rx_channel_config_t::[anonymous] flags RX channel config flags struct rmt_rx_channel_config_t::[anonymous] flags RX channel config flags int intr_priority RMT interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) int intr_priority RMT interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) gpio_num_t gpio_num struct rmt_receive_config_t RMT receive specific configuration. Header File This header file can be included with: #include "driver/rmt_common.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t rmt_del_channel(rmt_channel_handle_t channel) Delete an RMT channel. Parameters channel -- [in] RMT generic channel that created by rmt_new_tx_channel() or rmt_new_rx_channel() Returns ESP_OK: Delete RMT channel successfully ESP_ERR_INVALID_ARG: Delete RMT channel failed because of invalid argument ESP_ERR_INVALID_STATE: Delete RMT channel failed because it is still in working ESP_FAIL: Delete RMT channel failed because of other error ESP_OK: Delete RMT channel successfully ESP_ERR_INVALID_ARG: Delete RMT channel failed because of invalid argument ESP_ERR_INVALID_STATE: Delete RMT channel failed because it is still in working ESP_FAIL: Delete RMT channel failed because of other error ESP_OK: Delete RMT channel successfully Parameters channel -- [in] RMT generic channel that created by rmt_new_tx_channel() or rmt_new_rx_channel() Returns ESP_OK: Delete RMT channel successfully ESP_ERR_INVALID_ARG: Delete RMT channel failed because of invalid argument ESP_ERR_INVALID_STATE: Delete RMT channel failed because it is still in working ESP_FAIL: Delete RMT channel failed because of other error esp_err_t rmt_apply_carrier(rmt_channel_handle_t channel, const rmt_carrier_config_t *config) Apply modulation feature for TX channel or demodulation feature for RX channel. Parameters channel -- [in] RMT generic channel that created by rmt_new_tx_channel() or rmt_new_rx_channel() config -- [in] Carrier configuration. Specially, a NULL config means to disable the carrier modulation or demodulation feature channel -- [in] RMT generic channel that created by rmt_new_tx_channel() or rmt_new_rx_channel() config -- [in] Carrier configuration. Specially, a NULL config means to disable the carrier modulation or demodulation feature channel -- [in] RMT generic channel that created by rmt_new_tx_channel() or rmt_new_rx_channel() Returns ESP_OK: Apply carrier configuration successfully ESP_ERR_INVALID_ARG: Apply carrier configuration failed because of invalid argument ESP_FAIL: Apply carrier configuration failed because of other error ESP_OK: Apply carrier configuration successfully ESP_ERR_INVALID_ARG: Apply carrier configuration failed because of invalid argument ESP_FAIL: Apply carrier configuration failed because of other error ESP_OK: Apply carrier configuration successfully Parameters channel -- [in] RMT generic channel that created by rmt_new_tx_channel() or rmt_new_rx_channel() config -- [in] Carrier configuration. Specially, a NULL config means to disable the carrier modulation or demodulation feature Returns ESP_OK: Apply carrier configuration successfully ESP_ERR_INVALID_ARG: Apply carrier configuration failed because of invalid argument ESP_FAIL: Apply carrier configuration failed because of other error esp_err_t rmt_enable(rmt_channel_handle_t channel) Enable the RMT channel. Note This function will acquire a PM lock that might be installed during channel allocation Parameters channel -- [in] RMT generic channel that created by rmt_new_tx_channel() or rmt_new_rx_channel() Returns ESP_OK: Enable RMT channel successfully ESP_ERR_INVALID_ARG: Enable RMT channel failed because of invalid argument ESP_ERR_INVALID_STATE: Enable RMT channel failed because it's enabled already ESP_FAIL: Enable RMT channel failed because of other error ESP_OK: Enable RMT channel successfully ESP_ERR_INVALID_ARG: Enable RMT channel failed because of invalid argument ESP_ERR_INVALID_STATE: Enable RMT channel failed because it's enabled already ESP_FAIL: Enable RMT channel failed because of other error ESP_OK: Enable RMT channel successfully Parameters channel -- [in] RMT generic channel that created by rmt_new_tx_channel() or rmt_new_rx_channel() Returns ESP_OK: Enable RMT channel successfully ESP_ERR_INVALID_ARG: Enable RMT channel failed because of invalid argument ESP_ERR_INVALID_STATE: Enable RMT channel failed because it's enabled already ESP_FAIL: Enable RMT channel failed because of other error esp_err_t rmt_disable(rmt_channel_handle_t channel) Disable the RMT channel. Note This function will release a PM lock that might be installed during channel allocation Parameters channel -- [in] RMT generic channel that created by rmt_new_tx_channel() or rmt_new_rx_channel() Returns ESP_OK: Disable RMT channel successfully ESP_ERR_INVALID_ARG: Disable RMT channel failed because of invalid argument ESP_ERR_INVALID_STATE: Disable RMT channel failed because it's not enabled yet ESP_FAIL: Disable RMT channel failed because of other error ESP_OK: Disable RMT channel successfully ESP_ERR_INVALID_ARG: Disable RMT channel failed because of invalid argument ESP_ERR_INVALID_STATE: Disable RMT channel failed because it's not enabled yet ESP_FAIL: Disable RMT channel failed because of other error ESP_OK: Disable RMT channel successfully Parameters channel -- [in] RMT generic channel that created by rmt_new_tx_channel() or rmt_new_rx_channel() Returns ESP_OK: Disable RMT channel successfully ESP_ERR_INVALID_ARG: Disable RMT channel failed because of invalid argument ESP_ERR_INVALID_STATE: Disable RMT channel failed because it's not enabled yet ESP_FAIL: Disable RMT channel failed because of other error Structures struct rmt_carrier_config_t RMT carrier wave configuration (for either modulation or demodulation) Public Members uint32_t frequency_hz Carrier wave frequency, in Hz, 0 means disabling the carrier uint32_t frequency_hz Carrier wave frequency, in Hz, 0 means disabling the carrier float duty_cycle Carrier wave duty cycle (0~100%) float duty_cycle Carrier wave duty cycle (0~100%) uint32_t polarity_active_low Specify the polarity of carrier, by default it's modulated to base signal's high level uint32_t polarity_active_low Specify the polarity of carrier, by default it's modulated to base signal's high level uint32_t always_on If set, the carrier can always exist even there's not transfer undergoing uint32_t always_on If set, the carrier can always exist even there's not transfer undergoing struct rmt_carrier_config_t::[anonymous] flags Carrier config flags struct rmt_carrier_config_t::[anonymous] flags Carrier config flags uint32_t frequency_hz Header File This header file can be included with: #include "driver/rmt_encoder.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t rmt_new_bytes_encoder(const rmt_bytes_encoder_config_t *config, rmt_encoder_handle_t *ret_encoder) Create RMT bytes encoder, which can encode byte stream into RMT symbols. Parameters config -- [in] Bytes encoder configuration ret_encoder -- [out] Returned encoder handle config -- [in] Bytes encoder configuration ret_encoder -- [out] Returned encoder handle config -- [in] Bytes encoder configuration Returns ESP_OK: Create RMT bytes encoder successfully ESP_ERR_INVALID_ARG: Create RMT bytes encoder failed because of invalid argument ESP_ERR_NO_MEM: Create RMT bytes encoder failed because out of memory ESP_FAIL: Create RMT bytes encoder failed because of other error ESP_OK: Create RMT bytes encoder successfully ESP_ERR_INVALID_ARG: Create RMT bytes encoder failed because of invalid argument ESP_ERR_NO_MEM: Create RMT bytes encoder failed because out of memory ESP_FAIL: Create RMT bytes encoder failed because of other error ESP_OK: Create RMT bytes encoder successfully Parameters config -- [in] Bytes encoder configuration ret_encoder -- [out] Returned encoder handle Returns ESP_OK: Create RMT bytes encoder successfully ESP_ERR_INVALID_ARG: Create RMT bytes encoder failed because of invalid argument ESP_ERR_NO_MEM: Create RMT bytes encoder failed because out of memory ESP_FAIL: Create RMT bytes encoder failed because of other error esp_err_t rmt_bytes_encoder_update_config(rmt_encoder_handle_t bytes_encoder, const rmt_bytes_encoder_config_t *config) Update the configuration of the bytes encoder. Note The configurations of the bytes encoder is also set up by rmt_new_bytes_encoder() . This function is used to update the configuration of the bytes encoder at runtime. Parameters bytes_encoder -- [in] Bytes encoder handle, created by e.g rmt_new_bytes_encoder() config -- [in] Bytes encoder configuration bytes_encoder -- [in] Bytes encoder handle, created by e.g rmt_new_bytes_encoder() config -- [in] Bytes encoder configuration bytes_encoder -- [in] Bytes encoder handle, created by e.g rmt_new_bytes_encoder() Returns ESP_OK: Update RMT bytes encoder successfully ESP_ERR_INVALID_ARG: Update RMT bytes encoder failed because of invalid argument ESP_FAIL: Update RMT bytes encoder failed because of other error ESP_OK: Update RMT bytes encoder successfully ESP_ERR_INVALID_ARG: Update RMT bytes encoder failed because of invalid argument ESP_FAIL: Update RMT bytes encoder failed because of other error ESP_OK: Update RMT bytes encoder successfully Parameters bytes_encoder -- [in] Bytes encoder handle, created by e.g rmt_new_bytes_encoder() config -- [in] Bytes encoder configuration Returns ESP_OK: Update RMT bytes encoder successfully ESP_ERR_INVALID_ARG: Update RMT bytes encoder failed because of invalid argument ESP_FAIL: Update RMT bytes encoder failed because of other error esp_err_t rmt_new_copy_encoder(const rmt_copy_encoder_config_t *config, rmt_encoder_handle_t *ret_encoder) Create RMT copy encoder, which copies the given RMT symbols into RMT memory. Parameters config -- [in] Copy encoder configuration ret_encoder -- [out] Returned encoder handle config -- [in] Copy encoder configuration ret_encoder -- [out] Returned encoder handle config -- [in] Copy encoder configuration Returns ESP_OK: Create RMT copy encoder successfully ESP_ERR_INVALID_ARG: Create RMT copy encoder failed because of invalid argument ESP_ERR_NO_MEM: Create RMT copy encoder failed because out of memory ESP_FAIL: Create RMT copy encoder failed because of other error ESP_OK: Create RMT copy encoder successfully ESP_ERR_INVALID_ARG: Create RMT copy encoder failed because of invalid argument ESP_ERR_NO_MEM: Create RMT copy encoder failed because out of memory ESP_FAIL: Create RMT copy encoder failed because of other error ESP_OK: Create RMT copy encoder successfully Parameters config -- [in] Copy encoder configuration ret_encoder -- [out] Returned encoder handle Returns ESP_OK: Create RMT copy encoder successfully ESP_ERR_INVALID_ARG: Create RMT copy encoder failed because of invalid argument ESP_ERR_NO_MEM: Create RMT copy encoder failed because out of memory ESP_FAIL: Create RMT copy encoder failed because of other error esp_err_t rmt_del_encoder(rmt_encoder_handle_t encoder) Delete RMT encoder. Parameters encoder -- [in] RMT encoder handle, created by e.g rmt_new_bytes_encoder() Returns ESP_OK: Delete RMT encoder successfully ESP_ERR_INVALID_ARG: Delete RMT encoder failed because of invalid argument ESP_FAIL: Delete RMT encoder failed because of other error ESP_OK: Delete RMT encoder successfully ESP_ERR_INVALID_ARG: Delete RMT encoder failed because of invalid argument ESP_FAIL: Delete RMT encoder failed because of other error ESP_OK: Delete RMT encoder successfully Parameters encoder -- [in] RMT encoder handle, created by e.g rmt_new_bytes_encoder() Returns ESP_OK: Delete RMT encoder successfully ESP_ERR_INVALID_ARG: Delete RMT encoder failed because of invalid argument ESP_FAIL: Delete RMT encoder failed because of other error esp_err_t rmt_encoder_reset(rmt_encoder_handle_t encoder) Reset RMT encoder. Parameters encoder -- [in] RMT encoder handle, created by e.g rmt_new_bytes_encoder() Returns ESP_OK: Reset RMT encoder successfully ESP_ERR_INVALID_ARG: Reset RMT encoder failed because of invalid argument ESP_FAIL: Reset RMT encoder failed because of other error ESP_OK: Reset RMT encoder successfully ESP_ERR_INVALID_ARG: Reset RMT encoder failed because of invalid argument ESP_FAIL: Reset RMT encoder failed because of other error ESP_OK: Reset RMT encoder successfully Parameters encoder -- [in] RMT encoder handle, created by e.g rmt_new_bytes_encoder() Returns ESP_OK: Reset RMT encoder successfully ESP_ERR_INVALID_ARG: Reset RMT encoder failed because of invalid argument ESP_FAIL: Reset RMT encoder failed because of other error void *rmt_alloc_encoder_mem(size_t size) A helper function to allocate a proper memory for RMT encoder. Parameters size -- Size of memory to be allocated Returns Pointer to the allocated memory if the allocation is successful, NULL otherwise Parameters size -- Size of memory to be allocated Returns Pointer to the allocated memory if the allocation is successful, NULL otherwise Structures struct rmt_encoder_t Interface of RMT encoder. Public Members size_t (*encode)(rmt_encoder_t *encoder, rmt_channel_handle_t tx_channel, const void *primary_data, size_t data_size, rmt_encode_state_t *ret_state) Encode the user data into RMT symbols and write into RMT memory. Note The encoding function will also be called from an ISR context, thus the function must not call any blocking API. Note It's recommended to put this function implementation in the IRAM, to achieve a high performance and less interrupt latency. Param encoder [in] Encoder handle Param tx_channel [in] RMT TX channel handle, returned from rmt_new_tx_channel() Param primary_data [in] App data to be encoded into RMT symbols Param data_size [in] Size of primary_data, in bytes Param ret_state [out] Returned current encoder's state Return Number of RMT symbols that the primary data has been encoded into Param encoder [in] Encoder handle Param tx_channel [in] RMT TX channel handle, returned from rmt_new_tx_channel() Param primary_data [in] App data to be encoded into RMT symbols Param data_size [in] Size of primary_data, in bytes Param ret_state [out] Returned current encoder's state Return Number of RMT symbols that the primary data has been encoded into size_t (*encode)(rmt_encoder_t *encoder, rmt_channel_handle_t tx_channel, const void *primary_data, size_t data_size, rmt_encode_state_t *ret_state) Encode the user data into RMT symbols and write into RMT memory. Note The encoding function will also be called from an ISR context, thus the function must not call any blocking API. Note It's recommended to put this function implementation in the IRAM, to achieve a high performance and less interrupt latency. Param encoder [in] Encoder handle Param tx_channel [in] RMT TX channel handle, returned from rmt_new_tx_channel() Param primary_data [in] App data to be encoded into RMT symbols Param data_size [in] Size of primary_data, in bytes Param ret_state [out] Returned current encoder's state Return Number of RMT symbols that the primary data has been encoded into esp_err_t (*reset)(rmt_encoder_t *encoder) Reset encoding state. Param encoder [in] Encoder handle Return ESP_OK: reset encoder successfully ESP_FAIL: reset encoder failed ESP_OK: reset encoder successfully ESP_FAIL: reset encoder failed ESP_OK: reset encoder successfully Param encoder [in] Encoder handle Return ESP_OK: reset encoder successfully ESP_FAIL: reset encoder failed esp_err_t (*reset)(rmt_encoder_t *encoder) Reset encoding state. Param encoder [in] Encoder handle Return ESP_OK: reset encoder successfully ESP_FAIL: reset encoder failed esp_err_t (*del)(rmt_encoder_t *encoder) Delete encoder object. Param encoder [in] Encoder handle Return ESP_OK: delete encoder successfully ESP_FAIL: delete encoder failed ESP_OK: delete encoder successfully ESP_FAIL: delete encoder failed ESP_OK: delete encoder successfully Param encoder [in] Encoder handle Return ESP_OK: delete encoder successfully ESP_FAIL: delete encoder failed esp_err_t (*del)(rmt_encoder_t *encoder) Delete encoder object. Param encoder [in] Encoder handle Return ESP_OK: delete encoder successfully ESP_FAIL: delete encoder failed size_t (*encode)(rmt_encoder_t *encoder, rmt_channel_handle_t tx_channel, const void *primary_data, size_t data_size, rmt_encode_state_t *ret_state) struct rmt_bytes_encoder_config_t Bytes encoder configuration. Public Members rmt_symbol_word_t bit0 How to represent BIT0 in RMT symbol rmt_symbol_word_t bit0 How to represent BIT0 in RMT symbol rmt_symbol_word_t bit1 How to represent BIT1 in RMT symbol rmt_symbol_word_t bit1 How to represent BIT1 in RMT symbol uint32_t msb_first Whether to encode MSB bit first uint32_t msb_first Whether to encode MSB bit first struct rmt_bytes_encoder_config_t::[anonymous] flags Encoder config flag struct rmt_bytes_encoder_config_t::[anonymous] flags Encoder config flag rmt_symbol_word_t bit0 struct rmt_copy_encoder_config_t Copy encoder configuration. Enumerations enum rmt_encode_state_t RMT encoding state. Values: enumerator RMT_ENCODING_RESET The encoding session is in reset state enumerator RMT_ENCODING_RESET The encoding session is in reset state enumerator RMT_ENCODING_COMPLETE The encoding session is finished, the caller can continue with subsequent encoding enumerator RMT_ENCODING_COMPLETE The encoding session is finished, the caller can continue with subsequent encoding enumerator RMT_ENCODING_MEM_FULL The encoding artifact memory is full, the caller should return from current encoding session enumerator RMT_ENCODING_MEM_FULL The encoding artifact memory is full, the caller should return from current encoding session enumerator RMT_ENCODING_RESET Header File This header file can be included with: #include "driver/rmt_types.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Structures struct rmt_tx_done_event_data_t Type of RMT TX done event data. Public Members size_t num_symbols The number of transmitted RMT symbols, including one EOF symbol, which is appended by the driver to mark the end of a transmission. For a loop transmission, this value only counts for one round. size_t num_symbols The number of transmitted RMT symbols, including one EOF symbol, which is appended by the driver to mark the end of a transmission. For a loop transmission, this value only counts for one round. size_t num_symbols struct rmt_rx_done_event_data_t Type of RMT RX done event data. Public Members rmt_symbol_word_t *received_symbols Point to the received RMT symbols rmt_symbol_word_t *received_symbols Point to the received RMT symbols size_t num_symbols The number of received RMT symbols size_t num_symbols The number of received RMT symbols rmt_symbol_word_t *received_symbols Type Definitions typedef struct rmt_channel_t *rmt_channel_handle_t Type of RMT channel handle. typedef struct rmt_sync_manager_t *rmt_sync_manager_handle_t Type of RMT synchronization manager handle. typedef struct rmt_encoder_t *rmt_encoder_handle_t Type of RMT encoder handle. typedef bool (*rmt_tx_done_callback_t)(rmt_channel_handle_t tx_chan, const rmt_tx_done_event_data_t *edata, void *user_ctx) Prototype of RMT event callback. Param tx_chan [in] RMT channel handle, created from rmt_new_tx_channel() Param edata [in] Point to RMT event data. The lifecycle of this pointer memory is inside this function, user should copy it into static memory if used outside this function. Param user_ctx [in] User registered context, passed from rmt_tx_register_event_callbacks() Return Whether a high priority task has been waken up by this callback function Param tx_chan [in] RMT channel handle, created from rmt_new_tx_channel() Param edata [in] Point to RMT event data. The lifecycle of this pointer memory is inside this function, user should copy it into static memory if used outside this function. Param user_ctx [in] User registered context, passed from rmt_tx_register_event_callbacks() Return Whether a high priority task has been waken up by this callback function typedef bool (*rmt_rx_done_callback_t)(rmt_channel_handle_t rx_chan, const rmt_rx_done_event_data_t *edata, void *user_ctx) Prototype of RMT event callback. Param rx_chan [in] RMT channel handle, created from rmt_new_rx_channel() Param edata [in] Point to RMT event data. The lifecycle of this pointer memory is inside this function, user should copy it into static memory if used outside this function. Param user_ctx [in] User registered context, passed from rmt_rx_register_event_callbacks() Return Whether a high priority task has been waken up by this function Param rx_chan [in] RMT channel handle, created from rmt_new_rx_channel() Param edata [in] Point to RMT event data. The lifecycle of this pointer memory is inside this function, user should copy it into static memory if used outside this function. Param user_ctx [in] User registered context, passed from rmt_rx_register_event_callbacks() Return Whether a high priority task has been waken up by this function Header File This header file can be included with: #include "hal/rmt_types.h" Unions union rmt_symbol_word_t #include <rmt_types.h> The layout of RMT symbol stored in memory, which is decided by the hardware design. Type Definitions typedef soc_periph_rmt_clk_src_t rmt_clock_source_t RMT group clock source. Note User should select the clock source based on the power and resolution requirement 1 Different ESP chip series might have different numbers of RMT channels. Please refer to [TRM] for details. The driver does not forbid you from applying for more RMT channels, but it returns an error when there are no hardware resources available. Please always check the return value when doing Resource Allocation. 2 The callback function, e.g., rmt_tx_event_callbacks_t::on_trans_done , and the functions invoked by itself should also reside in IRAM, users need to take care of this by themselves.
Remote Control Transceiver (RMT) Introduction The RMT (Remote Control Transceiver) peripheral was designed to act as an infrared transceiver. However, due to the flexibility of its data format, RMT can be extended to a versatile and general-purpose transceiver, transmitting or receiving many other types of signals. From the perspective of network layering, the RMT hardware contains both physical and data link layers. The physical layer defines the communication media and bit signal representation. The data link layer defines the format of an RMT frame. The minimal data unit in the frame is called the RMT symbol, which is represented by rmt_symbol_word_t in the driver. ESP32 contains multiple channels in the RMT peripheral 1. Each channel can be independently configured as either transmitter or receiver. Typically, the RMT peripheral can be used in the following scenarios: Transmit or receive infrared signals, with any IR protocols, e.g., NEC General-purpose sequence generator Transmit signals in a hardware-controlled loop, with a finite or infinite number of times Multi-channel simultaneous transmission Modulate the carrier to the output signal or demodulate the carrier from the input signal Layout of RMT Symbols The RMT hardware defines data in its own pattern -- the RMT symbol. The diagram below illustrates the bit fields of an RMT symbol. Each symbol consists of two pairs of two values. The first value in the pair is a 15-bit value representing the signal's duration in units of RMT ticks. The second in the pair is a 1-bit value representing the signal's logic level, i.e., high or low. RMT Transmitter Overview The data path and control path of an RMT TX channel is illustrated in the figure below: The driver encodes the user's data into RMT data format, then the RMT transmitter can generate the waveforms according to the encoding artifacts. It is also possible to modulate a high-frequency carrier signal before being routed to a GPIO pad. RMT Receiver Overview The data path and control path of an RMT RX channel is illustrated in the figure below: The RMT receiver can sample incoming signals into RMT data format, and store the data in memory. It is also possible to tell the receiver the basic characteristics of the incoming signal, so that the signal's stop condition can be recognized, and signal glitches and noise can be filtered out. The RMT peripheral also supports demodulating the high-frequency carrier from the base signal. Functional Overview The description of the RMT functionality is divided into the following sections: Resource Allocation - covers how to allocate and properly configure RMT channels. It also covers how to recycle channels and other resources when they are no longer used. Carrier Modulation and Demodulation - describes how to modulate and demodulate the carrier signals for TX and RX channels respectively. Register Event Callbacks - covers how to register user-provided event callbacks to receive RMT channel events. Enable and Disable Channel - shows how to enable and disable the RMT channel. Initiate TX Transaction - describes the steps to initiate a transaction for a TX channel. Initiate RX Transaction - describes the steps to initiate a transaction for an RX channel. Multiple Channels Simultaneous Transmission - describes how to collect multiple channels into a sync group so that their transmissions can be started simultaneously. RMT Encoder - focuses on how to write a customized encoder by combining multiple primitive encoders that are provided by the driver. Power Management - describes how different clock sources affects power consumption. IRAM Safe - describes how disabling the cache affects the RMT driver, and tips to mitigate it. Thread Safety - lists which APIs are guaranteed to be thread-safe by the driver. Kconfig Options - describes the various Kconfig options supported by the RMT driver. Resource Allocation Both RMT TX and RX channels are represented by rmt_channel_handle_t in the driver. The driver internally manages which channels are available and hands out a free channel on request. Install RMT TX Channel To install an RMT TX channel, there is a configuration structure that needs to be given in advance rmt_tx_channel_config_t. The following list describes each member of the configuration structure. rmt_tx_channel_config_t::gpio_numsets the GPIO number used by the transmitter. rmt_tx_channel_config_t::clk_srcselects the source clock for the RMT channel. The available clocks are listed in rmt_clock_source_t. Note that, the selected clock is also used by other channels, which means the user should ensure this configuration is the same when allocating other channels, regardless of TX or RX. For the effect on the power consumption of different clock sources, please refer to the Power Management section. rmt_tx_channel_config_t::resolution_hzsets the resolution of the internal tick counter. The timing parameter of the RMT signal is calculated based on this tick. rmt_tx_channel_config_t::mem_block_symbolshas a slightly different meaning based on if the DMA backend is enabled or not. If the DMA is enabled via rmt_tx_channel_config_t::with_dma, then this field controls the size of the internal DMA buffer. To achieve a better throughput and smaller CPU overhead, you can set a larger value, e.g., 1024. If DMA is not used, this field controls the size of the dedicated memory block owned by the channel, which should be at least 64. - rmt_tx_channel_config_t::trans_queue_depthsets the depth of the internal transaction queue, the deeper the queue, the more transactions can be prepared in the backlog. rmt_tx_channel_config_t::invert_outis used to decide whether to invert the RMT signal before sending it to the GPIO pad. rmt_tx_channel_config_t::with_dmaenables the DMA backend for the channel. Using the DMA allows a significant amount of the channel's workload to be offloaded from the CPU. However, the DMA backend is not available on all ESP chips, please refer to [TRM] before you enable this option. Or you might encounter a ESP_ERR_NOT_SUPPORTEDerror. rmt_tx_channel_config_t::io_loop_backenables both input and output capabilities on the channel's assigned GPIO. Thus, by binding a TX and RX channel to the same GPIO, loopback can be achieved. rmt_tx_channel_config_t::io_od_modeconfigures the channel's assigned GPIO as open-drain. When combined with rmt_tx_channel_config_t::io_loop_back, a bi-directional bus (e.g., 1-wire) can be achieved. rmt_tx_channel_config_t::intr_prioritySet the priority of the interrupt. If set to 0, then the driver will use a interrupt with low or medium priority (priority level may be one of 1,2 or 3), otherwise use the priority indicated by rmt_tx_channel_config_t::intr_priority. Please use the number form (1,2,3) , not the bitmask form ((1<<1),(1<<2),(1<<3)). Please pay attention that once the interrupt priority is set, it cannot be changed until rmt_del_channel()is called. Once the rmt_tx_channel_config_t structure is populated with mandatory parameters, users can call rmt_new_tx_channel() to allocate and initialize a TX channel. This function returns an RMT channel handle if it runs correctly. Specifically, when there are no more free channels in the RMT resource pool, this function returns ESP_ERR_NOT_FOUND error. If some feature (e.g., DMA backend) is not supported by the hardware, it returns ESP_ERR_NOT_SUPPORTED error. rmt_channel_handle_t tx_chan = NULL; rmt_tx_channel_config_t tx_chan_config = { .clk_src = RMT_CLK_SRC_DEFAULT, // select source clock .gpio_num = 0, // GPIO number .mem_block_symbols = 64, // memory block size, 64 * 4 = 256 Bytes .resolution_hz = 1 * 1000 * 1000, // 1 MHz tick resolution, i.e., 1 tick = 1 µs .trans_queue_depth = 4, // set the number of transactions that can pend in the background .flags.invert_out = false, // do not invert output signal .flags.with_dma = false, // do not need DMA backend }; ESP_ERROR_CHECK(rmt_new_tx_channel(&tx_chan_config, &tx_chan)); Install RMT RX Channel To install an RMT RX channel, there is a configuration structure that needs to be given in advance rmt_rx_channel_config_t. The following list describes each member of the configuration structure. rmt_rx_channel_config_t::gpio_numsets the GPIO number used by the receiver. rmt_rx_channel_config_t::clk_srcselects the source clock for the RMT channel. The available clocks are listed in rmt_clock_source_t. Note that, the selected clock is also used by other channels, which means the user should ensure this configuration is the same when allocating other channels, regardless of TX or RX. For the effect on the power consumption of different clock sources, please refer to the Power Management section. rmt_rx_channel_config_t::resolution_hzsets the resolution of the internal tick counter. The timing parameter of the RMT signal is calculated based on this tick. rmt_rx_channel_config_t::mem_block_symbolshas a slightly different meaning based on whether the DMA backend is enabled. If the DMA is enabled via rmt_rx_channel_config_t::with_dma, this field controls the maximum size of the DMA buffer. If DMA is not used, this field controls the size of the dedicated memory block owned by the channel, which should be at least 64. - rmt_rx_channel_config_t::invert_inis used to invert the input signals before it is passed to the RMT receiver. The inversion is done by the GPIO matrix instead of by the RMT peripheral. rmt_rx_channel_config_t::with_dmaenables the DMA backend for the channel. Using the DMA allows a significant amount of the channel's workload to be offloaded from the CPU. However, the DMA backend is not available on all ESP chips, please refer to [TRM] before you enable this option. Or you might encounter a ESP_ERR_NOT_SUPPORTEDerror. rmt_rx_channel_config_t::io_loop_backenables both input and output capabilities on the channel's assigned GPIO. Thus, by binding a TX and RX channel to the same GPIO, loopback can be achieved. rmt_rx_channel_config_t::intr_prioritySet the priority of the interrupt. If set to 0, then the driver will use a interrupt with low or medium priority (priority level may be one of 1,2 or 3), otherwise use the priority indicated by rmt_rx_channel_config_t::intr_priority. Please use the number form (1,2,3) , not the bitmask form ((1<<1),(1<<2),(1<<3)). Please pay attention that once the interrupt priority is set, it cannot be changed until rmt_del_channel()is called. Once the rmt_rx_channel_config_t structure is populated with mandatory parameters, users can call rmt_new_rx_channel() to allocate and initialize an RX channel. This function returns an RMT channel handle if it runs correctly. Specifically, when there are no more free channels in the RMT resource pool, this function returns ESP_ERR_NOT_FOUND error. If some feature (e.g., DMA backend) is not supported by the hardware, it returns ESP_ERR_NOT_SUPPORTED error. rmt_channel_handle_t rx_chan = NULL; rmt_rx_channel_config_t rx_chan_config = { .clk_src = RMT_CLK_SRC_DEFAULT, // select source clock .resolution_hz = 1 * 1000 * 1000, // 1 MHz tick resolution, i.e., 1 tick = 1 µs .mem_block_symbols = 64, // memory block size, 64 * 4 = 256 Bytes .gpio_num = 2, // GPIO number .flags.invert_in = false, // do not invert input signal .flags.with_dma = false, // do not need DMA backend }; ESP_ERROR_CHECK(rmt_new_rx_channel(&rx_chan_config, &rx_chan)); Note Due to a software limitation in the GPIO driver, when both TX and RX channels are bound to the same GPIO, ensure the RX Channel is initialized before the TX Channel. If the TX Channel was set up first, then during the RX Channel setup, the previous RMT TX Channel signal will be overridden by the GPIO control signal. Uninstall RMT Channel If a previously installed RMT channel is no longer needed, it is recommended to recycle the resources by calling rmt_del_channel(), which in return allows the underlying software and hardware resources to be reused for other purposes. Carrier Modulation and Demodulation The RMT transmitter can generate a carrier wave and modulate it onto the message signal. Compared to the message signal, the carrier signal's frequency is significantly higher. In addition, the user can only set the frequency and duty cycle for the carrier signal. The RMT receiver can demodulate the carrier signal from the incoming signal. Note that, carrier modulation and demodulation are not supported on all ESP chips, please refer to [TRM] before configuring the carrier, or you might encounter a ESP_ERR_NOT_SUPPORTED error. Carrier-related configurations lie in rmt_carrier_config_t: rmt_carrier_config_t::frequency_hzsets the carrier frequency, in Hz. rmt_carrier_config_t::duty_cyclesets the carrier duty cycle. rmt_carrier_config_t::polarity_active_lowsets the carrier polarity, i.e., on which level the carrier is applied. rmt_carrier_config_t::always_onsets whether to output the carrier even when the data transmission has finished. This configuration is only valid for the TX channel. Note For the RX channel, we should not set the carrier frequency exactly to the theoretical value. It is recommended to leave a tolerance for the carrier frequency. For example, in the snippet below, we set the frequency to 25 KHz, instead of the 38 KHz configured on the TX side. The reason is that reflection and refraction occur when a signal travels through the air, leading to distortion on the receiver side. rmt_carrier_config_t tx_carrier_cfg = { .duty_cycle = 0.33, // duty cycle 33% .frequency_hz = 38000, // 38 KHz .flags.polarity_active_low = false, // carrier should be modulated to high level }; // modulate carrier to TX channel ESP_ERROR_CHECK(rmt_apply_carrier(tx_chan, &tx_carrier_cfg)); rmt_carrier_config_t rx_carrier_cfg = { .duty_cycle = 0.33, // duty cycle 33% .frequency_hz = 25000, // 25 KHz carrier, should be smaller than the transmitter's carrier frequency .flags.polarity_active_low = false, // the carrier is modulated to high level }; // demodulate carrier from RX channel ESP_ERROR_CHECK(rmt_apply_carrier(rx_chan, &rx_carrier_cfg)); Register Event Callbacks When an event occurs on an RMT channel (e.g., transmission or receiving is completed), the CPU is notified of this event via an interrupt. If you have some function that needs to be called when a particular events occur, you can register a callback for that event to the RMT driver's ISR (Interrupt Service Routine) by calling rmt_tx_register_event_callbacks() and rmt_rx_register_event_callbacks() for TX and RX channel respectively. Since the registered callback functions are called in the interrupt context, the user should ensure the callback function does not block, e.g., by making sure that only FreeRTOS APIs with the FromISR suffix are called from within the function. The callback function has a boolean return value used to indicate whether a higher priority task has been unblocked by the callback. The TX channel-supported event callbacks are listed in the rmt_tx_event_callbacks_t: rmt_tx_event_callbacks_t::on_trans_donesets a callback function for the "trans-done" event. The function prototype is declared in rmt_tx_done_callback_t. The RX channel-supported event callbacks are listed in the rmt_rx_event_callbacks_t: rmt_rx_event_callbacks_t::on_recv_donesets a callback function for "receive-done" event. The function prototype is declared in rmt_rx_done_callback_t. Users can save their own context in rmt_tx_register_event_callbacks() and rmt_rx_register_event_callbacks() as well, via the parameter user_data. The user data is directly passed to each callback function. In the callback function, users can fetch the event-specific data that is filled by the driver in the edata. Note that the edata pointer is only valid during the callback. The TX-done event data is defined in rmt_tx_done_event_data_t: rmt_tx_done_event_data_t::num_symbolsindicates the number of transmitted RMT symbols. This also reflects the size of the encoding artifacts. Please note, this value accounts for the EOFsymbol as well, which is appended by the driver to mark the end of one transaction. The RX-complete event data is defined in rmt_rx_done_event_data_t: rmt_rx_done_event_data_t::received_symbolspoints to the received RMT symbols. These symbols are saved in the bufferparameter of the rmt_receive()function. Users should not free this receive buffer before the callback returns. rmt_rx_done_event_data_t::num_symbolsindicates the number of received RMT symbols. This value is not larger than the buffer_sizeparameter of rmt_receive()function. If the buffer_sizeis not sufficient to accommodate all the received RMT symbols, the driver only keeps the maximum number of symbols that the buffer can hold, and excess symbols are discarded or ignored. Enable and Disable Channel rmt_enable() must be called in advance before transmitting or receiving RMT symbols. For TX channels, enabling a channel enables a specific interrupt and prepares the hardware to dispatch transactions. For RX channels, enabling a channel enables an interrupt, but the receiver is not started during this time, as the characteristics of the incoming signal have yet to be specified. The receiver is started in rmt_receive(). rmt_disable() does the opposite by disabling the interrupt and clearing any pending interrupts. The transmitter and receiver are disabled as well. ESP_ERROR_CHECK(rmt_enable(tx_chan)); ESP_ERROR_CHECK(rmt_enable(rx_chan)); Initiate TX Transaction RMT is a special communication peripheral, as it is unable to transmit raw byte streams like SPI and I2C. RMT can only send data in its own format rmt_symbol_word_t. However, the hardware does not help to convert the user data into RMT symbols, this can only be done in software by the so-called RMT Encoder. The encoder is responsible for encoding user data into RMT symbols and then writing to the RMT memory block or the DMA buffer. For how to create an RMT encoder, please refer to RMT Encoder. Once you created an encoder, you can initiate a TX transaction by calling rmt_transmit(). This function takes several positional parameters like channel handle, encoder handle, and payload buffer. Besides, you also need to provide a transmission-specific configuration in rmt_transmit_config_t: rmt_transmit_config_t::loop_countsets the number of transmission loops. After the transmitter has finished one round of transmission, it can restart the same transmission again if this value is not set to zero. As the loop is controlled by hardware, the RMT channel can be used to generate many periodic sequences with minimal CPU intervention. Setting rmt_transmit_config_t::loop_countto -1 means an infinite loop transmission. In this case, the channel does not stop until rmt_disable()is called. The "trans-done" event is not generated as well. Setting rmt_transmit_config_t::loop_countto a positive number means finite number of iterations. In this case, the "trans-done" event is when the specified number of iterations have completed. Note The loop transmit feature is not supported on all ESP chips, please refer to [TRM] before you configure this option, or you might encounter ESP_ERR_NOT_SUPPORTEDerror. - rmt_transmit_config_t::eot_levelsets the output level when the transmitter finishes working or stops working by calling rmt_disable(). rmt_transmit_config_t::queue_nonblockingsets whether to wait for a free slot in the transaction queue when it is full. If this value is set to true, then the function will return with an error code ESP_ERR_INVALID_STATEwhen the queue is full. Otherwise, the function will block until a free slot is available in the queue. Note There is a limitation in the transmission size if the rmt_transmit_config_t::loop_count is set to non-zero, i.e., to enable the loop feature. The encoded RMT symbols should not exceed the capacity of the RMT hardware memory block size, or you might see an error message like encoding artifacts can't exceed hw memory block for loop transmission. If you have to start a large transaction by loop, you can try either of the following methods. Increase the rmt_tx_channel_config_t::mem_block_symbols. This approach does not work if the DMA backend is also enabled. Customize an encoder and construct an infinite loop in the encoding function. See also RMT Encoder. Internally, rmt_transmit() constructs a transaction descriptor and sends it to a job queue, which is dispatched in the ISR. So it is possible that the transaction is not started yet when rmt_transmit() returns. To ensure all pending transactions to complete, the user can use rmt_tx_wait_all_done(). Multiple Channels Simultaneous Transmission In some real-time control applications (e.g., to make two robotic arms move simultaneously), you do not want any time drift between different channels. The RMT driver can help to manage this by creating a so-called Sync Manager. The sync manager is represented by rmt_sync_manager_handle_t in the driver. The procedure of RMT sync transmission is shown as follows: Install RMT Sync Manager To create a sync manager, the user needs to tell which channels are going to be managed in the rmt_sync_manager_config_t: rmt_sync_manager_config_t::tx_channel_arraypoints to the array of TX channels to be managed. rmt_sync_manager_config_t::array_sizesets the number of channels to be managed. rmt_new_sync_manager() can return a manager handle on success. This function could also fail due to various errors such as invalid arguments, etc. Especially, when the sync manager has been installed before, and there are no hardware resources to create another manager, this function reports ESP_ERR_NOT_FOUND error. In addition, if the sync manager is not supported by the hardware, it reports a ESP_ERR_NOT_SUPPORTED error. Please refer to [TRM] before using the sync manager feature. Start Transmission Simultaneously For any managed TX channel, it does not start the machine until rmt_transmit() has been called on all channels in rmt_sync_manager_config_t::tx_channel_array. Before that, the channel is just put in a waiting state. TX channels will usually complete their transactions at different times due to differing transactions, thus resulting in a loss of sync. So before restarting a simultaneous transmission, the user needs to call rmt_sync_reset() to synchronize all channels again. Calling rmt_del_sync_manager() can recycle the sync manager and enable the channels to initiate transactions independently afterward. rmt_channel_handle_t tx_channels[2] = {NULL}; // declare two channels int tx_gpio_number[2] = {0, 2}; // install channels one by one for (int i = 0; i < 2; i++) { rmt_tx_channel_config_t tx_chan_config = { .clk_src = RMT_CLK_SRC_DEFAULT, // select source clock .gpio_num = tx_gpio_number[i], // GPIO number .mem_block_symbols = 64, // memory block size, 64 * 4 = 256 Bytes .resolution_hz = 1 * 1000 * 1000, // 1 MHz resolution .trans_queue_depth = 1, // set the number of transactions that can pend in the background }; ESP_ERROR_CHECK(rmt_new_tx_channel(&tx_chan_config, &tx_channels[i])); } // install sync manager rmt_sync_manager_handle_t synchro = NULL; rmt_sync_manager_config_t synchro_config = { .tx_channel_array = tx_channels, .array_size = sizeof(tx_channels) / sizeof(tx_channels[0]), }; ESP_ERROR_CHECK(rmt_new_sync_manager(&synchro_config, &synchro)); ESP_ERROR_CHECK(rmt_transmit(tx_channels[0], led_strip_encoders[0], led_data, led_num * 3, &transmit_config)); // tx_channels[0] does not start transmission until call of `rmt_transmit()` for tx_channels[1] returns ESP_ERROR_CHECK(rmt_transmit(tx_channels[1], led_strip_encoders[1], led_data, led_num * 3, &transmit_config)); Initiate RX Transaction As also discussed in the Enable and Disable Channel, calling rmt_enable() does not prepare an RX to receive RMT symbols. The user needs to specify the basic characteristics of the incoming signals in rmt_receive_config_t: rmt_receive_config_t::signal_range_min_nsspecifies the minimal valid pulse duration in either high or low logic levels. A pulse width that is smaller than this value is treated as a glitch, and ignored by the hardware. rmt_receive_config_t::signal_range_max_nsspecifies the maximum valid pulse duration in either high or low logic levels. A pulse width that is bigger than this value is treated as Stop Signal, and the receiver generates receive-complete event immediately. The RMT receiver starts the RX machine after the user calls rmt_receive() with the provided configuration above. Note that, this configuration is transaction specific, which means, to start a new round of reception, the user needs to set the rmt_receive_config_t again. The receiver saves the incoming signals into its internal memory block or DMA buffer, in the format of rmt_symbol_word_t. Due to the limited size of the memory block, the RMT receiver can only save short frames whose length is not longer than the memory block capacity. Long frames are truncated by the hardware, and the driver reports an error message: hw buffer too small, received symbols truncated. The copy destination should be provided in the buffer parameter of rmt_receive() function. If this buffer overlfows due to an insufficient buffer size, the receiver can continue to work, but overflowed symbols are dropped and the following error message is reported: user buffer too small, received symbols truncated. Please take care of the lifecycle of the buffer parameter, ensuring that the buffer is not recycled before the receiver is finished or stopped. The receiver is stopped by the driver when it finishes working, i.e., receive a signal whose duration is bigger than rmt_receive_config_t::signal_range_max_ns. The user needs to call rmt_receive() again to restart the receiver, if necessary. The user can get the received data in the rmt_rx_event_callbacks_t::on_recv_done callback. See also Register Event Callbacks for more information. static bool example_rmt_rx_done_callback(rmt_channel_handle_t channel, const rmt_rx_done_event_data_t *edata, void *user_data) { BaseType_t high_task_wakeup = pdFALSE; QueueHandle_t receive_queue = (QueueHandle_t)user_data; // send the received RMT symbols to the parser task xQueueSendFromISR(receive_queue, edata, &high_task_wakeup); // return whether any task is woken up return high_task_wakeup == pdTRUE; } QueueHandle_t receive_queue = xQueueCreate(1, sizeof(rmt_rx_done_event_data_t)); rmt_rx_event_callbacks_t cbs = { .on_recv_done = example_rmt_rx_done_callback, }; ESP_ERROR_CHECK(rmt_rx_register_event_callbacks(rx_channel, &cbs, receive_queue)); // the following timing requirement is based on NEC protocol rmt_receive_config_t receive_config = { .signal_range_min_ns = 1250, // the shortest duration for NEC signal is 560 µs, 1250 ns < 560 µs, valid signal is not treated as noise .signal_range_max_ns = 12000000, // the longest duration for NEC signal is 9000 µs, 12000000 ns > 9000 µs, the receive does not stop early }; rmt_symbol_word_t raw_symbols[64]; // 64 symbols should be sufficient for a standard NEC frame // ready to receive ESP_ERROR_CHECK(rmt_receive(rx_channel, raw_symbols, sizeof(raw_symbols), &receive_config)); // wait for the RX-done signal rmt_rx_done_event_data_t rx_data; xQueueReceive(receive_queue, &rx_data, portMAX_DELAY); // parse the received symbols example_parse_nec_frame(rx_data.received_symbols, rx_data.num_symbols); RMT Encoder An RMT encoder is part of the RMT TX transaction, whose responsibility is to generate and write the correct RMT symbols into hardware memory or DMA buffer at a specific time. There are some special restrictions for an encoding function: During a single transaction, the encoding function may be called multiple times. This is necessary because the target RMT memory block cannot hold all the artifacts at once. To overcome this limitation, the driver utilizes a ping-pong approach, where the encoding session is divided into multiple parts. This means that the encoder needs to keep track of its state to continue encoding from where it left off in the previous part. The encoding function is running in the ISR context. To speed up the encoding session, it is highly recommended to put the encoding function into IRAM. This can also avoid the cache miss during encoding. To help get started with the RMT driver faster, some commonly used encoders are provided out-of-the-box. They can either work alone or be chained together into a new encoder. See also Composite Pattern for the principle behind it. The driver has defined the encoder interface in rmt_encoder_t, it contains the following functions: rmt_encoder_t::encodeis the fundamental function of an encoder. This is where the encoding session happens. The function might be called multiple times within a single transaction. The encode function should return the state of the current encoding session. The supported states are listed in the rmt_encode_state_t. If the result contains RMT_ENCODING_COMPLETE, it means the current encoder has finished work. If the result contains RMT_ENCODING_MEM_FULL, the program needs to yield from the current session, as there is no space to save more encoding artifacts. - rmt_encoder_t::resetshould reset the encoder state back to the initial state (the RMT encoder is stateful). If the RMT transmitter is manually stopped without resetting its corresponding encoder, subsequent encoding session can be erroneous. This function is also called implicitly in rmt_disable(). - rmt_encoder_t::delshould free the resources allocated by the encoder. Copy Encoder A copy encoder is created by calling rmt_new_copy_encoder(). A copy encoder's main functionality is to copy the RMT symbols from user space into the driver layer. It is usually used to encode const data, i.e., data does not change at runtime after initialization such as the leading code in the IR protocol. A configuration structure rmt_copy_encoder_config_t should be provided in advance before calling rmt_new_copy_encoder(). Currently, this configuration is reserved for future expansion, and has no specific use or setting items for now. Bytes Encoder A bytes encoder is created by calling rmt_new_bytes_encoder(). The bytes encoder's main functionality is to convert the user space byte stream into RMT symbols dynamically. It is usually used to encode dynamic data, e.g., the address and command fields in the IR protocol. A configuration structure rmt_bytes_encoder_config_t should be provided in advance before calling rmt_new_bytes_encoder(): rmt_bytes_encoder_config_t::bit0and rmt_bytes_encoder_config_t::bit1are necessary to specify the encoder how to represent bit zero and bit one in the format of rmt_symbol_word_t. rmt_bytes_encoder_config_t::msb_firstsets the bit endianess of each byte. If it is set to true, the encoder encodes the Most Significant Bit first. Otherwise, it encodes the Least Significant Bit first. Besides the primitive encoders provided by the driver, the user can implement his own encoder by chaining the existing encoders together. A common encoder chain is shown as follows: Customize RMT Encoder for NEC Protocol This section demonstrates how to write an NEC encoder. The NEC IR protocol uses pulse distance encoding of the message bits. Each pulse burst is 562.5 µs in length, logical bits are transmitted as follows. It is worth mentioning that the least significant bit of each byte is sent first. Logical 0: a 562.5 µspulse burst followed by a 562.5 µsspace, with a total transmit time of 1.125 ms Logical 1: a 562.5 µspulse burst followed by a 1.6875 msspace, with a total transmit time of 2.25 ms When a key is pressed on the remote controller, the transmitted message includes the following elements in the specified order: 9 msleading pulse burst, also called the "AGC pulse" 4.5 msspace 8-bit address for the receiving device 8-bit logical inverse of the address 8-bit command 8-bit logical inverse of the command a final 562.5 µspulse burst to signify the end of message transmission Then you can construct the NEC rmt_encoder_t::encode function in the same order, for example: // IR NEC scan code representation typedef struct { uint16_t address; uint16_t command; } ir_nec_scan_code_t; // construct an encoder by combining primitive encoders typedef struct { rmt_encoder_t base; // the base "class" declares the standard encoder interface rmt_encoder_t *copy_encoder; // use the copy_encoder to encode the leading and ending pulse rmt_encoder_t *bytes_encoder; // use the bytes_encoder to encode the address and command data rmt_symbol_word_t nec_leading_symbol; // NEC leading code with RMT representation rmt_symbol_word_t nec_ending_symbol; // NEC ending code with RMT representation int state; // record the current encoding state, i.e., we are in which encoding phase } rmt_ir_nec_encoder_t; static size_t rmt_encode_ir_nec(rmt_encoder_t *encoder, rmt_channel_handle_t channel, const void *primary_data, size_t data_size, rmt_encode_state_t *ret_state) { rmt_ir_nec_encoder_t *nec_encoder = __containerof(encoder, rmt_ir_nec_encoder_t, base); rmt_encode_state_t session_state = RMT_ENCODING_RESET; rmt_encode_state_t state = RMT_ENCODING_RESET; size_t encoded_symbols = 0; ir_nec_scan_code_t *scan_code = (ir_nec_scan_code_t *)primary_data; rmt_encoder_handle_t copy_encoder = nec_encoder->copy_encoder; rmt_encoder_handle_t bytes_encoder = nec_encoder->bytes_encoder; switch (nec_encoder->state) { case 0: // send leading code encoded_symbols += copy_encoder->encode(copy_encoder, channel, &nec_encoder->nec_leading_symbol, sizeof(rmt_symbol_word_t), &session_state); if (session_state & RMT_ENCODING_COMPLETE) { nec_encoder->state = 1; // we can only switch to the next state when the current encoder finished } if (session_state & RMT_ENCODING_MEM_FULL) { state |= RMT_ENCODING_MEM_FULL; goto out; // yield if there is no free space to put other encoding artifacts } // fall-through case 1: // send address encoded_symbols += bytes_encoder->encode(bytes_encoder, channel, &scan_code->address, sizeof(uint16_t), &session_state); if (session_state & RMT_ENCODING_COMPLETE) { nec_encoder->state = 2; // we can only switch to the next state when the current encoder finished } if (session_state & RMT_ENCODING_MEM_FULL) { state |= RMT_ENCODING_MEM_FULL; goto out; // yield if there is no free space to put other encoding artifacts } // fall-through case 2: // send command encoded_symbols += bytes_encoder->encode(bytes_encoder, channel, &scan_code->command, sizeof(uint16_t), &session_state); if (session_state & RMT_ENCODING_COMPLETE) { nec_encoder->state = 3; // we can only switch to the next state when the current encoder finished } if (session_state & RMT_ENCODING_MEM_FULL) { state |= RMT_ENCODING_MEM_FULL; goto out; // yield if there is no free space to put other encoding artifacts } // fall-through case 3: // send ending code encoded_symbols += copy_encoder->encode(copy_encoder, channel, &nec_encoder->nec_ending_symbol, sizeof(rmt_symbol_word_t), &session_state); if (session_state & RMT_ENCODING_COMPLETE) { nec_encoder->state = RMT_ENCODING_RESET; // back to the initial encoding session state |= RMT_ENCODING_COMPLETE; // telling the caller the NEC encoding has finished } if (session_state & RMT_ENCODING_MEM_FULL) { state |= RMT_ENCODING_MEM_FULL; goto out; // yield if there is no free space to put other encoding artifacts } } out: *ret_state = state; return encoded_symbols; } A full sample code can be found in peripherals/rmt/ir_nec_transceiver. In the above snippet, we use a switch-case and several goto statements to implement a Finite-state machine . With this pattern, users can construct much more complex IR protocols. Power Management When power management is enabled, i.e., CONFIG_PM_ENABLE is on, the system adjusts the APB frequency before going into Light-sleep, thus potentially changing the resolution of the RMT internal counter. However, the driver can prevent the system from changing APB frequency by acquiring a power management lock of type ESP_PM_APB_FREQ_MAX. Whenever the user creates an RMT channel that has selected RMT_CLK_SRC_APB as the clock source, the driver guarantees that the power management lock is acquired after the channel enabled by rmt_enable(). Likewise, the driver releases the lock after rmt_disable() is called for the same channel. This also reveals that the rmt_enable() and rmt_disable() should appear in pairs. If the channel clock source is selected to others like RMT_CLK_SRC_XTAL, then the driver does not install a power management lock for it, which is more suitable for a low-power application as long as the source clock can still provide sufficient resolution. IRAM Safe By default, the RMT interrupt is deferred when the Cache is disabled for reasons like writing or erasing the main Flash. Thus the transaction-done interrupt does not get handled in time, which is not acceptable in a real-time application. What is worse, when the RMT transaction relies on ping-pong interrupt to successively encode or copy RMT symbols, a delayed interrupt can lead to an unpredictable result. There is a Kconfig option CONFIG_RMT_ISR_IRAM_SAFE that has the following features: Enable the interrupt being serviced even when the cache is disabled Place all functions used by the ISR into IRAM 2 Place the driver object into DRAM in case it is mapped to PSRAM by accident This Kconfig option allows the interrupt handler to run while the cache is disabled but comes at the cost of increased IRAM consumption. Another Kconfig option CONFIG_RMT_RECV_FUNC_IN_IRAM can place rmt_receive() into the IRAM as well. So that the receive function can be used even when the flash cache is disabled. Thread Safety The factory function rmt_new_tx_channel(), rmt_new_rx_channel() and rmt_new_sync_manager() are guaranteed to be thread-safe by the driver, which means, user can call them from different RTOS tasks without protection by extra locks. Other functions that take the rmt_channel_handle_t and rmt_sync_manager_handle_t as the first positional parameter, are not thread-safe. which means the user should avoid calling them from multiple tasks. The following functions are allowed to use under ISR context as well. Kconfig Options CONFIG_RMT_ISR_IRAM_SAFE controls whether the default ISR handler can work when cache is disabled, see also IRAM Safe for more information. CONFIG_RMT_ENABLE_DEBUG_LOG is used to enable the debug log at the cost of increased firmware binary size. CONFIG_RMT_RECV_FUNC_IN_IRAM controls where to place the RMT receive function (IRAM or Flash), see IRAM Safe for more information. Application Examples RMT-based RGB LED strip customized encoder: peripherals/rmt/led_strip RMT IR NEC protocol encoding and decoding: peripherals/rmt/ir_nec_transceiver RMT transactions in queue: peripherals/rmt/musical_buzzer RMT-based stepper motor with S-curve algorithm: : peripherals/rmt/stepper_motor RMT infinite loop for driving DShot ESC: peripherals/rmt/dshot_esc RMT simulate 1-wire protocol (take DS18B20 as example): peripherals/rmt/onewire FAQ Why the RMT encoder results in more data than expected? The RMT encoding takes place in the ISR context. If your RMT encoding session takes a long time (e.g., by logging debug information) or the encoding session is deferred somehow because of interrupt latency, then it is possible the transmitting becomes faster than the encoding. As a result, the encoder can not prepare the next data in time, leading to the transmitter sending the previous data again. There is no way to ask the transmitter to stop and wait. You can mitigate the issue by combining the following ways: - Increase the rmt_tx_channel_config_t::mem_block_symbols, in steps of 64. - Place the encoding function in the IRAM. - Enables the rmt_tx_channel_config_t::with_dmaif it is available for your chip. API Reference Header File This header file can be included with: #include "driver/rmt_tx.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t rmt_new_tx_channel(const rmt_tx_channel_config_t *config, rmt_channel_handle_t *ret_chan) Create a RMT TX channel. - Parameters config -- [in] TX channel configurations ret_chan -- [out] Returned generic RMT channel handle - - Returns ESP_OK: Create RMT TX channel successfully ESP_ERR_INVALID_ARG: Create RMT TX channel failed because of invalid argument ESP_ERR_NO_MEM: Create RMT TX channel failed because out of memory ESP_ERR_NOT_FOUND: Create RMT TX channel failed because all RMT channels are used up and no more free one ESP_ERR_NOT_SUPPORTED: Create RMT TX channel failed because some feature is not supported by hardware, e.g. DMA feature is not supported by hardware ESP_FAIL: Create RMT TX channel failed because of other error - - esp_err_t rmt_transmit(rmt_channel_handle_t tx_channel, rmt_encoder_handle_t encoder, const void *payload, size_t payload_bytes, const rmt_transmit_config_t *config) Transmit data by RMT TX channel. Note This function constructs a transaction descriptor then pushes to a queue. The transaction will not start immediately if there's another one under processing. Based on the setting of rmt_transmit_config_t::queue_nonblocking, if there're too many transactions pending in the queue, this function can block until it has free slot, otherwise just return quickly. Note The data to be transmitted will be encoded into RMT symbols by the specific encoder. - Parameters tx_channel -- [in] RMT TX channel that created by rmt_new_tx_channel() encoder -- [in] RMT encoder that created by various factory APIs like rmt_new_bytes_encoder() payload -- [in] The raw data to be encoded into RMT symbols payload_bytes -- [in] Size of the payloadin bytes config -- [in] Transmission specific configuration - - Returns ESP_OK: Transmit data successfully ESP_ERR_INVALID_ARG: Transmit data failed because of invalid argument ESP_ERR_INVALID_STATE: Transmit data failed because channel is not enabled ESP_ERR_NOT_SUPPORTED: Transmit data failed because some feature is not supported by hardware, e.g. unsupported loop count ESP_FAIL: Transmit data failed because of other error - - esp_err_t rmt_tx_wait_all_done(rmt_channel_handle_t tx_channel, int timeout_ms) Wait for all pending TX transactions done. Note This function will block forever if the pending transaction can't be finished within a limited time (e.g. an infinite loop transaction). See also rmt_disable()for how to terminate a working channel. - Parameters tx_channel -- [in] RMT TX channel that created by rmt_new_tx_channel() timeout_ms -- [in] Wait timeout, in ms. Specially, -1 means to wait forever. - - Returns ESP_OK: Flush transactions successfully ESP_ERR_INVALID_ARG: Flush transactions failed because of invalid argument ESP_ERR_TIMEOUT: Flush transactions failed because of timeout ESP_FAIL: Flush transactions failed because of other error - - esp_err_t rmt_tx_register_event_callbacks(rmt_channel_handle_t tx_channel, const rmt_tx_event_callbacks_t *cbs, void *user_data) Set event callbacks for RMT TX channel. Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbsstructure to NULL. Note When CONFIG_RMT_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. The user_datashould also reside in SRAM. - Parameters tx_channel -- [in] RMT generic channel that created by rmt_new_tx_channel() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly - - Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error - - esp_err_t rmt_new_sync_manager(const rmt_sync_manager_config_t *config, rmt_sync_manager_handle_t *ret_synchro) Create a synchronization manager for multiple TX channels, so that the managed channel can start transmitting at the same time. Note All the channels to be managed should be enabled by rmt_enable()before put them into sync manager. - Parameters config -- [in] Synchronization manager configuration ret_synchro -- [out] Returned synchronization manager handle - - Returns ESP_OK: Create sync manager successfully ESP_ERR_INVALID_ARG: Create sync manager failed because of invalid argument ESP_ERR_NOT_SUPPORTED: Create sync manager failed because it is not supported by hardware ESP_ERR_INVALID_STATE: Create sync manager failed because not all channels are enabled ESP_ERR_NO_MEM: Create sync manager failed because out of memory ESP_ERR_NOT_FOUND: Create sync manager failed because all sync controllers are used up and no more free one ESP_FAIL: Create sync manager failed because of other error - - esp_err_t rmt_del_sync_manager(rmt_sync_manager_handle_t synchro) Delete synchronization manager. - Parameters synchro -- [in] Synchronization manager handle returned from rmt_new_sync_manager() - Returns ESP_OK: Delete the synchronization manager successfully ESP_ERR_INVALID_ARG: Delete the synchronization manager failed because of invalid argument ESP_FAIL: Delete the synchronization manager failed because of other error - - esp_err_t rmt_sync_reset(rmt_sync_manager_handle_t synchro) Reset synchronization manager. - Parameters synchro -- [in] Synchronization manager handle returned from rmt_new_sync_manager() - Returns ESP_OK: Reset the synchronization manager successfully ESP_ERR_INVALID_ARG: Reset the synchronization manager failed because of invalid argument ESP_FAIL: Reset the synchronization manager failed because of other error - Structures - struct rmt_tx_event_callbacks_t Group of RMT TX callbacks. Note The callbacks are all running under ISR environment Note When CONFIG_RMT_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. Public Members - rmt_tx_done_callback_t on_trans_done Event callback, invoked when transmission is finished - rmt_tx_done_callback_t on_trans_done - struct rmt_tx_channel_config_t RMT TX channel specific configuration. Public Members - gpio_num_t gpio_num GPIO number used by RMT TX channel. Set to -1 if unused - rmt_clock_source_t clk_src Clock source of RMT TX channel, channels in the same group must use the same clock source - uint32_t resolution_hz Channel clock resolution, in Hz - size_t mem_block_symbols Size of memory block, in number of rmt_symbol_word_t, must be an even. In the DMA mode, this field controls the DMA buffer size, it can be set to a large value; In the normal mode, this field controls the number of RMT memory block that will be used by the channel. - size_t trans_queue_depth Depth of internal transfer queue, increase this value can support more transfers pending in the background - int intr_priority RMT interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) - uint32_t invert_out Whether to invert the RMT channel signal before output to GPIO pad - uint32_t with_dma If set, the driver will allocate an RMT channel with DMA capability - uint32_t io_loop_back The signal output from the GPIO will be fed to the input path as well - uint32_t io_od_mode Configure the GPIO as open-drain mode - struct rmt_tx_channel_config_t::[anonymous] flags TX channel config flags - gpio_num_t gpio_num - struct rmt_transmit_config_t RMT transmit specific configuration. Public Members - int loop_count Specify the times of transmission in a loop, -1 means transmitting in an infinite loop - uint32_t eot_level Set the output level for the "End Of Transmission" - uint32_t queue_nonblocking If set, when the transaction queue is full, driver will not block the thread but return directly - struct rmt_transmit_config_t::[anonymous] flags Transmit specific config flags - int loop_count - struct rmt_sync_manager_config_t Synchronous manager configuration. Public Members - const rmt_channel_handle_t *tx_channel_array Array of TX channels that are about to be managed by a synchronous controller - size_t array_size Size of the tx_channel_array - const rmt_channel_handle_t *tx_channel_array Header File This header file can be included with: #include "driver/rmt_rx.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t rmt_new_rx_channel(const rmt_rx_channel_config_t *config, rmt_channel_handle_t *ret_chan) Create a RMT RX channel. - Parameters config -- [in] RX channel configurations ret_chan -- [out] Returned generic RMT channel handle - - Returns ESP_OK: Create RMT RX channel successfully ESP_ERR_INVALID_ARG: Create RMT RX channel failed because of invalid argument ESP_ERR_NO_MEM: Create RMT RX channel failed because out of memory ESP_ERR_NOT_FOUND: Create RMT RX channel failed because all RMT channels are used up and no more free one ESP_ERR_NOT_SUPPORTED: Create RMT RX channel failed because some feature is not supported by hardware, e.g. DMA feature is not supported by hardware ESP_FAIL: Create RMT RX channel failed because of other error - - esp_err_t rmt_receive(rmt_channel_handle_t rx_channel, void *buffer, size_t buffer_size, const rmt_receive_config_t *config) Initiate a receive job for RMT RX channel. Note This function is non-blocking, it initiates a new receive job and then returns. User should check the received data from the on_recv_donecallback that registered by rmt_rx_register_event_callbacks(). Note This function can also be called in ISR context. Note If you want this function to work even when the flash cache is disabled, please enable the CONFIG_RMT_RECV_FUNC_IN_IRAMoption. - Parameters rx_channel -- [in] RMT RX channel that created by rmt_new_rx_channel() buffer -- [in] The buffer to store the received RMT symbols buffer_size -- [in] size of the buffer, in bytes config -- [in] Receive specific configurations - - Returns ESP_OK: Initiate receive job successfully ESP_ERR_INVALID_ARG: Initiate receive job failed because of invalid argument ESP_ERR_INVALID_STATE: Initiate receive job failed because channel is not enabled ESP_FAIL: Initiate receive job failed because of other error - - esp_err_t rmt_rx_register_event_callbacks(rmt_channel_handle_t rx_channel, const rmt_rx_event_callbacks_t *cbs, void *user_data) Set callbacks for RMT RX channel. Note User can deregister a previously registered callback by calling this function and setting the callback member in the cbsstructure to NULL. Note When CONFIG_RMT_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. The user_datashould also reside in SRAM. - Parameters rx_channel -- [in] RMT generic channel that created by rmt_new_rx_channel() cbs -- [in] Group of callback functions user_data -- [in] User data, which will be passed to callback functions directly - - Returns ESP_OK: Set event callbacks successfully ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument ESP_FAIL: Set event callbacks failed because of other error - Structures - struct rmt_rx_event_callbacks_t Group of RMT RX callbacks. Note The callbacks are all running under ISR environment Note When CONFIG_RMT_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. Public Members - rmt_rx_done_callback_t on_recv_done Event callback, invoked when one RMT channel receiving transaction completes - rmt_rx_done_callback_t on_recv_done - struct rmt_rx_channel_config_t RMT RX channel specific configuration. Public Members - gpio_num_t gpio_num GPIO number used by RMT RX channel. Set to -1 if unused - rmt_clock_source_t clk_src Clock source of RMT RX channel, channels in the same group must use the same clock source - uint32_t resolution_hz Channel clock resolution, in Hz - size_t mem_block_symbols Size of memory block, in number of rmt_symbol_word_t, must be an even. In the DMA mode, this field controls the DMA buffer size, it can be set to a large value (e.g. 1024); In the normal mode, this field controls the number of RMT memory block that will be used by the channel. - uint32_t invert_in Whether to invert the incoming RMT channel signal - uint32_t with_dma If set, the driver will allocate an RMT channel with DMA capability - uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well - struct rmt_rx_channel_config_t::[anonymous] flags RX channel config flags - int intr_priority RMT interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3) - gpio_num_t gpio_num - struct rmt_receive_config_t RMT receive specific configuration. Header File This header file can be included with: #include "driver/rmt_common.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t rmt_del_channel(rmt_channel_handle_t channel) Delete an RMT channel. - Parameters channel -- [in] RMT generic channel that created by rmt_new_tx_channel()or rmt_new_rx_channel() - Returns ESP_OK: Delete RMT channel successfully ESP_ERR_INVALID_ARG: Delete RMT channel failed because of invalid argument ESP_ERR_INVALID_STATE: Delete RMT channel failed because it is still in working ESP_FAIL: Delete RMT channel failed because of other error - - esp_err_t rmt_apply_carrier(rmt_channel_handle_t channel, const rmt_carrier_config_t *config) Apply modulation feature for TX channel or demodulation feature for RX channel. - Parameters channel -- [in] RMT generic channel that created by rmt_new_tx_channel()or rmt_new_rx_channel() config -- [in] Carrier configuration. Specially, a NULL config means to disable the carrier modulation or demodulation feature - - Returns ESP_OK: Apply carrier configuration successfully ESP_ERR_INVALID_ARG: Apply carrier configuration failed because of invalid argument ESP_FAIL: Apply carrier configuration failed because of other error - - esp_err_t rmt_enable(rmt_channel_handle_t channel) Enable the RMT channel. Note This function will acquire a PM lock that might be installed during channel allocation - Parameters channel -- [in] RMT generic channel that created by rmt_new_tx_channel()or rmt_new_rx_channel() - Returns ESP_OK: Enable RMT channel successfully ESP_ERR_INVALID_ARG: Enable RMT channel failed because of invalid argument ESP_ERR_INVALID_STATE: Enable RMT channel failed because it's enabled already ESP_FAIL: Enable RMT channel failed because of other error - - esp_err_t rmt_disable(rmt_channel_handle_t channel) Disable the RMT channel. Note This function will release a PM lock that might be installed during channel allocation - Parameters channel -- [in] RMT generic channel that created by rmt_new_tx_channel()or rmt_new_rx_channel() - Returns ESP_OK: Disable RMT channel successfully ESP_ERR_INVALID_ARG: Disable RMT channel failed because of invalid argument ESP_ERR_INVALID_STATE: Disable RMT channel failed because it's not enabled yet ESP_FAIL: Disable RMT channel failed because of other error - Structures - struct rmt_carrier_config_t RMT carrier wave configuration (for either modulation or demodulation) Public Members - uint32_t frequency_hz Carrier wave frequency, in Hz, 0 means disabling the carrier - float duty_cycle Carrier wave duty cycle (0~100%) - uint32_t polarity_active_low Specify the polarity of carrier, by default it's modulated to base signal's high level - uint32_t always_on If set, the carrier can always exist even there's not transfer undergoing - struct rmt_carrier_config_t::[anonymous] flags Carrier config flags - uint32_t frequency_hz Header File This header file can be included with: #include "driver/rmt_encoder.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t rmt_new_bytes_encoder(const rmt_bytes_encoder_config_t *config, rmt_encoder_handle_t *ret_encoder) Create RMT bytes encoder, which can encode byte stream into RMT symbols. - Parameters config -- [in] Bytes encoder configuration ret_encoder -- [out] Returned encoder handle - - Returns ESP_OK: Create RMT bytes encoder successfully ESP_ERR_INVALID_ARG: Create RMT bytes encoder failed because of invalid argument ESP_ERR_NO_MEM: Create RMT bytes encoder failed because out of memory ESP_FAIL: Create RMT bytes encoder failed because of other error - - esp_err_t rmt_bytes_encoder_update_config(rmt_encoder_handle_t bytes_encoder, const rmt_bytes_encoder_config_t *config) Update the configuration of the bytes encoder. Note The configurations of the bytes encoder is also set up by rmt_new_bytes_encoder(). This function is used to update the configuration of the bytes encoder at runtime. - Parameters bytes_encoder -- [in] Bytes encoder handle, created by e.g rmt_new_bytes_encoder() config -- [in] Bytes encoder configuration - - Returns ESP_OK: Update RMT bytes encoder successfully ESP_ERR_INVALID_ARG: Update RMT bytes encoder failed because of invalid argument ESP_FAIL: Update RMT bytes encoder failed because of other error - - esp_err_t rmt_new_copy_encoder(const rmt_copy_encoder_config_t *config, rmt_encoder_handle_t *ret_encoder) Create RMT copy encoder, which copies the given RMT symbols into RMT memory. - Parameters config -- [in] Copy encoder configuration ret_encoder -- [out] Returned encoder handle - - Returns ESP_OK: Create RMT copy encoder successfully ESP_ERR_INVALID_ARG: Create RMT copy encoder failed because of invalid argument ESP_ERR_NO_MEM: Create RMT copy encoder failed because out of memory ESP_FAIL: Create RMT copy encoder failed because of other error - - esp_err_t rmt_del_encoder(rmt_encoder_handle_t encoder) Delete RMT encoder. - Parameters encoder -- [in] RMT encoder handle, created by e.g rmt_new_bytes_encoder() - Returns ESP_OK: Delete RMT encoder successfully ESP_ERR_INVALID_ARG: Delete RMT encoder failed because of invalid argument ESP_FAIL: Delete RMT encoder failed because of other error - - esp_err_t rmt_encoder_reset(rmt_encoder_handle_t encoder) Reset RMT encoder. - Parameters encoder -- [in] RMT encoder handle, created by e.g rmt_new_bytes_encoder() - Returns ESP_OK: Reset RMT encoder successfully ESP_ERR_INVALID_ARG: Reset RMT encoder failed because of invalid argument ESP_FAIL: Reset RMT encoder failed because of other error - - void *rmt_alloc_encoder_mem(size_t size) A helper function to allocate a proper memory for RMT encoder. - Parameters size -- Size of memory to be allocated - Returns Pointer to the allocated memory if the allocation is successful, NULL otherwise Structures - struct rmt_encoder_t Interface of RMT encoder. Public Members - size_t (*encode)(rmt_encoder_t *encoder, rmt_channel_handle_t tx_channel, const void *primary_data, size_t data_size, rmt_encode_state_t *ret_state) Encode the user data into RMT symbols and write into RMT memory. Note The encoding function will also be called from an ISR context, thus the function must not call any blocking API. Note It's recommended to put this function implementation in the IRAM, to achieve a high performance and less interrupt latency. - Param encoder [in] Encoder handle - Param tx_channel [in] RMT TX channel handle, returned from rmt_new_tx_channel() - Param primary_data [in] App data to be encoded into RMT symbols - Param data_size [in] Size of primary_data, in bytes - Param ret_state [out] Returned current encoder's state - Return Number of RMT symbols that the primary data has been encoded into - esp_err_t (*reset)(rmt_encoder_t *encoder) Reset encoding state. - Param encoder [in] Encoder handle - Return ESP_OK: reset encoder successfully ESP_FAIL: reset encoder failed - - esp_err_t (*del)(rmt_encoder_t *encoder) Delete encoder object. - Param encoder [in] Encoder handle - Return ESP_OK: delete encoder successfully ESP_FAIL: delete encoder failed - - size_t (*encode)(rmt_encoder_t *encoder, rmt_channel_handle_t tx_channel, const void *primary_data, size_t data_size, rmt_encode_state_t *ret_state) - struct rmt_bytes_encoder_config_t Bytes encoder configuration. Public Members - rmt_symbol_word_t bit0 How to represent BIT0 in RMT symbol - rmt_symbol_word_t bit1 How to represent BIT1 in RMT symbol - uint32_t msb_first Whether to encode MSB bit first - struct rmt_bytes_encoder_config_t::[anonymous] flags Encoder config flag - rmt_symbol_word_t bit0 - struct rmt_copy_encoder_config_t Copy encoder configuration. Enumerations - enum rmt_encode_state_t RMT encoding state. Values: - enumerator RMT_ENCODING_RESET The encoding session is in reset state - enumerator RMT_ENCODING_COMPLETE The encoding session is finished, the caller can continue with subsequent encoding - enumerator RMT_ENCODING_MEM_FULL The encoding artifact memory is full, the caller should return from current encoding session - enumerator RMT_ENCODING_RESET Header File This header file can be included with: #include "driver/rmt_types.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Structures - struct rmt_tx_done_event_data_t Type of RMT TX done event data. Public Members - size_t num_symbols The number of transmitted RMT symbols, including one EOF symbol, which is appended by the driver to mark the end of a transmission. For a loop transmission, this value only counts for one round. - size_t num_symbols - struct rmt_rx_done_event_data_t Type of RMT RX done event data. Public Members - rmt_symbol_word_t *received_symbols Point to the received RMT symbols - size_t num_symbols The number of received RMT symbols - rmt_symbol_word_t *received_symbols Type Definitions - typedef struct rmt_channel_t *rmt_channel_handle_t Type of RMT channel handle. - typedef struct rmt_sync_manager_t *rmt_sync_manager_handle_t Type of RMT synchronization manager handle. - typedef struct rmt_encoder_t *rmt_encoder_handle_t Type of RMT encoder handle. - typedef bool (*rmt_tx_done_callback_t)(rmt_channel_handle_t tx_chan, const rmt_tx_done_event_data_t *edata, void *user_ctx) Prototype of RMT event callback. - Param tx_chan [in] RMT channel handle, created from rmt_new_tx_channel() - Param edata [in] Point to RMT event data. The lifecycle of this pointer memory is inside this function, user should copy it into static memory if used outside this function. - Param user_ctx [in] User registered context, passed from rmt_tx_register_event_callbacks() - Return Whether a high priority task has been waken up by this callback function - typedef bool (*rmt_rx_done_callback_t)(rmt_channel_handle_t rx_chan, const rmt_rx_done_event_data_t *edata, void *user_ctx) Prototype of RMT event callback. - Param rx_chan [in] RMT channel handle, created from rmt_new_rx_channel() - Param edata [in] Point to RMT event data. The lifecycle of this pointer memory is inside this function, user should copy it into static memory if used outside this function. - Param user_ctx [in] User registered context, passed from rmt_rx_register_event_callbacks() - Return Whether a high priority task has been waken up by this function Header File This header file can be included with: #include "hal/rmt_types.h" Unions - union rmt_symbol_word_t - #include <rmt_types.h> The layout of RMT symbol stored in memory, which is decided by the hardware design. Type Definitions - typedef soc_periph_rmt_clk_src_t rmt_clock_source_t RMT group clock source. Note User should select the clock source based on the power and resolution requirement - 1 Different ESP chip series might have different numbers of RMT channels. Please refer to [TRM] for details. The driver does not forbid you from applying for more RMT channels, but it returns an error when there are no hardware resources available. Please always check the return value when doing Resource Allocation. - 2 The callback function, e.g., rmt_tx_event_callbacks_t::on_trans_done, and the functions invoked by itself should also reside in IRAM, users need to take care of this by themselves.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/rmt.html
ESP-IDF Programming Guide v5.2.1 documentation
null
SD SPI Host Driver
null
espressif.com
2016-01-01
8e49cc11e213b299
null
null
SD SPI Host Driver Overview The SD SPI host driver allows communication with one or more SD cards using the SPI Master driver, which utilizes the SPI host. Each card is accessed through an SD SPI device, represented by an SD SPI handle sdspi_dev_handle_t , which returns when the device is attached to an SPI bus by calling sdspi_host_init_device() . It is important to note that the SPI bus should be initialized beforehand by spi_bus_initialize() . This driver's naming pattern was adopted from the SDMMC Host Driver due to their similarity. Likewise, the APIs of both drivers are also very similar. SD SPI driver that accesses the SD card in SPI mode offers lower throughput but makes pin selection more flexible. With the help of the GPIO matrix, an SPI peripheral's signals can be routed to any ESP32 pin. Otherwise, if an SDMMC host driver is used (see SDMMC Host Driver) to access the card in SD 1-bit/4-bit mode, higher throughput can be reached while requiring routing the signals through their dedicated IO_MUX pins only. With the help of SPI Master Driver the SD SPI host driver based on, the SPI bus can be shared among SD cards and other SPI devices. The SPI Master driver will handle exclusive access from different tasks. The SD SPI driver uses software-controlled CS signal. How to Use Firstly, use the macro SDSPI_DEVICE_CONFIG_DEFAULT to initialize the structure sdspi_device_config_t , which is used to initialize an SD SPI device. This macro will also fill in the default pin mappings, which are the same as the pin mappings of the SDMMC host driver. Modify the host and pins of the structure to desired value. Then call sdspi_host_init_device to initialize the SD SPI device and attach to its bus. Then use the SDSPI_HOST_DEFAULT macro to initialize the sdmmc_host_t structure, which is used to store the state and configurations of the upper layer (SD/SDIO/MMC driver). Modify the slot parameter of the structure to the SD SPI device SD SPI handle just returned from sdspi_host_init_device . Call sdmmc_card_init with the sdmmc_host_t to probe and initialize the SD card. Now you can use SD/SDIO/MMC driver functions to access your card! Other Details Only the following driver's API functions are normally used by most applications: Other functions are mostly used by the protocol level SD/SDIO/MMC driver via function pointers in the sdmmc_host_t structure. For more details, see SD/SDIO/MMC Driver. Note SD over SPI does not support speeds above SDMMC_FREQ_DEFAULT due to the limitations of the SPI driver. Warning If you want to share the SPI bus among SD card and other SPI devices, there are some restrictions, see Sharing the SPI Bus Among SD Cards and Other SPI Devices. API Reference Header File This header file can be included with: #include "driver/sdspi_host.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t sdspi_host_init(void) Initialize SD SPI driver. Note This function is not thread safe Returns ESP_OK on success other error codes may be returned in future versions ESP_OK on success other error codes may be returned in future versions ESP_OK on success Returns ESP_OK on success other error codes may be returned in future versions esp_err_t sdspi_host_init_device(const sdspi_device_config_t *dev_config, sdspi_dev_handle_t *out_handle) Attach and initialize an SD SPI device on the specific SPI bus. Note This function is not thread safe Note Initialize the SPI bus by spi_bus_initialize() before calling this function. Note The SDIO over sdspi needs an extra interrupt line. Call gpio_install_isr_service() before this function. Parameters dev_config -- pointer to device configuration structure out_handle -- Output of the handle to the sdspi device. dev_config -- pointer to device configuration structure out_handle -- Output of the handle to the sdspi device. dev_config -- pointer to device configuration structure Returns ESP_OK on success ESP_ERR_INVALID_ARG if sdspi_host_init_device has invalid arguments ESP_ERR_NO_MEM if memory can not be allocated other errors from the underlying spi_master and gpio drivers ESP_OK on success ESP_ERR_INVALID_ARG if sdspi_host_init_device has invalid arguments ESP_ERR_NO_MEM if memory can not be allocated other errors from the underlying spi_master and gpio drivers ESP_OK on success Parameters dev_config -- pointer to device configuration structure out_handle -- Output of the handle to the sdspi device. Returns ESP_OK on success ESP_ERR_INVALID_ARG if sdspi_host_init_device has invalid arguments ESP_ERR_NO_MEM if memory can not be allocated other errors from the underlying spi_master and gpio drivers esp_err_t sdspi_host_remove_device(sdspi_dev_handle_t handle) Remove an SD SPI device. Parameters handle -- Handle of the SD SPI device Returns Always ESP_OK Parameters handle -- Handle of the SD SPI device Returns Always ESP_OK esp_err_t sdspi_host_do_transaction(sdspi_dev_handle_t handle, sdmmc_command_t *cmdinfo) Send command to the card and get response. This function returns when command is sent and response is received, or data is transferred, or timeout occurs. Note This function is not thread safe w.r.t. init/deinit functions, and bus width/clock speed configuration functions. Multiple tasks can call sdspi_host_do_transaction as long as other sdspi_host_* functions are not called. Parameters handle -- Handle of the sdspi device cmdinfo -- pointer to structure describing command and data to transfer handle -- Handle of the sdspi device cmdinfo -- pointer to structure describing command and data to transfer handle -- Handle of the sdspi device Returns ESP_OK on success ESP_ERR_TIMEOUT if response or data transfer has timed out ESP_ERR_INVALID_CRC if response or data transfer CRC check has failed ESP_ERR_INVALID_RESPONSE if the card has sent an invalid response ESP_OK on success ESP_ERR_TIMEOUT if response or data transfer has timed out ESP_ERR_INVALID_CRC if response or data transfer CRC check has failed ESP_ERR_INVALID_RESPONSE if the card has sent an invalid response ESP_OK on success Parameters handle -- Handle of the sdspi device cmdinfo -- pointer to structure describing command and data to transfer Returns ESP_OK on success ESP_ERR_TIMEOUT if response or data transfer has timed out ESP_ERR_INVALID_CRC if response or data transfer CRC check has failed ESP_ERR_INVALID_RESPONSE if the card has sent an invalid response esp_err_t sdspi_host_set_card_clk(sdspi_dev_handle_t host, uint32_t freq_khz) Set card clock frequency. Currently only integer fractions of 40MHz clock can be used. For High Speed cards, 40MHz can be used. For Default Speed cards, 20MHz can be used. Note This function is not thread safe Parameters host -- Handle of the sdspi device freq_khz -- card clock frequency, in kHz host -- Handle of the sdspi device freq_khz -- card clock frequency, in kHz host -- Handle of the sdspi device Returns ESP_OK on success other error codes may be returned in the future ESP_OK on success other error codes may be returned in the future ESP_OK on success Parameters host -- Handle of the sdspi device freq_khz -- card clock frequency, in kHz Returns ESP_OK on success other error codes may be returned in the future esp_err_t sdspi_host_get_real_freq(sdspi_dev_handle_t handle, int *real_freq_khz) Calculate working frequency for specific device. Parameters handle -- SDSPI device handle real_freq_khz -- [out] output parameter to hold the calculated frequency (in kHz) handle -- SDSPI device handle real_freq_khz -- [out] output parameter to hold the calculated frequency (in kHz) handle -- SDSPI device handle Returns ESP_ERR_INVALID_ARG : handle is NULL or invalid or real_freq_khz parameter is NULL ESP_OK : Success ESP_ERR_INVALID_ARG : handle is NULL or invalid or real_freq_khz parameter is NULL ESP_OK : Success ESP_ERR_INVALID_ARG : handle is NULL or invalid or real_freq_khz parameter is NULL Parameters handle -- SDSPI device handle real_freq_khz -- [out] output parameter to hold the calculated frequency (in kHz) Returns ESP_ERR_INVALID_ARG : handle is NULL or invalid or real_freq_khz parameter is NULL ESP_OK : Success esp_err_t sdspi_host_deinit(void) Release resources allocated using sdspi_host_init. Note This function is not thread safe Returns ESP_OK on success ESP_ERR_INVALID_STATE if sdspi_host_init function has not been called ESP_OK on success ESP_ERR_INVALID_STATE if sdspi_host_init function has not been called ESP_OK on success Returns ESP_OK on success ESP_ERR_INVALID_STATE if sdspi_host_init function has not been called esp_err_t sdspi_host_io_int_enable(sdspi_dev_handle_t handle) Enable SDIO interrupt. Parameters handle -- Handle of the sdspi device Returns ESP_OK on success ESP_OK on success ESP_OK on success Parameters handle -- Handle of the sdspi device Returns ESP_OK on success esp_err_t sdspi_host_io_int_wait(sdspi_dev_handle_t handle, TickType_t timeout_ticks) Wait for SDIO interrupt until timeout. Parameters handle -- Handle of the sdspi device timeout_ticks -- Ticks to wait before timeout. handle -- Handle of the sdspi device timeout_ticks -- Ticks to wait before timeout. handle -- Handle of the sdspi device Returns ESP_OK on success ESP_OK on success ESP_OK on success Parameters handle -- Handle of the sdspi device timeout_ticks -- Ticks to wait before timeout. Returns ESP_OK on success Structures struct sdspi_device_config_t Extra configuration for SD SPI device. Public Members spi_host_device_t host_id SPI host to use, SPIx_HOST (see spi_types.h). spi_host_device_t host_id SPI host to use, SPIx_HOST (see spi_types.h). gpio_num_t gpio_cs GPIO number of CS signal. gpio_num_t gpio_cs GPIO number of CS signal. gpio_num_t gpio_cd GPIO number of card detect signal. gpio_num_t gpio_cd GPIO number of card detect signal. gpio_num_t gpio_wp GPIO number of write protect signal. gpio_num_t gpio_wp GPIO number of write protect signal. gpio_num_t gpio_int GPIO number of interrupt line (input) for SDIO card. gpio_num_t gpio_int GPIO number of interrupt line (input) for SDIO card. bool gpio_wp_polarity GPIO write protect polarity 0 means "active low", i.e. card is protected when the GPIO is low; 1 means "active high", i.e. card is protected when GPIO is high. bool gpio_wp_polarity GPIO write protect polarity 0 means "active low", i.e. card is protected when the GPIO is low; 1 means "active high", i.e. card is protected when GPIO is high. spi_host_device_t host_id Macros SDSPI_DEFAULT_HOST SDSPI_DEFAULT_DMA SDSPI_HOST_DEFAULT() Default sdmmc_host_t structure initializer for SD over SPI driver. Uses SPI mode and max frequency set to 20MHz 'slot' should be set to an sdspi device initialized by sdspi_host_init_device() . SDSPI_SLOT_NO_CS indicates that card select line is not used SDSPI_SLOT_NO_CD indicates that card detect line is not used SDSPI_SLOT_NO_WP indicates that write protect line is not used SDSPI_SLOT_NO_INT indicates that interrupt line is not used SDSPI_IO_ACTIVE_LOW SDSPI_DEVICE_CONFIG_DEFAULT() Macro defining default configuration of SD SPI device. Type Definitions typedef int sdspi_dev_handle_t Handle representing an SD SPI device.
SD SPI Host Driver Overview The SD SPI host driver allows communication with one or more SD cards using the SPI Master driver, which utilizes the SPI host. Each card is accessed through an SD SPI device, represented by an SD SPI handle sdspi_dev_handle_t, which returns when the device is attached to an SPI bus by calling sdspi_host_init_device(). It is important to note that the SPI bus should be initialized beforehand by spi_bus_initialize(). This driver's naming pattern was adopted from the SDMMC Host Driver due to their similarity. Likewise, the APIs of both drivers are also very similar. SD SPI driver that accesses the SD card in SPI mode offers lower throughput but makes pin selection more flexible. With the help of the GPIO matrix, an SPI peripheral's signals can be routed to any ESP32 pin. Otherwise, if an SDMMC host driver is used (see SDMMC Host Driver) to access the card in SD 1-bit/4-bit mode, higher throughput can be reached while requiring routing the signals through their dedicated IO_MUX pins only. With the help of SPI Master Driver the SD SPI host driver based on, the SPI bus can be shared among SD cards and other SPI devices. The SPI Master driver will handle exclusive access from different tasks. The SD SPI driver uses software-controlled CS signal. How to Use Firstly, use the macro SDSPI_DEVICE_CONFIG_DEFAULT to initialize the structure sdspi_device_config_t, which is used to initialize an SD SPI device. This macro will also fill in the default pin mappings, which are the same as the pin mappings of the SDMMC host driver. Modify the host and pins of the structure to desired value. Then call sdspi_host_init_device to initialize the SD SPI device and attach to its bus. Then use the SDSPI_HOST_DEFAULT macro to initialize the sdmmc_host_t structure, which is used to store the state and configurations of the upper layer (SD/SDIO/MMC driver). Modify the slot parameter of the structure to the SD SPI device SD SPI handle just returned from sdspi_host_init_device. Call sdmmc_card_init with the sdmmc_host_t to probe and initialize the SD card. Now you can use SD/SDIO/MMC driver functions to access your card! Other Details Only the following driver's API functions are normally used by most applications: Other functions are mostly used by the protocol level SD/SDIO/MMC driver via function pointers in the sdmmc_host_t structure. For more details, see SD/SDIO/MMC Driver. Note SD over SPI does not support speeds above SDMMC_FREQ_DEFAULT due to the limitations of the SPI driver. Warning If you want to share the SPI bus among SD card and other SPI devices, there are some restrictions, see Sharing the SPI Bus Among SD Cards and Other SPI Devices. API Reference Header File This header file can be included with: #include "driver/sdspi_host.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t sdspi_host_init(void) Initialize SD SPI driver. Note This function is not thread safe - Returns ESP_OK on success other error codes may be returned in future versions - - esp_err_t sdspi_host_init_device(const sdspi_device_config_t *dev_config, sdspi_dev_handle_t *out_handle) Attach and initialize an SD SPI device on the specific SPI bus. Note This function is not thread safe Note Initialize the SPI bus by spi_bus_initialize()before calling this function. Note The SDIO over sdspi needs an extra interrupt line. Call gpio_install_isr_service()before this function. - Parameters dev_config -- pointer to device configuration structure out_handle -- Output of the handle to the sdspi device. - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if sdspi_host_init_device has invalid arguments ESP_ERR_NO_MEM if memory can not be allocated other errors from the underlying spi_master and gpio drivers - - esp_err_t sdspi_host_remove_device(sdspi_dev_handle_t handle) Remove an SD SPI device. - Parameters handle -- Handle of the SD SPI device - Returns Always ESP_OK - esp_err_t sdspi_host_do_transaction(sdspi_dev_handle_t handle, sdmmc_command_t *cmdinfo) Send command to the card and get response. This function returns when command is sent and response is received, or data is transferred, or timeout occurs. Note This function is not thread safe w.r.t. init/deinit functions, and bus width/clock speed configuration functions. Multiple tasks can call sdspi_host_do_transaction as long as other sdspi_host_* functions are not called. - Parameters handle -- Handle of the sdspi device cmdinfo -- pointer to structure describing command and data to transfer - - Returns ESP_OK on success ESP_ERR_TIMEOUT if response or data transfer has timed out ESP_ERR_INVALID_CRC if response or data transfer CRC check has failed ESP_ERR_INVALID_RESPONSE if the card has sent an invalid response - - esp_err_t sdspi_host_set_card_clk(sdspi_dev_handle_t host, uint32_t freq_khz) Set card clock frequency. Currently only integer fractions of 40MHz clock can be used. For High Speed cards, 40MHz can be used. For Default Speed cards, 20MHz can be used. Note This function is not thread safe - Parameters host -- Handle of the sdspi device freq_khz -- card clock frequency, in kHz - - Returns ESP_OK on success other error codes may be returned in the future - - esp_err_t sdspi_host_get_real_freq(sdspi_dev_handle_t handle, int *real_freq_khz) Calculate working frequency for specific device. - Parameters handle -- SDSPI device handle real_freq_khz -- [out] output parameter to hold the calculated frequency (in kHz) - - Returns ESP_ERR_INVALID_ARG : handleis NULL or invalid or real_freq_khzparameter is NULL ESP_OK : Success - - esp_err_t sdspi_host_deinit(void) Release resources allocated using sdspi_host_init. Note This function is not thread safe - Returns ESP_OK on success ESP_ERR_INVALID_STATE if sdspi_host_init function has not been called - - esp_err_t sdspi_host_io_int_enable(sdspi_dev_handle_t handle) Enable SDIO interrupt. - Parameters handle -- Handle of the sdspi device - Returns ESP_OK on success - - esp_err_t sdspi_host_io_int_wait(sdspi_dev_handle_t handle, TickType_t timeout_ticks) Wait for SDIO interrupt until timeout. - Parameters handle -- Handle of the sdspi device timeout_ticks -- Ticks to wait before timeout. - - Returns ESP_OK on success - Structures - struct sdspi_device_config_t Extra configuration for SD SPI device. Public Members - spi_host_device_t host_id SPI host to use, SPIx_HOST (see spi_types.h). - gpio_num_t gpio_cs GPIO number of CS signal. - gpio_num_t gpio_cd GPIO number of card detect signal. - gpio_num_t gpio_wp GPIO number of write protect signal. - gpio_num_t gpio_int GPIO number of interrupt line (input) for SDIO card. - bool gpio_wp_polarity GPIO write protect polarity 0 means "active low", i.e. card is protected when the GPIO is low; 1 means "active high", i.e. card is protected when GPIO is high. - spi_host_device_t host_id Macros - SDSPI_DEFAULT_HOST - SDSPI_DEFAULT_DMA - SDSPI_HOST_DEFAULT() Default sdmmc_host_t structure initializer for SD over SPI driver. Uses SPI mode and max frequency set to 20MHz 'slot' should be set to an sdspi device initialized by sdspi_host_init_device(). - SDSPI_SLOT_NO_CS indicates that card select line is not used - SDSPI_SLOT_NO_CD indicates that card detect line is not used - SDSPI_SLOT_NO_WP indicates that write protect line is not used - SDSPI_SLOT_NO_INT indicates that interrupt line is not used - SDSPI_IO_ACTIVE_LOW - SDSPI_DEVICE_CONFIG_DEFAULT() Macro defining default configuration of SD SPI device. Type Definitions - typedef int sdspi_dev_handle_t Handle representing an SD SPI device.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/sdspi_host.html
ESP-IDF Programming Guide v5.2.1 documentation
null
SDIO Card Slave Driver
null
espressif.com
2016-01-01
8edafa5fe432bd9b
null
null
SDIO Card Slave Driver Overview The ESP32 SDIO Card host and slave peripherals share two sets of pins, as shown in the table below. The first set is usually occupied by the SPI0 bus, which is responsible for the SPI flash holding the code to run. This means the SDIO slave driver can only run on the second set of pins while the SDIO host is not using it. The SDIO slave can run under three modes: SPI, 1-bit SD, and 4-bit SD modes. Based on the signals on the interface, the device can determine the current mode and configure itself to adapt to that mode. Later, the slave driver can communicate with the slave device to properly handle commands and data transfers. According to the SDIO specification, the CMD and DAT0-3 signal lines should be pulled up whether in 1-bit SD, 4-bit SD or SPI mode. Connections Pin Name Corresponding Pins in SPI Mode GPIO Number (Slot 1) GPIO Number (Slot 2) CLK SCLK 6 14 CMD MOSI 11 15 DAT0 MISO 7 2 DAT1 Interrupt 8 4 DAT2 N.C. (pullup) 9 12 DAT3 #CS 10 13 1-bit SD mode: Connect CLK, CMD, DAT0, DAT1 pins, and the ground. 4-bit SD mode: Connect all pins, and the ground. SPI mode: Connect SCLK, MOSI, MISO, Interrupt, #CS pins, and the ground. Note Please check if CMD and DATA lines DAT0-DAT3 of the card are properly pulled up by 10 KOhm - 90 KOhm resistors, which should be ensured even in 1-bit mode or SPI mode. Most official modules do not offer these pullups internally. If you are using official development boards, check Overview of Compatibility to see whether your development boards have such pullups. Note Most official modules have conflicts on strapping pins with the SDIO slave function. If you are using an ESP32 module with 3.3 V flash inside, when you are developing on the module for the first time, you will need to perform an eFuse burn-in prior to development. This will adjust the pin configuration of the module to make the module compatible with SDIO functionality. See Overview of Compatibility for details on how to configure this. Here is a list of modules/kits with 3.3 V flash: Modules: All modules except ESP32-WROVER, ESP32-WROVER-I, ESP32-S3-WROOM-2, and please check Modules Overview for module list Kits: ESP32-PICO-KIT, ESP32-DevKitC (up to v4), ESP32-WROVER-KIT (v4.1 [also known as ESP32-WROVER-KIT-VB], v2, v1 [also known as DevKitJ v1]) You can tell the version of your ESP23-WROVER-KIT version from the module on it: v4.1 are with ESP32-WROVER-B modules, v3 are with ESP32-WROVER modules, while v2 and v1 are with ESP32-WROOM-32 modules. Refer to SD Pull-up Requirements for more technical details of the pullups. The host initializes the slave into SD mode by sending the CMD0 command with the DAT3 pin set to a high level. Alternatively, the host initializes the SPI mode by sending CMD0 with CS pin low, which is the same pin as DAT3. After the initialization, the host can enable the 4-bit SD mode by writing CCCR register 0x07 by CMD52. All the bus detection processes are handled by the slave peripheral. The host has to communicate with the slave by an ESP-slave-specific protocol. The slave driver offers three services over Function 1 access by CMD52 and CMD53: sending and receiving FIFO 52 R/W registers (8-bit) shared by host and slave 16 interrupt sources (8 from host to slave, and 8 from slave to host) Terminology The SDIO slave driver uses the following terms: A transfer is initiated by a command token from the host and may consist of a response and multiple data blocks. The core mechanism of the ESP32 SDIO slave driver involves data exchange and communication through transfers. Sending: slave to host transfers. Receiving: host to slave transfers. Note The register names in ESP32 Technical Reference Manual > SDIO Slave Controller [PDF] are organized from the host's perspective. For instance, RX registers indicate sending, while TX registers denote receiving. In our driver implementation, we've chosen not to utilize the terms TX or RX to prevent any potential ambiguities. FIFO: A designated address within Function 1 that can be accessed using CMD53 commands for reading or writing substantial volumes of data. The address corresponds to the length intended for reading from or writing to the slave in a single transfer: requested length = 0x1F800 – address. Ownership: When the driver assumes ownership of a buffer, it means that the driver has the capability to perform random read/write operations on the buffer (often via DMA). The application should not read/write the buffer until the ownership is returned to the application. If the application reads from a buffer owned by a receiving driver, the data read can be random; similarly, if the application writes to a buffer owned by a sending driver, the data sent may be corrupted. Requested length: The length requested in one transfer determined by the FIFO address. Transfer length: The length requested in one transfer determined by the CMD53 byte/block count field. Note Requested length is different from the transfer length. In the context of ESP32 SDIO slave DMA, the operation is based on the requested length rather than the transfer length. This means the DMA controller will process the data transfer according to the requested length, ensuring that only data within the requested length is transferred. The transfer length should be no shorter than the requested length, and the rest part is filled with 0 during sending or discard during receiving. Receiving buffer size: The buffer size is pre-defined between the host and the slave before communication starts. The slave application has to set the buffer size during initialization by the recv_buffer_size parameter in the sdio_slave_config_t structure. Interrupts: The ESP32 SDIO slave supports interrupts in two directions: from host to slave (referred to as slave interrupts) and from slave to host (referred to as host interrupts). For more details, refer to Interrupts. Registers: Specific addresses in Function 1 accessed by CMD52 or CMD53. Communication with ESP SDIO Slave The host should initialize the ESP32 SDIO slave according to the standard SDIO initialization process (Sector 3.1.2 of SDIO Simplified Specification), which is described briefly in ESP SDIO Slave Initialization. Furthermore, there is an ESP32-specific upper-level communication protocol built upon the foundation of CMD52/CMD53 to Function 1. Within this particular communication protocol, the master and slave engage in data exchange and communication through the utilization of CMD52/CMD53 commands. For more detailed information, please consult the ESP SDIO Slave Protocol section. There is also a component ESP Serial Slave Link designed for ESP32 master to communicate with ESP32 SDIO slave. See example peripherals/sdio when programming your host. Interrupts There are interrupts from host to slave, and from slave to host to help communicating conveniently. Slave Interrupts The host can trigger an interruption in the slave by writing a single bit to the 0x08D register. As soon as any bit within the register is set, an interrupt is generated, prompting the SDIO slave driver to invoke the callback function specified in the slave_intr_cb member of the sdio_slave_config_t structure. Note The callback function is called in the ISR. Do not use any delay, loop or blocking function in the callback, e.g., mutex. Similar to the previous information, there's an alternative set of functions available. You can call sdio_slave_wait_int to wait for an interrupt within a certain time, or call sdio_slave_clear_int to clear interrupts from host. The callback function can work with the wait functions perfectly. Host Interrupts The slave can interrupt the host by an interrupt line at certain time, which is level-sensitive, i.e., the interrupt signal can be triggered by detecting the level change of the interrupt line. When the host see the interrupt line pulled down, it may read the slave interrupt status register, to see the interrupt source. Host can clear interrupt bits, or choose to disable a interrupt source. The interrupt line holds active until all the sources are cleared or disabled. There are several dedicated interrupt sources as well as general-purpose sources. see sdio_slave_hostint_t for more information. Receiving FIFO When the host is going to send the slave some packets, it has to check whether the slave is ready to receive by reading the buffer number of slave. To allow the host sending data to the slave, the application has to load buffers to the slave driver by the following steps: Register the buffer by calling sdio_slave_recv_register_buf , and get the handle of the registered buffer. The driver allocates memory for the linked-list descriptor needed to link the buffer onto the hardware. The size of these buffers should equal to the Receiving buffer size. Load buffers onto the driver by passing the buffer handle to sdio_slave_recv_load_buf . Get the received data by calling sdio_slave_recv or sdio_slave_recv_packet . If a non-blocking call is needed, set wait=0 . The difference between two APIs is that, sdio_slave_recv_packet gives more information about packet, which can consist of several buffers. When ESP_ERR_NOT_FINISHED is returned by this API, you should call this API iteratively until the return value is ESP_OK . All the continuous buffers returned with ESP_ERR_NOT_FINISHED , together with the last buffer returned with ESP_OK , belong to one packet from the host. Call sdio_slave_recv_get_buf to get the address of the received data, and the actual length received in each buffer. The packet length is the sum of received length of all the buffers in the packet. If the host never send data longer than the Receiving buffer size, or you do not care about the packet boundary (e.g., the data is only a byte stream), you can call the simpler version sdio_slave_recv instead. Pass the handle of processed buffer back to the driver by sdio_recv_load_buf again. Note To minimize data copying overhead, the driver itself does not maintain any internal buffer; it is the responsibility of the application to promptly provide new buffers. The DMA system automatically stores received data into these buffers. Sending FIFO Each time the slave has data to send, it raises an interrupt, and the host requests the packet length. There are two sending modes: Stream Mode: When a buffer is loaded into the driver, the buffer length is included into the packet length requested by host in the incoming communications. This is irrespective of whether previous packets have been sent or not. In other words, the length of the newly loaded buffer is included into the length of the packet requested by the host, even if there are previously unsent packets. This enables the host to receive data from several buffers in a single transfer. Packet Mode: The packet length is updated packet by packet, and only when previous packet is sent. This means that the host can only get data of one buffer in one transfer. Note To avoid overhead from copying data, the driver itself does not have any buffer inside. Namely, the DMA takes data directly from the buffer provided by the application. The application should not touch the buffer until the sending is finished, so as to ensure that the data is transferred correctly. The sending mode can be set in the sending_mode member of sdio_slave_config_t , and the buffer numbers can be set in the send_queue_size . All the buffers are restricted to be no larger than 4092 bytes. Though in the stream mode, several buffers can be sent in one transfer, each buffer is still counted as one in the queue. The application can call sdio_slave_transmit to send packets. In this case, the function returns when the transfer is successfully done, so the queue is not fully used. When higher efficiency is required, the application can use the following functions instead: Pass buffer information (address, length, as well as an arg indicating the buffer) to sdio_slave_send_queue . If non-blocking call is needed, set wait=0 . If the wait is not portMAX_DELAY (wait until success), application has to check the result to know whether the data is put in to the queue or discard. If non-blocking call is needed, set wait=0 . If the wait is not portMAX_DELAY (wait until success), application has to check the result to know whether the data is put in to the queue or discard. If non-blocking call is needed, set wait=0 . Call sdio_slave_send_get_finished to get and deal with a finished transfer. A buffer should be kept unmodified until returned from sdio_slave_send_get_finished . This means the buffer is actually sent to the host, rather than just staying in the queue. There are several ways to use the arg in the queue parameter: Directly point arg to a dynamic-allocated buffer, and use the arg to free it when transfer finished. Wrap transfer informations in a transfer structure, and point arg to the structure. You can use the structure to do more things like: typedef struct { uint8_t* buffer; size_t size; int id; }sdio_transfer_t; //and send as: sdio_transfer_t trans = { .buffer = ADDRESS_TO_SEND, .size = 8, .id = 3, //the 3rd transfer so far }; sdio_slave_send_queue(trans.buffer, trans.size, &trans, portMAX_DELAY); //... maybe more transfers are sent here //and deal with finished transfer as: sdio_transfer_t* arg = NULL; sdio_slave_send_get_finished((void**)&arg, portMAX_DELAY); ESP_LOGI("tag", "(%d) successfully send %d bytes of %p", arg->id, arg->size, arg->buffer); some_post_callback(arg); //do more things Work with the receiving part of this driver, and point arg to the receive buffer handle of this buffer, so that we can directly use the buffer to receive data when it is sent: uint8_t buffer[256]={1,2,3,4,5,6,7,8}; sdio_slave_buf_handle_t handle = sdio_slave_recv_register_buf(buffer); sdio_slave_send_queue(buffer, 8, handle, portMAX_DELAY); //... maybe more transfers are sent here //and load finished buffer to receive as sdio_slave_buf_handle_t handle = NULL; sdio_slave_send_get_finished((void**)&handle, portMAX_DELAY); sdio_slave_recv_load_buf(handle); For more about this, see peripherals/sdio. Application Example Slave/master communication: peripherals/sdio. API Reference Header File This header file can be included with: #include "hal/sdio_slave_types.h" Enumerations enum sdio_slave_hostint_t Mask of interrupts sending to the host. Values: enumerator SDIO_SLAVE_HOSTINT_BIT0 General purpose interrupt bit 0. enumerator SDIO_SLAVE_HOSTINT_BIT0 General purpose interrupt bit 0. enumerator SDIO_SLAVE_HOSTINT_BIT1 enumerator SDIO_SLAVE_HOSTINT_BIT1 enumerator SDIO_SLAVE_HOSTINT_BIT2 enumerator SDIO_SLAVE_HOSTINT_BIT2 enumerator SDIO_SLAVE_HOSTINT_BIT3 enumerator SDIO_SLAVE_HOSTINT_BIT3 enumerator SDIO_SLAVE_HOSTINT_BIT4 enumerator SDIO_SLAVE_HOSTINT_BIT4 enumerator SDIO_SLAVE_HOSTINT_BIT5 enumerator SDIO_SLAVE_HOSTINT_BIT5 enumerator SDIO_SLAVE_HOSTINT_BIT6 enumerator SDIO_SLAVE_HOSTINT_BIT6 enumerator SDIO_SLAVE_HOSTINT_BIT7 enumerator SDIO_SLAVE_HOSTINT_BIT7 enumerator SDIO_SLAVE_HOSTINT_SEND_NEW_PACKET New packet available. enumerator SDIO_SLAVE_HOSTINT_SEND_NEW_PACKET New packet available. enumerator SDIO_SLAVE_HOSTINT_BIT0 enum sdio_slave_timing_t Timing of SDIO slave. Values: enumerator SDIO_SLAVE_TIMING_PSEND_PSAMPLE Send at posedge, and sample at posedge. Default value for HS mode. If :c:macro: SDIO_SLAVE_FLAG_HIGH_SPEED is specified in :cpp:class: sdio_slave_config_t , this should be selected. Normally there's no problem using this to work in DS mode. enumerator SDIO_SLAVE_TIMING_PSEND_PSAMPLE Send at posedge, and sample at posedge. Default value for HS mode. If :c:macro: SDIO_SLAVE_FLAG_HIGH_SPEED is specified in :cpp:class: sdio_slave_config_t , this should be selected. Normally there's no problem using this to work in DS mode. enumerator SDIO_SLAVE_TIMING_NSEND_PSAMPLE Send at negedge, and sample at posedge. Default value for DS mode and below. If :c:macro: SDIO_SLAVE_FLAG_DEFAULT_SPEED is specified in :cpp:class: sdio_slave_config_t , this should be selected. enumerator SDIO_SLAVE_TIMING_NSEND_PSAMPLE Send at negedge, and sample at posedge. Default value for DS mode and below. If :c:macro: SDIO_SLAVE_FLAG_DEFAULT_SPEED is specified in :cpp:class: sdio_slave_config_t , this should be selected. enumerator SDIO_SLAVE_TIMING_PSEND_NSAMPLE Send at posedge, and sample at negedge. enumerator SDIO_SLAVE_TIMING_PSEND_NSAMPLE Send at posedge, and sample at negedge. enumerator SDIO_SLAVE_TIMING_NSEND_NSAMPLE Send at negedge, and sample at negedge. enumerator SDIO_SLAVE_TIMING_NSEND_NSAMPLE Send at negedge, and sample at negedge. enumerator SDIO_SLAVE_TIMING_PSEND_PSAMPLE enum sdio_slave_sending_mode_t Configuration of SDIO slave mode. Values: enumerator SDIO_SLAVE_SEND_STREAM Stream mode, all packets to send will be combined as one if possible. enumerator SDIO_SLAVE_SEND_STREAM Stream mode, all packets to send will be combined as one if possible. enumerator SDIO_SLAVE_SEND_PACKET Packet mode, one packets will be sent one after another (only increase packet_len if last packet sent). enumerator SDIO_SLAVE_SEND_PACKET Packet mode, one packets will be sent one after another (only increase packet_len if last packet sent). enumerator SDIO_SLAVE_SEND_STREAM Header File This header file can be included with: #include "driver/sdio_slave.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t sdio_slave_initialize(sdio_slave_config_t *config) Initialize the sdio slave driver Parameters config -- Configuration of the sdio slave driver. Returns ESP_ERR_NOT_FOUND if no free interrupt found. ESP_ERR_INVALID_STATE if already initialized. ESP_ERR_NO_MEM if fail due to memory allocation failed. ESP_OK if success ESP_ERR_NOT_FOUND if no free interrupt found. ESP_ERR_INVALID_STATE if already initialized. ESP_ERR_NO_MEM if fail due to memory allocation failed. ESP_OK if success ESP_ERR_NOT_FOUND if no free interrupt found. Parameters config -- Configuration of the sdio slave driver. Returns ESP_ERR_NOT_FOUND if no free interrupt found. ESP_ERR_INVALID_STATE if already initialized. ESP_ERR_NO_MEM if fail due to memory allocation failed. ESP_OK if success void sdio_slave_deinit(void) De-initialize the sdio slave driver to release the resources. esp_err_t sdio_slave_start(void) Start hardware for sending and receiving, as well as set the IOREADY1 to 1. Note The driver will continue sending from previous data and PKT_LEN counting, keep data received as well as start receiving from current TOKEN1 counting. See sdio_slave_reset . Returns ESP_ERR_INVALID_STATE if already started. ESP_OK otherwise. ESP_ERR_INVALID_STATE if already started. ESP_OK otherwise. ESP_ERR_INVALID_STATE if already started. Returns ESP_ERR_INVALID_STATE if already started. ESP_OK otherwise. void sdio_slave_stop(void) Stop hardware from sending and receiving, also set IOREADY1 to 0. Note this will not clear the data already in the driver, and also not reset the PKT_LEN and TOKEN1 counting. Call sdio_slave_reset to do that. esp_err_t sdio_slave_reset(void) Clear the data still in the driver, as well as reset the PKT_LEN and TOKEN1 counting. Returns always return ESP_OK. Returns always return ESP_OK. sdio_slave_buf_handle_t sdio_slave_recv_register_buf(uint8_t *start) Register buffer used for receiving. All buffers should be registered before used, and then can be used (again) in the driver by the handle returned. Note The driver will use and only use the amount of space specified in the recv_buffer_size member set in the sdio_slave_config_t . All buffers should be larger than that. The buffer is used by the DMA, so it should be DMA capable and 32-bit aligned. Parameters start -- The start address of the buffer. Returns The buffer handle if success, otherwise NULL. Parameters start -- The start address of the buffer. Returns The buffer handle if success, otherwise NULL. esp_err_t sdio_slave_recv_unregister_buf(sdio_slave_buf_handle_t handle) Unregister buffer from driver, and free the space used by the descriptor pointing to the buffer. Parameters handle -- Handle to the buffer to release. Returns ESP_OK if success, ESP_ERR_INVALID_ARG if the handle is NULL or the buffer is being used. Parameters handle -- Handle to the buffer to release. Returns ESP_OK if success, ESP_ERR_INVALID_ARG if the handle is NULL or the buffer is being used. esp_err_t sdio_slave_recv_load_buf(sdio_slave_buf_handle_t handle) Load buffer to the queue waiting to receive data. The driver takes ownership of the buffer until the buffer is returned by sdio_slave_send_get_finished after the transaction is finished. Parameters handle -- Handle to the buffer ready to receive data. Returns ESP_ERR_INVALID_ARG if invalid handle or the buffer is already in the queue. Only after the buffer is returened by sdio_slave_recv can you load it again. ESP_OK if success ESP_ERR_INVALID_ARG if invalid handle or the buffer is already in the queue. Only after the buffer is returened by sdio_slave_recv can you load it again. ESP_OK if success ESP_ERR_INVALID_ARG if invalid handle or the buffer is already in the queue. Only after the buffer is returened by sdio_slave_recv can you load it again. Parameters handle -- Handle to the buffer ready to receive data. Returns ESP_ERR_INVALID_ARG if invalid handle or the buffer is already in the queue. Only after the buffer is returened by sdio_slave_recv can you load it again. ESP_OK if success esp_err_t sdio_slave_recv_packet(sdio_slave_buf_handle_t *handle_ret, TickType_t wait) Get buffer of received data if exist with packet information. The driver returns the ownership of the buffer to the app. When you see return value is ESP_ERR_NOT_FINISHED , you should call this API iteratively until the return value is ESP_OK . All the continuous buffers returned with ESP_ERR_NOT_FINISHED , together with the last buffer returned with ESP_OK , belong to one packet from the host. You can call simpler sdio_slave_recv instead, if the host never send data longer than the Receiving buffer size, or you don't care about the packet boundary (e.g. the data is only a byte stream). Note Call sdio_slave_load_buf with the handle to re-load the buffer onto the link list, and receive with the same buffer again. The address and length of the buffer got here is the same as got from sdio_slave_get_buffer . Parameters handle_ret -- Handle of the buffer holding received data. Use this handle in sdio_slave_recv_load_buf() to receive in the same buffer again. wait -- Time to wait before data received. handle_ret -- Handle of the buffer holding received data. Use this handle in sdio_slave_recv_load_buf() to receive in the same buffer again. wait -- Time to wait before data received. handle_ret -- Handle of the buffer holding received data. Use this handle in sdio_slave_recv_load_buf() to receive in the same buffer again. Returns ESP_ERR_INVALID_ARG if handle_ret is NULL ESP_ERR_TIMEOUT if timeout before receiving new data ESP_ERR_NOT_FINISHED if returned buffer is not the end of a packet from the host, should call this API again until the end of a packet ESP_OK if success ESP_ERR_INVALID_ARG if handle_ret is NULL ESP_ERR_TIMEOUT if timeout before receiving new data ESP_ERR_NOT_FINISHED if returned buffer is not the end of a packet from the host, should call this API again until the end of a packet ESP_OK if success ESP_ERR_INVALID_ARG if handle_ret is NULL Parameters handle_ret -- Handle of the buffer holding received data. Use this handle in sdio_slave_recv_load_buf() to receive in the same buffer again. wait -- Time to wait before data received. Returns ESP_ERR_INVALID_ARG if handle_ret is NULL ESP_ERR_TIMEOUT if timeout before receiving new data ESP_ERR_NOT_FINISHED if returned buffer is not the end of a packet from the host, should call this API again until the end of a packet ESP_OK if success esp_err_t sdio_slave_recv(sdio_slave_buf_handle_t *handle_ret, uint8_t **out_addr, size_t *out_len, TickType_t wait) Get received data if exist. The driver returns the ownership of the buffer to the app. Note Call sdio_slave_load_buf with the handle to re-load the buffer onto the link list, and receive with the same buffer again. The address and length of the buffer got here is the same as got from sdio_slave_get_buffer . Parameters handle_ret -- Handle to the buffer holding received data. Use this handle in sdio_slave_recv_load_buf to receive in the same buffer again. out_addr -- [out] Output of the start address, set to NULL if not needed. out_len -- [out] Actual length of the data in the buffer, set to NULL if not needed. wait -- Time to wait before data received. handle_ret -- Handle to the buffer holding received data. Use this handle in sdio_slave_recv_load_buf to receive in the same buffer again. out_addr -- [out] Output of the start address, set to NULL if not needed. out_len -- [out] Actual length of the data in the buffer, set to NULL if not needed. wait -- Time to wait before data received. handle_ret -- Handle to the buffer holding received data. Use this handle in sdio_slave_recv_load_buf to receive in the same buffer again. Returns ESP_ERR_INVALID_ARG if handle_ret is NULL ESP_ERR_TIMEOUT if timeout before receiving new data ESP_OK if success ESP_ERR_INVALID_ARG if handle_ret is NULL ESP_ERR_TIMEOUT if timeout before receiving new data ESP_OK if success ESP_ERR_INVALID_ARG if handle_ret is NULL Parameters handle_ret -- Handle to the buffer holding received data. Use this handle in sdio_slave_recv_load_buf to receive in the same buffer again. out_addr -- [out] Output of the start address, set to NULL if not needed. out_len -- [out] Actual length of the data in the buffer, set to NULL if not needed. wait -- Time to wait before data received. Returns ESP_ERR_INVALID_ARG if handle_ret is NULL ESP_ERR_TIMEOUT if timeout before receiving new data ESP_OK if success uint8_t *sdio_slave_recv_get_buf(sdio_slave_buf_handle_t handle, size_t *len_o) Retrieve the buffer corresponding to a handle. Parameters handle -- Handle to get the buffer. len_o -- Output of buffer length handle -- Handle to get the buffer. len_o -- Output of buffer length handle -- Handle to get the buffer. Returns buffer address if success, otherwise NULL. Parameters handle -- Handle to get the buffer. len_o -- Output of buffer length Returns buffer address if success, otherwise NULL. esp_err_t sdio_slave_send_queue(uint8_t *addr, size_t len, void *arg, TickType_t wait) Put a new sending transfer into the send queue. The driver takes ownership of the buffer until the buffer is returned by sdio_slave_send_get_finished after the transaction is finished. Parameters addr -- Address for data to be sent. The buffer should be DMA capable and 32-bit aligned. len -- Length of the data, should not be longer than 4092 bytes (may support longer in the future). arg -- Argument to returned in sdio_slave_send_get_finished . The argument can be used to indicate which transaction is done, or as a parameter for a callback. Set to NULL if not needed. wait -- Time to wait if the buffer is full. addr -- Address for data to be sent. The buffer should be DMA capable and 32-bit aligned. len -- Length of the data, should not be longer than 4092 bytes (may support longer in the future). arg -- Argument to returned in sdio_slave_send_get_finished . The argument can be used to indicate which transaction is done, or as a parameter for a callback. Set to NULL if not needed. wait -- Time to wait if the buffer is full. addr -- Address for data to be sent. The buffer should be DMA capable and 32-bit aligned. Returns ESP_ERR_INVALID_ARG if the length is not greater than 0. ESP_ERR_TIMEOUT if the queue is still full until timeout. ESP_OK if success. ESP_ERR_INVALID_ARG if the length is not greater than 0. ESP_ERR_TIMEOUT if the queue is still full until timeout. ESP_OK if success. ESP_ERR_INVALID_ARG if the length is not greater than 0. Parameters addr -- Address for data to be sent. The buffer should be DMA capable and 32-bit aligned. len -- Length of the data, should not be longer than 4092 bytes (may support longer in the future). arg -- Argument to returned in sdio_slave_send_get_finished . The argument can be used to indicate which transaction is done, or as a parameter for a callback. Set to NULL if not needed. wait -- Time to wait if the buffer is full. Returns ESP_ERR_INVALID_ARG if the length is not greater than 0. ESP_ERR_TIMEOUT if the queue is still full until timeout. ESP_OK if success. esp_err_t sdio_slave_send_get_finished(void **out_arg, TickType_t wait) Return the ownership of a finished transaction. Parameters out_arg -- Argument of the finished transaction. Set to NULL if unused. wait -- Time to wait if there's no finished sending transaction. out_arg -- Argument of the finished transaction. Set to NULL if unused. wait -- Time to wait if there's no finished sending transaction. out_arg -- Argument of the finished transaction. Set to NULL if unused. Returns ESP_ERR_TIMEOUT if no transaction finished, or ESP_OK if succeed. Parameters out_arg -- Argument of the finished transaction. Set to NULL if unused. wait -- Time to wait if there's no finished sending transaction. Returns ESP_ERR_TIMEOUT if no transaction finished, or ESP_OK if succeed. esp_err_t sdio_slave_transmit(uint8_t *addr, size_t len) Start a new sending transfer, and wait for it (blocked) to be finished. Parameters addr -- Start address of the buffer to send len -- Length of buffer to send. addr -- Start address of the buffer to send len -- Length of buffer to send. addr -- Start address of the buffer to send Returns ESP_ERR_INVALID_ARG if the length of descriptor is not greater than 0. ESP_ERR_TIMEOUT if the queue is full or host do not start a transfer before timeout. ESP_OK if success. ESP_ERR_INVALID_ARG if the length of descriptor is not greater than 0. ESP_ERR_TIMEOUT if the queue is full or host do not start a transfer before timeout. ESP_OK if success. ESP_ERR_INVALID_ARG if the length of descriptor is not greater than 0. Parameters addr -- Start address of the buffer to send len -- Length of buffer to send. Returns ESP_ERR_INVALID_ARG if the length of descriptor is not greater than 0. ESP_ERR_TIMEOUT if the queue is full or host do not start a transfer before timeout. ESP_OK if success. uint8_t sdio_slave_read_reg(int pos) Read the spi slave register shared with host. Note register 28 to 31 are reserved for interrupt vector. Parameters pos -- register address, 0-27 or 32-63. Returns value of the register. Parameters pos -- register address, 0-27 or 32-63. Returns value of the register. esp_err_t sdio_slave_write_reg(int pos, uint8_t reg) Write the spi slave register shared with host. Note register 29 and 31 are used for interrupt vector. Parameters pos -- register address, 0-11, 14-15, 18-19, 24-27 and 32-63, other address are reserved. reg -- the value to write. pos -- register address, 0-11, 14-15, 18-19, 24-27 and 32-63, other address are reserved. reg -- the value to write. pos -- register address, 0-11, 14-15, 18-19, 24-27 and 32-63, other address are reserved. Returns ESP_ERR_INVALID_ARG if address wrong, otherwise ESP_OK. Parameters pos -- register address, 0-11, 14-15, 18-19, 24-27 and 32-63, other address are reserved. reg -- the value to write. Returns ESP_ERR_INVALID_ARG if address wrong, otherwise ESP_OK. Get the interrupt enable for host. Returns the interrupt mask. Returns the interrupt mask. void sdio_slave_set_host_intena(sdio_slave_hostint_t mask) Set the interrupt enable for host. Parameters mask -- Enable mask for host interrupt. Parameters mask -- Enable mask for host interrupt. esp_err_t sdio_slave_send_host_int(uint8_t pos) Interrupt the host by general purpose interrupt. Parameters pos -- Interrupt num, 0-7. Returns ESP_ERR_INVALID_ARG if interrupt num error ESP_OK otherwise ESP_ERR_INVALID_ARG if interrupt num error ESP_OK otherwise ESP_ERR_INVALID_ARG if interrupt num error Parameters pos -- Interrupt num, 0-7. Returns ESP_ERR_INVALID_ARG if interrupt num error ESP_OK otherwise void sdio_slave_clear_host_int(sdio_slave_hostint_t mask) Clear general purpose interrupt to host. Parameters mask -- Interrupt bits to clear, by bit mask. Parameters mask -- Interrupt bits to clear, by bit mask. esp_err_t sdio_slave_wait_int(int pos, TickType_t wait) Wait for general purpose interrupt from host. Note this clears the interrupt at the same time. Parameters pos -- Interrupt source number to wait for. is set. wait -- Time to wait before interrupt triggered. pos -- Interrupt source number to wait for. is set. wait -- Time to wait before interrupt triggered. pos -- Interrupt source number to wait for. is set. Returns ESP_OK if success, ESP_ERR_TIMEOUT if timeout. Parameters pos -- Interrupt source number to wait for. is set. wait -- Time to wait before interrupt triggered. Returns ESP_OK if success, ESP_ERR_TIMEOUT if timeout. Structures struct sdio_slave_config_t Configuration of SDIO slave. Public Members sdio_slave_timing_t timing timing of sdio_slave. see sdio_slave_timing_t . sdio_slave_timing_t timing timing of sdio_slave. see sdio_slave_timing_t . sdio_slave_sending_mode_t sending_mode mode of sdio_slave. SDIO_SLAVE_MODE_STREAM if the data needs to be sent as much as possible; SDIO_SLAVE_MODE_PACKET if the data should be sent in packets. sdio_slave_sending_mode_t sending_mode mode of sdio_slave. SDIO_SLAVE_MODE_STREAM if the data needs to be sent as much as possible; SDIO_SLAVE_MODE_PACKET if the data should be sent in packets. int send_queue_size max buffers that can be queued before sending. int send_queue_size max buffers that can be queued before sending. size_t recv_buffer_size If buffer_size is too small, it costs more CPU time to handle larger number of buffers. If buffer_size is too large, the space larger than the transaction length is left blank but still counts a buffer, and the buffers are easily run out. Should be set according to length of data really transferred. All data that do not fully fill a buffer is still counted as one buffer. E.g. 10 bytes data costs 2 buffers if the size is 8 bytes per buffer. Buffer size of the slave pre-defined between host and slave before communication. All receive buffer given to the driver should be larger than this. size_t recv_buffer_size If buffer_size is too small, it costs more CPU time to handle larger number of buffers. If buffer_size is too large, the space larger than the transaction length is left blank but still counts a buffer, and the buffers are easily run out. Should be set according to length of data really transferred. All data that do not fully fill a buffer is still counted as one buffer. E.g. 10 bytes data costs 2 buffers if the size is 8 bytes per buffer. Buffer size of the slave pre-defined between host and slave before communication. All receive buffer given to the driver should be larger than this. sdio_event_cb_t event_cb when the host interrupts slave, this callback will be called with interrupt number (0-7). sdio_event_cb_t event_cb when the host interrupts slave, this callback will be called with interrupt number (0-7). uint32_t flags Features to be enabled for the slave, combinations of SDIO_SLAVE_FLAG_* . uint32_t flags Features to be enabled for the slave, combinations of SDIO_SLAVE_FLAG_* . sdio_slave_timing_t timing Macros SDIO_SLAVE_RECV_MAX_BUFFER SDIO_SLAVE_FLAG_DAT2_DISABLED It is required by the SD specification that all 4 data lines should be used and pulled up even in 1-bit mode or SPI mode. However, as a feature, the user can specify this flag to make use of DAT2 pin in 1-bit mode. Note that the host cannot read CCCR registers to know we don't support 4-bit mode anymore, please do this at your own risk. SDIO_SLAVE_FLAG_HOST_INTR_DISABLED The DAT1 line is used as the interrupt line in SDIO protocol. However, as a feature, the user can specify this flag to make use of DAT1 pin of the slave in 1-bit mode. Note that the host has to do polling to the interrupt registers to know whether there are interrupts from the slave. And it cannot read CCCR registers to know we don't support 4-bit mode anymore, please do this at your own risk. SDIO_SLAVE_FLAG_INTERNAL_PULLUP Enable internal pullups for enabled pins. It is required by the SD specification that all the 4 data lines should be pulled up even in 1-bit mode or SPI mode. Note that the internal pull-ups are not sufficient for stable communication, please do connect external pull-ups on the bus. This is only for example and debug use. SDIO_SLAVE_FLAG_DEFAULT_SPEED Disable the highspeed support of the hardware. SDIO_SLAVE_FLAG_HIGH_SPEED Enable the highspeed support of the hardware. This is the default option. The host will see highspeed capability, but the mode actually used is determined by the host. Type Definitions typedef void (*sdio_event_cb_t)(uint8_t event) typedef void *sdio_slave_buf_handle_t Handle of a receive buffer, register a handle by calling sdio_slave_recv_register_buf . Use the handle to load the buffer to the driver, or call sdio_slave_recv_unregister_buf if it is no longer used.
SDIO Card Slave Driver Overview The ESP32 SDIO Card host and slave peripherals share two sets of pins, as shown in the table below. The first set is usually occupied by the SPI0 bus, which is responsible for the SPI flash holding the code to run. This means the SDIO slave driver can only run on the second set of pins while the SDIO host is not using it. The SDIO slave can run under three modes: SPI, 1-bit SD, and 4-bit SD modes. Based on the signals on the interface, the device can determine the current mode and configure itself to adapt to that mode. Later, the slave driver can communicate with the slave device to properly handle commands and data transfers. According to the SDIO specification, the CMD and DAT0-3 signal lines should be pulled up whether in 1-bit SD, 4-bit SD or SPI mode. Connections | Pin Name | Corresponding Pins in SPI Mode | GPIO Number (Slot 1) | GPIO Number (Slot 2) | CLK | SCLK | 6 | 14 | CMD | MOSI | 11 | 15 | DAT0 | MISO | 7 | 2 | DAT1 | Interrupt | 8 | 4 | DAT2 | N.C. (pullup) | 9 | 12 | DAT3 | #CS | 10 | 13 1-bit SD mode: Connect CLK, CMD, DAT0, DAT1 pins, and the ground. 4-bit SD mode: Connect all pins, and the ground. SPI mode: Connect SCLK, MOSI, MISO, Interrupt, #CS pins, and the ground. Note Please check if CMD and DATA lines DAT0-DAT3 of the card are properly pulled up by 10 KOhm - 90 KOhm resistors, which should be ensured even in 1-bit mode or SPI mode. Most official modules do not offer these pullups internally. If you are using official development boards, check Overview of Compatibility to see whether your development boards have such pullups. Note Most official modules have conflicts on strapping pins with the SDIO slave function. If you are using an ESP32 module with 3.3 V flash inside, when you are developing on the module for the first time, you will need to perform an eFuse burn-in prior to development. This will adjust the pin configuration of the module to make the module compatible with SDIO functionality. See Overview of Compatibility for details on how to configure this. Here is a list of modules/kits with 3.3 V flash: - Modules: All modules except ESP32-WROVER, ESP32-WROVER-I, ESP32-S3-WROOM-2, and please check Modules Overview for module list - Kits: ESP32-PICO-KIT, ESP32-DevKitC (up to v4), ESP32-WROVER-KIT (v4.1 [also known as ESP32-WROVER-KIT-VB], v2, v1 [also known as DevKitJ v1]) You can tell the version of your ESP23-WROVER-KIT version from the module on it: v4.1 are with ESP32-WROVER-B modules, v3 are with ESP32-WROVER modules, while v2 and v1 are with ESP32-WROOM-32 modules. Refer to SD Pull-up Requirements for more technical details of the pullups. The host initializes the slave into SD mode by sending the CMD0 command with the DAT3 pin set to a high level. Alternatively, the host initializes the SPI mode by sending CMD0 with CS pin low, which is the same pin as DAT3. After the initialization, the host can enable the 4-bit SD mode by writing CCCR register 0x07 by CMD52. All the bus detection processes are handled by the slave peripheral. The host has to communicate with the slave by an ESP-slave-specific protocol. The slave driver offers three services over Function 1 access by CMD52 and CMD53: sending and receiving FIFO 52 R/W registers (8-bit) shared by host and slave 16 interrupt sources (8 from host to slave, and 8 from slave to host) Terminology The SDIO slave driver uses the following terms: A transfer is initiated by a command token from the host and may consist of a response and multiple data blocks. The core mechanism of the ESP32 SDIO slave driver involves data exchange and communication through transfers. Sending: slave to host transfers. Receiving: host to slave transfers. Note The register names in ESP32 Technical Reference Manual > SDIO Slave Controller [PDF] are organized from the host's perspective. For instance, RX registers indicate sending, while TX registers denote receiving. In our driver implementation, we've chosen not to utilize the terms TX or RX to prevent any potential ambiguities. FIFO: A designated address within Function 1 that can be accessed using CMD53 commands for reading or writing substantial volumes of data. The address corresponds to the length intended for reading from or writing to the slave in a single transfer: requested length = 0x1F800 – address. Ownership: When the driver assumes ownership of a buffer, it means that the driver has the capability to perform random read/write operations on the buffer (often via DMA). The application should not read/write the buffer until the ownership is returned to the application. If the application reads from a buffer owned by a receiving driver, the data read can be random; similarly, if the application writes to a buffer owned by a sending driver, the data sent may be corrupted. Requested length: The length requested in one transfer determined by the FIFO address. Transfer length: The length requested in one transfer determined by the CMD53 byte/block count field. Note Requested length is different from the transfer length. In the context of ESP32 SDIO slave DMA, the operation is based on the requested length rather than the transfer length. This means the DMA controller will process the data transfer according to the requested length, ensuring that only data within the requested length is transferred. The transfer length should be no shorter than the requested length, and the rest part is filled with 0 during sending or discard during receiving. Receiving buffer size: The buffer size is pre-defined between the host and the slave before communication starts. The slave application has to set the buffer size during initialization by the recv_buffer_sizeparameter in the sdio_slave_config_tstructure. Interrupts: The ESP32 SDIO slave supports interrupts in two directions: from host to slave (referred to as slave interrupts) and from slave to host (referred to as host interrupts). For more details, refer to Interrupts. Registers: Specific addresses in Function 1 accessed by CMD52 or CMD53. Communication with ESP SDIO Slave The host should initialize the ESP32 SDIO slave according to the standard SDIO initialization process (Sector 3.1.2 of SDIO Simplified Specification), which is described briefly in ESP SDIO Slave Initialization. Furthermore, there is an ESP32-specific upper-level communication protocol built upon the foundation of CMD52/CMD53 to Function 1. Within this particular communication protocol, the master and slave engage in data exchange and communication through the utilization of CMD52/CMD53 commands. For more detailed information, please consult the ESP SDIO Slave Protocol section. There is also a component ESP Serial Slave Link designed for ESP32 master to communicate with ESP32 SDIO slave. See example peripherals/sdio when programming your host. Interrupts There are interrupts from host to slave, and from slave to host to help communicating conveniently. Slave Interrupts The host can trigger an interruption in the slave by writing a single bit to the 0x08D register. As soon as any bit within the register is set, an interrupt is generated, prompting the SDIO slave driver to invoke the callback function specified in the slave_intr_cb member of the sdio_slave_config_t structure. Note The callback function is called in the ISR. Do not use any delay, loop or blocking function in the callback, e.g., mutex. Similar to the previous information, there's an alternative set of functions available. You can call sdio_slave_wait_int to wait for an interrupt within a certain time, or call sdio_slave_clear_int to clear interrupts from host. The callback function can work with the wait functions perfectly. Host Interrupts The slave can interrupt the host by an interrupt line at certain time, which is level-sensitive, i.e., the interrupt signal can be triggered by detecting the level change of the interrupt line. When the host see the interrupt line pulled down, it may read the slave interrupt status register, to see the interrupt source. Host can clear interrupt bits, or choose to disable a interrupt source. The interrupt line holds active until all the sources are cleared or disabled. There are several dedicated interrupt sources as well as general-purpose sources. see sdio_slave_hostint_t for more information. Receiving FIFO When the host is going to send the slave some packets, it has to check whether the slave is ready to receive by reading the buffer number of slave. To allow the host sending data to the slave, the application has to load buffers to the slave driver by the following steps: Register the buffer by calling sdio_slave_recv_register_buf, and get the handle of the registered buffer. The driver allocates memory for the linked-list descriptor needed to link the buffer onto the hardware. The size of these buffers should equal to the Receiving buffer size. Load buffers onto the driver by passing the buffer handle to sdio_slave_recv_load_buf. Get the received data by calling sdio_slave_recvor sdio_slave_recv_packet. If a non-blocking call is needed, set wait=0. The difference between two APIs is that, sdio_slave_recv_packetgives more information about packet, which can consist of several buffers. When ESP_ERR_NOT_FINISHEDis returned by this API, you should call this API iteratively until the return value is ESP_OK. All the continuous buffers returned with ESP_ERR_NOT_FINISHED, together with the last buffer returned with ESP_OK, belong to one packet from the host. Call sdio_slave_recv_get_bufto get the address of the received data, and the actual length received in each buffer. The packet length is the sum of received length of all the buffers in the packet. If the host never send data longer than the Receiving buffer size, or you do not care about the packet boundary (e.g., the data is only a byte stream), you can call the simpler version sdio_slave_recvinstead. Pass the handle of processed buffer back to the driver by sdio_recv_load_bufagain. Note To minimize data copying overhead, the driver itself does not maintain any internal buffer; it is the responsibility of the application to promptly provide new buffers. The DMA system automatically stores received data into these buffers. Sending FIFO Each time the slave has data to send, it raises an interrupt, and the host requests the packet length. There are two sending modes: Stream Mode: When a buffer is loaded into the driver, the buffer length is included into the packet length requested by host in the incoming communications. This is irrespective of whether previous packets have been sent or not. In other words, the length of the newly loaded buffer is included into the length of the packet requested by the host, even if there are previously unsent packets. This enables the host to receive data from several buffers in a single transfer. Packet Mode: The packet length is updated packet by packet, and only when previous packet is sent. This means that the host can only get data of one buffer in one transfer. Note To avoid overhead from copying data, the driver itself does not have any buffer inside. Namely, the DMA takes data directly from the buffer provided by the application. The application should not touch the buffer until the sending is finished, so as to ensure that the data is transferred correctly. The sending mode can be set in the sending_mode member of sdio_slave_config_t, and the buffer numbers can be set in the send_queue_size. All the buffers are restricted to be no larger than 4092 bytes. Though in the stream mode, several buffers can be sent in one transfer, each buffer is still counted as one in the queue. The application can call sdio_slave_transmit to send packets. In this case, the function returns when the transfer is successfully done, so the queue is not fully used. When higher efficiency is required, the application can use the following functions instead: Pass buffer information (address, length, as well as an argindicating the buffer) to sdio_slave_send_queue. If non-blocking call is needed, set wait=0. If the waitis not portMAX_DELAY(wait until success), application has to check the result to know whether the data is put in to the queue or discard. - Call sdio_slave_send_get_finishedto get and deal with a finished transfer. A buffer should be kept unmodified until returned from sdio_slave_send_get_finished. This means the buffer is actually sent to the host, rather than just staying in the queue. There are several ways to use the arg in the queue parameter: - Directly point argto a dynamic-allocated buffer, and use the argto free it when transfer finished. - Wrap transfer informations in a transfer structure, and point argto the structure. You can use the structure to do more things like:typedef struct { uint8_t* buffer; size_t size; int id; }sdio_transfer_t; //and send as: sdio_transfer_t trans = { .buffer = ADDRESS_TO_SEND, .size = 8, .id = 3, //the 3rd transfer so far }; sdio_slave_send_queue(trans.buffer, trans.size, &trans, portMAX_DELAY); //... maybe more transfers are sent here //and deal with finished transfer as: sdio_transfer_t* arg = NULL; sdio_slave_send_get_finished((void**)&arg, portMAX_DELAY); ESP_LOGI("tag", "(%d) successfully send %d bytes of %p", arg->id, arg->size, arg->buffer); some_post_callback(arg); //do more things - Work with the receiving part of this driver, and point argto the receive buffer handle of this buffer, so that we can directly use the buffer to receive data when it is sent:uint8_t buffer[256]={1,2,3,4,5,6,7,8}; sdio_slave_buf_handle_t handle = sdio_slave_recv_register_buf(buffer); sdio_slave_send_queue(buffer, 8, handle, portMAX_DELAY); //... maybe more transfers are sent here //and load finished buffer to receive as sdio_slave_buf_handle_t handle = NULL; sdio_slave_send_get_finished((void**)&handle, portMAX_DELAY); sdio_slave_recv_load_buf(handle); For more about this, see peripherals/sdio. Application Example Slave/master communication: peripherals/sdio. API Reference Header File This header file can be included with: #include "hal/sdio_slave_types.h" Enumerations - enum sdio_slave_hostint_t Mask of interrupts sending to the host. Values: - enumerator SDIO_SLAVE_HOSTINT_BIT0 General purpose interrupt bit 0. - enumerator SDIO_SLAVE_HOSTINT_BIT1 - enumerator SDIO_SLAVE_HOSTINT_BIT2 - enumerator SDIO_SLAVE_HOSTINT_BIT3 - enumerator SDIO_SLAVE_HOSTINT_BIT4 - enumerator SDIO_SLAVE_HOSTINT_BIT5 - enumerator SDIO_SLAVE_HOSTINT_BIT6 - enumerator SDIO_SLAVE_HOSTINT_BIT7 - enumerator SDIO_SLAVE_HOSTINT_SEND_NEW_PACKET New packet available. - enumerator SDIO_SLAVE_HOSTINT_BIT0 - enum sdio_slave_timing_t Timing of SDIO slave. Values: - enumerator SDIO_SLAVE_TIMING_PSEND_PSAMPLE Send at posedge, and sample at posedge. Default value for HS mode. If :c:macro: SDIO_SLAVE_FLAG_HIGH_SPEEDis specified in :cpp:class: sdio_slave_config_t, this should be selected. Normally there's no problem using this to work in DS mode. - enumerator SDIO_SLAVE_TIMING_NSEND_PSAMPLE Send at negedge, and sample at posedge. Default value for DS mode and below. If :c:macro: SDIO_SLAVE_FLAG_DEFAULT_SPEEDis specified in :cpp:class: sdio_slave_config_t, this should be selected. - enumerator SDIO_SLAVE_TIMING_PSEND_NSAMPLE Send at posedge, and sample at negedge. - enumerator SDIO_SLAVE_TIMING_NSEND_NSAMPLE Send at negedge, and sample at negedge. - enumerator SDIO_SLAVE_TIMING_PSEND_PSAMPLE - enum sdio_slave_sending_mode_t Configuration of SDIO slave mode. Values: - enumerator SDIO_SLAVE_SEND_STREAM Stream mode, all packets to send will be combined as one if possible. - enumerator SDIO_SLAVE_SEND_PACKET Packet mode, one packets will be sent one after another (only increase packet_len if last packet sent). - enumerator SDIO_SLAVE_SEND_STREAM Header File This header file can be included with: #include "driver/sdio_slave.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t sdio_slave_initialize(sdio_slave_config_t *config) Initialize the sdio slave driver - Parameters config -- Configuration of the sdio slave driver. - Returns ESP_ERR_NOT_FOUND if no free interrupt found. ESP_ERR_INVALID_STATE if already initialized. ESP_ERR_NO_MEM if fail due to memory allocation failed. ESP_OK if success - - void sdio_slave_deinit(void) De-initialize the sdio slave driver to release the resources. - esp_err_t sdio_slave_start(void) Start hardware for sending and receiving, as well as set the IOREADY1 to 1. Note The driver will continue sending from previous data and PKT_LEN counting, keep data received as well as start receiving from current TOKEN1 counting. See sdio_slave_reset. - Returns ESP_ERR_INVALID_STATE if already started. ESP_OK otherwise. - - void sdio_slave_stop(void) Stop hardware from sending and receiving, also set IOREADY1 to 0. Note this will not clear the data already in the driver, and also not reset the PKT_LEN and TOKEN1 counting. Call sdio_slave_resetto do that. - esp_err_t sdio_slave_reset(void) Clear the data still in the driver, as well as reset the PKT_LEN and TOKEN1 counting. - Returns always return ESP_OK. - sdio_slave_buf_handle_t sdio_slave_recv_register_buf(uint8_t *start) Register buffer used for receiving. All buffers should be registered before used, and then can be used (again) in the driver by the handle returned. Note The driver will use and only use the amount of space specified in the recv_buffer_sizemember set in the sdio_slave_config_t. All buffers should be larger than that. The buffer is used by the DMA, so it should be DMA capable and 32-bit aligned. - Parameters start -- The start address of the buffer. - Returns The buffer handle if success, otherwise NULL. - esp_err_t sdio_slave_recv_unregister_buf(sdio_slave_buf_handle_t handle) Unregister buffer from driver, and free the space used by the descriptor pointing to the buffer. - Parameters handle -- Handle to the buffer to release. - Returns ESP_OK if success, ESP_ERR_INVALID_ARG if the handle is NULL or the buffer is being used. - esp_err_t sdio_slave_recv_load_buf(sdio_slave_buf_handle_t handle) Load buffer to the queue waiting to receive data. The driver takes ownership of the buffer until the buffer is returned by sdio_slave_send_get_finishedafter the transaction is finished. - Parameters handle -- Handle to the buffer ready to receive data. - Returns ESP_ERR_INVALID_ARG if invalid handle or the buffer is already in the queue. Only after the buffer is returened by sdio_slave_recvcan you load it again. ESP_OK if success - - esp_err_t sdio_slave_recv_packet(sdio_slave_buf_handle_t *handle_ret, TickType_t wait) Get buffer of received data if exist with packet information. The driver returns the ownership of the buffer to the app. When you see return value is ESP_ERR_NOT_FINISHED, you should call this API iteratively until the return value is ESP_OK. All the continuous buffers returned with ESP_ERR_NOT_FINISHED, together with the last buffer returned with ESP_OK, belong to one packet from the host. You can call simpler sdio_slave_recvinstead, if the host never send data longer than the Receiving buffer size, or you don't care about the packet boundary (e.g. the data is only a byte stream). Note Call sdio_slave_load_bufwith the handle to re-load the buffer onto the link list, and receive with the same buffer again. The address and length of the buffer got here is the same as got from sdio_slave_get_buffer. - Parameters handle_ret -- Handle of the buffer holding received data. Use this handle in sdio_slave_recv_load_buf()to receive in the same buffer again. wait -- Time to wait before data received. - - Returns ESP_ERR_INVALID_ARG if handle_ret is NULL ESP_ERR_TIMEOUT if timeout before receiving new data ESP_ERR_NOT_FINISHED if returned buffer is not the end of a packet from the host, should call this API again until the end of a packet ESP_OK if success - - esp_err_t sdio_slave_recv(sdio_slave_buf_handle_t *handle_ret, uint8_t **out_addr, size_t *out_len, TickType_t wait) Get received data if exist. The driver returns the ownership of the buffer to the app. Note Call sdio_slave_load_bufwith the handle to re-load the buffer onto the link list, and receive with the same buffer again. The address and length of the buffer got here is the same as got from sdio_slave_get_buffer. - Parameters handle_ret -- Handle to the buffer holding received data. Use this handle in sdio_slave_recv_load_bufto receive in the same buffer again. out_addr -- [out] Output of the start address, set to NULL if not needed. out_len -- [out] Actual length of the data in the buffer, set to NULL if not needed. wait -- Time to wait before data received. - - Returns ESP_ERR_INVALID_ARG if handle_ret is NULL ESP_ERR_TIMEOUT if timeout before receiving new data ESP_OK if success - - uint8_t *sdio_slave_recv_get_buf(sdio_slave_buf_handle_t handle, size_t *len_o) Retrieve the buffer corresponding to a handle. - Parameters handle -- Handle to get the buffer. len_o -- Output of buffer length - - Returns buffer address if success, otherwise NULL. - esp_err_t sdio_slave_send_queue(uint8_t *addr, size_t len, void *arg, TickType_t wait) Put a new sending transfer into the send queue. The driver takes ownership of the buffer until the buffer is returned by sdio_slave_send_get_finishedafter the transaction is finished. - Parameters addr -- Address for data to be sent. The buffer should be DMA capable and 32-bit aligned. len -- Length of the data, should not be longer than 4092 bytes (may support longer in the future). arg -- Argument to returned in sdio_slave_send_get_finished. The argument can be used to indicate which transaction is done, or as a parameter for a callback. Set to NULL if not needed. wait -- Time to wait if the buffer is full. - - Returns ESP_ERR_INVALID_ARG if the length is not greater than 0. ESP_ERR_TIMEOUT if the queue is still full until timeout. ESP_OK if success. - - esp_err_t sdio_slave_send_get_finished(void **out_arg, TickType_t wait) Return the ownership of a finished transaction. - Parameters out_arg -- Argument of the finished transaction. Set to NULL if unused. wait -- Time to wait if there's no finished sending transaction. - - Returns ESP_ERR_TIMEOUT if no transaction finished, or ESP_OK if succeed. - esp_err_t sdio_slave_transmit(uint8_t *addr, size_t len) Start a new sending transfer, and wait for it (blocked) to be finished. - Parameters addr -- Start address of the buffer to send len -- Length of buffer to send. - - Returns ESP_ERR_INVALID_ARG if the length of descriptor is not greater than 0. ESP_ERR_TIMEOUT if the queue is full or host do not start a transfer before timeout. ESP_OK if success. - - uint8_t sdio_slave_read_reg(int pos) Read the spi slave register shared with host. Note register 28 to 31 are reserved for interrupt vector. - Parameters pos -- register address, 0-27 or 32-63. - Returns value of the register. - esp_err_t sdio_slave_write_reg(int pos, uint8_t reg) Write the spi slave register shared with host. Note register 29 and 31 are used for interrupt vector. - Parameters pos -- register address, 0-11, 14-15, 18-19, 24-27 and 32-63, other address are reserved. reg -- the value to write. - - Returns ESP_ERR_INVALID_ARG if address wrong, otherwise ESP_OK. Get the interrupt enable for host. - Returns the interrupt mask. - void sdio_slave_set_host_intena(sdio_slave_hostint_t mask) Set the interrupt enable for host. - Parameters mask -- Enable mask for host interrupt. - esp_err_t sdio_slave_send_host_int(uint8_t pos) Interrupt the host by general purpose interrupt. - Parameters pos -- Interrupt num, 0-7. - Returns ESP_ERR_INVALID_ARG if interrupt num error ESP_OK otherwise - - void sdio_slave_clear_host_int(sdio_slave_hostint_t mask) Clear general purpose interrupt to host. - Parameters mask -- Interrupt bits to clear, by bit mask. - esp_err_t sdio_slave_wait_int(int pos, TickType_t wait) Wait for general purpose interrupt from host. Note this clears the interrupt at the same time. - Parameters pos -- Interrupt source number to wait for. is set. wait -- Time to wait before interrupt triggered. - - Returns ESP_OK if success, ESP_ERR_TIMEOUT if timeout. Structures - struct sdio_slave_config_t Configuration of SDIO slave. Public Members - sdio_slave_timing_t timing timing of sdio_slave. see sdio_slave_timing_t. - sdio_slave_sending_mode_t sending_mode mode of sdio_slave. SDIO_SLAVE_MODE_STREAMif the data needs to be sent as much as possible; SDIO_SLAVE_MODE_PACKETif the data should be sent in packets. - int send_queue_size max buffers that can be queued before sending. - size_t recv_buffer_size If buffer_size is too small, it costs more CPU time to handle larger number of buffers. If buffer_size is too large, the space larger than the transaction length is left blank but still counts a buffer, and the buffers are easily run out. Should be set according to length of data really transferred. All data that do not fully fill a buffer is still counted as one buffer. E.g. 10 bytes data costs 2 buffers if the size is 8 bytes per buffer. Buffer size of the slave pre-defined between host and slave before communication. All receive buffer given to the driver should be larger than this. - sdio_event_cb_t event_cb when the host interrupts slave, this callback will be called with interrupt number (0-7). - uint32_t flags Features to be enabled for the slave, combinations of SDIO_SLAVE_FLAG_*. - sdio_slave_timing_t timing Macros - SDIO_SLAVE_RECV_MAX_BUFFER - SDIO_SLAVE_FLAG_DAT2_DISABLED It is required by the SD specification that all 4 data lines should be used and pulled up even in 1-bit mode or SPI mode. However, as a feature, the user can specify this flag to make use of DAT2 pin in 1-bit mode. Note that the host cannot read CCCR registers to know we don't support 4-bit mode anymore, please do this at your own risk. - SDIO_SLAVE_FLAG_HOST_INTR_DISABLED The DAT1 line is used as the interrupt line in SDIO protocol. However, as a feature, the user can specify this flag to make use of DAT1 pin of the slave in 1-bit mode. Note that the host has to do polling to the interrupt registers to know whether there are interrupts from the slave. And it cannot read CCCR registers to know we don't support 4-bit mode anymore, please do this at your own risk. - SDIO_SLAVE_FLAG_INTERNAL_PULLUP Enable internal pullups for enabled pins. It is required by the SD specification that all the 4 data lines should be pulled up even in 1-bit mode or SPI mode. Note that the internal pull-ups are not sufficient for stable communication, please do connect external pull-ups on the bus. This is only for example and debug use. - SDIO_SLAVE_FLAG_DEFAULT_SPEED Disable the highspeed support of the hardware. - SDIO_SLAVE_FLAG_HIGH_SPEED Enable the highspeed support of the hardware. This is the default option. The host will see highspeed capability, but the mode actually used is determined by the host. Type Definitions - typedef void (*sdio_event_cb_t)(uint8_t event) - typedef void *sdio_slave_buf_handle_t Handle of a receive buffer, register a handle by calling sdio_slave_recv_register_buf. Use the handle to load the buffer to the driver, or call sdio_slave_recv_unregister_bufif it is no longer used.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/sdio_slave.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Sigma-Delta Modulation (SDM)
null
espressif.com
2016-01-01
140e9c941ade06e9
null
null
Sigma-Delta Modulation (SDM) Introduction ESP32 has a second-order sigma-delta modulator, which can generate independent PDM pulses to multiple channels. Please refer to the TRM to check how many hardware channels are available. 1 Delta-sigma modulation converts an analog voltage signal into a pulse frequency, or pulse density, which can be understood as pulse-density modulation (PDM) (refer to Delta-sigma modulation on Wikipedia). The main differences comparing to I2S PDM mode and DAC peripheral are: SDM has no clock signal, it is just like the DAC mode of PDM; SDM has no DMA, and it can not change its output density continuously. If you have to, you can update the density in a timer's callback; Based on the former two points, unlike the DAC peripheral, an external active or passive low-pass filter is required additionally to restore the analog wave (See Convert to an Analog Signal (Optional)). Typically, a Sigma-Delta modulated channel can be used in scenarios like: LED dimming Simple DAC (8-bit), with the help of an active RC low-pass filter Class D amplifier, with the help of a half-bridge or full-bridge circuit plus an LC low-pass filter Functional Overview The following sections of this document cover the typical steps to install and operate an SDM channel: Resource Allocation - covers how to initialize and configure an SDM channel and how to recycle the resources when it finishes working. Enable and Disable Channel - covers how to enable and disable the channel. Set Pulse Density - describes how to set the equivalent duty cycle of the PDM pulses. Power Management - describes how different source clock selections can affect power consumption. IRAM Safe - lists which functions are supposed to work even when the cache is disabled. Thread Safety - lists which APIs are guaranteed to be thread-safe by the driver. Kconfig Options - lists the supported Kconfig options that can be used to make a different effect on driver behavior. Resource Allocation In ESP-IDF, the information and attributes of SDM channels are managed and accessed through specific data structures, where the data structure is called sdm_channel_handle_t . Each channel is capable to output the binary, hardware-generated signal with the sigma-delta modulation. The driver manages all available channels in a pool so that there is no need to manually assign a fixed channel to a GPIO. To install an SDM channel, you should call sdm_new_channel() to get a channel handle. Channel-specific configurations are passed in the sdm_config_t structure: sdm_config_t::gpio_num sets the GPIO that the PDM pulses output from. sdm_config_t::clk_src selects the source clock for the SDM module. Note that, all channels should select the same clock source. sdm_config_t::sample_rate_hz sets the sample rate of the SDM module. sdm_config_t::invert_out sets whether to invert the output signal. sdm_config_t::io_loop_back is for debugging purposes only. It enables both the GPIO's input and output ability through the GPIO matrix peripheral. The function sdm_new_channel() can fail due to various errors such as insufficient memory, invalid arguments, etc. Specifically, when there are no more free channels (i.e., all hardware SDM channels have been used up), ESP_ERR_NOT_FOUND will be returned. If a previously created SDM channel is no longer required, you should recycle it by calling sdm_del_channel() . It allows the underlying HW channel to be used for other purposes. Before deleting an SDM channel handle, you should disable it by sdm_channel_disable() in advance or make sure it has not been enabled yet by sdm_channel_enable() . Creating an SDM Channel with a Sample Rate of 1 MHz sdm_channel_handle_t chan = NULL; sdm_config_t config = { .clk_src = SDM_CLK_SRC_DEFAULT, .sample_rate_hz = 1 * 1000 * 1000, .gpio_num = 0, }; ESP_ERROR_CHECK(sdm_new_channel(&config, &chan)); Enable and Disable Channel Before doing further IO control to the SDM channel, you should enable it first, by calling sdm_channel_enable() . Internally, this function: switches the channel state from init to enable acquires a proper power management lock if a specific clock source (e.g., APB clock) is selected. See also Power Management for more information. On the contrary, calling sdm_channel_disable() does the opposite, that is, put the channel back to the init state and releases the power management lock. Set Pulse Density For the output PDM signals, the pulse density decides the output analog voltage that is restored by a low-pass filter. The restored analog voltage from the channel is calculated by Vout = VDD_IO / 256 * duty + VDD_IO / 2 . The range of the quantized density input parameter of sdm_channel_set_pulse_density() is from -128 to 127 (8-bit signed integer). Depending on the value of the density parameter, the duty cycle of the output signal will be changed accordingly. For example, if a zero value is set, then the output signal's duty will be around 50%. Power Management When power management is enabled (i.e., CONFIG_PM_ENABLE is on), the system will adjust the APB frequency before going into Light-sleep, thus potentially changing the sample rate of the sigma-delta modulator. However, the driver can prevent the system from changing APB frequency by acquiring a power management lock of type ESP_PM_APB_FREQ_MAX . Whenever the driver creates an SDM channel instance that has selected SDM_CLK_SRC_APB as its clock source, the driver guarantees that the power management lock is acquired when enabling the channel by sdm_channel_enable() . Likewise, the driver releases the lock when sdm_channel_disable() is called for that channel. IRAM Safe There is a Kconfig option CONFIG_SDM_CTRL_FUNC_IN_IRAM that can put commonly-used IO control functions into IRAM as well. So that these functions can also be executable when the cache is disabled. These IO control functions are listed as follows: Thread Safety The factory function sdm_new_channel() is guaranteed to be thread-safe by the driver, which means, the user can call it from different RTOS tasks without protection by extra locks. The following functions are allowed to run under ISR context, the driver uses a critical section to prevent them being called concurrently in both task and ISR. Other functions that take the sdm_channel_handle_t as the first positional parameter, are not treated as thread-safe. This means the user should avoid calling them from multiple tasks. Kconfig Options CONFIG_SDM_CTRL_FUNC_IN_IRAM controls where to place the SDM channel control functions (IRAM or Flash), see IRAM Safe for more information. CONFIG_SDM_ENABLE_DEBUG_LOG is used to enable the debug log output. Enabling this option increases the firmware binary size. Convert to an Analog Signal (Optional) Typically, if a Sigma-Delta signal is connected to an LED to adjust the brightness, you do not have to add any filter between them, because our eyes have their own low-pass filters for changes in light intensity. However, if you want to check the real voltage or watch the analog waveform, you need to design an analog low-pass filter. Also, it is recommended to use an active filter instead of a passive filter to gain better isolation and not lose too much voltage. For example, you can take the following Sallen-Key topology Low Pass Filter as a reference. Application Example 100 Hz sine wave that is modulated with Sigma-Delta: peripherals/sigma_delta/sdm_dac. LED driven by a GPIO that is modulated with Sigma-Delta: peripherals/sigma_delta/sdm_led. API Reference Header File This header file can be included with: #include "driver/sdm.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t sdm_new_channel(const sdm_config_t *config, sdm_channel_handle_t *ret_chan) Create a new Sigma Delta channel. Parameters config -- [in] SDM configuration ret_chan -- [out] Returned SDM channel handle config -- [in] SDM configuration ret_chan -- [out] Returned SDM channel handle config -- [in] SDM configuration Returns ESP_OK: Create SDM channel successfully ESP_ERR_INVALID_ARG: Create SDM channel failed because of invalid argument ESP_ERR_NO_MEM: Create SDM channel failed because out of memory ESP_ERR_NOT_FOUND: Create SDM channel failed because all channels are used up and no more free one ESP_FAIL: Create SDM channel failed because of other error ESP_OK: Create SDM channel successfully ESP_ERR_INVALID_ARG: Create SDM channel failed because of invalid argument ESP_ERR_NO_MEM: Create SDM channel failed because out of memory ESP_ERR_NOT_FOUND: Create SDM channel failed because all channels are used up and no more free one ESP_FAIL: Create SDM channel failed because of other error ESP_OK: Create SDM channel successfully Parameters config -- [in] SDM configuration ret_chan -- [out] Returned SDM channel handle Returns ESP_OK: Create SDM channel successfully ESP_ERR_INVALID_ARG: Create SDM channel failed because of invalid argument ESP_ERR_NO_MEM: Create SDM channel failed because out of memory ESP_ERR_NOT_FOUND: Create SDM channel failed because all channels are used up and no more free one ESP_FAIL: Create SDM channel failed because of other error esp_err_t sdm_del_channel(sdm_channel_handle_t chan) Delete the Sigma Delta channel. Parameters chan -- [in] SDM channel created by sdm_new_channel Returns ESP_OK: Delete the SDM channel successfully ESP_ERR_INVALID_ARG: Delete the SDM channel failed because of invalid argument ESP_ERR_INVALID_STATE: Delete the SDM channel failed because the channel is not in init state ESP_FAIL: Delete the SDM channel failed because of other error ESP_OK: Delete the SDM channel successfully ESP_ERR_INVALID_ARG: Delete the SDM channel failed because of invalid argument ESP_ERR_INVALID_STATE: Delete the SDM channel failed because the channel is not in init state ESP_FAIL: Delete the SDM channel failed because of other error ESP_OK: Delete the SDM channel successfully Parameters chan -- [in] SDM channel created by sdm_new_channel Returns ESP_OK: Delete the SDM channel successfully ESP_ERR_INVALID_ARG: Delete the SDM channel failed because of invalid argument ESP_ERR_INVALID_STATE: Delete the SDM channel failed because the channel is not in init state ESP_FAIL: Delete the SDM channel failed because of other error esp_err_t sdm_channel_enable(sdm_channel_handle_t chan) Enable the Sigma Delta channel. Note This function will transit the channel state from init to enable. Note This function will acquire a PM lock, if a specific source clock (e.g. APB) is selected in the sdm_config_t , while CONFIG_PM_ENABLE is enabled. Parameters chan -- [in] SDM channel created by sdm_new_channel Returns ESP_OK: Enable SDM channel successfully ESP_ERR_INVALID_ARG: Enable SDM channel failed because of invalid argument ESP_ERR_INVALID_STATE: Enable SDM channel failed because the channel is already enabled ESP_FAIL: Enable SDM channel failed because of other error ESP_OK: Enable SDM channel successfully ESP_ERR_INVALID_ARG: Enable SDM channel failed because of invalid argument ESP_ERR_INVALID_STATE: Enable SDM channel failed because the channel is already enabled ESP_FAIL: Enable SDM channel failed because of other error ESP_OK: Enable SDM channel successfully Parameters chan -- [in] SDM channel created by sdm_new_channel Returns ESP_OK: Enable SDM channel successfully ESP_ERR_INVALID_ARG: Enable SDM channel failed because of invalid argument ESP_ERR_INVALID_STATE: Enable SDM channel failed because the channel is already enabled ESP_FAIL: Enable SDM channel failed because of other error esp_err_t sdm_channel_disable(sdm_channel_handle_t chan) Disable the Sigma Delta channel. Note This function will do the opposite work to the sdm_channel_enable() Parameters chan -- [in] SDM channel created by sdm_new_channel Returns ESP_OK: Disable SDM channel successfully ESP_ERR_INVALID_ARG: Disable SDM channel failed because of invalid argument ESP_ERR_INVALID_STATE: Disable SDM channel failed because the channel is not enabled yet ESP_FAIL: Disable SDM channel failed because of other error ESP_OK: Disable SDM channel successfully ESP_ERR_INVALID_ARG: Disable SDM channel failed because of invalid argument ESP_ERR_INVALID_STATE: Disable SDM channel failed because the channel is not enabled yet ESP_FAIL: Disable SDM channel failed because of other error ESP_OK: Disable SDM channel successfully Parameters chan -- [in] SDM channel created by sdm_new_channel Returns ESP_OK: Disable SDM channel successfully ESP_ERR_INVALID_ARG: Disable SDM channel failed because of invalid argument ESP_ERR_INVALID_STATE: Disable SDM channel failed because the channel is not enabled yet ESP_FAIL: Disable SDM channel failed because of other error esp_err_t sdm_channel_set_pulse_density(sdm_channel_handle_t chan, int8_t density) Set the pulse density of the PDM output signal. Note The raw output signal requires a low-pass filter to restore it into analog voltage, the restored analog output voltage could be Vout = VDD_IO / 256 * density + VDD_IO / 2 Note This function is allowed to run within ISR context Note This function will be placed into IRAM if CONFIG_SDM_CTRL_FUNC_IN_IRAM is on, so that it's allowed to be executed when Cache is disabled Parameters chan -- [in] SDM channel created by sdm_new_channel density -- [in] Quantized pulse density of the PDM output signal, ranges from -128 to 127. But the range of [-90, 90] can provide a better randomness. chan -- [in] SDM channel created by sdm_new_channel density -- [in] Quantized pulse density of the PDM output signal, ranges from -128 to 127. But the range of [-90, 90] can provide a better randomness. chan -- [in] SDM channel created by sdm_new_channel Returns ESP_OK: Set pulse density successfully ESP_ERR_INVALID_ARG: Set pulse density failed because of invalid argument ESP_FAIL: Set pulse density failed because of other error ESP_OK: Set pulse density successfully ESP_ERR_INVALID_ARG: Set pulse density failed because of invalid argument ESP_FAIL: Set pulse density failed because of other error ESP_OK: Set pulse density successfully Parameters chan -- [in] SDM channel created by sdm_new_channel density -- [in] Quantized pulse density of the PDM output signal, ranges from -128 to 127. But the range of [-90, 90] can provide a better randomness. Returns ESP_OK: Set pulse density successfully ESP_ERR_INVALID_ARG: Set pulse density failed because of invalid argument ESP_FAIL: Set pulse density failed because of other error esp_err_t sdm_channel_set_duty(sdm_channel_handle_t chan, int8_t duty) The alias function of sdm_channel_set_pulse_density , it decides the pulse density of the output signal. Note sdm_channel_set_pulse_density has a more appropriate name compare this alias function, suggest to turn to sdm_channel_set_pulse_density instead Parameters chan -- [in] SDM channel created by sdm_new_channel duty -- [in] Actually it's the quantized pulse density of the PDM output signal chan -- [in] SDM channel created by sdm_new_channel duty -- [in] Actually it's the quantized pulse density of the PDM output signal chan -- [in] SDM channel created by sdm_new_channel Returns ESP_OK: Set duty cycle successfully ESP_ERR_INVALID_ARG: Set duty cycle failed because of invalid argument ESP_FAIL: Set duty cycle failed because of other error ESP_OK: Set duty cycle successfully ESP_ERR_INVALID_ARG: Set duty cycle failed because of invalid argument ESP_FAIL: Set duty cycle failed because of other error ESP_OK: Set duty cycle successfully Parameters chan -- [in] SDM channel created by sdm_new_channel duty -- [in] Actually it's the quantized pulse density of the PDM output signal Returns ESP_OK: Set duty cycle successfully ESP_ERR_INVALID_ARG: Set duty cycle failed because of invalid argument ESP_FAIL: Set duty cycle failed because of other error Structures struct sdm_config_t Sigma Delta channel configuration. Public Members int gpio_num GPIO number int gpio_num GPIO number sdm_clock_source_t clk_src Clock source sdm_clock_source_t clk_src Clock source uint32_t sample_rate_hz Over sample rate in Hz, it determines the frequency of the carrier pulses uint32_t sample_rate_hz Over sample rate in Hz, it determines the frequency of the carrier pulses uint32_t invert_out Whether to invert the output signal uint32_t invert_out Whether to invert the output signal uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well struct sdm_config_t::[anonymous] flags Extra flags struct sdm_config_t::[anonymous] flags Extra flags int gpio_num Type Definitions typedef struct sdm_channel_t *sdm_channel_handle_t Type of Sigma Delta channel handle. Header File This header file can be included with: #include "hal/sdm_types.h" Type Definitions typedef soc_periph_sdm_clk_src_t sdm_clock_source_t 1 Different ESP chip series might have different numbers of SDM channels. Please refer to Chapter GPIO and IOMUX in ESP32 Technical Reference Manual for more details. The driver does not forbid you from applying for more channels, but it will return an error when all available hardware resources are used up. Please always check the return value when doing resource allocation (e.g., sdm_new_channel() ).
Sigma-Delta Modulation (SDM) Introduction ESP32 has a second-order sigma-delta modulator, which can generate independent PDM pulses to multiple channels. Please refer to the TRM to check how many hardware channels are available. 1 Delta-sigma modulation converts an analog voltage signal into a pulse frequency, or pulse density, which can be understood as pulse-density modulation (PDM) (refer to Delta-sigma modulation on Wikipedia). The main differences comparing to I2S PDM mode and DAC peripheral are: SDM has no clock signal, it is just like the DAC mode of PDM; SDM has no DMA, and it can not change its output density continuously. If you have to, you can update the density in a timer's callback; Based on the former two points, unlike the DAC peripheral, an external active or passive low-pass filter is required additionally to restore the analog wave (See Convert to an Analog Signal (Optional)). Typically, a Sigma-Delta modulated channel can be used in scenarios like: LED dimming Simple DAC (8-bit), with the help of an active RC low-pass filter Class D amplifier, with the help of a half-bridge or full-bridge circuit plus an LC low-pass filter Functional Overview The following sections of this document cover the typical steps to install and operate an SDM channel: Resource Allocation - covers how to initialize and configure an SDM channel and how to recycle the resources when it finishes working. Enable and Disable Channel - covers how to enable and disable the channel. Set Pulse Density - describes how to set the equivalent duty cycle of the PDM pulses. Power Management - describes how different source clock selections can affect power consumption. IRAM Safe - lists which functions are supposed to work even when the cache is disabled. Thread Safety - lists which APIs are guaranteed to be thread-safe by the driver. Kconfig Options - lists the supported Kconfig options that can be used to make a different effect on driver behavior. Resource Allocation In ESP-IDF, the information and attributes of SDM channels are managed and accessed through specific data structures, where the data structure is called sdm_channel_handle_t. Each channel is capable to output the binary, hardware-generated signal with the sigma-delta modulation. The driver manages all available channels in a pool so that there is no need to manually assign a fixed channel to a GPIO. To install an SDM channel, you should call sdm_new_channel() to get a channel handle. Channel-specific configurations are passed in the sdm_config_t structure: sdm_config_t::gpio_numsets the GPIO that the PDM pulses output from. sdm_config_t::clk_srcselects the source clock for the SDM module. Note that, all channels should select the same clock source. sdm_config_t::sample_rate_hzsets the sample rate of the SDM module. sdm_config_t::invert_outsets whether to invert the output signal. sdm_config_t::io_loop_backis for debugging purposes only. It enables both the GPIO's input and output ability through the GPIO matrix peripheral. The function sdm_new_channel() can fail due to various errors such as insufficient memory, invalid arguments, etc. Specifically, when there are no more free channels (i.e., all hardware SDM channels have been used up), ESP_ERR_NOT_FOUND will be returned. If a previously created SDM channel is no longer required, you should recycle it by calling sdm_del_channel(). It allows the underlying HW channel to be used for other purposes. Before deleting an SDM channel handle, you should disable it by sdm_channel_disable() in advance or make sure it has not been enabled yet by sdm_channel_enable(). Creating an SDM Channel with a Sample Rate of 1 MHz sdm_channel_handle_t chan = NULL; sdm_config_t config = { .clk_src = SDM_CLK_SRC_DEFAULT, .sample_rate_hz = 1 * 1000 * 1000, .gpio_num = 0, }; ESP_ERROR_CHECK(sdm_new_channel(&config, &chan)); Enable and Disable Channel Before doing further IO control to the SDM channel, you should enable it first, by calling sdm_channel_enable(). Internally, this function: switches the channel state from init to enable acquires a proper power management lock if a specific clock source (e.g., APB clock) is selected. See also Power Management for more information. On the contrary, calling sdm_channel_disable() does the opposite, that is, put the channel back to the init state and releases the power management lock. Set Pulse Density For the output PDM signals, the pulse density decides the output analog voltage that is restored by a low-pass filter. The restored analog voltage from the channel is calculated by Vout = VDD_IO / 256 * duty + VDD_IO / 2. The range of the quantized density input parameter of sdm_channel_set_pulse_density() is from -128 to 127 (8-bit signed integer). Depending on the value of the density parameter, the duty cycle of the output signal will be changed accordingly. For example, if a zero value is set, then the output signal's duty will be around 50%. Power Management When power management is enabled (i.e., CONFIG_PM_ENABLE is on), the system will adjust the APB frequency before going into Light-sleep, thus potentially changing the sample rate of the sigma-delta modulator. However, the driver can prevent the system from changing APB frequency by acquiring a power management lock of type ESP_PM_APB_FREQ_MAX. Whenever the driver creates an SDM channel instance that has selected SDM_CLK_SRC_APB as its clock source, the driver guarantees that the power management lock is acquired when enabling the channel by sdm_channel_enable(). Likewise, the driver releases the lock when sdm_channel_disable() is called for that channel. IRAM Safe There is a Kconfig option CONFIG_SDM_CTRL_FUNC_IN_IRAM that can put commonly-used IO control functions into IRAM as well. So that these functions can also be executable when the cache is disabled. These IO control functions are listed as follows: Thread Safety The factory function sdm_new_channel() is guaranteed to be thread-safe by the driver, which means, the user can call it from different RTOS tasks without protection by extra locks. The following functions are allowed to run under ISR context, the driver uses a critical section to prevent them being called concurrently in both task and ISR. Other functions that take the sdm_channel_handle_t as the first positional parameter, are not treated as thread-safe. This means the user should avoid calling them from multiple tasks. Kconfig Options CONFIG_SDM_CTRL_FUNC_IN_IRAM controls where to place the SDM channel control functions (IRAM or Flash), see IRAM Safe for more information. CONFIG_SDM_ENABLE_DEBUG_LOG is used to enable the debug log output. Enabling this option increases the firmware binary size. Convert to an Analog Signal (Optional) Typically, if a Sigma-Delta signal is connected to an LED to adjust the brightness, you do not have to add any filter between them, because our eyes have their own low-pass filters for changes in light intensity. However, if you want to check the real voltage or watch the analog waveform, you need to design an analog low-pass filter. Also, it is recommended to use an active filter instead of a passive filter to gain better isolation and not lose too much voltage. For example, you can take the following Sallen-Key topology Low Pass Filter as a reference. Application Example 100 Hz sine wave that is modulated with Sigma-Delta: peripherals/sigma_delta/sdm_dac. LED driven by a GPIO that is modulated with Sigma-Delta: peripherals/sigma_delta/sdm_led. API Reference Header File This header file can be included with: #include "driver/sdm.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t sdm_new_channel(const sdm_config_t *config, sdm_channel_handle_t *ret_chan) Create a new Sigma Delta channel. - Parameters config -- [in] SDM configuration ret_chan -- [out] Returned SDM channel handle - - Returns ESP_OK: Create SDM channel successfully ESP_ERR_INVALID_ARG: Create SDM channel failed because of invalid argument ESP_ERR_NO_MEM: Create SDM channel failed because out of memory ESP_ERR_NOT_FOUND: Create SDM channel failed because all channels are used up and no more free one ESP_FAIL: Create SDM channel failed because of other error - - esp_err_t sdm_del_channel(sdm_channel_handle_t chan) Delete the Sigma Delta channel. - Parameters chan -- [in] SDM channel created by sdm_new_channel - Returns ESP_OK: Delete the SDM channel successfully ESP_ERR_INVALID_ARG: Delete the SDM channel failed because of invalid argument ESP_ERR_INVALID_STATE: Delete the SDM channel failed because the channel is not in init state ESP_FAIL: Delete the SDM channel failed because of other error - - esp_err_t sdm_channel_enable(sdm_channel_handle_t chan) Enable the Sigma Delta channel. Note This function will transit the channel state from init to enable. Note This function will acquire a PM lock, if a specific source clock (e.g. APB) is selected in the sdm_config_t, while CONFIG_PM_ENABLEis enabled. - Parameters chan -- [in] SDM channel created by sdm_new_channel - Returns ESP_OK: Enable SDM channel successfully ESP_ERR_INVALID_ARG: Enable SDM channel failed because of invalid argument ESP_ERR_INVALID_STATE: Enable SDM channel failed because the channel is already enabled ESP_FAIL: Enable SDM channel failed because of other error - - esp_err_t sdm_channel_disable(sdm_channel_handle_t chan) Disable the Sigma Delta channel. Note This function will do the opposite work to the sdm_channel_enable() - Parameters chan -- [in] SDM channel created by sdm_new_channel - Returns ESP_OK: Disable SDM channel successfully ESP_ERR_INVALID_ARG: Disable SDM channel failed because of invalid argument ESP_ERR_INVALID_STATE: Disable SDM channel failed because the channel is not enabled yet ESP_FAIL: Disable SDM channel failed because of other error - - esp_err_t sdm_channel_set_pulse_density(sdm_channel_handle_t chan, int8_t density) Set the pulse density of the PDM output signal. Note The raw output signal requires a low-pass filter to restore it into analog voltage, the restored analog output voltage could be Vout = VDD_IO / 256 * density + VDD_IO / 2 Note This function is allowed to run within ISR context Note This function will be placed into IRAM if CONFIG_SDM_CTRL_FUNC_IN_IRAMis on, so that it's allowed to be executed when Cache is disabled - Parameters chan -- [in] SDM channel created by sdm_new_channel density -- [in] Quantized pulse density of the PDM output signal, ranges from -128 to 127. But the range of [-90, 90] can provide a better randomness. - - Returns ESP_OK: Set pulse density successfully ESP_ERR_INVALID_ARG: Set pulse density failed because of invalid argument ESP_FAIL: Set pulse density failed because of other error - - esp_err_t sdm_channel_set_duty(sdm_channel_handle_t chan, int8_t duty) The alias function of sdm_channel_set_pulse_density, it decides the pulse density of the output signal. Note sdm_channel_set_pulse_densityhas a more appropriate name compare this alias function, suggest to turn to sdm_channel_set_pulse_densityinstead - Parameters chan -- [in] SDM channel created by sdm_new_channel duty -- [in] Actually it's the quantized pulse density of the PDM output signal - - Returns ESP_OK: Set duty cycle successfully ESP_ERR_INVALID_ARG: Set duty cycle failed because of invalid argument ESP_FAIL: Set duty cycle failed because of other error - Structures - struct sdm_config_t Sigma Delta channel configuration. Public Members - int gpio_num GPIO number - sdm_clock_source_t clk_src Clock source - uint32_t sample_rate_hz Over sample rate in Hz, it determines the frequency of the carrier pulses - uint32_t invert_out Whether to invert the output signal - uint32_t io_loop_back For debug/test, the signal output from the GPIO will be fed to the input path as well - struct sdm_config_t::[anonymous] flags Extra flags - int gpio_num Type Definitions - typedef struct sdm_channel_t *sdm_channel_handle_t Type of Sigma Delta channel handle. Header File This header file can be included with: #include "hal/sdm_types.h" Type Definitions - typedef soc_periph_sdm_clk_src_t sdm_clock_source_t - 1 Different ESP chip series might have different numbers of SDM channels. Please refer to Chapter GPIO and IOMUX in ESP32 Technical Reference Manual for more details. The driver does not forbid you from applying for more channels, but it will return an error when all available hardware resources are used up. Please always check the return value when doing resource allocation (e.g., sdm_new_channel()).
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/sdm.html
ESP-IDF Programming Guide v5.2.1 documentation
null
SPI Flash API
null
espressif.com
2016-01-01
96c6d95f86138949
null
null
SPI Flash API Overview The spi_flash component contains API functions related to reading, writing, erasing, and memory mapping for data in the external flash. For higher-level API functions which work with partitions defined in the partition table, see Partitions API Note esp_partition_* APIs are recommended to be used instead of the lower level esp_flash_* API functions when accessing the main SPI flash chip, since they conduct bounds checking and are guaranteed to calculate correct offsets in flash based on the information in the partition table. esp_flash_* functions can still be used directly when accessing an external (secondary) SPI flash chip. Different from the API before ESP-IDF v4.0, the functionality of esp_flash_* APIs is not limited to the "main" SPI flash chip (the same SPI flash chip from which program runs). With different chip pointers, you can access external flash chips connected to not only SPI0/1 but also other SPI buses like SPI2. Note Instead of going through the cache connected to the SPI0 peripheral, most esp_flash_* APIs go through other SPI peripherals like SPI1, SPI2, etc. This makes them able to access not only the main flash, but also external (secondary) flash. However, due to the limitations of the cache, operations through the cache are limited to the main flash. The address range limitation for these operations is also on the cache side. The cache is not able to access external flash chips or address range above its capabilities. These cache operations include: mmap, encrypted read/write, executing code or access to variables in the flash. Note Flash APIs after ESP-IDF v4.0 are no longer atomic. If a write operation occurs during another on-going read operation, and the flash addresses of both operations overlap, the data returned from the read operation may contain both old data and new data (that was updated written by the write operation). Note Encrypted flash operations are only supported with the main flash chip (and not with other flash chips, that is on SPI1 with different CS, or on other SPI buses). Reading through cache is only supported on the main flash, which is determined by the HW. Support for Features of Flash Chips Quad/Dual Mode Chips Features of different flashes are implemented in different ways and thus need special support. The fast/slow read and Dual mode (DOUT/DIO) of almost all flashes with 24-bit address are supported, because they do not need any vendor-specific commands. Quad mode (QIO/QOUT) is supported on the following chip types: ISSI GD MXIC FM Winbond XMC BOYA Note Only when one flash series listed above is supported by ESP32, this flash series is supported by the chip driver by default. You can use Component config > SPI Flash driver > Auto-detect flash chips in menuconfig to enable/disable a flash series. Optional Features There are some features that are not supported by all flash chips, or not supported by all Espressif chips. These features include: 32-bit address flash - usually means that the flash has higher capacity (equal to or larger than 16 MB) that needs longer addresses. Flash unique ID - means that flash supports its unique 64-bit ID. If you want to use these features, please ensure both ESP32 and ALL flash chips in your product support these features. For more details, refer to Optional Features for Flash. You may also customise your own flash chip driver. See Overriding Default Chip Drivers for more details. Initializing a Flash Device To use the esp_flash_* APIs, you need to initialise a flash chip on a certain SPI bus, as shown below: Call spi_bus_initialize() to properly initialize an SPI bus. This function initializes the resources (I/O, DMA, interrupts) shared among devices attached to this bus. Call spi_bus_add_flash_device() to attach the flash device to the bus. This function allocates memory and fills the members for the esp_flash_t structure. The CS I/O is also initialized here. Call esp_flash_init() to actually communicate with the chip. This also detects the chip type, and influence the following operations. Note Multiple flash chips can be attached to the same bus now. SPI Flash Access API This is the set of API functions for working with data in flash: esp_flash_read() reads data from flash to RAM esp_flash_write() writes data from RAM to flash esp_flash_erase_region() erases specific region of flash esp_flash_erase_chip() erases the whole flash esp_flash_get_chip_size() returns flash chip size, in bytes, as configured in menuconfig Generally, try to avoid using the raw SPI flash functions to the "main" SPI flash chip in favour of partition-specific functions. SPI Flash Size The SPI flash size is configured by writing a field in the software bootloader image header, flashed at offset 0x1000. By default, the SPI flash size is detected by esptool.py when this bootloader is written to flash, and the header is updated with the correct size. Alternatively, it is possible to generate a fixed flash size by setting CONFIG_ESPTOOLPY_FLASHSIZE in the project configuration. If it is necessary to override the configured flash size at runtime, it is possible to set the chip_size member of the g_rom_flashchip structure. This size is used by esp_flash_* functions (in both software & ROM) to check the bounds. Concurrency Constraints for Flash on SPI1 Attention The SPI0/1 bus is shared between the instruction & data cache (for firmware execution) and the SPI1 peripheral (controlled by the drivers including this SPI flash driver). Hence, calling SPI Flash API on SPI1 bus (including the main flash) causes significant influence to the whole system. See Concurrency Constraints for Flash on SPI1 for more details. SPI Flash Encryption It is possible to encrypt the contents of SPI flash and have it transparently decrypted by hardware. Refer to the Flash Encryption documentation for more details. Memory Mapping API ESP32 features memory hardware which allows regions of flash memory to be mapped into instruction and data address spaces. This mapping works only for read operations. It is not possible to modify contents of flash memory by writing to a mapped memory region. Mapping happens in 64 KB pages. Memory mapping hardware can map flash into the data address space and the instruction address space. See the technical reference manual for more details and limitations about memory mapping hardware. Note that some pages are used to map the application itself into memory, so the actual number of available pages may be less than the capability of the hardware. Reading data from flash using a memory mapped region is the only way to decrypt contents of flash when flash encryption is enabled. Decryption is performed at the hardware level. Memory mapping API are declared in spi_flash_mmap.h and esp_partition.h : spi_flash_mmap() maps a region of physical flash addresses into instruction space or data space of the CPU. spi_flash_munmap() unmaps previously mapped region. esp_partition_mmap() maps part of a partition into the instruction space or data space of the CPU. Differences between spi_flash_mmap() and esp_partition_mmap() are as follows: spi_flash_mmap() must be given a 64 KB aligned physical address. esp_partition_mmap() may be given any arbitrary offset within the partition. It adjusts the returned pointer to mapped memory as necessary. Note that since memory mapping happens in pages, it may be possible to read data outside of the partition provided to esp_partition_mmap , regardless of the partition boundary. Note mmap is supported by cache, so it can only be used on main flash. SPI Flash Implementation The esp_flash_t structure holds chip data as well as three important parts of this API: The host driver, which provides the hardware support to access the chip; The chip driver, which provides compatibility service to different chips; The OS functions, provide support of some OS functions (e.g., lock, delay) in different stages (1st/2nd boot, or the app). Host Driver The host driver relies on an interface ( spi_flash_host_driver_t ) defined in the spi_flash_types.h (in the hal/include/hal folder). This interface provides some common functions to communicate with the chip. In other files of the SPI HAL, some of these functions are implemented with existing ESP32 memory-spi functionalities. However, due to the speed limitations of ESP32, the HAL layer cannot provide high-speed implementations to some reading commands (so the support for it was dropped). The files ( memspi_host_driver.h and .c ) implement the high-speed version of these commands with the common_command function provided in the HAL, and wrap these functions as spi_flash_host_driver_t for upper layer to use. You can also implement your own host driver, even with the GPIO. As long as all the functions in the spi_flash_host_driver_t are implemented, the esp_flash API can access the flash regardless of the low-level hardware. Chip Driver The chip driver, defined in spi_flash_chip_driver.h , wraps basic functions provided by the host driver for the API layer to use. Some operations need some commands to be sent first, or read some status afterwards. Some chips need different commands or values, or need special communication ways. There is a type of chip called generic chip which stands for common chips. Other special chip drivers can be developed on the base of the generic chip. The chip driver relies on the host driver. OS Functions Currently the OS function layer provides entries of a lock and delay. The lock (see SPI Bus Lock) is used to resolve the conflicts among the access of devices on the same SPI bus, and the SPI Flash chip access. E.g. On SPI1 bus, the cache (used to fetch the data (code) in the Flash and PSRAM) should be disabled when the flash chip on the SPI0/1 is being accessed. On the other buses, the flash driver needs to disable the ISR registered by SPI Master driver, to avoid conflicts. Some devices of SPI Master driver may require to use the bus monopolized during a period (especially when the device does not have a CS wire, or the wire is controlled by software like SDSPI driver). The delay is used by some long operations which requires the master to wait or polling periodically. The top API wraps these the chip driver and OS functions into an entire component, and also provides some argument checking. OS functions can also help to avoid a watchdog timeout when erasing large flash areas. During this time, the CPU is occupied with the flash erasing task. This stops other tasks from being executed. Among these tasks is the idle task to feed the watchdog timer (WDT). If the configuration option CONFIG_ESP_TASK_WDT_PANIC is selected and the flash operation time is longer than the watchdog timeout period, the system will reboot. It is pretty hard to totally eliminate this risk, because the erasing time varies with different flash chips, making it hard to be compatible in flash drivers. Therefore, users need to pay attention to it. Please use the following guidelines: It is recommended to enable the CONFIG_SPI_FLASH_YIELD_DURING_ERASE option to allow the scheduler to re-schedule during erasing flash memory. Besides, following parameters can also be used. Increase CONFIG_SPI_FLASH_ERASE_YIELD_TICKS or decrease CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS in menuconfig. You can also increase CONFIG_ESP_TASK_WDT_TIMEOUT_S in menuconfig for a larger watchdog timeout period. However, with larger watchdog timeout period, previously detected timeouts may no longer be detected. Please be aware of the consequences of enabling the CONFIG_ESP_TASK_WDT_PANIC option when doing long-running SPI flash operations which triggers the panic handler when it times out. However, this option can also help dealing with unexpected exceptions in your application. Please decide whether this is needed to be enabled according to actual condition. During your development, please carefully review the actual flash operation according to the specific requirements and time limits on erasing flash memory of your projects. Always allow reasonable redundancy based on your specific product requirements when configuring the flash erasing timeout threshold, thus improving the reliability of your product. Implementation Details In order to perform some flash operations, it is necessary to make sure that both CPUs are not running any code from flash for the duration of the flash operation: In a single-core setup, the SDK needs to disable interrupts or scheduler before performing the flash operation. In a dual-core setup, the SDK needs to make sure that both CPUs are not running any code from flash. When SPI flash API is called on CPU A (can be PRO or APP), start the spi_flash_op_block_func function on CPU B using the esp_ipc_call API. This API wakes up a high priority task on CPU B and tells it to execute a given function, in this case, spi_flash_op_block_func . This function disables cache on CPU B and signals that the cache is disabled by setting the s_flash_op_can_start flag. Then the task on CPU A disables cache as well and proceeds to execute flash operation. While a flash operation is running, interrupts can still run on CPUs A and B. It is assumed that all interrupt code is placed into RAM. Once the interrupt allocation API is added, a flag should be added to request the interrupt to be disabled for the duration of a flash operations. Once the flash operation is complete, the function on CPU A sets another flag, s_flash_op_complete , to let the task on CPU B know that it can re-enable cache and release the CPU. Then the function on CPU A re-enables the cache on CPU A as well and returns control to the calling code. Additionally, all API functions are protected with a mutex ( s_flash_op_mutex ). In a single core environment (CONFIG_FREERTOS_UNICORE enabled), you need to disable both caches, so that no inter-CPU communication can take place. API Reference - SPI Flash Header File This header file can be included with: #include "esp_flash_spi_init.h" This header file is a part of the API provided by the spi_flash component. To declare that your component depends on spi_flash , add the following to your CMakeLists.txt: REQUIRES spi_flash or PRIV_REQUIRES spi_flash Functions esp_err_t spi_bus_add_flash_device(esp_flash_t **out_chip, const esp_flash_spi_device_config_t *config) Add a SPI Flash device onto the SPI bus. The bus should be already initialized by spi_bus_initialization . Parameters out_chip -- Pointer to hold the initialized chip. config -- Configuration of the chips to initialize. out_chip -- Pointer to hold the initialized chip. config -- Configuration of the chips to initialize. out_chip -- Pointer to hold the initialized chip. Returns ESP_ERR_INVALID_ARG: out_chip is NULL, or some field in the config is invalid. ESP_ERR_NO_MEM: failed to allocate memory for the chip structures. ESP_OK: success. ESP_ERR_INVALID_ARG: out_chip is NULL, or some field in the config is invalid. ESP_ERR_NO_MEM: failed to allocate memory for the chip structures. ESP_OK: success. ESP_ERR_INVALID_ARG: out_chip is NULL, or some field in the config is invalid. Parameters out_chip -- Pointer to hold the initialized chip. config -- Configuration of the chips to initialize. Returns ESP_ERR_INVALID_ARG: out_chip is NULL, or some field in the config is invalid. ESP_ERR_NO_MEM: failed to allocate memory for the chip structures. ESP_OK: success. esp_err_t spi_bus_remove_flash_device(esp_flash_t *chip) Remove a SPI Flash device from the SPI bus. Parameters chip -- The flash device to remove. Returns ESP_ERR_INVALID_ARG: The chip is invalid. ESP_OK: success. ESP_ERR_INVALID_ARG: The chip is invalid. ESP_OK: success. ESP_ERR_INVALID_ARG: The chip is invalid. Parameters chip -- The flash device to remove. Returns ESP_ERR_INVALID_ARG: The chip is invalid. ESP_OK: success. Structures struct esp_flash_spi_device_config_t Configurations for the SPI Flash to init. Public Members spi_host_device_t host_id Bus to use. spi_host_device_t host_id Bus to use. int cs_io_num GPIO pin to output the CS signal. int cs_io_num GPIO pin to output the CS signal. esp_flash_io_mode_t io_mode IO mode to read from the Flash. esp_flash_io_mode_t io_mode IO mode to read from the Flash. enum esp_flash_speed_s speed Speed of the Flash clock. Replaced by freq_mhz. enum esp_flash_speed_s speed Speed of the Flash clock. Replaced by freq_mhz. int input_delay_ns Input delay of the data pins, in ns. Set to 0 if unknown. int input_delay_ns Input delay of the data pins, in ns. Set to 0 if unknown. int cs_id CS line ID, ignored when not host_id is not SPI1_HOST, or CONFIG_SPI_FLASH_SHARE_SPI1_BUS is enabled. In this case, the CS line used is automatically assigned by the SPI bus lock. int cs_id CS line ID, ignored when not host_id is not SPI1_HOST, or CONFIG_SPI_FLASH_SHARE_SPI1_BUS is enabled. In this case, the CS line used is automatically assigned by the SPI bus lock. int freq_mhz The frequency of flash chip(MHZ) int freq_mhz The frequency of flash chip(MHZ) spi_host_device_t host_id Header File This header file can be included with: #include "esp_flash.h" This header file is a part of the API provided by the spi_flash component. To declare that your component depends on spi_flash , add the following to your CMakeLists.txt: REQUIRES spi_flash or PRIV_REQUIRES spi_flash Functions esp_err_t esp_flash_init(esp_flash_t *chip) Initialise SPI flash chip interface. This function must be called before any other API functions are called for this chip. Note Only the host and read_mode fields of the chip structure must be initialised before this function is called. Other fields may be auto-detected if left set to zero or NULL. Note If the chip->drv pointer is NULL, chip chip_drv will be auto-detected based on its manufacturer & product IDs. See esp_flash_registered_flash_drivers pointer for details of this process. Parameters chip -- Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted. Returns ESP_OK on success, or a flash error code if initialisation fails. Parameters chip -- Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted. Returns ESP_OK on success, or a flash error code if initialisation fails. bool esp_flash_chip_driver_initialized(const esp_flash_t *chip) Check if appropriate chip driver is set. Parameters chip -- Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted. Returns true if set, otherwise false. Parameters chip -- Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted. Returns true if set, otherwise false. esp_err_t esp_flash_read_id(esp_flash_t *chip, uint32_t *out_id) Read flash ID via the common "RDID" SPI flash command. ID is a 24-bit value. Lower 16 bits of 'id' are the chip ID, upper 8 bits are the manufacturer ID. Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() out_id -- [out] Pointer to receive ID value. chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() out_id -- [out] Pointer to receive ID value. chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() Returns ESP_OK on success, or a flash error code if operation failed. Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() out_id -- [out] Pointer to receive ID value. Returns ESP_OK on success, or a flash error code if operation failed. esp_err_t esp_flash_get_size(esp_flash_t *chip, uint32_t *out_size) Detect flash size based on flash ID. Note 1. Most flash chips use a common format for flash ID, where the lower 4 bits specify the size as a power of 2. If the manufacturer doesn't follow this convention, the size may be incorrectly detected. The out_size returned only stands for The out_size stands for the size in the binary image header. If you want to get the real size of the chip, please call esp_flash_get_physical_size instead. The out_size returned only stands for The out_size stands for the size in the binary image header. If you want to get the real size of the chip, please call esp_flash_get_physical_size instead. Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() out_size -- [out] Detected size in bytes, standing for the size in the binary image header. chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() out_size -- [out] Detected size in bytes, standing for the size in the binary image header. chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() Returns ESP_OK on success, or a flash error code if operation failed. Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() out_size -- [out] Detected size in bytes, standing for the size in the binary image header. Returns ESP_OK on success, or a flash error code if operation failed. The out_size returned only stands for The out_size stands for the size in the binary image header. If you want to get the real size of the chip, please call esp_flash_get_physical_size instead. esp_err_t esp_flash_get_physical_size(esp_flash_t *chip, uint32_t *flash_size) Detect flash size based on flash ID. Note Most flash chips use a common format for flash ID, where the lower 4 bits specify the size as a power of 2. If the manufacturer doesn't follow this convention, the size may be incorrectly detected. Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() flash_size -- [out] Detected size in bytes. chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() flash_size -- [out] Detected size in bytes. chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() Returns ESP_OK on success, or a flash error code if operation failed. Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() flash_size -- [out] Detected size in bytes. Returns ESP_OK on success, or a flash error code if operation failed. esp_err_t esp_flash_read_unique_chip_id(esp_flash_t *chip, uint64_t *out_id) Read flash unique ID via the common "RDUID" SPI flash command. ID is a 64-bit value. Note This is an optional feature, which is not supported on all flash chips. READ PROGRAMMING GUIDE FIRST! Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init(). out_id -- [out] Pointer to receive unique ID value. chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init(). out_id -- [out] Pointer to receive unique ID value. chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init(). Returns ESP_OK on success, or a flash error code if operation failed. ESP_ERR_NOT_SUPPORTED if the chip doesn't support read id. ESP_OK on success, or a flash error code if operation failed. ESP_ERR_NOT_SUPPORTED if the chip doesn't support read id. ESP_OK on success, or a flash error code if operation failed. Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init(). out_id -- [out] Pointer to receive unique ID value. Returns ESP_OK on success, or a flash error code if operation failed. ESP_ERR_NOT_SUPPORTED if the chip doesn't support read id. esp_err_t esp_flash_erase_chip(esp_flash_t *chip) Erase flash chip contents. Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() Returns ESP_OK on success, ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is indicated by WREN = 1 after the command is sent. ESP_ERR_NOT_ALLOWED if a read-only partition is present. Other flash error code if operation failed. ESP_OK on success, ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is indicated by WREN = 1 after the command is sent. ESP_ERR_NOT_ALLOWED if a read-only partition is present. Other flash error code if operation failed. ESP_OK on success, Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() Returns ESP_OK on success, ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is indicated by WREN = 1 after the command is sent. ESP_ERR_NOT_ALLOWED if a read-only partition is present. Other flash error code if operation failed. esp_err_t esp_flash_erase_region(esp_flash_t *chip, uint32_t start, uint32_t len) Erase a region of the flash chip. Sector size is specifyed in chip->drv->sector_size field (typically 4096 bytes.) ESP_ERR_INVALID_ARG will be returned if the start & length are not a multiple of this size. Erase is performed using block (multi-sector) erases where possible (block size is specified in chip->drv->block_erase_size field, typically 65536 bytes). Remaining sectors are erased using individual sector erase commands. Parameters chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() start -- Address to start erasing flash. Must be sector aligned. len -- Length of region to erase. Must also be sector aligned. chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() start -- Address to start erasing flash. Must be sector aligned. len -- Length of region to erase. Must also be sector aligned. chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() Returns ESP_OK on success, ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is indicated by WREN = 1 after the command is sent. ESP_ERR_NOT_ALLOWED if the address range (start – start + len) overlaps with a read-only partition address space Other flash error code if operation failed. ESP_OK on success, ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is indicated by WREN = 1 after the command is sent. ESP_ERR_NOT_ALLOWED if the address range (start – start + len) overlaps with a read-only partition address space Other flash error code if operation failed. ESP_OK on success, Parameters chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() start -- Address to start erasing flash. Must be sector aligned. len -- Length of region to erase. Must also be sector aligned. Returns ESP_OK on success, ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is indicated by WREN = 1 after the command is sent. ESP_ERR_NOT_ALLOWED if the address range (start – start + len) overlaps with a read-only partition address space Other flash error code if operation failed. esp_err_t esp_flash_get_chip_write_protect(esp_flash_t *chip, bool *write_protected) Read if the entire chip is write protected. Note A correct result for this flag depends on the SPI flash chip model and chip_drv in use (via the 'chip->drv' field). Parameters chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() write_protected -- [out] Pointer to boolean, set to the value of the write protect flag. chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() write_protected -- [out] Pointer to boolean, set to the value of the write protect flag. chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() Returns ESP_OK on success, or a flash error code if operation failed. Parameters chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() write_protected -- [out] Pointer to boolean, set to the value of the write protect flag. Returns ESP_OK on success, or a flash error code if operation failed. esp_err_t esp_flash_set_chip_write_protect(esp_flash_t *chip, bool write_protect) Set write protection for the SPI flash chip. Some SPI flash chips may require a power cycle before write protect status can be cleared. Otherwise, write protection can be removed via a follow-up call to this function. Note Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the 'chip->drv' field). Parameters chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() write_protect -- Boolean value for the write protect flag chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() write_protect -- Boolean value for the write protect flag chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() Returns ESP_OK on success, or a flash error code if operation failed. Parameters chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() write_protect -- Boolean value for the write protect flag Returns ESP_OK on success, or a flash error code if operation failed. esp_err_t esp_flash_get_protectable_regions(const esp_flash_t *chip, const esp_flash_region_t **out_regions, uint32_t *out_num_regions) Read the list of individually protectable regions of this SPI flash chip. Note Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the 'chip->drv' field). Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() out_regions -- [out] Pointer to receive a pointer to the array of protectable regions of the chip. out_num_regions -- [out] Pointer to an integer receiving the count of protectable regions in the array returned in 'regions'. chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() out_regions -- [out] Pointer to receive a pointer to the array of protectable regions of the chip. out_num_regions -- [out] Pointer to an integer receiving the count of protectable regions in the array returned in 'regions'. chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() Returns ESP_OK on success, or a flash error code if operation failed. Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() out_regions -- [out] Pointer to receive a pointer to the array of protectable regions of the chip. out_num_regions -- [out] Pointer to an integer receiving the count of protectable regions in the array returned in 'regions'. Returns ESP_OK on success, or a flash error code if operation failed. esp_err_t esp_flash_get_protected_region(esp_flash_t *chip, const esp_flash_region_t *region, bool *out_protected) Detect if a region of the SPI flash chip is protected. Note It is possible for this result to be false and write operations to still fail, if protection is enabled for the entire chip. Note Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the 'chip->drv' field). Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() region -- Pointer to a struct describing a protected region. This must match one of the regions returned from esp_flash_get_protectable_regions(...). out_protected -- [out] Pointer to a flag which is set based on the protected status for this region. chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() region -- Pointer to a struct describing a protected region. This must match one of the regions returned from esp_flash_get_protectable_regions(...). out_protected -- [out] Pointer to a flag which is set based on the protected status for this region. chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() Returns ESP_OK on success, or a flash error code if operation failed. Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() region -- Pointer to a struct describing a protected region. This must match one of the regions returned from esp_flash_get_protectable_regions(...). out_protected -- [out] Pointer to a flag which is set based on the protected status for this region. Returns ESP_OK on success, or a flash error code if operation failed. esp_err_t esp_flash_set_protected_region(esp_flash_t *chip, const esp_flash_region_t *region, bool protect) Update the protected status for a region of the SPI flash chip. Note It is possible for the region protection flag to be cleared and write operations to still fail, if protection is enabled for the entire chip. Note Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the 'chip->drv' field). Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() region -- Pointer to a struct describing a protected region. This must match one of the regions returned from esp_flash_get_protectable_regions(...). protect -- Write protection flag to set. chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() region -- Pointer to a struct describing a protected region. This must match one of the regions returned from esp_flash_get_protectable_regions(...). protect -- Write protection flag to set. chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() Returns ESP_OK on success, or a flash error code if operation failed. Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() region -- Pointer to a struct describing a protected region. This must match one of the regions returned from esp_flash_get_protectable_regions(...). protect -- Write protection flag to set. Returns ESP_OK on success, or a flash error code if operation failed. esp_err_t esp_flash_read(esp_flash_t *chip, void *buffer, uint32_t address, uint32_t length) Read data from the SPI flash chip. There are no alignment constraints on buffer, address or length. Note If on-chip flash encryption is used, this function returns raw (ie encrypted) data. Use the flash cache to transparently decrypt data. Parameters chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() buffer -- Pointer to a buffer where the data will be read. To get better performance, this should be in the DRAM and word aligned. address -- Address on flash to read from. Must be less than chip->size field. length -- Length (in bytes) of data to read. chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() buffer -- Pointer to a buffer where the data will be read. To get better performance, this should be in the DRAM and word aligned. address -- Address on flash to read from. Must be less than chip->size field. length -- Length (in bytes) of data to read. chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() Returns ESP_OK: success ESP_ERR_NO_MEM: Buffer is in external PSRAM which cannot be concurrently accessed, and a temporary internal buffer could not be allocated. or a flash error code if operation failed. ESP_OK: success ESP_ERR_NO_MEM: Buffer is in external PSRAM which cannot be concurrently accessed, and a temporary internal buffer could not be allocated. or a flash error code if operation failed. ESP_OK: success Parameters chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() buffer -- Pointer to a buffer where the data will be read. To get better performance, this should be in the DRAM and word aligned. address -- Address on flash to read from. Must be less than chip->size field. length -- Length (in bytes) of data to read. Returns ESP_OK: success ESP_ERR_NO_MEM: Buffer is in external PSRAM which cannot be concurrently accessed, and a temporary internal buffer could not be allocated. or a flash error code if operation failed. esp_err_t esp_flash_write(esp_flash_t *chip, const void *buffer, uint32_t address, uint32_t length) Write data to the SPI flash chip. There are no alignment constraints on buffer, address or length. Parameters chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() address -- Address on flash to write to. Must be previously erased (SPI NOR flash can only write bits 1->0). buffer -- Pointer to a buffer with the data to write. To get better performance, this should be in the DRAM and word aligned. length -- Length (in bytes) of data to write. chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() address -- Address on flash to write to. Must be previously erased (SPI NOR flash can only write bits 1->0). buffer -- Pointer to a buffer with the data to write. To get better performance, this should be in the DRAM and word aligned. length -- Length (in bytes) of data to write. chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() Returns ESP_OK on success ESP_FAIL, bad write, this will be detected only when CONFIG_SPI_FLASH_VERIFY_WRITE is enabled ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is indicated by WREN = 1 after the command is sent. ESP_ERR_NOT_ALLOWED if the address range (address – address + length) overlaps with a read-only partition address space Other flash error code if operation failed. ESP_OK on success ESP_FAIL, bad write, this will be detected only when CONFIG_SPI_FLASH_VERIFY_WRITE is enabled ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is indicated by WREN = 1 after the command is sent. ESP_ERR_NOT_ALLOWED if the address range (address – address + length) overlaps with a read-only partition address space Other flash error code if operation failed. ESP_OK on success Parameters chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() address -- Address on flash to write to. Must be previously erased (SPI NOR flash can only write bits 1->0). buffer -- Pointer to a buffer with the data to write. To get better performance, this should be in the DRAM and word aligned. length -- Length (in bytes) of data to write. Returns ESP_OK on success ESP_FAIL, bad write, this will be detected only when CONFIG_SPI_FLASH_VERIFY_WRITE is enabled ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is indicated by WREN = 1 after the command is sent. ESP_ERR_NOT_ALLOWED if the address range (address – address + length) overlaps with a read-only partition address space Other flash error code if operation failed. esp_err_t esp_flash_write_encrypted(esp_flash_t *chip, uint32_t address, const void *buffer, uint32_t length) Encrypted and write data to the SPI flash chip using on-chip hardware flash encryption. Note Both address & length must be 16 byte aligned, as this is the encryption block size Parameters chip -- Pointer to identify flash chip. Must be NULL (the main flash chip). For other chips, encrypted write is not supported. address -- Address on flash to write to. 16 byte aligned. Must be previously erased (SPI NOR flash can only write bits 1->0). buffer -- Pointer to a buffer with the data to write. length -- Length (in bytes) of data to write. 16 byte aligned. chip -- Pointer to identify flash chip. Must be NULL (the main flash chip). For other chips, encrypted write is not supported. address -- Address on flash to write to. 16 byte aligned. Must be previously erased (SPI NOR flash can only write bits 1->0). buffer -- Pointer to a buffer with the data to write. length -- Length (in bytes) of data to write. 16 byte aligned. chip -- Pointer to identify flash chip. Must be NULL (the main flash chip). For other chips, encrypted write is not supported. Returns ESP_OK: on success ESP_FAIL: bad write, this will be detected only when CONFIG_SPI_FLASH_VERIFY_WRITE is enabled ESP_ERR_NOT_SUPPORTED: encrypted write not supported for this chip. ESP_ERR_INVALID_ARG: Either the address, buffer or length is invalid. ESP_ERR_NOT_ALLOWED if the address range (address – address + length) overlaps with a read-only partition address space ESP_OK: on success ESP_FAIL: bad write, this will be detected only when CONFIG_SPI_FLASH_VERIFY_WRITE is enabled ESP_ERR_NOT_SUPPORTED: encrypted write not supported for this chip. ESP_ERR_INVALID_ARG: Either the address, buffer or length is invalid. ESP_ERR_NOT_ALLOWED if the address range (address – address + length) overlaps with a read-only partition address space ESP_OK: on success Parameters chip -- Pointer to identify flash chip. Must be NULL (the main flash chip). For other chips, encrypted write is not supported. address -- Address on flash to write to. 16 byte aligned. Must be previously erased (SPI NOR flash can only write bits 1->0). buffer -- Pointer to a buffer with the data to write. length -- Length (in bytes) of data to write. 16 byte aligned. Returns ESP_OK: on success ESP_FAIL: bad write, this will be detected only when CONFIG_SPI_FLASH_VERIFY_WRITE is enabled ESP_ERR_NOT_SUPPORTED: encrypted write not supported for this chip. ESP_ERR_INVALID_ARG: Either the address, buffer or length is invalid. ESP_ERR_NOT_ALLOWED if the address range (address – address + length) overlaps with a read-only partition address space esp_err_t esp_flash_read_encrypted(esp_flash_t *chip, uint32_t address, void *out_buffer, uint32_t length) Read and decrypt data from the SPI flash chip using on-chip hardware flash encryption. Parameters chip -- Pointer to identify flash chip. Must be NULL (the main flash chip). For other chips, encrypted read is not supported. address -- Address on flash to read from. out_buffer -- Pointer to a buffer for the data to read to. length -- Length (in bytes) of data to read. chip -- Pointer to identify flash chip. Must be NULL (the main flash chip). For other chips, encrypted read is not supported. address -- Address on flash to read from. out_buffer -- Pointer to a buffer for the data to read to. length -- Length (in bytes) of data to read. chip -- Pointer to identify flash chip. Must be NULL (the main flash chip). For other chips, encrypted read is not supported. Returns ESP_OK: on success ESP_ERR_NOT_SUPPORTED: encrypted read not supported for this chip. ESP_OK: on success ESP_ERR_NOT_SUPPORTED: encrypted read not supported for this chip. ESP_OK: on success Parameters chip -- Pointer to identify flash chip. Must be NULL (the main flash chip). For other chips, encrypted read is not supported. address -- Address on flash to read from. out_buffer -- Pointer to a buffer for the data to read to. length -- Length (in bytes) of data to read. Returns ESP_OK: on success ESP_ERR_NOT_SUPPORTED: encrypted read not supported for this chip. static inline bool esp_flash_is_quad_mode(const esp_flash_t *chip) Returns true if chip is configured for Quad I/O or Quad Fast Read. Parameters chip -- Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted. Returns true if flash works in quad mode, otherwise false Parameters chip -- Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted. Returns true if flash works in quad mode, otherwise false Structures struct esp_flash_region_t Structure for describing a region of flash. struct esp_flash_os_functions_t OS-level integration hooks for accessing flash chips inside a running OS. It's in the public header because some instances should be allocated statically in the startup code. May be updated according to hardware version and new flash chip feature requirements, shouldn't be treated as public API. For advanced developers, you may replace some of them with your implementations at your own risk. Public Members esp_err_t (*start)(void *arg) Called before commencing any flash operation. Does not need to be recursive (ie is called at most once for each call to 'end'). esp_err_t (*start)(void *arg) Called before commencing any flash operation. Does not need to be recursive (ie is called at most once for each call to 'end'). esp_err_t (*region_protected)(void *arg, size_t start_addr, size_t size) Called before any erase/write operations to check whether the region is limited by the OS esp_err_t (*region_protected)(void *arg, size_t start_addr, size_t size) Called before any erase/write operations to check whether the region is limited by the OS esp_err_t (*delay_us)(void *arg, uint32_t us) Delay for at least 'us' microseconds. Called in between 'start' and 'end'. esp_err_t (*delay_us)(void *arg, uint32_t us) Delay for at least 'us' microseconds. Called in between 'start' and 'end'. void *(*get_temp_buffer)(void *arg, size_t reqest_size, size_t *out_size) Called for get temp buffer when buffer from application cannot be directly read into/write from. void *(*get_temp_buffer)(void *arg, size_t reqest_size, size_t *out_size) Called for get temp buffer when buffer from application cannot be directly read into/write from. void (*release_temp_buffer)(void *arg, void *temp_buf) Called for release temp buffer. void (*release_temp_buffer)(void *arg, void *temp_buf) Called for release temp buffer. esp_err_t (*check_yield)(void *arg, uint32_t chip_status, uint32_t *out_request) Yield to other tasks. Called during erase operations. Return ESP_OK means yield needs to be called (got an event to handle), while ESP_ERR_TIMEOUT means skip yield. Return ESP_OK means yield needs to be called (got an event to handle), while ESP_ERR_TIMEOUT means skip yield. esp_err_t (*check_yield)(void *arg, uint32_t chip_status, uint32_t *out_request) Yield to other tasks. Called during erase operations. Return ESP_OK means yield needs to be called (got an event to handle), while ESP_ERR_TIMEOUT means skip yield. esp_err_t (*yield)(void *arg, uint32_t *out_status) Yield to other tasks. Called during erase operations. esp_err_t (*yield)(void *arg, uint32_t *out_status) Yield to other tasks. Called during erase operations. int64_t (*get_system_time)(void *arg) Called for get system time. int64_t (*get_system_time)(void *arg) Called for get system time. void (*set_flash_op_status)(uint32_t op_status) Call to set flash operation status void (*set_flash_op_status)(uint32_t op_status) Call to set flash operation status esp_err_t (*start)(void *arg) struct esp_flash_t Structure to describe a SPI flash chip connected to the system. Structure must be initialized before use (passed to esp_flash_init()). It's in the public header because some instances should be allocated statically in the startup code. May be updated according to hardware version and new flash chip feature requirements, shouldn't be treated as public API. For advanced developers, you may replace some of them with your implementations at your own risk. Public Members spi_flash_host_inst_t *host Pointer to hardware-specific "host_driver" structure. Must be initialized before used. spi_flash_host_inst_t *host Pointer to hardware-specific "host_driver" structure. Must be initialized before used. const spi_flash_chip_t *chip_drv Pointer to chip-model-specific "adapter" structure. If NULL, will be detected during initialisation. const spi_flash_chip_t *chip_drv Pointer to chip-model-specific "adapter" structure. If NULL, will be detected during initialisation. const esp_flash_os_functions_t *os_func Pointer to os-specific hook structure. Call esp_flash_init_os_functions() to setup this field, after the host is properly initialized. const esp_flash_os_functions_t *os_func Pointer to os-specific hook structure. Call esp_flash_init_os_functions() to setup this field, after the host is properly initialized. void *os_func_data Pointer to argument for os-specific hooks. Left NULL and will be initialized with os_func . void *os_func_data Pointer to argument for os-specific hooks. Left NULL and will be initialized with os_func . esp_flash_io_mode_t read_mode Configured SPI flash read mode. Set before esp_flash_init is called. esp_flash_io_mode_t read_mode Configured SPI flash read mode. Set before esp_flash_init is called. uint32_t size Size of SPI flash in bytes. If 0, size will be detected during initialisation. Note: this stands for the size in the binary image header. If you want to get the flash physical size, please call esp_flash_get_physical_size . uint32_t size Size of SPI flash in bytes. If 0, size will be detected during initialisation. Note: this stands for the size in the binary image header. If you want to get the flash physical size, please call esp_flash_get_physical_size . uint32_t chip_id Detected chip id. uint32_t chip_id Detected chip id. uint32_t busy This flag is used to verify chip's status. uint32_t busy This flag is used to verify chip's status. uint32_t hpm_dummy_ena This flag is used to verify whether flash works under HPM status. uint32_t hpm_dummy_ena This flag is used to verify whether flash works under HPM status. uint32_t reserved_flags reserved. uint32_t reserved_flags reserved. spi_flash_host_inst_t *host Macros SPI_FLASH_YIELD_REQ_YIELD SPI_FLASH_YIELD_REQ_SUSPEND SPI_FLASH_YIELD_STA_RESUME SPI_FLASH_OS_IS_ERASING_STATUS_FLAG Type Definitions typedef struct spi_flash_chip_t spi_flash_chip_t Header File This header file can be included with: #include "spi_flash_mmap.h" This header file is a part of the API provided by the spi_flash component. To declare that your component depends on spi_flash , add the following to your CMakeLists.txt: REQUIRES spi_flash or PRIV_REQUIRES spi_flash Functions esp_err_t spi_flash_mmap(size_t src_addr, size_t size, spi_flash_mmap_memory_t memory, const void **out_ptr, spi_flash_mmap_handle_t *out_handle) Map region of flash memory into data or instruction address space. This function allocates sufficient number of 64kB MMU pages and configures them to map the requested region of flash memory into the address space. It may reuse MMU pages which already provide the required mapping. As with any allocator, if mmap/munmap are heavily used then the address space may become fragmented. To troubleshoot issues with page allocation, use spi_flash_mmap_dump() function. Parameters src_addr -- Physical address in flash where requested region starts. This address must be aligned to 64kB boundary (SPI_FLASH_MMU_PAGE_SIZE) size -- Size of region to be mapped. This size will be rounded up to a 64kB boundary memory -- Address space where the region should be mapped (data or instruction) out_ptr -- [out] Output, pointer to the mapped memory region out_handle -- [out] Output, handle which should be used for spi_flash_munmap call src_addr -- Physical address in flash where requested region starts. This address must be aligned to 64kB boundary (SPI_FLASH_MMU_PAGE_SIZE) size -- Size of region to be mapped. This size will be rounded up to a 64kB boundary memory -- Address space where the region should be mapped (data or instruction) out_ptr -- [out] Output, pointer to the mapped memory region out_handle -- [out] Output, handle which should be used for spi_flash_munmap call src_addr -- Physical address in flash where requested region starts. This address must be aligned to 64kB boundary (SPI_FLASH_MMU_PAGE_SIZE) Returns ESP_OK on success, ESP_ERR_NO_MEM if pages can not be allocated Parameters src_addr -- Physical address in flash where requested region starts. This address must be aligned to 64kB boundary (SPI_FLASH_MMU_PAGE_SIZE) size -- Size of region to be mapped. This size will be rounded up to a 64kB boundary memory -- Address space where the region should be mapped (data or instruction) out_ptr -- [out] Output, pointer to the mapped memory region out_handle -- [out] Output, handle which should be used for spi_flash_munmap call Returns ESP_OK on success, ESP_ERR_NO_MEM if pages can not be allocated esp_err_t spi_flash_mmap_pages(const int *pages, size_t page_count, spi_flash_mmap_memory_t memory, const void **out_ptr, spi_flash_mmap_handle_t *out_handle) Map sequences of pages of flash memory into data or instruction address space. This function allocates sufficient number of 64kB MMU pages and configures them to map the indicated pages of flash memory contiguously into address space. In this respect, it works in a similar way as spi_flash_mmap() but it allows mapping a (maybe non-contiguous) set of pages into a contiguous region of memory. Parameters pages -- An array of numbers indicating the 64kB pages in flash to be mapped contiguously into memory. These indicate the indexes of the 64kB pages, not the byte-size addresses as used in other functions. Array must be located in internal memory. page_count -- Number of entries in the pages array memory -- Address space where the region should be mapped (instruction or data) out_ptr -- [out] Output, pointer to the mapped memory region out_handle -- [out] Output, handle which should be used for spi_flash_munmap call pages -- An array of numbers indicating the 64kB pages in flash to be mapped contiguously into memory. These indicate the indexes of the 64kB pages, not the byte-size addresses as used in other functions. Array must be located in internal memory. page_count -- Number of entries in the pages array memory -- Address space where the region should be mapped (instruction or data) out_ptr -- [out] Output, pointer to the mapped memory region out_handle -- [out] Output, handle which should be used for spi_flash_munmap call pages -- An array of numbers indicating the 64kB pages in flash to be mapped contiguously into memory. These indicate the indexes of the 64kB pages, not the byte-size addresses as used in other functions. Array must be located in internal memory. Returns ESP_OK on success ESP_ERR_NO_MEM if pages can not be allocated ESP_ERR_INVALID_ARG if pagecount is zero or pages array is not in internal memory ESP_OK on success ESP_ERR_NO_MEM if pages can not be allocated ESP_ERR_INVALID_ARG if pagecount is zero or pages array is not in internal memory ESP_OK on success Parameters pages -- An array of numbers indicating the 64kB pages in flash to be mapped contiguously into memory. These indicate the indexes of the 64kB pages, not the byte-size addresses as used in other functions. Array must be located in internal memory. page_count -- Number of entries in the pages array memory -- Address space where the region should be mapped (instruction or data) out_ptr -- [out] Output, pointer to the mapped memory region out_handle -- [out] Output, handle which should be used for spi_flash_munmap call Returns ESP_OK on success ESP_ERR_NO_MEM if pages can not be allocated ESP_ERR_INVALID_ARG if pagecount is zero or pages array is not in internal memory void spi_flash_munmap(spi_flash_mmap_handle_t handle) Release region previously obtained using spi_flash_mmap. Note Calling this function will not necessarily unmap memory region. Region will only be unmapped when there are no other handles which reference this region. In case of partially overlapping regions it is possible that memory will be unmapped partially. Parameters handle -- Handle obtained from spi_flash_mmap Parameters handle -- Handle obtained from spi_flash_mmap void spi_flash_mmap_dump(void) Display information about mapped regions. This function lists handles obtained using spi_flash_mmap, along with range of pages allocated to each handle. It also lists all non-zero entries of MMU table and corresponding reference counts. uint32_t spi_flash_mmap_get_free_pages(spi_flash_mmap_memory_t memory) get free pages number which can be mmap This function will return number of free pages available in mmu table. This could be useful before calling actual spi_flash_mmap (maps flash range to DCache or ICache memory) to check if there is sufficient space available for mapping. Parameters memory -- memory type of MMU table free page Returns number of free pages which can be mmaped Parameters memory -- memory type of MMU table free page Returns number of free pages which can be mmaped size_t spi_flash_cache2phys(const void *cached) Given a memory address where flash is mapped, return the corresponding physical flash offset. Cache address does not have have been assigned via spi_flash_mmap(), any address in memory mapped flash space can be looked up. Parameters cached -- Pointer to flashed cached memory. Returns SPI_FLASH_CACHE2PHYS_FAIL If cache address is outside flash cache region, or the address is not mapped. Otherwise, returns physical offset in flash SPI_FLASH_CACHE2PHYS_FAIL If cache address is outside flash cache region, or the address is not mapped. Otherwise, returns physical offset in flash SPI_FLASH_CACHE2PHYS_FAIL If cache address is outside flash cache region, or the address is not mapped. Parameters cached -- Pointer to flashed cached memory. Returns SPI_FLASH_CACHE2PHYS_FAIL If cache address is outside flash cache region, or the address is not mapped. Otherwise, returns physical offset in flash const void *spi_flash_phys2cache(size_t phys_offs, spi_flash_mmap_memory_t memory) Given a physical offset in flash, return the address where it is mapped in the memory space. Physical address does not have to have been assigned via spi_flash_mmap(), any address in flash can be looked up. Note Only the first matching cache address is returned. If MMU flash cache table is configured so multiple entries point to the same physical address, there may be more than one cache address corresponding to that physical address. It is also possible for a single physical address to be mapped to both the IROM and DROM regions. Note This function doesn't impose any alignment constraints, but if memory argument is SPI_FLASH_MMAP_INST and phys_offs is not 4-byte aligned, then reading from the returned pointer will result in a crash. Parameters phys_offs -- Physical offset in flash memory to look up. memory -- Address space type to look up a flash cache address mapping for (instruction or data) phys_offs -- Physical offset in flash memory to look up. memory -- Address space type to look up a flash cache address mapping for (instruction or data) phys_offs -- Physical offset in flash memory to look up. Returns NULL if the physical address is invalid or not mapped to flash cache of the specified memory type. Cached memory address (in IROM or DROM space) corresponding to phys_offs. NULL if the physical address is invalid or not mapped to flash cache of the specified memory type. Cached memory address (in IROM or DROM space) corresponding to phys_offs. NULL if the physical address is invalid or not mapped to flash cache of the specified memory type. Parameters phys_offs -- Physical offset in flash memory to look up. memory -- Address space type to look up a flash cache address mapping for (instruction or data) Returns NULL if the physical address is invalid or not mapped to flash cache of the specified memory type. Cached memory address (in IROM or DROM space) corresponding to phys_offs. Macros ESP_ERR_FLASH_OP_FAIL This file contains spi_flash_mmap_xx APIs, mainly for doing memory mapping to an SPI0-connected external Flash, as well as some helper functions to convert between virtual and physical address ESP_ERR_FLASH_OP_TIMEOUT SPI_FLASH_SEC_SIZE SPI Flash sector size SPI_FLASH_MMU_PAGE_SIZE Flash cache MMU mapping page size SPI_FLASH_CACHE2PHYS_FAIL Type Definitions typedef uint32_t spi_flash_mmap_handle_t Opaque handle for memory region obtained from spi_flash_mmap. Enumerations Header File This header file can be included with: #include "hal/spi_flash_types.h" Structures struct spi_flash_trans_t Definition of a common transaction. Also holds the return value. Public Members uint8_t reserved Reserved, must be 0. uint8_t reserved Reserved, must be 0. uint8_t mosi_len Output data length, in bytes. uint8_t mosi_len Output data length, in bytes. uint8_t miso_len Input data length, in bytes. uint8_t miso_len Input data length, in bytes. uint8_t address_bitlen Length of address in bits, set to 0 if command does not need an address. uint8_t address_bitlen Length of address in bits, set to 0 if command does not need an address. uint32_t address Address to perform operation on. uint32_t address Address to perform operation on. const uint8_t *mosi_data Output data to salve. const uint8_t *mosi_data Output data to salve. uint8_t *miso_data [out] Input data from slave, little endian uint8_t *miso_data [out] Input data from slave, little endian uint32_t flags Flags for this transaction. Set to 0 for now. uint32_t flags Flags for this transaction. Set to 0 for now. uint16_t command Command to send. uint16_t command Command to send. uint8_t dummy_bitlen Basic dummy bits to use. uint8_t dummy_bitlen Basic dummy bits to use. uint32_t io_mode Flash working mode when SPI_FLASH_IGNORE_BASEIO is specified. uint32_t io_mode Flash working mode when SPI_FLASH_IGNORE_BASEIO is specified. uint8_t reserved struct spi_flash_sus_cmd_conf Configuration structure for the flash chip suspend feature. struct spi_flash_encryption_t Structure for flash encryption operations. Public Members void (*flash_encryption_enable)(void) Enable the flash encryption. void (*flash_encryption_enable)(void) Enable the flash encryption. void (*flash_encryption_disable)(void) Disable the flash encryption. void (*flash_encryption_disable)(void) Disable the flash encryption. void (*flash_encryption_data_prepare)(uint32_t address, const uint32_t *buffer, uint32_t size) Prepare flash encryption before operation. Note address and buffer must be 8-word aligned. Param address The destination address in flash for the write operation. Param buffer Data for programming Param size Size to program. Param address The destination address in flash for the write operation. Param buffer Data for programming Param size Size to program. void (*flash_encryption_data_prepare)(uint32_t address, const uint32_t *buffer, uint32_t size) Prepare flash encryption before operation. Note address and buffer must be 8-word aligned. Param address The destination address in flash for the write operation. Param buffer Data for programming Param size Size to program. void (*flash_encryption_done)(void) flash data encryption operation is done. void (*flash_encryption_done)(void) flash data encryption operation is done. void (*flash_encryption_destroy)(void) Destroy encrypted result void (*flash_encryption_destroy)(void) Destroy encrypted result bool (*flash_encryption_check)(uint32_t address, uint32_t length) Check if is qualified to encrypt the buffer Param address the address of written flash partition. Param length Buffer size. Param address the address of written flash partition. Param length Buffer size. bool (*flash_encryption_check)(uint32_t address, uint32_t length) Check if is qualified to encrypt the buffer Param address the address of written flash partition. Param length Buffer size. void (*flash_encryption_enable)(void) struct spi_flash_host_inst_t SPI Flash Host driver instance Public Members const struct spi_flash_host_driver_s *driver Pointer to the implementation function table. const struct spi_flash_host_driver_s *driver Pointer to the implementation function table. const struct spi_flash_host_driver_s *driver struct spi_flash_host_driver_s Host driver configuration and context structure. Public Members esp_err_t (*dev_config)(spi_flash_host_inst_t *host) Configure the device-related register before transactions. This saves some time to re-configure those registers when we send continuously esp_err_t (*dev_config)(spi_flash_host_inst_t *host) Configure the device-related register before transactions. This saves some time to re-configure those registers when we send continuously esp_err_t (*common_command)(spi_flash_host_inst_t *host, spi_flash_trans_t *t) Send an user-defined spi transaction to the device. esp_err_t (*common_command)(spi_flash_host_inst_t *host, spi_flash_trans_t *t) Send an user-defined spi transaction to the device. esp_err_t (*read_id)(spi_flash_host_inst_t *host, uint32_t *id) Read flash ID. esp_err_t (*read_id)(spi_flash_host_inst_t *host, uint32_t *id) Read flash ID. void (*erase_chip)(spi_flash_host_inst_t *host) Erase whole flash chip. void (*erase_chip)(spi_flash_host_inst_t *host) Erase whole flash chip. void (*erase_sector)(spi_flash_host_inst_t *host, uint32_t start_address) Erase a specific sector by its start address. void (*erase_sector)(spi_flash_host_inst_t *host, uint32_t start_address) Erase a specific sector by its start address. void (*erase_block)(spi_flash_host_inst_t *host, uint32_t start_address) Erase a specific block by its start address. void (*erase_block)(spi_flash_host_inst_t *host, uint32_t start_address) Erase a specific block by its start address. esp_err_t (*read_status)(spi_flash_host_inst_t *host, uint8_t *out_sr) Read the status of the flash chip. esp_err_t (*read_status)(spi_flash_host_inst_t *host, uint8_t *out_sr) Read the status of the flash chip. esp_err_t (*set_write_protect)(spi_flash_host_inst_t *host, bool wp) Disable write protection. esp_err_t (*set_write_protect)(spi_flash_host_inst_t *host, bool wp) Disable write protection. void (*program_page)(spi_flash_host_inst_t *host, const void *buffer, uint32_t address, uint32_t length) Program a page of the flash. Check max_write_bytes for the maximum allowed writing length. void (*program_page)(spi_flash_host_inst_t *host, const void *buffer, uint32_t address, uint32_t length) Program a page of the flash. Check max_write_bytes for the maximum allowed writing length. bool (*supports_direct_write)(spi_flash_host_inst_t *host, const void *p) Check whether the SPI host supports direct write. When cache is disabled, SPI1 doesn't support directly write when buffer isn't internal. bool (*supports_direct_write)(spi_flash_host_inst_t *host, const void *p) Check whether the SPI host supports direct write. When cache is disabled, SPI1 doesn't support directly write when buffer isn't internal. int (*write_data_slicer)(spi_flash_host_inst_t *host, uint32_t address, uint32_t len, uint32_t *align_addr, uint32_t page_size) Slicer for write data. The program_page should be called iteratively with the return value of this function. Param address Beginning flash address to write Param len Length request to write Param align_addr Output of the aligned address to write to Param page_size Physical page size of the flash chip Return Length that can be actually written in one program_page call Param address Beginning flash address to write Param len Length request to write Param align_addr Output of the aligned address to write to Param page_size Physical page size of the flash chip Return Length that can be actually written in one program_page call int (*write_data_slicer)(spi_flash_host_inst_t *host, uint32_t address, uint32_t len, uint32_t *align_addr, uint32_t page_size) Slicer for write data. The program_page should be called iteratively with the return value of this function. Param address Beginning flash address to write Param len Length request to write Param align_addr Output of the aligned address to write to Param page_size Physical page size of the flash chip Return Length that can be actually written in one program_page call esp_err_t (*read)(spi_flash_host_inst_t *host, void *buffer, uint32_t address, uint32_t read_len) Read data from the flash. Check max_read_bytes for the maximum allowed reading length. esp_err_t (*read)(spi_flash_host_inst_t *host, void *buffer, uint32_t address, uint32_t read_len) Read data from the flash. Check max_read_bytes for the maximum allowed reading length. bool (*supports_direct_read)(spi_flash_host_inst_t *host, const void *p) Check whether the SPI host supports direct read. When cache is disabled, SPI1 doesn't support directly read when the given buffer isn't internal. bool (*supports_direct_read)(spi_flash_host_inst_t *host, const void *p) Check whether the SPI host supports direct read. When cache is disabled, SPI1 doesn't support directly read when the given buffer isn't internal. int (*read_data_slicer)(spi_flash_host_inst_t *host, uint32_t address, uint32_t len, uint32_t *align_addr, uint32_t page_size) Slicer for read data. The read should be called iteratively with the return value of this function. Param address Beginning flash address to read Param len Length request to read Param align_addr Output of the aligned address to read Param page_size Physical page size of the flash chip Return Length that can be actually read in one read call Param address Beginning flash address to read Param len Length request to read Param align_addr Output of the aligned address to read Param page_size Physical page size of the flash chip Return Length that can be actually read in one read call int (*read_data_slicer)(spi_flash_host_inst_t *host, uint32_t address, uint32_t len, uint32_t *align_addr, uint32_t page_size) Slicer for read data. The read should be called iteratively with the return value of this function. Param address Beginning flash address to read Param len Length request to read Param align_addr Output of the aligned address to read Param page_size Physical page size of the flash chip Return Length that can be actually read in one read call uint32_t (*host_status)(spi_flash_host_inst_t *host) Check the host status, 0:busy, 1:idle, 2:suspended. uint32_t (*host_status)(spi_flash_host_inst_t *host) Check the host status, 0:busy, 1:idle, 2:suspended. esp_err_t (*configure_host_io_mode)(spi_flash_host_inst_t *host, uint32_t command, uint32_t addr_bitlen, int dummy_bitlen_base, esp_flash_io_mode_t io_mode) Configure the host to work at different read mode. Responsible to compensate the timing and set IO mode. esp_err_t (*configure_host_io_mode)(spi_flash_host_inst_t *host, uint32_t command, uint32_t addr_bitlen, int dummy_bitlen_base, esp_flash_io_mode_t io_mode) Configure the host to work at different read mode. Responsible to compensate the timing and set IO mode. void (*poll_cmd_done)(spi_flash_host_inst_t *host) Internal use, poll the HW until the last operation is done. void (*poll_cmd_done)(spi_flash_host_inst_t *host) Internal use, poll the HW until the last operation is done. esp_err_t (*flush_cache)(spi_flash_host_inst_t *host, uint32_t addr, uint32_t size) For some host (SPI1), they are shared with a cache. When the data is modified, the cache needs to be flushed. Left NULL if not supported. esp_err_t (*flush_cache)(spi_flash_host_inst_t *host, uint32_t addr, uint32_t size) For some host (SPI1), they are shared with a cache. When the data is modified, the cache needs to be flushed. Left NULL if not supported. void (*check_suspend)(spi_flash_host_inst_t *host) Suspend check erase/program operation, reserved for ESP32-C3 and ESP32-S3 spi flash ROM IMPL. void (*check_suspend)(spi_flash_host_inst_t *host) Suspend check erase/program operation, reserved for ESP32-C3 and ESP32-S3 spi flash ROM IMPL. void (*resume)(spi_flash_host_inst_t *host) Resume flash from suspend manually void (*resume)(spi_flash_host_inst_t *host) Resume flash from suspend manually void (*suspend)(spi_flash_host_inst_t *host) Set flash in suspend status manually void (*suspend)(spi_flash_host_inst_t *host) Set flash in suspend status manually esp_err_t (*sus_setup)(spi_flash_host_inst_t *host, const spi_flash_sus_cmd_conf *sus_conf) Suspend feature setup for setting cmd and status register mask. esp_err_t (*sus_setup)(spi_flash_host_inst_t *host, const spi_flash_sus_cmd_conf *sus_conf) Suspend feature setup for setting cmd and status register mask. esp_err_t (*dev_config)(spi_flash_host_inst_t *host) Macros SPI_FLASH_TRANS_FLAG_CMD16 Send command of 16 bits. SPI_FLASH_TRANS_FLAG_IGNORE_BASEIO Not applying the basic io mode configuration for this transaction. SPI_FLASH_TRANS_FLAG_BYTE_SWAP Used for DTR mode, to swap the bytes of a pair of rising/falling edge. SPI_FLASH_TRANS_FLAG_PE_CMD Indicates that this transaction is to erase/program flash chip. SPI_FLASH_CONFIG_CONF_BITS OR the io_mode with this mask, to enable the dummy output feature or replace the first several dummy bits into address to meet the requirements of conf bits. (Used in DIO/QIO/OIO mode) SPI_FLASH_OPI_FLAG A flag for flash work in opi mode, the io mode below are opi, above are SPI/QSPI mode. DO NOT use this value in any API. SPI_FLASH_READ_MODE_MIN Slowest io mode supported by ESP32, currently SlowRd. Type Definitions typedef enum esp_flash_speed_s esp_flash_speed_t SPI flash clock speed values, always refer to them by the enum rather than the actual value (more speed may be appended into the list). A strategy to select the maximum allowed speed is to enumerate from the ESP_FLSH_SPEED_MAX-1 or highest frequency supported by your flash, and decrease the speed until the probing success. typedef struct spi_flash_host_driver_s spi_flash_host_driver_t Enumerations enum esp_flash_speed_s SPI flash clock speed values, always refer to them by the enum rather than the actual value (more speed may be appended into the list). A strategy to select the maximum allowed speed is to enumerate from the ESP_FLSH_SPEED_MAX-1 or highest frequency supported by your flash, and decrease the speed until the probing success. Values: enumerator ESP_FLASH_5MHZ The flash runs under 5MHz. enumerator ESP_FLASH_5MHZ The flash runs under 5MHz. enumerator ESP_FLASH_10MHZ The flash runs under 10MHz. enumerator ESP_FLASH_10MHZ The flash runs under 10MHz. enumerator ESP_FLASH_20MHZ The flash runs under 20MHz. enumerator ESP_FLASH_20MHZ The flash runs under 20MHz. enumerator ESP_FLASH_26MHZ The flash runs under 26MHz. enumerator ESP_FLASH_26MHZ The flash runs under 26MHz. enumerator ESP_FLASH_40MHZ The flash runs under 40MHz. enumerator ESP_FLASH_40MHZ The flash runs under 40MHz. enumerator ESP_FLASH_80MHZ The flash runs under 80MHz. enumerator ESP_FLASH_80MHZ The flash runs under 80MHz. enumerator ESP_FLASH_120MHZ The flash runs under 120MHz, 120MHZ can only be used by main flash after timing tuning in system. Do not use this directely in any API. enumerator ESP_FLASH_120MHZ The flash runs under 120MHz, 120MHZ can only be used by main flash after timing tuning in system. Do not use this directely in any API. enumerator ESP_FLASH_SPEED_MAX The maximum frequency supported by the host is ESP_FLASH_SPEED_MAX-1 . enumerator ESP_FLASH_SPEED_MAX The maximum frequency supported by the host is ESP_FLASH_SPEED_MAX-1 . enumerator ESP_FLASH_5MHZ enum esp_flash_io_mode_t Mode used for reading from SPI flash. Values: enumerator SPI_FLASH_SLOWRD Data read using single I/O, some limits on speed. enumerator SPI_FLASH_SLOWRD Data read using single I/O, some limits on speed. enumerator SPI_FLASH_FASTRD Data read using single I/O, no limit on speed. enumerator SPI_FLASH_FASTRD Data read using single I/O, no limit on speed. enumerator SPI_FLASH_DOUT Data read using dual I/O. enumerator SPI_FLASH_DOUT Data read using dual I/O. enumerator SPI_FLASH_DIO Both address & data transferred using dual I/O. enumerator SPI_FLASH_DIO Both address & data transferred using dual I/O. enumerator SPI_FLASH_QOUT Data read using quad I/O. enumerator SPI_FLASH_QOUT Data read using quad I/O. enumerator SPI_FLASH_QIO Both address & data transferred using quad I/O. enumerator SPI_FLASH_QIO Both address & data transferred using quad I/O. enumerator SPI_FLASH_OPI_STR Only support on OPI flash, flash read and write under STR mode. enumerator SPI_FLASH_OPI_STR Only support on OPI flash, flash read and write under STR mode. enumerator SPI_FLASH_OPI_DTR Only support on OPI flash, flash read and write under DTR mode. enumerator SPI_FLASH_OPI_DTR Only support on OPI flash, flash read and write under DTR mode. enumerator SPI_FLASH_READ_MODE_MAX The fastest io mode supported by the host is ESP_FLASH_READ_MODE_MAX-1 . enumerator SPI_FLASH_READ_MODE_MAX The fastest io mode supported by the host is ESP_FLASH_READ_MODE_MAX-1 . enumerator SPI_FLASH_SLOWRD Header File This header file can be included with: #include "hal/esp_flash_err.h" Macros ESP_ERR_FLASH_NOT_INITIALISED esp_flash_chip_t structure not correctly initialised by esp_flash_init(). ESP_ERR_FLASH_UNSUPPORTED_HOST Requested operation isn't supported via this host SPI bus (chip->spi field). ESP_ERR_FLASH_UNSUPPORTED_CHIP Requested operation isn't supported by this model of SPI flash chip. ESP_ERR_FLASH_PROTECTED Write operation failed due to chip's write protection being enabled. Enumerations Header File This header file can be included with: #include "esp_spi_flash_counters.h" This header file is a part of the API provided by the spi_flash component. To declare that your component depends on spi_flash , add the following to your CMakeLists.txt: REQUIRES spi_flash or PRIV_REQUIRES spi_flash Functions void esp_flash_reset_counters(void) Reset SPI flash operation counters. void spi_flash_reset_counters(void) void esp_flash_dump_counters(FILE *stream) Print SPI flash operation counters. void spi_flash_dump_counters(void) const esp_flash_counters_t *esp_flash_get_counters(void) Return current SPI flash operation counters. Returns pointer to the esp_flash_counters_t structure holding values of the operation counters Returns pointer to the esp_flash_counters_t structure holding values of the operation counters const spi_flash_counters_t *spi_flash_get_counters(void) Structures struct esp_flash_counter_t Structure holding statistics for one type of operation struct esp_flash_counters_t Structure for counters of flash actions Public Members esp_flash_counter_t read counters for read action, like esp_flash_read esp_flash_counter_t read counters for read action, like esp_flash_read esp_flash_counter_t write counters for write action, like esp_flash_write esp_flash_counter_t write counters for write action, like esp_flash_write esp_flash_counter_t erase counters for erase action, like esp_flash_erase esp_flash_counter_t erase counters for erase action, like esp_flash_erase esp_flash_counter_t read Type Definitions typedef esp_flash_counter_t spi_flash_counter_t typedef esp_flash_counters_t spi_flash_counters_t API Reference - Flash Encrypt Header File This header file can be included with: #include "esp_flash_encrypt.h" This header file is a part of the API provided by the bootloader_support component. To declare that your component depends on bootloader_support , add the following to your CMakeLists.txt: REQUIRES bootloader_support or PRIV_REQUIRES bootloader_support Functions bool esp_flash_encryption_enabled(void) Is flash encryption currently enabled in hardware? Flash encryption is enabled if the FLASH_CRYPT_CNT efuse has an odd number of bits set. Returns true if flash encryption is enabled. Returns true if flash encryption is enabled. bool esp_flash_encrypt_state(void) Returns the Flash Encryption state and prints it. Returns True - Flash Encryption is enabled False - Flash Encryption is not enabled Returns True - Flash Encryption is enabled False - Flash Encryption is not enabled bool esp_flash_encrypt_initialized_once(void) Checks if the first initialization was done. If the first initialization was done then FLASH_CRYPT_CNT != 0 Returns true - the first initialization was done false - the first initialization was NOT done Returns true - the first initialization was done false - the first initialization was NOT done esp_err_t esp_flash_encrypt_init(void) The first initialization of Flash Encryption key and related eFuses. Returns ESP_OK if all operations succeeded Returns ESP_OK if all operations succeeded esp_err_t esp_flash_encrypt_contents(void) Encrypts flash content. Returns ESP_OK if all operations succeeded Returns ESP_OK if all operations succeeded esp_err_t esp_flash_encrypt_enable(void) Activates Flash encryption on the chip. It burns FLASH_CRYPT_CNT eFuse based on the CONFIG_SECURE_FLASH_ENCRYPTION_MODE_RELEASE option. Returns ESP_OK if all operations succeeded Returns ESP_OK if all operations succeeded bool esp_flash_encrypt_is_write_protected(bool print_error) Returns True if the write protection of FLASH_CRYPT_CNT is set. Parameters print_error -- Print error if it is write protected Returns true - if FLASH_CRYPT_CNT is write protected Parameters print_error -- Print error if it is write protected Returns true - if FLASH_CRYPT_CNT is write protected esp_err_t esp_flash_encrypt_region(uint32_t src_addr, size_t data_length) Encrypt-in-place a block of flash sectors. Note This function resets RTC_WDT between operations with sectors. Parameters src_addr -- Source offset in flash. Should be multiple of 4096 bytes. data_length -- Length of data to encrypt in bytes. Will be rounded up to next multiple of 4096 bytes. src_addr -- Source offset in flash. Should be multiple of 4096 bytes. data_length -- Length of data to encrypt in bytes. Will be rounded up to next multiple of 4096 bytes. src_addr -- Source offset in flash. Should be multiple of 4096 bytes. Returns ESP_OK if all operations succeeded, ESP_ERR_FLASH_OP_FAIL if SPI flash fails, ESP_ERR_FLASH_OP_TIMEOUT if flash times out. Parameters src_addr -- Source offset in flash. Should be multiple of 4096 bytes. data_length -- Length of data to encrypt in bytes. Will be rounded up to next multiple of 4096 bytes. Returns ESP_OK if all operations succeeded, ESP_ERR_FLASH_OP_FAIL if SPI flash fails, ESP_ERR_FLASH_OP_TIMEOUT if flash times out. void esp_flash_write_protect_crypt_cnt(void) Write protect FLASH_CRYPT_CNT. Intended to be called as a part of boot process if flash encryption is enabled but secure boot is not used. This should protect against serial re-flashing of an unauthorised code in absence of secure boot. Note On ESP32 V3 only, write protecting FLASH_CRYPT_CNT will also prevent disabling UART Download Mode. If both are wanted, call esp_efuse_disable_rom_download_mode() before calling this function. esp_flash_enc_mode_t esp_get_flash_encryption_mode(void) Return the flash encryption mode. The API is called during boot process but can also be called by application to check the current flash encryption mode of ESP32 Returns Returns void esp_flash_encryption_init_checks(void) Check the flash encryption mode during startup. Verifies the flash encryption config during startup: Correct any insecure flash encryption settings if hardware Secure Boot is enabled. Log warnings if the efuse config doesn't match the project config in any way Correct any insecure flash encryption settings if hardware Secure Boot is enabled. Log warnings if the efuse config doesn't match the project config in any way Note This function is called automatically during app startup, it doesn't need to be called from the app. Correct any insecure flash encryption settings if hardware Secure Boot is enabled. esp_err_t esp_flash_encryption_enable_secure_features(void) Set all secure eFuse features related to flash encryption. Returns ESP_OK - Successfully ESP_OK - Successfully ESP_OK - Successfully Returns ESP_OK - Successfully bool esp_flash_encryption_cfg_verify_release_mode(void) Returns the verification status for all physical security features of flash encryption in release mode. If the device has flash encryption feature configured in the release mode, then it is highly recommended to call this API in the application startup code. This API verifies the sanity of the eFuse configuration against the release (production) mode of the flash encryption feature. Returns True - all eFuses are configured correctly False - not all eFuses are configured correctly. True - all eFuses are configured correctly False - not all eFuses are configured correctly. True - all eFuses are configured correctly Returns True - all eFuses are configured correctly False - not all eFuses are configured correctly. void esp_flash_encryption_set_release_mode(void) Switches Flash Encryption from "Development" to "Release". If already in "Release" mode, the function will do nothing. If flash encryption efuse is not enabled yet then abort. It burns: "disable encrypt in dl mode" set FLASH_CRYPT_CNT efuse to max "disable encrypt in dl mode" set FLASH_CRYPT_CNT efuse to max "disable encrypt in dl mode"
SPI Flash API Overview The spi_flash component contains API functions related to reading, writing, erasing, and memory mapping for data in the external flash. For higher-level API functions which work with partitions defined in the partition table, see Partitions API Note esp_partition_* APIs are recommended to be used instead of the lower level esp_flash_* API functions when accessing the main SPI flash chip, since they conduct bounds checking and are guaranteed to calculate correct offsets in flash based on the information in the partition table. esp_flash_* functions can still be used directly when accessing an external (secondary) SPI flash chip. Different from the API before ESP-IDF v4.0, the functionality of esp_flash_* APIs is not limited to the "main" SPI flash chip (the same SPI flash chip from which program runs). With different chip pointers, you can access external flash chips connected to not only SPI0/1 but also other SPI buses like SPI2. Note Instead of going through the cache connected to the SPI0 peripheral, most esp_flash_* APIs go through other SPI peripherals like SPI1, SPI2, etc. This makes them able to access not only the main flash, but also external (secondary) flash. However, due to the limitations of the cache, operations through the cache are limited to the main flash. The address range limitation for these operations is also on the cache side. The cache is not able to access external flash chips or address range above its capabilities. These cache operations include: mmap, encrypted read/write, executing code or access to variables in the flash. Note Flash APIs after ESP-IDF v4.0 are no longer atomic. If a write operation occurs during another on-going read operation, and the flash addresses of both operations overlap, the data returned from the read operation may contain both old data and new data (that was updated written by the write operation). Note Encrypted flash operations are only supported with the main flash chip (and not with other flash chips, that is on SPI1 with different CS, or on other SPI buses). Reading through cache is only supported on the main flash, which is determined by the HW. Support for Features of Flash Chips Quad/Dual Mode Chips Features of different flashes are implemented in different ways and thus need special support. The fast/slow read and Dual mode (DOUT/DIO) of almost all flashes with 24-bit address are supported, because they do not need any vendor-specific commands. Quad mode (QIO/QOUT) is supported on the following chip types: ISSI GD MXIC FM Winbond XMC BOYA Note Only when one flash series listed above is supported by ESP32, this flash series is supported by the chip driver by default. You can use Component config > SPI Flash driver > Auto-detect flash chips in menuconfig to enable/disable a flash series. Optional Features There are some features that are not supported by all flash chips, or not supported by all Espressif chips. These features include: 32-bit address flash - usually means that the flash has higher capacity (equal to or larger than 16 MB) that needs longer addresses. Flash unique ID - means that flash supports its unique 64-bit ID. If you want to use these features, please ensure both ESP32 and ALL flash chips in your product support these features. For more details, refer to Optional Features for Flash. You may also customise your own flash chip driver. See Overriding Default Chip Drivers for more details. Initializing a Flash Device To use the esp_flash_* APIs, you need to initialise a flash chip on a certain SPI bus, as shown below: Call spi_bus_initialize()to properly initialize an SPI bus. This function initializes the resources (I/O, DMA, interrupts) shared among devices attached to this bus. Call spi_bus_add_flash_device()to attach the flash device to the bus. This function allocates memory and fills the members for the esp_flash_tstructure. The CS I/O is also initialized here. Call esp_flash_init()to actually communicate with the chip. This also detects the chip type, and influence the following operations. Note Multiple flash chips can be attached to the same bus now. SPI Flash Access API This is the set of API functions for working with data in flash: esp_flash_read()reads data from flash to RAM esp_flash_write()writes data from RAM to flash esp_flash_erase_region()erases specific region of flash esp_flash_erase_chip()erases the whole flash esp_flash_get_chip_size()returns flash chip size, in bytes, as configured in menuconfig Generally, try to avoid using the raw SPI flash functions to the "main" SPI flash chip in favour of partition-specific functions. SPI Flash Size The SPI flash size is configured by writing a field in the software bootloader image header, flashed at offset 0x1000. By default, the SPI flash size is detected by esptool.py when this bootloader is written to flash, and the header is updated with the correct size. Alternatively, it is possible to generate a fixed flash size by setting CONFIG_ESPTOOLPY_FLASHSIZE in the project configuration. If it is necessary to override the configured flash size at runtime, it is possible to set the chip_size member of the g_rom_flashchip structure. This size is used by esp_flash_* functions (in both software & ROM) to check the bounds. Concurrency Constraints for Flash on SPI1 Attention The SPI0/1 bus is shared between the instruction & data cache (for firmware execution) and the SPI1 peripheral (controlled by the drivers including this SPI flash driver). Hence, calling SPI Flash API on SPI1 bus (including the main flash) causes significant influence to the whole system. See Concurrency Constraints for Flash on SPI1 for more details. SPI Flash Encryption It is possible to encrypt the contents of SPI flash and have it transparently decrypted by hardware. Refer to the Flash Encryption documentation for more details. Memory Mapping API ESP32 features memory hardware which allows regions of flash memory to be mapped into instruction and data address spaces. This mapping works only for read operations. It is not possible to modify contents of flash memory by writing to a mapped memory region. Mapping happens in 64 KB pages. Memory mapping hardware can map flash into the data address space and the instruction address space. See the technical reference manual for more details and limitations about memory mapping hardware. Note that some pages are used to map the application itself into memory, so the actual number of available pages may be less than the capability of the hardware. Reading data from flash using a memory mapped region is the only way to decrypt contents of flash when flash encryption is enabled. Decryption is performed at the hardware level. Memory mapping API are declared in spi_flash_mmap.h and esp_partition.h: spi_flash_mmap()maps a region of physical flash addresses into instruction space or data space of the CPU. spi_flash_munmap()unmaps previously mapped region. esp_partition_mmap()maps part of a partition into the instruction space or data space of the CPU. Differences between spi_flash_mmap() and esp_partition_mmap() are as follows: spi_flash_mmap()must be given a 64 KB aligned physical address. esp_partition_mmap()may be given any arbitrary offset within the partition. It adjusts the returned pointer to mapped memory as necessary. Note that since memory mapping happens in pages, it may be possible to read data outside of the partition provided to esp_partition_mmap, regardless of the partition boundary. Note mmap is supported by cache, so it can only be used on main flash. SPI Flash Implementation The esp_flash_t structure holds chip data as well as three important parts of this API: The host driver, which provides the hardware support to access the chip; The chip driver, which provides compatibility service to different chips; The OS functions, provide support of some OS functions (e.g., lock, delay) in different stages (1st/2nd boot, or the app). Host Driver The host driver relies on an interface ( spi_flash_host_driver_t) defined in the spi_flash_types.h (in the hal/include/hal folder). This interface provides some common functions to communicate with the chip. In other files of the SPI HAL, some of these functions are implemented with existing ESP32 memory-spi functionalities. However, due to the speed limitations of ESP32, the HAL layer cannot provide high-speed implementations to some reading commands (so the support for it was dropped). The files ( memspi_host_driver.h and .c) implement the high-speed version of these commands with the common_command function provided in the HAL, and wrap these functions as spi_flash_host_driver_t for upper layer to use. You can also implement your own host driver, even with the GPIO. As long as all the functions in the spi_flash_host_driver_t are implemented, the esp_flash API can access the flash regardless of the low-level hardware. Chip Driver The chip driver, defined in spi_flash_chip_driver.h, wraps basic functions provided by the host driver for the API layer to use. Some operations need some commands to be sent first, or read some status afterwards. Some chips need different commands or values, or need special communication ways. There is a type of chip called generic chip which stands for common chips. Other special chip drivers can be developed on the base of the generic chip. The chip driver relies on the host driver. OS Functions Currently the OS function layer provides entries of a lock and delay. The lock (see SPI Bus Lock) is used to resolve the conflicts among the access of devices on the same SPI bus, and the SPI Flash chip access. E.g. On SPI1 bus, the cache (used to fetch the data (code) in the Flash and PSRAM) should be disabled when the flash chip on the SPI0/1 is being accessed. On the other buses, the flash driver needs to disable the ISR registered by SPI Master driver, to avoid conflicts. Some devices of SPI Master driver may require to use the bus monopolized during a period (especially when the device does not have a CS wire, or the wire is controlled by software like SDSPI driver). The delay is used by some long operations which requires the master to wait or polling periodically. The top API wraps these the chip driver and OS functions into an entire component, and also provides some argument checking. OS functions can also help to avoid a watchdog timeout when erasing large flash areas. During this time, the CPU is occupied with the flash erasing task. This stops other tasks from being executed. Among these tasks is the idle task to feed the watchdog timer (WDT). If the configuration option CONFIG_ESP_TASK_WDT_PANIC is selected and the flash operation time is longer than the watchdog timeout period, the system will reboot. It is pretty hard to totally eliminate this risk, because the erasing time varies with different flash chips, making it hard to be compatible in flash drivers. Therefore, users need to pay attention to it. Please use the following guidelines: It is recommended to enable the CONFIG_SPI_FLASH_YIELD_DURING_ERASE option to allow the scheduler to re-schedule during erasing flash memory. Besides, following parameters can also be used. Increase CONFIG_SPI_FLASH_ERASE_YIELD_TICKS or decrease CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS in menuconfig. You can also increase CONFIG_ESP_TASK_WDT_TIMEOUT_S in menuconfig for a larger watchdog timeout period. However, with larger watchdog timeout period, previously detected timeouts may no longer be detected. Please be aware of the consequences of enabling the CONFIG_ESP_TASK_WDT_PANIC option when doing long-running SPI flash operations which triggers the panic handler when it times out. However, this option can also help dealing with unexpected exceptions in your application. Please decide whether this is needed to be enabled according to actual condition. During your development, please carefully review the actual flash operation according to the specific requirements and time limits on erasing flash memory of your projects. Always allow reasonable redundancy based on your specific product requirements when configuring the flash erasing timeout threshold, thus improving the reliability of your product. Implementation Details In order to perform some flash operations, it is necessary to make sure that both CPUs are not running any code from flash for the duration of the flash operation: In a single-core setup, the SDK needs to disable interrupts or scheduler before performing the flash operation. In a dual-core setup, the SDK needs to make sure that both CPUs are not running any code from flash. When SPI flash API is called on CPU A (can be PRO or APP), start the spi_flash_op_block_func function on CPU B using the esp_ipc_call API. This API wakes up a high priority task on CPU B and tells it to execute a given function, in this case, spi_flash_op_block_func. This function disables cache on CPU B and signals that the cache is disabled by setting the s_flash_op_can_start flag. Then the task on CPU A disables cache as well and proceeds to execute flash operation. While a flash operation is running, interrupts can still run on CPUs A and B. It is assumed that all interrupt code is placed into RAM. Once the interrupt allocation API is added, a flag should be added to request the interrupt to be disabled for the duration of a flash operations. Once the flash operation is complete, the function on CPU A sets another flag, s_flash_op_complete, to let the task on CPU B know that it can re-enable cache and release the CPU. Then the function on CPU A re-enables the cache on CPU A as well and returns control to the calling code. Additionally, all API functions are protected with a mutex ( s_flash_op_mutex). In a single core environment (CONFIG_FREERTOS_UNICORE enabled), you need to disable both caches, so that no inter-CPU communication can take place. API Reference - SPI Flash Header File This header file can be included with: #include "esp_flash_spi_init.h" This header file is a part of the API provided by the spi_flashcomponent. To declare that your component depends on spi_flash, add the following to your CMakeLists.txt: REQUIRES spi_flash or PRIV_REQUIRES spi_flash Functions - esp_err_t spi_bus_add_flash_device(esp_flash_t **out_chip, const esp_flash_spi_device_config_t *config) Add a SPI Flash device onto the SPI bus. The bus should be already initialized by spi_bus_initialization. - Parameters out_chip -- Pointer to hold the initialized chip. config -- Configuration of the chips to initialize. - - Returns ESP_ERR_INVALID_ARG: out_chip is NULL, or some field in the config is invalid. ESP_ERR_NO_MEM: failed to allocate memory for the chip structures. ESP_OK: success. - - esp_err_t spi_bus_remove_flash_device(esp_flash_t *chip) Remove a SPI Flash device from the SPI bus. - Parameters chip -- The flash device to remove. - Returns ESP_ERR_INVALID_ARG: The chip is invalid. ESP_OK: success. - Structures - struct esp_flash_spi_device_config_t Configurations for the SPI Flash to init. Public Members - spi_host_device_t host_id Bus to use. - int cs_io_num GPIO pin to output the CS signal. - esp_flash_io_mode_t io_mode IO mode to read from the Flash. - enum esp_flash_speed_s speed Speed of the Flash clock. Replaced by freq_mhz. - int input_delay_ns Input delay of the data pins, in ns. Set to 0 if unknown. - int cs_id CS line ID, ignored when not host_idis not SPI1_HOST, or CONFIG_SPI_FLASH_SHARE_SPI1_BUSis enabled. In this case, the CS line used is automatically assigned by the SPI bus lock. - int freq_mhz The frequency of flash chip(MHZ) - spi_host_device_t host_id Header File This header file can be included with: #include "esp_flash.h" This header file is a part of the API provided by the spi_flashcomponent. To declare that your component depends on spi_flash, add the following to your CMakeLists.txt: REQUIRES spi_flash or PRIV_REQUIRES spi_flash Functions - esp_err_t esp_flash_init(esp_flash_t *chip) Initialise SPI flash chip interface. This function must be called before any other API functions are called for this chip. Note Only the hostand read_modefields of the chip structure must be initialised before this function is called. Other fields may be auto-detected if left set to zero or NULL. Note If the chip->drv pointer is NULL, chip chip_drv will be auto-detected based on its manufacturer & product IDs. See esp_flash_registered_flash_driverspointer for details of this process. - Parameters chip -- Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted. - Returns ESP_OK on success, or a flash error code if initialisation fails. - bool esp_flash_chip_driver_initialized(const esp_flash_t *chip) Check if appropriate chip driver is set. - Parameters chip -- Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted. - Returns true if set, otherwise false. - esp_err_t esp_flash_read_id(esp_flash_t *chip, uint32_t *out_id) Read flash ID via the common "RDID" SPI flash command. ID is a 24-bit value. Lower 16 bits of 'id' are the chip ID, upper 8 bits are the manufacturer ID. - Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() out_id -- [out] Pointer to receive ID value. - - Returns ESP_OK on success, or a flash error code if operation failed. - esp_err_t esp_flash_get_size(esp_flash_t *chip, uint32_t *out_size) Detect flash size based on flash ID. Note 1. Most flash chips use a common format for flash ID, where the lower 4 bits specify the size as a power of 2. If the manufacturer doesn't follow this convention, the size may be incorrectly detected. The out_size returned only stands for The out_size stands for the size in the binary image header. If you want to get the real size of the chip, please call esp_flash_get_physical_sizeinstead. - Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() out_size -- [out] Detected size in bytes, standing for the size in the binary image header. - - Returns ESP_OK on success, or a flash error code if operation failed. - - esp_err_t esp_flash_get_physical_size(esp_flash_t *chip, uint32_t *flash_size) Detect flash size based on flash ID. Note Most flash chips use a common format for flash ID, where the lower 4 bits specify the size as a power of 2. If the manufacturer doesn't follow this convention, the size may be incorrectly detected. - Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() flash_size -- [out] Detected size in bytes. - - Returns ESP_OK on success, or a flash error code if operation failed. - esp_err_t esp_flash_read_unique_chip_id(esp_flash_t *chip, uint64_t *out_id) Read flash unique ID via the common "RDUID" SPI flash command. ID is a 64-bit value. Note This is an optional feature, which is not supported on all flash chips. READ PROGRAMMING GUIDE FIRST! - Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init(). out_id -- [out] Pointer to receive unique ID value. - - Returns ESP_OK on success, or a flash error code if operation failed. ESP_ERR_NOT_SUPPORTED if the chip doesn't support read id. - - esp_err_t esp_flash_erase_chip(esp_flash_t *chip) Erase flash chip contents. - Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() - Returns ESP_OK on success, ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is indicated by WREN = 1 after the command is sent. ESP_ERR_NOT_ALLOWED if a read-only partition is present. Other flash error code if operation failed. - - esp_err_t esp_flash_erase_region(esp_flash_t *chip, uint32_t start, uint32_t len) Erase a region of the flash chip. Sector size is specifyed in chip->drv->sector_size field (typically 4096 bytes.) ESP_ERR_INVALID_ARG will be returned if the start & length are not a multiple of this size. Erase is performed using block (multi-sector) erases where possible (block size is specified in chip->drv->block_erase_size field, typically 65536 bytes). Remaining sectors are erased using individual sector erase commands. - Parameters chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() start -- Address to start erasing flash. Must be sector aligned. len -- Length of region to erase. Must also be sector aligned. - - Returns ESP_OK on success, ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is indicated by WREN = 1 after the command is sent. ESP_ERR_NOT_ALLOWED if the address range (start – start + len) overlaps with a read-only partition address space Other flash error code if operation failed. - - esp_err_t esp_flash_get_chip_write_protect(esp_flash_t *chip, bool *write_protected) Read if the entire chip is write protected. Note A correct result for this flag depends on the SPI flash chip model and chip_drv in use (via the 'chip->drv' field). - Parameters chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() write_protected -- [out] Pointer to boolean, set to the value of the write protect flag. - - Returns ESP_OK on success, or a flash error code if operation failed. - esp_err_t esp_flash_set_chip_write_protect(esp_flash_t *chip, bool write_protect) Set write protection for the SPI flash chip. Some SPI flash chips may require a power cycle before write protect status can be cleared. Otherwise, write protection can be removed via a follow-up call to this function. Note Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the 'chip->drv' field). - Parameters chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() write_protect -- Boolean value for the write protect flag - - Returns ESP_OK on success, or a flash error code if operation failed. - esp_err_t esp_flash_get_protectable_regions(const esp_flash_t *chip, const esp_flash_region_t **out_regions, uint32_t *out_num_regions) Read the list of individually protectable regions of this SPI flash chip. Note Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the 'chip->drv' field). - Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() out_regions -- [out] Pointer to receive a pointer to the array of protectable regions of the chip. out_num_regions -- [out] Pointer to an integer receiving the count of protectable regions in the array returned in 'regions'. - - Returns ESP_OK on success, or a flash error code if operation failed. - esp_err_t esp_flash_get_protected_region(esp_flash_t *chip, const esp_flash_region_t *region, bool *out_protected) Detect if a region of the SPI flash chip is protected. Note It is possible for this result to be false and write operations to still fail, if protection is enabled for the entire chip. Note Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the 'chip->drv' field). - Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() region -- Pointer to a struct describing a protected region. This must match one of the regions returned from esp_flash_get_protectable_regions(...). out_protected -- [out] Pointer to a flag which is set based on the protected status for this region. - - Returns ESP_OK on success, or a flash error code if operation failed. - esp_err_t esp_flash_set_protected_region(esp_flash_t *chip, const esp_flash_region_t *region, bool protect) Update the protected status for a region of the SPI flash chip. Note It is possible for the region protection flag to be cleared and write operations to still fail, if protection is enabled for the entire chip. Note Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the 'chip->drv' field). - Parameters chip -- Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() region -- Pointer to a struct describing a protected region. This must match one of the regions returned from esp_flash_get_protectable_regions(...). protect -- Write protection flag to set. - - Returns ESP_OK on success, or a flash error code if operation failed. - esp_err_t esp_flash_read(esp_flash_t *chip, void *buffer, uint32_t address, uint32_t length) Read data from the SPI flash chip. There are no alignment constraints on buffer, address or length. Note If on-chip flash encryption is used, this function returns raw (ie encrypted) data. Use the flash cache to transparently decrypt data. - Parameters chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() buffer -- Pointer to a buffer where the data will be read. To get better performance, this should be in the DRAM and word aligned. address -- Address on flash to read from. Must be less than chip->size field. length -- Length (in bytes) of data to read. - - Returns ESP_OK: success ESP_ERR_NO_MEM: Buffer is in external PSRAM which cannot be concurrently accessed, and a temporary internal buffer could not be allocated. or a flash error code if operation failed. - - esp_err_t esp_flash_write(esp_flash_t *chip, const void *buffer, uint32_t address, uint32_t length) Write data to the SPI flash chip. There are no alignment constraints on buffer, address or length. - Parameters chip -- Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted. Must have been successfully initialised via esp_flash_init() address -- Address on flash to write to. Must be previously erased (SPI NOR flash can only write bits 1->0). buffer -- Pointer to a buffer with the data to write. To get better performance, this should be in the DRAM and word aligned. length -- Length (in bytes) of data to write. - - Returns ESP_OK on success ESP_FAIL, bad write, this will be detected only when CONFIG_SPI_FLASH_VERIFY_WRITE is enabled ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is indicated by WREN = 1 after the command is sent. ESP_ERR_NOT_ALLOWED if the address range (address – address + length) overlaps with a read-only partition address space Other flash error code if operation failed. - - esp_err_t esp_flash_write_encrypted(esp_flash_t *chip, uint32_t address, const void *buffer, uint32_t length) Encrypted and write data to the SPI flash chip using on-chip hardware flash encryption. Note Both address & length must be 16 byte aligned, as this is the encryption block size - Parameters chip -- Pointer to identify flash chip. Must be NULL (the main flash chip). For other chips, encrypted write is not supported. address -- Address on flash to write to. 16 byte aligned. Must be previously erased (SPI NOR flash can only write bits 1->0). buffer -- Pointer to a buffer with the data to write. length -- Length (in bytes) of data to write. 16 byte aligned. - - Returns ESP_OK: on success ESP_FAIL: bad write, this will be detected only when CONFIG_SPI_FLASH_VERIFY_WRITE is enabled ESP_ERR_NOT_SUPPORTED: encrypted write not supported for this chip. ESP_ERR_INVALID_ARG: Either the address, buffer or length is invalid. ESP_ERR_NOT_ALLOWED if the address range (address – address + length) overlaps with a read-only partition address space - - esp_err_t esp_flash_read_encrypted(esp_flash_t *chip, uint32_t address, void *out_buffer, uint32_t length) Read and decrypt data from the SPI flash chip using on-chip hardware flash encryption. - Parameters chip -- Pointer to identify flash chip. Must be NULL (the main flash chip). For other chips, encrypted read is not supported. address -- Address on flash to read from. out_buffer -- Pointer to a buffer for the data to read to. length -- Length (in bytes) of data to read. - - Returns ESP_OK: on success ESP_ERR_NOT_SUPPORTED: encrypted read not supported for this chip. - - static inline bool esp_flash_is_quad_mode(const esp_flash_t *chip) Returns true if chip is configured for Quad I/O or Quad Fast Read. - Parameters chip -- Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted. - Returns true if flash works in quad mode, otherwise false Structures - struct esp_flash_region_t Structure for describing a region of flash. - struct esp_flash_os_functions_t OS-level integration hooks for accessing flash chips inside a running OS. It's in the public header because some instances should be allocated statically in the startup code. May be updated according to hardware version and new flash chip feature requirements, shouldn't be treated as public API. For advanced developers, you may replace some of them with your implementations at your own risk. Public Members - esp_err_t (*start)(void *arg) Called before commencing any flash operation. Does not need to be recursive (ie is called at most once for each call to 'end'). - esp_err_t (*region_protected)(void *arg, size_t start_addr, size_t size) Called before any erase/write operations to check whether the region is limited by the OS - esp_err_t (*delay_us)(void *arg, uint32_t us) Delay for at least 'us' microseconds. Called in between 'start' and 'end'. - void *(*get_temp_buffer)(void *arg, size_t reqest_size, size_t *out_size) Called for get temp buffer when buffer from application cannot be directly read into/write from. - void (*release_temp_buffer)(void *arg, void *temp_buf) Called for release temp buffer. - esp_err_t (*check_yield)(void *arg, uint32_t chip_status, uint32_t *out_request) Yield to other tasks. Called during erase operations. - Return ESP_OK means yield needs to be called (got an event to handle), while ESP_ERR_TIMEOUT means skip yield. - esp_err_t (*yield)(void *arg, uint32_t *out_status) Yield to other tasks. Called during erase operations. - int64_t (*get_system_time)(void *arg) Called for get system time. - void (*set_flash_op_status)(uint32_t op_status) Call to set flash operation status - esp_err_t (*start)(void *arg) - struct esp_flash_t Structure to describe a SPI flash chip connected to the system. Structure must be initialized before use (passed to esp_flash_init()). It's in the public header because some instances should be allocated statically in the startup code. May be updated according to hardware version and new flash chip feature requirements, shouldn't be treated as public API. For advanced developers, you may replace some of them with your implementations at your own risk. Public Members - spi_flash_host_inst_t *host Pointer to hardware-specific "host_driver" structure. Must be initialized before used. - const spi_flash_chip_t *chip_drv Pointer to chip-model-specific "adapter" structure. If NULL, will be detected during initialisation. - const esp_flash_os_functions_t *os_func Pointer to os-specific hook structure. Call esp_flash_init_os_functions()to setup this field, after the host is properly initialized. - void *os_func_data Pointer to argument for os-specific hooks. Left NULL and will be initialized with os_func. - esp_flash_io_mode_t read_mode Configured SPI flash read mode. Set before esp_flash_initis called. - uint32_t size Size of SPI flash in bytes. If 0, size will be detected during initialisation. Note: this stands for the size in the binary image header. If you want to get the flash physical size, please call esp_flash_get_physical_size. - uint32_t chip_id Detected chip id. - uint32_t busy This flag is used to verify chip's status. - uint32_t hpm_dummy_ena This flag is used to verify whether flash works under HPM status. - uint32_t reserved_flags reserved. - spi_flash_host_inst_t *host Macros - SPI_FLASH_YIELD_REQ_YIELD - SPI_FLASH_YIELD_REQ_SUSPEND - SPI_FLASH_YIELD_STA_RESUME - SPI_FLASH_OS_IS_ERASING_STATUS_FLAG Type Definitions - typedef struct spi_flash_chip_t spi_flash_chip_t Header File This header file can be included with: #include "spi_flash_mmap.h" This header file is a part of the API provided by the spi_flashcomponent. To declare that your component depends on spi_flash, add the following to your CMakeLists.txt: REQUIRES spi_flash or PRIV_REQUIRES spi_flash Functions - esp_err_t spi_flash_mmap(size_t src_addr, size_t size, spi_flash_mmap_memory_t memory, const void **out_ptr, spi_flash_mmap_handle_t *out_handle) Map region of flash memory into data or instruction address space. This function allocates sufficient number of 64kB MMU pages and configures them to map the requested region of flash memory into the address space. It may reuse MMU pages which already provide the required mapping. As with any allocator, if mmap/munmap are heavily used then the address space may become fragmented. To troubleshoot issues with page allocation, use spi_flash_mmap_dump() function. - Parameters src_addr -- Physical address in flash where requested region starts. This address must be aligned to 64kB boundary (SPI_FLASH_MMU_PAGE_SIZE) size -- Size of region to be mapped. This size will be rounded up to a 64kB boundary memory -- Address space where the region should be mapped (data or instruction) out_ptr -- [out] Output, pointer to the mapped memory region out_handle -- [out] Output, handle which should be used for spi_flash_munmap call - - Returns ESP_OK on success, ESP_ERR_NO_MEM if pages can not be allocated - esp_err_t spi_flash_mmap_pages(const int *pages, size_t page_count, spi_flash_mmap_memory_t memory, const void **out_ptr, spi_flash_mmap_handle_t *out_handle) Map sequences of pages of flash memory into data or instruction address space. This function allocates sufficient number of 64kB MMU pages and configures them to map the indicated pages of flash memory contiguously into address space. In this respect, it works in a similar way as spi_flash_mmap() but it allows mapping a (maybe non-contiguous) set of pages into a contiguous region of memory. - Parameters pages -- An array of numbers indicating the 64kB pages in flash to be mapped contiguously into memory. These indicate the indexes of the 64kB pages, not the byte-size addresses as used in other functions. Array must be located in internal memory. page_count -- Number of entries in the pages array memory -- Address space where the region should be mapped (instruction or data) out_ptr -- [out] Output, pointer to the mapped memory region out_handle -- [out] Output, handle which should be used for spi_flash_munmap call - - Returns ESP_OK on success ESP_ERR_NO_MEM if pages can not be allocated ESP_ERR_INVALID_ARG if pagecount is zero or pages array is not in internal memory - - void spi_flash_munmap(spi_flash_mmap_handle_t handle) Release region previously obtained using spi_flash_mmap. Note Calling this function will not necessarily unmap memory region. Region will only be unmapped when there are no other handles which reference this region. In case of partially overlapping regions it is possible that memory will be unmapped partially. - Parameters handle -- Handle obtained from spi_flash_mmap - void spi_flash_mmap_dump(void) Display information about mapped regions. This function lists handles obtained using spi_flash_mmap, along with range of pages allocated to each handle. It also lists all non-zero entries of MMU table and corresponding reference counts. - uint32_t spi_flash_mmap_get_free_pages(spi_flash_mmap_memory_t memory) get free pages number which can be mmap This function will return number of free pages available in mmu table. This could be useful before calling actual spi_flash_mmap (maps flash range to DCache or ICache memory) to check if there is sufficient space available for mapping. - Parameters memory -- memory type of MMU table free page - Returns number of free pages which can be mmaped - size_t spi_flash_cache2phys(const void *cached) Given a memory address where flash is mapped, return the corresponding physical flash offset. Cache address does not have have been assigned via spi_flash_mmap(), any address in memory mapped flash space can be looked up. - Parameters cached -- Pointer to flashed cached memory. - Returns SPI_FLASH_CACHE2PHYS_FAIL If cache address is outside flash cache region, or the address is not mapped. Otherwise, returns physical offset in flash - - const void *spi_flash_phys2cache(size_t phys_offs, spi_flash_mmap_memory_t memory) Given a physical offset in flash, return the address where it is mapped in the memory space. Physical address does not have to have been assigned via spi_flash_mmap(), any address in flash can be looked up. Note Only the first matching cache address is returned. If MMU flash cache table is configured so multiple entries point to the same physical address, there may be more than one cache address corresponding to that physical address. It is also possible for a single physical address to be mapped to both the IROM and DROM regions. Note This function doesn't impose any alignment constraints, but if memory argument is SPI_FLASH_MMAP_INST and phys_offs is not 4-byte aligned, then reading from the returned pointer will result in a crash. - Parameters phys_offs -- Physical offset in flash memory to look up. memory -- Address space type to look up a flash cache address mapping for (instruction or data) - - Returns NULL if the physical address is invalid or not mapped to flash cache of the specified memory type. Cached memory address (in IROM or DROM space) corresponding to phys_offs. - Macros - ESP_ERR_FLASH_OP_FAIL This file contains spi_flash_mmap_xxAPIs, mainly for doing memory mapping to an SPI0-connected external Flash, as well as some helper functions to convert between virtual and physical address - ESP_ERR_FLASH_OP_TIMEOUT - SPI_FLASH_SEC_SIZE SPI Flash sector size - SPI_FLASH_MMU_PAGE_SIZE Flash cache MMU mapping page size - SPI_FLASH_CACHE2PHYS_FAIL Type Definitions - typedef uint32_t spi_flash_mmap_handle_t Opaque handle for memory region obtained from spi_flash_mmap. Enumerations Header File This header file can be included with: #include "hal/spi_flash_types.h" Structures - struct spi_flash_trans_t Definition of a common transaction. Also holds the return value. Public Members - uint8_t reserved Reserved, must be 0. - uint8_t mosi_len Output data length, in bytes. - uint8_t miso_len Input data length, in bytes. - uint8_t address_bitlen Length of address in bits, set to 0 if command does not need an address. - uint32_t address Address to perform operation on. - const uint8_t *mosi_data Output data to salve. - uint8_t *miso_data [out] Input data from slave, little endian - uint32_t flags Flags for this transaction. Set to 0 for now. - uint16_t command Command to send. - uint8_t dummy_bitlen Basic dummy bits to use. - uint32_t io_mode Flash working mode when SPI_FLASH_IGNORE_BASEIOis specified. - uint8_t reserved - struct spi_flash_sus_cmd_conf Configuration structure for the flash chip suspend feature. - struct spi_flash_encryption_t Structure for flash encryption operations. Public Members - void (*flash_encryption_enable)(void) Enable the flash encryption. - void (*flash_encryption_disable)(void) Disable the flash encryption. - void (*flash_encryption_data_prepare)(uint32_t address, const uint32_t *buffer, uint32_t size) Prepare flash encryption before operation. Note address and buffer must be 8-word aligned. - Param address The destination address in flash for the write operation. - Param buffer Data for programming - Param size Size to program. - void (*flash_encryption_done)(void) flash data encryption operation is done. - void (*flash_encryption_destroy)(void) Destroy encrypted result - bool (*flash_encryption_check)(uint32_t address, uint32_t length) Check if is qualified to encrypt the buffer - Param address the address of written flash partition. - Param length Buffer size. - void (*flash_encryption_enable)(void) - struct spi_flash_host_inst_t SPI Flash Host driver instance Public Members - const struct spi_flash_host_driver_s *driver Pointer to the implementation function table. - const struct spi_flash_host_driver_s *driver - struct spi_flash_host_driver_s Host driver configuration and context structure. Public Members - esp_err_t (*dev_config)(spi_flash_host_inst_t *host) Configure the device-related register before transactions. This saves some time to re-configure those registers when we send continuously - esp_err_t (*common_command)(spi_flash_host_inst_t *host, spi_flash_trans_t *t) Send an user-defined spi transaction to the device. - esp_err_t (*read_id)(spi_flash_host_inst_t *host, uint32_t *id) Read flash ID. - void (*erase_chip)(spi_flash_host_inst_t *host) Erase whole flash chip. - void (*erase_sector)(spi_flash_host_inst_t *host, uint32_t start_address) Erase a specific sector by its start address. - void (*erase_block)(spi_flash_host_inst_t *host, uint32_t start_address) Erase a specific block by its start address. - esp_err_t (*read_status)(spi_flash_host_inst_t *host, uint8_t *out_sr) Read the status of the flash chip. - esp_err_t (*set_write_protect)(spi_flash_host_inst_t *host, bool wp) Disable write protection. - void (*program_page)(spi_flash_host_inst_t *host, const void *buffer, uint32_t address, uint32_t length) Program a page of the flash. Check max_write_bytesfor the maximum allowed writing length. - bool (*supports_direct_write)(spi_flash_host_inst_t *host, const void *p) Check whether the SPI host supports direct write. When cache is disabled, SPI1 doesn't support directly write when buffer isn't internal. - int (*write_data_slicer)(spi_flash_host_inst_t *host, uint32_t address, uint32_t len, uint32_t *align_addr, uint32_t page_size) Slicer for write data. The program_pageshould be called iteratively with the return value of this function. - Param address Beginning flash address to write - Param len Length request to write - Param align_addr Output of the aligned address to write to - Param page_size Physical page size of the flash chip - Return Length that can be actually written in one program_pagecall - esp_err_t (*read)(spi_flash_host_inst_t *host, void *buffer, uint32_t address, uint32_t read_len) Read data from the flash. Check max_read_bytesfor the maximum allowed reading length. - bool (*supports_direct_read)(spi_flash_host_inst_t *host, const void *p) Check whether the SPI host supports direct read. When cache is disabled, SPI1 doesn't support directly read when the given buffer isn't internal. - int (*read_data_slicer)(spi_flash_host_inst_t *host, uint32_t address, uint32_t len, uint32_t *align_addr, uint32_t page_size) Slicer for read data. The readshould be called iteratively with the return value of this function. - Param address Beginning flash address to read - Param len Length request to read - Param align_addr Output of the aligned address to read - Param page_size Physical page size of the flash chip - Return Length that can be actually read in one readcall - uint32_t (*host_status)(spi_flash_host_inst_t *host) Check the host status, 0:busy, 1:idle, 2:suspended. - esp_err_t (*configure_host_io_mode)(spi_flash_host_inst_t *host, uint32_t command, uint32_t addr_bitlen, int dummy_bitlen_base, esp_flash_io_mode_t io_mode) Configure the host to work at different read mode. Responsible to compensate the timing and set IO mode. - void (*poll_cmd_done)(spi_flash_host_inst_t *host) Internal use, poll the HW until the last operation is done. - esp_err_t (*flush_cache)(spi_flash_host_inst_t *host, uint32_t addr, uint32_t size) For some host (SPI1), they are shared with a cache. When the data is modified, the cache needs to be flushed. Left NULL if not supported. - void (*check_suspend)(spi_flash_host_inst_t *host) Suspend check erase/program operation, reserved for ESP32-C3 and ESP32-S3 spi flash ROM IMPL. - void (*resume)(spi_flash_host_inst_t *host) Resume flash from suspend manually - void (*suspend)(spi_flash_host_inst_t *host) Set flash in suspend status manually - esp_err_t (*sus_setup)(spi_flash_host_inst_t *host, const spi_flash_sus_cmd_conf *sus_conf) Suspend feature setup for setting cmd and status register mask. - esp_err_t (*dev_config)(spi_flash_host_inst_t *host) Macros - SPI_FLASH_TRANS_FLAG_CMD16 Send command of 16 bits. - SPI_FLASH_TRANS_FLAG_IGNORE_BASEIO Not applying the basic io mode configuration for this transaction. - SPI_FLASH_TRANS_FLAG_BYTE_SWAP Used for DTR mode, to swap the bytes of a pair of rising/falling edge. - SPI_FLASH_TRANS_FLAG_PE_CMD Indicates that this transaction is to erase/program flash chip. - SPI_FLASH_CONFIG_CONF_BITS OR the io_mode with this mask, to enable the dummy output feature or replace the first several dummy bits into address to meet the requirements of conf bits. (Used in DIO/QIO/OIO mode) - SPI_FLASH_OPI_FLAG A flag for flash work in opi mode, the io mode below are opi, above are SPI/QSPI mode. DO NOT use this value in any API. - SPI_FLASH_READ_MODE_MIN Slowest io mode supported by ESP32, currently SlowRd. Type Definitions - typedef enum esp_flash_speed_s esp_flash_speed_t SPI flash clock speed values, always refer to them by the enum rather than the actual value (more speed may be appended into the list). A strategy to select the maximum allowed speed is to enumerate from the ESP_FLSH_SPEED_MAX-1or highest frequency supported by your flash, and decrease the speed until the probing success. - typedef struct spi_flash_host_driver_s spi_flash_host_driver_t Enumerations - enum esp_flash_speed_s SPI flash clock speed values, always refer to them by the enum rather than the actual value (more speed may be appended into the list). A strategy to select the maximum allowed speed is to enumerate from the ESP_FLSH_SPEED_MAX-1or highest frequency supported by your flash, and decrease the speed until the probing success. Values: - enumerator ESP_FLASH_5MHZ The flash runs under 5MHz. - enumerator ESP_FLASH_10MHZ The flash runs under 10MHz. - enumerator ESP_FLASH_20MHZ The flash runs under 20MHz. - enumerator ESP_FLASH_26MHZ The flash runs under 26MHz. - enumerator ESP_FLASH_40MHZ The flash runs under 40MHz. - enumerator ESP_FLASH_80MHZ The flash runs under 80MHz. - enumerator ESP_FLASH_120MHZ The flash runs under 120MHz, 120MHZ can only be used by main flash after timing tuning in system. Do not use this directely in any API. - enumerator ESP_FLASH_SPEED_MAX The maximum frequency supported by the host is ESP_FLASH_SPEED_MAX-1. - enumerator ESP_FLASH_5MHZ - enum esp_flash_io_mode_t Mode used for reading from SPI flash. Values: - enumerator SPI_FLASH_SLOWRD Data read using single I/O, some limits on speed. - enumerator SPI_FLASH_FASTRD Data read using single I/O, no limit on speed. - enumerator SPI_FLASH_DOUT Data read using dual I/O. - enumerator SPI_FLASH_DIO Both address & data transferred using dual I/O. - enumerator SPI_FLASH_QOUT Data read using quad I/O. - enumerator SPI_FLASH_QIO Both address & data transferred using quad I/O. - enumerator SPI_FLASH_OPI_STR Only support on OPI flash, flash read and write under STR mode. - enumerator SPI_FLASH_OPI_DTR Only support on OPI flash, flash read and write under DTR mode. - enumerator SPI_FLASH_READ_MODE_MAX The fastest io mode supported by the host is ESP_FLASH_READ_MODE_MAX-1. - enumerator SPI_FLASH_SLOWRD Header File This header file can be included with: #include "hal/esp_flash_err.h" Macros - ESP_ERR_FLASH_NOT_INITIALISED esp_flash_chip_t structure not correctly initialised by esp_flash_init(). - ESP_ERR_FLASH_UNSUPPORTED_HOST Requested operation isn't supported via this host SPI bus (chip->spi field). - ESP_ERR_FLASH_UNSUPPORTED_CHIP Requested operation isn't supported by this model of SPI flash chip. - ESP_ERR_FLASH_PROTECTED Write operation failed due to chip's write protection being enabled. Enumerations Header File This header file can be included with: #include "esp_spi_flash_counters.h" This header file is a part of the API provided by the spi_flashcomponent. To declare that your component depends on spi_flash, add the following to your CMakeLists.txt: REQUIRES spi_flash or PRIV_REQUIRES spi_flash Functions - void esp_flash_reset_counters(void) Reset SPI flash operation counters. - void spi_flash_reset_counters(void) - void esp_flash_dump_counters(FILE *stream) Print SPI flash operation counters. - void spi_flash_dump_counters(void) - const esp_flash_counters_t *esp_flash_get_counters(void) Return current SPI flash operation counters. - Returns pointer to the esp_flash_counters_t structure holding values of the operation counters - const spi_flash_counters_t *spi_flash_get_counters(void) Structures - struct esp_flash_counter_t Structure holding statistics for one type of operation - struct esp_flash_counters_t Structure for counters of flash actions Public Members - esp_flash_counter_t read counters for read action, like esp_flash_read - esp_flash_counter_t write counters for write action, like esp_flash_write - esp_flash_counter_t erase counters for erase action, like esp_flash_erase - esp_flash_counter_t read Type Definitions - typedef esp_flash_counter_t spi_flash_counter_t - typedef esp_flash_counters_t spi_flash_counters_t API Reference - Flash Encrypt Header File This header file can be included with: #include "esp_flash_encrypt.h" This header file is a part of the API provided by the bootloader_supportcomponent. To declare that your component depends on bootloader_support, add the following to your CMakeLists.txt: REQUIRES bootloader_support or PRIV_REQUIRES bootloader_support Functions - bool esp_flash_encryption_enabled(void) Is flash encryption currently enabled in hardware? Flash encryption is enabled if the FLASH_CRYPT_CNT efuse has an odd number of bits set. - Returns true if flash encryption is enabled. - bool esp_flash_encrypt_state(void) Returns the Flash Encryption state and prints it. - Returns True - Flash Encryption is enabled False - Flash Encryption is not enabled - bool esp_flash_encrypt_initialized_once(void) Checks if the first initialization was done. If the first initialization was done then FLASH_CRYPT_CNT != 0 - Returns true - the first initialization was done false - the first initialization was NOT done - esp_err_t esp_flash_encrypt_init(void) The first initialization of Flash Encryption key and related eFuses. - Returns ESP_OK if all operations succeeded - esp_err_t esp_flash_encrypt_contents(void) Encrypts flash content. - Returns ESP_OK if all operations succeeded - esp_err_t esp_flash_encrypt_enable(void) Activates Flash encryption on the chip. It burns FLASH_CRYPT_CNT eFuse based on the CONFIG_SECURE_FLASH_ENCRYPTION_MODE_RELEASE option. - Returns ESP_OK if all operations succeeded - bool esp_flash_encrypt_is_write_protected(bool print_error) Returns True if the write protection of FLASH_CRYPT_CNT is set. - Parameters print_error -- Print error if it is write protected - Returns true - if FLASH_CRYPT_CNT is write protected - esp_err_t esp_flash_encrypt_region(uint32_t src_addr, size_t data_length) Encrypt-in-place a block of flash sectors. Note This function resets RTC_WDT between operations with sectors. - Parameters src_addr -- Source offset in flash. Should be multiple of 4096 bytes. data_length -- Length of data to encrypt in bytes. Will be rounded up to next multiple of 4096 bytes. - - Returns ESP_OK if all operations succeeded, ESP_ERR_FLASH_OP_FAIL if SPI flash fails, ESP_ERR_FLASH_OP_TIMEOUT if flash times out. - void esp_flash_write_protect_crypt_cnt(void) Write protect FLASH_CRYPT_CNT. Intended to be called as a part of boot process if flash encryption is enabled but secure boot is not used. This should protect against serial re-flashing of an unauthorised code in absence of secure boot. Note On ESP32 V3 only, write protecting FLASH_CRYPT_CNT will also prevent disabling UART Download Mode. If both are wanted, call esp_efuse_disable_rom_download_mode() before calling this function. - esp_flash_enc_mode_t esp_get_flash_encryption_mode(void) Return the flash encryption mode. The API is called during boot process but can also be called by application to check the current flash encryption mode of ESP32 - Returns - - void esp_flash_encryption_init_checks(void) Check the flash encryption mode during startup. Verifies the flash encryption config during startup: Correct any insecure flash encryption settings if hardware Secure Boot is enabled. Log warnings if the efuse config doesn't match the project config in any way Note This function is called automatically during app startup, it doesn't need to be called from the app. - - esp_err_t esp_flash_encryption_enable_secure_features(void) Set all secure eFuse features related to flash encryption. - Returns ESP_OK - Successfully - - bool esp_flash_encryption_cfg_verify_release_mode(void) Returns the verification status for all physical security features of flash encryption in release mode. If the device has flash encryption feature configured in the release mode, then it is highly recommended to call this API in the application startup code. This API verifies the sanity of the eFuse configuration against the release (production) mode of the flash encryption feature. - Returns True - all eFuses are configured correctly False - not all eFuses are configured correctly. - - void esp_flash_encryption_set_release_mode(void) Switches Flash Encryption from "Development" to "Release". If already in "Release" mode, the function will do nothing. If flash encryption efuse is not enabled yet then abort. It burns: "disable encrypt in dl mode" set FLASH_CRYPT_CNT efuse to max -
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/spi_flash/index.html
ESP-IDF Programming Guide v5.2.1 documentation
null
SPI Master Driver
null
espressif.com
2016-01-01
be4afbdea372b389
null
null
SPI Master Driver SPI Master driver is a program that controls ESP32's General Purpose SPI (GP-SPI) peripheral(s) when it functions as a master. Note SPI1 is not a GP-SPI. SPI Master driver also supports SPI1 but with quite a few limitations, see Notes on Using the SPI Master Driver on SPI1 Bus. For more hardware information about the GP-SPI peripheral(s), see ESP32 Technical Reference Manual > SPI Controller [PDF]. Terminology The terms used in relation to the SPI Master driver are given in the table below. Term Definition Host The SPI controller peripheral inside ESP32 initiates SPI transmissions over the bus and acts as an SPI Master. Device SPI slave Device. An SPI bus may be connected to one or more Devices. Each Device shares the MOSI, MISO, and SCLK signals but is only active on the bus when the Host asserts the Device's individual CS line. Bus A signal bus, common to all Devices connected to one Host. In general, a bus includes the following lines: MISO, MOSI, SCLK, one or more CS lines, and, optionally, QUADWP and QUADHD. So Devices are connected to the same lines, with the exception that each Device has its own CS line. Several Devices can also share one CS line if connected in a daisy-chain manner. MOSI Master Out, Slave In, a.k.a. D. Data transmission from a Host to Device. Also data0 signal in Octal/OPI mode. MISO Master In, Slave Out, a.k.a. Q. Data transmission from a Device to Host. Also data1 signal in Octal/OPI mode. SCLK Serial Clock. The oscillating signal generated by a Host keeps the transmission of data bits in sync. CS Chip Select. Allows a Host to select individual Device(s) connected to the bus in order to send or receive data. QUADWP Write Protect signal. Used for 4-bit (qio/qout) transactions. Also for the data2 signal in Octal/OPI mode. QUADHD Hold signal. Used for 4-bit (qio/qout) transactions. Also for the data3 signal in Octal/OPI mode. DATA4 Data4 signal in Octal/OPI mode. DATA5 Data5 signal in Octal/OPI mode. DATA6 Data6 signal in Octal/OPI mode. DATA7 Data7 signal in Octal/OPI mode. Assertion The action of activating a line. De-assertion The action of returning the line back to inactive (back to idle) status. Transaction One instance of a Host asserting a CS line, transferring data to and from a Device, and de-asserting the CS line. Transactions are atomic, which means they can never be interrupted by another transaction. Launch Edge Edge of the clock at which the source register launches the signal onto the line. Latch Edge Edge of the clock at which the destination register latches in the signal. Driver Features The SPI Master driver governs the communications between Hosts and Devices. The driver supports the following features: Multi-threaded environments Transparent handling of DMA transfers while reading and writing data Automatic time-division multiplexing of data coming from different Devices on the same signal bus, see SPI Bus Lock. Warning The SPI Master driver allows multiple Devices to be connected on a same SPI bus (sharing a single ESP32 SPI peripheral). As long as each Device is accessed by only one task, the driver is thread-safe. However, if multiple tasks try to access the same SPI Device, the driver is not thread-safe. In this case, it is recommended to either: Refactor your application so that each SPI peripheral is only accessed by a single task at a time. You can use spi_bus_config_t::isr_cpu_id to register the SPI ISR to the same core as SPI peripheral-related tasks to ensure thread safety. Add a mutex lock around the shared Device using xSemaphoreCreateMutex . SPI Transactions An SPI bus transaction consists of five phases which can be found in the table below. Any of these phases can be skipped. Phase Description Command In this phase, a command (0-16 bit) is written to the bus by the Host. Address In this phase, an address (0-64 bit) is transmitted over the bus by the Host. Dummy This phase is configurable and is used to meet the timing requirements. Write Host sends data to a Device. This data follows the optional command and address phases and is indistinguishable from them at the electrical level. Read Device sends data to its Host. The attributes of a transaction are determined by the bus configuration structure spi_bus_config_t , Device configuration structure spi_device_interface_config_t , and transaction configuration structure spi_transaction_t . An SPI Host can send full-duplex transactions, during which the Read and Write phases occur simultaneously. The total transaction length is determined by the sum of the following members: While the member spi_transaction_t::rxlength only determines the length of data received into the buffer. In half-duplex transactions, the Read and Write phases are not simultaneous (one direction at a time). The lengths of the Write and Read phases are determined by spi_transaction_t::length and spi_transaction_t::rxlength respectively. The Command and Address phases are optional, as not every SPI Device requires a command and/or address. This is reflected in the Device's configuration: if spi_device_interface_config_t::command_bits and/or spi_device_interface_config_t::address_bits are set to zero, no Command or Address phase will occur. The Read and Write phases can also be optional, as not every transaction requires both writing and reading data. If spi_transaction_t::rx_buffer is NULL and SPI_TRANS_USE_RXDATA is not set, the Read phase is skipped. If spi_transaction_t::tx_buffer is NULL and SPI_TRANS_USE_TXDATA is not set, the Write phase is skipped. The driver supports two types of transactions: interrupt transactions and polling transactions. The programmer can choose to use a different transaction type per Device. If your Device requires both transaction types, see Notes on Sending Mixed Transactions to the Same Device. Interrupt Transactions Interrupt transactions blocks the transaction routine until the transaction completes, thus allowing the CPU to run other tasks. An application task can queue multiple transactions, and the driver automatically handles them one by one in the interrupt service routine (ISR). It allows the task to switch to other procedures until all the transactions are complete. Polling Transactions Polling transactions do not use interrupts. The routine keeps polling the SPI Host's status bit until the transaction is finished. All the tasks that use interrupt transactions can be blocked by the queue. At this point, they need to wait for the ISR to run twice before the transaction is finished. Polling transactions save time otherwise spent on queue handling and context switching, which results in smaller transaction duration. The disadvantage is that the CPU is busy while these transactions are in progress. The spi_device_polling_end() routine needs an overhead of at least 1 µs to unblock other tasks when the transaction is finished. It is strongly recommended to wrap a series of polling transactions using the functions spi_device_acquire_bus() and spi_device_release_bus() to avoid the overhead. For more information, see Bus Acquiring. Transaction Line Mode Supported line modes for ESP32 are listed as follows, to make use of these modes, set the member flags in the struct spi_transaction_t as shown in the Transaction Flag column. If you want to check if corresponding IO pins are set or not, set the member flags in the spi_bus_config_t as shown in the Bus IO setting Flag column. Mode name Command Line Width Address Line Width Data Line Width Transaction Flag Bus IO Setting Flag Normal SPI 1 1 1 0 0 Dual Output 1 1 2 SPI_TRANS_MODE_DIO SPICOMMON_BUSFLAG_DUAL Dual I/O 1 2 2 SPI_TRANS_MODE_DIO SPI_TRANS_MULTILINE_ADDR SPICOMMON_BUSFLAG_DUAL Quad Output 1 1 4 SPI_TRANS_MODE_QIO SPICOMMON_BUSFLAG_QUAD Quad I/O 1 4 4 SPI_TRANS_MODE_QIO SPI_TRANS_MULTILINE_ADDR SPICOMMON_BUSFLAG_QUAD Command and Address Phases During the Command and Address phases, the members spi_transaction_t::cmd and spi_transaction_t::addr are sent to the bus, nothing is read at this time. The default lengths of the Command and Address phases are set in spi_device_interface_config_t by calling spi_bus_add_device() . If the flags SPI_TRANS_VARIABLE_CMD and SPI_TRANS_VARIABLE_ADDR in the member spi_transaction_t::flags are not set, the driver automatically sets the length of these phases to default values during Device initialization. If the lengths of the Command and Address phases need to be variable, declare the struct spi_transaction_ext_t , set the flags SPI_TRANS_VARIABLE_CMD and/or SPI_TRANS_VARIABLE_ADDR in the member spi_transaction_ext_t::base and configure the rest of base as usual. Then the length of each phase will be equal to spi_transaction_ext_t::command_bits and spi_transaction_ext_t::address_bits set in the struct spi_transaction_ext_t . If the Command and Address phase need to have the same number of lines as the data phase, you need to set SPI_TRANS_MULTILINE_CMD and/or SPI_TRANS_MULTILINE_ADDR to the flags member in the struct spi_transaction_t . Also see Transaction Line Mode. Write and Read Phases Normally, the data that needs to be transferred to or from a Device is read from or written to a chunk of memory indicated by the members spi_transaction_t::rx_buffer and spi_transaction_t::tx_buffer . If DMA is enabled for transfers, the buffers are required to be: Allocated in DMA-capable internal memory (MALLOC_CAP_DMA), see DMA-Capable Memory. 32-bit aligned (starting from a 32-bit boundary and having a length of multiples of 4 bytes). If these requirements are not satisfied, the transaction efficiency will be affected due to the allocation and copying of temporary buffers. If using more than one data line to transmit, please set SPI_DEVICE_HALFDUPLEX flag for the member flags in the struct spi_device_interface_config_t . And the member flags in the struct spi_transaction_t should be set as described in Transaction Line Mode. Note Half-duplex transactions with both Read and Write phases are not supported when using DMA. For details and workarounds, see Known Issues. Bus Acquiring Sometimes you might want to send SPI transactions exclusively and continuously so that it takes as little time as possible. For this, you can use bus acquiring, which helps to suspend transactions (both polling or interrupt) to other Devices until the bus is released. To acquire and release a bus, use the functions spi_device_acquire_bus() and spi_device_release_bus() . Driver Usage Initialize an SPI bus by calling the function spi_bus_initialize() . Make sure to set the correct I/O pins in the struct spi_bus_config_t . Set the signals that are not needed to -1 . Register a Device connected to the bus with the driver by calling the function spi_bus_add_device() . Make sure to configure any timing requirements the Device might need with the parameter dev_config . You should now have obtained the Device's handle which will be used when sending a transaction to it. To interact with the Device, fill one or more spi_transaction_t structs with any transaction parameters required. Then send the structs either using a polling transaction or an interrupt transaction: Interrupt Either queue all transactions by calling the function spi_device_queue_trans() and, at a later time, query the result using the function spi_device_get_trans_result() , or handle all requests synchronously by feeding them into spi_device_transmit() . Interrupt Either queue all transactions by calling the function spi_device_queue_trans() and, at a later time, query the result using the function spi_device_get_trans_result() , or handle all requests synchronously by feeding them into spi_device_transmit() . Polling Call the function spi_device_polling_transmit() to send polling transactions. Alternatively, if you want to insert something in between, send the transactions by using spi_device_polling_start() and spi_device_polling_end() . Polling Call the function spi_device_polling_transmit() to send polling transactions. Alternatively, if you want to insert something in between, send the transactions by using spi_device_polling_start() and spi_device_polling_end() . Interrupt Either queue all transactions by calling the function spi_device_queue_trans() and, at a later time, query the result using the function spi_device_get_trans_result() , or handle all requests synchronously by feeding them into spi_device_transmit() . Polling Call the function spi_device_polling_transmit() to send polling transactions. Alternatively, if you want to insert something in between, send the transactions by using spi_device_polling_start() and spi_device_polling_end() . Interrupt Either queue all transactions by calling the function spi_device_queue_trans() and, at a later time, query the result using the function spi_device_get_trans_result() , or handle all requests synchronously by feeding them into spi_device_transmit() . (Optional) To perform back-to-back transactions with a Device, call the function spi_device_acquire_bus() before sending transactions and spi_device_release_bus() after the transactions have been sent. (Optional) To remove a certain Device from the bus, call spi_bus_remove_device() with the Device handle as an argument. (Optional) To remove the driver from the bus, make sure no more devices are attached and call spi_bus_free() . The example code for the SPI Master driver can be found in the peripherals/spi_master directory of ESP-IDF examples. Transactions with Data Not Exceeding 32 Bits When the transaction data size is equal to or less than 32 bits, it will be sub-optimal to allocate a buffer for the data. The data can be directly stored in the transaction struct instead. For transmitted data, it can be achieved by using the spi_transaction_t::tx_data member and setting the SPI_TRANS_USE_TXDATA flag on the transmission. For received data, use spi_transaction_t::rx_data and set SPI_TRANS_USE_RXDATA . In both cases, do not touch the spi_transaction_t::tx_buffer or spi_transaction_t::rx_buffer members, because they use the same memory locations as spi_transaction_t::tx_data and spi_transaction_t::rx_data . Transactions with Integers Other than uint8_t  uint8_t  An SPI Host reads and writes data into memory byte by byte. By default, data is sent with the most significant bit (MSB) first, as LSB is first used in rare cases. If a value of fewer than 8 bits needs to be sent, the bits should be written into memory in the MSB first manner. For example, if 0b00010 needs to be sent, it should be written into a uint8_t variable, and the length for reading should be set to 5 bits. The Device will still receive 8 bits with 3 additional "random" bits, so the reading must be performed correctly. On top of that, ESP32 is a little-endian chip, which means that the least significant byte of uint16_t and uint32_t variables is stored at the smallest address. Hence, if uint16_t is stored in memory, bits [7:0] are sent first, followed by bits [15:8]. For cases when the data to be transmitted has a size differing from uint8_t arrays, the following macros can be used to transform data to the format that can be sent by the SPI driver directly: SPI_SWAP_DATA_TX for data to be transmitted SPI_SWAP_DATA_RX for data received Notes on Sending Mixed Transactions to the Same Device To reduce coding complexity, send only one type of transaction (interrupt or polling) to one Device. However, you still can send both interrupt and polling transactions alternately. The notes below explain how to do this. The polling transactions should be initiated only after all the polling and interrupt transactions are finished. Since an unfinished polling transaction blocks other transactions, please do not forget to call the function spi_device_polling_end() after spi_device_polling_start() to allow other transactions or to allow other Devices to use the bus. Remember that if there is no need to switch to other tasks during your polling transaction, you can initiate a transaction with spi_device_polling_transmit() so that it will be ended automatically. In-flight polling transactions are disturbed by the ISR operation to accommodate interrupt transactions. Always make sure that all the interrupt transactions sent to the ISR are finished before you call spi_device_polling_start() . To do that, you can keep calling spi_device_get_trans_result() until all the transactions are returned. To have better control of the calling sequence of functions, send mixed transactions to the same Device only within a single task. Notes on Using the SPI Master Driver on SPI1 Bus Note Though the SPI Bus Lock feature makes it possible to use SPI Master driver on the SPI1 bus, it is still tricky and needs a lot of special treatment. It is a feature for advanced developers. To use SPI Master driver on SPI1 bus, you have to take care of two problems: The code and data should be in the internal memory when the driver is operating on SPI1 bus. SPI1 bus is shared among Devices and the cache for data (code) in the flash as well as the PSRAM. The cache should be disabled when other drivers are operating on the SPI1 bus. Hence the data (code) in the flash as well as the PSRAM cannot be fetched while the driver acquires the SPI1 bus by: Explicit bus acquiring between spi_device_acquire_bus() and spi_device_release_bus() . Implicit bus acquiring between spi_device_polling_start() and spi_device_polling_end() (or inside spi_device_polling_transmit() ). Explicit bus acquiring between spi_device_acquire_bus() and spi_device_release_bus() . Implicit bus acquiring between spi_device_polling_start() and spi_device_polling_end() (or inside spi_device_polling_transmit() ). During the time above, all other tasks and most ISRs will be disabled (see IRAM-Safe Interrupt Handlers). Application code and data used by the current task should be placed in internal memory (DRAM or IRAM), or already in the ROM. Access to external memory (flash code, const data in the flash, and static/heap data in the PSRAM) will cause a Cache disabled but cached memory region accessed exception. For differences between IRAM, DRAM, and flash cache, please refer to the application memory layout documentation. To place functions into the IRAM, you can either: Add IRAM_ATTR (include esp_attr.h ) to the function like: IRAM_ATTR void foo(void) { } Please note that when a function is inlined, it will follow its caller's segment, and the attribute will not take effect. You may need to use NOLINE_ATTR to avoid this. Please also note that the compiler may transform some code into a lookup table in the const data, so noflash_text is not safe. Use the noflash placement in the linker.lf . See more in Linker Script Generation. Please note that the compiler may transform some code into a lookup table in the const data, so noflash_text is not safe. Add IRAM_ATTR (include esp_attr.h ) to the function like: IRAM_ATTR void foo(void) { } Please note that when a function is inlined, it will follow its caller's segment, and the attribute will not take effect. You may need to use NOLINE_ATTR to avoid this. Please also note that the compiler may transform some code into a lookup table in the const data, so noflash_text is not safe. Use the noflash placement in the linker.lf . See more in Linker Script Generation. Please note that the compiler may transform some code into a lookup table in the const data, so noflash_text is not safe. Please do take care that the optimization level may affect the compiler behavior of inline, or transform some code into a lookup table in the const data, etc. To place data into the DRAM, you can either: Add DRAM_ATTR (include esp_attr.h ) to the data definition like: DRAM_ATTR int g_foo = 3; Use the noflash placement in the linker.lf. See more in Linker Script Generation. Add DRAM_ATTR (include esp_attr.h ) to the data definition like: DRAM_ATTR int g_foo = 3; Use the noflash placement in the linker.lf. See more in Linker Script Generation. Explicit bus acquiring between spi_device_acquire_bus() and spi_device_release_bus() . Please also see the example peripherals/spi_master/hd_eeprom. GPIO Matrix and IO_MUX Most of ESP32's peripheral signals have a direct connection to their dedicated IO_MUX pins. However, the signals can also be routed to any other available pins using the less direct GPIO matrix. If at least one signal is routed through the GPIO matrix, then all signals will be routed through it. The GPIO matrix introduces flexibility of routing but also brings the following disadvantages: Increases the input delay of the MISO signal, which makes MISO setup time violations more likely. If SPI needs to operate at high speeds, use dedicated IO_MUX pins. Allows signals with clock frequencies only up to 40 MHz, as opposed to 80 MHz if IO_MUX pins are used. Note For more details about the influence of the MISO input delay on the maximum clock frequency, see Timing Considerations. The IO_MUX pins for SPI buses are given below. Pin Name SPI 2 (GPIO Number) SPI 3 (GPIO Number) CS0 1 15 5 SCLK 14 18 MISO 12 19 MOSI 13 23 QUADWP 2 22 QUADHD 4 21 1 Only the first Device attached to the bus can use the CS0 pin. Transfer Speed Considerations There are three factors limiting the transfer speed: Transaction interval SPI clock frequency Cache miss of SPI functions, including callbacks The main parameter that determines the transfer speed for large transactions is clock frequency. For multiple small transactions, the transfer speed is mostly determined by the length of transaction intervals. Transaction Duration Transaction duration includes setting up SPI peripheral registers, copying data to FIFOs or setting up DMA links, and the time for SPI transactions. Interrupt transactions allow appending extra overhead to accommodate the cost of FreeRTOS queues and the time needed for switching between tasks and the ISR. For interrupt transactions, the CPU can switch to other tasks when a transaction is in progress. This saves CPU time but increases the transaction duration. See Interrupt Transactions. For polling transactions, it does not block the task but allows to do polling when the transaction is in progress. For more information, see Polling Transactions. If DMA is enabled, setting up the linked list requires about 2 µs per transaction. When a master is transferring data, it automatically reads the data from the linked list. If DMA is not enabled, the CPU has to write and read each byte from the FIFO by itself. Usually, this is faster than 2 µs, but the transaction length is limited to 64 bytes for both write and read. The typical transaction duration for one byte of data is given below. Interrupt Transaction via DMA: 28 µs. Interrupt Transaction via CPU: 25 µs. Polling Transaction via DMA: 10 µs. Polling Transaction via CPU: 8 µs. Note that these data are tested with CONFIG_SPI_MASTER_ISR_IN_IRAM enabled. SPI transaction related code are placed in the internal memory. If this option is turned off (for example, for internal memory optimization), the transaction duration may be affected. SPI Clock Frequency The clock source of the GPSPI peripherals can be selected by setting spi_device_handle_t::cfg::clock_source . You can refer to spi_clock_source_t to know the supported clock sources. By default driver sets spi_device_handle_t::cfg::clock_source to SPI_CLK_SRC_DEFAULT . This usually stands for the highest frequency among GPSPI clock sources. Its value is different among chips. The actual clock frequency of a Device may not be exactly equal to the number you set, it is re-calculated by the driver to the nearest hardware-compatible number, and not larger than the clock frequency of the clock source. You can call spi_device_get_actual_freq() to know the actual frequency computed by the driver. The theoretical maximum transfer speed of the Write or Read phase can be calculated according to the table below: Line Width of Write/Read phase Speed (Bps) 1-Line SPI Frequency / 8 2-Line SPI Frequency / 4 4-Line SPI Frequency / 2 The transfer speed calculation of other phases (Command, Address, Dummy) is similar. If the clock frequency is too high, the use of some functions might be limited. See Timing Considerations. Cache Missing The default config puts only the ISR into the IRAM. Other SPI-related functions, including the driver itself and the callback, might suffer from cache misses and need to wait until the code is read from flash. Select CONFIG_SPI_MASTER_IN_IRAM to put the whole SPI driver into IRAM and put the entire callback(s) and its callee functions into IRAM to prevent cache missing. Note SPI driver implementation is based on FreeRTOS APIs, to use CONFIG_SPI_MASTER_IN_IRAM, you should not enable CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH. For an interrupt transaction, the overall cost is 20+8n/Fspi[MHz] [µs] for n bytes transferred in one transaction. Hence, the transferring speed is: n/(20+8n/Fspi). An example of transferring speed at 8 MHz clock speed is given in the following table. Frequency (MHz) Transaction Interval (µs) Transaction Length (bytes) Total Time (µs) Total Speed (KBps) 8 25 1 26 38.5 8 25 8 33 242.4 8 25 16 41 490.2 8 25 64 89 719.1 8 25 128 153 836.6 When a transaction length is short, the cost of the transaction interval is high. If possible, try to squash several short transactions into one transaction to achieve a higher transfer speed. Please note that the ISR is disabled during flash operation by default. To keep sending transactions during flash operations, enable CONFIG_SPI_MASTER_ISR_IN_IRAM and set ESP_INTR_FLAG_IRAM in the member spi_bus_config_t::intr_flags . In this case, all the transactions queued before starting flash operations are handled by the ISR in parallel. Also note that the callback of each Device and their callee functions should be in IRAM, or your callback will crash due to cache missing. For more details, see IRAM-Safe Interrupt Handlers. Timing Considerations As shown in the figure below, there is a delay on the MISO line after the SCLK launch edge and before the signal is latched by the internal register. As a result, the MISO pin setup time is the limiting factor for the SPI clock speed. When the delay is too long, the setup slack is < 0, which means the setup timing requirement is violated and the reading might be incorrect. The maximum allowed frequency is dependent on: spi_device_interface_config_t::input_delay_ns - maximum data valid time on the MISO bus after a clock cycle on SCLK starts If the IO_MUX pin or the GPIO Matrix is used When the GPIO matrix is used, the maximum allowed frequency is reduced to about 33 ~ 77% in comparison to the existing input delay. To retain a higher frequency, you have to use the IO_MUX pins or the dummy bit workaround. You can obtain the maximum reading frequency of the master by using the function spi_get_freq_limit() . Dummy bit workaround: Dummy clocks, during which the Host does not read data, can be inserted before the Read phase begins. The Device still sees the dummy clocks and sends out data, but the Host does not read until the Read phase comes. This compensates for the lack of the MISO setup time required by the Host and allows the Host to do reading at a higher frequency. In the ideal case, if the Device is so fast that the input delay is shorter than an APB clock cycle - 12.5 ns - the maximum frequency at which the Host can read (or read and write) in different conditions is as follows: Frequency Limit (MHz) Frequency Limit (MHz) Dummy Bits Used by Driver Comments GPIO Matrix IO_MUX Pins 26.6 80 No 40 -- Yes Half-duplex, no DMA allowed If the Host only writes data, the dummy bit workaround and the frequency check can be disabled by setting the bit SPI_DEVICE_NO_DUMMY in the member spi_device_interface_config_t::flags . When disabled, the output frequency can be 80 MHz, even if the GPIO matrix is used. spi_device_interface_config_t::flags The SPI Master driver still works even if the spi_device_interface_config_t::input_delay_ns in the structure spi_device_interface_config_t is set to 0. However, setting an accurate value helps to: Calculate the frequency limit for full-duplex transactions Compensate the timing correctly with dummy bits for half-duplex transactions You can approximate the maximum data valid time after the launch edge of SPI clocks by checking the statistics in the AC characteristics chapter of your Device's specification or measure the time using an oscilloscope or logic analyzer. Please note that the actual PCB layout design and excessive loads may increase the input delay. It means that non-optimal wiring and/or a load capacitor on the bus will most likely lead to input delay values exceeding the values given in the Device specification or measured while the bus is floating. Some typical delay values are shown in the following table. These data are retrieved when the slave Device is on a different physical chip. Device Input Delay (ns) Ideal Device 0 ESP32 slave using IO_MUX 50 ESP32 slave using GPIO_MATRIX 75 The MISO path delay (valid time) consists of a slave's input delay plus the master's GPIO matrix delay. The delay determines the above frequency limit for full-duplex transfers. Once exceeding, full-duplex transfers will not work as well as the half-duplex transactions that use dummy bits. The frequency limit is: Freq limit [MHz] = 80 / (floor(MISO delay[ns]/12.5) + 1) The figure below shows the relationship between frequency limit and input delay. Two extra APB clock cycle periods should be added to the MISO delay if the master uses the GPIO matrix. Corresponding frequency limits for different Devices with different input delay times are shown in the table below. When the master is IO_MUX (0 ns): Input Delay (ns) MISO Path Delay (ns) Freq. Limit (MHz) 0 0 80 50 50 16 75 75 11.43 When the master is GPIO_MATRIX (25 ns): Input Delay (ns) MISO Path Delay (ns) Freq. Limit (MHz) 0 25 26.67 50 75 11.43 75 100 8.89 Known Issues Half-duplex transactions are not compatible with DMA when both the Write and Read phases are used. If such transactions are required, you have to use one of the alternative solutions: Use full-duplex transactions instead. Disable DMA by setting the bus initialization function's last parameter to 0 as follows: ret=spi_bus_initialize(VSPI_HOST, &buscfg, 0); Disable DMA by setting the bus initialization function's last parameter to 0 as follows: ret=spi_bus_initialize(VSPI_HOST, &buscfg, 0); Use full-duplex transactions instead. Disable DMA by setting the bus initialization function's last parameter to 0 as follows: ret=spi_bus_initialize(VSPI_HOST, &buscfg, 0); This can prohibit you from transmitting and receiving data longer than 64 bytes. 3. Try using the command and address fields to replace the Write phase. Use full-duplex transactions instead. Full-duplex transactions are not compatible with the dummy bit workaround, hence the frequency is limited. See dummy bit speed-up workaround. dummy_bits in spi_device_interface_config_t and spi_transaction_ext_t are not available when SPI Read and Write phases are both enabled (regardless of full duplex or half duplex mode). cs_ena_pretrans is not compatible with the Command and Address phases of full-duplex transactions. Application Example The code example for using the SPI master half duplex mode to read/write an AT93C46D EEPROM (8-bit mode) can be found in the peripherals/spi_master/hd_eeprom directory of ESP-IDF examples. The code example for using the SPI master full duplex mode to drive a SPI_LCD (e.g. ST7789V or ILI9341) can be found in the peripherals/spi_master/lcd directory of ESP-IDF examples. API Reference - SPI Common Header File This header file can be included with: #include "hal/spi_types.h" Structures struct spi_line_mode_t Line mode of SPI transaction phases: CMD, ADDR, DOUT/DIN. Type Definitions typedef soc_periph_spi_clk_src_t spi_clock_source_t Type of SPI clock source. Enumerations enum spi_host_device_t Enum with the three SPI peripherals that are software-accessible in it. Values: enumerator SPI1_HOST SPI1. enumerator SPI1_HOST SPI1. enumerator SPI2_HOST SPI2. enumerator SPI2_HOST SPI2. enumerator SPI3_HOST SPI3. enumerator SPI3_HOST SPI3. enumerator SPI_HOST_MAX invalid host value enumerator SPI_HOST_MAX invalid host value enumerator SPI1_HOST enum spi_event_t SPI Events. Values: enumerator SPI_EV_BUF_TX The buffer has sent data to master. enumerator SPI_EV_BUF_TX The buffer has sent data to master. enumerator SPI_EV_BUF_RX The buffer has received data from master. enumerator SPI_EV_BUF_RX The buffer has received data from master. enumerator SPI_EV_SEND_DMA_READY Slave has loaded its TX data buffer to the hardware (DMA). enumerator SPI_EV_SEND_DMA_READY Slave has loaded its TX data buffer to the hardware (DMA). enumerator SPI_EV_SEND Master has received certain number of the data, the number is determined by Master. enumerator SPI_EV_SEND Master has received certain number of the data, the number is determined by Master. enumerator SPI_EV_RECV_DMA_READY Slave has loaded its RX data buffer to the hardware (DMA). enumerator SPI_EV_RECV_DMA_READY Slave has loaded its RX data buffer to the hardware (DMA). enumerator SPI_EV_RECV Slave has received certain number of data from master, the number is determined by Master. enumerator SPI_EV_RECV Slave has received certain number of data from master, the number is determined by Master. enumerator SPI_EV_CMD9 Received CMD9 from master. enumerator SPI_EV_CMD9 Received CMD9 from master. enumerator SPI_EV_CMDA Received CMDA from master. enumerator SPI_EV_CMDA Received CMDA from master. enumerator SPI_EV_TRANS A transaction has done. enumerator SPI_EV_TRANS A transaction has done. enumerator SPI_EV_BUF_TX enum spi_command_t SPI command. Values: enumerator SPI_CMD_HD_WRBUF enumerator SPI_CMD_HD_WRBUF enumerator SPI_CMD_HD_RDBUF enumerator SPI_CMD_HD_RDBUF enumerator SPI_CMD_HD_WRDMA enumerator SPI_CMD_HD_WRDMA enumerator SPI_CMD_HD_RDDMA enumerator SPI_CMD_HD_RDDMA enumerator SPI_CMD_HD_SEG_END enumerator SPI_CMD_HD_SEG_END enumerator SPI_CMD_HD_EN_QPI enumerator SPI_CMD_HD_EN_QPI enumerator SPI_CMD_HD_WR_END enumerator SPI_CMD_HD_WR_END enumerator SPI_CMD_HD_INT0 enumerator SPI_CMD_HD_INT0 enumerator SPI_CMD_HD_INT1 enumerator SPI_CMD_HD_INT1 enumerator SPI_CMD_HD_INT2 enumerator SPI_CMD_HD_INT2 enumerator SPI_CMD_HD_WRBUF Header File This header file can be included with: #include "driver/spi_common.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t spi_bus_initialize(spi_host_device_t host_id, const spi_bus_config_t *bus_config, spi_dma_chan_t dma_chan) Initialize a SPI bus. Warning SPI0/1 is not supported Warning If a DMA channel is selected, any transmit and receive buffer used should be allocated in DMA-capable memory. Warning The ISR of SPI is always executed on the core which calls this function. Never starve the ISR on this core or the SPI transactions will not be handled. Parameters host_id -- SPI peripheral that controls this bus bus_config -- Pointer to a spi_bus_config_t struct specifying how the host should be initialized dma_chan -- - Selecting a DMA channel for an SPI bus allows transactions on the bus with size only limited by the amount of internal memory. Selecting SPI_DMA_DISABLED limits the size of transactions. Set to SPI_DMA_DISABLED if only the SPI flash uses this bus. Set to SPI_DMA_CH_AUTO to let the driver to allocate the DMA channel. Selecting SPI_DMA_DISABLED limits the size of transactions. Set to SPI_DMA_DISABLED if only the SPI flash uses this bus. Set to SPI_DMA_CH_AUTO to let the driver to allocate the DMA channel. Selecting SPI_DMA_DISABLED limits the size of transactions. host_id -- SPI peripheral that controls this bus bus_config -- Pointer to a spi_bus_config_t struct specifying how the host should be initialized dma_chan -- - Selecting a DMA channel for an SPI bus allows transactions on the bus with size only limited by the amount of internal memory. Selecting SPI_DMA_DISABLED limits the size of transactions. Set to SPI_DMA_DISABLED if only the SPI flash uses this bus. Set to SPI_DMA_CH_AUTO to let the driver to allocate the DMA channel. host_id -- SPI peripheral that controls this bus Returns ESP_ERR_INVALID_ARG if configuration is invalid ESP_ERR_INVALID_STATE if host already is in use ESP_ERR_NOT_FOUND if there is no available DMA channel ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if configuration is invalid ESP_ERR_INVALID_STATE if host already is in use ESP_ERR_NOT_FOUND if there is no available DMA channel ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if configuration is invalid Parameters host_id -- SPI peripheral that controls this bus bus_config -- Pointer to a spi_bus_config_t struct specifying how the host should be initialized dma_chan -- - Selecting a DMA channel for an SPI bus allows transactions on the bus with size only limited by the amount of internal memory. Selecting SPI_DMA_DISABLED limits the size of transactions. Set to SPI_DMA_DISABLED if only the SPI flash uses this bus. Set to SPI_DMA_CH_AUTO to let the driver to allocate the DMA channel. Returns ESP_ERR_INVALID_ARG if configuration is invalid ESP_ERR_INVALID_STATE if host already is in use ESP_ERR_NOT_FOUND if there is no available DMA channel ESP_ERR_NO_MEM if out of memory ESP_OK on success esp_err_t spi_bus_free(spi_host_device_t host_id) Free a SPI bus. Warning In order for this to succeed, all devices have to be removed first. Parameters host_id -- SPI peripheral to free Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if bus hasn't been initialized before, or not all devices on the bus are freed ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if bus hasn't been initialized before, or not all devices on the bus are freed ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters host_id -- SPI peripheral to free Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if bus hasn't been initialized before, or not all devices on the bus are freed ESP_OK on success Structures struct spi_bus_config_t This is a configuration structure for a SPI bus. You can use this structure to specify the GPIO pins of the bus. Normally, the driver will use the GPIO matrix to route the signals. An exception is made when all signals either can be routed through the IO_MUX or are -1. In that case, the IO_MUX is used, allowing for >40MHz speeds. Note Be advised that the slave driver does not use the quadwp/quadhd lines and fields in spi_bus_config_t refering to these lines will be ignored and can thus safely be left uninitialized. Public Members int mosi_io_num GPIO pin for Master Out Slave In (=spi_d) signal, or -1 if not used. int mosi_io_num GPIO pin for Master Out Slave In (=spi_d) signal, or -1 if not used. int data0_io_num GPIO pin for spi data0 signal in quad/octal mode, or -1 if not used. int data0_io_num GPIO pin for spi data0 signal in quad/octal mode, or -1 if not used. int miso_io_num GPIO pin for Master In Slave Out (=spi_q) signal, or -1 if not used. int miso_io_num GPIO pin for Master In Slave Out (=spi_q) signal, or -1 if not used. int data1_io_num GPIO pin for spi data1 signal in quad/octal mode, or -1 if not used. int data1_io_num GPIO pin for spi data1 signal in quad/octal mode, or -1 if not used. int sclk_io_num GPIO pin for SPI Clock signal, or -1 if not used. int sclk_io_num GPIO pin for SPI Clock signal, or -1 if not used. int quadwp_io_num GPIO pin for WP (Write Protect) signal, or -1 if not used. int quadwp_io_num GPIO pin for WP (Write Protect) signal, or -1 if not used. int data2_io_num GPIO pin for spi data2 signal in quad/octal mode, or -1 if not used. int data2_io_num GPIO pin for spi data2 signal in quad/octal mode, or -1 if not used. int quadhd_io_num GPIO pin for HD (Hold) signal, or -1 if not used. int quadhd_io_num GPIO pin for HD (Hold) signal, or -1 if not used. int data3_io_num GPIO pin for spi data3 signal in quad/octal mode, or -1 if not used. int data3_io_num GPIO pin for spi data3 signal in quad/octal mode, or -1 if not used. int data4_io_num GPIO pin for spi data4 signal in octal mode, or -1 if not used. int data4_io_num GPIO pin for spi data4 signal in octal mode, or -1 if not used. int data5_io_num GPIO pin for spi data5 signal in octal mode, or -1 if not used. int data5_io_num GPIO pin for spi data5 signal in octal mode, or -1 if not used. int data6_io_num GPIO pin for spi data6 signal in octal mode, or -1 if not used. int data6_io_num GPIO pin for spi data6 signal in octal mode, or -1 if not used. int data7_io_num GPIO pin for spi data7 signal in octal mode, or -1 if not used. int data7_io_num GPIO pin for spi data7 signal in octal mode, or -1 if not used. int max_transfer_sz Maximum transfer size, in bytes. Defaults to 4092 if 0 when DMA enabled, or to SOC_SPI_MAXIMUM_BUFFER_SIZE if DMA is disabled. int max_transfer_sz Maximum transfer size, in bytes. Defaults to 4092 if 0 when DMA enabled, or to SOC_SPI_MAXIMUM_BUFFER_SIZE if DMA is disabled. uint32_t flags Abilities of bus to be checked by the driver. Or-ed value of SPICOMMON_BUSFLAG_* flags. uint32_t flags Abilities of bus to be checked by the driver. Or-ed value of SPICOMMON_BUSFLAG_* flags. esp_intr_cpu_affinity_t isr_cpu_id Select cpu core to register SPI ISR. esp_intr_cpu_affinity_t isr_cpu_id Select cpu core to register SPI ISR. int intr_flags Interrupt flag for the bus to set the priority, and IRAM attribute, see esp_intr_alloc.h . Note that the EDGE, INTRDISABLED attribute are ignored by the driver. Note that if ESP_INTR_FLAG_IRAM is set, ALL the callbacks of the driver, and their callee functions, should be put in the IRAM. int intr_flags Interrupt flag for the bus to set the priority, and IRAM attribute, see esp_intr_alloc.h . Note that the EDGE, INTRDISABLED attribute are ignored by the driver. Note that if ESP_INTR_FLAG_IRAM is set, ALL the callbacks of the driver, and their callee functions, should be put in the IRAM. int mosi_io_num Macros SPI_MAX_DMA_LEN SPI_SWAP_DATA_TX(DATA, LEN) Transform unsigned integer of length <= 32 bits to the format which can be sent by the SPI driver directly. E.g. to send 9 bits of data, you can: uint16_t data = SPI_SWAP_DATA_TX(0x145, 9); Then points tx_buffer to &data . Parameters DATA -- Data to be sent, can be uint8_t, uint16_t or uint32_t. LEN -- Length of data to be sent, since the SPI peripheral sends from the MSB, this helps to shift the data to the MSB. DATA -- Data to be sent, can be uint8_t, uint16_t or uint32_t. LEN -- Length of data to be sent, since the SPI peripheral sends from the MSB, this helps to shift the data to the MSB. DATA -- Data to be sent, can be uint8_t, uint16_t or uint32_t. Parameters DATA -- Data to be sent, can be uint8_t, uint16_t or uint32_t. LEN -- Length of data to be sent, since the SPI peripheral sends from the MSB, this helps to shift the data to the MSB. SPI_SWAP_DATA_RX(DATA, LEN) Transform received data of length <= 32 bits to the format of an unsigned integer. E.g. to transform the data of 15 bits placed in a 4-byte array to integer: uint16_t data = SPI_SWAP_DATA_RX(*(uint32_t*)t->rx_data, 15); Parameters DATA -- Data to be rearranged, can be uint8_t, uint16_t or uint32_t. LEN -- Length of data received, since the SPI peripheral writes from the MSB, this helps to shift the data to the LSB. DATA -- Data to be rearranged, can be uint8_t, uint16_t or uint32_t. LEN -- Length of data received, since the SPI peripheral writes from the MSB, this helps to shift the data to the LSB. DATA -- Data to be rearranged, can be uint8_t, uint16_t or uint32_t. Parameters DATA -- Data to be rearranged, can be uint8_t, uint16_t or uint32_t. LEN -- Length of data received, since the SPI peripheral writes from the MSB, this helps to shift the data to the LSB. SPICOMMON_BUSFLAG_SLAVE Initialize I/O in slave mode. SPICOMMON_BUSFLAG_MASTER Initialize I/O in master mode. SPICOMMON_BUSFLAG_IOMUX_PINS Check using iomux pins. Or indicates the pins are configured through the IO mux rather than GPIO matrix. SPICOMMON_BUSFLAG_GPIO_PINS Force the signals to be routed through GPIO matrix. Or indicates the pins are routed through the GPIO matrix. SPICOMMON_BUSFLAG_SCLK Check existing of SCLK pin. Or indicates CLK line initialized. SPICOMMON_BUSFLAG_MISO Check existing of MISO pin. Or indicates MISO line initialized. SPICOMMON_BUSFLAG_MOSI Check existing of MOSI pin. Or indicates MOSI line initialized. SPICOMMON_BUSFLAG_DUAL Check MOSI and MISO pins can output. Or indicates bus able to work under DIO mode. SPICOMMON_BUSFLAG_WPHD Check existing of WP and HD pins. Or indicates WP & HD pins initialized. SPICOMMON_BUSFLAG_QUAD Check existing of MOSI/MISO/WP/HD pins as output. Or indicates bus able to work under QIO mode. SPICOMMON_BUSFLAG_IO4_IO7 Check existing of IO4~IO7 pins. Or indicates IO4~IO7 pins initialized. SPICOMMON_BUSFLAG_OCTAL Check existing of MOSI/MISO/WP/HD/SPIIO4/SPIIO5/SPIIO6/SPIIO7 pins as output. Or indicates bus able to work under octal mode. SPICOMMON_BUSFLAG_NATIVE_PINS Type Definitions typedef spi_common_dma_t spi_dma_chan_t Enumerations enum spi_common_dma_t SPI DMA channels. Values: enumerator SPI_DMA_DISABLED Do not enable DMA for SPI. enumerator SPI_DMA_DISABLED Do not enable DMA for SPI. enumerator SPI_DMA_CH1 Enable DMA, select DMA Channel 1. enumerator SPI_DMA_CH1 Enable DMA, select DMA Channel 1. enumerator SPI_DMA_CH2 Enable DMA, select DMA Channel 2. enumerator SPI_DMA_CH2 Enable DMA, select DMA Channel 2. enumerator SPI_DMA_CH_AUTO Enable DMA, channel is automatically selected by driver. enumerator SPI_DMA_CH_AUTO Enable DMA, channel is automatically selected by driver. enumerator SPI_DMA_DISABLED API Reference - SPI Master Header File This header file can be included with: #include "driver/spi_master.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t spi_bus_add_device(spi_host_device_t host_id, const spi_device_interface_config_t *dev_config, spi_device_handle_t *handle) Allocate a device on a SPI bus. This initializes the internal structures for a device, plus allocates a CS pin on the indicated SPI master peripheral and routes it to the indicated GPIO. All SPI master devices have three CS pins and can thus control up to three devices. Note While in general, speeds up to 80MHz on the dedicated SPI pins and 40MHz on GPIO-matrix-routed pins are supported, full-duplex transfers routed over the GPIO matrix only support speeds up to 26MHz. Parameters host_id -- SPI peripheral to allocate device on dev_config -- SPI interface protocol config for the device handle -- Pointer to variable to hold the device handle host_id -- SPI peripheral to allocate device on dev_config -- SPI interface protocol config for the device handle -- Pointer to variable to hold the device handle host_id -- SPI peripheral to allocate device on Returns ESP_ERR_INVALID_ARG if parameter is invalid or configuration combination is not supported (e.g. dev_config->post_cb isn't set while flag SPI_DEVICE_NO_RETURN_RESULT is enabled) ESP_ERR_INVALID_STATE if selected clock source is unavailable or spi bus not initialized ESP_ERR_NOT_FOUND if host doesn't have any free CS slots ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid or configuration combination is not supported (e.g. dev_config->post_cb isn't set while flag SPI_DEVICE_NO_RETURN_RESULT is enabled) ESP_ERR_INVALID_STATE if selected clock source is unavailable or spi bus not initialized ESP_ERR_NOT_FOUND if host doesn't have any free CS slots ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid or configuration combination is not supported (e.g. dev_config->post_cb isn't set while flag SPI_DEVICE_NO_RETURN_RESULT is enabled) Parameters host_id -- SPI peripheral to allocate device on dev_config -- SPI interface protocol config for the device handle -- Pointer to variable to hold the device handle Returns ESP_ERR_INVALID_ARG if parameter is invalid or configuration combination is not supported (e.g. dev_config->post_cb isn't set while flag SPI_DEVICE_NO_RETURN_RESULT is enabled) ESP_ERR_INVALID_STATE if selected clock source is unavailable or spi bus not initialized ESP_ERR_NOT_FOUND if host doesn't have any free CS slots ESP_ERR_NO_MEM if out of memory ESP_OK on success esp_err_t spi_bus_remove_device(spi_device_handle_t handle) Remove a device from the SPI bus. Parameters handle -- Device handle to free Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if device already is freed ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if device already is freed ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters handle -- Device handle to free Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if device already is freed ESP_OK on success esp_err_t spi_device_queue_trans(spi_device_handle_t handle, spi_transaction_t *trans_desc, TickType_t ticks_to_wait) Queue a SPI transaction for interrupt transaction execution. Get the result by spi_device_get_trans_result . Note Normally a device cannot start (queue) polling and interrupt transactions simultaneously. Parameters handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute ticks_to_wait -- Ticks to wait until there's room in the queue; use portMAX_DELAY to never time out. handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute ticks_to_wait -- Ticks to wait until there's room in the queue; use portMAX_DELAY to never time out. handle -- Device handle obtained using spi_host_add_dev Returns ESP_ERR_INVALID_ARG if parameter is invalid. This can happen if SPI_TRANS_CS_KEEP_ACTIVE flag is specified while the bus was not acquired ( spi_device_acquire_bus() should be called first) or set flag SPI_TRANS_DMA_BUFFER_ALIGN_MANUAL but tx or rx buffer not DMA-capable, or addr&len not align to cache line size ESP_ERR_TIMEOUT if there was no room in the queue before ticks_to_wait expired ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed ESP_ERR_INVALID_STATE if previous transactions are not finished ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid. This can happen if SPI_TRANS_CS_KEEP_ACTIVE flag is specified while the bus was not acquired ( spi_device_acquire_bus() should be called first) or set flag SPI_TRANS_DMA_BUFFER_ALIGN_MANUAL but tx or rx buffer not DMA-capable, or addr&len not align to cache line size ESP_ERR_TIMEOUT if there was no room in the queue before ticks_to_wait expired ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed ESP_ERR_INVALID_STATE if previous transactions are not finished ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid. This can happen if SPI_TRANS_CS_KEEP_ACTIVE flag is specified while the bus was not acquired ( spi_device_acquire_bus() should be called first) or set flag SPI_TRANS_DMA_BUFFER_ALIGN_MANUAL but tx or rx buffer not DMA-capable, or addr&len not align to cache line size Parameters handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute ticks_to_wait -- Ticks to wait until there's room in the queue; use portMAX_DELAY to never time out. Returns ESP_ERR_INVALID_ARG if parameter is invalid. This can happen if SPI_TRANS_CS_KEEP_ACTIVE flag is specified while the bus was not acquired ( spi_device_acquire_bus() should be called first) or set flag SPI_TRANS_DMA_BUFFER_ALIGN_MANUAL but tx or rx buffer not DMA-capable, or addr&len not align to cache line size ESP_ERR_TIMEOUT if there was no room in the queue before ticks_to_wait expired ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed ESP_ERR_INVALID_STATE if previous transactions are not finished ESP_OK on success esp_err_t spi_device_get_trans_result(spi_device_handle_t handle, spi_transaction_t **trans_desc, TickType_t ticks_to_wait) Get the result of a SPI transaction queued earlier by spi_device_queue_trans . This routine will wait until a transaction to the given device succesfully completed. It will then return the description of the completed transaction so software can inspect the result and e.g. free the memory or re-use the buffers. Parameters handle -- Device handle obtained using spi_host_add_dev trans_desc -- Pointer to variable able to contain a pointer to the description of the transaction that is executed. The descriptor should not be modified until the descriptor is returned by spi_device_get_trans_result. ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. handle -- Device handle obtained using spi_host_add_dev trans_desc -- Pointer to variable able to contain a pointer to the description of the transaction that is executed. The descriptor should not be modified until the descriptor is returned by spi_device_get_trans_result. ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. handle -- Device handle obtained using spi_host_add_dev Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if flag SPI_DEVICE_NO_RETURN_RESULT is set ESP_ERR_TIMEOUT if there was no completed transaction before ticks_to_wait expired ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if flag SPI_DEVICE_NO_RETURN_RESULT is set ESP_ERR_TIMEOUT if there was no completed transaction before ticks_to_wait expired ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters handle -- Device handle obtained using spi_host_add_dev trans_desc -- Pointer to variable able to contain a pointer to the description of the transaction that is executed. The descriptor should not be modified until the descriptor is returned by spi_device_get_trans_result. ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if flag SPI_DEVICE_NO_RETURN_RESULT is set ESP_ERR_TIMEOUT if there was no completed transaction before ticks_to_wait expired ESP_OK on success esp_err_t spi_device_transmit(spi_device_handle_t handle, spi_transaction_t *trans_desc) Send a SPI transaction, wait for it to complete, and return the result. This function is the equivalent of calling spi_device_queue_trans() followed by spi_device_get_trans_result(). Do not use this when there is still a transaction separately queued (started) from spi_device_queue_trans() or polling_start/transmit that hasn't been finalized. Note This function is not thread safe when multiple tasks access the same SPI device. Normally a device cannot start (queue) polling and interrupt transactions simutanuously. Parameters handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute handle -- Device handle obtained using spi_host_add_dev Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success esp_err_t spi_device_polling_start(spi_device_handle_t handle, spi_transaction_t *trans_desc, TickType_t ticks_to_wait) Immediately start a polling transaction. Note Normally a device cannot start (queue) polling and interrupt transactions simutanuously. Moreover, a device cannot start a new polling transaction if another polling transaction is not finished. Parameters handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute ticks_to_wait -- Ticks to wait until there's room in the queue; currently only portMAX_DELAY is supported. handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute ticks_to_wait -- Ticks to wait until there's room in the queue; currently only portMAX_DELAY is supported. handle -- Device handle obtained using spi_host_add_dev Returns ESP_ERR_INVALID_ARG if parameter is invalid. This can happen if SPI_TRANS_CS_KEEP_ACTIVE flag is specified while the bus was not acquired ( spi_device_acquire_bus() should be called first) or set flag SPI_TRANS_DMA_BUFFER_ALIGN_MANUAL but tx or rx buffer not DMA-capable, or addr&len not align to cache line size ESP_ERR_TIMEOUT if the device cannot get control of the bus before ticks_to_wait expired ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed ESP_ERR_INVALID_STATE if previous transactions are not finished ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid. This can happen if SPI_TRANS_CS_KEEP_ACTIVE flag is specified while the bus was not acquired ( spi_device_acquire_bus() should be called first) or set flag SPI_TRANS_DMA_BUFFER_ALIGN_MANUAL but tx or rx buffer not DMA-capable, or addr&len not align to cache line size ESP_ERR_TIMEOUT if the device cannot get control of the bus before ticks_to_wait expired ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed ESP_ERR_INVALID_STATE if previous transactions are not finished ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid. This can happen if SPI_TRANS_CS_KEEP_ACTIVE flag is specified while the bus was not acquired ( spi_device_acquire_bus() should be called first) or set flag SPI_TRANS_DMA_BUFFER_ALIGN_MANUAL but tx or rx buffer not DMA-capable, or addr&len not align to cache line size Parameters handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute ticks_to_wait -- Ticks to wait until there's room in the queue; currently only portMAX_DELAY is supported. Returns ESP_ERR_INVALID_ARG if parameter is invalid. This can happen if SPI_TRANS_CS_KEEP_ACTIVE flag is specified while the bus was not acquired ( spi_device_acquire_bus() should be called first) or set flag SPI_TRANS_DMA_BUFFER_ALIGN_MANUAL but tx or rx buffer not DMA-capable, or addr&len not align to cache line size ESP_ERR_TIMEOUT if the device cannot get control of the bus before ticks_to_wait expired ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed ESP_ERR_INVALID_STATE if previous transactions are not finished ESP_OK on success esp_err_t spi_device_polling_end(spi_device_handle_t handle, TickType_t ticks_to_wait) Poll until the polling transaction ends. This routine will not return until the transaction to the given device has succesfully completed. The task is not blocked, but actively busy-spins for the transaction to be completed. Parameters handle -- Device handle obtained using spi_host_add_dev ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. handle -- Device handle obtained using spi_host_add_dev ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. handle -- Device handle obtained using spi_host_add_dev Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_TIMEOUT if the transaction cannot finish before ticks_to_wait expired ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_TIMEOUT if the transaction cannot finish before ticks_to_wait expired ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters handle -- Device handle obtained using spi_host_add_dev ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_TIMEOUT if the transaction cannot finish before ticks_to_wait expired ESP_OK on success esp_err_t spi_device_polling_transmit(spi_device_handle_t handle, spi_transaction_t *trans_desc) Send a polling transaction, wait for it to complete, and return the result. This function is the equivalent of calling spi_device_polling_start() followed by spi_device_polling_end(). Do not use this when there is still a transaction that hasn't been finalized. Note This function is not thread safe when multiple tasks access the same SPI device. Normally a device cannot start (queue) polling and interrupt transactions simutanuously. Parameters handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute handle -- Device handle obtained using spi_host_add_dev Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_TIMEOUT if the device cannot get control of the bus ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed ESP_ERR_INVALID_STATE if previous transactions of same device are not finished ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_TIMEOUT if the device cannot get control of the bus ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed ESP_ERR_INVALID_STATE if previous transactions of same device are not finished ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_TIMEOUT if the device cannot get control of the bus ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed ESP_ERR_INVALID_STATE if previous transactions of same device are not finished ESP_OK on success esp_err_t spi_device_acquire_bus(spi_device_handle_t device, TickType_t wait) Occupy the SPI bus for a device to do continuous transactions. Transactions to all other devices will be put off until spi_device_release_bus is called. Note The function will wait until all the existing transactions have been sent. Parameters device -- The device to occupy the bus. wait -- Time to wait before the the bus is occupied by the device. Currently MUST set to portMAX_DELAY. device -- The device to occupy the bus. wait -- Time to wait before the the bus is occupied by the device. Currently MUST set to portMAX_DELAY. device -- The device to occupy the bus. Returns ESP_ERR_INVALID_ARG : wait is not set to portMAX_DELAY. ESP_OK : Success. ESP_ERR_INVALID_ARG : wait is not set to portMAX_DELAY. ESP_OK : Success. ESP_ERR_INVALID_ARG : wait is not set to portMAX_DELAY. Parameters device -- The device to occupy the bus. wait -- Time to wait before the the bus is occupied by the device. Currently MUST set to portMAX_DELAY. Returns ESP_ERR_INVALID_ARG : wait is not set to portMAX_DELAY. ESP_OK : Success. void spi_device_release_bus(spi_device_handle_t dev) Release the SPI bus occupied by the device. All other devices can start sending transactions. Parameters dev -- The device to release the bus. Parameters dev -- The device to release the bus. esp_err_t spi_device_get_actual_freq(spi_device_handle_t handle, int *freq_khz) Calculate working frequency for specific device. Parameters handle -- SPI device handle freq_khz -- [out] output parameter to hold calculated frequency in kHz handle -- SPI device handle freq_khz -- [out] output parameter to hold calculated frequency in kHz handle -- SPI device handle Returns ESP_ERR_INVALID_ARG : handle or freq_khz parameter is NULL ESP_OK : Success ESP_ERR_INVALID_ARG : handle or freq_khz parameter is NULL ESP_OK : Success ESP_ERR_INVALID_ARG : handle or freq_khz parameter is NULL Parameters handle -- SPI device handle freq_khz -- [out] output parameter to hold calculated frequency in kHz Returns ESP_ERR_INVALID_ARG : handle or freq_khz parameter is NULL ESP_OK : Success int spi_get_actual_clock(int fapb, int hz, int duty_cycle) Calculate the working frequency that is most close to desired frequency. Parameters fapb -- The frequency of apb clock, should be APB_CLK_FREQ . hz -- Desired working frequency duty_cycle -- Duty cycle of the spi clock fapb -- The frequency of apb clock, should be APB_CLK_FREQ . hz -- Desired working frequency duty_cycle -- Duty cycle of the spi clock fapb -- The frequency of apb clock, should be APB_CLK_FREQ . Returns Actual working frequency that most fit. Parameters fapb -- The frequency of apb clock, should be APB_CLK_FREQ . hz -- Desired working frequency duty_cycle -- Duty cycle of the spi clock Returns Actual working frequency that most fit. void spi_get_timing(bool gpio_is_used, int input_delay_ns, int eff_clk, int *dummy_o, int *cycles_remain_o) Calculate the timing settings of specified frequency and settings. Note If **dummy_o* is not zero, it means dummy bits should be applied in half duplex mode, and full duplex mode may not work. Parameters gpio_is_used -- True if using GPIO matrix, or False if iomux pins are used. input_delay_ns -- Input delay from SCLK launch edge to MISO data valid. eff_clk -- Effective clock frequency (in Hz) from spi_get_actual_clock() . dummy_o -- Address of dummy bits used output. Set to NULL if not needed. cycles_remain_o -- Address of cycles remaining (after dummy bits are used) output. -1 If too many cycles remaining, suggest to compensate half a clock. 0 If no remaining cycles or dummy bits are not used. positive value: cycles suggest to compensate. -1 If too many cycles remaining, suggest to compensate half a clock. 0 If no remaining cycles or dummy bits are not used. positive value: cycles suggest to compensate. -1 If too many cycles remaining, suggest to compensate half a clock. gpio_is_used -- True if using GPIO matrix, or False if iomux pins are used. input_delay_ns -- Input delay from SCLK launch edge to MISO data valid. eff_clk -- Effective clock frequency (in Hz) from spi_get_actual_clock() . dummy_o -- Address of dummy bits used output. Set to NULL if not needed. cycles_remain_o -- Address of cycles remaining (after dummy bits are used) output. -1 If too many cycles remaining, suggest to compensate half a clock. 0 If no remaining cycles or dummy bits are not used. positive value: cycles suggest to compensate. gpio_is_used -- True if using GPIO matrix, or False if iomux pins are used. Parameters gpio_is_used -- True if using GPIO matrix, or False if iomux pins are used. input_delay_ns -- Input delay from SCLK launch edge to MISO data valid. eff_clk -- Effective clock frequency (in Hz) from spi_get_actual_clock() . dummy_o -- Address of dummy bits used output. Set to NULL if not needed. cycles_remain_o -- Address of cycles remaining (after dummy bits are used) output. -1 If too many cycles remaining, suggest to compensate half a clock. 0 If no remaining cycles or dummy bits are not used. positive value: cycles suggest to compensate. int spi_get_freq_limit(bool gpio_is_used, int input_delay_ns) Get the frequency limit of current configurations. SPI master working at this limit is OK, while above the limit, full duplex mode and DMA will not work, and dummy bits will be aplied in the half duplex mode. Parameters gpio_is_used -- True if using GPIO matrix, or False if native pins are used. input_delay_ns -- Input delay from SCLK launch edge to MISO data valid. gpio_is_used -- True if using GPIO matrix, or False if native pins are used. input_delay_ns -- Input delay from SCLK launch edge to MISO data valid. gpio_is_used -- True if using GPIO matrix, or False if native pins are used. Returns Frequency limit of current configurations. Parameters gpio_is_used -- True if using GPIO matrix, or False if native pins are used. input_delay_ns -- Input delay from SCLK launch edge to MISO data valid. Returns Frequency limit of current configurations. esp_err_t spi_bus_get_max_transaction_len(spi_host_device_t host_id, size_t *max_bytes) Get max length (in bytes) of one transaction. Parameters host_id -- SPI peripheral max_bytes -- [out] Max length of one transaction, in bytes host_id -- SPI peripheral max_bytes -- [out] Max length of one transaction, in bytes host_id -- SPI peripheral Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument ESP_OK: On success Parameters host_id -- SPI peripheral max_bytes -- [out] Max length of one transaction, in bytes Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument Structures struct spi_device_interface_config_t This is a configuration for a SPI slave device that is connected to one of the SPI buses. Public Members uint8_t command_bits Default amount of bits in command phase (0-16), used when SPI_TRANS_VARIABLE_CMD is not used, otherwise ignored. uint8_t command_bits Default amount of bits in command phase (0-16), used when SPI_TRANS_VARIABLE_CMD is not used, otherwise ignored. uint8_t address_bits Default amount of bits in address phase (0-64), used when SPI_TRANS_VARIABLE_ADDR is not used, otherwise ignored. uint8_t address_bits Default amount of bits in address phase (0-64), used when SPI_TRANS_VARIABLE_ADDR is not used, otherwise ignored. uint8_t dummy_bits Amount of dummy bits to insert between address and data phase. uint8_t dummy_bits Amount of dummy bits to insert between address and data phase. uint8_t mode SPI mode, representing a pair of (CPOL, CPHA) configuration: 0: (0, 0) 1: (0, 1) 2: (1, 0) 3: (1, 1) 0: (0, 0) 1: (0, 1) 2: (1, 0) 3: (1, 1) 0: (0, 0) uint8_t mode SPI mode, representing a pair of (CPOL, CPHA) configuration: 0: (0, 0) 1: (0, 1) 2: (1, 0) 3: (1, 1) spi_clock_source_t clock_source Select SPI clock source, SPI_CLK_SRC_DEFAULT by default. spi_clock_source_t clock_source Select SPI clock source, SPI_CLK_SRC_DEFAULT by default. uint16_t duty_cycle_pos Duty cycle of positive clock, in 1/256th increments (128 = 50%/50% duty). Setting this to 0 (=not setting it) is equivalent to setting this to 128. uint16_t duty_cycle_pos Duty cycle of positive clock, in 1/256th increments (128 = 50%/50% duty). Setting this to 0 (=not setting it) is equivalent to setting this to 128. uint16_t cs_ena_pretrans Amount of SPI bit-cycles the cs should be activated before the transmission (0-16). This only works on half-duplex transactions. uint16_t cs_ena_pretrans Amount of SPI bit-cycles the cs should be activated before the transmission (0-16). This only works on half-duplex transactions. uint8_t cs_ena_posttrans Amount of SPI bit-cycles the cs should stay active after the transmission (0-16) uint8_t cs_ena_posttrans Amount of SPI bit-cycles the cs should stay active after the transmission (0-16) int clock_speed_hz SPI clock speed in Hz. Derived from clock_source . int clock_speed_hz SPI clock speed in Hz. Derived from clock_source . int input_delay_ns Maximum data valid time of slave. The time required between SCLK and MISO valid, including the possible clock delay from slave to master. The driver uses this value to give an extra delay before the MISO is ready on the line. Leave at 0 unless you know you need a delay. For better timing performance at high frequency (over 8MHz), it's suggest to have the right value. int input_delay_ns Maximum data valid time of slave. The time required between SCLK and MISO valid, including the possible clock delay from slave to master. The driver uses this value to give an extra delay before the MISO is ready on the line. Leave at 0 unless you know you need a delay. For better timing performance at high frequency (over 8MHz), it's suggest to have the right value. int spics_io_num CS GPIO pin for this device, or -1 if not used. int spics_io_num CS GPIO pin for this device, or -1 if not used. uint32_t flags Bitwise OR of SPI_DEVICE_* flags. uint32_t flags Bitwise OR of SPI_DEVICE_* flags. int queue_size Transaction queue size. This sets how many transactions can be 'in the air' (queued using spi_device_queue_trans but not yet finished using spi_device_get_trans_result) at the same time. int queue_size Transaction queue size. This sets how many transactions can be 'in the air' (queued using spi_device_queue_trans but not yet finished using spi_device_get_trans_result) at the same time. transaction_cb_t pre_cb Callback to be called before a transmission is started. This callback is called within interrupt context should be in IRAM for best performance, see "Transferring Speed" section in the SPI Master documentation for full details. If not, the callback may crash during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM. transaction_cb_t pre_cb Callback to be called before a transmission is started. This callback is called within interrupt context should be in IRAM for best performance, see "Transferring Speed" section in the SPI Master documentation for full details. If not, the callback may crash during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM. transaction_cb_t post_cb Callback to be called after a transmission has completed. This callback is called within interrupt context should be in IRAM for best performance, see "Transferring Speed" section in the SPI Master documentation for full details. If not, the callback may crash during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM. transaction_cb_t post_cb Callback to be called after a transmission has completed. This callback is called within interrupt context should be in IRAM for best performance, see "Transferring Speed" section in the SPI Master documentation for full details. If not, the callback may crash during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM. uint8_t command_bits struct spi_transaction_t This structure describes one SPI transaction. The descriptor should not be modified until the transaction finishes. Public Members uint32_t flags Bitwise OR of SPI_TRANS_* flags. uint32_t flags Bitwise OR of SPI_TRANS_* flags. uint16_t cmd Command data, of which the length is set in the command_bits of spi_device_interface_config_t. NOTE: this field, used to be "command" in ESP-IDF 2.1 and before, is re-written to be used in a new way in ESP-IDF 3.0. Example: write 0x0123 and command_bits=12 to send command 0x12, 0x3_ (in previous version, you may have to write 0x3_12). uint16_t cmd Command data, of which the length is set in the command_bits of spi_device_interface_config_t. NOTE: this field, used to be "command" in ESP-IDF 2.1 and before, is re-written to be used in a new way in ESP-IDF 3.0. Example: write 0x0123 and command_bits=12 to send command 0x12, 0x3_ (in previous version, you may have to write 0x3_12). uint64_t addr Address data, of which the length is set in the address_bits of spi_device_interface_config_t. NOTE: this field, used to be "address" in ESP-IDF 2.1 and before, is re-written to be used in a new way in ESP-IDF3.0. Example: write 0x123400 and address_bits=24 to send address of 0x12, 0x34, 0x00 (in previous version, you may have to write 0x12340000). uint64_t addr Address data, of which the length is set in the address_bits of spi_device_interface_config_t. NOTE: this field, used to be "address" in ESP-IDF 2.1 and before, is re-written to be used in a new way in ESP-IDF3.0. Example: write 0x123400 and address_bits=24 to send address of 0x12, 0x34, 0x00 (in previous version, you may have to write 0x12340000). size_t length Total data length, in bits. size_t length Total data length, in bits. size_t rxlength Total data length received, should be not greater than length in full-duplex mode (0 defaults this to the value of length ). size_t rxlength Total data length received, should be not greater than length in full-duplex mode (0 defaults this to the value of length ). void *user User-defined variable. Can be used to store eg transaction ID. void *user User-defined variable. Can be used to store eg transaction ID. const void *tx_buffer Pointer to transmit buffer, or NULL for no MOSI phase. const void *tx_buffer Pointer to transmit buffer, or NULL for no MOSI phase. uint8_t tx_data[4] If SPI_TRANS_USE_TXDATA is set, data set here is sent directly from this variable. uint8_t tx_data[4] If SPI_TRANS_USE_TXDATA is set, data set here is sent directly from this variable. void *rx_buffer Pointer to receive buffer, or NULL for no MISO phase. Written by 4 bytes-unit if DMA is used. void *rx_buffer Pointer to receive buffer, or NULL for no MISO phase. Written by 4 bytes-unit if DMA is used. uint8_t rx_data[4] If SPI_TRANS_USE_RXDATA is set, data is received directly to this variable. uint8_t rx_data[4] If SPI_TRANS_USE_RXDATA is set, data is received directly to this variable. uint32_t flags struct spi_transaction_ext_t This struct is for SPI transactions which may change their address and command length. Please do set the flags in base to SPI_TRANS_VARIABLE_CMD_ADR to use the bit length here. Public Members struct spi_transaction_t base Transaction data, so that pointer to spi_transaction_t can be converted into spi_transaction_ext_t. struct spi_transaction_t base Transaction data, so that pointer to spi_transaction_t can be converted into spi_transaction_ext_t. uint8_t command_bits The command length in this transaction, in bits. uint8_t command_bits The command length in this transaction, in bits. uint8_t address_bits The address length in this transaction, in bits. uint8_t address_bits The address length in this transaction, in bits. uint8_t dummy_bits The dummy length in this transaction, in bits. uint8_t dummy_bits The dummy length in this transaction, in bits. struct spi_transaction_t base Macros SPI_MASTER_FREQ_8M SPI common used frequency (in Hz) Note SPI peripheral only has an integer divider, and the default clock source can be different on other targets, so the actual frequency may be slightly different from the desired frequency. 8MHz SPI_MASTER_FREQ_9M 8.89MHz SPI_MASTER_FREQ_10M 10MHz SPI_MASTER_FREQ_11M 11.43MHz SPI_MASTER_FREQ_13M 13.33MHz SPI_MASTER_FREQ_16M 16MHz SPI_MASTER_FREQ_20M 20MHz SPI_MASTER_FREQ_26M 26.67MHz SPI_MASTER_FREQ_40M 40MHz SPI_MASTER_FREQ_80M 80MHz SPI_DEVICE_TXBIT_LSBFIRST Transmit command/address/data LSB first instead of the default MSB first. SPI_DEVICE_RXBIT_LSBFIRST Receive data LSB first instead of the default MSB first. SPI_DEVICE_BIT_LSBFIRST Transmit and receive LSB first. SPI_DEVICE_3WIRE Use MOSI (=spid) for both sending and receiving data. SPI_DEVICE_POSITIVE_CS Make CS positive during a transaction instead of negative. SPI_DEVICE_HALFDUPLEX Transmit data before receiving it, instead of simultaneously. SPI_DEVICE_CLK_AS_CS Output clock on CS line if CS is active. SPI_DEVICE_NO_DUMMY There are timing issue when reading at high frequency (the frequency is related to whether iomux pins are used, valid time after slave sees the clock). In half-duplex mode, the driver automatically inserts dummy bits before reading phase to fix the timing issue. Set this flag to disable this feature. In full-duplex mode, however, the hardware cannot use dummy bits, so there is no way to prevent data being read from getting corrupted. Set this flag to confirm that you're going to work with output only, or read without dummy bits at your own risk. In half-duplex mode, the driver automatically inserts dummy bits before reading phase to fix the timing issue. Set this flag to disable this feature. In full-duplex mode, however, the hardware cannot use dummy bits, so there is no way to prevent data being read from getting corrupted. Set this flag to confirm that you're going to work with output only, or read without dummy bits at your own risk. In half-duplex mode, the driver automatically inserts dummy bits before reading phase to fix the timing issue. Set this flag to disable this feature. SPI_DEVICE_DDRCLK SPI_DEVICE_NO_RETURN_RESULT Don't return the descriptor to the host on completion (use post_cb to notify instead) SPI_TRANS_MODE_DIO Transmit/receive data in 2-bit mode. SPI_TRANS_MODE_QIO Transmit/receive data in 4-bit mode. SPI_TRANS_USE_RXDATA Receive into rx_data member of spi_transaction_t instead into memory at rx_buffer. SPI_TRANS_USE_TXDATA Transmit tx_data member of spi_transaction_t instead of data at tx_buffer. Do not set tx_buffer when using this. SPI_TRANS_MODE_DIOQIO_ADDR Also transmit address in mode selected by SPI_MODE_DIO/SPI_MODE_QIO. SPI_TRANS_VARIABLE_CMD Use the command_bits in spi_transaction_ext_t rather than default value in spi_device_interface_config_t . SPI_TRANS_VARIABLE_ADDR Use the address_bits in spi_transaction_ext_t rather than default value in spi_device_interface_config_t . SPI_TRANS_VARIABLE_DUMMY Use the dummy_bits in spi_transaction_ext_t rather than default value in spi_device_interface_config_t . SPI_TRANS_CS_KEEP_ACTIVE Keep CS active after data transfer. SPI_TRANS_MULTILINE_CMD The data lines used at command phase is the same as data phase (otherwise, only one data line is used at command phase) SPI_TRANS_MODE_OCT Transmit/receive data in 8-bit mode. SPI_TRANS_MULTILINE_ADDR The data lines used at address phase is the same as data phase (otherwise, only one data line is used at address phase) SPI_TRANS_DMA_BUFFER_ALIGN_MANUAL By default driver will automatically re-alloc dma buffer if it doesn't meet hardware alignment or dma_capable requirements, this flag is for you to disable this feature, you will need to take care of the alignment otherwise driver will return you error ESP_ERR_INVALID_ARG. Type Definitions typedef void (*transaction_cb_t)(spi_transaction_t *trans) typedef struct spi_device_t *spi_device_handle_t Handle for a device on a SPI bus.
SPI Master Driver SPI Master driver is a program that controls ESP32's General Purpose SPI (GP-SPI) peripheral(s) when it functions as a master. Note SPI1 is not a GP-SPI. SPI Master driver also supports SPI1 but with quite a few limitations, see Notes on Using the SPI Master Driver on SPI1 Bus. For more hardware information about the GP-SPI peripheral(s), see ESP32 Technical Reference Manual > SPI Controller [PDF]. Terminology The terms used in relation to the SPI Master driver are given in the table below. | Term | Definition | Host | The SPI controller peripheral inside ESP32 initiates SPI transmissions over the bus and acts as an SPI Master. | Device | SPI slave Device. An SPI bus may be connected to one or more Devices. Each Device shares the MOSI, MISO, and SCLK signals but is only active on the bus when the Host asserts the Device's individual CS line. | Bus | A signal bus, common to all Devices connected to one Host. In general, a bus includes the following lines: MISO, MOSI, SCLK, one or more CS lines, and, optionally, QUADWP and QUADHD. So Devices are connected to the same lines, with the exception that each Device has its own CS line. Several Devices can also share one CS line if connected in a daisy-chain manner. | MOSI | Master Out, Slave In, a.k.a. D. Data transmission from a Host to Device. Also data0 signal in Octal/OPI mode. | MISO | Master In, Slave Out, a.k.a. Q. Data transmission from a Device to Host. Also data1 signal in Octal/OPI mode. | SCLK | Serial Clock. The oscillating signal generated by a Host keeps the transmission of data bits in sync. | CS | Chip Select. Allows a Host to select individual Device(s) connected to the bus in order to send or receive data. | QUADWP | Write Protect signal. Used for 4-bit (qio/qout) transactions. Also for the data2 signal in Octal/OPI mode. | QUADHD | Hold signal. Used for 4-bit (qio/qout) transactions. Also for the data3 signal in Octal/OPI mode. | DATA4 | Data4 signal in Octal/OPI mode. | DATA5 | Data5 signal in Octal/OPI mode. | DATA6 | Data6 signal in Octal/OPI mode. | DATA7 | Data7 signal in Octal/OPI mode. | Assertion | The action of activating a line. | De-assertion | The action of returning the line back to inactive (back to idle) status. | Transaction | One instance of a Host asserting a CS line, transferring data to and from a Device, and de-asserting the CS line. Transactions are atomic, which means they can never be interrupted by another transaction. | Launch Edge | Edge of the clock at which the source register launches the signal onto the line. | Latch Edge | Edge of the clock at which the destination register latches in the signal. Driver Features The SPI Master driver governs the communications between Hosts and Devices. The driver supports the following features: Multi-threaded environments Transparent handling of DMA transfers while reading and writing data Automatic time-division multiplexing of data coming from different Devices on the same signal bus, see SPI Bus Lock. Warning The SPI Master driver allows multiple Devices to be connected on a same SPI bus (sharing a single ESP32 SPI peripheral). As long as each Device is accessed by only one task, the driver is thread-safe. However, if multiple tasks try to access the same SPI Device, the driver is not thread-safe. In this case, it is recommended to either: Refactor your application so that each SPI peripheral is only accessed by a single task at a time. You can use spi_bus_config_t::isr_cpu_idto register the SPI ISR to the same core as SPI peripheral-related tasks to ensure thread safety. Add a mutex lock around the shared Device using xSemaphoreCreateMutex. SPI Transactions An SPI bus transaction consists of five phases which can be found in the table below. Any of these phases can be skipped. | Phase | Description | Command | In this phase, a command (0-16 bit) is written to the bus by the Host. | Address | In this phase, an address (0-64 bit) is transmitted over the bus by the Host. | Dummy | This phase is configurable and is used to meet the timing requirements. | Write | Host sends data to a Device. This data follows the optional command and address phases and is indistinguishable from them at the electrical level. | Read | Device sends data to its Host. The attributes of a transaction are determined by the bus configuration structure spi_bus_config_t, Device configuration structure spi_device_interface_config_t, and transaction configuration structure spi_transaction_t. An SPI Host can send full-duplex transactions, during which the Read and Write phases occur simultaneously. The total transaction length is determined by the sum of the following members: While the member spi_transaction_t::rxlength only determines the length of data received into the buffer. In half-duplex transactions, the Read and Write phases are not simultaneous (one direction at a time). The lengths of the Write and Read phases are determined by spi_transaction_t::length and spi_transaction_t::rxlength respectively. The Command and Address phases are optional, as not every SPI Device requires a command and/or address. This is reflected in the Device's configuration: if spi_device_interface_config_t::command_bits and/or spi_device_interface_config_t::address_bits are set to zero, no Command or Address phase will occur. The Read and Write phases can also be optional, as not every transaction requires both writing and reading data. If spi_transaction_t::rx_buffer is NULL and SPI_TRANS_USE_RXDATA is not set, the Read phase is skipped. If spi_transaction_t::tx_buffer is NULL and SPI_TRANS_USE_TXDATA is not set, the Write phase is skipped. The driver supports two types of transactions: interrupt transactions and polling transactions. The programmer can choose to use a different transaction type per Device. If your Device requires both transaction types, see Notes on Sending Mixed Transactions to the Same Device. Interrupt Transactions Interrupt transactions blocks the transaction routine until the transaction completes, thus allowing the CPU to run other tasks. An application task can queue multiple transactions, and the driver automatically handles them one by one in the interrupt service routine (ISR). It allows the task to switch to other procedures until all the transactions are complete. Polling Transactions Polling transactions do not use interrupts. The routine keeps polling the SPI Host's status bit until the transaction is finished. All the tasks that use interrupt transactions can be blocked by the queue. At this point, they need to wait for the ISR to run twice before the transaction is finished. Polling transactions save time otherwise spent on queue handling and context switching, which results in smaller transaction duration. The disadvantage is that the CPU is busy while these transactions are in progress. The spi_device_polling_end() routine needs an overhead of at least 1 µs to unblock other tasks when the transaction is finished. It is strongly recommended to wrap a series of polling transactions using the functions spi_device_acquire_bus() and spi_device_release_bus() to avoid the overhead. For more information, see Bus Acquiring. Transaction Line Mode Supported line modes for ESP32 are listed as follows, to make use of these modes, set the member flags in the struct spi_transaction_t as shown in the Transaction Flag column. If you want to check if corresponding IO pins are set or not, set the member flags in the spi_bus_config_t as shown in the Bus IO setting Flag column. | Mode name | Command Line Width | Address Line Width | Data Line Width | Transaction Flag | Bus IO Setting Flag | Normal SPI | 1 | 1 | 1 | 0 | 0 | Dual Output | 1 | 1 | 2 | SPI_TRANS_MODE_DIO | SPICOMMON_BUSFLAG_DUAL | Dual I/O | 1 | 2 | 2 | SPI_TRANS_MODE_DIO SPI_TRANS_MULTILINE_ADDR | SPICOMMON_BUSFLAG_DUAL | Quad Output | 1 | 1 | 4 | SPI_TRANS_MODE_QIO | SPICOMMON_BUSFLAG_QUAD | Quad I/O | 1 | 4 | 4 | SPI_TRANS_MODE_QIO SPI_TRANS_MULTILINE_ADDR | SPICOMMON_BUSFLAG_QUAD Command and Address Phases During the Command and Address phases, the members spi_transaction_t::cmd and spi_transaction_t::addr are sent to the bus, nothing is read at this time. The default lengths of the Command and Address phases are set in spi_device_interface_config_t by calling spi_bus_add_device(). If the flags SPI_TRANS_VARIABLE_CMD and SPI_TRANS_VARIABLE_ADDR in the member spi_transaction_t::flags are not set, the driver automatically sets the length of these phases to default values during Device initialization. If the lengths of the Command and Address phases need to be variable, declare the struct spi_transaction_ext_t, set the flags SPI_TRANS_VARIABLE_CMD and/or SPI_TRANS_VARIABLE_ADDR in the member spi_transaction_ext_t::base and configure the rest of base as usual. Then the length of each phase will be equal to spi_transaction_ext_t::command_bits and spi_transaction_ext_t::address_bits set in the struct spi_transaction_ext_t. If the Command and Address phase need to have the same number of lines as the data phase, you need to set SPI_TRANS_MULTILINE_CMD and/or SPI_TRANS_MULTILINE_ADDR to the flags member in the struct spi_transaction_t. Also see Transaction Line Mode. Write and Read Phases Normally, the data that needs to be transferred to or from a Device is read from or written to a chunk of memory indicated by the members spi_transaction_t::rx_buffer and spi_transaction_t::tx_buffer. If DMA is enabled for transfers, the buffers are required to be: - Allocated in DMA-capable internal memory (MALLOC_CAP_DMA), see DMA-Capable Memory. - 32-bit aligned (starting from a 32-bit boundary and having a length of multiples of 4 bytes). If these requirements are not satisfied, the transaction efficiency will be affected due to the allocation and copying of temporary buffers. If using more than one data line to transmit, please set SPI_DEVICE_HALFDUPLEX flag for the member flags in the struct spi_device_interface_config_t. And the member flags in the struct spi_transaction_t should be set as described in Transaction Line Mode. Note Half-duplex transactions with both Read and Write phases are not supported when using DMA. For details and workarounds, see Known Issues. Bus Acquiring Sometimes you might want to send SPI transactions exclusively and continuously so that it takes as little time as possible. For this, you can use bus acquiring, which helps to suspend transactions (both polling or interrupt) to other Devices until the bus is released. To acquire and release a bus, use the functions spi_device_acquire_bus() and spi_device_release_bus(). Driver Usage Initialize an SPI bus by calling the function spi_bus_initialize(). Make sure to set the correct I/O pins in the struct spi_bus_config_t. Set the signals that are not needed to -1. Register a Device connected to the bus with the driver by calling the function spi_bus_add_device(). Make sure to configure any timing requirements the Device might need with the parameter dev_config. You should now have obtained the Device's handle which will be used when sending a transaction to it. To interact with the Device, fill one or more spi_transaction_tstructs with any transaction parameters required. Then send the structs either using a polling transaction or an interrupt transaction: - Interrupt Either queue all transactions by calling the function spi_device_queue_trans()and, at a later time, query the result using the function spi_device_get_trans_result(), or handle all requests synchronously by feeding them into spi_device_transmit(). - Polling Call the function spi_device_polling_transmit()to send polling transactions. Alternatively, if you want to insert something in between, send the transactions by using spi_device_polling_start()and spi_device_polling_end(). - (Optional) To perform back-to-back transactions with a Device, call the function spi_device_acquire_bus()before sending transactions and spi_device_release_bus()after the transactions have been sent. (Optional) To remove a certain Device from the bus, call spi_bus_remove_device()with the Device handle as an argument. (Optional) To remove the driver from the bus, make sure no more devices are attached and call spi_bus_free(). The example code for the SPI Master driver can be found in the peripherals/spi_master directory of ESP-IDF examples. Transactions with Data Not Exceeding 32 Bits When the transaction data size is equal to or less than 32 bits, it will be sub-optimal to allocate a buffer for the data. The data can be directly stored in the transaction struct instead. For transmitted data, it can be achieved by using the spi_transaction_t::tx_data member and setting the SPI_TRANS_USE_TXDATA flag on the transmission. For received data, use spi_transaction_t::rx_data and set SPI_TRANS_USE_RXDATA. In both cases, do not touch the spi_transaction_t::tx_buffer or spi_transaction_t::rx_buffer members, because they use the same memory locations as spi_transaction_t::tx_data and spi_transaction_t::rx_data. Transactions with Integers Other than uint8_t An SPI Host reads and writes data into memory byte by byte. By default, data is sent with the most significant bit (MSB) first, as LSB is first used in rare cases. If a value of fewer than 8 bits needs to be sent, the bits should be written into memory in the MSB first manner. For example, if 0b00010 needs to be sent, it should be written into a uint8_t variable, and the length for reading should be set to 5 bits. The Device will still receive 8 bits with 3 additional "random" bits, so the reading must be performed correctly. On top of that, ESP32 is a little-endian chip, which means that the least significant byte of uint16_t and uint32_t variables is stored at the smallest address. Hence, if uint16_t is stored in memory, bits [7:0] are sent first, followed by bits [15:8]. For cases when the data to be transmitted has a size differing from uint8_t arrays, the following macros can be used to transform data to the format that can be sent by the SPI driver directly: SPI_SWAP_DATA_TXfor data to be transmitted SPI_SWAP_DATA_RXfor data received Notes on Sending Mixed Transactions to the Same Device To reduce coding complexity, send only one type of transaction (interrupt or polling) to one Device. However, you still can send both interrupt and polling transactions alternately. The notes below explain how to do this. The polling transactions should be initiated only after all the polling and interrupt transactions are finished. Since an unfinished polling transaction blocks other transactions, please do not forget to call the function spi_device_polling_end() after spi_device_polling_start() to allow other transactions or to allow other Devices to use the bus. Remember that if there is no need to switch to other tasks during your polling transaction, you can initiate a transaction with spi_device_polling_transmit() so that it will be ended automatically. In-flight polling transactions are disturbed by the ISR operation to accommodate interrupt transactions. Always make sure that all the interrupt transactions sent to the ISR are finished before you call spi_device_polling_start(). To do that, you can keep calling spi_device_get_trans_result() until all the transactions are returned. To have better control of the calling sequence of functions, send mixed transactions to the same Device only within a single task. Notes on Using the SPI Master Driver on SPI1 Bus Note Though the SPI Bus Lock feature makes it possible to use SPI Master driver on the SPI1 bus, it is still tricky and needs a lot of special treatment. It is a feature for advanced developers. To use SPI Master driver on SPI1 bus, you have to take care of two problems: The code and data should be in the internal memory when the driver is operating on SPI1 bus. SPI1 bus is shared among Devices and the cache for data (code) in the flash as well as the PSRAM. The cache should be disabled when other drivers are operating on the SPI1 bus. Hence the data (code) in the flash as well as the PSRAM cannot be fetched while the driver acquires the SPI1 bus by: Explicit bus acquiring between spi_device_acquire_bus()and spi_device_release_bus(). Implicit bus acquiring between spi_device_polling_start()and spi_device_polling_end()(or inside spi_device_polling_transmit()). During the time above, all other tasks and most ISRs will be disabled (see IRAM-Safe Interrupt Handlers). Application code and data used by the current task should be placed in internal memory (DRAM or IRAM), or already in the ROM. Access to external memory (flash code, const data in the flash, and static/heap data in the PSRAM) will cause a Cache disabled but cached memory region accessedexception. For differences between IRAM, DRAM, and flash cache, please refer to the application memory layout documentation. To place functions into the IRAM, you can either: Add IRAM_ATTR(include esp_attr.h) to the function like: IRAM_ATTR void foo(void) { } Please note that when a function is inlined, it will follow its caller's segment, and the attribute will not take effect. You may need to use NOLINE_ATTRto avoid this. Please also note that the compiler may transform some code into a lookup table in the const data, so noflash_textis not safe. Use the noflashplacement in the linker.lf. See more in Linker Script Generation. Please note that the compiler may transform some code into a lookup table in the const data, so noflash_textis not safe. Please do take care that the optimization level may affect the compiler behavior of inline, or transform some code into a lookup table in the const data, etc. To place data into the DRAM, you can either: Add DRAM_ATTR(include esp_attr.h) to the data definition like: DRAM_ATTR int g_foo = 3; Use the noflashplacement in the linker.lf. See more in Linker Script Generation. - Please also see the example peripherals/spi_master/hd_eeprom. GPIO Matrix and IO_MUX Most of ESP32's peripheral signals have a direct connection to their dedicated IO_MUX pins. However, the signals can also be routed to any other available pins using the less direct GPIO matrix. If at least one signal is routed through the GPIO matrix, then all signals will be routed through it. The GPIO matrix introduces flexibility of routing but also brings the following disadvantages: Increases the input delay of the MISO signal, which makes MISO setup time violations more likely. If SPI needs to operate at high speeds, use dedicated IO_MUX pins. Allows signals with clock frequencies only up to 40 MHz, as opposed to 80 MHz if IO_MUX pins are used. Note For more details about the influence of the MISO input delay on the maximum clock frequency, see Timing Considerations. The IO_MUX pins for SPI buses are given below. | Pin Name | SPI 2 (GPIO Number) | SPI 3 (GPIO Number) | CS0 1 | 15 | 5 | SCLK | 14 | 18 | MISO | 12 | 19 | MOSI | 13 | 23 | QUADWP | 2 | 22 | QUADHD | 4 | 21 - 1 Only the first Device attached to the bus can use the CS0 pin. Transfer Speed Considerations There are three factors limiting the transfer speed: Transaction interval SPI clock frequency Cache miss of SPI functions, including callbacks The main parameter that determines the transfer speed for large transactions is clock frequency. For multiple small transactions, the transfer speed is mostly determined by the length of transaction intervals. Transaction Duration Transaction duration includes setting up SPI peripheral registers, copying data to FIFOs or setting up DMA links, and the time for SPI transactions. Interrupt transactions allow appending extra overhead to accommodate the cost of FreeRTOS queues and the time needed for switching between tasks and the ISR. For interrupt transactions, the CPU can switch to other tasks when a transaction is in progress. This saves CPU time but increases the transaction duration. See Interrupt Transactions. For polling transactions, it does not block the task but allows to do polling when the transaction is in progress. For more information, see Polling Transactions. If DMA is enabled, setting up the linked list requires about 2 µs per transaction. When a master is transferring data, it automatically reads the data from the linked list. If DMA is not enabled, the CPU has to write and read each byte from the FIFO by itself. Usually, this is faster than 2 µs, but the transaction length is limited to 64 bytes for both write and read. The typical transaction duration for one byte of data is given below. Interrupt Transaction via DMA: 28 µs. Interrupt Transaction via CPU: 25 µs. Polling Transaction via DMA: 10 µs. Polling Transaction via CPU: 8 µs. Note that these data are tested with CONFIG_SPI_MASTER_ISR_IN_IRAM enabled. SPI transaction related code are placed in the internal memory. If this option is turned off (for example, for internal memory optimization), the transaction duration may be affected. SPI Clock Frequency The clock source of the GPSPI peripherals can be selected by setting spi_device_handle_t::cfg::clock_source. You can refer to spi_clock_source_t to know the supported clock sources. By default driver sets spi_device_handle_t::cfg::clock_source to SPI_CLK_SRC_DEFAULT. This usually stands for the highest frequency among GPSPI clock sources. Its value is different among chips. The actual clock frequency of a Device may not be exactly equal to the number you set, it is re-calculated by the driver to the nearest hardware-compatible number, and not larger than the clock frequency of the clock source. You can call spi_device_get_actual_freq() to know the actual frequency computed by the driver. The theoretical maximum transfer speed of the Write or Read phase can be calculated according to the table below: | Line Width of Write/Read phase | Speed (Bps) | 1-Line | SPI Frequency / 8 | 2-Line | SPI Frequency / 4 | 4-Line | SPI Frequency / 2 The transfer speed calculation of other phases (Command, Address, Dummy) is similar. If the clock frequency is too high, the use of some functions might be limited. See Timing Considerations. Cache Missing The default config puts only the ISR into the IRAM. Other SPI-related functions, including the driver itself and the callback, might suffer from cache misses and need to wait until the code is read from flash. Select CONFIG_SPI_MASTER_IN_IRAM to put the whole SPI driver into IRAM and put the entire callback(s) and its callee functions into IRAM to prevent cache missing. Note SPI driver implementation is based on FreeRTOS APIs, to use CONFIG_SPI_MASTER_IN_IRAM, you should not enable CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH. For an interrupt transaction, the overall cost is 20+8n/Fspi[MHz] [µs] for n bytes transferred in one transaction. Hence, the transferring speed is: n/(20+8n/Fspi). An example of transferring speed at 8 MHz clock speed is given in the following table. | Frequency (MHz) | Transaction Interval (µs) | Transaction Length (bytes) | Total Time (µs) | Total Speed (KBps) | 8 | 25 | 1 | 26 | 38.5 | 8 | 25 | 8 | 33 | 242.4 | 8 | 25 | 16 | 41 | 490.2 | 8 | 25 | 64 | 89 | 719.1 | 8 | 25 | 128 | 153 | 836.6 When a transaction length is short, the cost of the transaction interval is high. If possible, try to squash several short transactions into one transaction to achieve a higher transfer speed. Please note that the ISR is disabled during flash operation by default. To keep sending transactions during flash operations, enable CONFIG_SPI_MASTER_ISR_IN_IRAM and set ESP_INTR_FLAG_IRAM in the member spi_bus_config_t::intr_flags. In this case, all the transactions queued before starting flash operations are handled by the ISR in parallel. Also note that the callback of each Device and their callee functions should be in IRAM, or your callback will crash due to cache missing. For more details, see IRAM-Safe Interrupt Handlers. Timing Considerations As shown in the figure below, there is a delay on the MISO line after the SCLK launch edge and before the signal is latched by the internal register. As a result, the MISO pin setup time is the limiting factor for the SPI clock speed. When the delay is too long, the setup slack is < 0, which means the setup timing requirement is violated and the reading might be incorrect. The maximum allowed frequency is dependent on: spi_device_interface_config_t::input_delay_ns- maximum data valid time on the MISO bus after a clock cycle on SCLK starts If the IO_MUX pin or the GPIO Matrix is used When the GPIO matrix is used, the maximum allowed frequency is reduced to about 33 ~ 77% in comparison to the existing input delay. To retain a higher frequency, you have to use the IO_MUX pins or the dummy bit workaround. You can obtain the maximum reading frequency of the master by using the function spi_get_freq_limit(). Dummy bit workaround: Dummy clocks, during which the Host does not read data, can be inserted before the Read phase begins. The Device still sees the dummy clocks and sends out data, but the Host does not read until the Read phase comes. This compensates for the lack of the MISO setup time required by the Host and allows the Host to do reading at a higher frequency. In the ideal case, if the Device is so fast that the input delay is shorter than an APB clock cycle - 12.5 ns - the maximum frequency at which the Host can read (or read and write) in different conditions is as follows: | Frequency Limit (MHz) | Frequency Limit (MHz) | Dummy Bits Used by Driver | Comments | GPIO Matrix | IO_MUX Pins | 26.6 | 80 | No | 40 | -- | Yes | Half-duplex, no DMA allowed If the Host only writes data, the dummy bit workaround and the frequency check can be disabled by setting the bit SPI_DEVICE_NO_DUMMY in the member spi_device_interface_config_t::flags. When disabled, the output frequency can be 80 MHz, even if the GPIO matrix is used. spi_device_interface_config_t::flags The SPI Master driver still works even if the spi_device_interface_config_t::input_delay_ns in the structure spi_device_interface_config_t is set to 0. However, setting an accurate value helps to: Calculate the frequency limit for full-duplex transactions Compensate the timing correctly with dummy bits for half-duplex transactions You can approximate the maximum data valid time after the launch edge of SPI clocks by checking the statistics in the AC characteristics chapter of your Device's specification or measure the time using an oscilloscope or logic analyzer. Please note that the actual PCB layout design and excessive loads may increase the input delay. It means that non-optimal wiring and/or a load capacitor on the bus will most likely lead to input delay values exceeding the values given in the Device specification or measured while the bus is floating. Some typical delay values are shown in the following table. These data are retrieved when the slave Device is on a different physical chip. | Device | Input Delay (ns) | Ideal Device | 0 | ESP32 slave using IO_MUX | 50 | ESP32 slave using GPIO_MATRIX | 75 The MISO path delay (valid time) consists of a slave's input delay plus the master's GPIO matrix delay. The delay determines the above frequency limit for full-duplex transfers. Once exceeding, full-duplex transfers will not work as well as the half-duplex transactions that use dummy bits. The frequency limit is: Freq limit [MHz] = 80 / (floor(MISO delay[ns]/12.5) + 1) The figure below shows the relationship between frequency limit and input delay. Two extra APB clock cycle periods should be added to the MISO delay if the master uses the GPIO matrix. Corresponding frequency limits for different Devices with different input delay times are shown in the table below. When the master is IO_MUX (0 ns): | Input Delay (ns) | MISO Path Delay (ns) | Freq. Limit (MHz) | 0 | 0 | 80 | 50 | 50 | 16 | 75 | 75 | 11.43 When the master is GPIO_MATRIX (25 ns): | Input Delay (ns) | MISO Path Delay (ns) | Freq. Limit (MHz) | 0 | 25 | 26.67 | 50 | 75 | 11.43 | 75 | 100 | 8.89 Known Issues Half-duplex transactions are not compatible with DMA when both the Write and Read phases are used. If such transactions are required, you have to use one of the alternative solutions: Use full-duplex transactions instead. - Disable DMA by setting the bus initialization function's last parameter to 0 as follows: ret=spi_bus_initialize(VSPI_HOST, &buscfg, 0); This can prohibit you from transmitting and receiving data longer than 64 bytes. 3. Try using the command and address fields to replace the Write phase. - Full-duplex transactions are not compatible with the dummy bit workaround, hence the frequency is limited. See dummy bit speed-up workaround. dummy_bitsin spi_device_interface_config_tand spi_transaction_ext_tare not available when SPI Read and Write phases are both enabled (regardless of full duplex or half duplex mode). cs_ena_pretransis not compatible with the Command and Address phases of full-duplex transactions. Application Example The code example for using the SPI master half duplex mode to read/write an AT93C46D EEPROM (8-bit mode) can be found in the peripherals/spi_master/hd_eeprom directory of ESP-IDF examples. The code example for using the SPI master full duplex mode to drive a SPI_LCD (e.g. ST7789V or ILI9341) can be found in the peripherals/spi_master/lcd directory of ESP-IDF examples. API Reference - SPI Common Header File This header file can be included with: #include "hal/spi_types.h" Structures - struct spi_line_mode_t Line mode of SPI transaction phases: CMD, ADDR, DOUT/DIN. Type Definitions - typedef soc_periph_spi_clk_src_t spi_clock_source_t Type of SPI clock source. Enumerations - enum spi_host_device_t Enum with the three SPI peripherals that are software-accessible in it. Values: - enumerator SPI1_HOST SPI1. - enumerator SPI2_HOST SPI2. - enumerator SPI3_HOST SPI3. - enumerator SPI_HOST_MAX invalid host value - enumerator SPI1_HOST - enum spi_event_t SPI Events. Values: - enumerator SPI_EV_BUF_TX The buffer has sent data to master. - enumerator SPI_EV_BUF_RX The buffer has received data from master. - enumerator SPI_EV_SEND_DMA_READY Slave has loaded its TX data buffer to the hardware (DMA). - enumerator SPI_EV_SEND Master has received certain number of the data, the number is determined by Master. - enumerator SPI_EV_RECV_DMA_READY Slave has loaded its RX data buffer to the hardware (DMA). - enumerator SPI_EV_RECV Slave has received certain number of data from master, the number is determined by Master. - enumerator SPI_EV_CMD9 Received CMD9 from master. - enumerator SPI_EV_CMDA Received CMDA from master. - enumerator SPI_EV_TRANS A transaction has done. - enumerator SPI_EV_BUF_TX - enum spi_command_t SPI command. Values: - enumerator SPI_CMD_HD_WRBUF - enumerator SPI_CMD_HD_RDBUF - enumerator SPI_CMD_HD_WRDMA - enumerator SPI_CMD_HD_RDDMA - enumerator SPI_CMD_HD_SEG_END - enumerator SPI_CMD_HD_EN_QPI - enumerator SPI_CMD_HD_WR_END - enumerator SPI_CMD_HD_INT0 - enumerator SPI_CMD_HD_INT1 - enumerator SPI_CMD_HD_INT2 - enumerator SPI_CMD_HD_WRBUF Header File This header file can be included with: #include "driver/spi_common.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t spi_bus_initialize(spi_host_device_t host_id, const spi_bus_config_t *bus_config, spi_dma_chan_t dma_chan) Initialize a SPI bus. Warning SPI0/1 is not supported Warning If a DMA channel is selected, any transmit and receive buffer used should be allocated in DMA-capable memory. Warning The ISR of SPI is always executed on the core which calls this function. Never starve the ISR on this core or the SPI transactions will not be handled. - Parameters host_id -- SPI peripheral that controls this bus bus_config -- Pointer to a spi_bus_config_t struct specifying how the host should be initialized dma_chan -- - Selecting a DMA channel for an SPI bus allows transactions on the bus with size only limited by the amount of internal memory. Selecting SPI_DMA_DISABLED limits the size of transactions. Set to SPI_DMA_DISABLED if only the SPI flash uses this bus. Set to SPI_DMA_CH_AUTO to let the driver to allocate the DMA channel. - - - Returns ESP_ERR_INVALID_ARG if configuration is invalid ESP_ERR_INVALID_STATE if host already is in use ESP_ERR_NOT_FOUND if there is no available DMA channel ESP_ERR_NO_MEM if out of memory ESP_OK on success - - esp_err_t spi_bus_free(spi_host_device_t host_id) Free a SPI bus. Warning In order for this to succeed, all devices have to be removed first. - Parameters host_id -- SPI peripheral to free - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if bus hasn't been initialized before, or not all devices on the bus are freed ESP_OK on success - Structures - struct spi_bus_config_t This is a configuration structure for a SPI bus. You can use this structure to specify the GPIO pins of the bus. Normally, the driver will use the GPIO matrix to route the signals. An exception is made when all signals either can be routed through the IO_MUX or are -1. In that case, the IO_MUX is used, allowing for >40MHz speeds. Note Be advised that the slave driver does not use the quadwp/quadhd lines and fields in spi_bus_config_t refering to these lines will be ignored and can thus safely be left uninitialized. Public Members - int mosi_io_num GPIO pin for Master Out Slave In (=spi_d) signal, or -1 if not used. - int data0_io_num GPIO pin for spi data0 signal in quad/octal mode, or -1 if not used. - int miso_io_num GPIO pin for Master In Slave Out (=spi_q) signal, or -1 if not used. - int data1_io_num GPIO pin for spi data1 signal in quad/octal mode, or -1 if not used. - int sclk_io_num GPIO pin for SPI Clock signal, or -1 if not used. - int quadwp_io_num GPIO pin for WP (Write Protect) signal, or -1 if not used. - int data2_io_num GPIO pin for spi data2 signal in quad/octal mode, or -1 if not used. - int quadhd_io_num GPIO pin for HD (Hold) signal, or -1 if not used. - int data3_io_num GPIO pin for spi data3 signal in quad/octal mode, or -1 if not used. - int data4_io_num GPIO pin for spi data4 signal in octal mode, or -1 if not used. - int data5_io_num GPIO pin for spi data5 signal in octal mode, or -1 if not used. - int data6_io_num GPIO pin for spi data6 signal in octal mode, or -1 if not used. - int data7_io_num GPIO pin for spi data7 signal in octal mode, or -1 if not used. - int max_transfer_sz Maximum transfer size, in bytes. Defaults to 4092 if 0 when DMA enabled, or to SOC_SPI_MAXIMUM_BUFFER_SIZEif DMA is disabled. - uint32_t flags Abilities of bus to be checked by the driver. Or-ed value of SPICOMMON_BUSFLAG_*flags. - esp_intr_cpu_affinity_t isr_cpu_id Select cpu core to register SPI ISR. - int intr_flags Interrupt flag for the bus to set the priority, and IRAM attribute, see esp_intr_alloc.h. Note that the EDGE, INTRDISABLED attribute are ignored by the driver. Note that if ESP_INTR_FLAG_IRAM is set, ALL the callbacks of the driver, and their callee functions, should be put in the IRAM. - int mosi_io_num Macros - SPI_MAX_DMA_LEN - SPI_SWAP_DATA_TX(DATA, LEN) Transform unsigned integer of length <= 32 bits to the format which can be sent by the SPI driver directly. E.g. to send 9 bits of data, you can: uint16_t data = SPI_SWAP_DATA_TX(0x145, 9); Then points tx_buffer to &data. - Parameters DATA -- Data to be sent, can be uint8_t, uint16_t or uint32_t. LEN -- Length of data to be sent, since the SPI peripheral sends from the MSB, this helps to shift the data to the MSB. - - SPI_SWAP_DATA_RX(DATA, LEN) Transform received data of length <= 32 bits to the format of an unsigned integer. E.g. to transform the data of 15 bits placed in a 4-byte array to integer: uint16_t data = SPI_SWAP_DATA_RX(*(uint32_t*)t->rx_data, 15); - Parameters DATA -- Data to be rearranged, can be uint8_t, uint16_t or uint32_t. LEN -- Length of data received, since the SPI peripheral writes from the MSB, this helps to shift the data to the LSB. - - SPICOMMON_BUSFLAG_SLAVE Initialize I/O in slave mode. - SPICOMMON_BUSFLAG_MASTER Initialize I/O in master mode. - SPICOMMON_BUSFLAG_IOMUX_PINS Check using iomux pins. Or indicates the pins are configured through the IO mux rather than GPIO matrix. - SPICOMMON_BUSFLAG_GPIO_PINS Force the signals to be routed through GPIO matrix. Or indicates the pins are routed through the GPIO matrix. - SPICOMMON_BUSFLAG_SCLK Check existing of SCLK pin. Or indicates CLK line initialized. - SPICOMMON_BUSFLAG_MISO Check existing of MISO pin. Or indicates MISO line initialized. - SPICOMMON_BUSFLAG_MOSI Check existing of MOSI pin. Or indicates MOSI line initialized. - SPICOMMON_BUSFLAG_DUAL Check MOSI and MISO pins can output. Or indicates bus able to work under DIO mode. - SPICOMMON_BUSFLAG_WPHD Check existing of WP and HD pins. Or indicates WP & HD pins initialized. - SPICOMMON_BUSFLAG_QUAD Check existing of MOSI/MISO/WP/HD pins as output. Or indicates bus able to work under QIO mode. - SPICOMMON_BUSFLAG_IO4_IO7 Check existing of IO4~IO7 pins. Or indicates IO4~IO7 pins initialized. - SPICOMMON_BUSFLAG_OCTAL Check existing of MOSI/MISO/WP/HD/SPIIO4/SPIIO5/SPIIO6/SPIIO7 pins as output. Or indicates bus able to work under octal mode. - SPICOMMON_BUSFLAG_NATIVE_PINS Type Definitions - typedef spi_common_dma_t spi_dma_chan_t Enumerations - enum spi_common_dma_t SPI DMA channels. Values: - enumerator SPI_DMA_DISABLED Do not enable DMA for SPI. - enumerator SPI_DMA_CH1 Enable DMA, select DMA Channel 1. - enumerator SPI_DMA_CH2 Enable DMA, select DMA Channel 2. - enumerator SPI_DMA_CH_AUTO Enable DMA, channel is automatically selected by driver. - enumerator SPI_DMA_DISABLED API Reference - SPI Master Header File This header file can be included with: #include "driver/spi_master.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t spi_bus_add_device(spi_host_device_t host_id, const spi_device_interface_config_t *dev_config, spi_device_handle_t *handle) Allocate a device on a SPI bus. This initializes the internal structures for a device, plus allocates a CS pin on the indicated SPI master peripheral and routes it to the indicated GPIO. All SPI master devices have three CS pins and can thus control up to three devices. Note While in general, speeds up to 80MHz on the dedicated SPI pins and 40MHz on GPIO-matrix-routed pins are supported, full-duplex transfers routed over the GPIO matrix only support speeds up to 26MHz. - Parameters host_id -- SPI peripheral to allocate device on dev_config -- SPI interface protocol config for the device handle -- Pointer to variable to hold the device handle - - Returns ESP_ERR_INVALID_ARG if parameter is invalid or configuration combination is not supported (e.g. dev_config->post_cbisn't set while flag SPI_DEVICE_NO_RETURN_RESULTis enabled) ESP_ERR_INVALID_STATE if selected clock source is unavailable or spi bus not initialized ESP_ERR_NOT_FOUND if host doesn't have any free CS slots ESP_ERR_NO_MEM if out of memory ESP_OK on success - - esp_err_t spi_bus_remove_device(spi_device_handle_t handle) Remove a device from the SPI bus. - Parameters handle -- Device handle to free - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if device already is freed ESP_OK on success - - esp_err_t spi_device_queue_trans(spi_device_handle_t handle, spi_transaction_t *trans_desc, TickType_t ticks_to_wait) Queue a SPI transaction for interrupt transaction execution. Get the result by spi_device_get_trans_result. Note Normally a device cannot start (queue) polling and interrupt transactions simultaneously. - Parameters handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute ticks_to_wait -- Ticks to wait until there's room in the queue; use portMAX_DELAY to never time out. - - Returns ESP_ERR_INVALID_ARG if parameter is invalid. This can happen if SPI_TRANS_CS_KEEP_ACTIVE flag is specified while the bus was not acquired ( spi_device_acquire_bus()should be called first) or set flag SPI_TRANS_DMA_BUFFER_ALIGN_MANUAL but tx or rx buffer not DMA-capable, or addr&len not align to cache line size ESP_ERR_TIMEOUT if there was no room in the queue before ticks_to_wait expired ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed ESP_ERR_INVALID_STATE if previous transactions are not finished ESP_OK on success - - esp_err_t spi_device_get_trans_result(spi_device_handle_t handle, spi_transaction_t **trans_desc, TickType_t ticks_to_wait) Get the result of a SPI transaction queued earlier by spi_device_queue_trans. This routine will wait until a transaction to the given device succesfully completed. It will then return the description of the completed transaction so software can inspect the result and e.g. free the memory or re-use the buffers. - Parameters handle -- Device handle obtained using spi_host_add_dev trans_desc -- Pointer to variable able to contain a pointer to the description of the transaction that is executed. The descriptor should not be modified until the descriptor is returned by spi_device_get_trans_result. ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if flag SPI_DEVICE_NO_RETURN_RESULTis set ESP_ERR_TIMEOUT if there was no completed transaction before ticks_to_wait expired ESP_OK on success - - esp_err_t spi_device_transmit(spi_device_handle_t handle, spi_transaction_t *trans_desc) Send a SPI transaction, wait for it to complete, and return the result. This function is the equivalent of calling spi_device_queue_trans() followed by spi_device_get_trans_result(). Do not use this when there is still a transaction separately queued (started) from spi_device_queue_trans() or polling_start/transmit that hasn't been finalized. Note This function is not thread safe when multiple tasks access the same SPI device. Normally a device cannot start (queue) polling and interrupt transactions simutanuously. - Parameters handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success - - esp_err_t spi_device_polling_start(spi_device_handle_t handle, spi_transaction_t *trans_desc, TickType_t ticks_to_wait) Immediately start a polling transaction. Note Normally a device cannot start (queue) polling and interrupt transactions simutanuously. Moreover, a device cannot start a new polling transaction if another polling transaction is not finished. - Parameters handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute ticks_to_wait -- Ticks to wait until there's room in the queue; currently only portMAX_DELAY is supported. - - Returns ESP_ERR_INVALID_ARG if parameter is invalid. This can happen if SPI_TRANS_CS_KEEP_ACTIVE flag is specified while the bus was not acquired ( spi_device_acquire_bus()should be called first) or set flag SPI_TRANS_DMA_BUFFER_ALIGN_MANUAL but tx or rx buffer not DMA-capable, or addr&len not align to cache line size ESP_ERR_TIMEOUT if the device cannot get control of the bus before ticks_to_waitexpired ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed ESP_ERR_INVALID_STATE if previous transactions are not finished ESP_OK on success - - esp_err_t spi_device_polling_end(spi_device_handle_t handle, TickType_t ticks_to_wait) Poll until the polling transaction ends. This routine will not return until the transaction to the given device has succesfully completed. The task is not blocked, but actively busy-spins for the transaction to be completed. - Parameters handle -- Device handle obtained using spi_host_add_dev ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_TIMEOUT if the transaction cannot finish before ticks_to_wait expired ESP_OK on success - - esp_err_t spi_device_polling_transmit(spi_device_handle_t handle, spi_transaction_t *trans_desc) Send a polling transaction, wait for it to complete, and return the result. This function is the equivalent of calling spi_device_polling_start() followed by spi_device_polling_end(). Do not use this when there is still a transaction that hasn't been finalized. Note This function is not thread safe when multiple tasks access the same SPI device. Normally a device cannot start (queue) polling and interrupt transactions simutanuously. - Parameters handle -- Device handle obtained using spi_host_add_dev trans_desc -- Description of transaction to execute - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_TIMEOUT if the device cannot get control of the bus ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed ESP_ERR_INVALID_STATE if previous transactions of same device are not finished ESP_OK on success - - esp_err_t spi_device_acquire_bus(spi_device_handle_t device, TickType_t wait) Occupy the SPI bus for a device to do continuous transactions. Transactions to all other devices will be put off until spi_device_release_busis called. Note The function will wait until all the existing transactions have been sent. - Parameters device -- The device to occupy the bus. wait -- Time to wait before the the bus is occupied by the device. Currently MUST set to portMAX_DELAY. - - Returns ESP_ERR_INVALID_ARG : waitis not set to portMAX_DELAY. ESP_OK : Success. - - void spi_device_release_bus(spi_device_handle_t dev) Release the SPI bus occupied by the device. All other devices can start sending transactions. - Parameters dev -- The device to release the bus. - esp_err_t spi_device_get_actual_freq(spi_device_handle_t handle, int *freq_khz) Calculate working frequency for specific device. - Parameters handle -- SPI device handle freq_khz -- [out] output parameter to hold calculated frequency in kHz - - Returns ESP_ERR_INVALID_ARG : handleor freq_khzparameter is NULL ESP_OK : Success - - int spi_get_actual_clock(int fapb, int hz, int duty_cycle) Calculate the working frequency that is most close to desired frequency. - Parameters fapb -- The frequency of apb clock, should be APB_CLK_FREQ. hz -- Desired working frequency duty_cycle -- Duty cycle of the spi clock - - Returns Actual working frequency that most fit. - void spi_get_timing(bool gpio_is_used, int input_delay_ns, int eff_clk, int *dummy_o, int *cycles_remain_o) Calculate the timing settings of specified frequency and settings. Note If **dummy_o* is not zero, it means dummy bits should be applied in half duplex mode, and full duplex mode may not work. - Parameters gpio_is_used -- True if using GPIO matrix, or False if iomux pins are used. input_delay_ns -- Input delay from SCLK launch edge to MISO data valid. eff_clk -- Effective clock frequency (in Hz) from spi_get_actual_clock(). dummy_o -- Address of dummy bits used output. Set to NULL if not needed. cycles_remain_o -- Address of cycles remaining (after dummy bits are used) output. -1 If too many cycles remaining, suggest to compensate half a clock. 0 If no remaining cycles or dummy bits are not used. positive value: cycles suggest to compensate. - - - int spi_get_freq_limit(bool gpio_is_used, int input_delay_ns) Get the frequency limit of current configurations. SPI master working at this limit is OK, while above the limit, full duplex mode and DMA will not work, and dummy bits will be aplied in the half duplex mode. - Parameters gpio_is_used -- True if using GPIO matrix, or False if native pins are used. input_delay_ns -- Input delay from SCLK launch edge to MISO data valid. - - Returns Frequency limit of current configurations. - esp_err_t spi_bus_get_max_transaction_len(spi_host_device_t host_id, size_t *max_bytes) Get max length (in bytes) of one transaction. - Parameters host_id -- SPI peripheral max_bytes -- [out] Max length of one transaction, in bytes - - Returns ESP_OK: On success ESP_ERR_INVALID_ARG: Invalid argument - Structures - struct spi_device_interface_config_t This is a configuration for a SPI slave device that is connected to one of the SPI buses. Public Members - uint8_t command_bits Default amount of bits in command phase (0-16), used when SPI_TRANS_VARIABLE_CMDis not used, otherwise ignored. - uint8_t address_bits Default amount of bits in address phase (0-64), used when SPI_TRANS_VARIABLE_ADDRis not used, otherwise ignored. - uint8_t dummy_bits Amount of dummy bits to insert between address and data phase. - uint8_t mode SPI mode, representing a pair of (CPOL, CPHA) configuration: 0: (0, 0) 1: (0, 1) 2: (1, 0) 3: (1, 1) - - spi_clock_source_t clock_source Select SPI clock source, SPI_CLK_SRC_DEFAULTby default. - uint16_t duty_cycle_pos Duty cycle of positive clock, in 1/256th increments (128 = 50%/50% duty). Setting this to 0 (=not setting it) is equivalent to setting this to 128. - uint16_t cs_ena_pretrans Amount of SPI bit-cycles the cs should be activated before the transmission (0-16). This only works on half-duplex transactions. - uint8_t cs_ena_posttrans Amount of SPI bit-cycles the cs should stay active after the transmission (0-16) - int clock_speed_hz SPI clock speed in Hz. Derived from clock_source. - int input_delay_ns Maximum data valid time of slave. The time required between SCLK and MISO valid, including the possible clock delay from slave to master. The driver uses this value to give an extra delay before the MISO is ready on the line. Leave at 0 unless you know you need a delay. For better timing performance at high frequency (over 8MHz), it's suggest to have the right value. - int spics_io_num CS GPIO pin for this device, or -1 if not used. - uint32_t flags Bitwise OR of SPI_DEVICE_* flags. - int queue_size Transaction queue size. This sets how many transactions can be 'in the air' (queued using spi_device_queue_trans but not yet finished using spi_device_get_trans_result) at the same time. - transaction_cb_t pre_cb Callback to be called before a transmission is started. This callback is called within interrupt context should be in IRAM for best performance, see "Transferring Speed" section in the SPI Master documentation for full details. If not, the callback may crash during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM. - transaction_cb_t post_cb Callback to be called after a transmission has completed. This callback is called within interrupt context should be in IRAM for best performance, see "Transferring Speed" section in the SPI Master documentation for full details. If not, the callback may crash during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM. - uint8_t command_bits - struct spi_transaction_t This structure describes one SPI transaction. The descriptor should not be modified until the transaction finishes. Public Members - uint32_t flags Bitwise OR of SPI_TRANS_* flags. - uint16_t cmd Command data, of which the length is set in the command_bitsof spi_device_interface_config_t. NOTE: this field, used to be "command" in ESP-IDF 2.1 and before, is re-written to be used in a new way in ESP-IDF 3.0. Example: write 0x0123 and command_bits=12 to send command 0x12, 0x3_ (in previous version, you may have to write 0x3_12). - uint64_t addr Address data, of which the length is set in the address_bitsof spi_device_interface_config_t. NOTE: this field, used to be "address" in ESP-IDF 2.1 and before, is re-written to be used in a new way in ESP-IDF3.0. Example: write 0x123400 and address_bits=24 to send address of 0x12, 0x34, 0x00 (in previous version, you may have to write 0x12340000). - size_t length Total data length, in bits. - size_t rxlength Total data length received, should be not greater than lengthin full-duplex mode (0 defaults this to the value of length). - void *user User-defined variable. Can be used to store eg transaction ID. - const void *tx_buffer Pointer to transmit buffer, or NULL for no MOSI phase. - uint8_t tx_data[4] If SPI_TRANS_USE_TXDATA is set, data set here is sent directly from this variable. - void *rx_buffer Pointer to receive buffer, or NULL for no MISO phase. Written by 4 bytes-unit if DMA is used. - uint8_t rx_data[4] If SPI_TRANS_USE_RXDATA is set, data is received directly to this variable. - uint32_t flags - struct spi_transaction_ext_t This struct is for SPI transactions which may change their address and command length. Please do set the flags in base to SPI_TRANS_VARIABLE_CMD_ADRto use the bit length here. Public Members - struct spi_transaction_t base Transaction data, so that pointer to spi_transaction_t can be converted into spi_transaction_ext_t. - uint8_t command_bits The command length in this transaction, in bits. - uint8_t address_bits The address length in this transaction, in bits. - uint8_t dummy_bits The dummy length in this transaction, in bits. - struct spi_transaction_t base Macros - SPI_MASTER_FREQ_8M SPI common used frequency (in Hz) Note SPI peripheral only has an integer divider, and the default clock source can be different on other targets, so the actual frequency may be slightly different from the desired frequency. 8MHz - SPI_MASTER_FREQ_9M 8.89MHz - SPI_MASTER_FREQ_10M 10MHz - SPI_MASTER_FREQ_11M 11.43MHz - SPI_MASTER_FREQ_13M 13.33MHz - SPI_MASTER_FREQ_16M 16MHz - SPI_MASTER_FREQ_20M 20MHz - SPI_MASTER_FREQ_26M 26.67MHz - SPI_MASTER_FREQ_40M 40MHz - SPI_MASTER_FREQ_80M 80MHz - SPI_DEVICE_TXBIT_LSBFIRST Transmit command/address/data LSB first instead of the default MSB first. - SPI_DEVICE_RXBIT_LSBFIRST Receive data LSB first instead of the default MSB first. - SPI_DEVICE_BIT_LSBFIRST Transmit and receive LSB first. - SPI_DEVICE_3WIRE Use MOSI (=spid) for both sending and receiving data. - SPI_DEVICE_POSITIVE_CS Make CS positive during a transaction instead of negative. - SPI_DEVICE_HALFDUPLEX Transmit data before receiving it, instead of simultaneously. - SPI_DEVICE_CLK_AS_CS Output clock on CS line if CS is active. - SPI_DEVICE_NO_DUMMY There are timing issue when reading at high frequency (the frequency is related to whether iomux pins are used, valid time after slave sees the clock). In half-duplex mode, the driver automatically inserts dummy bits before reading phase to fix the timing issue. Set this flag to disable this feature. In full-duplex mode, however, the hardware cannot use dummy bits, so there is no way to prevent data being read from getting corrupted. Set this flag to confirm that you're going to work with output only, or read without dummy bits at your own risk. - - SPI_DEVICE_DDRCLK - SPI_DEVICE_NO_RETURN_RESULT Don't return the descriptor to the host on completion (use post_cb to notify instead) - SPI_TRANS_MODE_DIO Transmit/receive data in 2-bit mode. - SPI_TRANS_MODE_QIO Transmit/receive data in 4-bit mode. - SPI_TRANS_USE_RXDATA Receive into rx_data member of spi_transaction_t instead into memory at rx_buffer. - SPI_TRANS_USE_TXDATA Transmit tx_data member of spi_transaction_t instead of data at tx_buffer. Do not set tx_buffer when using this. - SPI_TRANS_MODE_DIOQIO_ADDR Also transmit address in mode selected by SPI_MODE_DIO/SPI_MODE_QIO. - SPI_TRANS_VARIABLE_CMD Use the command_bitsin spi_transaction_ext_trather than default value in spi_device_interface_config_t. - SPI_TRANS_VARIABLE_ADDR Use the address_bitsin spi_transaction_ext_trather than default value in spi_device_interface_config_t. - SPI_TRANS_VARIABLE_DUMMY Use the dummy_bitsin spi_transaction_ext_trather than default value in spi_device_interface_config_t. - SPI_TRANS_CS_KEEP_ACTIVE Keep CS active after data transfer. - SPI_TRANS_MULTILINE_CMD The data lines used at command phase is the same as data phase (otherwise, only one data line is used at command phase) - SPI_TRANS_MODE_OCT Transmit/receive data in 8-bit mode. - SPI_TRANS_MULTILINE_ADDR The data lines used at address phase is the same as data phase (otherwise, only one data line is used at address phase) - SPI_TRANS_DMA_BUFFER_ALIGN_MANUAL By default driver will automatically re-alloc dma buffer if it doesn't meet hardware alignment or dma_capable requirements, this flag is for you to disable this feature, you will need to take care of the alignment otherwise driver will return you error ESP_ERR_INVALID_ARG. Type Definitions - typedef void (*transaction_cb_t)(spi_transaction_t *trans) - typedef struct spi_device_t *spi_device_handle_t Handle for a device on a SPI bus.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/spi_master.html
ESP-IDF Programming Guide v5.2.1 documentation
null
SPI Slave Driver
null
espressif.com
2016-01-01
be8e83dc82729189
null
null
SPI Slave Driver SPI Slave driver is a program that controls ESP32's General Purpose SPI (GP-SPI) peripheral(s) when it functions as a slave. For more hardware information about the GP-SPI peripheral(s), see ESP32 Technical Reference Manual > SPI Controller [PDF]. Terminology The terms used in relation to the SPI slave driver are given in the table below. Term Definition Host The SPI controller peripheral external to ESP32 that initiates SPI transmissions over the bus, and acts as an SPI Master. Device SPI slave device (general purpose SPI controller). Each Device shares the MOSI, MISO and SCLK signals but is only active on the bus when the Host asserts the Device's individual CS line. Bus A signal bus, common to all Devices connected to one Host. In general, a bus includes the following lines: MISO, MOSI, SCLK, one or more CS lines, and, optionally, QUADWP and QUADHD. So Devices are connected to the same lines, with the exception that each Device has its own CS line. Several Devices can also share one CS line if connected in the daisy-chain manner. MISO Master In, Slave Out, a.k.a. Q. Data transmission from a Device to Host. MOSI Master Out, Slave In, a.k.a. D. Data transmission from a Host to Device. SCLK Serial Clock. Oscillating signal generated by a Host that keeps the transmission of data bits in sync. CS Chip Select. Allows a Host to select individual Device(s) connected to the bus in order to send or receive data. QUADWP Write Protect signal. Only used for 4-bit (qio/qout) transactions. QUADHD Hold signal. Only used for 4-bit (qio/qout) transactions. Assertion The action of activating a line. The opposite action of returning the line back to inactive (back to idle) is called de-assertion. Transaction One instance of a Host asserting a CS line, transferring data to and from a Device, and de-asserting the CS line. Transactions are atomic, which means they can never be interrupted by another transaction. Launch Edge Edge of the clock at which the source register launches the signal onto the line. Latch Edge Edge of the clock at which the destination register latches in the signal. Driver Features The SPI slave driver allows using the SPI peripherals as full-duplex Devices. The driver can send/receive transactions up to 64 bytes in length, or utilize DMA to send/receive longer transactions. However, there are some known issues related to DMA. The SPI slave driver supports registering the SPI ISR to a certain CPU core. If multiple tasks try to access the same SPI Device simultaneously, it is recommended that your application be refactored so that each SPI peripheral is only accessed by a single task at a time. Please also use spi_bus_config_t::isr_cpu_id to register the SPI ISR to the same core as SPI peripheral related tasks to ensure thread safety. SPI Transactions A full-duplex SPI transaction begins when the Host asserts the CS line and starts sending out clock pulses on the SCLK line. Every clock pulse, a data bit is shifted from the Host to the Device on the MOSI line and back on the MISO line at the same time. At the end of the transaction, the Host de-asserts the CS line. The attributes of a transaction are determined by the configuration structure for an SPI peripheral acting as a slave device spi_slave_interface_config_t , and transaction configuration structure spi_slave_transaction_t . As not every transaction requires both writing and reading data, you can choose to configure the spi_transaction_t structure for TX only, RX only, or TX and RX transactions. If spi_slave_transaction_t::rx_buffer is set to NULL , the read phase will be skipped. Similarly, if spi_slave_transaction_t::tx_buffer is set to NULL , the write phase will be skipped. Note A Host should not start a transaction before its Device is ready for receiving data. It is recommended to use another GPIO pin for a handshake signal to sync the Devices. For more details, see Transaction Interval. Driver Usage Initialize an SPI peripheral as a Device by calling the function spi_slave_initialize() . Make sure to set the correct I/O pins in the struct bus_config. Set the unused signals to -1 . If transactions are expected to be longer than 32 bytes, set the parameter dma_chan to 1 or 2 to allow a DMA channel 1 or 2 respectively. Otherwise, set dma_chan to 0 . Before initiating transactions, fill one or more spi_slave_transaction_t structs with the transaction parameters required. Either queue all transactions by calling the function spi_slave_queue_trans() and, at a later time, query the result by using the function spi_slave_get_trans_result() , or handle all requests individually by feeding them into spi_slave_transmit() . The latter two functions will be blocked until the Host has initiated and finished a transaction, causing the queued data to be sent and received. (Optional) To unload the SPI slave driver, call spi_slave_free() . Transaction Data and Master/Slave Length Mismatches Normally, the data that needs to be transferred to or from a Device is read or written to a chunk of memory indicated by the spi_slave_transaction_t::rx_buffer and spi_slave_transaction_t::tx_buffer . The SPI driver can be configured to use DMA for transfers, in which case these buffers must be allocated in DMA-capable memory using pvPortMallocCaps(size, MALLOC_CAP_DMA) . The amount of data that the driver can read or write to the buffers is limited by spi_slave_transaction_t::length . However, this member does not define the actual length of an SPI transaction. A transaction's length is determined by the clock and CS lines driven by the Host. The actual length of the transmission can be read only after a transaction is finished from the member spi_slave_transaction_t::trans_len . If the length of the transmission is greater than the buffer length, only the initial number of bits specified in the spi_slave_transaction_t::length member will be sent and received. In this case, spi_slave_transaction_t::trans_len is set to spi_slave_transaction_t::length instead of the actual transaction length. To meet the actual transaction length requirements, set spi_slave_transaction_t::length to a value greater than the maximum spi_slave_transaction_t::trans_len expected. If the transmission length is shorter than the buffer length, only the data equal to the length of the buffer will be transmitted. GPIO Matrix and IO_MUX Most of ESP32's peripheral signals have direct connection to their dedicated IO_MUX pins. However, the signals can also be routed to any other available pins using the less direct GPIO matrix. If at least one signal is routed through the GPIO matrix, then all signals will be routed through it. If the driver is configured so that all SPI signals are either routed to their dedicated IO_MUX pins or are not connected at all, the GPIO matrix will be bypassed. The GPIO matrix introduces flexibility of routing but also increases the input delay of the MISO signal, which makes MISO setup time violations more likely. If SPI needs to operate at high speeds, use dedicated IO_MUX pins. Note For more details about the influence of the MISO input delay on the maximum clock frequency, see Timing Considerations. The IO_MUX pins for SPI buses are given below. Pin Name GPIO Number (SPI2) GPIO Number (SPI3) CS0 15 5 SCLK 14 18 MISO 12 19 MOSI 13 23 QUADWP 2 22 QUADHD 4 21 Speed and Timing Considerations Transaction Interval The ESP32 SPI slave peripherals are designed as general purpose Devices controlled by a CPU. As opposed to dedicated slaves, CPU-based SPI Devices have a limited number of pre-defined registers. All transactions must be handled by the CPU, which means that the transfers and responses are not real-time, and there might be noticeable latency. As a solution, a Device's response rate can be doubled by using the functions spi_slave_queue_trans() and then spi_slave_get_trans_result() instead of using spi_slave_transmit() . You can also configure a GPIO pin through which the Device will signal to the Host when it is ready for a new transaction. A code example of this can be found in peripherals/spi_slave. SCLK Frequency Requirements The SPI slaves are designed to operate at up to 10 MHz. The data cannot be recognized or received correctly if the clock is too fast or does not have a 50% duty cycle. On top of that, there are additional requirements for the data to meet the timing constraints: Read (MOSI): The Device can read data correctly only if the data is already set at the launch edge. Although it is usually the case for most masters. Read (MOSI): The Device can read data correctly only if the data is already set at the launch edge. Although it is usually the case for most masters. Write (MISO): The output delay of the MISO signal needs to be shorter than half of a clock cycle period so that the MISO line is stable before the next latch edge. Given that the clock is balanced, the output delay and frequency limitations in different cases are given below. / Output delay of MISO (ns) Freq. limit (MHz) IO_MUX 43.75 < 11.4 GPIO matrix 68.75 < 7.2 Note: 1. If the frequency reaches the maximum limitation, random errors may occur. 2. The clock uncertainty between the Host and the Device (12.5 ns) is included. 3. The output delay is measured under ideal circumstances (no load). If the MISO pin is heavily loaded, the output delay will be longer, and the maximum allowed frequency will be lower. Exception: The frequency is allowed to be higher if the master has more tolerance for the MISO setup time, e.g., latch data at the next edge, or configurable latching time. Write (MISO): The output delay of the MISO signal needs to be shorter than half of a clock cycle period so that the MISO line is stable before the next latch edge. Given that the clock is balanced, the output delay and frequency limitations in different cases are given below. / Output delay of MISO (ns) Freq. limit (MHz) IO_MUX 43.75 < 11.4 GPIO matrix 68.75 < 7.2 Note: 1. If the frequency reaches the maximum limitation, random errors may occur. 2. The clock uncertainty between the Host and the Device (12.5 ns) is included. 3. The output delay is measured under ideal circumstances (no load). If the MISO pin is heavily loaded, the output delay will be longer, and the maximum allowed frequency will be lower. Exception: The frequency is allowed to be higher if the master has more tolerance for the MISO setup time, e.g., latch data at the next edge, or configurable latching time. Restrictions and Known Issues If DMA is enabled, the rx buffer should be word-aligned (starting from a 32-bit boundary and having a length of multiples of 4 bytes). Otherwise, DMA may write incorrectly or not in a boundary aligned manner. The driver reports an error if this condition is not satisfied. Also, a Host should write lengths that are multiples of 4 bytes. The data with inappropriate lengths will be discarded. Furthermore, DMA requires SPI modes 1 and 3. For SPI modes 0 and 2, the MISO signal has to be launched half a clock cycle earlier to meet the timing. The new timing is as follows: If DMA is enabled, a Device's launch edge is half of an SPI clock cycle ahead of the normal time, shifting to the Master's actual latch edge. In this case, if the GPIO matrix is bypassed, the hold time for data sampling is 68.75 ns and no longer a half of an SPI clock cycle. If the GPIO matrix is used, the hold time will increase to 93.75 ns. The Host should sample the data immediately at the latch edge or communicate in SPI modes 1 or 3. If your Host cannot meet these timing requirements, initialize your Device without DMA. Application Example The code example for Device/Host communication can be found in the peripherals/spi_slave directory of ESP-IDF examples. API Reference Header File This header file can be included with: #include "driver/spi_slave.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t spi_slave_initialize(spi_host_device_t host, const spi_bus_config_t *bus_config, const spi_slave_interface_config_t *slave_config, spi_dma_chan_t dma_chan) Initialize a SPI bus as a slave interface. Warning SPI0/1 is not supported Warning If a DMA channel is selected, any transmit and receive buffer used should be allocated in DMA-capable memory. Warning The ISR of SPI is always executed on the core which calls this function. Never starve the ISR on this core or the SPI transactions will not be handled. Parameters host -- SPI peripheral to use as a SPI slave interface bus_config -- Pointer to a spi_bus_config_t struct specifying how the host should be initialized slave_config -- Pointer to a spi_slave_interface_config_t struct specifying the details for the slave interface dma_chan -- - Selecting a DMA channel for an SPI bus allows transactions on the bus with size only limited by the amount of internal memory. Selecting SPI_DMA_DISABLED limits the size of transactions. Set to SPI_DMA_DISABLED if only the SPI flash uses this bus. Set to SPI_DMA_CH_AUTO to let the driver to allocate the DMA channel. Selecting SPI_DMA_DISABLED limits the size of transactions. Set to SPI_DMA_DISABLED if only the SPI flash uses this bus. Set to SPI_DMA_CH_AUTO to let the driver to allocate the DMA channel. Selecting SPI_DMA_DISABLED limits the size of transactions. host -- SPI peripheral to use as a SPI slave interface bus_config -- Pointer to a spi_bus_config_t struct specifying how the host should be initialized slave_config -- Pointer to a spi_slave_interface_config_t struct specifying the details for the slave interface dma_chan -- - Selecting a DMA channel for an SPI bus allows transactions on the bus with size only limited by the amount of internal memory. Selecting SPI_DMA_DISABLED limits the size of transactions. Set to SPI_DMA_DISABLED if only the SPI flash uses this bus. Set to SPI_DMA_CH_AUTO to let the driver to allocate the DMA channel. host -- SPI peripheral to use as a SPI slave interface Returns ESP_ERR_INVALID_ARG if configuration is invalid ESP_ERR_INVALID_STATE if host already is in use ESP_ERR_NOT_FOUND if there is no available DMA channel ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if configuration is invalid ESP_ERR_INVALID_STATE if host already is in use ESP_ERR_NOT_FOUND if there is no available DMA channel ESP_ERR_NO_MEM if out of memory ESP_OK on success ESP_ERR_INVALID_ARG if configuration is invalid Parameters host -- SPI peripheral to use as a SPI slave interface bus_config -- Pointer to a spi_bus_config_t struct specifying how the host should be initialized slave_config -- Pointer to a spi_slave_interface_config_t struct specifying the details for the slave interface dma_chan -- - Selecting a DMA channel for an SPI bus allows transactions on the bus with size only limited by the amount of internal memory. Selecting SPI_DMA_DISABLED limits the size of transactions. Set to SPI_DMA_DISABLED if only the SPI flash uses this bus. Set to SPI_DMA_CH_AUTO to let the driver to allocate the DMA channel. Returns ESP_ERR_INVALID_ARG if configuration is invalid ESP_ERR_INVALID_STATE if host already is in use ESP_ERR_NOT_FOUND if there is no available DMA channel ESP_ERR_NO_MEM if out of memory ESP_OK on success esp_err_t spi_slave_free(spi_host_device_t host) Free a SPI bus claimed as a SPI slave interface. Parameters host -- SPI peripheral to free Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if not all devices on the bus are freed ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if not all devices on the bus are freed ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters host -- SPI peripheral to free Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if not all devices on the bus are freed ESP_OK on success esp_err_t spi_slave_queue_trans(spi_host_device_t host, const spi_slave_transaction_t *trans_desc, TickType_t ticks_to_wait) Queue a SPI transaction for execution. Queues a SPI transaction to be executed by this slave device. (The transaction queue size was specified when the slave device was initialised via spi_slave_initialize.) This function may block if the queue is full (depending on the ticks_to_wait parameter). No SPI operation is directly initiated by this function, the next queued transaction will happen when the master initiates a SPI transaction by pulling down CS and sending out clock signals. This function hands over ownership of the buffers in trans_desc to the SPI slave driver; the application is not to access this memory until spi_slave_queue_trans is called to hand ownership back to the application. Parameters host -- SPI peripheral that is acting as a slave trans_desc -- Description of transaction to execute. Not const because we may want to write status back into the transaction description. ticks_to_wait -- Ticks to wait until there's room in the queue; use portMAX_DELAY to never time out. host -- SPI peripheral that is acting as a slave trans_desc -- Description of transaction to execute. Not const because we may want to write status back into the transaction description. ticks_to_wait -- Ticks to wait until there's room in the queue; use portMAX_DELAY to never time out. host -- SPI peripheral that is acting as a slave Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters host -- SPI peripheral that is acting as a slave trans_desc -- Description of transaction to execute. Not const because we may want to write status back into the transaction description. ticks_to_wait -- Ticks to wait until there's room in the queue; use portMAX_DELAY to never time out. Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success esp_err_t spi_slave_get_trans_result(spi_host_device_t host, spi_slave_transaction_t **trans_desc, TickType_t ticks_to_wait) Get the result of a SPI transaction queued earlier. This routine will wait until a transaction to the given device (queued earlier with spi_slave_queue_trans) has succesfully completed. It will then return the description of the completed transaction so software can inspect the result and e.g. free the memory or re-use the buffers. It is mandatory to eventually use this function for any transaction queued by spi_slave_queue_trans . Parameters host -- SPI peripheral to that is acting as a slave trans_desc -- [out] Pointer to variable able to contain a pointer to the description of the transaction that is executed ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. host -- SPI peripheral to that is acting as a slave trans_desc -- [out] Pointer to variable able to contain a pointer to the description of the transaction that is executed ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. host -- SPI peripheral to that is acting as a slave Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if flag SPI_SLAVE_NO_RETURN_RESULT is set ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if flag SPI_SLAVE_NO_RETURN_RESULT is set ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters host -- SPI peripheral to that is acting as a slave trans_desc -- [out] Pointer to variable able to contain a pointer to the description of the transaction that is executed ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if flag SPI_SLAVE_NO_RETURN_RESULT is set ESP_OK on success esp_err_t spi_slave_transmit(spi_host_device_t host, spi_slave_transaction_t *trans_desc, TickType_t ticks_to_wait) Do a SPI transaction. Essentially does the same as spi_slave_queue_trans followed by spi_slave_get_trans_result. Do not use this when there is still a transaction queued that hasn't been finalized using spi_slave_get_trans_result. Parameters host -- SPI peripheral to that is acting as a slave trans_desc -- Pointer to variable able to contain a pointer to the description of the transaction that is executed. Not const because we may want to write status back into the transaction description. ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. host -- SPI peripheral to that is acting as a slave trans_desc -- Pointer to variable able to contain a pointer to the description of the transaction that is executed. Not const because we may want to write status back into the transaction description. ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. host -- SPI peripheral to that is acting as a slave Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success ESP_ERR_INVALID_ARG if parameter is invalid Parameters host -- SPI peripheral to that is acting as a slave trans_desc -- Pointer to variable able to contain a pointer to the description of the transaction that is executed. Not const because we may want to write status back into the transaction description. ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success Structures struct spi_slave_interface_config_t This is a configuration for a SPI host acting as a slave device. Public Members int spics_io_num CS GPIO pin for this device. int spics_io_num CS GPIO pin for this device. uint32_t flags Bitwise OR of SPI_SLAVE_* flags. uint32_t flags Bitwise OR of SPI_SLAVE_* flags. int queue_size Transaction queue size. This sets how many transactions can be 'in the air' (queued using spi_slave_queue_trans but not yet finished using spi_slave_get_trans_result) at the same time. int queue_size Transaction queue size. This sets how many transactions can be 'in the air' (queued using spi_slave_queue_trans but not yet finished using spi_slave_get_trans_result) at the same time. uint8_t mode SPI mode, representing a pair of (CPOL, CPHA) configuration: 0: (0, 0) 1: (0, 1) 2: (1, 0) 3: (1, 1) 0: (0, 0) 1: (0, 1) 2: (1, 0) 3: (1, 1) 0: (0, 0) uint8_t mode SPI mode, representing a pair of (CPOL, CPHA) configuration: 0: (0, 0) 1: (0, 1) 2: (1, 0) 3: (1, 1) slave_transaction_cb_t post_setup_cb Callback called after the SPI registers are loaded with new data. This callback is called within interrupt context should be in IRAM for best performance, see "Transferring Speed" section in the SPI Master documentation for full details. If not, the callback may crash during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM. slave_transaction_cb_t post_setup_cb Callback called after the SPI registers are loaded with new data. This callback is called within interrupt context should be in IRAM for best performance, see "Transferring Speed" section in the SPI Master documentation for full details. If not, the callback may crash during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM. slave_transaction_cb_t post_trans_cb Callback called after a transaction is done. This callback is called within interrupt context should be in IRAM for best performance, see "Transferring Speed" section in the SPI Master documentation for full details. If not, the callback may crash during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM. slave_transaction_cb_t post_trans_cb Callback called after a transaction is done. This callback is called within interrupt context should be in IRAM for best performance, see "Transferring Speed" section in the SPI Master documentation for full details. If not, the callback may crash during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM. int spics_io_num struct spi_slave_transaction_t This structure describes one SPI transaction Public Members size_t length Total data length, in bits. size_t length Total data length, in bits. size_t trans_len Transaction data length, in bits. size_t trans_len Transaction data length, in bits. const void *tx_buffer Pointer to transmit buffer, or NULL for no MOSI phase. const void *tx_buffer Pointer to transmit buffer, or NULL for no MOSI phase. void *rx_buffer Pointer to receive buffer, or NULL for no MISO phase. When the DMA is anabled, must start at WORD boundary ( rx_buffer%4==0 ), and has length of a multiple of 4 bytes. void *rx_buffer Pointer to receive buffer, or NULL for no MISO phase. When the DMA is anabled, must start at WORD boundary ( rx_buffer%4==0 ), and has length of a multiple of 4 bytes. void *user User-defined variable. Can be used to store eg transaction ID. void *user User-defined variable. Can be used to store eg transaction ID. size_t length Macros SPI_SLAVE_TXBIT_LSBFIRST Transmit command/address/data LSB first instead of the default MSB first. SPI_SLAVE_RXBIT_LSBFIRST Receive data LSB first instead of the default MSB first. SPI_SLAVE_BIT_LSBFIRST Transmit and receive LSB first. SPI_SLAVE_NO_RETURN_RESULT Don't return the descriptor to the host on completion (use post_trans_cb to notify instead) Type Definitions typedef void (*slave_transaction_cb_t)(spi_slave_transaction_t *trans)
SPI Slave Driver SPI Slave driver is a program that controls ESP32's General Purpose SPI (GP-SPI) peripheral(s) when it functions as a slave. For more hardware information about the GP-SPI peripheral(s), see ESP32 Technical Reference Manual > SPI Controller [PDF]. Terminology The terms used in relation to the SPI slave driver are given in the table below. | Term | Definition | Host | The SPI controller peripheral external to ESP32 that initiates SPI transmissions over the bus, and acts as an SPI Master. | Device | SPI slave device (general purpose SPI controller). Each Device shares the MOSI, MISO and SCLK signals but is only active on the bus when the Host asserts the Device's individual CS line. | Bus | A signal bus, common to all Devices connected to one Host. In general, a bus includes the following lines: MISO, MOSI, SCLK, one or more CS lines, and, optionally, QUADWP and QUADHD. So Devices are connected to the same lines, with the exception that each Device has its own CS line. Several Devices can also share one CS line if connected in the daisy-chain manner. | MISO | Master In, Slave Out, a.k.a. Q. Data transmission from a Device to Host. | MOSI | Master Out, Slave In, a.k.a. D. Data transmission from a Host to Device. | SCLK | Serial Clock. Oscillating signal generated by a Host that keeps the transmission of data bits in sync. | CS | Chip Select. Allows a Host to select individual Device(s) connected to the bus in order to send or receive data. | QUADWP | Write Protect signal. Only used for 4-bit (qio/qout) transactions. | QUADHD | Hold signal. Only used for 4-bit (qio/qout) transactions. | Assertion | The action of activating a line. The opposite action of returning the line back to inactive (back to idle) is called de-assertion. | Transaction | One instance of a Host asserting a CS line, transferring data to and from a Device, and de-asserting the CS line. Transactions are atomic, which means they can never be interrupted by another transaction. | Launch Edge | Edge of the clock at which the source register launches the signal onto the line. | Latch Edge | Edge of the clock at which the destination register latches in the signal. Driver Features The SPI slave driver allows using the SPI peripherals as full-duplex Devices. The driver can send/receive transactions up to 64 bytes in length, or utilize DMA to send/receive longer transactions. However, there are some known issues related to DMA. The SPI slave driver supports registering the SPI ISR to a certain CPU core. If multiple tasks try to access the same SPI Device simultaneously, it is recommended that your application be refactored so that each SPI peripheral is only accessed by a single task at a time. Please also use spi_bus_config_t::isr_cpu_id to register the SPI ISR to the same core as SPI peripheral related tasks to ensure thread safety. SPI Transactions A full-duplex SPI transaction begins when the Host asserts the CS line and starts sending out clock pulses on the SCLK line. Every clock pulse, a data bit is shifted from the Host to the Device on the MOSI line and back on the MISO line at the same time. At the end of the transaction, the Host de-asserts the CS line. The attributes of a transaction are determined by the configuration structure for an SPI peripheral acting as a slave device spi_slave_interface_config_t, and transaction configuration structure spi_slave_transaction_t. As not every transaction requires both writing and reading data, you can choose to configure the spi_transaction_t structure for TX only, RX only, or TX and RX transactions. If spi_slave_transaction_t::rx_buffer is set to NULL, the read phase will be skipped. Similarly, if spi_slave_transaction_t::tx_buffer is set to NULL, the write phase will be skipped. Note A Host should not start a transaction before its Device is ready for receiving data. It is recommended to use another GPIO pin for a handshake signal to sync the Devices. For more details, see Transaction Interval. Driver Usage Initialize an SPI peripheral as a Device by calling the function spi_slave_initialize(). Make sure to set the correct I/O pins in the struct bus_config. Set the unused signals to -1. If transactions are expected to be longer than 32 bytes, set the parameter dma_chan to 1 or 2 to allow a DMA channel 1 or 2 respectively. Otherwise, set dma_chan to 0. Before initiating transactions, fill one or more spi_slave_transaction_tstructs with the transaction parameters required. Either queue all transactions by calling the function spi_slave_queue_trans()and, at a later time, query the result by using the function spi_slave_get_trans_result(), or handle all requests individually by feeding them into spi_slave_transmit(). The latter two functions will be blocked until the Host has initiated and finished a transaction, causing the queued data to be sent and received. (Optional) To unload the SPI slave driver, call spi_slave_free(). Transaction Data and Master/Slave Length Mismatches Normally, the data that needs to be transferred to or from a Device is read or written to a chunk of memory indicated by the spi_slave_transaction_t::rx_buffer and spi_slave_transaction_t::tx_buffer. The SPI driver can be configured to use DMA for transfers, in which case these buffers must be allocated in DMA-capable memory using pvPortMallocCaps(size, MALLOC_CAP_DMA). The amount of data that the driver can read or write to the buffers is limited by spi_slave_transaction_t::length. However, this member does not define the actual length of an SPI transaction. A transaction's length is determined by the clock and CS lines driven by the Host. The actual length of the transmission can be read only after a transaction is finished from the member spi_slave_transaction_t::trans_len. If the length of the transmission is greater than the buffer length, only the initial number of bits specified in the spi_slave_transaction_t::length member will be sent and received. In this case, spi_slave_transaction_t::trans_len is set to spi_slave_transaction_t::length instead of the actual transaction length. To meet the actual transaction length requirements, set spi_slave_transaction_t::length to a value greater than the maximum spi_slave_transaction_t::trans_len expected. If the transmission length is shorter than the buffer length, only the data equal to the length of the buffer will be transmitted. GPIO Matrix and IO_MUX Most of ESP32's peripheral signals have direct connection to their dedicated IO_MUX pins. However, the signals can also be routed to any other available pins using the less direct GPIO matrix. If at least one signal is routed through the GPIO matrix, then all signals will be routed through it. If the driver is configured so that all SPI signals are either routed to their dedicated IO_MUX pins or are not connected at all, the GPIO matrix will be bypassed. The GPIO matrix introduces flexibility of routing but also increases the input delay of the MISO signal, which makes MISO setup time violations more likely. If SPI needs to operate at high speeds, use dedicated IO_MUX pins. Note For more details about the influence of the MISO input delay on the maximum clock frequency, see Timing Considerations. The IO_MUX pins for SPI buses are given below. | Pin Name | GPIO Number (SPI2) | GPIO Number (SPI3) | CS0 | 15 | 5 | SCLK | 14 | 18 | MISO | 12 | 19 | MOSI | 13 | 23 | QUADWP | 2 | 22 | QUADHD | 4 | 21 Speed and Timing Considerations Transaction Interval The ESP32 SPI slave peripherals are designed as general purpose Devices controlled by a CPU. As opposed to dedicated slaves, CPU-based SPI Devices have a limited number of pre-defined registers. All transactions must be handled by the CPU, which means that the transfers and responses are not real-time, and there might be noticeable latency. As a solution, a Device's response rate can be doubled by using the functions spi_slave_queue_trans() and then spi_slave_get_trans_result() instead of using spi_slave_transmit(). You can also configure a GPIO pin through which the Device will signal to the Host when it is ready for a new transaction. A code example of this can be found in peripherals/spi_slave. SCLK Frequency Requirements The SPI slaves are designed to operate at up to 10 MHz. The data cannot be recognized or received correctly if the clock is too fast or does not have a 50% duty cycle. On top of that, there are additional requirements for the data to meet the timing constraints: - Read (MOSI): The Device can read data correctly only if the data is already set at the launch edge. Although it is usually the case for most masters. - Write (MISO): The output delay of the MISO signal needs to be shorter than half of a clock cycle period so that the MISO line is stable before the next latch edge. Given that the clock is balanced, the output delay and frequency limitations in different cases are given below. / Output delay of MISO (ns) Freq. limit (MHz) IO_MUX 43.75 < 11.4 GPIO matrix 68.75 < 7.2 Note: 1. If the frequency reaches the maximum limitation, random errors may occur. 2. The clock uncertainty between the Host and the Device (12.5 ns) is included. 3. The output delay is measured under ideal circumstances (no load). If the MISO pin is heavily loaded, the output delay will be longer, and the maximum allowed frequency will be lower. Exception: The frequency is allowed to be higher if the master has more tolerance for the MISO setup time, e.g., latch data at the next edge, or configurable latching time. Restrictions and Known Issues If DMA is enabled, the rx buffer should be word-aligned (starting from a 32-bit boundary and having a length of multiples of 4 bytes). Otherwise, DMA may write incorrectly or not in a boundary aligned manner. The driver reports an error if this condition is not satisfied. Also, a Host should write lengths that are multiples of 4 bytes. The data with inappropriate lengths will be discarded. Furthermore, DMA requires SPI modes 1 and 3. For SPI modes 0 and 2, the MISO signal has to be launched half a clock cycle earlier to meet the timing. The new timing is as follows: If DMA is enabled, a Device's launch edge is half of an SPI clock cycle ahead of the normal time, shifting to the Master's actual latch edge. In this case, if the GPIO matrix is bypassed, the hold time for data sampling is 68.75 ns and no longer a half of an SPI clock cycle. If the GPIO matrix is used, the hold time will increase to 93.75 ns. The Host should sample the data immediately at the latch edge or communicate in SPI modes 1 or 3. If your Host cannot meet these timing requirements, initialize your Device without DMA. Application Example The code example for Device/Host communication can be found in the peripherals/spi_slave directory of ESP-IDF examples. API Reference Header File This header file can be included with: #include "driver/spi_slave.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t spi_slave_initialize(spi_host_device_t host, const spi_bus_config_t *bus_config, const spi_slave_interface_config_t *slave_config, spi_dma_chan_t dma_chan) Initialize a SPI bus as a slave interface. Warning SPI0/1 is not supported Warning If a DMA channel is selected, any transmit and receive buffer used should be allocated in DMA-capable memory. Warning The ISR of SPI is always executed on the core which calls this function. Never starve the ISR on this core or the SPI transactions will not be handled. - Parameters host -- SPI peripheral to use as a SPI slave interface bus_config -- Pointer to a spi_bus_config_t struct specifying how the host should be initialized slave_config -- Pointer to a spi_slave_interface_config_t struct specifying the details for the slave interface dma_chan -- - Selecting a DMA channel for an SPI bus allows transactions on the bus with size only limited by the amount of internal memory. Selecting SPI_DMA_DISABLED limits the size of transactions. Set to SPI_DMA_DISABLED if only the SPI flash uses this bus. Set to SPI_DMA_CH_AUTO to let the driver to allocate the DMA channel. - - - Returns ESP_ERR_INVALID_ARG if configuration is invalid ESP_ERR_INVALID_STATE if host already is in use ESP_ERR_NOT_FOUND if there is no available DMA channel ESP_ERR_NO_MEM if out of memory ESP_OK on success - - esp_err_t spi_slave_free(spi_host_device_t host) Free a SPI bus claimed as a SPI slave interface. - Parameters host -- SPI peripheral to free - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_INVALID_STATE if not all devices on the bus are freed ESP_OK on success - - esp_err_t spi_slave_queue_trans(spi_host_device_t host, const spi_slave_transaction_t *trans_desc, TickType_t ticks_to_wait) Queue a SPI transaction for execution. Queues a SPI transaction to be executed by this slave device. (The transaction queue size was specified when the slave device was initialised via spi_slave_initialize.) This function may block if the queue is full (depending on the ticks_to_wait parameter). No SPI operation is directly initiated by this function, the next queued transaction will happen when the master initiates a SPI transaction by pulling down CS and sending out clock signals. This function hands over ownership of the buffers in trans_descto the SPI slave driver; the application is not to access this memory until spi_slave_queue_transis called to hand ownership back to the application. - Parameters host -- SPI peripheral that is acting as a slave trans_desc -- Description of transaction to execute. Not const because we may want to write status back into the transaction description. ticks_to_wait -- Ticks to wait until there's room in the queue; use portMAX_DELAY to never time out. - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success - - esp_err_t spi_slave_get_trans_result(spi_host_device_t host, spi_slave_transaction_t **trans_desc, TickType_t ticks_to_wait) Get the result of a SPI transaction queued earlier. This routine will wait until a transaction to the given device (queued earlier with spi_slave_queue_trans) has succesfully completed. It will then return the description of the completed transaction so software can inspect the result and e.g. free the memory or re-use the buffers. It is mandatory to eventually use this function for any transaction queued by spi_slave_queue_trans. - Parameters host -- SPI peripheral to that is acting as a slave trans_desc -- [out] Pointer to variable able to contain a pointer to the description of the transaction that is executed ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_ERR_NOT_SUPPORTED if flag SPI_SLAVE_NO_RETURN_RESULTis set ESP_OK on success - - esp_err_t spi_slave_transmit(spi_host_device_t host, spi_slave_transaction_t *trans_desc, TickType_t ticks_to_wait) Do a SPI transaction. Essentially does the same as spi_slave_queue_trans followed by spi_slave_get_trans_result. Do not use this when there is still a transaction queued that hasn't been finalized using spi_slave_get_trans_result. - Parameters host -- SPI peripheral to that is acting as a slave trans_desc -- Pointer to variable able to contain a pointer to the description of the transaction that is executed. Not const because we may want to write status back into the transaction description. ticks_to_wait -- Ticks to wait until there's a returned item; use portMAX_DELAY to never time out. - - Returns ESP_ERR_INVALID_ARG if parameter is invalid ESP_OK on success - Structures - struct spi_slave_interface_config_t This is a configuration for a SPI host acting as a slave device. Public Members - int spics_io_num CS GPIO pin for this device. - uint32_t flags Bitwise OR of SPI_SLAVE_* flags. - int queue_size Transaction queue size. This sets how many transactions can be 'in the air' (queued using spi_slave_queue_trans but not yet finished using spi_slave_get_trans_result) at the same time. - uint8_t mode SPI mode, representing a pair of (CPOL, CPHA) configuration: 0: (0, 0) 1: (0, 1) 2: (1, 0) 3: (1, 1) - - slave_transaction_cb_t post_setup_cb Callback called after the SPI registers are loaded with new data. This callback is called within interrupt context should be in IRAM for best performance, see "Transferring Speed" section in the SPI Master documentation for full details. If not, the callback may crash during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM. - slave_transaction_cb_t post_trans_cb Callback called after a transaction is done. This callback is called within interrupt context should be in IRAM for best performance, see "Transferring Speed" section in the SPI Master documentation for full details. If not, the callback may crash during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM. - int spics_io_num - struct spi_slave_transaction_t This structure describes one SPI transaction Public Members - size_t length Total data length, in bits. - size_t trans_len Transaction data length, in bits. - const void *tx_buffer Pointer to transmit buffer, or NULL for no MOSI phase. - void *rx_buffer Pointer to receive buffer, or NULL for no MISO phase. When the DMA is anabled, must start at WORD boundary ( rx_buffer%4==0), and has length of a multiple of 4 bytes. - void *user User-defined variable. Can be used to store eg transaction ID. - size_t length Macros - SPI_SLAVE_TXBIT_LSBFIRST Transmit command/address/data LSB first instead of the default MSB first. - SPI_SLAVE_RXBIT_LSBFIRST Receive data LSB first instead of the default MSB first. - SPI_SLAVE_BIT_LSBFIRST Transmit and receive LSB first. - SPI_SLAVE_NO_RETURN_RESULT Don't return the descriptor to the host on completion (use post_trans_cbto notify instead) Type Definitions - typedef void (*slave_transaction_cb_t)(spi_slave_transaction_t *trans)
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/spi_slave.html
ESP-IDF Programming Guide v5.2.1 documentation
null
ESP32-WROOM-32SE (Secure Element)
null
espressif.com
2016-01-01
2f4b6c2c30b36f75
null
null
ESP32-WROOM-32SE (Secure Element) Overview ESP32-WROOM-32SE integrates Microchip's ATECC608A cryptoauth chip in the module. ATECC608A is a secure element, which would generate and store ECC private key in the hardware. The ECC private key can be used to enhance security to connect to IoT cloud services with the use of X.509-based mutual authentication. The application example demonstrates ECDSA sign and verify functions using ECC private key stored in ATECC608A. Application Example Secure Element ECDSA Sign/Verify example: peripherals/secure_element/atecc608_ecdsa. How to Configure and Provision ESP32-WROOM-32SE for TLS To configure and provision ATECC608A chip on ESP32-WROOM-32SE please visit esp_cryptoauth_utility. How to Use ATECC608A of ESP32-WROOM-32SE for TLS ATECC608A can be used for TLS connections using ESP-TLS. To configure ESP-TLS for using a secure element, please refer to ATECC608A (Secure Element) with ESP-TLS in ESP-TLS.
ESP32-WROOM-32SE (Secure Element) Overview ESP32-WROOM-32SE integrates Microchip's ATECC608A cryptoauth chip in the module. ATECC608A is a secure element, which would generate and store ECC private key in the hardware. The ECC private key can be used to enhance security to connect to IoT cloud services with the use of X.509-based mutual authentication. The application example demonstrates ECDSA sign and verify functions using ECC private key stored in ATECC608A. Application Example Secure Element ECDSA Sign/Verify example: peripherals/secure_element/atecc608_ecdsa. How to Configure and Provision ESP32-WROOM-32SE for TLS To configure and provision ATECC608A chip on ESP32-WROOM-32SE please visit esp_cryptoauth_utility. How to Use ATECC608A of ESP32-WROOM-32SE for TLS ATECC608A can be used for TLS connections using ESP-TLS. To configure ESP-TLS for using a secure element, please refer to ATECC608A (Secure Element) with ESP-TLS in ESP-TLS.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/secure_element.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Touch Sensor
null
espressif.com
2016-01-01
9a065a1ca87ed353
null
null
Touch Sensor Introduction A touch sensor system is built on a substrate which carries electrodes and relevant connections under a protective flat surface. When the surface is touched, the capacitance variation is used to evaluate if the touch was valid. The sensing pads can be arranged in different combinations (e.g., matrix, slider), so that a larger area or more points can be detected. The touch pad sensing process is under the control of a hardware-implemented finite-state machine (FSM) which is initiated by software or a dedicated hardware timer. For design, operation, and control registers of a touch sensor, see ESP32 Technical Reference Manual > On-Chip Sensors and Analog Signal Processing [PDF]. In-depth design details of touch sensors and firmware development guidelines for ESP32 are available in Touch Sensor Application Note. For more information about testing touch sensors in various configurations, please check the Guide for ESP32-Sense-Kit. Functionality Overview Description of API is broken down into groups of functions to provide a quick overview of the following features: Initialization of touch pad driver Configuration of touch pad GPIO pins Taking measurements Adjusting parameters of measurements Filtering measurements Touch detection methods Setting up interrupts to report touch detection Waking up from Sleep mode on interrupt For detailed description of a particular function, please go to Section API Reference. Practical implementation of this API is covered in Section Application Examples. Initialization Before using a touch pad, you need to initialize the touch pad driver by calling the function touch_pad_init() . This function sets several .._DEFAULT driver parameters listed in API Reference under Macros. It also removes the information about which pads have been touched before, if any, and disables interrupts. If the driver is not required anymore, deinitialize it by calling touch_pad_deinit() . Configuration Enabling the touch sensor functionality for a particular GPIO is done with touch_pad_config() . The following 10 capacitive touch pads are supported for ESP32. Touch Pad GPIO Pin T0 GPIO4 T1 GPIO0 T2 GPIO2 T3 MTDO T4 MTCK T5 MTDI T6 MTMS T7 GPIO27 T8 32K_XN T9 32K_XP Use the function touch_pad_set_fsm_mode() to select if touch pad measurement (operated by FSM) should be started automatically by a hardware timer, or by software. If software mode is selected, use touch_pad_sw_start() to start the FSM. Touch State Measurements The following two functions come in handy to read raw or filtered measurements from the sensor: They can also be used, for example, to evaluate a particular touch pad design by checking the range of sensor readings when a pad is touched or released. This information can be then used to establish a touch threshold. Note Before using touch_pad_read_filtered() , you need to initialize and configure the filter by calling specific filter functions described in Section Filtering of Measurements. For the demonstration of how to read the touch pad data, check the application example peripherals/touch_sensor/touch_sensor_v1/touch_pad_read. Method of Measurements The touch sensor counts the number of charge/discharge cycles over a fixed period of time (specified by touch_pad_set_measurement_clock_cycles() ). The count result is the raw data that read from touch_pad_read_raw_data() . After finishing one measurement, the touch sensor sleeps until the next measurement start, this interval between two measurements can be set by touch_pad_set_measurement_interval() . Note If the specified clock cycles for measurement is too samll, the result may be inaccurate, but increasing clock cycles will increase the power consumption as well. Additionally, the response of the touch sensor will slow down if the total time of the inverval and measurement is too long. Optimization of Measurements A touch sensor has several configurable parameters to match the characteristics of a particular touch pad design. For instance, to sense smaller capacity changes, it is possible to narrow down the reference voltage range within which the touch pads are charged/discharged. The high and low reference voltages are set using the function touch_pad_set_voltage() . Besides the ability to discern smaller capacity changes, a positive side effect is reduction of power consumption for low power applications. A likely negative effect is an increase in measurement noise. If the dynamic range of obtained readings is still satisfactory, then further reduction of power consumption might be done by reducing the measurement time with touch_pad_set_measurement_clock_cycles() . The following list summarizes available measurement parameters and corresponding 'set' functions: Touch pad charge / discharge parameters: voltage range: touch_pad_set_voltage() speed (slope): touch_pad_set_cnt_mode() voltage range: touch_pad_set_voltage() speed (slope): touch_pad_set_cnt_mode() voltage range: touch_pad_set_voltage() Clock cycles of one measurement: touch_pad_set_measurement_clock_cycles() Relationship between the voltage range (high/low reference voltages), speed (slope), and measurement time is shown in the figure below. The last chart Output represents the touch sensor reading, i.e., the count of pulses collected within the measurement time. All functions are provided in pairs to set a specific parameter and to get the current parameter's value, e.g., touch_pad_set_voltage() and touch_pad_get_voltage() . Filtering of Measurements If measurements are noisy, you can filter them with provided API functions. Before using the filter, please start it by calling touch_pad_filter_start() . The filter type is IIR (infinite impulse response), and it has a configurable period that can be set with the function touch_pad_set_filter_period() . You can stop the filter with touch_pad_filter_stop() . If not required anymore, the filter can be deleted by invoking touch_pad_filter_delete() . Touch Detection Touch detection is implemented in ESP32's hardware based on the user-configured threshold and raw measurements executed by FSM. Use the functions touch_pad_get_status() to check which pads have been touched and touch_pad_clear_status() to clear the touch status information. Hardware touch detection can also be wired to interrupts. This is described in the next section. If measurements are noisy and capacity changes are small, hardware touch detection might be unreliable. To resolve this issue, instead of using hardware detection/provided interrupts, implement measurement filtering and perform touch detection in your own application. For sample implementation of both methods of touch detection, see peripherals/touch_sensor/touch_sensor_v1/touch_pad_interrupt. Touch Triggered Interrupts Before enabling an interrupt on a touch detection, you should establish a touch detection threshold. Use the functions described in Touch State Measurements to read and display sensor measurements when a pad is touched and released. Apply a filter if measurements are noisy and relative capacity changes are small. Depending on your application and environment conditions, test the influence of temperature and power supply voltage changes on measured values. Once a detection threshold is established, it can be set during initialization with touch_pad_config() or at the runtime with touch_pad_set_thresh() . In the next step, configure how interrupts are triggered. They can be triggered below or above the threshold, which is set with the function touch_pad_set_trigger_mode() . Finally, configure and manage interrupt calls using the following functions: When interrupts are operational, you can obtain the information from which particular pad an interrupt came by invoking touch_pad_get_status() and clear the pad status with touch_pad_clear_status() . Note Interrupts on touch detection operate on raw/unfiltered measurements checked against user established threshold and are implemented in hardware. Enabling the software filtering API (see Filtering of Measurements) does not affect this process. Wakeup from Sleep Mode If touch pad interrupts are used to wake up the chip from a sleep mode, you can select a certain configuration of pads (SET1 or both SET1 and SET2) that should be touched to trigger the interrupt and cause the subsequent wakeup. To do so, use the function touch_pad_set_trigger_source() . Configuration of required bit patterns of pads may be managed for each 'SET' with: Application Examples Touch sensor read example: peripherals/touch_sensor/touch_sensor_v1/touch_pad_read. Touch sensor interrupt example: peripherals/touch_sensor/touch_sensor_v1/touch_pad_interrupt. API Reference Header File components/driver/touch_sensor/esp32/include/driver/touch_sensor.h This header file can be included with: #include "driver/touch_sensor.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t touch_pad_config(touch_pad_t touch_num, uint16_t threshold) Configure touch pad interrupt threshold. Note If FSM mode is set to TOUCH_FSM_MODE_TIMER, this function will be blocked for one measurement cycle and wait for data to be valid. Parameters touch_num -- touch pad index threshold -- interrupt threshold, touch_num -- touch pad index threshold -- interrupt threshold, touch_num -- touch pad index Returns ESP_OK Success ESP_ERR_INVALID_ARG if argument wrong ESP_FAIL if touch pad not initialized ESP_OK Success ESP_ERR_INVALID_ARG if argument wrong ESP_FAIL if touch pad not initialized ESP_OK Success Parameters touch_num -- touch pad index threshold -- interrupt threshold, Returns ESP_OK Success ESP_ERR_INVALID_ARG if argument wrong ESP_FAIL if touch pad not initialized esp_err_t touch_pad_read(touch_pad_t touch_num, uint16_t *touch_value) get touch sensor counter value. Each touch sensor has a counter to count the number of charge/discharge cycles. When the pad is not 'touched', we can get a number of the counter. When the pad is 'touched', the value in counter will get smaller because of the larger equivalent capacitance. Note This API requests hardware measurement once. If IIR filter mode is enabled, please use 'touch_pad_read_raw_data' interface instead. Parameters touch_num -- touch pad index touch_value -- pointer to accept touch sensor value touch_num -- touch pad index touch_value -- pointer to accept touch sensor value touch_num -- touch pad index Returns ESP_OK Success ESP_ERR_INVALID_ARG Touch pad parameter error ESP_ERR_INVALID_STATE This touch pad hardware connection is error, the value of "touch_value" is 0. ESP_FAIL Touch pad not initialized ESP_OK Success ESP_ERR_INVALID_ARG Touch pad parameter error ESP_ERR_INVALID_STATE This touch pad hardware connection is error, the value of "touch_value" is 0. ESP_FAIL Touch pad not initialized ESP_OK Success Parameters touch_num -- touch pad index touch_value -- pointer to accept touch sensor value Returns ESP_OK Success ESP_ERR_INVALID_ARG Touch pad parameter error ESP_ERR_INVALID_STATE This touch pad hardware connection is error, the value of "touch_value" is 0. ESP_FAIL Touch pad not initialized esp_err_t touch_pad_read_filtered(touch_pad_t touch_num, uint16_t *touch_value) get filtered touch sensor counter value by IIR filter. Note touch_pad_filter_start has to be called before calling touch_pad_read_filtered. This function can be called from ISR Parameters touch_num -- touch pad index touch_value -- pointer to accept touch sensor value touch_num -- touch pad index touch_value -- pointer to accept touch sensor value touch_num -- touch pad index Returns ESP_OK Success ESP_ERR_INVALID_ARG Touch pad parameter error ESP_ERR_INVALID_STATE This touch pad hardware connection is error, the value of "touch_value" is 0. ESP_FAIL Touch pad not initialized ESP_OK Success ESP_ERR_INVALID_ARG Touch pad parameter error ESP_ERR_INVALID_STATE This touch pad hardware connection is error, the value of "touch_value" is 0. ESP_FAIL Touch pad not initialized ESP_OK Success Parameters touch_num -- touch pad index touch_value -- pointer to accept touch sensor value Returns ESP_OK Success ESP_ERR_INVALID_ARG Touch pad parameter error ESP_ERR_INVALID_STATE This touch pad hardware connection is error, the value of "touch_value" is 0. ESP_FAIL Touch pad not initialized esp_err_t touch_pad_read_raw_data(touch_pad_t touch_num, uint16_t *touch_value) get raw data (touch sensor counter value) from IIR filter process. Need not request hardware measurements. Note touch_pad_filter_start has to be called before calling touch_pad_read_raw_data. This function can be called from ISR Parameters touch_num -- touch pad index touch_value -- pointer to accept touch sensor value touch_num -- touch pad index touch_value -- pointer to accept touch sensor value touch_num -- touch pad index Returns ESP_OK Success ESP_ERR_INVALID_ARG Touch pad parameter error ESP_ERR_INVALID_STATE This touch pad hardware connection is error, the value of "touch_value" is 0. ESP_FAIL Touch pad not initialized ESP_OK Success ESP_ERR_INVALID_ARG Touch pad parameter error ESP_ERR_INVALID_STATE This touch pad hardware connection is error, the value of "touch_value" is 0. ESP_FAIL Touch pad not initialized ESP_OK Success Parameters touch_num -- touch pad index touch_value -- pointer to accept touch sensor value Returns ESP_OK Success ESP_ERR_INVALID_ARG Touch pad parameter error ESP_ERR_INVALID_STATE This touch pad hardware connection is error, the value of "touch_value" is 0. ESP_FAIL Touch pad not initialized esp_err_t touch_pad_set_filter_read_cb(filter_cb_t read_cb) Register the callback function that is called after each IIR filter calculation. Note The 'read_cb' callback is called in timer task in each filtering cycle. Parameters read_cb -- Pointer to filtered callback function. If the argument passed in is NULL, the callback will stop. Returns ESP_OK Success ESP_ERR_INVALID_ARG set error ESP_OK Success ESP_ERR_INVALID_ARG set error ESP_OK Success Parameters read_cb -- Pointer to filtered callback function. If the argument passed in is NULL, the callback will stop. Returns ESP_OK Success ESP_ERR_INVALID_ARG set error esp_err_t touch_pad_isr_register(intr_handler_t fn, void *arg) Register touch-pad ISR. The handler will be attached to the same CPU core that this function is running on. Parameters fn -- Pointer to ISR handler arg -- Parameter for ISR fn -- Pointer to ISR handler arg -- Parameter for ISR fn -- Pointer to ISR handler Returns ESP_OK Success ; ESP_ERR_INVALID_ARG GPIO error ESP_ERR_NO_MEM No memory ESP_OK Success ; ESP_ERR_INVALID_ARG GPIO error ESP_ERR_NO_MEM No memory ESP_OK Success ; Parameters fn -- Pointer to ISR handler arg -- Parameter for ISR Returns ESP_OK Success ; ESP_ERR_INVALID_ARG GPIO error ESP_ERR_NO_MEM No memory esp_err_t touch_pad_set_measurement_clock_cycles(uint16_t clock_cycle) Set the clock cycles of each measurement. Note This function will specify the clock cycles of each measurement and the clock is sourced from SOC_MOD_CLK_RTC_FAST, its default frequency is SOC_CLK_RC_FAST_FREQ_APPROX The touch sensor will record the charge and discharge times during these clock cycles as the final result (raw value) Note If clock cyles is too small, it may lead to inaccurate results. Parameters clock_cycle -- The clock cycles of each measurement measure_time = clock_cycle / SOC_CLK_RC_FAST_FREQ_APPROX, the maximum measure time is 0xffff / SOC_CLK_RC_FAST_FREQ_APPROX Returns ESP_OK Set the clock cycle success ESP_OK Set the clock cycle success ESP_OK Set the clock cycle success Parameters clock_cycle -- The clock cycles of each measurement measure_time = clock_cycle / SOC_CLK_RC_FAST_FREQ_APPROX, the maximum measure time is 0xffff / SOC_CLK_RC_FAST_FREQ_APPROX Returns ESP_OK Set the clock cycle success esp_err_t touch_pad_get_measurement_clock_cycles(uint16_t *clock_cycle) Get the clock cycles of each measurement. Parameters clock_cycle -- The clock cycles of each measurement Returns ESP_OK Get the clock cycle success ESP_ERR_INVALID_ARG The input parameter is NULL ESP_OK Get the clock cycle success ESP_ERR_INVALID_ARG The input parameter is NULL ESP_OK Get the clock cycle success Parameters clock_cycle -- The clock cycles of each measurement Returns ESP_OK Get the clock cycle success ESP_ERR_INVALID_ARG The input parameter is NULL esp_err_t touch_pad_set_measurement_interval(uint16_t interval_cycle) Set the interval between two measurements. Note The touch sensor will sleep between two mesurements This function is to set the interval cycle And the interval is clocked from SOC_MOD_CLK_RTC_SLOW, its default frequency is SOC_CLK_RC_SLOW_FREQ_APPROX Parameters interval_cycle -- The interval between two measurements sleep_time = interval_cycle / SOC_CLK_RC_SLOW_FREQ_APPROX. The approximate frequency value of RTC_SLOW_CLK can be obtained using rtc_clk_slow_freq_get_hz function. Returns ESP_OK Set interval cycle success ESP_OK Set interval cycle success ESP_OK Set interval cycle success Parameters interval_cycle -- The interval between two measurements sleep_time = interval_cycle / SOC_CLK_RC_SLOW_FREQ_APPROX. The approximate frequency value of RTC_SLOW_CLK can be obtained using rtc_clk_slow_freq_get_hz function. Returns ESP_OK Set interval cycle success esp_err_t touch_pad_get_measurement_interval(uint16_t *interval_cycle) Get the interval between two measurements. Parameters interval_cycle -- The interval between two measurements Returns ESP_OK Get interval cycle success ESP_ERR_INVALID_ARG The input parameter is NULL ESP_OK Get interval cycle success ESP_ERR_INVALID_ARG The input parameter is NULL ESP_OK Get interval cycle success Parameters interval_cycle -- The interval between two measurements Returns ESP_OK Get interval cycle success ESP_ERR_INVALID_ARG The input parameter is NULL esp_err_t touch_pad_set_meas_time(uint16_t sleep_cycle, uint16_t meas_cycle) Set touch sensor measurement and sleep time. Excessive total time will slow down the touch response. Too small measurement time will not be sampled enough, resulting in inaccurate measurements. Note The touch sensor will count the number of charge/discharge cycles over a fixed period of time (specified as the second parameter). That means the number of cycles (raw value) will decrease as the capacity of the touch pad is increasing. Note The greater the duty cycle of the measurement time, the more system power is consumed. Parameters sleep_cycle -- The touch sensor will sleep after each measurement. sleep_cycle decide the interval between each measurement. t_sleep = sleep_cycle / SOC_CLK_RC_SLOW_FREQ_APPROX. The approximate frequency value of RTC_SLOW_CLK can be obtained using rtc_clk_slow_freq_get_hz function. meas_cycle -- The duration of the touch sensor measurement. t_meas = meas_cycle / SOC_CLK_RC_FAST_FREQ_APPROX, the maximum measure time is 0xffff / SOC_CLK_RC_FAST_FREQ_APPROX sleep_cycle -- The touch sensor will sleep after each measurement. sleep_cycle decide the interval between each measurement. t_sleep = sleep_cycle / SOC_CLK_RC_SLOW_FREQ_APPROX. The approximate frequency value of RTC_SLOW_CLK can be obtained using rtc_clk_slow_freq_get_hz function. meas_cycle -- The duration of the touch sensor measurement. t_meas = meas_cycle / SOC_CLK_RC_FAST_FREQ_APPROX, the maximum measure time is 0xffff / SOC_CLK_RC_FAST_FREQ_APPROX sleep_cycle -- The touch sensor will sleep after each measurement. sleep_cycle decide the interval between each measurement. t_sleep = sleep_cycle / SOC_CLK_RC_SLOW_FREQ_APPROX. The approximate frequency value of RTC_SLOW_CLK can be obtained using rtc_clk_slow_freq_get_hz function. Returns ESP_OK on success ESP_OK on success ESP_OK on success Parameters sleep_cycle -- The touch sensor will sleep after each measurement. sleep_cycle decide the interval between each measurement. t_sleep = sleep_cycle / SOC_CLK_RC_SLOW_FREQ_APPROX. The approximate frequency value of RTC_SLOW_CLK can be obtained using rtc_clk_slow_freq_get_hz function. meas_cycle -- The duration of the touch sensor measurement. t_meas = meas_cycle / SOC_CLK_RC_FAST_FREQ_APPROX, the maximum measure time is 0xffff / SOC_CLK_RC_FAST_FREQ_APPROX Returns ESP_OK on success esp_err_t touch_pad_get_meas_time(uint16_t *sleep_cycle, uint16_t *meas_cycle) Get touch sensor measurement and sleep time. Parameters sleep_cycle -- Pointer to accept sleep cycle number meas_cycle -- Pointer to accept measurement cycle count. sleep_cycle -- Pointer to accept sleep cycle number meas_cycle -- Pointer to accept measurement cycle count. sleep_cycle -- Pointer to accept sleep cycle number Returns ESP_OK on success ESP_ERR_INVALID_ARG The input parameter is NULL ESP_OK on success ESP_ERR_INVALID_ARG The input parameter is NULL ESP_OK on success Parameters sleep_cycle -- Pointer to accept sleep cycle number meas_cycle -- Pointer to accept measurement cycle count. Returns ESP_OK on success ESP_ERR_INVALID_ARG The input parameter is NULL esp_err_t touch_pad_sw_start(void) Trigger a touch sensor measurement, only support in SW mode of FSM. Returns ESP_OK on success ESP_OK on success ESP_OK on success Returns ESP_OK on success esp_err_t touch_pad_set_thresh(touch_pad_t touch_num, uint16_t threshold) Set touch sensor interrupt threshold. Parameters touch_num -- touch pad index threshold -- threshold of touchpad count, refer to touch_pad_set_trigger_mode to see how to set trigger mode. touch_num -- touch pad index threshold -- threshold of touchpad count, refer to touch_pad_set_trigger_mode to see how to set trigger mode. touch_num -- touch pad index Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success Parameters touch_num -- touch pad index threshold -- threshold of touchpad count, refer to touch_pad_set_trigger_mode to see how to set trigger mode. Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong esp_err_t touch_pad_get_thresh(touch_pad_t touch_num, uint16_t *threshold) Get touch sensor interrupt threshold. Parameters touch_num -- touch pad index threshold -- pointer to accept threshold touch_num -- touch pad index threshold -- pointer to accept threshold touch_num -- touch pad index Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success Parameters touch_num -- touch pad index threshold -- pointer to accept threshold Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong esp_err_t touch_pad_set_trigger_mode(touch_trigger_mode_t mode) Set touch sensor interrupt trigger mode. Interrupt can be triggered either when counter result is less than threshold or when counter result is more than threshold. Parameters mode -- touch sensor interrupt trigger mode Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success Parameters mode -- touch sensor interrupt trigger mode Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong esp_err_t touch_pad_get_trigger_mode(touch_trigger_mode_t *mode) Get touch sensor interrupt trigger mode. Parameters mode -- pointer to accept touch sensor interrupt trigger mode Returns ESP_OK on success ESP_OK on success ESP_OK on success Parameters mode -- pointer to accept touch sensor interrupt trigger mode Returns ESP_OK on success esp_err_t touch_pad_set_trigger_source(touch_trigger_src_t src) Set touch sensor interrupt trigger source. There are two sets of touch signals. Set1 and set2 can be mapped to several touch signals. Either set will be triggered if at least one of its touch signal is 'touched'. The interrupt can be configured to be generated if set1 is triggered, or only if both sets are triggered. Parameters src -- touch sensor interrupt trigger source Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success Parameters src -- touch sensor interrupt trigger source Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong esp_err_t touch_pad_get_trigger_source(touch_trigger_src_t *src) Get touch sensor interrupt trigger source. Parameters src -- pointer to accept touch sensor interrupt trigger source Returns ESP_OK on success ESP_OK on success ESP_OK on success Parameters src -- pointer to accept touch sensor interrupt trigger source Returns ESP_OK on success esp_err_t touch_pad_set_group_mask(uint16_t set1_mask, uint16_t set2_mask, uint16_t en_mask) Set touch sensor group mask. Touch pad module has two sets of signals, 'Touched' signal is triggered only if at least one of touch pad in this group is "touched". This function will set the register bits according to the given bitmask. Parameters set1_mask -- bitmask of touch sensor signal group1, it's a 10-bit value set2_mask -- bitmask of touch sensor signal group2, it's a 10-bit value en_mask -- bitmask of touch sensor work enable, it's a 10-bit value set1_mask -- bitmask of touch sensor signal group1, it's a 10-bit value set2_mask -- bitmask of touch sensor signal group2, it's a 10-bit value en_mask -- bitmask of touch sensor work enable, it's a 10-bit value set1_mask -- bitmask of touch sensor signal group1, it's a 10-bit value Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success Parameters set1_mask -- bitmask of touch sensor signal group1, it's a 10-bit value set2_mask -- bitmask of touch sensor signal group2, it's a 10-bit value en_mask -- bitmask of touch sensor work enable, it's a 10-bit value Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong esp_err_t touch_pad_get_group_mask(uint16_t *set1_mask, uint16_t *set2_mask, uint16_t *en_mask) Get touch sensor group mask. Parameters set1_mask -- pointer to accept bitmask of touch sensor signal group1, it's a 10-bit value set2_mask -- pointer to accept bitmask of touch sensor signal group2, it's a 10-bit value en_mask -- pointer to accept bitmask of touch sensor work enable, it's a 10-bit value set1_mask -- pointer to accept bitmask of touch sensor signal group1, it's a 10-bit value set2_mask -- pointer to accept bitmask of touch sensor signal group2, it's a 10-bit value en_mask -- pointer to accept bitmask of touch sensor work enable, it's a 10-bit value set1_mask -- pointer to accept bitmask of touch sensor signal group1, it's a 10-bit value Returns ESP_OK on success ESP_OK on success ESP_OK on success Parameters set1_mask -- pointer to accept bitmask of touch sensor signal group1, it's a 10-bit value set2_mask -- pointer to accept bitmask of touch sensor signal group2, it's a 10-bit value en_mask -- pointer to accept bitmask of touch sensor work enable, it's a 10-bit value Returns ESP_OK on success esp_err_t touch_pad_clear_group_mask(uint16_t set1_mask, uint16_t set2_mask, uint16_t en_mask) Clear touch sensor group mask. Touch pad module has two sets of signals, Interrupt is triggered only if at least one of touch pad in this group is "touched". This function will clear the register bits according to the given bitmask. Parameters set1_mask -- bitmask touch sensor signal group1, it's a 10-bit value set2_mask -- bitmask touch sensor signal group2, it's a 10-bit value en_mask -- bitmask of touch sensor work enable, it's a 10-bit value set1_mask -- bitmask touch sensor signal group1, it's a 10-bit value set2_mask -- bitmask touch sensor signal group2, it's a 10-bit value en_mask -- bitmask of touch sensor work enable, it's a 10-bit value set1_mask -- bitmask touch sensor signal group1, it's a 10-bit value Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success Parameters set1_mask -- bitmask touch sensor signal group1, it's a 10-bit value set2_mask -- bitmask touch sensor signal group2, it's a 10-bit value en_mask -- bitmask of touch sensor work enable, it's a 10-bit value Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong esp_err_t touch_pad_set_filter_period(uint32_t new_period_ms) set touch pad filter calibration period, in ms. Need to call touch_pad_filter_start before all touch filter APIs Parameters new_period_ms -- filter period, in ms Returns ESP_OK Success ESP_ERR_INVALID_STATE driver state error ESP_ERR_INVALID_ARG parameter error ESP_OK Success ESP_ERR_INVALID_STATE driver state error ESP_ERR_INVALID_ARG parameter error ESP_OK Success Parameters new_period_ms -- filter period, in ms Returns ESP_OK Success ESP_ERR_INVALID_STATE driver state error ESP_ERR_INVALID_ARG parameter error esp_err_t touch_pad_get_filter_period(uint32_t *p_period_ms) get touch pad filter calibration period, in ms Need to call touch_pad_filter_start before all touch filter APIs Parameters p_period_ms -- pointer to accept period Returns ESP_OK Success ESP_ERR_INVALID_STATE driver state error ESP_ERR_INVALID_ARG parameter error ESP_OK Success ESP_ERR_INVALID_STATE driver state error ESP_ERR_INVALID_ARG parameter error ESP_OK Success Parameters p_period_ms -- pointer to accept period Returns ESP_OK Success ESP_ERR_INVALID_STATE driver state error ESP_ERR_INVALID_ARG parameter error esp_err_t touch_pad_filter_start(uint32_t filter_period_ms) start touch pad filter function This API will start a filter to process the noise in order to prevent false triggering when detecting slight change of capacitance. Need to call touch_pad_filter_start before all touch filter APIs Note This filter uses FreeRTOS timer, which is dispatched from a task with priority 1 by default on CPU 0. So if some application task with higher priority takes a lot of CPU0 time, then the quality of data obtained from this filter will be affected. You can adjust FreeRTOS timer task priority in menuconfig. Parameters filter_period_ms -- filter calibration period, in ms Returns ESP_OK Success ESP_ERR_INVALID_ARG parameter error ESP_ERR_NO_MEM No memory for driver ESP_ERR_INVALID_STATE driver state error ESP_OK Success ESP_ERR_INVALID_ARG parameter error ESP_ERR_NO_MEM No memory for driver ESP_ERR_INVALID_STATE driver state error ESP_OK Success Parameters filter_period_ms -- filter calibration period, in ms Returns ESP_OK Success ESP_ERR_INVALID_ARG parameter error ESP_ERR_NO_MEM No memory for driver ESP_ERR_INVALID_STATE driver state error esp_err_t touch_pad_filter_stop(void) stop touch pad filter function Need to call touch_pad_filter_start before all touch filter APIs Returns ESP_OK Success ESP_ERR_INVALID_STATE driver state error ESP_OK Success ESP_ERR_INVALID_STATE driver state error ESP_OK Success Returns ESP_OK Success ESP_ERR_INVALID_STATE driver state error Type Definitions typedef void (*filter_cb_t)(uint16_t *raw_value, uint16_t *filtered_value) Callback function that is called after each IIR filter calculation. Note This callback is called in timer task in each filtering cycle. Note This callback should not be blocked. Param raw_value The latest raw data(touch sensor counter value) that points to all channels(raw_value[0..TOUCH_PAD_MAX-1]). Param filtered_value The latest IIR filtered data(calculated from raw data) that points to all channels(filtered_value[0..TOUCH_PAD_MAX-1]). Param raw_value The latest raw data(touch sensor counter value) that points to all channels(raw_value[0..TOUCH_PAD_MAX-1]). Param filtered_value The latest IIR filtered data(calculated from raw data) that points to all channels(filtered_value[0..TOUCH_PAD_MAX-1]). Header File components/driver/touch_sensor/include/driver/touch_sensor_common.h This header file can be included with: #include "driver/touch_sensor_common.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t touch_pad_init(void) Initialize touch module. Note If default parameter don't match the usage scenario, it can be changed after this function. Returns ESP_OK Success ESP_ERR_NO_MEM Touch pad init error ESP_ERR_NOT_SUPPORTED Touch pad is providing current to external XTAL ESP_OK Success ESP_ERR_NO_MEM Touch pad init error ESP_ERR_NOT_SUPPORTED Touch pad is providing current to external XTAL ESP_OK Success Returns ESP_OK Success ESP_ERR_NO_MEM Touch pad init error ESP_ERR_NOT_SUPPORTED Touch pad is providing current to external XTAL esp_err_t touch_pad_deinit(void) Un-install touch pad driver. Note After this function is called, other touch functions are prohibited from being called. Returns ESP_OK Success ESP_FAIL Touch pad driver not initialized ESP_OK Success ESP_FAIL Touch pad driver not initialized ESP_OK Success Returns ESP_OK Success ESP_FAIL Touch pad driver not initialized esp_err_t touch_pad_io_init(touch_pad_t touch_num) Initialize touch pad GPIO. Parameters touch_num -- touch pad index Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success Parameters touch_num -- touch pad index Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong esp_err_t touch_pad_set_voltage(touch_high_volt_t refh, touch_low_volt_t refl, touch_volt_atten_t atten) Set touch sensor high voltage threshold of chanrge. The touch sensor measures the channel capacitance value by charging and discharging the channel. So the high threshold should be less than the supply voltage. Parameters refh -- the value of DREFH refl -- the value of DREFL atten -- the attenuation on DREFH refh -- the value of DREFH refl -- the value of DREFL atten -- the attenuation on DREFH refh -- the value of DREFH Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success Parameters refh -- the value of DREFH refl -- the value of DREFL atten -- the attenuation on DREFH Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong esp_err_t touch_pad_get_voltage(touch_high_volt_t *refh, touch_low_volt_t *refl, touch_volt_atten_t *atten) Get touch sensor reference voltage,. Parameters refh -- pointer to accept DREFH value refl -- pointer to accept DREFL value atten -- pointer to accept the attenuation on DREFH refh -- pointer to accept DREFH value refl -- pointer to accept DREFL value atten -- pointer to accept the attenuation on DREFH refh -- pointer to accept DREFH value Returns ESP_OK on success ESP_OK on success ESP_OK on success Parameters refh -- pointer to accept DREFH value refl -- pointer to accept DREFL value atten -- pointer to accept the attenuation on DREFH Returns ESP_OK on success esp_err_t touch_pad_set_cnt_mode(touch_pad_t touch_num, touch_cnt_slope_t slope, touch_tie_opt_t opt) Set touch sensor charge/discharge speed for each pad. If the slope is 0, the counter would always be zero. If the slope is 1, the charging and discharging would be slow, accordingly. If the slope is set 7, which is the maximum value, the charging and discharging would be fast. Note The higher the charge and discharge current, the greater the immunity of the touch channel, but it will increase the system power consumption. Parameters touch_num -- touch pad index slope -- touch pad charge/discharge speed opt -- the initial voltage touch_num -- touch pad index slope -- touch pad charge/discharge speed opt -- the initial voltage touch_num -- touch pad index Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success Parameters touch_num -- touch pad index slope -- touch pad charge/discharge speed opt -- the initial voltage Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong esp_err_t touch_pad_get_cnt_mode(touch_pad_t touch_num, touch_cnt_slope_t *slope, touch_tie_opt_t *opt) Get touch sensor charge/discharge speed for each pad. Parameters touch_num -- touch pad index slope -- pointer to accept touch pad charge/discharge slope opt -- pointer to accept the initial voltage touch_num -- touch pad index slope -- pointer to accept touch pad charge/discharge slope opt -- pointer to accept the initial voltage touch_num -- touch pad index Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success Parameters touch_num -- touch pad index slope -- pointer to accept touch pad charge/discharge slope opt -- pointer to accept the initial voltage Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong esp_err_t touch_pad_isr_deregister(void (*fn)(void*), void *arg) Deregister the handler previously registered using touch_pad_isr_handler_register. Parameters fn -- handler function to call (as passed to touch_pad_isr_handler_register) arg -- argument of the handler (as passed to touch_pad_isr_handler_register) fn -- handler function to call (as passed to touch_pad_isr_handler_register) arg -- argument of the handler (as passed to touch_pad_isr_handler_register) fn -- handler function to call (as passed to touch_pad_isr_handler_register) Returns ESP_OK on success ESP_ERR_INVALID_STATE if a handler matching both fn and arg isn't registered ESP_OK on success ESP_ERR_INVALID_STATE if a handler matching both fn and arg isn't registered ESP_OK on success Parameters fn -- handler function to call (as passed to touch_pad_isr_handler_register) arg -- argument of the handler (as passed to touch_pad_isr_handler_register) Returns ESP_OK on success ESP_ERR_INVALID_STATE if a handler matching both fn and arg isn't registered esp_err_t touch_pad_get_wakeup_status(touch_pad_t *pad_num) Get the touch pad which caused wakeup from deep sleep. Parameters pad_num -- pointer to touch pad which caused wakeup Returns ESP_OK Success ESP_ERR_INVALID_ARG parameter is NULL ESP_OK Success ESP_ERR_INVALID_ARG parameter is NULL ESP_OK Success Parameters pad_num -- pointer to touch pad which caused wakeup Returns ESP_OK Success ESP_ERR_INVALID_ARG parameter is NULL esp_err_t touch_pad_set_fsm_mode(touch_fsm_mode_t mode) Set touch sensor FSM mode, the test action can be triggered by the timer, as well as by the software. Parameters mode -- FSM mode Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong ESP_OK on success Parameters mode -- FSM mode Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong esp_err_t touch_pad_get_fsm_mode(touch_fsm_mode_t *mode) Get touch sensor FSM mode. Parameters mode -- pointer to accept FSM mode Returns ESP_OK on success ESP_OK on success ESP_OK on success Parameters mode -- pointer to accept FSM mode Returns ESP_OK on success esp_err_t touch_pad_clear_status(void) To clear the touch sensor channel active status. Note The FSM automatically updates the touch sensor status. It is generally not necessary to call this API to clear the status. Returns ESP_OK on success ESP_OK on success ESP_OK on success Returns ESP_OK on success uint32_t touch_pad_get_status(void) Get the touch sensor channel active status mask. The bit position represents the channel number. The 0/1 status of the bit represents the trigger status. Returns The touch sensor status. e.g. Touch1 trigger status is status_mask & (BIT1) . The touch sensor status. e.g. Touch1 trigger status is status_mask & (BIT1) . The touch sensor status. e.g. Touch1 trigger status is status_mask & (BIT1) . Returns The touch sensor status. e.g. Touch1 trigger status is status_mask & (BIT1) . bool touch_pad_meas_is_done(void) Check touch sensor measurement status. Returns True measurement is under way False measurement done True measurement is under way False measurement done True measurement is under way Returns True measurement is under way False measurement done GPIO Lookup Macros Some useful macros can be used to specified the GPIO number of a touch pad channel, or vice versa. e.g., TOUCH_PAD_NUM5_GPIO_NUM is the GPIO number of channel 5 (12); TOUCH_PAD_GPIO4_CHANNEL is the channel number of GPIO 4 (channel 0). Header File This header file can be included with: #include "soc/touch_sensor_channel.h" Macros TOUCH_PAD_GPIO4_CHANNEL TOUCH_PAD_NUM0_GPIO_NUM TOUCH_PAD_GPIO0_CHANNEL TOUCH_PAD_NUM1_GPIO_NUM TOUCH_PAD_GPIO2_CHANNEL TOUCH_PAD_NUM2_GPIO_NUM TOUCH_PAD_GPIO15_CHANNEL TOUCH_PAD_NUM3_GPIO_NUM TOUCH_PAD_GPIO13_CHANNEL TOUCH_PAD_NUM4_GPIO_NUM TOUCH_PAD_GPIO12_CHANNEL TOUCH_PAD_NUM5_GPIO_NUM TOUCH_PAD_GPIO14_CHANNEL TOUCH_PAD_NUM6_GPIO_NUM TOUCH_PAD_GPIO27_CHANNEL TOUCH_PAD_NUM7_GPIO_NUM TOUCH_PAD_GPIO33_CHANNEL TOUCH_PAD_NUM8_GPIO_NUM TOUCH_PAD_GPIO32_CHANNEL TOUCH_PAD_NUM9_GPIO_NUM Header File This header file can be included with: #include "hal/touch_sensor_types.h" Macros TOUCH_PAD_BIT_MASK_ALL TOUCH_PAD_SLOPE_DEFAULT TOUCH_PAD_TIE_OPT_DEFAULT TOUCH_PAD_BIT_MASK_MAX TOUCH_PAD_HIGH_VOLTAGE_THRESHOLD TOUCH_PAD_LOW_VOLTAGE_THRESHOLD TOUCH_PAD_ATTEN_VOLTAGE_THRESHOLD TOUCH_PAD_IDLE_CH_CONNECT_DEFAULT TOUCH_PAD_THRESHOLD_MAX If set touch threshold max value, The touch sensor can't be in touched status TOUCH_PAD_SLEEP_CYCLE_DEFAULT The timer frequency is RTC_SLOW_CLK (can be 150k or 32k depending on the options), max value is 0xffff TOUCH_PAD_MEASURE_CYCLE_DEFAULT The timer frequency is 8Mhz, the max value is 0x7fff TOUCH_FSM_MODE_DEFAULT The touch FSM my be started by the software or timer TOUCH_TRIGGER_MODE_DEFAULT Interrupts can be triggered if sensor value gets below or above threshold TOUCH_TRIGGER_SOURCE_DEFAULT The wakeup trigger source can be SET1 or both SET1 and SET2 Enumerations enum touch_pad_t Touch pad channel Values: enumerator TOUCH_PAD_NUM0 Touch pad channel 0 is GPIO4(ESP32) enumerator TOUCH_PAD_NUM0 Touch pad channel 0 is GPIO4(ESP32) enumerator TOUCH_PAD_NUM1 Touch pad channel 1 is GPIO0(ESP32) / GPIO1(ESP32-S2) enumerator TOUCH_PAD_NUM1 Touch pad channel 1 is GPIO0(ESP32) / GPIO1(ESP32-S2) enumerator TOUCH_PAD_NUM2 Touch pad channel 2 is GPIO2(ESP32) / GPIO2(ESP32-S2) enumerator TOUCH_PAD_NUM2 Touch pad channel 2 is GPIO2(ESP32) / GPIO2(ESP32-S2) enumerator TOUCH_PAD_NUM3 Touch pad channel 3 is GPIO15(ESP32) / GPIO3(ESP32-S2) enumerator TOUCH_PAD_NUM3 Touch pad channel 3 is GPIO15(ESP32) / GPIO3(ESP32-S2) enumerator TOUCH_PAD_NUM4 Touch pad channel 4 is GPIO13(ESP32) / GPIO4(ESP32-S2) enumerator TOUCH_PAD_NUM4 Touch pad channel 4 is GPIO13(ESP32) / GPIO4(ESP32-S2) enumerator TOUCH_PAD_NUM5 Touch pad channel 5 is GPIO12(ESP32) / GPIO5(ESP32-S2) enumerator TOUCH_PAD_NUM5 Touch pad channel 5 is GPIO12(ESP32) / GPIO5(ESP32-S2) enumerator TOUCH_PAD_NUM6 Touch pad channel 6 is GPIO14(ESP32) / GPIO6(ESP32-S2) enumerator TOUCH_PAD_NUM6 Touch pad channel 6 is GPIO14(ESP32) / GPIO6(ESP32-S2) enumerator TOUCH_PAD_NUM7 Touch pad channel 7 is GPIO27(ESP32) / GPIO7(ESP32-S2) enumerator TOUCH_PAD_NUM7 Touch pad channel 7 is GPIO27(ESP32) / GPIO7(ESP32-S2) enumerator TOUCH_PAD_NUM8 Touch pad channel 8 is GPIO33(ESP32) / GPIO8(ESP32-S2) enumerator TOUCH_PAD_NUM8 Touch pad channel 8 is GPIO33(ESP32) / GPIO8(ESP32-S2) enumerator TOUCH_PAD_NUM9 Touch pad channel 9 is GPIO32(ESP32) / GPIO9(ESP32-S2) enumerator TOUCH_PAD_NUM9 Touch pad channel 9 is GPIO32(ESP32) / GPIO9(ESP32-S2) enumerator TOUCH_PAD_MAX enumerator TOUCH_PAD_MAX enumerator TOUCH_PAD_NUM0 enum touch_high_volt_t Touch sensor high reference voltage Values: enumerator TOUCH_HVOLT_KEEP Touch sensor high reference voltage, no change enumerator TOUCH_HVOLT_KEEP Touch sensor high reference voltage, no change enumerator TOUCH_HVOLT_2V4 Touch sensor high reference voltage, 2.4V enumerator TOUCH_HVOLT_2V4 Touch sensor high reference voltage, 2.4V enumerator TOUCH_HVOLT_2V5 Touch sensor high reference voltage, 2.5V enumerator TOUCH_HVOLT_2V5 Touch sensor high reference voltage, 2.5V enumerator TOUCH_HVOLT_2V6 Touch sensor high reference voltage, 2.6V enumerator TOUCH_HVOLT_2V6 Touch sensor high reference voltage, 2.6V enumerator TOUCH_HVOLT_2V7 Touch sensor high reference voltage, 2.7V enumerator TOUCH_HVOLT_2V7 Touch sensor high reference voltage, 2.7V enumerator TOUCH_HVOLT_MAX enumerator TOUCH_HVOLT_MAX enumerator TOUCH_HVOLT_KEEP enum touch_low_volt_t Touch sensor low reference voltage Values: enumerator TOUCH_LVOLT_KEEP Touch sensor low reference voltage, no change enumerator TOUCH_LVOLT_KEEP Touch sensor low reference voltage, no change enumerator TOUCH_LVOLT_0V5 Touch sensor low reference voltage, 0.5V enumerator TOUCH_LVOLT_0V5 Touch sensor low reference voltage, 0.5V enumerator TOUCH_LVOLT_0V6 Touch sensor low reference voltage, 0.6V enumerator TOUCH_LVOLT_0V6 Touch sensor low reference voltage, 0.6V enumerator TOUCH_LVOLT_0V7 Touch sensor low reference voltage, 0.7V enumerator TOUCH_LVOLT_0V7 Touch sensor low reference voltage, 0.7V enumerator TOUCH_LVOLT_0V8 Touch sensor low reference voltage, 0.8V enumerator TOUCH_LVOLT_0V8 Touch sensor low reference voltage, 0.8V enumerator TOUCH_LVOLT_MAX enumerator TOUCH_LVOLT_MAX enumerator TOUCH_LVOLT_KEEP enum touch_volt_atten_t Touch sensor high reference voltage attenuation Values: enumerator TOUCH_HVOLT_ATTEN_KEEP Touch sensor high reference voltage attenuation, no change enumerator TOUCH_HVOLT_ATTEN_KEEP Touch sensor high reference voltage attenuation, no change enumerator TOUCH_HVOLT_ATTEN_1V5 Touch sensor high reference voltage attenuation, 1.5V attenuation enumerator TOUCH_HVOLT_ATTEN_1V5 Touch sensor high reference voltage attenuation, 1.5V attenuation enumerator TOUCH_HVOLT_ATTEN_1V Touch sensor high reference voltage attenuation, 1.0V attenuation enumerator TOUCH_HVOLT_ATTEN_1V Touch sensor high reference voltage attenuation, 1.0V attenuation enumerator TOUCH_HVOLT_ATTEN_0V5 Touch sensor high reference voltage attenuation, 0.5V attenuation enumerator TOUCH_HVOLT_ATTEN_0V5 Touch sensor high reference voltage attenuation, 0.5V attenuation enumerator TOUCH_HVOLT_ATTEN_0V Touch sensor high reference voltage attenuation, 0V attenuation enumerator TOUCH_HVOLT_ATTEN_0V Touch sensor high reference voltage attenuation, 0V attenuation enumerator TOUCH_HVOLT_ATTEN_MAX enumerator TOUCH_HVOLT_ATTEN_MAX enumerator TOUCH_HVOLT_ATTEN_KEEP enum touch_cnt_slope_t Touch sensor charge/discharge speed Values: enumerator TOUCH_PAD_SLOPE_0 Touch sensor charge / discharge speed, always zero enumerator TOUCH_PAD_SLOPE_0 Touch sensor charge / discharge speed, always zero enumerator TOUCH_PAD_SLOPE_1 Touch sensor charge / discharge speed, slowest enumerator TOUCH_PAD_SLOPE_1 Touch sensor charge / discharge speed, slowest enumerator TOUCH_PAD_SLOPE_2 Touch sensor charge / discharge speed enumerator TOUCH_PAD_SLOPE_2 Touch sensor charge / discharge speed enumerator TOUCH_PAD_SLOPE_3 Touch sensor charge / discharge speed enumerator TOUCH_PAD_SLOPE_3 Touch sensor charge / discharge speed enumerator TOUCH_PAD_SLOPE_4 Touch sensor charge / discharge speed enumerator TOUCH_PAD_SLOPE_4 Touch sensor charge / discharge speed enumerator TOUCH_PAD_SLOPE_5 Touch sensor charge / discharge speed enumerator TOUCH_PAD_SLOPE_5 Touch sensor charge / discharge speed enumerator TOUCH_PAD_SLOPE_6 Touch sensor charge / discharge speed enumerator TOUCH_PAD_SLOPE_6 Touch sensor charge / discharge speed enumerator TOUCH_PAD_SLOPE_7 Touch sensor charge / discharge speed, fast enumerator TOUCH_PAD_SLOPE_7 Touch sensor charge / discharge speed, fast enumerator TOUCH_PAD_SLOPE_MAX enumerator TOUCH_PAD_SLOPE_MAX enumerator TOUCH_PAD_SLOPE_0 enum touch_tie_opt_t Touch sensor initial charge level Values: enumerator TOUCH_PAD_TIE_OPT_LOW Initial level of charging voltage, low level enumerator TOUCH_PAD_TIE_OPT_LOW Initial level of charging voltage, low level enumerator TOUCH_PAD_TIE_OPT_HIGH Initial level of charging voltage, high level enumerator TOUCH_PAD_TIE_OPT_HIGH Initial level of charging voltage, high level enumerator TOUCH_PAD_TIE_OPT_MAX enumerator TOUCH_PAD_TIE_OPT_MAX enumerator TOUCH_PAD_TIE_OPT_LOW enum touch_fsm_mode_t Touch sensor FSM mode Values: enumerator TOUCH_FSM_MODE_TIMER To start touch FSM by timer enumerator TOUCH_FSM_MODE_TIMER To start touch FSM by timer enumerator TOUCH_FSM_MODE_SW To start touch FSM by software trigger enumerator TOUCH_FSM_MODE_SW To start touch FSM by software trigger enumerator TOUCH_FSM_MODE_MAX enumerator TOUCH_FSM_MODE_MAX enumerator TOUCH_FSM_MODE_TIMER enum touch_trigger_mode_t Values: enumerator TOUCH_TRIGGER_BELOW Touch interrupt will happen if counter value is less than threshold. enumerator TOUCH_TRIGGER_BELOW Touch interrupt will happen if counter value is less than threshold. enumerator TOUCH_TRIGGER_ABOVE Touch interrupt will happen if counter value is larger than threshold. enumerator TOUCH_TRIGGER_ABOVE Touch interrupt will happen if counter value is larger than threshold. enumerator TOUCH_TRIGGER_MAX enumerator TOUCH_TRIGGER_MAX enumerator TOUCH_TRIGGER_BELOW
Touch Sensor Introduction A touch sensor system is built on a substrate which carries electrodes and relevant connections under a protective flat surface. When the surface is touched, the capacitance variation is used to evaluate if the touch was valid. The sensing pads can be arranged in different combinations (e.g., matrix, slider), so that a larger area or more points can be detected. The touch pad sensing process is under the control of a hardware-implemented finite-state machine (FSM) which is initiated by software or a dedicated hardware timer. For design, operation, and control registers of a touch sensor, see ESP32 Technical Reference Manual > On-Chip Sensors and Analog Signal Processing [PDF]. In-depth design details of touch sensors and firmware development guidelines for ESP32 are available in Touch Sensor Application Note. For more information about testing touch sensors in various configurations, please check the Guide for ESP32-Sense-Kit. Functionality Overview Description of API is broken down into groups of functions to provide a quick overview of the following features: Initialization of touch pad driver Configuration of touch pad GPIO pins Taking measurements Adjusting parameters of measurements Filtering measurements Touch detection methods Setting up interrupts to report touch detection Waking up from Sleep mode on interrupt For detailed description of a particular function, please go to Section API Reference. Practical implementation of this API is covered in Section Application Examples. Initialization Before using a touch pad, you need to initialize the touch pad driver by calling the function touch_pad_init(). This function sets several .._DEFAULT driver parameters listed in API Reference under Macros. It also removes the information about which pads have been touched before, if any, and disables interrupts. If the driver is not required anymore, deinitialize it by calling touch_pad_deinit(). Configuration Enabling the touch sensor functionality for a particular GPIO is done with touch_pad_config(). The following 10 capacitive touch pads are supported for ESP32. | Touch Pad | GPIO Pin | T0 | GPIO4 | T1 | GPIO0 | T2 | GPIO2 | T3 | MTDO | T4 | MTCK | T5 | MTDI | T6 | MTMS | T7 | GPIO27 | T8 | 32K_XN | T9 | 32K_XP Use the function touch_pad_set_fsm_mode() to select if touch pad measurement (operated by FSM) should be started automatically by a hardware timer, or by software. If software mode is selected, use touch_pad_sw_start() to start the FSM. Touch State Measurements The following two functions come in handy to read raw or filtered measurements from the sensor: They can also be used, for example, to evaluate a particular touch pad design by checking the range of sensor readings when a pad is touched or released. This information can be then used to establish a touch threshold. Note Before using touch_pad_read_filtered(), you need to initialize and configure the filter by calling specific filter functions described in Section Filtering of Measurements. For the demonstration of how to read the touch pad data, check the application example peripherals/touch_sensor/touch_sensor_v1/touch_pad_read. Method of Measurements The touch sensor counts the number of charge/discharge cycles over a fixed period of time (specified by touch_pad_set_measurement_clock_cycles()). The count result is the raw data that read from touch_pad_read_raw_data(). After finishing one measurement, the touch sensor sleeps until the next measurement start, this interval between two measurements can be set by touch_pad_set_measurement_interval(). Note If the specified clock cycles for measurement is too samll, the result may be inaccurate, but increasing clock cycles will increase the power consumption as well. Additionally, the response of the touch sensor will slow down if the total time of the inverval and measurement is too long. Optimization of Measurements A touch sensor has several configurable parameters to match the characteristics of a particular touch pad design. For instance, to sense smaller capacity changes, it is possible to narrow down the reference voltage range within which the touch pads are charged/discharged. The high and low reference voltages are set using the function touch_pad_set_voltage(). Besides the ability to discern smaller capacity changes, a positive side effect is reduction of power consumption for low power applications. A likely negative effect is an increase in measurement noise. If the dynamic range of obtained readings is still satisfactory, then further reduction of power consumption might be done by reducing the measurement time with touch_pad_set_measurement_clock_cycles(). The following list summarizes available measurement parameters and corresponding 'set' functions: Touch pad charge / discharge parameters: voltage range: touch_pad_set_voltage() speed (slope): touch_pad_set_cnt_mode() - Clock cycles of one measurement: touch_pad_set_measurement_clock_cycles() Relationship between the voltage range (high/low reference voltages), speed (slope), and measurement time is shown in the figure below. The last chart Output represents the touch sensor reading, i.e., the count of pulses collected within the measurement time. All functions are provided in pairs to set a specific parameter and to get the current parameter's value, e.g., touch_pad_set_voltage() and touch_pad_get_voltage(). Filtering of Measurements If measurements are noisy, you can filter them with provided API functions. Before using the filter, please start it by calling touch_pad_filter_start(). The filter type is IIR (infinite impulse response), and it has a configurable period that can be set with the function touch_pad_set_filter_period(). You can stop the filter with touch_pad_filter_stop(). If not required anymore, the filter can be deleted by invoking touch_pad_filter_delete(). Touch Detection Touch detection is implemented in ESP32's hardware based on the user-configured threshold and raw measurements executed by FSM. Use the functions touch_pad_get_status() to check which pads have been touched and touch_pad_clear_status() to clear the touch status information. Hardware touch detection can also be wired to interrupts. This is described in the next section. If measurements are noisy and capacity changes are small, hardware touch detection might be unreliable. To resolve this issue, instead of using hardware detection/provided interrupts, implement measurement filtering and perform touch detection in your own application. For sample implementation of both methods of touch detection, see peripherals/touch_sensor/touch_sensor_v1/touch_pad_interrupt. Touch Triggered Interrupts Before enabling an interrupt on a touch detection, you should establish a touch detection threshold. Use the functions described in Touch State Measurements to read and display sensor measurements when a pad is touched and released. Apply a filter if measurements are noisy and relative capacity changes are small. Depending on your application and environment conditions, test the influence of temperature and power supply voltage changes on measured values. Once a detection threshold is established, it can be set during initialization with touch_pad_config() or at the runtime with touch_pad_set_thresh(). In the next step, configure how interrupts are triggered. They can be triggered below or above the threshold, which is set with the function touch_pad_set_trigger_mode(). Finally, configure and manage interrupt calls using the following functions: When interrupts are operational, you can obtain the information from which particular pad an interrupt came by invoking touch_pad_get_status() and clear the pad status with touch_pad_clear_status(). Note Interrupts on touch detection operate on raw/unfiltered measurements checked against user established threshold and are implemented in hardware. Enabling the software filtering API (see Filtering of Measurements) does not affect this process. Wakeup from Sleep Mode If touch pad interrupts are used to wake up the chip from a sleep mode, you can select a certain configuration of pads (SET1 or both SET1 and SET2) that should be touched to trigger the interrupt and cause the subsequent wakeup. To do so, use the function touch_pad_set_trigger_source(). Configuration of required bit patterns of pads may be managed for each 'SET' with: Application Examples Touch sensor read example: peripherals/touch_sensor/touch_sensor_v1/touch_pad_read. Touch sensor interrupt example: peripherals/touch_sensor/touch_sensor_v1/touch_pad_interrupt. API Reference Header File components/driver/touch_sensor/esp32/include/driver/touch_sensor.h This header file can be included with: #include "driver/touch_sensor.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t touch_pad_config(touch_pad_t touch_num, uint16_t threshold) Configure touch pad interrupt threshold. Note If FSM mode is set to TOUCH_FSM_MODE_TIMER, this function will be blocked for one measurement cycle and wait for data to be valid. - Parameters touch_num -- touch pad index threshold -- interrupt threshold, - - Returns ESP_OK Success ESP_ERR_INVALID_ARG if argument wrong ESP_FAIL if touch pad not initialized - - esp_err_t touch_pad_read(touch_pad_t touch_num, uint16_t *touch_value) get touch sensor counter value. Each touch sensor has a counter to count the number of charge/discharge cycles. When the pad is not 'touched', we can get a number of the counter. When the pad is 'touched', the value in counter will get smaller because of the larger equivalent capacitance. Note This API requests hardware measurement once. If IIR filter mode is enabled, please use 'touch_pad_read_raw_data' interface instead. - Parameters touch_num -- touch pad index touch_value -- pointer to accept touch sensor value - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Touch pad parameter error ESP_ERR_INVALID_STATE This touch pad hardware connection is error, the value of "touch_value" is 0. ESP_FAIL Touch pad not initialized - - esp_err_t touch_pad_read_filtered(touch_pad_t touch_num, uint16_t *touch_value) get filtered touch sensor counter value by IIR filter. Note touch_pad_filter_start has to be called before calling touch_pad_read_filtered. This function can be called from ISR - Parameters touch_num -- touch pad index touch_value -- pointer to accept touch sensor value - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Touch pad parameter error ESP_ERR_INVALID_STATE This touch pad hardware connection is error, the value of "touch_value" is 0. ESP_FAIL Touch pad not initialized - - esp_err_t touch_pad_read_raw_data(touch_pad_t touch_num, uint16_t *touch_value) get raw data (touch sensor counter value) from IIR filter process. Need not request hardware measurements. Note touch_pad_filter_start has to be called before calling touch_pad_read_raw_data. This function can be called from ISR - Parameters touch_num -- touch pad index touch_value -- pointer to accept touch sensor value - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Touch pad parameter error ESP_ERR_INVALID_STATE This touch pad hardware connection is error, the value of "touch_value" is 0. ESP_FAIL Touch pad not initialized - - esp_err_t touch_pad_set_filter_read_cb(filter_cb_t read_cb) Register the callback function that is called after each IIR filter calculation. Note The 'read_cb' callback is called in timer task in each filtering cycle. - Parameters read_cb -- Pointer to filtered callback function. If the argument passed in is NULL, the callback will stop. - Returns ESP_OK Success ESP_ERR_INVALID_ARG set error - - esp_err_t touch_pad_isr_register(intr_handler_t fn, void *arg) Register touch-pad ISR. The handler will be attached to the same CPU core that this function is running on. - Parameters fn -- Pointer to ISR handler arg -- Parameter for ISR - - Returns ESP_OK Success ; ESP_ERR_INVALID_ARG GPIO error ESP_ERR_NO_MEM No memory - - esp_err_t touch_pad_set_measurement_clock_cycles(uint16_t clock_cycle) Set the clock cycles of each measurement. Note This function will specify the clock cycles of each measurement and the clock is sourced from SOC_MOD_CLK_RTC_FAST, its default frequency is SOC_CLK_RC_FAST_FREQ_APPROX The touch sensor will record the charge and discharge times during these clock cycles as the final result (raw value) Note If clock cyles is too small, it may lead to inaccurate results. - Parameters clock_cycle -- The clock cycles of each measurement measure_time = clock_cycle / SOC_CLK_RC_FAST_FREQ_APPROX, the maximum measure time is 0xffff / SOC_CLK_RC_FAST_FREQ_APPROX - Returns ESP_OK Set the clock cycle success - - esp_err_t touch_pad_get_measurement_clock_cycles(uint16_t *clock_cycle) Get the clock cycles of each measurement. - Parameters clock_cycle -- The clock cycles of each measurement - Returns ESP_OK Get the clock cycle success ESP_ERR_INVALID_ARG The input parameter is NULL - - esp_err_t touch_pad_set_measurement_interval(uint16_t interval_cycle) Set the interval between two measurements. Note The touch sensor will sleep between two mesurements This function is to set the interval cycle And the interval is clocked from SOC_MOD_CLK_RTC_SLOW, its default frequency is SOC_CLK_RC_SLOW_FREQ_APPROX - Parameters interval_cycle -- The interval between two measurements sleep_time = interval_cycle / SOC_CLK_RC_SLOW_FREQ_APPROX. The approximate frequency value of RTC_SLOW_CLK can be obtained using rtc_clk_slow_freq_get_hz function. - Returns ESP_OK Set interval cycle success - - esp_err_t touch_pad_get_measurement_interval(uint16_t *interval_cycle) Get the interval between two measurements. - Parameters interval_cycle -- The interval between two measurements - Returns ESP_OK Get interval cycle success ESP_ERR_INVALID_ARG The input parameter is NULL - - esp_err_t touch_pad_set_meas_time(uint16_t sleep_cycle, uint16_t meas_cycle) Set touch sensor measurement and sleep time. Excessive total time will slow down the touch response. Too small measurement time will not be sampled enough, resulting in inaccurate measurements. Note The touch sensor will count the number of charge/discharge cycles over a fixed period of time (specified as the second parameter). That means the number of cycles (raw value) will decrease as the capacity of the touch pad is increasing. Note The greater the duty cycle of the measurement time, the more system power is consumed. - Parameters sleep_cycle -- The touch sensor will sleep after each measurement. sleep_cycle decide the interval between each measurement. t_sleep = sleep_cycle / SOC_CLK_RC_SLOW_FREQ_APPROX. The approximate frequency value of RTC_SLOW_CLK can be obtained using rtc_clk_slow_freq_get_hz function. meas_cycle -- The duration of the touch sensor measurement. t_meas = meas_cycle / SOC_CLK_RC_FAST_FREQ_APPROX, the maximum measure time is 0xffff / SOC_CLK_RC_FAST_FREQ_APPROX - - Returns ESP_OK on success - - esp_err_t touch_pad_get_meas_time(uint16_t *sleep_cycle, uint16_t *meas_cycle) Get touch sensor measurement and sleep time. - Parameters sleep_cycle -- Pointer to accept sleep cycle number meas_cycle -- Pointer to accept measurement cycle count. - - Returns ESP_OK on success ESP_ERR_INVALID_ARG The input parameter is NULL - - esp_err_t touch_pad_sw_start(void) Trigger a touch sensor measurement, only support in SW mode of FSM. - Returns ESP_OK on success - - esp_err_t touch_pad_set_thresh(touch_pad_t touch_num, uint16_t threshold) Set touch sensor interrupt threshold. - Parameters touch_num -- touch pad index threshold -- threshold of touchpad count, refer to touch_pad_set_trigger_mode to see how to set trigger mode. - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong - - esp_err_t touch_pad_get_thresh(touch_pad_t touch_num, uint16_t *threshold) Get touch sensor interrupt threshold. - Parameters touch_num -- touch pad index threshold -- pointer to accept threshold - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong - - esp_err_t touch_pad_set_trigger_mode(touch_trigger_mode_t mode) Set touch sensor interrupt trigger mode. Interrupt can be triggered either when counter result is less than threshold or when counter result is more than threshold. - Parameters mode -- touch sensor interrupt trigger mode - Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong - - esp_err_t touch_pad_get_trigger_mode(touch_trigger_mode_t *mode) Get touch sensor interrupt trigger mode. - Parameters mode -- pointer to accept touch sensor interrupt trigger mode - Returns ESP_OK on success - - esp_err_t touch_pad_set_trigger_source(touch_trigger_src_t src) Set touch sensor interrupt trigger source. There are two sets of touch signals. Set1 and set2 can be mapped to several touch signals. Either set will be triggered if at least one of its touch signal is 'touched'. The interrupt can be configured to be generated if set1 is triggered, or only if both sets are triggered. - Parameters src -- touch sensor interrupt trigger source - Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong - - esp_err_t touch_pad_get_trigger_source(touch_trigger_src_t *src) Get touch sensor interrupt trigger source. - Parameters src -- pointer to accept touch sensor interrupt trigger source - Returns ESP_OK on success - - esp_err_t touch_pad_set_group_mask(uint16_t set1_mask, uint16_t set2_mask, uint16_t en_mask) Set touch sensor group mask. Touch pad module has two sets of signals, 'Touched' signal is triggered only if at least one of touch pad in this group is "touched". This function will set the register bits according to the given bitmask. - Parameters set1_mask -- bitmask of touch sensor signal group1, it's a 10-bit value set2_mask -- bitmask of touch sensor signal group2, it's a 10-bit value en_mask -- bitmask of touch sensor work enable, it's a 10-bit value - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong - - esp_err_t touch_pad_get_group_mask(uint16_t *set1_mask, uint16_t *set2_mask, uint16_t *en_mask) Get touch sensor group mask. - Parameters set1_mask -- pointer to accept bitmask of touch sensor signal group1, it's a 10-bit value set2_mask -- pointer to accept bitmask of touch sensor signal group2, it's a 10-bit value en_mask -- pointer to accept bitmask of touch sensor work enable, it's a 10-bit value - - Returns ESP_OK on success - - esp_err_t touch_pad_clear_group_mask(uint16_t set1_mask, uint16_t set2_mask, uint16_t en_mask) Clear touch sensor group mask. Touch pad module has two sets of signals, Interrupt is triggered only if at least one of touch pad in this group is "touched". This function will clear the register bits according to the given bitmask. - Parameters set1_mask -- bitmask touch sensor signal group1, it's a 10-bit value set2_mask -- bitmask touch sensor signal group2, it's a 10-bit value en_mask -- bitmask of touch sensor work enable, it's a 10-bit value - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong - - esp_err_t touch_pad_set_filter_period(uint32_t new_period_ms) set touch pad filter calibration period, in ms. Need to call touch_pad_filter_start before all touch filter APIs - Parameters new_period_ms -- filter period, in ms - Returns ESP_OK Success ESP_ERR_INVALID_STATE driver state error ESP_ERR_INVALID_ARG parameter error - - esp_err_t touch_pad_get_filter_period(uint32_t *p_period_ms) get touch pad filter calibration period, in ms Need to call touch_pad_filter_start before all touch filter APIs - Parameters p_period_ms -- pointer to accept period - Returns ESP_OK Success ESP_ERR_INVALID_STATE driver state error ESP_ERR_INVALID_ARG parameter error - - esp_err_t touch_pad_filter_start(uint32_t filter_period_ms) start touch pad filter function This API will start a filter to process the noise in order to prevent false triggering when detecting slight change of capacitance. Need to call touch_pad_filter_start before all touch filter APIs Note This filter uses FreeRTOS timer, which is dispatched from a task with priority 1 by default on CPU 0. So if some application task with higher priority takes a lot of CPU0 time, then the quality of data obtained from this filter will be affected. You can adjust FreeRTOS timer task priority in menuconfig. - Parameters filter_period_ms -- filter calibration period, in ms - Returns ESP_OK Success ESP_ERR_INVALID_ARG parameter error ESP_ERR_NO_MEM No memory for driver ESP_ERR_INVALID_STATE driver state error - - esp_err_t touch_pad_filter_stop(void) stop touch pad filter function Need to call touch_pad_filter_start before all touch filter APIs - Returns ESP_OK Success ESP_ERR_INVALID_STATE driver state error - Type Definitions - typedef void (*filter_cb_t)(uint16_t *raw_value, uint16_t *filtered_value) Callback function that is called after each IIR filter calculation. Note This callback is called in timer task in each filtering cycle. Note This callback should not be blocked. - Param raw_value The latest raw data(touch sensor counter value) that points to all channels(raw_value[0..TOUCH_PAD_MAX-1]). - Param filtered_value The latest IIR filtered data(calculated from raw data) that points to all channels(filtered_value[0..TOUCH_PAD_MAX-1]). Header File components/driver/touch_sensor/include/driver/touch_sensor_common.h This header file can be included with: #include "driver/touch_sensor_common.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t touch_pad_init(void) Initialize touch module. Note If default parameter don't match the usage scenario, it can be changed after this function. - Returns ESP_OK Success ESP_ERR_NO_MEM Touch pad init error ESP_ERR_NOT_SUPPORTED Touch pad is providing current to external XTAL - - esp_err_t touch_pad_deinit(void) Un-install touch pad driver. Note After this function is called, other touch functions are prohibited from being called. - Returns ESP_OK Success ESP_FAIL Touch pad driver not initialized - - esp_err_t touch_pad_io_init(touch_pad_t touch_num) Initialize touch pad GPIO. - Parameters touch_num -- touch pad index - Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong - - esp_err_t touch_pad_set_voltage(touch_high_volt_t refh, touch_low_volt_t refl, touch_volt_atten_t atten) Set touch sensor high voltage threshold of chanrge. The touch sensor measures the channel capacitance value by charging and discharging the channel. So the high threshold should be less than the supply voltage. - Parameters refh -- the value of DREFH refl -- the value of DREFL atten -- the attenuation on DREFH - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong - - esp_err_t touch_pad_get_voltage(touch_high_volt_t *refh, touch_low_volt_t *refl, touch_volt_atten_t *atten) Get touch sensor reference voltage,. - Parameters refh -- pointer to accept DREFH value refl -- pointer to accept DREFL value atten -- pointer to accept the attenuation on DREFH - - Returns ESP_OK on success - - esp_err_t touch_pad_set_cnt_mode(touch_pad_t touch_num, touch_cnt_slope_t slope, touch_tie_opt_t opt) Set touch sensor charge/discharge speed for each pad. If the slope is 0, the counter would always be zero. If the slope is 1, the charging and discharging would be slow, accordingly. If the slope is set 7, which is the maximum value, the charging and discharging would be fast. Note The higher the charge and discharge current, the greater the immunity of the touch channel, but it will increase the system power consumption. - Parameters touch_num -- touch pad index slope -- touch pad charge/discharge speed opt -- the initial voltage - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong - - esp_err_t touch_pad_get_cnt_mode(touch_pad_t touch_num, touch_cnt_slope_t *slope, touch_tie_opt_t *opt) Get touch sensor charge/discharge speed for each pad. - Parameters touch_num -- touch pad index slope -- pointer to accept touch pad charge/discharge slope opt -- pointer to accept the initial voltage - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong - - esp_err_t touch_pad_isr_deregister(void (*fn)(void*), void *arg) Deregister the handler previously registered using touch_pad_isr_handler_register. - Parameters fn -- handler function to call (as passed to touch_pad_isr_handler_register) arg -- argument of the handler (as passed to touch_pad_isr_handler_register) - - Returns ESP_OK on success ESP_ERR_INVALID_STATE if a handler matching both fn and arg isn't registered - - esp_err_t touch_pad_get_wakeup_status(touch_pad_t *pad_num) Get the touch pad which caused wakeup from deep sleep. - Parameters pad_num -- pointer to touch pad which caused wakeup - Returns ESP_OK Success ESP_ERR_INVALID_ARG parameter is NULL - - esp_err_t touch_pad_set_fsm_mode(touch_fsm_mode_t mode) Set touch sensor FSM mode, the test action can be triggered by the timer, as well as by the software. - Parameters mode -- FSM mode - Returns ESP_OK on success ESP_ERR_INVALID_ARG if argument is wrong - - esp_err_t touch_pad_get_fsm_mode(touch_fsm_mode_t *mode) Get touch sensor FSM mode. - Parameters mode -- pointer to accept FSM mode - Returns ESP_OK on success - - esp_err_t touch_pad_clear_status(void) To clear the touch sensor channel active status. Note The FSM automatically updates the touch sensor status. It is generally not necessary to call this API to clear the status. - Returns ESP_OK on success - - uint32_t touch_pad_get_status(void) Get the touch sensor channel active status mask. The bit position represents the channel number. The 0/1 status of the bit represents the trigger status. - Returns The touch sensor status. e.g. Touch1 trigger status is status_mask & (BIT1). - - bool touch_pad_meas_is_done(void) Check touch sensor measurement status. - Returns True measurement is under way False measurement done - GPIO Lookup Macros Some useful macros can be used to specified the GPIO number of a touch pad channel, or vice versa. e.g., TOUCH_PAD_NUM5_GPIO_NUMis the GPIO number of channel 5 (12); TOUCH_PAD_GPIO4_CHANNELis the channel number of GPIO 4 (channel 0). Header File This header file can be included with: #include "soc/touch_sensor_channel.h" Macros - TOUCH_PAD_GPIO4_CHANNEL - TOUCH_PAD_NUM0_GPIO_NUM - TOUCH_PAD_GPIO0_CHANNEL - TOUCH_PAD_NUM1_GPIO_NUM - TOUCH_PAD_GPIO2_CHANNEL - TOUCH_PAD_NUM2_GPIO_NUM - TOUCH_PAD_GPIO15_CHANNEL - TOUCH_PAD_NUM3_GPIO_NUM - TOUCH_PAD_GPIO13_CHANNEL - TOUCH_PAD_NUM4_GPIO_NUM - TOUCH_PAD_GPIO12_CHANNEL - TOUCH_PAD_NUM5_GPIO_NUM - TOUCH_PAD_GPIO14_CHANNEL - TOUCH_PAD_NUM6_GPIO_NUM - TOUCH_PAD_GPIO27_CHANNEL - TOUCH_PAD_NUM7_GPIO_NUM - TOUCH_PAD_GPIO33_CHANNEL - TOUCH_PAD_NUM8_GPIO_NUM - TOUCH_PAD_GPIO32_CHANNEL - TOUCH_PAD_NUM9_GPIO_NUM Header File This header file can be included with: #include "hal/touch_sensor_types.h" Macros - TOUCH_PAD_BIT_MASK_ALL - TOUCH_PAD_SLOPE_DEFAULT - TOUCH_PAD_TIE_OPT_DEFAULT - TOUCH_PAD_BIT_MASK_MAX - TOUCH_PAD_HIGH_VOLTAGE_THRESHOLD - TOUCH_PAD_LOW_VOLTAGE_THRESHOLD - TOUCH_PAD_ATTEN_VOLTAGE_THRESHOLD - TOUCH_PAD_IDLE_CH_CONNECT_DEFAULT - TOUCH_PAD_THRESHOLD_MAX If set touch threshold max value, The touch sensor can't be in touched status - TOUCH_PAD_SLEEP_CYCLE_DEFAULT The timer frequency is RTC_SLOW_CLK (can be 150k or 32k depending on the options), max value is 0xffff - TOUCH_PAD_MEASURE_CYCLE_DEFAULT The timer frequency is 8Mhz, the max value is 0x7fff - TOUCH_FSM_MODE_DEFAULT The touch FSM my be started by the software or timer - TOUCH_TRIGGER_MODE_DEFAULT Interrupts can be triggered if sensor value gets below or above threshold - TOUCH_TRIGGER_SOURCE_DEFAULT The wakeup trigger source can be SET1 or both SET1 and SET2 Enumerations - enum touch_pad_t Touch pad channel Values: - enumerator TOUCH_PAD_NUM0 Touch pad channel 0 is GPIO4(ESP32) - enumerator TOUCH_PAD_NUM1 Touch pad channel 1 is GPIO0(ESP32) / GPIO1(ESP32-S2) - enumerator TOUCH_PAD_NUM2 Touch pad channel 2 is GPIO2(ESP32) / GPIO2(ESP32-S2) - enumerator TOUCH_PAD_NUM3 Touch pad channel 3 is GPIO15(ESP32) / GPIO3(ESP32-S2) - enumerator TOUCH_PAD_NUM4 Touch pad channel 4 is GPIO13(ESP32) / GPIO4(ESP32-S2) - enumerator TOUCH_PAD_NUM5 Touch pad channel 5 is GPIO12(ESP32) / GPIO5(ESP32-S2) - enumerator TOUCH_PAD_NUM6 Touch pad channel 6 is GPIO14(ESP32) / GPIO6(ESP32-S2) - enumerator TOUCH_PAD_NUM7 Touch pad channel 7 is GPIO27(ESP32) / GPIO7(ESP32-S2) - enumerator TOUCH_PAD_NUM8 Touch pad channel 8 is GPIO33(ESP32) / GPIO8(ESP32-S2) - enumerator TOUCH_PAD_NUM9 Touch pad channel 9 is GPIO32(ESP32) / GPIO9(ESP32-S2) - enumerator TOUCH_PAD_MAX - enumerator TOUCH_PAD_NUM0 - enum touch_high_volt_t Touch sensor high reference voltage Values: - enumerator TOUCH_HVOLT_KEEP Touch sensor high reference voltage, no change - enumerator TOUCH_HVOLT_2V4 Touch sensor high reference voltage, 2.4V - enumerator TOUCH_HVOLT_2V5 Touch sensor high reference voltage, 2.5V - enumerator TOUCH_HVOLT_2V6 Touch sensor high reference voltage, 2.6V - enumerator TOUCH_HVOLT_2V7 Touch sensor high reference voltage, 2.7V - enumerator TOUCH_HVOLT_MAX - enumerator TOUCH_HVOLT_KEEP - enum touch_low_volt_t Touch sensor low reference voltage Values: - enumerator TOUCH_LVOLT_KEEP Touch sensor low reference voltage, no change - enumerator TOUCH_LVOLT_0V5 Touch sensor low reference voltage, 0.5V - enumerator TOUCH_LVOLT_0V6 Touch sensor low reference voltage, 0.6V - enumerator TOUCH_LVOLT_0V7 Touch sensor low reference voltage, 0.7V - enumerator TOUCH_LVOLT_0V8 Touch sensor low reference voltage, 0.8V - enumerator TOUCH_LVOLT_MAX - enumerator TOUCH_LVOLT_KEEP - enum touch_volt_atten_t Touch sensor high reference voltage attenuation Values: - enumerator TOUCH_HVOLT_ATTEN_KEEP Touch sensor high reference voltage attenuation, no change - enumerator TOUCH_HVOLT_ATTEN_1V5 Touch sensor high reference voltage attenuation, 1.5V attenuation - enumerator TOUCH_HVOLT_ATTEN_1V Touch sensor high reference voltage attenuation, 1.0V attenuation - enumerator TOUCH_HVOLT_ATTEN_0V5 Touch sensor high reference voltage attenuation, 0.5V attenuation - enumerator TOUCH_HVOLT_ATTEN_0V Touch sensor high reference voltage attenuation, 0V attenuation - enumerator TOUCH_HVOLT_ATTEN_MAX - enumerator TOUCH_HVOLT_ATTEN_KEEP - enum touch_cnt_slope_t Touch sensor charge/discharge speed Values: - enumerator TOUCH_PAD_SLOPE_0 Touch sensor charge / discharge speed, always zero - enumerator TOUCH_PAD_SLOPE_1 Touch sensor charge / discharge speed, slowest - enumerator TOUCH_PAD_SLOPE_2 Touch sensor charge / discharge speed - enumerator TOUCH_PAD_SLOPE_3 Touch sensor charge / discharge speed - enumerator TOUCH_PAD_SLOPE_4 Touch sensor charge / discharge speed - enumerator TOUCH_PAD_SLOPE_5 Touch sensor charge / discharge speed - enumerator TOUCH_PAD_SLOPE_6 Touch sensor charge / discharge speed - enumerator TOUCH_PAD_SLOPE_7 Touch sensor charge / discharge speed, fast - enumerator TOUCH_PAD_SLOPE_MAX - enumerator TOUCH_PAD_SLOPE_0 - enum touch_tie_opt_t Touch sensor initial charge level Values: - enumerator TOUCH_PAD_TIE_OPT_LOW Initial level of charging voltage, low level - enumerator TOUCH_PAD_TIE_OPT_HIGH Initial level of charging voltage, high level - enumerator TOUCH_PAD_TIE_OPT_MAX - enumerator TOUCH_PAD_TIE_OPT_LOW - enum touch_fsm_mode_t Touch sensor FSM mode Values: - enumerator TOUCH_FSM_MODE_TIMER To start touch FSM by timer - enumerator TOUCH_FSM_MODE_SW To start touch FSM by software trigger - enumerator TOUCH_FSM_MODE_MAX - enumerator TOUCH_FSM_MODE_TIMER - enum touch_trigger_mode_t Values: - enumerator TOUCH_TRIGGER_BELOW Touch interrupt will happen if counter value is less than threshold. - enumerator TOUCH_TRIGGER_ABOVE Touch interrupt will happen if counter value is larger than threshold. - enumerator TOUCH_TRIGGER_MAX - enumerator TOUCH_TRIGGER_BELOW
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/touch_pad.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Two-Wire Automotive Interface (TWAI)
null
espressif.com
2016-01-01
aeddf81e68a6f9cb
null
null
Two-Wire Automotive Interface (TWAI) Overview The Two-Wire Automotive Interface (TWAI) is a real-time serial communication protocol suited for automotive and industrial applications. It is compatible with ISO11898-1 Classical frames, thus can support Standard Frame Format (11-bit ID) and Extended Frame Format (29-bit ID). The ESP32 contains 1 TWAI controller(s) that can be configured to communicate on a TWAI bus via an external transceiver. Warning The TWAI controller is not compatible with ISO11898-1 FD Format frames, and will interpret such frames as errors. This programming guide is split into the following sections: TWAI Protocol Summary The TWAI is a multi-master, multi-cast, asynchronous, serial communication protocol. TWAI also supports error detection and signalling, and inbuilt message prioritization. Multi-master: Any node on the bus can initiate the transfer of a message. Multi-cast: When a node transmits a message, all nodes on the bus will receive the message (i.e., broadcast) thus ensuring data consistency across all nodes. However, some nodes can selectively choose which messages to accept via the use of acceptance filtering (multi-cast). Asynchronous: The bus does not contain a clock signal. All nodes on the bus operate at the same bit rate and synchronize using the edges of the bits transmitted on the bus. Error Detection and Signaling: Every node constantly monitors the bus. When any node detects an error, it signals the detection by transmitting an error frame. Other nodes will receive the error frame and transmit their own error frames in response. This results in an error detection being propagated to all nodes on the bus. Message Priorities: Messages contain an ID field. If two or more nodes attempt to transmit simultaneously, the node transmitting the message with the lower ID value will win arbitration of the bus. All other nodes will become receivers ensuring that there is at most one transmitter at any time. TWAI Messages TWAI Messages are split into Data Frames and Remote Frames. Data Frames are used to deliver a data payload to other nodes, whereas a Remote Frame is used to request a Data Frame from other nodes (other nodes can optionally respond with a Data Frame). Data and Remote Frames have two frame formats known as Extended Frame and Standard Frame which contain a 29-bit ID and an 11-bit ID respectively. A TWAI message consists of the following fields: 29-bit or 11-bit ID: Determines the priority of the message (lower value has higher priority). Data Length Code (DLC) between 0 to 8: Indicates the size (in bytes) of the data payload for a Data Frame, or the amount of data to request for a Remote Frame. Up to 8 bytes of data for a Data Frame (should match DLC). Error States and Counters The TWAI protocol implements a feature known as "fault confinement" where a persistently erroneous node will eventually eliminate itself from the bus. This is implemented by requiring every node to maintain two internal error counters known as the Transmit Error Counter (TEC) and the Receive Error Counter (REC). The two error counters are incremented and decremented according to a set of rules (where the counters increase on an error, and decrease on a successful message transmission/reception). The values of the counters are used to determine a node's error state, namely Error Active, Error Passive, and Bus-Off. Error Active: A node is Error Active when both TEC and REC are less than 128 and indicates that the node is operating normally. Error Active nodes are allowed to participate in bus communications, and will actively signal the detection of any errors by automatically transmitting an Active Error Flag over the bus. Error Passive: A node is Error Passive when either the TEC or REC becomes greater than or equal to 128. Error Passive nodes are still able to take part in bus communications, but will instead transmit a Passive Error Flag upon detection of an error. Bus-Off: A node becomes Bus-Off when the TEC becomes greater than or equal to 256. A Bus-Off node is unable influence the bus in any manner (essentially disconnected from the bus) thus eliminating itself from the bus. A node will remain in the Bus-Off state until it undergoes bus-off recovery. Signals Lines and Transceiver The TWAI controller does not contain a integrated transceiver. Therefore, to connect the TWAI controller to a TWAI bus, an external transceiver is required. The type of external transceiver used should depend on the application's physical layer specification (e.g., using SN65HVD23x transceivers for ISO 11898-2 compatibility). The TWAI controller's interface consists of 4 signal lines known as TX, RX, BUS-OFF, and CLKOUT. These four signal lines can be routed through the GPIO Matrix to the ESP32's GPIO pads. TX and RX: The TX and RX signal lines are required to interface with an external transceiver. Both signal lines represent/interpret a dominant bit as a low logic level (0 V), and a recessive bit as a high logic level (3.3 V). BUS-OFF: The BUS-OFF signal line is optional and is set to a low logic level (0 V) whenever the TWAI controller reaches a bus-off state. The BUS-OFF signal line is set to a high logic level (3.3 V) otherwise. CLKOUT: The CLKOUT signal line is optional and outputs a prescaled version of the controller's source clock. Note An external transceiver must internally loopback the TX to RX such that a change in logic level to the TX signal line can be observed on the RX line. Failing to do so will cause the TWAI controller to interpret differences in logic levels between the two signal lines as a loss in arbitration or a bit error. API Naming Conventions Note The TWAI driver provides two sets of API. One is handle-free and is widely used in IDF versions earlier than v5.2, but it can only support one TWAI hardware controller. The other set is with handles, and the function name is usually suffixed with "v2", which can support any number of TWAI controllers. These two sets of API can be used at the same time, but it is recommended to use the "v2" version in your new projects. Driver Configuration This section covers how to configure the TWAI driver. Operating Modes The TWAI driver supports the following modes of operations: Normal Mode: The normal operating mode allows the TWAI controller to take part in bus activities such as transmitting and receiving messages/error frames. Acknowledgement from another node is required when transmitting a message. No Ack Mode: The No Acknowledgement mode is similar to normal mode, however acknowledgements are not required for a message transmission to be considered successful. This mode is useful when self testing the TWAI controller (loopback of transmissions). Listen Only Mode: This mode prevents the TWAI controller from influencing the bus. Therefore, transmission of messages/acknowledgement/error frames will be disabled. However the TWAI controller is still able to receive messages but will not acknowledge the message. This mode is suited for bus monitor applications. Alerts The TWAI driver contains an alert feature that is used to notify the application layer of certain TWAI controller or TWAI bus events. Alerts are selectively enabled when the TWAI driver is installed, but can be reconfigured during runtime by calling twai_reconfigure_alerts() . The application can then wait for any enabled alerts to occur by calling twai_read_alerts() . The TWAI driver supports the following alerts: Alert Flag Description No more messages queued for transmission The previous transmission was successful A frame has been received and added to the RX queue Both error counters have dropped below error warning limit TWAI controller has become error active TWAI controller is undergoing bus recovery TWAI controller has successfully completed bus recovery The previous transmission lost arbitration One of the error counters have exceeded the error warning limit A (Bit, Stuff, CRC, Form, ACK) error has occurred on the bus The previous transmission has failed The RX queue is full causing a received frame to be lost TWAI controller has become error passive Bus-off condition occurred. TWAI controller can no longer influence bus Note The TWAI controller's error warning limit is used to preemptively warn the application of bus errors before the error passive state is reached. By default, the TWAI driver sets the error warning limit to 96. The TWAI_ALERT_ABOVE_ERR_WARN is raised when the TEC or REC becomes larger then or equal to the error warning limit. The TWAI_ALERT_BELOW_ERR_WARN is raised when both TEC and REC return back to values below 96. Note When enabling alerts, the TWAI_ALERT_AND_LOG flag can be used to cause the TWAI driver to log any raised alerts to UART. However, alert logging is disabled and TWAI_ALERT_AND_LOG if the CONFIG_TWAI_ISR_IN_IRAM option is enabled (see Placing ISR into IRAM). Note The TWAI_ALERT_ALL and TWAI_ALERT_NONE macros can also be used to enable/disable all alerts during configuration/reconfiguration. Bit Timing The operating bit rate of the TWAI driver is configured using the twai_timing_config_t structure. The period of each bit is made up of multiple time quanta, and the period of a time quantum is determined by a pre-scaled version of the TWAI controller's source clock. A single bit contains the following segments in the following order: The Synchronization Segment consists of a single time quantum Timing Segment 1 consists of 1 to 16 time quanta before sample point Timing Segment 2 consists of 1 to 8 time quanta after sample point The Baudrate Prescaler is used to determine the period of each time quantum by dividing the TWAI controller's source clock. On the ESP32, the brp can be any even number from 2 to 128. Alternatively, you can decide the resolution of each quantum, by setting twai_timing_config_t::quanta_resolution_hz to a non-zero value. In this way, the driver can calculate the underlying brp value for you. It is useful when you set different clock sources but want the bitrate to keep the same. Supported clock source for a TWAI controller is listed in the twai_clock_source_t and can be specified in twai_timing_config_t::clk_src . If the ESP32 is a revision 2 or later chip, the brp will also support any multiple of 4 from 132 to 256, and can be enabled by setting the CONFIG_ESP32_REV_MIN to revision 2 or higher. The sample point of a bit is located on the intersection of Timing Segment 1 and 2. Enabling Triple Sampling causes 3 time quanta to be sampled per bit instead of 1 (extra samples are located at the tail end of Timing Segment 1). The Synchronization Jump Width is used to determine the maximum number of time quanta a single bit time can be lengthened/shortened for synchronization purposes. sjw can range from 1 to 4. Note Multiple combinations of brp , tseg_1 , tseg_2 , and sjw can achieve the same bit rate. Users should tune these values to the physical characteristics of their bus by taking into account factors such as propagation delay, node information processing time, and phase errors. Bit timing macro initializers are also available for commonly used bit rates. The following macro initializers are provided by the TWAI driver. TWAI_TIMING_CONFIG_1MBITS TWAI_TIMING_CONFIG_800KBITS TWAI_TIMING_CONFIG_500KBITS TWAI_TIMING_CONFIG_250KBITS TWAI_TIMING_CONFIG_125KBITS TWAI_TIMING_CONFIG_100KBITS TWAI_TIMING_CONFIG_50KBITS TWAI_TIMING_CONFIG_25KBITS Revision 2 or later of the ESP32 also supports the following bit rates: TWAI_TIMING_CONFIG_20KBITS TWAI_TIMING_CONFIG_16KBITS TWAI_TIMING_CONFIG_12_5KBITS Acceptance Filter The TWAI controller contains a hardware acceptance filter which can be used to filter messages of a particular ID. A node that filters out a message does not receive the message, but will still acknowledge it. Acceptance filters can make a node more efficient by filtering out messages sent over the bus that are irrelevant to the node. The acceptance filter is configured using two 32-bit values within twai_filter_config_t known as the acceptance code and the acceptance mask. The acceptance code specifies the bit sequence which a message's ID, RTR, and data bytes must match in order for the message to be received by the TWAI controller. The acceptance mask is a bit sequence specifying which bits of the acceptance code can be ignored. This allows for a messages of different IDs to be accepted by a single acceptance code. The acceptance filter can be used under Single or Dual Filter Mode. Single Filter Mode uses the acceptance code and mask to define a single filter. This allows for the first two data bytes of a standard frame to be filtered, or the entirety of an extended frame's 29-bit ID. The following diagram illustrates how the 32-bit acceptance code and mask are interpreted under Single Filter Mode (Note: The yellow and blue fields represent standard and extended frame formats respectively). Dual Filter Mode uses the acceptance code and mask to define two separate filters allowing for increased flexibility of ID's to accept, but does not allow for all 29-bits of an extended ID to be filtered. The following diagram illustrates how the 32-bit acceptance code and mask are interpreted under Dual Filter Mode (Note: The yellow and blue fields represent standard and extended frame formats respectively). Disabling TX Queue The TX queue can be disabled during configuration by setting the tx_queue_len member of twai_general_config_t to 0 . This allows applications that do not require message transmission to save a small amount of memory when using the TWAI driver. Placing ISR into IRAM The TWAI driver's ISR (Interrupt Service Routine) can be placed into IRAM so that the ISR can still run whilst the cache is disabled. Placing the ISR into IRAM may be necessary to maintain the TWAI driver's functionality during lengthy cache disabling operations (such as SPI Flash writes, OTA updates etc). Whilst the cache is disabled, the ISR continues to: Read received messages from the RX buffer and place them into the driver's RX queue. Load messages pending transmission from the driver's TX queue and write them into the TX buffer. To place the TWAI driver's ISR, users must do the following: Enable the CONFIG_TWAI_ISR_IN_IRAM option using idf.py menuconfig . When calling twai_driver_install() , the intr_flags member of twai_general_config_t should set the ESP_INTR_FLAG_IRAM set. Note When the CONFIG_TWAI_ISR_IN_IRAM option is enabled, the TWAI driver will no longer log any alerts (i.e., the TWAI_ALERT_AND_LOG flag will not have any effect). ESP32 Errata Workarounds The ESP32's TWAI controller contains multiple hardware errata (more details about the errata can be found in the ESP32's ECO document). Some of these errata are critical, and under specific circumstances, can place the TWAI controller into an unrecoverable state (i.e., the controller gets stuck until it is reset by the CPU). The TWAI driver contains software workarounds for these critical errata. With these workarounds, the ESP32 TWAI driver can operate normally, albeit with degraded performance. The degraded performance will affect users in the following ways depending on what particular errata conditions are encountered: The TWAI driver can occasionally drop some received messages. The TWAI driver can be unresponsive for a short period of time (i.e., will not transmit or ACK for 11 bit times or longer). If CONFIG_TWAI_ISR_IN_IRAM is enabled, the workarounds will increase IRAM usage by approximately 1 KB. The software workarounds are enabled by default and it is recommended that users keep this workarounds enabled. Driver Operation The TWAI driver is designed with distinct states and strict rules regarding the functions or conditions that trigger a state transition. The following diagram illustrates the various states and their transitions. Label Transition Action/Condition A Uninstalled > Stopped B Stopped > Uninstalled C Stopped > Running D Running > Stopped E Running > Bus-Off Transmit Error Counter >= 256 F Bus-Off > Uninstalled G Bus-Off > Recovering H Recovering > Stopped 128 occurrences of 11 consecutive recessive bits. Driver States Uninstalled: In the uninstalled state, no memory is allocated for the driver and the TWAI controller is powered OFF. Stopped: In this state, the TWAI controller is powered ON and the TWAI driver has been installed. However the TWAI controller is unable to take part in any bus activities such as transmitting, receiving, or acknowledging messages. Running: In the running state, the TWAI controller is able to take part in bus activities. Therefore messages can be transmitted/received/acknowledged. Furthermore, the TWAI controller is able to transmit error frames upon detection of errors on the bus. Bus-Off: The bus-off state is automatically entered when the TWAI controller's Transmit Error Counter becomes greater than or equal to 256. The bus-off state indicates the occurrence of severe errors on the bus or in the TWAI controller. Whilst in the bus-off state, the TWAI controller is unable to take part in any bus activities. To exit the bus-off state, the TWAI controller must undergo the bus recovery process. Recovering: The recovering state is entered when the TWAI controller undergoes bus recovery. The TWAI controller/TWAI driver remains in the recovering state until the 128 occurrences of 11 consecutive recessive bits is observed on the bus. Message Fields and Flags The TWAI driver distinguishes different types of messages by using the various bit field members of the twai_message_t structure. These bit field members determine whether a message is in standard or extended format, a remote frame, and the type of transmission to use when transmitting such a message. These bit field members can also be toggled using the flags member of twai_message_t and the following message flags: Message Flag Description Message is in Extended Frame Format (29bit ID) Message is a Remote Frame (Remote Transmission Request) Transmit message using Single Shot Transmission (Message will not be retransmitted upon error or loss of arbitration). Unused for received message. Transmit message using Self Reception Request (Transmitted message will also received by the same node). Unused for received message. Message's Data length code is larger than 8. This will break compliance with TWAI Clears all bit fields. Equivalent to a Standard Frame Format (11bit ID) Data Frame. Examples Configuration & Installation The following code snippet demonstrates how to configure, install, and start the TWAI driver via the use of the various configuration structures, macro initializers, the twai_driver_install() function, and the twai_start() function. #include "driver/gpio.h" #include "driver/twai.h" void app_main() { //Initialize configuration structures using macro initializers twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(GPIO_NUM_21, GPIO_NUM_22, TWAI_MODE_NORMAL); twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS(); twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL(); //Install TWAI driver if (twai_driver_install(&g_config, &t_config, &f_config) == ESP_OK) { printf("Driver installed\n"); } else { printf("Failed to install driver\n"); return; } //Start TWAI driver if (twai_start() == ESP_OK) { printf("Driver started\n"); } else { printf("Failed to start driver\n"); return; } ... } The usage of macro initializers is not mandatory and each of the configuration structures can be manually. Install Multiple TWAI Instances The following code snippet demonstrates how to install multiple TWAI instances via the use of the twai_driver_install_v2() function. #include "driver/gpio.h" #include "driver/twai.h" void app_main() { twai_handle_t twai_bus_0; twai_handle_t twai_bus_1; //Initialize configuration structures using macro initializers twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(GPIO_NUM_0, GPIO_NUM_1, TWAI_MODE_NORMAL); twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS(); twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL(); //Install driver for TWAI bus 0 g_config.controller_id = 0; if (twai_driver_install_v2(&g_config, &t_config, &f_config, &twai_bus_0) == ESP_OK) { printf("Driver installed\n"); } else { printf("Failed to install driver\n"); return; } //Start TWAI driver if (twai_start_v2(twai_bus_0) == ESP_OK) { printf("Driver started\n"); } else { printf("Failed to start driver\n"); return; } //Install driver for TWAI bus 1 g_config.controller_id = 1; g_config.tx_io = GPIO_NUM_2; g_config.rx_io = GPIO_NUM_3; if (twai_driver_install_v2(&g_config, &t_config, &f_config, &twai_bus_1) == ESP_OK) { printf("Driver installed\n"); } else { printf("Failed to install driver\n"); return; } //Start TWAI driver if (twai_start_v2(twai_bus_1) == ESP_OK) { printf("Driver started\n"); } else { printf("Failed to start driver\n"); return; } //Other Driver operations must use version 2 API as well ... } Message Transmission The following code snippet demonstrates how to transmit a message via the usage of the twai_message_t type and twai_transmit() function. #include "driver/twai.h" ... //Configure message to transmit twai_message_t message; message.identifier = 0xAAAA; message.extd = 1; message.data_length_code = 4; for (int i = 0; i < 4; i++) { message.data[i] = 0; } //Queue message for transmission if (twai_transmit(&message, pdMS_TO_TICKS(1000)) == ESP_OK) { printf("Message queued for transmission\n"); } else { printf("Failed to queue message for transmission\n"); } Message Reception The following code snippet demonstrates how to receive a message via the usage of the twai_message_t type and twai_receive() function. #include "driver/twai.h" ... //Wait for message to be received twai_message_t message; if (twai_receive(&message, pdMS_TO_TICKS(10000)) == ESP_OK) { printf("Message received\n"); } else { printf("Failed to receive message\n"); return; } //Process received message if (message.extd) { printf("Message is in Extended Format\n"); } else { printf("Message is in Standard Format\n"); } printf("ID is %d\n", message.identifier); if (!(message.rtr)) { for (int i = 0; i < message.data_length_code; i++) { printf("Data byte %d = %d\n", i, message.data[i]); } } Reconfiguring and Reading Alerts The following code snippet demonstrates how to reconfigure and read TWAI driver alerts via the use of the twai_reconfigure_alerts() and twai_read_alerts() functions. #include "driver/twai.h" ... //Reconfigure alerts to detect Error Passive and Bus-Off error states uint32_t alerts_to_enable = TWAI_ALERT_ERR_PASS | TWAI_ALERT_BUS_OFF; if (twai_reconfigure_alerts(alerts_to_enable, NULL) == ESP_OK) { printf("Alerts reconfigured\n"); } else { printf("Failed to reconfigure alerts"); } //Block indefinitely until an alert occurs uint32_t alerts_triggered; twai_read_alerts(&alerts_triggered, portMAX_DELAY); Stop and Uninstall The following code demonstrates how to stop and uninstall the TWAI driver via the use of the twai_stop() and twai_driver_uninstall() functions. #include "driver/twai.h" ... //Stop the TWAI driver if (twai_stop() == ESP_OK) { printf("Driver stopped\n"); } else { printf("Failed to stop driver\n"); return; } //Uninstall the TWAI driver if (twai_driver_uninstall() == ESP_OK) { printf("Driver uninstalled\n"); } else { printf("Failed to uninstall driver\n"); return; } Multiple ID Filter Configuration The acceptance mask in twai_filter_config_t can be configured such that two or more IDs are accepted for a single filter. For a particular filter to accept multiple IDs, the conflicting bit positions amongst the IDs must be set in the acceptance mask. The acceptance code can be set to any one of the IDs. The following example shows how the calculate the acceptance mask given multiple IDs: ID1 = 11'b101 1010 0000 ID2 = 11'b101 1010 0001 ID3 = 11'b101 1010 0100 ID4 = 11'b101 1010 1000 //Acceptance Mask MASK = 11'b000 0000 1101 Application Examples Network Example: The TWAI Network example demonstrates communication between two ESP32s using the TWAI driver API. One TWAI node acts as a network master that initiates and ceases the transfer of a data from another node acting as a network slave. The example can be found via peripherals/twai/twai_network. Alert and Recovery Example: This example demonstrates how to use the TWAI driver's alert and bus-off recovery API. The example purposely introduces errors on the bus to put the TWAI controller into the Bus-Off state. An alert is used to detect the Bus-Off state and trigger the bus recovery process. The example can be found via peripherals/twai/twai_alert_and_recovery. Self Test Example: This example uses the No Acknowledge Mode and Self Reception Request to cause the TWAI controller to send and simultaneously receive a series of messages. This example can be used to verify if the connections between the TWAI controller and the external transceiver are working correctly. The example can be found via peripherals/twai/twai_self_test. API Reference Header File This header file can be included with: #include "hal/twai_types.h" Structures struct twai_message_t Structure to store a TWAI message. Note The flags member is deprecated Public Members uint32_t extd Extended Frame Format (29bit ID) uint32_t extd Extended Frame Format (29bit ID) uint32_t rtr Message is a Remote Frame uint32_t rtr Message is a Remote Frame uint32_t ss Transmit as a Single Shot Transmission. Unused for received. uint32_t ss Transmit as a Single Shot Transmission. Unused for received. uint32_t self Transmit as a Self Reception Request. Unused for received. uint32_t self Transmit as a Self Reception Request. Unused for received. uint32_t dlc_non_comp Message's Data length code is larger than 8. This will break compliance with ISO 11898-1 uint32_t dlc_non_comp Message's Data length code is larger than 8. This will break compliance with ISO 11898-1 uint32_t reserved Reserved bits uint32_t reserved Reserved bits uint32_t flags Deprecated: Alternate way to set bits using message flags uint32_t flags Deprecated: Alternate way to set bits using message flags uint32_t identifier 11 or 29 bit identifier uint32_t identifier 11 or 29 bit identifier uint8_t data_length_code Data length code uint8_t data_length_code Data length code uint8_t data[TWAI_FRAME_MAX_DLC] Data bytes (not relevant in RTR frame) uint8_t data[TWAI_FRAME_MAX_DLC] Data bytes (not relevant in RTR frame) uint32_t extd struct twai_timing_config_t Structure for bit timing configuration of the TWAI driver. Note Macro initializers are available for this structure Public Members twai_clock_source_t clk_src Clock source, set to 0 or TWAI_CLK_SRC_DEFAULT if you want a default clock source twai_clock_source_t clk_src Clock source, set to 0 or TWAI_CLK_SRC_DEFAULT if you want a default clock source uint32_t quanta_resolution_hz The resolution of one timing quanta, in Hz. Note: the value of brp will reflected by this field if it's non-zero, otherwise, brp needs to be set manually uint32_t quanta_resolution_hz The resolution of one timing quanta, in Hz. Note: the value of brp will reflected by this field if it's non-zero, otherwise, brp needs to be set manually uint32_t brp Baudrate prescale (i.e., clock divider). Any even number from 2 to 128 for ESP32, 2 to 32768 for non-ESP32 chip. Note: For ESP32 ECO 2 or later, multiples of 4 from 132 to 256 are also supported uint32_t brp Baudrate prescale (i.e., clock divider). Any even number from 2 to 128 for ESP32, 2 to 32768 for non-ESP32 chip. Note: For ESP32 ECO 2 or later, multiples of 4 from 132 to 256 are also supported uint8_t tseg_1 Timing segment 1 (Number of time quanta, between 1 to 16) uint8_t tseg_1 Timing segment 1 (Number of time quanta, between 1 to 16) uint8_t tseg_2 Timing segment 2 (Number of time quanta, 1 to 8) uint8_t tseg_2 Timing segment 2 (Number of time quanta, 1 to 8) uint8_t sjw Synchronization Jump Width (Max time quanta jump for synchronize from 1 to 4) uint8_t sjw Synchronization Jump Width (Max time quanta jump for synchronize from 1 to 4) bool triple_sampling Enables triple sampling when the TWAI controller samples a bit bool triple_sampling Enables triple sampling when the TWAI controller samples a bit twai_clock_source_t clk_src struct twai_filter_config_t Structure for acceptance filter configuration of the TWAI driver (see documentation) Note Macro initializers are available for this structure Macros TWAI_EXTD_ID_MASK TWAI Constants. Bit mask for 29 bit Extended Frame Format ID TWAI_STD_ID_MASK Bit mask for 11 bit Standard Frame Format ID TWAI_FRAME_MAX_DLC Max data bytes allowed in TWAI TWAI_FRAME_EXTD_ID_LEN_BYTES EFF ID requires 4 bytes (29bit) TWAI_FRAME_STD_ID_LEN_BYTES SFF ID requires 2 bytes (11bit) TWAI_ERR_PASS_THRESH Error counter threshold for error passive Type Definitions typedef soc_periph_twai_clk_src_t twai_clock_source_t RMT group clock source. Note User should select the clock source based on the power and resolution requirement Enumerations enum twai_mode_t TWAI Controller operating modes. Values: enumerator TWAI_MODE_NORMAL Normal operating mode where TWAI controller can send/receive/acknowledge messages enumerator TWAI_MODE_NORMAL Normal operating mode where TWAI controller can send/receive/acknowledge messages enumerator TWAI_MODE_NO_ACK Transmission does not require acknowledgment. Use this mode for self testing enumerator TWAI_MODE_NO_ACK Transmission does not require acknowledgment. Use this mode for self testing enumerator TWAI_MODE_LISTEN_ONLY The TWAI controller will not influence the bus (No transmissions or acknowledgments) but can receive messages enumerator TWAI_MODE_LISTEN_ONLY The TWAI controller will not influence the bus (No transmissions or acknowledgments) but can receive messages enumerator TWAI_MODE_NORMAL Header File This header file can be included with: #include "driver/twai.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t twai_driver_install(const twai_general_config_t *g_config, const twai_timing_config_t *t_config, const twai_filter_config_t *f_config) Install TWAI driver. This function installs the TWAI driver using three configuration structures. The required memory is allocated and the TWAI driver is placed in the stopped state after running this function. Note Macro initializers are available for the configuration structures (see documentation) Note To reinstall the TWAI driver, call twai_driver_uninstall() first Parameters g_config -- [in] General configuration structure t_config -- [in] Timing configuration structure f_config -- [in] Filter configuration structure g_config -- [in] General configuration structure t_config -- [in] Timing configuration structure f_config -- [in] Filter configuration structure g_config -- [in] General configuration structure Returns ESP_OK: Successfully installed TWAI driver ESP_ERR_INVALID_ARG: Arguments are invalid, e.g. invalid clock source, invalid quanta resolution ESP_ERR_NO_MEM: Insufficient memory ESP_ERR_INVALID_STATE: Driver is already installed ESP_OK: Successfully installed TWAI driver ESP_ERR_INVALID_ARG: Arguments are invalid, e.g. invalid clock source, invalid quanta resolution ESP_ERR_NO_MEM: Insufficient memory ESP_ERR_INVALID_STATE: Driver is already installed ESP_OK: Successfully installed TWAI driver Parameters g_config -- [in] General configuration structure t_config -- [in] Timing configuration structure f_config -- [in] Filter configuration structure Returns ESP_OK: Successfully installed TWAI driver ESP_ERR_INVALID_ARG: Arguments are invalid, e.g. invalid clock source, invalid quanta resolution ESP_ERR_NO_MEM: Insufficient memory ESP_ERR_INVALID_STATE: Driver is already installed esp_err_t twai_driver_install_v2(const twai_general_config_t *g_config, const twai_timing_config_t *t_config, const twai_filter_config_t *f_config, twai_handle_t *ret_twai) Install TWAI driver and return a handle. Note This is an advanced version of twai_driver_install that can return a driver handle, so that it allows you to install multiple TWAI drivers. Don't forget to set the proper controller_id in the twai_general_config_t Please refer to the documentation of twai_driver_install for more details. Parameters g_config -- [in] General configuration structure t_config -- [in] Timing configuration structure f_config -- [in] Filter configuration structure ret_twai -- [out] Pointer to a new created TWAI handle g_config -- [in] General configuration structure t_config -- [in] Timing configuration structure f_config -- [in] Filter configuration structure ret_twai -- [out] Pointer to a new created TWAI handle g_config -- [in] General configuration structure Returns ESP_OK: Successfully installed TWAI driver ESP_ERR_INVALID_ARG: Arguments are invalid, e.g. invalid clock source, invalid quanta resolution, invalid controller ID ESP_ERR_NO_MEM: Insufficient memory ESP_ERR_INVALID_STATE: Driver is already installed ESP_OK: Successfully installed TWAI driver ESP_ERR_INVALID_ARG: Arguments are invalid, e.g. invalid clock source, invalid quanta resolution, invalid controller ID ESP_ERR_NO_MEM: Insufficient memory ESP_ERR_INVALID_STATE: Driver is already installed ESP_OK: Successfully installed TWAI driver Parameters g_config -- [in] General configuration structure t_config -- [in] Timing configuration structure f_config -- [in] Filter configuration structure ret_twai -- [out] Pointer to a new created TWAI handle Returns ESP_OK: Successfully installed TWAI driver ESP_ERR_INVALID_ARG: Arguments are invalid, e.g. invalid clock source, invalid quanta resolution, invalid controller ID ESP_ERR_NO_MEM: Insufficient memory ESP_ERR_INVALID_STATE: Driver is already installed esp_err_t twai_driver_uninstall(void) Uninstall the TWAI driver. This function uninstalls the TWAI driver, freeing the memory utilized by the driver. This function can only be called when the driver is in the stopped state or the bus-off state. Warning The application must ensure that no tasks are blocked on TX/RX queues or alerts when this function is called. Returns ESP_OK: Successfully uninstalled TWAI driver ESP_ERR_INVALID_STATE: Driver is not in stopped/bus-off state, or is not installed ESP_OK: Successfully uninstalled TWAI driver ESP_ERR_INVALID_STATE: Driver is not in stopped/bus-off state, or is not installed ESP_OK: Successfully uninstalled TWAI driver Returns ESP_OK: Successfully uninstalled TWAI driver ESP_ERR_INVALID_STATE: Driver is not in stopped/bus-off state, or is not installed esp_err_t twai_driver_uninstall_v2(twai_handle_t handle) Uninstall the TWAI driver with a given handle. Note This is an advanced version of twai_driver_uninstall that can uninstall a TWAI driver with a given handle. Please refer to the documentation of twai_driver_uninstall for more details. Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: Successfully uninstalled TWAI driver ESP_ERR_INVALID_STATE: Driver is not in stopped/bus-off state, or is not installed ESP_OK: Successfully uninstalled TWAI driver ESP_ERR_INVALID_STATE: Driver is not in stopped/bus-off state, or is not installed ESP_OK: Successfully uninstalled TWAI driver Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: Successfully uninstalled TWAI driver ESP_ERR_INVALID_STATE: Driver is not in stopped/bus-off state, or is not installed esp_err_t twai_start(void) Start the TWAI driver. This function starts the TWAI driver, putting the TWAI driver into the running state. This allows the TWAI driver to participate in TWAI bus activities such as transmitting/receiving messages. The TX and RX queue are reset in this function, clearing any messages that are unread or pending transmission. This function can only be called when the TWAI driver is in the stopped state. Returns ESP_OK: TWAI driver is now running ESP_ERR_INVALID_STATE: Driver is not in stopped state, or is not installed ESP_OK: TWAI driver is now running ESP_ERR_INVALID_STATE: Driver is not in stopped state, or is not installed ESP_OK: TWAI driver is now running Returns ESP_OK: TWAI driver is now running ESP_ERR_INVALID_STATE: Driver is not in stopped state, or is not installed esp_err_t twai_start_v2(twai_handle_t handle) Start the TWAI driver with a given handle. Note This is an advanced version of twai_start that can start a TWAI driver with a given handle. Please refer to the documentation of twai_start for more details. Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: TWAI driver is now running ESP_ERR_INVALID_STATE: Driver is not in stopped state, or is not installed ESP_OK: TWAI driver is now running ESP_ERR_INVALID_STATE: Driver is not in stopped state, or is not installed ESP_OK: TWAI driver is now running Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: TWAI driver is now running ESP_ERR_INVALID_STATE: Driver is not in stopped state, or is not installed esp_err_t twai_stop(void) Stop the TWAI driver. This function stops the TWAI driver, preventing any further message from being transmitted or received until twai_start() is called. Any messages in the TX queue are cleared. Any messages in the RX queue should be read by the application after this function is called. This function can only be called when the TWAI driver is in the running state. Warning A message currently being transmitted/received on the TWAI bus will be ceased immediately. This may lead to other TWAI nodes interpreting the unfinished message as an error. Returns ESP_OK: TWAI driver is now Stopped ESP_ERR_INVALID_STATE: Driver is not in running state, or is not installed ESP_OK: TWAI driver is now Stopped ESP_ERR_INVALID_STATE: Driver is not in running state, or is not installed ESP_OK: TWAI driver is now Stopped Returns ESP_OK: TWAI driver is now Stopped ESP_ERR_INVALID_STATE: Driver is not in running state, or is not installed esp_err_t twai_stop_v2(twai_handle_t handle) Stop the TWAI driver with a given handle. Note This is an advanced version of twai_stop that can stop a TWAI driver with a given handle. Please refer to the documentation of twai_stop for more details. Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: TWAI driver is now Stopped ESP_ERR_INVALID_STATE: Driver is not in running state, or is not installed ESP_OK: TWAI driver is now Stopped ESP_ERR_INVALID_STATE: Driver is not in running state, or is not installed ESP_OK: TWAI driver is now Stopped Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: TWAI driver is now Stopped ESP_ERR_INVALID_STATE: Driver is not in running state, or is not installed esp_err_t twai_transmit(const twai_message_t *message, TickType_t ticks_to_wait) Transmit a TWAI message. This function queues a TWAI message for transmission. Transmission will start immediately if no other messages are queued for transmission. If the TX queue is full, this function will block until more space becomes available or until it times out. If the TX queue is disabled (TX queue length = 0 in configuration), this function will return immediately if another message is undergoing transmission. This function can only be called when the TWAI driver is in the running state and cannot be called under Listen Only Mode. Note This function does not guarantee that the transmission is successful. The TX_SUCCESS/TX_FAILED alert can be enabled to alert the application upon the success/failure of a transmission. Note The TX_IDLE alert can be used to alert the application when no other messages are awaiting transmission. Parameters message -- [in] Message to transmit ticks_to_wait -- [in] Number of FreeRTOS ticks to block on the TX queue message -- [in] Message to transmit ticks_to_wait -- [in] Number of FreeRTOS ticks to block on the TX queue message -- [in] Message to transmit Returns ESP_OK: Transmission successfully queued/initiated ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_TIMEOUT: Timed out waiting for space on TX queue ESP_FAIL: TX queue is disabled and another message is currently transmitting ESP_ERR_INVALID_STATE: TWAI driver is not in running state, or is not installed ESP_ERR_NOT_SUPPORTED: Listen Only Mode does not support transmissions ESP_OK: Transmission successfully queued/initiated ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_TIMEOUT: Timed out waiting for space on TX queue ESP_FAIL: TX queue is disabled and another message is currently transmitting ESP_ERR_INVALID_STATE: TWAI driver is not in running state, or is not installed ESP_ERR_NOT_SUPPORTED: Listen Only Mode does not support transmissions ESP_OK: Transmission successfully queued/initiated Parameters message -- [in] Message to transmit ticks_to_wait -- [in] Number of FreeRTOS ticks to block on the TX queue Returns ESP_OK: Transmission successfully queued/initiated ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_TIMEOUT: Timed out waiting for space on TX queue ESP_FAIL: TX queue is disabled and another message is currently transmitting ESP_ERR_INVALID_STATE: TWAI driver is not in running state, or is not installed ESP_ERR_NOT_SUPPORTED: Listen Only Mode does not support transmissions esp_err_t twai_transmit_v2(twai_handle_t handle, const twai_message_t *message, TickType_t ticks_to_wait) Transmit a TWAI message via a given handle. Note This is an advanced version of twai_transmit that can transmit a TWAI message with a given handle. Please refer to the documentation of twai_transmit for more details. Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 message -- [in] Message to transmit ticks_to_wait -- [in] Number of FreeRTOS ticks to block on the TX queue handle -- [in] TWAI driver handle returned by twai_driver_install_v2 message -- [in] Message to transmit ticks_to_wait -- [in] Number of FreeRTOS ticks to block on the TX queue handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: Transmission successfully queued/initiated ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_TIMEOUT: Timed out waiting for space on TX queue ESP_FAIL: TX queue is disabled and another message is currently transmitting ESP_ERR_INVALID_STATE: TWAI driver is not in running state, or is not installed ESP_ERR_NOT_SUPPORTED: Listen Only Mode does not support transmissions ESP_OK: Transmission successfully queued/initiated ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_TIMEOUT: Timed out waiting for space on TX queue ESP_FAIL: TX queue is disabled and another message is currently transmitting ESP_ERR_INVALID_STATE: TWAI driver is not in running state, or is not installed ESP_ERR_NOT_SUPPORTED: Listen Only Mode does not support transmissions ESP_OK: Transmission successfully queued/initiated Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 message -- [in] Message to transmit ticks_to_wait -- [in] Number of FreeRTOS ticks to block on the TX queue Returns ESP_OK: Transmission successfully queued/initiated ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_TIMEOUT: Timed out waiting for space on TX queue ESP_FAIL: TX queue is disabled and another message is currently transmitting ESP_ERR_INVALID_STATE: TWAI driver is not in running state, or is not installed ESP_ERR_NOT_SUPPORTED: Listen Only Mode does not support transmissions esp_err_t twai_receive(twai_message_t *message, TickType_t ticks_to_wait) Receive a TWAI message. This function receives a message from the RX queue. The flags field of the message structure will indicate the type of message received. This function will block if there are no messages in the RX queue Warning The flags field of the received message should be checked to determine if the received message contains any data bytes. Parameters message -- [out] Received message ticks_to_wait -- [in] Number of FreeRTOS ticks to block on RX queue message -- [out] Received message ticks_to_wait -- [in] Number of FreeRTOS ticks to block on RX queue message -- [out] Received message Returns ESP_OK: Message successfully received from RX queue ESP_ERR_TIMEOUT: Timed out waiting for message ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Message successfully received from RX queue ESP_ERR_TIMEOUT: Timed out waiting for message ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Message successfully received from RX queue Parameters message -- [out] Received message ticks_to_wait -- [in] Number of FreeRTOS ticks to block on RX queue Returns ESP_OK: Message successfully received from RX queue ESP_ERR_TIMEOUT: Timed out waiting for message ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed esp_err_t twai_receive_v2(twai_handle_t handle, twai_message_t *message, TickType_t ticks_to_wait) Receive a TWAI message via a given handle. Note This is an advanced version of twai_receive that can receive a TWAI message with a given handle. Please refer to the documentation of twai_receive for more details. Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 message -- [out] Received message ticks_to_wait -- [in] Number of FreeRTOS ticks to block on RX queue handle -- [in] TWAI driver handle returned by twai_driver_install_v2 message -- [out] Received message ticks_to_wait -- [in] Number of FreeRTOS ticks to block on RX queue handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: Message successfully received from RX queue ESP_ERR_TIMEOUT: Timed out waiting for message ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Message successfully received from RX queue ESP_ERR_TIMEOUT: Timed out waiting for message ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Message successfully received from RX queue Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 message -- [out] Received message ticks_to_wait -- [in] Number of FreeRTOS ticks to block on RX queue Returns ESP_OK: Message successfully received from RX queue ESP_ERR_TIMEOUT: Timed out waiting for message ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed esp_err_t twai_read_alerts(uint32_t *alerts, TickType_t ticks_to_wait) Read TWAI driver alerts. This function will read the alerts raised by the TWAI driver. If no alert has been issued when this function is called, this function will block until an alert occurs or until it timeouts. Note Multiple alerts can be raised simultaneously. The application should check for all alerts that have been enabled. Parameters alerts -- [out] Bit field of raised alerts (see documentation for alert flags) ticks_to_wait -- [in] Number of FreeRTOS ticks to block for alert alerts -- [out] Bit field of raised alerts (see documentation for alert flags) ticks_to_wait -- [in] Number of FreeRTOS ticks to block for alert alerts -- [out] Bit field of raised alerts (see documentation for alert flags) Returns ESP_OK: Alerts read ESP_ERR_TIMEOUT: Timed out waiting for alerts ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Alerts read ESP_ERR_TIMEOUT: Timed out waiting for alerts ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Alerts read Parameters alerts -- [out] Bit field of raised alerts (see documentation for alert flags) ticks_to_wait -- [in] Number of FreeRTOS ticks to block for alert Returns ESP_OK: Alerts read ESP_ERR_TIMEOUT: Timed out waiting for alerts ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed esp_err_t twai_read_alerts_v2(twai_handle_t handle, uint32_t *alerts, TickType_t ticks_to_wait) Read TWAI driver alerts with a given handle. Note This is an advanced version of twai_read_alerts that can read TWAI driver alerts with a given handle. Please refer to the documentation of twai_read_alerts for more details. Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 alerts -- [out] Bit field of raised alerts (see documentation for alert flags) ticks_to_wait -- [in] Number of FreeRTOS ticks to block for alert handle -- [in] TWAI driver handle returned by twai_driver_install_v2 alerts -- [out] Bit field of raised alerts (see documentation for alert flags) ticks_to_wait -- [in] Number of FreeRTOS ticks to block for alert handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: Alerts read ESP_ERR_TIMEOUT: Timed out waiting for alerts ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Alerts read ESP_ERR_TIMEOUT: Timed out waiting for alerts ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Alerts read Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 alerts -- [out] Bit field of raised alerts (see documentation for alert flags) ticks_to_wait -- [in] Number of FreeRTOS ticks to block for alert Returns ESP_OK: Alerts read ESP_ERR_TIMEOUT: Timed out waiting for alerts ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed esp_err_t twai_reconfigure_alerts(uint32_t alerts_enabled, uint32_t *current_alerts) Reconfigure which alerts are enabled. This function reconfigures which alerts are enabled. If there are alerts which have not been read whilst reconfiguring, this function can read those alerts. Parameters alerts_enabled -- [in] Bit field of alerts to enable (see documentation for alert flags) current_alerts -- [out] Bit field of currently raised alerts. Set to NULL if unused alerts_enabled -- [in] Bit field of alerts to enable (see documentation for alert flags) current_alerts -- [out] Bit field of currently raised alerts. Set to NULL if unused alerts_enabled -- [in] Bit field of alerts to enable (see documentation for alert flags) Returns ESP_OK: Alerts reconfigured ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Alerts reconfigured ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Alerts reconfigured Parameters alerts_enabled -- [in] Bit field of alerts to enable (see documentation for alert flags) current_alerts -- [out] Bit field of currently raised alerts. Set to NULL if unused Returns ESP_OK: Alerts reconfigured ESP_ERR_INVALID_STATE: TWAI driver is not installed esp_err_t twai_reconfigure_alerts_v2(twai_handle_t handle, uint32_t alerts_enabled, uint32_t *current_alerts) Reconfigure which alerts are enabled, with a given handle. Note This is an advanced version of twai_reconfigure_alerts that can reconfigure which alerts are enabled with a given handle. Please refer to the documentation of twai_reconfigure_alerts for more details. Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 alerts_enabled -- [in] Bit field of alerts to enable (see documentation for alert flags) current_alerts -- [out] Bit field of currently raised alerts. Set to NULL if unused handle -- [in] TWAI driver handle returned by twai_driver_install_v2 alerts_enabled -- [in] Bit field of alerts to enable (see documentation for alert flags) current_alerts -- [out] Bit field of currently raised alerts. Set to NULL if unused handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: Alerts reconfigured ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Alerts reconfigured ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Alerts reconfigured Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 alerts_enabled -- [in] Bit field of alerts to enable (see documentation for alert flags) current_alerts -- [out] Bit field of currently raised alerts. Set to NULL if unused Returns ESP_OK: Alerts reconfigured ESP_ERR_INVALID_STATE: TWAI driver is not installed esp_err_t twai_initiate_recovery(void) Start the bus recovery process. This function initiates the bus recovery process when the TWAI driver is in the bus-off state. Once initiated, the TWAI driver will enter the recovering state and wait for 128 occurrences of the bus-free signal on the TWAI bus before returning to the stopped state. This function will reset the TX queue, clearing any messages pending transmission. Note The BUS_RECOVERED alert can be enabled to alert the application when the bus recovery process completes. Returns ESP_OK: Bus recovery started ESP_ERR_INVALID_STATE: TWAI driver is not in the bus-off state, or is not installed ESP_OK: Bus recovery started ESP_ERR_INVALID_STATE: TWAI driver is not in the bus-off state, or is not installed ESP_OK: Bus recovery started Returns ESP_OK: Bus recovery started ESP_ERR_INVALID_STATE: TWAI driver is not in the bus-off state, or is not installed esp_err_t twai_initiate_recovery_v2(twai_handle_t handle) Start the bus recovery process with a given handle. Note This is an advanced version of twai_initiate_recovery that can start the bus recovery process with a given handle. Please refer to the documentation of twai_initiate_recovery for more details. Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: Bus recovery started ESP_ERR_INVALID_STATE: TWAI driver is not in the bus-off state, or is not installed ESP_OK: Bus recovery started ESP_ERR_INVALID_STATE: TWAI driver is not in the bus-off state, or is not installed ESP_OK: Bus recovery started Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: Bus recovery started ESP_ERR_INVALID_STATE: TWAI driver is not in the bus-off state, or is not installed esp_err_t twai_get_status_info(twai_status_info_t *status_info) Get current status information of the TWAI driver. Parameters status_info -- [out] Status information Returns ESP_OK: Status information retrieved ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Status information retrieved ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Status information retrieved Parameters status_info -- [out] Status information Returns ESP_OK: Status information retrieved ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed esp_err_t twai_get_status_info_v2(twai_handle_t handle, twai_status_info_t *status_info) Get current status information of a given TWAI driver handle. Note This is an advanced version of twai_get_status_info that can get current status information of a given TWAI driver handle. Please refer to the documentation of twai_get_status_info for more details. Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 status_info -- [out] Status information handle -- [in] TWAI driver handle returned by twai_driver_install_v2 status_info -- [out] Status information handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: Status information retrieved ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Status information retrieved ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Status information retrieved Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 status_info -- [out] Status information Returns ESP_OK: Status information retrieved ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed esp_err_t twai_clear_transmit_queue(void) Clear the transmit queue. This function will clear the transmit queue of all messages. Note The transmit queue is automatically cleared when twai_stop() or twai_initiate_recovery() is called. Returns ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed or TX queue is disabled ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed or TX queue is disabled ESP_OK: Transmit queue cleared Returns ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed or TX queue is disabled esp_err_t twai_clear_transmit_queue_v2(twai_handle_t handle) Clear the transmit queue of a given TWAI driver handle. Note This is an advanced version of twai_clear_transmit_queue that can clear the transmit queue of a given TWAI driver handle. Please refer to the documentation of twai_clear_transmit_queue for more details. Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed or TX queue is disabled ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed or TX queue is disabled ESP_OK: Transmit queue cleared Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed or TX queue is disabled esp_err_t twai_clear_receive_queue(void) Clear the receive queue. This function will clear the receive queue of all messages. Note The receive queue is automatically cleared when twai_start() is called. Returns ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Transmit queue cleared Returns ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed esp_err_t twai_clear_receive_queue_v2(twai_handle_t handle) Clear the receive queue of a given TWAI driver handle. Note This is an advanced version of twai_clear_receive_queue that can clear the receive queue of a given TWAI driver handle. Please refer to the documentation of twai_clear_receive_queue for more details. Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed ESP_OK: Transmit queue cleared Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 Returns ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed Structures struct twai_general_config_t Structure for general configuration of the TWAI driver. Note Macro initializers are available for this structure Public Members int controller_id TWAI controller ID, index from 0. If you want to install TWAI driver with a non-zero controller_id, please use twai_driver_install_v2 int controller_id TWAI controller ID, index from 0. If you want to install TWAI driver with a non-zero controller_id, please use twai_driver_install_v2 twai_mode_t mode Mode of TWAI controller twai_mode_t mode Mode of TWAI controller gpio_num_t tx_io Transmit GPIO number gpio_num_t tx_io Transmit GPIO number gpio_num_t rx_io Receive GPIO number gpio_num_t rx_io Receive GPIO number gpio_num_t clkout_io CLKOUT GPIO number (optional, set to -1 if unused) gpio_num_t clkout_io CLKOUT GPIO number (optional, set to -1 if unused) gpio_num_t bus_off_io Bus off indicator GPIO number (optional, set to -1 if unused) gpio_num_t bus_off_io Bus off indicator GPIO number (optional, set to -1 if unused) uint32_t tx_queue_len Number of messages TX queue can hold (set to 0 to disable TX Queue) uint32_t tx_queue_len Number of messages TX queue can hold (set to 0 to disable TX Queue) uint32_t rx_queue_len Number of messages RX queue can hold uint32_t rx_queue_len Number of messages RX queue can hold uint32_t alerts_enabled Bit field of alerts to enable (see documentation) uint32_t alerts_enabled Bit field of alerts to enable (see documentation) uint32_t clkout_divider CLKOUT divider. Can be 1 or any even number from 2 to 14 (optional, set to 0 if unused) uint32_t clkout_divider CLKOUT divider. Can be 1 or any even number from 2 to 14 (optional, set to 0 if unused) int intr_flags Interrupt flags to set the priority of the driver's ISR. Note that to use the ESP_INTR_FLAG_IRAM, the CONFIG_TWAI_ISR_IN_IRAM option should be enabled first. int intr_flags Interrupt flags to set the priority of the driver's ISR. Note that to use the ESP_INTR_FLAG_IRAM, the CONFIG_TWAI_ISR_IN_IRAM option should be enabled first. int controller_id struct twai_status_info_t Structure to store status information of TWAI driver. Public Members twai_state_t state Current state of TWAI controller (Stopped/Running/Bus-Off/Recovery) twai_state_t state Current state of TWAI controller (Stopped/Running/Bus-Off/Recovery) uint32_t msgs_to_tx Number of messages queued for transmission or awaiting transmission completion uint32_t msgs_to_tx Number of messages queued for transmission or awaiting transmission completion uint32_t msgs_to_rx Number of messages in RX queue waiting to be read uint32_t msgs_to_rx Number of messages in RX queue waiting to be read uint32_t tx_error_counter Current value of Transmit Error Counter uint32_t tx_error_counter Current value of Transmit Error Counter uint32_t rx_error_counter Current value of Receive Error Counter uint32_t rx_error_counter Current value of Receive Error Counter uint32_t tx_failed_count Number of messages that failed transmissions uint32_t tx_failed_count Number of messages that failed transmissions uint32_t rx_missed_count Number of messages that were lost due to a full RX queue (or errata workaround if enabled) uint32_t rx_missed_count Number of messages that were lost due to a full RX queue (or errata workaround if enabled) uint32_t rx_overrun_count Number of messages that were lost due to a RX FIFO overrun uint32_t rx_overrun_count Number of messages that were lost due to a RX FIFO overrun uint32_t arb_lost_count Number of instances arbitration was lost uint32_t arb_lost_count Number of instances arbitration was lost uint32_t bus_error_count Number of instances a bus error has occurred uint32_t bus_error_count Number of instances a bus error has occurred twai_state_t state Macros TWAI_IO_UNUSED Marks GPIO as unused in TWAI configuration Type Definitions typedef struct twai_obj_t *twai_handle_t TWAI controller handle. Enumerations enum twai_state_t TWAI driver states. Values: enumerator TWAI_STATE_STOPPED Stopped state. The TWAI controller will not participate in any TWAI bus activities enumerator TWAI_STATE_STOPPED Stopped state. The TWAI controller will not participate in any TWAI bus activities enumerator TWAI_STATE_RUNNING Running state. The TWAI controller can transmit and receive messages enumerator TWAI_STATE_RUNNING Running state. The TWAI controller can transmit and receive messages enumerator TWAI_STATE_BUS_OFF Bus-off state. The TWAI controller cannot participate in bus activities until it has recovered enumerator TWAI_STATE_BUS_OFF Bus-off state. The TWAI controller cannot participate in bus activities until it has recovered enumerator TWAI_STATE_RECOVERING Recovering state. The TWAI controller is undergoing bus recovery enumerator TWAI_STATE_RECOVERING Recovering state. The TWAI controller is undergoing bus recovery enumerator TWAI_STATE_STOPPED
Two-Wire Automotive Interface (TWAI) Overview The Two-Wire Automotive Interface (TWAI) is a real-time serial communication protocol suited for automotive and industrial applications. It is compatible with ISO11898-1 Classical frames, thus can support Standard Frame Format (11-bit ID) and Extended Frame Format (29-bit ID). The ESP32 contains 1 TWAI controller(s) that can be configured to communicate on a TWAI bus via an external transceiver. Warning The TWAI controller is not compatible with ISO11898-1 FD Format frames, and will interpret such frames as errors. This programming guide is split into the following sections: TWAI Protocol Summary The TWAI is a multi-master, multi-cast, asynchronous, serial communication protocol. TWAI also supports error detection and signalling, and inbuilt message prioritization. Multi-master: Any node on the bus can initiate the transfer of a message. Multi-cast: When a node transmits a message, all nodes on the bus will receive the message (i.e., broadcast) thus ensuring data consistency across all nodes. However, some nodes can selectively choose which messages to accept via the use of acceptance filtering (multi-cast). Asynchronous: The bus does not contain a clock signal. All nodes on the bus operate at the same bit rate and synchronize using the edges of the bits transmitted on the bus. Error Detection and Signaling: Every node constantly monitors the bus. When any node detects an error, it signals the detection by transmitting an error frame. Other nodes will receive the error frame and transmit their own error frames in response. This results in an error detection being propagated to all nodes on the bus. Message Priorities: Messages contain an ID field. If two or more nodes attempt to transmit simultaneously, the node transmitting the message with the lower ID value will win arbitration of the bus. All other nodes will become receivers ensuring that there is at most one transmitter at any time. TWAI Messages TWAI Messages are split into Data Frames and Remote Frames. Data Frames are used to deliver a data payload to other nodes, whereas a Remote Frame is used to request a Data Frame from other nodes (other nodes can optionally respond with a Data Frame). Data and Remote Frames have two frame formats known as Extended Frame and Standard Frame which contain a 29-bit ID and an 11-bit ID respectively. A TWAI message consists of the following fields: - 29-bit or 11-bit ID: Determines the priority of the message (lower value has higher priority). - Data Length Code (DLC) between 0 to 8: Indicates the size (in bytes) of the data payload for a Data Frame, or the amount of data to request for a Remote Frame. - Up to 8 bytes of data for a Data Frame (should match DLC). Error States and Counters The TWAI protocol implements a feature known as "fault confinement" where a persistently erroneous node will eventually eliminate itself from the bus. This is implemented by requiring every node to maintain two internal error counters known as the Transmit Error Counter (TEC) and the Receive Error Counter (REC). The two error counters are incremented and decremented according to a set of rules (where the counters increase on an error, and decrease on a successful message transmission/reception). The values of the counters are used to determine a node's error state, namely Error Active, Error Passive, and Bus-Off. Error Active: A node is Error Active when both TEC and REC are less than 128 and indicates that the node is operating normally. Error Active nodes are allowed to participate in bus communications, and will actively signal the detection of any errors by automatically transmitting an Active Error Flag over the bus. Error Passive: A node is Error Passive when either the TEC or REC becomes greater than or equal to 128. Error Passive nodes are still able to take part in bus communications, but will instead transmit a Passive Error Flag upon detection of an error. Bus-Off: A node becomes Bus-Off when the TEC becomes greater than or equal to 256. A Bus-Off node is unable influence the bus in any manner (essentially disconnected from the bus) thus eliminating itself from the bus. A node will remain in the Bus-Off state until it undergoes bus-off recovery. Signals Lines and Transceiver The TWAI controller does not contain a integrated transceiver. Therefore, to connect the TWAI controller to a TWAI bus, an external transceiver is required. The type of external transceiver used should depend on the application's physical layer specification (e.g., using SN65HVD23x transceivers for ISO 11898-2 compatibility). The TWAI controller's interface consists of 4 signal lines known as TX, RX, BUS-OFF, and CLKOUT. These four signal lines can be routed through the GPIO Matrix to the ESP32's GPIO pads. TX and RX: The TX and RX signal lines are required to interface with an external transceiver. Both signal lines represent/interpret a dominant bit as a low logic level (0 V), and a recessive bit as a high logic level (3.3 V). BUS-OFF: The BUS-OFF signal line is optional and is set to a low logic level (0 V) whenever the TWAI controller reaches a bus-off state. The BUS-OFF signal line is set to a high logic level (3.3 V) otherwise. CLKOUT: The CLKOUT signal line is optional and outputs a prescaled version of the controller's source clock. Note An external transceiver must internally loopback the TX to RX such that a change in logic level to the TX signal line can be observed on the RX line. Failing to do so will cause the TWAI controller to interpret differences in logic levels between the two signal lines as a loss in arbitration or a bit error. API Naming Conventions Note The TWAI driver provides two sets of API. One is handle-free and is widely used in IDF versions earlier than v5.2, but it can only support one TWAI hardware controller. The other set is with handles, and the function name is usually suffixed with "v2", which can support any number of TWAI controllers. These two sets of API can be used at the same time, but it is recommended to use the "v2" version in your new projects. Driver Configuration This section covers how to configure the TWAI driver. Operating Modes The TWAI driver supports the following modes of operations: Normal Mode: The normal operating mode allows the TWAI controller to take part in bus activities such as transmitting and receiving messages/error frames. Acknowledgement from another node is required when transmitting a message. No Ack Mode: The No Acknowledgement mode is similar to normal mode, however acknowledgements are not required for a message transmission to be considered successful. This mode is useful when self testing the TWAI controller (loopback of transmissions). Listen Only Mode: This mode prevents the TWAI controller from influencing the bus. Therefore, transmission of messages/acknowledgement/error frames will be disabled. However the TWAI controller is still able to receive messages but will not acknowledge the message. This mode is suited for bus monitor applications. Alerts The TWAI driver contains an alert feature that is used to notify the application layer of certain TWAI controller or TWAI bus events. Alerts are selectively enabled when the TWAI driver is installed, but can be reconfigured during runtime by calling twai_reconfigure_alerts(). The application can then wait for any enabled alerts to occur by calling twai_read_alerts(). The TWAI driver supports the following alerts: | Alert Flag | Description | | No more messages queued for transmission | | The previous transmission was successful | | A frame has been received and added to the RX queue | | Both error counters have dropped below error warning limit | | TWAI controller has become error active | | TWAI controller is undergoing bus recovery | | TWAI controller has successfully completed bus recovery | | The previous transmission lost arbitration | | One of the error counters have exceeded the error warning limit | | A (Bit, Stuff, CRC, Form, ACK) error has occurred on the bus | | The previous transmission has failed | | The RX queue is full causing a received frame to be lost | | TWAI controller has become error passive | | Bus-off condition occurred. TWAI controller can no longer influence bus Note The TWAI controller's error warning limit is used to preemptively warn the application of bus errors before the error passive state is reached. By default, the TWAI driver sets the error warning limit to 96. The TWAI_ALERT_ABOVE_ERR_WARN is raised when the TEC or REC becomes larger then or equal to the error warning limit. The TWAI_ALERT_BELOW_ERR_WARN is raised when both TEC and REC return back to values below 96. Note When enabling alerts, the TWAI_ALERT_AND_LOG flag can be used to cause the TWAI driver to log any raised alerts to UART. However, alert logging is disabled and TWAI_ALERT_AND_LOG if the CONFIG_TWAI_ISR_IN_IRAM option is enabled (see Placing ISR into IRAM). Note The TWAI_ALERT_ALL and TWAI_ALERT_NONE macros can also be used to enable/disable all alerts during configuration/reconfiguration. Bit Timing The operating bit rate of the TWAI driver is configured using the twai_timing_config_t structure. The period of each bit is made up of multiple time quanta, and the period of a time quantum is determined by a pre-scaled version of the TWAI controller's source clock. A single bit contains the following segments in the following order: - The Synchronization Segment consists of a single time quantum - Timing Segment 1 consists of 1 to 16 time quanta before sample point - Timing Segment 2 consists of 1 to 8 time quanta after sample point The Baudrate Prescaler is used to determine the period of each time quantum by dividing the TWAI controller's source clock. On the ESP32, the brp can be any even number from 2 to 128. Alternatively, you can decide the resolution of each quantum, by setting twai_timing_config_t::quanta_resolution_hz to a non-zero value. In this way, the driver can calculate the underlying brp value for you. It is useful when you set different clock sources but want the bitrate to keep the same. Supported clock source for a TWAI controller is listed in the twai_clock_source_t and can be specified in twai_timing_config_t::clk_src. If the ESP32 is a revision 2 or later chip, the brp will also support any multiple of 4 from 132 to 256, and can be enabled by setting the CONFIG_ESP32_REV_MIN to revision 2 or higher. The sample point of a bit is located on the intersection of Timing Segment 1 and 2. Enabling Triple Sampling causes 3 time quanta to be sampled per bit instead of 1 (extra samples are located at the tail end of Timing Segment 1). The Synchronization Jump Width is used to determine the maximum number of time quanta a single bit time can be lengthened/shortened for synchronization purposes. sjw can range from 1 to 4. Note Multiple combinations of brp, tseg_1, tseg_2, and sjw can achieve the same bit rate. Users should tune these values to the physical characteristics of their bus by taking into account factors such as propagation delay, node information processing time, and phase errors. Bit timing macro initializers are also available for commonly used bit rates. The following macro initializers are provided by the TWAI driver. TWAI_TIMING_CONFIG_1MBITS TWAI_TIMING_CONFIG_800KBITS TWAI_TIMING_CONFIG_500KBITS TWAI_TIMING_CONFIG_250KBITS TWAI_TIMING_CONFIG_125KBITS TWAI_TIMING_CONFIG_100KBITS TWAI_TIMING_CONFIG_50KBITS TWAI_TIMING_CONFIG_25KBITS Revision 2 or later of the ESP32 also supports the following bit rates: TWAI_TIMING_CONFIG_20KBITS TWAI_TIMING_CONFIG_16KBITS TWAI_TIMING_CONFIG_12_5KBITS Acceptance Filter The TWAI controller contains a hardware acceptance filter which can be used to filter messages of a particular ID. A node that filters out a message does not receive the message, but will still acknowledge it. Acceptance filters can make a node more efficient by filtering out messages sent over the bus that are irrelevant to the node. The acceptance filter is configured using two 32-bit values within twai_filter_config_t known as the acceptance code and the acceptance mask. The acceptance code specifies the bit sequence which a message's ID, RTR, and data bytes must match in order for the message to be received by the TWAI controller. The acceptance mask is a bit sequence specifying which bits of the acceptance code can be ignored. This allows for a messages of different IDs to be accepted by a single acceptance code. The acceptance filter can be used under Single or Dual Filter Mode. Single Filter Mode uses the acceptance code and mask to define a single filter. This allows for the first two data bytes of a standard frame to be filtered, or the entirety of an extended frame's 29-bit ID. The following diagram illustrates how the 32-bit acceptance code and mask are interpreted under Single Filter Mode (Note: The yellow and blue fields represent standard and extended frame formats respectively). Dual Filter Mode uses the acceptance code and mask to define two separate filters allowing for increased flexibility of ID's to accept, but does not allow for all 29-bits of an extended ID to be filtered. The following diagram illustrates how the 32-bit acceptance code and mask are interpreted under Dual Filter Mode (Note: The yellow and blue fields represent standard and extended frame formats respectively). Disabling TX Queue The TX queue can be disabled during configuration by setting the tx_queue_len member of twai_general_config_t to 0. This allows applications that do not require message transmission to save a small amount of memory when using the TWAI driver. Placing ISR into IRAM The TWAI driver's ISR (Interrupt Service Routine) can be placed into IRAM so that the ISR can still run whilst the cache is disabled. Placing the ISR into IRAM may be necessary to maintain the TWAI driver's functionality during lengthy cache disabling operations (such as SPI Flash writes, OTA updates etc). Whilst the cache is disabled, the ISR continues to: Read received messages from the RX buffer and place them into the driver's RX queue. Load messages pending transmission from the driver's TX queue and write them into the TX buffer. To place the TWAI driver's ISR, users must do the following: Enable the CONFIG_TWAI_ISR_IN_IRAM option using idf.py menuconfig. When calling twai_driver_install(), the intr_flagsmember of twai_general_config_tshould set the ESP_INTR_FLAG_IRAMset. Note When the CONFIG_TWAI_ISR_IN_IRAM option is enabled, the TWAI driver will no longer log any alerts (i.e., the TWAI_ALERT_AND_LOG flag will not have any effect). ESP32 Errata Workarounds The ESP32's TWAI controller contains multiple hardware errata (more details about the errata can be found in the ESP32's ECO document). Some of these errata are critical, and under specific circumstances, can place the TWAI controller into an unrecoverable state (i.e., the controller gets stuck until it is reset by the CPU). The TWAI driver contains software workarounds for these critical errata. With these workarounds, the ESP32 TWAI driver can operate normally, albeit with degraded performance. The degraded performance will affect users in the following ways depending on what particular errata conditions are encountered: The TWAI driver can occasionally drop some received messages. The TWAI driver can be unresponsive for a short period of time (i.e., will not transmit or ACK for 11 bit times or longer). If CONFIG_TWAI_ISR_IN_IRAM is enabled, the workarounds will increase IRAM usage by approximately 1 KB. The software workarounds are enabled by default and it is recommended that users keep this workarounds enabled. Driver Operation The TWAI driver is designed with distinct states and strict rules regarding the functions or conditions that trigger a state transition. The following diagram illustrates the various states and their transitions. | Label | Transition | Action/Condition | A | Uninstalled > Stopped | B | Stopped > Uninstalled | C | Stopped > Running | D | Running > Stopped | E | Running > Bus-Off | Transmit Error Counter >= 256 | F | Bus-Off > Uninstalled | G | Bus-Off > Recovering | H | Recovering > Stopped | 128 occurrences of 11 consecutive recessive bits. Driver States Uninstalled: In the uninstalled state, no memory is allocated for the driver and the TWAI controller is powered OFF. Stopped: In this state, the TWAI controller is powered ON and the TWAI driver has been installed. However the TWAI controller is unable to take part in any bus activities such as transmitting, receiving, or acknowledging messages. Running: In the running state, the TWAI controller is able to take part in bus activities. Therefore messages can be transmitted/received/acknowledged. Furthermore, the TWAI controller is able to transmit error frames upon detection of errors on the bus. Bus-Off: The bus-off state is automatically entered when the TWAI controller's Transmit Error Counter becomes greater than or equal to 256. The bus-off state indicates the occurrence of severe errors on the bus or in the TWAI controller. Whilst in the bus-off state, the TWAI controller is unable to take part in any bus activities. To exit the bus-off state, the TWAI controller must undergo the bus recovery process. Recovering: The recovering state is entered when the TWAI controller undergoes bus recovery. The TWAI controller/TWAI driver remains in the recovering state until the 128 occurrences of 11 consecutive recessive bits is observed on the bus. Message Fields and Flags The TWAI driver distinguishes different types of messages by using the various bit field members of the twai_message_t structure. These bit field members determine whether a message is in standard or extended format, a remote frame, and the type of transmission to use when transmitting such a message. These bit field members can also be toggled using the flags member of twai_message_t and the following message flags: | Message Flag | Description | | Message is in Extended Frame Format (29bit ID) | | Message is a Remote Frame (Remote Transmission Request) | | Transmit message using Single Shot Transmission (Message will not be retransmitted upon error or loss of arbitration). Unused for received message. | | Transmit message using Self Reception Request (Transmitted message will also received by the same node). Unused for received message. | | Message's Data length code is larger than 8. This will break compliance with TWAI | | Clears all bit fields. Equivalent to a Standard Frame Format (11bit ID) Data Frame. Examples Configuration & Installation The following code snippet demonstrates how to configure, install, and start the TWAI driver via the use of the various configuration structures, macro initializers, the twai_driver_install() function, and the twai_start() function. #include "driver/gpio.h" #include "driver/twai.h" void app_main() { //Initialize configuration structures using macro initializers twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(GPIO_NUM_21, GPIO_NUM_22, TWAI_MODE_NORMAL); twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS(); twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL(); //Install TWAI driver if (twai_driver_install(&g_config, &t_config, &f_config) == ESP_OK) { printf("Driver installed\n"); } else { printf("Failed to install driver\n"); return; } //Start TWAI driver if (twai_start() == ESP_OK) { printf("Driver started\n"); } else { printf("Failed to start driver\n"); return; } ... } The usage of macro initializers is not mandatory and each of the configuration structures can be manually. Install Multiple TWAI Instances The following code snippet demonstrates how to install multiple TWAI instances via the use of the twai_driver_install_v2() function. #include "driver/gpio.h" #include "driver/twai.h" void app_main() { twai_handle_t twai_bus_0; twai_handle_t twai_bus_1; //Initialize configuration structures using macro initializers twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(GPIO_NUM_0, GPIO_NUM_1, TWAI_MODE_NORMAL); twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS(); twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL(); //Install driver for TWAI bus 0 g_config.controller_id = 0; if (twai_driver_install_v2(&g_config, &t_config, &f_config, &twai_bus_0) == ESP_OK) { printf("Driver installed\n"); } else { printf("Failed to install driver\n"); return; } //Start TWAI driver if (twai_start_v2(twai_bus_0) == ESP_OK) { printf("Driver started\n"); } else { printf("Failed to start driver\n"); return; } //Install driver for TWAI bus 1 g_config.controller_id = 1; g_config.tx_io = GPIO_NUM_2; g_config.rx_io = GPIO_NUM_3; if (twai_driver_install_v2(&g_config, &t_config, &f_config, &twai_bus_1) == ESP_OK) { printf("Driver installed\n"); } else { printf("Failed to install driver\n"); return; } //Start TWAI driver if (twai_start_v2(twai_bus_1) == ESP_OK) { printf("Driver started\n"); } else { printf("Failed to start driver\n"); return; } //Other Driver operations must use version 2 API as well ... } Message Transmission The following code snippet demonstrates how to transmit a message via the usage of the twai_message_t type and twai_transmit() function. #include "driver/twai.h" ... //Configure message to transmit twai_message_t message; message.identifier = 0xAAAA; message.extd = 1; message.data_length_code = 4; for (int i = 0; i < 4; i++) { message.data[i] = 0; } //Queue message for transmission if (twai_transmit(&message, pdMS_TO_TICKS(1000)) == ESP_OK) { printf("Message queued for transmission\n"); } else { printf("Failed to queue message for transmission\n"); } Message Reception The following code snippet demonstrates how to receive a message via the usage of the twai_message_t type and twai_receive() function. #include "driver/twai.h" ... //Wait for message to be received twai_message_t message; if (twai_receive(&message, pdMS_TO_TICKS(10000)) == ESP_OK) { printf("Message received\n"); } else { printf("Failed to receive message\n"); return; } //Process received message if (message.extd) { printf("Message is in Extended Format\n"); } else { printf("Message is in Standard Format\n"); } printf("ID is %d\n", message.identifier); if (!(message.rtr)) { for (int i = 0; i < message.data_length_code; i++) { printf("Data byte %d = %d\n", i, message.data[i]); } } Reconfiguring and Reading Alerts The following code snippet demonstrates how to reconfigure and read TWAI driver alerts via the use of the twai_reconfigure_alerts() and twai_read_alerts() functions. #include "driver/twai.h" ... //Reconfigure alerts to detect Error Passive and Bus-Off error states uint32_t alerts_to_enable = TWAI_ALERT_ERR_PASS | TWAI_ALERT_BUS_OFF; if (twai_reconfigure_alerts(alerts_to_enable, NULL) == ESP_OK) { printf("Alerts reconfigured\n"); } else { printf("Failed to reconfigure alerts"); } //Block indefinitely until an alert occurs uint32_t alerts_triggered; twai_read_alerts(&alerts_triggered, portMAX_DELAY); Stop and Uninstall The following code demonstrates how to stop and uninstall the TWAI driver via the use of the twai_stop() and twai_driver_uninstall() functions. #include "driver/twai.h" ... //Stop the TWAI driver if (twai_stop() == ESP_OK) { printf("Driver stopped\n"); } else { printf("Failed to stop driver\n"); return; } //Uninstall the TWAI driver if (twai_driver_uninstall() == ESP_OK) { printf("Driver uninstalled\n"); } else { printf("Failed to uninstall driver\n"); return; } Multiple ID Filter Configuration The acceptance mask in twai_filter_config_t can be configured such that two or more IDs are accepted for a single filter. For a particular filter to accept multiple IDs, the conflicting bit positions amongst the IDs must be set in the acceptance mask. The acceptance code can be set to any one of the IDs. The following example shows how the calculate the acceptance mask given multiple IDs: ID1 = 11'b101 1010 0000 ID2 = 11'b101 1010 0001 ID3 = 11'b101 1010 0100 ID4 = 11'b101 1010 1000 //Acceptance Mask MASK = 11'b000 0000 1101 Application Examples Network Example: The TWAI Network example demonstrates communication between two ESP32s using the TWAI driver API. One TWAI node acts as a network master that initiates and ceases the transfer of a data from another node acting as a network slave. The example can be found via peripherals/twai/twai_network. Alert and Recovery Example: This example demonstrates how to use the TWAI driver's alert and bus-off recovery API. The example purposely introduces errors on the bus to put the TWAI controller into the Bus-Off state. An alert is used to detect the Bus-Off state and trigger the bus recovery process. The example can be found via peripherals/twai/twai_alert_and_recovery. Self Test Example: This example uses the No Acknowledge Mode and Self Reception Request to cause the TWAI controller to send and simultaneously receive a series of messages. This example can be used to verify if the connections between the TWAI controller and the external transceiver are working correctly. The example can be found via peripherals/twai/twai_self_test. API Reference Header File This header file can be included with: #include "hal/twai_types.h" Structures - struct twai_message_t Structure to store a TWAI message. Note The flags member is deprecated Public Members - uint32_t extd Extended Frame Format (29bit ID) - uint32_t rtr Message is a Remote Frame - uint32_t ss Transmit as a Single Shot Transmission. Unused for received. - uint32_t self Transmit as a Self Reception Request. Unused for received. - uint32_t dlc_non_comp Message's Data length code is larger than 8. This will break compliance with ISO 11898-1 - uint32_t reserved Reserved bits - uint32_t flags Deprecated: Alternate way to set bits using message flags - uint32_t identifier 11 or 29 bit identifier - uint8_t data_length_code Data length code - uint8_t data[TWAI_FRAME_MAX_DLC] Data bytes (not relevant in RTR frame) - uint32_t extd - struct twai_timing_config_t Structure for bit timing configuration of the TWAI driver. Note Macro initializers are available for this structure Public Members - twai_clock_source_t clk_src Clock source, set to 0 or TWAI_CLK_SRC_DEFAULT if you want a default clock source - uint32_t quanta_resolution_hz The resolution of one timing quanta, in Hz. Note: the value of brpwill reflected by this field if it's non-zero, otherwise, brpneeds to be set manually - uint32_t brp Baudrate prescale (i.e., clock divider). Any even number from 2 to 128 for ESP32, 2 to 32768 for non-ESP32 chip. Note: For ESP32 ECO 2 or later, multiples of 4 from 132 to 256 are also supported - uint8_t tseg_1 Timing segment 1 (Number of time quanta, between 1 to 16) - uint8_t tseg_2 Timing segment 2 (Number of time quanta, 1 to 8) - uint8_t sjw Synchronization Jump Width (Max time quanta jump for synchronize from 1 to 4) - bool triple_sampling Enables triple sampling when the TWAI controller samples a bit - twai_clock_source_t clk_src - struct twai_filter_config_t Structure for acceptance filter configuration of the TWAI driver (see documentation) Note Macro initializers are available for this structure Macros - TWAI_EXTD_ID_MASK TWAI Constants. Bit mask for 29 bit Extended Frame Format ID - TWAI_STD_ID_MASK Bit mask for 11 bit Standard Frame Format ID - TWAI_FRAME_MAX_DLC Max data bytes allowed in TWAI - TWAI_FRAME_EXTD_ID_LEN_BYTES EFF ID requires 4 bytes (29bit) - TWAI_FRAME_STD_ID_LEN_BYTES SFF ID requires 2 bytes (11bit) - TWAI_ERR_PASS_THRESH Error counter threshold for error passive Type Definitions - typedef soc_periph_twai_clk_src_t twai_clock_source_t RMT group clock source. Note User should select the clock source based on the power and resolution requirement Enumerations - enum twai_mode_t TWAI Controller operating modes. Values: - enumerator TWAI_MODE_NORMAL Normal operating mode where TWAI controller can send/receive/acknowledge messages - enumerator TWAI_MODE_NO_ACK Transmission does not require acknowledgment. Use this mode for self testing - enumerator TWAI_MODE_LISTEN_ONLY The TWAI controller will not influence the bus (No transmissions or acknowledgments) but can receive messages - enumerator TWAI_MODE_NORMAL Header File This header file can be included with: #include "driver/twai.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t twai_driver_install(const twai_general_config_t *g_config, const twai_timing_config_t *t_config, const twai_filter_config_t *f_config) Install TWAI driver. This function installs the TWAI driver using three configuration structures. The required memory is allocated and the TWAI driver is placed in the stopped state after running this function. Note Macro initializers are available for the configuration structures (see documentation) Note To reinstall the TWAI driver, call twai_driver_uninstall() first - Parameters g_config -- [in] General configuration structure t_config -- [in] Timing configuration structure f_config -- [in] Filter configuration structure - - Returns ESP_OK: Successfully installed TWAI driver ESP_ERR_INVALID_ARG: Arguments are invalid, e.g. invalid clock source, invalid quanta resolution ESP_ERR_NO_MEM: Insufficient memory ESP_ERR_INVALID_STATE: Driver is already installed - - esp_err_t twai_driver_install_v2(const twai_general_config_t *g_config, const twai_timing_config_t *t_config, const twai_filter_config_t *f_config, twai_handle_t *ret_twai) Install TWAI driver and return a handle. Note This is an advanced version of twai_driver_installthat can return a driver handle, so that it allows you to install multiple TWAI drivers. Don't forget to set the proper controller_id in the twai_general_config_tPlease refer to the documentation of twai_driver_installfor more details. - Parameters g_config -- [in] General configuration structure t_config -- [in] Timing configuration structure f_config -- [in] Filter configuration structure ret_twai -- [out] Pointer to a new created TWAI handle - - Returns ESP_OK: Successfully installed TWAI driver ESP_ERR_INVALID_ARG: Arguments are invalid, e.g. invalid clock source, invalid quanta resolution, invalid controller ID ESP_ERR_NO_MEM: Insufficient memory ESP_ERR_INVALID_STATE: Driver is already installed - - esp_err_t twai_driver_uninstall(void) Uninstall the TWAI driver. This function uninstalls the TWAI driver, freeing the memory utilized by the driver. This function can only be called when the driver is in the stopped state or the bus-off state. Warning The application must ensure that no tasks are blocked on TX/RX queues or alerts when this function is called. - Returns ESP_OK: Successfully uninstalled TWAI driver ESP_ERR_INVALID_STATE: Driver is not in stopped/bus-off state, or is not installed - - esp_err_t twai_driver_uninstall_v2(twai_handle_t handle) Uninstall the TWAI driver with a given handle. Note This is an advanced version of twai_driver_uninstallthat can uninstall a TWAI driver with a given handle. Please refer to the documentation of twai_driver_uninstallfor more details. - Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 - Returns ESP_OK: Successfully uninstalled TWAI driver ESP_ERR_INVALID_STATE: Driver is not in stopped/bus-off state, or is not installed - - esp_err_t twai_start(void) Start the TWAI driver. This function starts the TWAI driver, putting the TWAI driver into the running state. This allows the TWAI driver to participate in TWAI bus activities such as transmitting/receiving messages. The TX and RX queue are reset in this function, clearing any messages that are unread or pending transmission. This function can only be called when the TWAI driver is in the stopped state. - Returns ESP_OK: TWAI driver is now running ESP_ERR_INVALID_STATE: Driver is not in stopped state, or is not installed - - esp_err_t twai_start_v2(twai_handle_t handle) Start the TWAI driver with a given handle. Note This is an advanced version of twai_startthat can start a TWAI driver with a given handle. Please refer to the documentation of twai_startfor more details. - Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 - Returns ESP_OK: TWAI driver is now running ESP_ERR_INVALID_STATE: Driver is not in stopped state, or is not installed - - esp_err_t twai_stop(void) Stop the TWAI driver. This function stops the TWAI driver, preventing any further message from being transmitted or received until twai_start() is called. Any messages in the TX queue are cleared. Any messages in the RX queue should be read by the application after this function is called. This function can only be called when the TWAI driver is in the running state. Warning A message currently being transmitted/received on the TWAI bus will be ceased immediately. This may lead to other TWAI nodes interpreting the unfinished message as an error. - Returns ESP_OK: TWAI driver is now Stopped ESP_ERR_INVALID_STATE: Driver is not in running state, or is not installed - - esp_err_t twai_stop_v2(twai_handle_t handle) Stop the TWAI driver with a given handle. Note This is an advanced version of twai_stopthat can stop a TWAI driver with a given handle. Please refer to the documentation of twai_stopfor more details. - Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 - Returns ESP_OK: TWAI driver is now Stopped ESP_ERR_INVALID_STATE: Driver is not in running state, or is not installed - - esp_err_t twai_transmit(const twai_message_t *message, TickType_t ticks_to_wait) Transmit a TWAI message. This function queues a TWAI message for transmission. Transmission will start immediately if no other messages are queued for transmission. If the TX queue is full, this function will block until more space becomes available or until it times out. If the TX queue is disabled (TX queue length = 0 in configuration), this function will return immediately if another message is undergoing transmission. This function can only be called when the TWAI driver is in the running state and cannot be called under Listen Only Mode. Note This function does not guarantee that the transmission is successful. The TX_SUCCESS/TX_FAILED alert can be enabled to alert the application upon the success/failure of a transmission. Note The TX_IDLE alert can be used to alert the application when no other messages are awaiting transmission. - Parameters message -- [in] Message to transmit ticks_to_wait -- [in] Number of FreeRTOS ticks to block on the TX queue - - Returns ESP_OK: Transmission successfully queued/initiated ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_TIMEOUT: Timed out waiting for space on TX queue ESP_FAIL: TX queue is disabled and another message is currently transmitting ESP_ERR_INVALID_STATE: TWAI driver is not in running state, or is not installed ESP_ERR_NOT_SUPPORTED: Listen Only Mode does not support transmissions - - esp_err_t twai_transmit_v2(twai_handle_t handle, const twai_message_t *message, TickType_t ticks_to_wait) Transmit a TWAI message via a given handle. Note This is an advanced version of twai_transmitthat can transmit a TWAI message with a given handle. Please refer to the documentation of twai_transmitfor more details. - Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 message -- [in] Message to transmit ticks_to_wait -- [in] Number of FreeRTOS ticks to block on the TX queue - - Returns ESP_OK: Transmission successfully queued/initiated ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_TIMEOUT: Timed out waiting for space on TX queue ESP_FAIL: TX queue is disabled and another message is currently transmitting ESP_ERR_INVALID_STATE: TWAI driver is not in running state, or is not installed ESP_ERR_NOT_SUPPORTED: Listen Only Mode does not support transmissions - - esp_err_t twai_receive(twai_message_t *message, TickType_t ticks_to_wait) Receive a TWAI message. This function receives a message from the RX queue. The flags field of the message structure will indicate the type of message received. This function will block if there are no messages in the RX queue Warning The flags field of the received message should be checked to determine if the received message contains any data bytes. - Parameters message -- [out] Received message ticks_to_wait -- [in] Number of FreeRTOS ticks to block on RX queue - - Returns ESP_OK: Message successfully received from RX queue ESP_ERR_TIMEOUT: Timed out waiting for message ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed - - esp_err_t twai_receive_v2(twai_handle_t handle, twai_message_t *message, TickType_t ticks_to_wait) Receive a TWAI message via a given handle. Note This is an advanced version of twai_receivethat can receive a TWAI message with a given handle. Please refer to the documentation of twai_receivefor more details. - Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 message -- [out] Received message ticks_to_wait -- [in] Number of FreeRTOS ticks to block on RX queue - - Returns ESP_OK: Message successfully received from RX queue ESP_ERR_TIMEOUT: Timed out waiting for message ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed - - esp_err_t twai_read_alerts(uint32_t *alerts, TickType_t ticks_to_wait) Read TWAI driver alerts. This function will read the alerts raised by the TWAI driver. If no alert has been issued when this function is called, this function will block until an alert occurs or until it timeouts. Note Multiple alerts can be raised simultaneously. The application should check for all alerts that have been enabled. - Parameters alerts -- [out] Bit field of raised alerts (see documentation for alert flags) ticks_to_wait -- [in] Number of FreeRTOS ticks to block for alert - - Returns ESP_OK: Alerts read ESP_ERR_TIMEOUT: Timed out waiting for alerts ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed - - esp_err_t twai_read_alerts_v2(twai_handle_t handle, uint32_t *alerts, TickType_t ticks_to_wait) Read TWAI driver alerts with a given handle. Note This is an advanced version of twai_read_alertsthat can read TWAI driver alerts with a given handle. Please refer to the documentation of twai_read_alertsfor more details. - Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 alerts -- [out] Bit field of raised alerts (see documentation for alert flags) ticks_to_wait -- [in] Number of FreeRTOS ticks to block for alert - - Returns ESP_OK: Alerts read ESP_ERR_TIMEOUT: Timed out waiting for alerts ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed - - esp_err_t twai_reconfigure_alerts(uint32_t alerts_enabled, uint32_t *current_alerts) Reconfigure which alerts are enabled. This function reconfigures which alerts are enabled. If there are alerts which have not been read whilst reconfiguring, this function can read those alerts. - Parameters alerts_enabled -- [in] Bit field of alerts to enable (see documentation for alert flags) current_alerts -- [out] Bit field of currently raised alerts. Set to NULL if unused - - Returns ESP_OK: Alerts reconfigured ESP_ERR_INVALID_STATE: TWAI driver is not installed - - esp_err_t twai_reconfigure_alerts_v2(twai_handle_t handle, uint32_t alerts_enabled, uint32_t *current_alerts) Reconfigure which alerts are enabled, with a given handle. Note This is an advanced version of twai_reconfigure_alertsthat can reconfigure which alerts are enabled with a given handle. Please refer to the documentation of twai_reconfigure_alertsfor more details. - Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 alerts_enabled -- [in] Bit field of alerts to enable (see documentation for alert flags) current_alerts -- [out] Bit field of currently raised alerts. Set to NULL if unused - - Returns ESP_OK: Alerts reconfigured ESP_ERR_INVALID_STATE: TWAI driver is not installed - - esp_err_t twai_initiate_recovery(void) Start the bus recovery process. This function initiates the bus recovery process when the TWAI driver is in the bus-off state. Once initiated, the TWAI driver will enter the recovering state and wait for 128 occurrences of the bus-free signal on the TWAI bus before returning to the stopped state. This function will reset the TX queue, clearing any messages pending transmission. Note The BUS_RECOVERED alert can be enabled to alert the application when the bus recovery process completes. - Returns ESP_OK: Bus recovery started ESP_ERR_INVALID_STATE: TWAI driver is not in the bus-off state, or is not installed - - esp_err_t twai_initiate_recovery_v2(twai_handle_t handle) Start the bus recovery process with a given handle. Note This is an advanced version of twai_initiate_recoverythat can start the bus recovery process with a given handle. Please refer to the documentation of twai_initiate_recoveryfor more details. - Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 - Returns ESP_OK: Bus recovery started ESP_ERR_INVALID_STATE: TWAI driver is not in the bus-off state, or is not installed - - esp_err_t twai_get_status_info(twai_status_info_t *status_info) Get current status information of the TWAI driver. - Parameters status_info -- [out] Status information - Returns ESP_OK: Status information retrieved ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed - - esp_err_t twai_get_status_info_v2(twai_handle_t handle, twai_status_info_t *status_info) Get current status information of a given TWAI driver handle. Note This is an advanced version of twai_get_status_infothat can get current status information of a given TWAI driver handle. Please refer to the documentation of twai_get_status_infofor more details. - Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 status_info -- [out] Status information - - Returns ESP_OK: Status information retrieved ESP_ERR_INVALID_ARG: Arguments are invalid ESP_ERR_INVALID_STATE: TWAI driver is not installed - - esp_err_t twai_clear_transmit_queue(void) Clear the transmit queue. This function will clear the transmit queue of all messages. Note The transmit queue is automatically cleared when twai_stop() or twai_initiate_recovery() is called. - Returns ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed or TX queue is disabled - - esp_err_t twai_clear_transmit_queue_v2(twai_handle_t handle) Clear the transmit queue of a given TWAI driver handle. Note This is an advanced version of twai_clear_transmit_queuethat can clear the transmit queue of a given TWAI driver handle. Please refer to the documentation of twai_clear_transmit_queuefor more details. - Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 - Returns ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed or TX queue is disabled - - esp_err_t twai_clear_receive_queue(void) Clear the receive queue. This function will clear the receive queue of all messages. Note The receive queue is automatically cleared when twai_start() is called. - Returns ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed - - esp_err_t twai_clear_receive_queue_v2(twai_handle_t handle) Clear the receive queue of a given TWAI driver handle. Note This is an advanced version of twai_clear_receive_queuethat can clear the receive queue of a given TWAI driver handle. Please refer to the documentation of twai_clear_receive_queuefor more details. - Parameters handle -- [in] TWAI driver handle returned by twai_driver_install_v2 - Returns ESP_OK: Transmit queue cleared ESP_ERR_INVALID_STATE: TWAI driver is not installed - Structures - struct twai_general_config_t Structure for general configuration of the TWAI driver. Note Macro initializers are available for this structure Public Members - int controller_id TWAI controller ID, index from 0. If you want to install TWAI driver with a non-zero controller_id, please use twai_driver_install_v2 - twai_mode_t mode Mode of TWAI controller - gpio_num_t tx_io Transmit GPIO number - gpio_num_t rx_io Receive GPIO number - gpio_num_t clkout_io CLKOUT GPIO number (optional, set to -1 if unused) - gpio_num_t bus_off_io Bus off indicator GPIO number (optional, set to -1 if unused) - uint32_t tx_queue_len Number of messages TX queue can hold (set to 0 to disable TX Queue) - uint32_t rx_queue_len Number of messages RX queue can hold - uint32_t alerts_enabled Bit field of alerts to enable (see documentation) - uint32_t clkout_divider CLKOUT divider. Can be 1 or any even number from 2 to 14 (optional, set to 0 if unused) - int intr_flags Interrupt flags to set the priority of the driver's ISR. Note that to use the ESP_INTR_FLAG_IRAM, the CONFIG_TWAI_ISR_IN_IRAM option should be enabled first. - int controller_id - struct twai_status_info_t Structure to store status information of TWAI driver. Public Members - twai_state_t state Current state of TWAI controller (Stopped/Running/Bus-Off/Recovery) - uint32_t msgs_to_tx Number of messages queued for transmission or awaiting transmission completion - uint32_t msgs_to_rx Number of messages in RX queue waiting to be read - uint32_t tx_error_counter Current value of Transmit Error Counter - uint32_t rx_error_counter Current value of Receive Error Counter - uint32_t tx_failed_count Number of messages that failed transmissions - uint32_t rx_missed_count Number of messages that were lost due to a full RX queue (or errata workaround if enabled) - uint32_t rx_overrun_count Number of messages that were lost due to a RX FIFO overrun - uint32_t arb_lost_count Number of instances arbitration was lost - uint32_t bus_error_count Number of instances a bus error has occurred - twai_state_t state Macros - TWAI_IO_UNUSED Marks GPIO as unused in TWAI configuration Type Definitions - typedef struct twai_obj_t *twai_handle_t TWAI controller handle. Enumerations - enum twai_state_t TWAI driver states. Values: - enumerator TWAI_STATE_STOPPED Stopped state. The TWAI controller will not participate in any TWAI bus activities - enumerator TWAI_STATE_RUNNING Running state. The TWAI controller can transmit and receive messages - enumerator TWAI_STATE_BUS_OFF Bus-off state. The TWAI controller cannot participate in bus activities until it has recovered - enumerator TWAI_STATE_RECOVERING Recovering state. The TWAI controller is undergoing bus recovery - enumerator TWAI_STATE_STOPPED
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/twai.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Universal Asynchronous Receiver/Transmitter (UART)
null
espressif.com
2016-01-01
4a5fda051038ac4b
null
null
Universal Asynchronous Receiver/Transmitter (UART) Introduction A Universal Asynchronous Receiver/Transmitter (UART) is a hardware feature that handles communication (i.e., timing requirements and data framing) using widely-adopted asynchronous serial communication interfaces, such as RS232, RS422, and RS485. A UART provides a widely adopted and cheap method to realize full-duplex or half-duplex data exchange among different devices. The ESP32 chip has 3 UART controllers (also referred to as port), each featuring an identical set of registers to simplify programming and for more flexibility. Each UART controller is independently configurable with parameters such as baud rate, data bit length, bit ordering, number of stop bits, parity bit, etc. All the regular UART controllers are compatible with UART-enabled devices from various manufacturers and can also support Infrared Data Association (IrDA) protocols. Functional Overview The overview describes how to establish communication between an ESP32 and other UART devices using the functions and data types of the UART driver. A typical programming workflow is broken down into the sections provided below: Set Communication Parameters - Setting baud rate, data bits, stop bits, etc. Set Communication Pins - Assigning pins for connection to a device Install Drivers - Allocating ESP32's resources for the UART driver Run UART Communication - Sending/receiving data Use Interrupts - Triggering interrupts on specific communication events Deleting a Driver - Freeing allocated resources if a UART communication is no longer required Steps 1 to 3 comprise the configuration stage. Step 4 is where the UART starts operating. Steps 5 and 6 are optional. The UART driver's functions identify each of the UART controllers using uart_port_t . This identification is needed for all the following function calls. Set Communication Parameters UART communication parameters can be configured all in a single step or individually in multiple steps. Single Step Call the function uart_param_config() and pass to it a uart_config_t structure. The uart_config_t structure should contain all the required parameters. See the example below. const uart_port_t uart_num = UART_NUM_2; uart_config_t uart_config = { .baud_rate = 115200, .data_bits = UART_DATA_8_BITS, .parity = UART_PARITY_DISABLE, .stop_bits = UART_STOP_BITS_1, .flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS, .rx_flow_ctrl_thresh = 122, }; // Configure UART parameters ESP_ERROR_CHECK(uart_param_config(uart_num, &uart_config)); For more information on how to configure the hardware flow control options, please refer to peripherals/uart/uart_echo. Multiple Steps Configure specific parameters individually by calling a dedicated function from the table given below. These functions are also useful if re-configuring a single parameter. Parameter to Configure Function Baud rate Number of transmitted bits Parity control Number of stop bits Hardware flow control mode Communication mode Each of the above functions has a _get_ counterpart to check the currently set value. For example, to check the current baud rate value, call uart_get_baudrate() . Set Communication Pins After setting communication parameters, configure the physical GPIO pins to which the other UART device will be connected. For this, call the function uart_set_pin() and specify the GPIO pin numbers to which the driver should route the TX, RX, RTS, and CTS signals. If you want to keep a currently allocated pin number for a specific signal, pass the macro UART_PIN_NO_CHANGE . The same macro UART_PIN_NO_CHANGE should be specified for pins that will not be used. // Set UART pins(TX: IO4, RX: IO5, RTS: IO18, CTS: IO19) ESP_ERROR_CHECK(uart_set_pin(UART_NUM_2, 4, 5, 18, 19)); Install Drivers Once the communication pins are set, install the driver by calling uart_driver_install() and specify the following parameters: Size of TX ring buffer Size of RX ring buffer Event queue handle and size Flags to allocate an interrupt The function allocates the required internal resources for the UART driver. // Setup UART buffered IO with event queue const int uart_buffer_size = (1024 * 2); QueueHandle_t uart_queue; // Install UART driver using an event queue here ESP_ERROR_CHECK(uart_driver_install(UART_NUM_2, uart_buffer_size, \ uart_buffer_size, 10, &uart_queue, 0)); Once this step is complete, you can connect the external UART device and check the communication. Run UART Communication Serial communication is controlled by each UART controller's finite state machine (FSM). The process of sending data involves the following steps: Write data into TX FIFO buffer FSM serializes the data FSM sends the data out The process of receiving data is similar, but the steps are reversed: FSM processes an incoming serial stream and parallelizes it FSM writes the data into RX FIFO buffer Read the data from RX FIFO buffer Therefore, an application only writes and reads data from a specific buffer using uart_write_bytes() and uart_read_bytes() respectively, and the FSM does the rest. Transmit Data After preparing the data for transmission, call the function uart_write_bytes() and pass the data buffer's address and data length to it. The function copies the data to the TX ring buffer (either immediately or after enough space is available), and then exit. When there is free space in the TX FIFO buffer, an interrupt service routine (ISR) moves the data from the TX ring buffer to the TX FIFO buffer in the background. The code below demonstrates the use of this function. // Write data to UART. char* test_str = "This is a test string.\n"; uart_write_bytes(uart_num, (const char*)test_str, strlen(test_str)); The function uart_write_bytes_with_break() is similar to uart_write_bytes() but adds a serial break signal at the end of the transmission. A 'serial break signal' means holding the TX line low for a period longer than one data frame. // Write data to UART, end with a break signal. uart_write_bytes_with_break(uart_num, "test break\n",strlen("test break\n"), 100); Another function for writing data to the TX FIFO buffer is uart_tx_chars() . Unlike uart_write_bytes() , this function does not block until space is available. Instead, it writes all data which can immediately fit into the hardware TX FIFO, and then return the number of bytes that were written. There is a 'companion' function uart_wait_tx_done() that monitors the status of the TX FIFO buffer and returns once it is empty. // Wait for packet to be sent const uart_port_t uart_num = UART_NUM_2; ESP_ERROR_CHECK(uart_wait_tx_done(uart_num, 100)); // wait timeout is 100 RTOS ticks (TickType_t) Receive Data Once the data is received by the UART and saved in the RX FIFO buffer, it needs to be retrieved using the function uart_read_bytes() . Before reading data, you can check the number of bytes available in the RX FIFO buffer by calling uart_get_buffered_data_len() . An example of using these functions is given below. // Read data from UART. const uart_port_t uart_num = UART_NUM_2; uint8_t data[128]; int length = 0; ESP_ERROR_CHECK(uart_get_buffered_data_len(uart_num, (size_t*)&length)); length = uart_read_bytes(uart_num, data, length, 100); If the data in the RX FIFO buffer is no longer needed, you can clear the buffer by calling uart_flush() . Software Flow Control If the hardware flow control is disabled, you can manually set the RTS and DTR signal levels by using the functions uart_set_rts() and uart_set_dtr() respectively. Communication Mode Selection The UART controller supports a number of communication modes. A mode can be selected using the function uart_set_mode() . Once a specific mode is selected, the UART driver handles the behavior of a connected UART device accordingly. As an example, it can control the RS485 driver chip using the RTS line to allow half-duplex RS485 communication. // Setup UART in rs485 half duplex mode ESP_ERROR_CHECK(uart_set_mode(uart_num, UART_MODE_RS485_HALF_DUPLEX)); Use Interrupts There are many interrupts that can be generated depending on specific UART states or detected errors. The full list of available interrupts is provided in ESP32 Technical Reference Manual > UART Controller (UART) > UART Interrupts and UHCI Interrupts [PDF]. You can enable or disable specific interrupts by calling uart_enable_intr_mask() or uart_disable_intr_mask() respectively. The uart_driver_install() function installs the driver's internal interrupt handler to manage the TX and RX ring buffers and provides high-level API functions like events (see below). The API provides a convenient way to handle specific interrupts discussed in this document by wrapping them into dedicated functions: Event detection: There are several events defined in uart_event_type_t that may be reported to a user application using the FreeRTOS queue functionality. You can enable this functionality when calling uart_driver_install() described in Install Drivers. An example of using Event detection can be found in peripherals/uart/uart_events. FIFO space threshold or transmission timeout reached: The TX and RX FIFO buffers can trigger an interrupt when they are filled with a specific number of characters, or on a timeout of sending or receiving data. To use these interrupts, do the following: Configure respective threshold values of the buffer length and timeout by entering them in the structure uart_intr_config_t and calling uart_intr_config() Enable the interrupts using the functions uart_enable_tx_intr() and uart_enable_rx_intr() Disable these interrupts using the corresponding functions uart_disable_tx_intr() or uart_disable_rx_intr() Configure respective threshold values of the buffer length and timeout by entering them in the structure uart_intr_config_t and calling uart_intr_config() Enable the interrupts using the functions uart_enable_tx_intr() and uart_enable_rx_intr() Disable these interrupts using the corresponding functions uart_disable_tx_intr() or uart_disable_rx_intr() Configure respective threshold values of the buffer length and timeout by entering them in the structure uart_intr_config_t and calling uart_intr_config() Pattern detection: An interrupt triggered on detecting a 'pattern' of the same character being received/sent repeatedly. This functionality is demonstrated in the example peripherals/uart/uart_events. It can be used, e.g., to detect a command string with a specific number of identical characters (the 'pattern') at the end. The following functions are available: Configure and enable this interrupt using uart_enable_pattern_det_baud_intr() Disable the interrupt using uart_disable_pattern_det_intr() Configure and enable this interrupt using uart_enable_pattern_det_baud_intr() Disable the interrupt using uart_disable_pattern_det_intr() Configure and enable this interrupt using uart_enable_pattern_det_baud_intr() Macros The API also defines several macros. For example, UART_HW_FIFO_LEN defines the length of hardware FIFO buffers; UART_BITRATE_MAX gives the maximum baud rate supported by the UART controllers, etc. Deleting a Driver If the communication established with uart_driver_install() is no longer required, the driver can be removed to free allocated resources by calling uart_driver_delete() . Overview of RS485 Specific Communication 0ptions Note The following section uses [UART_REGISTER_NAME].[UART_FIELD_BIT] to refer to UART register fields/bits. For more information on a specific option bit, see ESP32 Technical Reference Manual > UART Controller (UART) > Register Summary [PDF]. Use the register name to navigate to the register description and then find the field/bit. UART_RS485_CONF_REG.UART_RS485_EN : setting this bit enables RS485 communication mode support. UART_RS485_CONF_REG.UART_RS485TX_RX_EN : if this bit is set, the transmitter's output signal loops back to the receiver's input signal. UART_RS485_CONF_REG.UART_RS485RXBY_TX_EN : if this bit is set, the transmitter will still be sending data if the receiver is busy (remove collisions automatically by hardware). The ESP32's RS485 UART hardware can detect signal collisions during transmission of a datagram and generate the interrupt UART_RS485_CLASH_INT if this interrupt is enabled. The term collision means that a transmitted datagram is not equal to the one received on the other end. Data collisions are usually associated with the presence of other active devices on the bus or might occur due to bus errors. The collision detection feature allows handling collisions when their interrupts are activated and triggered. The interrupts UART_RS485_FRM_ERR_INT and UART_RS485_PARITY_ERR_INT can be used with the collision detection feature to control frame errors and parity bit errors accordingly in RS485 mode. This functionality is supported in the UART driver and can be used by selecting the UART_MODE_RS485_APP_CTRL mode (see the function uart_set_mode() ). The collision detection feature can work with circuit A and circuit C (see Section Interface Connection Options). In the case of using circuit A or B, the RTS pin connected to the DE pin of the bus driver should be controlled by the user application. Use the function uart_get_collision_flag() to check if the collision detection flag has been raised. The ESP32 UART controllers themselves do not support half-duplex communication as they cannot provide automatic control of the RTS pin connected to the RE/DE input of RS485 bus driver. However, half-duplex communication can be achieved via software control of the RTS pin by the UART driver. This can be enabled by selecting the UART_MODE_RS485_HALF_DUPLEX mode when calling uart_set_mode() . Once the host starts writing data to the TX FIFO buffer, the UART driver automatically asserts the RTS pin (logic 1); once the last bit of the data has been transmitted, the driver de-asserts the RTS pin (logic 0). To use this mode, the software would have to disable the hardware flow control function. This mode works with all the used circuits shown below. Interface Connection Options This section provides example schematics to demonstrate the basic aspects of ESP32's RS485 interface connection. Note The schematics below do not necessarily contain all required elements. The analog devices ADM483 & ADM2483 are examples of common RS485 transceivers and can be replaced with other similar transceivers. Circuit A: Collision Detection Circuit VCC ---------------+ | +-------x-------+ RXD <------| R | | B|----------<> B TXD ------>| D ADM483 | ESP | | RS485 bus side RTS ------>| DE | | A|----------<> A +----| /RE | | +-------x-------+ | | GND GND This circuit is preferable because it allows for collision detection and is quite simple at the same time. The receiver in the line driver is constantly enabled, which allows the UART to monitor the RS485 bus. Echo suppression is performed by the UART peripheral when the bit UART_RS485_CONF_REG.UART_RS485TX_RX_EN is enabled. Circuit B: Manual Switching Transmitter/Receiver Without Collision Detection VCC ---------------+ | +-------x-------+ RXD <------| R | | B|-----------<> B TXD ------>| D ADM483 | ESP | | RS485 bus side RTS --+--->| DE | | | A|-----------<> A +----| /RE | +-------x-------+ | GND This circuit does not allow for collision detection. It suppresses the null bytes that the hardware receives when the bit UART_RS485_CONF_REG.UART_RS485TX_RX_EN is set. The bit UART_RS485_CONF_REG.UART_RS485RXBY_TX_EN is not applicable in this case. Circuit C: Auto Switching Transmitter/Receiver VCC1 <-------------------+-----------+ +-------------------+----> VCC2 10K ____ | | | | +---|____|--+ +---x-----------x---+ 10K ____ | | | | +---|____|--+ RX <----------+-------------------| RXD | | 10K ____ | A|---+---------------<> A (+) +-------|____|------| PV ADM2483 | | ____ 120 | ____ | | +---|____|---+ RS485 bus side VCC1 <--+--|____|--+------->| DE | | 10K | | B|---+------------+--<> B (-) ---+ +-->| /RE | | ____ 10K | | | | +---|____|---+ ____ | /-C +---| TXD | 10K | TX >---|____|--+_B_|/ NPN | | | | |\ | +---x-----------x---+ | | \-E | | | | | | | | | GND1 GND1 GND1 GND2 GND2 This galvanically isolated circuit does not require RTS pin control by a software application or driver because it controls the transceiver direction automatically. However, it requires suppressing null bytes during transmission by setting UART_RS485_CONF_REG.UART_RS485RXBY_TX_EN to 1 and UART_RS485_CONF_REG.UART_RS485TX_RX_EN to 0. This setup can work in any RS485 UART mode or even in UART_MODE_UART . Application Examples The table below describes the code examples available in the directory peripherals/uart/. Code Example Description Configuring UART settings, installing the UART driver, and reading/writing over the UART1 interface. Reporting various communication events, using pattern detection interrupts. Transmitting and receiving data in two separate FreeRTOS tasks over the same UART. Using synchronous I/O multiplexing for UART file descriptors. Setting up UART driver to communicate over RS485 interface in half-duplex mode. This example is similar to peripherals/uart/uart_echo but allows communication through an RS485 interface chip connected to ESP32 pins. Obtaining GPS information by parsing NMEA0183 statements received from GPS via the UART peripheral. API Reference Header File This header file can be included with: #include "driver/uart.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions esp_err_t uart_driver_install(uart_port_t uart_num, int rx_buffer_size, int tx_buffer_size, int queue_size, QueueHandle_t *uart_queue, int intr_alloc_flags) Install UART driver and set the UART to the default configuration. UART ISR handler will be attached to the same CPU core that this function is running on. Note Rx_buffer_size should be greater than UART_HW_FIFO_LEN(uart_num). Tx_buffer_size should be either zero or greater than UART_HW_FIFO_LEN(uart_num). Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). rx_buffer_size -- UART RX ring buffer size. tx_buffer_size -- UART TX ring buffer size. If set to zero, driver will not use TX buffer, TX function will block task until all data have been sent out. queue_size -- UART event queue size/depth. uart_queue -- UART event queue handle (out param). On success, a new queue handle is written here to provide access to UART events. If set to NULL, driver will not use an event queue. intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. Do not set ESP_INTR_FLAG_IRAM here (the driver's ISR handler is not located in IRAM) uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). rx_buffer_size -- UART RX ring buffer size. tx_buffer_size -- UART TX ring buffer size. If set to zero, driver will not use TX buffer, TX function will block task until all data have been sent out. queue_size -- UART event queue size/depth. uart_queue -- UART event queue handle (out param). On success, a new queue handle is written here to provide access to UART events. If set to NULL, driver will not use an event queue. intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. Do not set ESP_INTR_FLAG_IRAM here (the driver's ISR handler is not located in IRAM) uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). rx_buffer_size -- UART RX ring buffer size. tx_buffer_size -- UART TX ring buffer size. If set to zero, driver will not use TX buffer, TX function will block task until all data have been sent out. queue_size -- UART event queue size/depth. uart_queue -- UART event queue handle (out param). On success, a new queue handle is written here to provide access to UART events. If set to NULL, driver will not use an event queue. intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. Do not set ESP_INTR_FLAG_IRAM here (the driver's ISR handler is not located in IRAM) Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_driver_delete(uart_port_t uart_num) Uninstall UART driver. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error bool uart_is_driver_installed(uart_port_t uart_num) Checks whether the driver is installed or not. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns true driver is installed false driver is not installed true driver is installed false driver is not installed true driver is installed Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns true driver is installed false driver is not installed esp_err_t uart_set_word_length(uart_port_t uart_num, uart_word_length_t data_bit) Set UART data bits. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). data_bit -- UART data bits uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). data_bit -- UART data bits uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). data_bit -- UART data bits Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_get_word_length(uart_port_t uart_num, uart_word_length_t *data_bit) Get the UART data bit configuration. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). data_bit -- Pointer to accept value of UART data bits. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). data_bit -- Pointer to accept value of UART data bits. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_FAIL Parameter error ESP_OK Success, result will be put in (*data_bit) ESP_FAIL Parameter error ESP_OK Success, result will be put in (*data_bit) ESP_FAIL Parameter error Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). data_bit -- Pointer to accept value of UART data bits. Returns ESP_FAIL Parameter error ESP_OK Success, result will be put in (*data_bit) esp_err_t uart_set_stop_bits(uart_port_t uart_num, uart_stop_bits_t stop_bits) Set UART stop bits. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). stop_bits -- UART stop bits uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). stop_bits -- UART stop bits uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Fail ESP_OK Success ESP_FAIL Fail ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). stop_bits -- UART stop bits Returns ESP_OK Success ESP_FAIL Fail esp_err_t uart_get_stop_bits(uart_port_t uart_num, uart_stop_bits_t *stop_bits) Get the UART stop bit configuration. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). stop_bits -- Pointer to accept value of UART stop bits. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). stop_bits -- Pointer to accept value of UART stop bits. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_FAIL Parameter error ESP_OK Success, result will be put in (*stop_bit) ESP_FAIL Parameter error ESP_OK Success, result will be put in (*stop_bit) ESP_FAIL Parameter error Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). stop_bits -- Pointer to accept value of UART stop bits. Returns ESP_FAIL Parameter error ESP_OK Success, result will be put in (*stop_bit) esp_err_t uart_set_parity(uart_port_t uart_num, uart_parity_t parity_mode) Set UART parity mode. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). parity_mode -- the enum of uart parity configuration uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). parity_mode -- the enum of uart parity configuration uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). parity_mode -- the enum of uart parity configuration Returns ESP_FAIL Parameter error ESP_OK Success esp_err_t uart_get_parity(uart_port_t uart_num, uart_parity_t *parity_mode) Get the UART parity mode configuration. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). parity_mode -- Pointer to accept value of UART parity mode. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). parity_mode -- Pointer to accept value of UART parity mode. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_FAIL Parameter error ESP_OK Success, result will be put in (*parity_mode) ESP_FAIL Parameter error ESP_OK Success, result will be put in (*parity_mode) ESP_FAIL Parameter error Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). parity_mode -- Pointer to accept value of UART parity mode. Returns ESP_FAIL Parameter error ESP_OK Success, result will be put in (*parity_mode) esp_err_t uart_get_sclk_freq(uart_sclk_t sclk, uint32_t *out_freq_hz) Get the frequency of a clock source for the HP UART port. Parameters sclk -- Clock source out_freq_hz -- [out] Output of frequency, in Hz sclk -- Clock source out_freq_hz -- [out] Output of frequency, in Hz sclk -- Clock source Returns ESP_ERR_INVALID_ARG: if the clock source is not supported otherwise ESP_OK ESP_ERR_INVALID_ARG: if the clock source is not supported otherwise ESP_OK ESP_ERR_INVALID_ARG: if the clock source is not supported Parameters sclk -- Clock source out_freq_hz -- [out] Output of frequency, in Hz Returns ESP_ERR_INVALID_ARG: if the clock source is not supported otherwise ESP_OK esp_err_t uart_set_baudrate(uart_port_t uart_num, uint32_t baudrate) Set UART baud rate. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). baudrate -- UART baud rate. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). baudrate -- UART baud rate. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). baudrate -- UART baud rate. Returns ESP_FAIL Parameter error ESP_OK Success esp_err_t uart_get_baudrate(uart_port_t uart_num, uint32_t *baudrate) Get the UART baud rate configuration. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). baudrate -- Pointer to accept value of UART baud rate uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). baudrate -- Pointer to accept value of UART baud rate uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_FAIL Parameter error ESP_OK Success, result will be put in (*baudrate) ESP_FAIL Parameter error ESP_OK Success, result will be put in (*baudrate) ESP_FAIL Parameter error Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). baudrate -- Pointer to accept value of UART baud rate Returns ESP_FAIL Parameter error ESP_OK Success, result will be put in (*baudrate) esp_err_t uart_set_line_inverse(uart_port_t uart_num, uint32_t inverse_mask) Set UART line inverse mode. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). inverse_mask -- Choose the wires that need to be inverted. Using the ORred mask of uart_signal_inv_t uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). inverse_mask -- Choose the wires that need to be inverted. Using the ORred mask of uart_signal_inv_t uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). inverse_mask -- Choose the wires that need to be inverted. Using the ORred mask of uart_signal_inv_t Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_set_hw_flow_ctrl(uart_port_t uart_num, uart_hw_flowcontrol_t flow_ctrl, uint8_t rx_thresh) Set hardware flow control. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). flow_ctrl -- Hardware flow control mode rx_thresh -- Threshold of Hardware RX flow control (0 ~ UART_HW_FIFO_LEN(uart_num)). Only when UART_HW_FLOWCTRL_RTS is set, will the rx_thresh value be set. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). flow_ctrl -- Hardware flow control mode rx_thresh -- Threshold of Hardware RX flow control (0 ~ UART_HW_FIFO_LEN(uart_num)). Only when UART_HW_FLOWCTRL_RTS is set, will the rx_thresh value be set. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). flow_ctrl -- Hardware flow control mode rx_thresh -- Threshold of Hardware RX flow control (0 ~ UART_HW_FIFO_LEN(uart_num)). Only when UART_HW_FLOWCTRL_RTS is set, will the rx_thresh value be set. Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_set_sw_flow_ctrl(uart_port_t uart_num, bool enable, uint8_t rx_thresh_xon, uint8_t rx_thresh_xoff) Set software flow control. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1) enable -- switch on or off rx_thresh_xon -- low water mark rx_thresh_xoff -- high water mark uart_num -- UART port number, the max port number is (UART_NUM_MAX -1) enable -- switch on or off rx_thresh_xon -- low water mark rx_thresh_xoff -- high water mark uart_num -- UART port number, the max port number is (UART_NUM_MAX -1) Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1) enable -- switch on or off rx_thresh_xon -- low water mark rx_thresh_xoff -- high water mark Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_get_hw_flow_ctrl(uart_port_t uart_num, uart_hw_flowcontrol_t *flow_ctrl) Get the UART hardware flow control configuration. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). flow_ctrl -- Option for different flow control mode. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). flow_ctrl -- Option for different flow control mode. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_FAIL Parameter error ESP_OK Success, result will be put in (*flow_ctrl) ESP_FAIL Parameter error ESP_OK Success, result will be put in (*flow_ctrl) ESP_FAIL Parameter error Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). flow_ctrl -- Option for different flow control mode. Returns ESP_FAIL Parameter error ESP_OK Success, result will be put in (*flow_ctrl) esp_err_t uart_clear_intr_status(uart_port_t uart_num, uint32_t clr_mask) Clear UART interrupt status. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). clr_mask -- Bit mask of the interrupt status to be cleared. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). clr_mask -- Bit mask of the interrupt status to be cleared. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). clr_mask -- Bit mask of the interrupt status to be cleared. Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_enable_intr_mask(uart_port_t uart_num, uint32_t enable_mask) Set UART interrupt enable. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). enable_mask -- Bit mask of the enable bits. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). enable_mask -- Bit mask of the enable bits. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). enable_mask -- Bit mask of the enable bits. Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_disable_intr_mask(uart_port_t uart_num, uint32_t disable_mask) Clear UART interrupt enable bits. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). disable_mask -- Bit mask of the disable bits. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). disable_mask -- Bit mask of the disable bits. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). disable_mask -- Bit mask of the disable bits. Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_enable_rx_intr(uart_port_t uart_num) Enable UART RX interrupt (RX_FULL & RX_TIMEOUT INTERRUPT) Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_disable_rx_intr(uart_port_t uart_num) Disable UART RX interrupt (RX_FULL & RX_TIMEOUT INTERRUPT) Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_disable_tx_intr(uart_port_t uart_num) Disable UART TX interrupt (TX_FULL & TX_TIMEOUT INTERRUPT) Parameters uart_num -- UART port number Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_enable_tx_intr(uart_port_t uart_num, int enable, int thresh) Enable UART TX interrupt (TX_FULL & TX_TIMEOUT INTERRUPT) Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). enable -- 1: enable; 0: disable thresh -- Threshold of TX interrupt, 0 ~ UART_HW_FIFO_LEN(uart_num) uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). enable -- 1: enable; 0: disable thresh -- Threshold of TX interrupt, 0 ~ UART_HW_FIFO_LEN(uart_num) uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). enable -- 1: enable; 0: disable thresh -- Threshold of TX interrupt, 0 ~ UART_HW_FIFO_LEN(uart_num) Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_set_pin(uart_port_t uart_num, int tx_io_num, int rx_io_num, int rts_io_num, int cts_io_num) Assign signals of a UART peripheral to GPIO pins. Note If the GPIO number configured for a UART signal matches one of the IOMUX signals for that GPIO, the signal will be connected directly via the IOMUX. Otherwise the GPIO and signal will be connected via the GPIO Matrix. For example, if on an ESP32 the call uart_set_pin(0, 1, 3, -1, -1) is performed, as GPIO1 is UART0's default TX pin and GPIO3 is UART0's default RX pin, both will be connected to respectively U0TXD and U0RXD through the IOMUX, totally bypassing the GPIO matrix. The check is performed on a per-pin basis. Thus, it is possible to have RX pin binded to a GPIO through the GPIO matrix, whereas TX is binded to its GPIO through the IOMUX. Note Internal signal can be output to multiple GPIO pads. Only one GPIO pad can connect with input signal. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). tx_io_num -- UART TX pin GPIO number. rx_io_num -- UART RX pin GPIO number. rts_io_num -- UART RTS pin GPIO number. cts_io_num -- UART CTS pin GPIO number. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). tx_io_num -- UART TX pin GPIO number. rx_io_num -- UART RX pin GPIO number. rts_io_num -- UART RTS pin GPIO number. cts_io_num -- UART CTS pin GPIO number. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). tx_io_num -- UART TX pin GPIO number. rx_io_num -- UART RX pin GPIO number. rts_io_num -- UART RTS pin GPIO number. cts_io_num -- UART CTS pin GPIO number. Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_set_rts(uart_port_t uart_num, int level) Manually set the UART RTS pin level. Note UART must be configured with hardware flow control disabled. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). level -- 1: RTS output low (active); 0: RTS output high (block) uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). level -- 1: RTS output low (active); 0: RTS output high (block) uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). level -- 1: RTS output low (active); 0: RTS output high (block) Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_set_dtr(uart_port_t uart_num, int level) Manually set the UART DTR pin level. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). level -- 1: DTR output low; 0: DTR output high uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). level -- 1: DTR output low; 0: DTR output high uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). level -- 1: DTR output low; 0: DTR output high Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_set_tx_idle_num(uart_port_t uart_num, uint16_t idle_num) Set UART idle interval after tx FIFO is empty. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). idle_num -- idle interval after tx FIFO is empty(unit: the time it takes to send one bit under current baudrate) uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). idle_num -- idle interval after tx FIFO is empty(unit: the time it takes to send one bit under current baudrate) uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). idle_num -- idle interval after tx FIFO is empty(unit: the time it takes to send one bit under current baudrate) Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_param_config(uart_port_t uart_num, const uart_config_t *uart_config) Set UART configuration parameters. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). uart_config -- UART parameter settings uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). uart_config -- UART parameter settings uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). uart_config -- UART parameter settings Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_intr_config(uart_port_t uart_num, const uart_intr_config_t *intr_conf) Configure UART interrupts. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). intr_conf -- UART interrupt settings uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). intr_conf -- UART interrupt settings uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). intr_conf -- UART interrupt settings Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_wait_tx_done(uart_port_t uart_num, TickType_t ticks_to_wait) Wait until UART TX FIFO is empty. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). ticks_to_wait -- Timeout, count in RTOS ticks uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). ticks_to_wait -- Timeout, count in RTOS ticks uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_ERR_TIMEOUT Timeout ESP_OK Success ESP_FAIL Parameter error ESP_ERR_TIMEOUT Timeout ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). ticks_to_wait -- Timeout, count in RTOS ticks Returns ESP_OK Success ESP_FAIL Parameter error ESP_ERR_TIMEOUT Timeout int uart_tx_chars(uart_port_t uart_num, const char *buffer, uint32_t len) Send data to the UART port from a given buffer and length. This function will not wait for enough space in TX FIFO. It will just fill the available TX FIFO and return when the FIFO is full. Note This function should only be used when UART TX buffer is not enabled. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). buffer -- data buffer address len -- data length to send uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). buffer -- data buffer address len -- data length to send uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns (-1) Parameter error OTHERS (>=0) The number of bytes pushed to the TX FIFO (-1) Parameter error OTHERS (>=0) The number of bytes pushed to the TX FIFO (-1) Parameter error Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). buffer -- data buffer address len -- data length to send Returns (-1) Parameter error OTHERS (>=0) The number of bytes pushed to the TX FIFO int uart_write_bytes(uart_port_t uart_num, const void *src, size_t size) Send data to the UART port from a given buffer and length,. If the UART driver's parameter 'tx_buffer_size' is set to zero: This function will not return until all the data have been sent out, or at least pushed into TX FIFO. Otherwise, if the 'tx_buffer_size' > 0, this function will return after copying all the data to tx ring buffer, UART ISR will then move data from the ring buffer to TX FIFO gradually. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). src -- data buffer address size -- data length to send uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). src -- data buffer address size -- data length to send uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns (-1) Parameter error OTHERS (>=0) The number of bytes pushed to the TX FIFO (-1) Parameter error OTHERS (>=0) The number of bytes pushed to the TX FIFO (-1) Parameter error Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). src -- data buffer address size -- data length to send Returns (-1) Parameter error OTHERS (>=0) The number of bytes pushed to the TX FIFO int uart_write_bytes_with_break(uart_port_t uart_num, const void *src, size_t size, int brk_len) Send data to the UART port from a given buffer and length,. If the UART driver's parameter 'tx_buffer_size' is set to zero: This function will not return until all the data and the break signal have been sent out. After all data is sent out, send a break signal. Otherwise, if the 'tx_buffer_size' > 0, this function will return after copying all the data to tx ring buffer, UART ISR will then move data from the ring buffer to TX FIFO gradually. After all data sent out, send a break signal. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). src -- data buffer address size -- data length to send brk_len -- break signal duration(unit: the time it takes to send one bit at current baudrate) uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). src -- data buffer address size -- data length to send brk_len -- break signal duration(unit: the time it takes to send one bit at current baudrate) uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns (-1) Parameter error OTHERS (>=0) The number of bytes pushed to the TX FIFO (-1) Parameter error OTHERS (>=0) The number of bytes pushed to the TX FIFO (-1) Parameter error Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). src -- data buffer address size -- data length to send brk_len -- break signal duration(unit: the time it takes to send one bit at current baudrate) Returns (-1) Parameter error OTHERS (>=0) The number of bytes pushed to the TX FIFO int uart_read_bytes(uart_port_t uart_num, void *buf, uint32_t length, TickType_t ticks_to_wait) UART read bytes from UART buffer. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). buf -- pointer to the buffer. length -- data length ticks_to_wait -- sTimeout, count in RTOS ticks uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). buf -- pointer to the buffer. length -- data length ticks_to_wait -- sTimeout, count in RTOS ticks uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns (-1) Error OTHERS (>=0) The number of bytes read from UART buffer (-1) Error OTHERS (>=0) The number of bytes read from UART buffer (-1) Error Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). buf -- pointer to the buffer. length -- data length ticks_to_wait -- sTimeout, count in RTOS ticks Returns (-1) Error OTHERS (>=0) The number of bytes read from UART buffer esp_err_t uart_flush(uart_port_t uart_num) Alias of uart_flush_input. UART ring buffer flush. This will discard all data in the UART RX buffer. Note Instead of waiting the data sent out, this function will clear UART rx buffer. In order to send all the data in tx FIFO, we can use uart_wait_tx_done function. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_flush_input(uart_port_t uart_num) Clear input buffer, discard all the data is in the ring-buffer. Note In order to send all the data in tx FIFO, we can use uart_wait_tx_done function. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_get_buffered_data_len(uart_port_t uart_num, size_t *size) UART get RX ring buffer cached data length. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). size -- Pointer of size_t to accept cached data length uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). size -- Pointer of size_t to accept cached data length uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). size -- Pointer of size_t to accept cached data length Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_get_tx_buffer_free_size(uart_port_t uart_num, size_t *size) UART get TX ring buffer free space size. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). size -- Pointer of size_t to accept the free space size uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). size -- Pointer of size_t to accept the free space size uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). size -- Pointer of size_t to accept the free space size Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t uart_disable_pattern_det_intr(uart_port_t uart_num) UART disable pattern detect function. Designed for applications like 'AT commands'. When the hardware detects a series of one same character, the interrupt will be triggered. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_FAIL Parameter error esp_err_t uart_enable_pattern_det_baud_intr(uart_port_t uart_num, char pattern_chr, uint8_t chr_num, int chr_tout, int post_idle, int pre_idle) UART enable pattern detect function. Designed for applications like 'AT commands'. When the hardware detect a series of one same character, the interrupt will be triggered. Parameters uart_num -- UART port number. pattern_chr -- character of the pattern. chr_num -- number of the character, 8bit value. chr_tout -- timeout of the interval between each pattern characters, 16bit value, unit is the baud-rate cycle you configured. When the duration is more than this value, it will not take this data as at_cmd char. post_idle -- idle time after the last pattern character, 16bit value, unit is the baud-rate cycle you configured. When the duration is less than this value, it will not take the previous data as the last at_cmd char pre_idle -- idle time before the first pattern character, 16bit value, unit is the baud-rate cycle you configured. When the duration is less than this value, it will not take this data as the first at_cmd char. uart_num -- UART port number. pattern_chr -- character of the pattern. chr_num -- number of the character, 8bit value. chr_tout -- timeout of the interval between each pattern characters, 16bit value, unit is the baud-rate cycle you configured. When the duration is more than this value, it will not take this data as at_cmd char. post_idle -- idle time after the last pattern character, 16bit value, unit is the baud-rate cycle you configured. When the duration is less than this value, it will not take the previous data as the last at_cmd char pre_idle -- idle time before the first pattern character, 16bit value, unit is the baud-rate cycle you configured. When the duration is less than this value, it will not take this data as the first at_cmd char. uart_num -- UART port number. Returns ESP_OK Success ESP_FAIL Parameter error ESP_OK Success ESP_FAIL Parameter error ESP_OK Success Parameters uart_num -- UART port number. pattern_chr -- character of the pattern. chr_num -- number of the character, 8bit value. chr_tout -- timeout of the interval between each pattern characters, 16bit value, unit is the baud-rate cycle you configured. When the duration is more than this value, it will not take this data as at_cmd char. post_idle -- idle time after the last pattern character, 16bit value, unit is the baud-rate cycle you configured. When the duration is less than this value, it will not take the previous data as the last at_cmd char pre_idle -- idle time before the first pattern character, 16bit value, unit is the baud-rate cycle you configured. When the duration is less than this value, it will not take this data as the first at_cmd char. Returns ESP_OK Success ESP_FAIL Parameter error int uart_pattern_pop_pos(uart_port_t uart_num) Return the nearest detected pattern position in buffer. The positions of the detected pattern are saved in a queue, this function will dequeue the first pattern position and move the pointer to next pattern position. The following APIs will modify the pattern position info: uart_flush_input, uart_read_bytes, uart_driver_delete, uart_pop_pattern_pos It is the application's responsibility to ensure atomic access to the pattern queue and the rx data buffer when using pattern detect feature. Note If the RX buffer is full and flow control is not enabled, the detected pattern may not be found in the rx buffer due to overflow. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns (-1) No pattern found for current index or parameter error others the pattern position in rx buffer. (-1) No pattern found for current index or parameter error others the pattern position in rx buffer. (-1) No pattern found for current index or parameter error Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns (-1) No pattern found for current index or parameter error others the pattern position in rx buffer. int uart_pattern_get_pos(uart_port_t uart_num) Return the nearest detected pattern position in buffer. The positions of the detected pattern are saved in a queue, This function do nothing to the queue. The following APIs will modify the pattern position info: uart_flush_input, uart_read_bytes, uart_driver_delete, uart_pop_pattern_pos It is the application's responsibility to ensure atomic access to the pattern queue and the rx data buffer when using pattern detect feature. Note If the RX buffer is full and flow control is not enabled, the detected pattern may not be found in the rx buffer due to overflow. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns (-1) No pattern found for current index or parameter error others the pattern position in rx buffer. (-1) No pattern found for current index or parameter error others the pattern position in rx buffer. (-1) No pattern found for current index or parameter error Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns (-1) No pattern found for current index or parameter error others the pattern position in rx buffer. esp_err_t uart_pattern_queue_reset(uart_port_t uart_num, int queue_length) Allocate a new memory with the given length to save record the detected pattern position in rx buffer. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). queue_length -- Max queue length for the detected pattern. If the queue length is not large enough, some pattern positions might be lost. Set this value to the maximum number of patterns that could be saved in data buffer at the same time. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). queue_length -- Max queue length for the detected pattern. If the queue length is not large enough, some pattern positions might be lost. Set this value to the maximum number of patterns that could be saved in data buffer at the same time. uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). Returns ESP_ERR_NO_MEM No enough memory ESP_ERR_INVALID_STATE Driver not installed ESP_FAIL Parameter error ESP_OK Success ESP_ERR_NO_MEM No enough memory ESP_ERR_INVALID_STATE Driver not installed ESP_FAIL Parameter error ESP_OK Success ESP_ERR_NO_MEM No enough memory Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). queue_length -- Max queue length for the detected pattern. If the queue length is not large enough, some pattern positions might be lost. Set this value to the maximum number of patterns that could be saved in data buffer at the same time. Returns ESP_ERR_NO_MEM No enough memory ESP_ERR_INVALID_STATE Driver not installed ESP_FAIL Parameter error ESP_OK Success esp_err_t uart_set_mode(uart_port_t uart_num, uart_mode_t mode) UART set communication mode. Note This function must be executed after uart_driver_install(), when the driver object is initialized. Parameters uart_num -- Uart number to configure, the max port number is (UART_NUM_MAX -1). mode -- UART UART mode to set uart_num -- Uart number to configure, the max port number is (UART_NUM_MAX -1). mode -- UART UART mode to set uart_num -- Uart number to configure, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters uart_num -- Uart number to configure, the max port number is (UART_NUM_MAX -1). mode -- UART UART mode to set Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t uart_set_rx_full_threshold(uart_port_t uart_num, int threshold) Set uart threshold value for RX fifo full. Note If application is using higher baudrate and it is observed that bytes in hardware RX fifo are overwritten then this threshold can be reduced Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1) threshold -- Threshold value above which RX fifo full interrupt is generated uart_num -- UART port number, the max port number is (UART_NUM_MAX -1) threshold -- Threshold value above which RX fifo full interrupt is generated uart_num -- UART port number, the max port number is (UART_NUM_MAX -1) Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Driver is not installed ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Driver is not installed ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1) threshold -- Threshold value above which RX fifo full interrupt is generated Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Driver is not installed esp_err_t uart_set_tx_empty_threshold(uart_port_t uart_num, int threshold) Set uart threshold values for TX fifo empty. Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1) threshold -- Threshold value below which TX fifo empty interrupt is generated uart_num -- UART port number, the max port number is (UART_NUM_MAX -1) threshold -- Threshold value below which TX fifo empty interrupt is generated uart_num -- UART port number, the max port number is (UART_NUM_MAX -1) Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Driver is not installed ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Driver is not installed ESP_OK Success Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1) threshold -- Threshold value below which TX fifo empty interrupt is generated Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Driver is not installed esp_err_t uart_set_rx_timeout(uart_port_t uart_num, const uint8_t tout_thresh) UART set threshold timeout for TOUT feature. Parameters uart_num -- Uart number to configure, the max port number is (UART_NUM_MAX -1). tout_thresh -- This parameter defines timeout threshold in uart symbol periods. The maximum value of threshold is 126. tout_thresh = 1, defines TOUT interrupt timeout equal to transmission time of one symbol (~11 bit) on current baudrate. If the time is expired the UART_RXFIFO_TOUT_INT interrupt is triggered. If tout_thresh == 0, the TOUT feature is disabled. uart_num -- Uart number to configure, the max port number is (UART_NUM_MAX -1). tout_thresh -- This parameter defines timeout threshold in uart symbol periods. The maximum value of threshold is 126. tout_thresh = 1, defines TOUT interrupt timeout equal to transmission time of one symbol (~11 bit) on current baudrate. If the time is expired the UART_RXFIFO_TOUT_INT interrupt is triggered. If tout_thresh == 0, the TOUT feature is disabled. uart_num -- Uart number to configure, the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Driver is not installed ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Driver is not installed ESP_OK Success Parameters uart_num -- Uart number to configure, the max port number is (UART_NUM_MAX -1). tout_thresh -- This parameter defines timeout threshold in uart symbol periods. The maximum value of threshold is 126. tout_thresh = 1, defines TOUT interrupt timeout equal to transmission time of one symbol (~11 bit) on current baudrate. If the time is expired the UART_RXFIFO_TOUT_INT interrupt is triggered. If tout_thresh == 0, the TOUT feature is disabled. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Driver is not installed esp_err_t uart_get_collision_flag(uart_port_t uart_num, bool *collision_flag) Returns collision detection flag for RS485 mode Function returns the collision detection flag into variable pointed by collision_flag. *collision_flag = true, if collision detected else it is equal to false. This function should be executed when actual transmission is completed (after uart_write_bytes()). Parameters uart_num -- Uart number to configure the max port number is (UART_NUM_MAX -1). collision_flag -- Pointer to variable of type bool to return collision flag. uart_num -- Uart number to configure the max port number is (UART_NUM_MAX -1). collision_flag -- Pointer to variable of type bool to return collision flag. uart_num -- Uart number to configure the max port number is (UART_NUM_MAX -1). Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters uart_num -- Uart number to configure the max port number is (UART_NUM_MAX -1). collision_flag -- Pointer to variable of type bool to return collision flag. Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error esp_err_t uart_set_wakeup_threshold(uart_port_t uart_num, int wakeup_threshold) Set the number of RX pin signal edges for light sleep wakeup. UART can be used to wake up the system from light sleep. This feature works by counting the number of positive edges on RX pin and comparing the count to the threshold. When the count exceeds the threshold, system is woken up from light sleep. This function allows setting the threshold value. Stop bit and parity bits (if enabled) also contribute to the number of edges. For example, letter 'a' with ASCII code 97 is encoded as 0100001101 on the wire (with 8n1 configuration), start and stop bits included. This sequence has 3 positive edges (transitions from 0 to 1). Therefore, to wake up the system when 'a' is sent, set wakeup_threshold=3. The character that triggers wakeup is not received by UART (i.e. it can not be obtained from UART FIFO). Depending on the baud rate, a few characters after that will also not be received. Note that when the chip enters and exits light sleep mode, APB frequency will be changing. To ensure that UART has correct Baud rate all the time, it is necessary to select a source clock which has a fixed frequency and remains active during sleep. For the supported clock sources of the chips, please refer to uart_sclk_t or soc_periph_uart_clk_src_legacy_t Note in ESP32, the wakeup signal can only be input via IO_MUX (i.e. GPIO3 should be configured as function_1 to wake up UART0, GPIO9 should be configured as function_5 to wake up UART1), UART2 does not support light sleep wakeup feature. Parameters uart_num -- UART number, the max port number is (UART_NUM_MAX -1). wakeup_threshold -- number of RX edges for light sleep wakeup, value is 3 .. 0x3ff. uart_num -- UART number, the max port number is (UART_NUM_MAX -1). wakeup_threshold -- number of RX edges for light sleep wakeup, value is 3 .. 0x3ff. uart_num -- UART number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK on success ESP_ERR_INVALID_ARG if uart_num is incorrect or wakeup_threshold is outside of [3, 0x3ff] range. ESP_OK on success ESP_ERR_INVALID_ARG if uart_num is incorrect or wakeup_threshold is outside of [3, 0x3ff] range. ESP_OK on success Parameters uart_num -- UART number, the max port number is (UART_NUM_MAX -1). wakeup_threshold -- number of RX edges for light sleep wakeup, value is 3 .. 0x3ff. Returns ESP_OK on success ESP_ERR_INVALID_ARG if uart_num is incorrect or wakeup_threshold is outside of [3, 0x3ff] range. esp_err_t uart_get_wakeup_threshold(uart_port_t uart_num, int *out_wakeup_threshold) Get the number of RX pin signal edges for light sleep wakeup. See description of uart_set_wakeup_threshold for the explanation of UART wakeup feature. Parameters uart_num -- UART number, the max port number is (UART_NUM_MAX -1). out_wakeup_threshold -- [out] output, set to the current value of wakeup threshold for the given UART. uart_num -- UART number, the max port number is (UART_NUM_MAX -1). out_wakeup_threshold -- [out] output, set to the current value of wakeup threshold for the given UART. uart_num -- UART number, the max port number is (UART_NUM_MAX -1). Returns ESP_OK on success ESP_ERR_INVALID_ARG if out_wakeup_threshold is NULL ESP_OK on success ESP_ERR_INVALID_ARG if out_wakeup_threshold is NULL ESP_OK on success Parameters uart_num -- UART number, the max port number is (UART_NUM_MAX -1). out_wakeup_threshold -- [out] output, set to the current value of wakeup threshold for the given UART. Returns ESP_OK on success ESP_ERR_INVALID_ARG if out_wakeup_threshold is NULL esp_err_t uart_wait_tx_idle_polling(uart_port_t uart_num) Wait until UART tx memory empty and the last char send ok (polling mode). Returns ESP_OK on success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Driver not installed ESP_OK on success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Driver not installed ESP_OK on success Parameters uart_num -- UART number Returns ESP_OK on success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Driver not installed Parameters uart_num -- UART number esp_err_t uart_set_loop_back(uart_port_t uart_num, bool loop_back_en) Configure TX signal loop back to RX module, just for the test usage. Returns ESP_OK on success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Driver not installed ESP_OK on success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Driver not installed ESP_OK on success Parameters uart_num -- UART number loop_back_en -- Set ture to enable the loop back function, else set it false. uart_num -- UART number loop_back_en -- Set ture to enable the loop back function, else set it false. uart_num -- UART number Returns ESP_OK on success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Driver not installed Parameters uart_num -- UART number loop_back_en -- Set ture to enable the loop back function, else set it false. void uart_set_always_rx_timeout(uart_port_t uart_num, bool always_rx_timeout_en) Configure behavior of UART RX timeout interrupt. When always_rx_timeout is true, timeout interrupt is triggered even if FIFO is full. This function can cause extra timeout interrupts triggered only to send the timeout event. Call this function only if you want to ensure timeout interrupt will always happen after a byte stream. Parameters uart_num -- UART number always_rx_timeout_en -- Set to false enable the default behavior of timeout interrupt, set it to true to always trigger timeout interrupt. uart_num -- UART number always_rx_timeout_en -- Set to false enable the default behavior of timeout interrupt, set it to true to always trigger timeout interrupt. uart_num -- UART number Parameters uart_num -- UART number always_rx_timeout_en -- Set to false enable the default behavior of timeout interrupt, set it to true to always trigger timeout interrupt. Structures struct uart_config_t UART configuration parameters for uart_param_config function. Public Members int baud_rate UART baud rate int baud_rate UART baud rate uart_word_length_t data_bits UART byte size uart_word_length_t data_bits UART byte size uart_parity_t parity UART parity mode uart_parity_t parity UART parity mode uart_stop_bits_t stop_bits UART stop bits uart_stop_bits_t stop_bits UART stop bits uart_hw_flowcontrol_t flow_ctrl UART HW flow control mode (cts/rts) uart_hw_flowcontrol_t flow_ctrl UART HW flow control mode (cts/rts) uint8_t rx_flow_ctrl_thresh UART HW RTS threshold uint8_t rx_flow_ctrl_thresh UART HW RTS threshold uart_sclk_t source_clk UART source clock selection uart_sclk_t source_clk UART source clock selection int baud_rate struct uart_intr_config_t UART interrupt configuration parameters for uart_intr_config function. Public Members uint32_t intr_enable_mask UART interrupt enable mask, choose from UART_XXXX_INT_ENA_M under UART_INT_ENA_REG(i), connect with bit-or operator uint32_t intr_enable_mask UART interrupt enable mask, choose from UART_XXXX_INT_ENA_M under UART_INT_ENA_REG(i), connect with bit-or operator uint8_t rx_timeout_thresh UART timeout interrupt threshold (unit: time of sending one byte) uint8_t rx_timeout_thresh UART timeout interrupt threshold (unit: time of sending one byte) uint8_t txfifo_empty_intr_thresh UART TX empty interrupt threshold. uint8_t txfifo_empty_intr_thresh UART TX empty interrupt threshold. uint8_t rxfifo_full_thresh UART RX full interrupt threshold. uint8_t rxfifo_full_thresh UART RX full interrupt threshold. uint32_t intr_enable_mask struct uart_event_t Event structure used in UART event queue. Public Members uart_event_type_t type UART event type uart_event_type_t type UART event type size_t size UART data size for UART_DATA event size_t size UART data size for UART_DATA event bool timeout_flag UART data read timeout flag for UART_DATA event (no new data received during configured RX TOUT) If the event is caused by FIFO-full interrupt, then there will be no event with the timeout flag before the next byte coming. bool timeout_flag UART data read timeout flag for UART_DATA event (no new data received during configured RX TOUT) If the event is caused by FIFO-full interrupt, then there will be no event with the timeout flag before the next byte coming. uart_event_type_t type Macros UART_PIN_NO_CHANGE UART_FIFO_LEN Length of the HP UART HW FIFO. UART_HW_FIFO_LEN(uart_num) Length of the UART HW FIFO. UART_BITRATE_MAX Maximum configurable bitrate. Type Definitions typedef intr_handle_t uart_isr_handle_t Enumerations enum uart_event_type_t UART event types used in the ring buffer. Values: enumerator UART_DATA UART data event enumerator UART_DATA UART data event enumerator UART_BREAK UART break event enumerator UART_BREAK UART break event enumerator UART_BUFFER_FULL UART RX buffer full event enumerator UART_BUFFER_FULL UART RX buffer full event enumerator UART_FIFO_OVF UART FIFO overflow event enumerator UART_FIFO_OVF UART FIFO overflow event enumerator UART_FRAME_ERR UART RX frame error event enumerator UART_FRAME_ERR UART RX frame error event enumerator UART_PARITY_ERR UART RX parity event enumerator UART_PARITY_ERR UART RX parity event enumerator UART_DATA_BREAK UART TX data and break event enumerator UART_DATA_BREAK UART TX data and break event enumerator UART_PATTERN_DET UART pattern detected enumerator UART_PATTERN_DET UART pattern detected enumerator UART_EVENT_MAX UART event max index enumerator UART_EVENT_MAX UART event max index enumerator UART_DATA Header File This header file can be included with: #include "hal/uart_types.h" Structures struct uart_at_cmd_t UART AT cmd char configuration parameters Note that this function may different on different chip. Please refer to the TRM at confirguration. Public Members uint8_t cmd_char UART AT cmd char uint8_t cmd_char UART AT cmd char uint8_t char_num AT cmd char repeat number uint8_t char_num AT cmd char repeat number uint32_t gap_tout gap time(in baud-rate) between AT cmd char uint32_t gap_tout gap time(in baud-rate) between AT cmd char uint32_t pre_idle the idle time(in baud-rate) between the non AT char and first AT char uint32_t pre_idle the idle time(in baud-rate) between the non AT char and first AT char uint32_t post_idle the idle time(in baud-rate) between the last AT char and the none AT char uint32_t post_idle the idle time(in baud-rate) between the last AT char and the none AT char uint8_t cmd_char struct uart_sw_flowctrl_t UART software flow control configuration parameters. Public Members uint8_t xon_char Xon flow control char uint8_t xon_char Xon flow control char uint8_t xoff_char Xoff flow control char uint8_t xoff_char Xoff flow control char uint8_t xon_thrd If the software flow control is enabled and the data amount in rxfifo is less than xon_thrd, an xon_char will be sent uint8_t xon_thrd If the software flow control is enabled and the data amount in rxfifo is less than xon_thrd, an xon_char will be sent uint8_t xoff_thrd If the software flow control is enabled and the data amount in rxfifo is more than xoff_thrd, an xoff_char will be sent uint8_t xoff_thrd If the software flow control is enabled and the data amount in rxfifo is more than xoff_thrd, an xoff_char will be sent uint8_t xon_char Type Definitions typedef soc_periph_uart_clk_src_legacy_t uart_sclk_t UART source clock. Enumerations enum uart_port_t UART port number, can be UART_NUM_0 ~ (UART_NUM_MAX -1). Values: enumerator UART_NUM_0 UART port 0 enumerator UART_NUM_0 UART port 0 enumerator UART_NUM_1 UART port 1 enumerator UART_NUM_1 UART port 1 enumerator UART_NUM_2 UART port 2 enumerator UART_NUM_2 UART port 2 enumerator UART_NUM_MAX UART port max enumerator UART_NUM_MAX UART port max enumerator UART_NUM_0 enum uart_mode_t UART mode selection. Values: enumerator UART_MODE_UART mode: regular UART mode enumerator UART_MODE_UART mode: regular UART mode enumerator UART_MODE_RS485_HALF_DUPLEX mode: half duplex RS485 UART mode control by RTS pin enumerator UART_MODE_RS485_HALF_DUPLEX mode: half duplex RS485 UART mode control by RTS pin enumerator UART_MODE_IRDA mode: IRDA UART mode enumerator UART_MODE_IRDA mode: IRDA UART mode enumerator UART_MODE_RS485_COLLISION_DETECT mode: RS485 collision detection UART mode (used for test purposes) enumerator UART_MODE_RS485_COLLISION_DETECT mode: RS485 collision detection UART mode (used for test purposes) enumerator UART_MODE_RS485_APP_CTRL mode: application control RS485 UART mode (used for test purposes) enumerator UART_MODE_RS485_APP_CTRL mode: application control RS485 UART mode (used for test purposes) enumerator UART_MODE_UART enum uart_word_length_t UART word length constants. Values: enumerator UART_DATA_5_BITS word length: 5bits enumerator UART_DATA_5_BITS word length: 5bits enumerator UART_DATA_6_BITS word length: 6bits enumerator UART_DATA_6_BITS word length: 6bits enumerator UART_DATA_7_BITS word length: 7bits enumerator UART_DATA_7_BITS word length: 7bits enumerator UART_DATA_8_BITS word length: 8bits enumerator UART_DATA_8_BITS word length: 8bits enumerator UART_DATA_BITS_MAX enumerator UART_DATA_BITS_MAX enumerator UART_DATA_5_BITS enum uart_stop_bits_t UART stop bits number. Values: enumerator UART_STOP_BITS_1 stop bit: 1bit enumerator UART_STOP_BITS_1 stop bit: 1bit enumerator UART_STOP_BITS_1_5 stop bit: 1.5bits enumerator UART_STOP_BITS_1_5 stop bit: 1.5bits enumerator UART_STOP_BITS_2 stop bit: 2bits enumerator UART_STOP_BITS_2 stop bit: 2bits enumerator UART_STOP_BITS_MAX enumerator UART_STOP_BITS_MAX enumerator UART_STOP_BITS_1 enum uart_parity_t UART parity constants. Values: enumerator UART_PARITY_DISABLE Disable UART parity enumerator UART_PARITY_DISABLE Disable UART parity enumerator UART_PARITY_EVEN Enable UART even parity enumerator UART_PARITY_EVEN Enable UART even parity enumerator UART_PARITY_ODD Enable UART odd parity enumerator UART_PARITY_ODD Enable UART odd parity enumerator UART_PARITY_DISABLE enum uart_hw_flowcontrol_t UART hardware flow control modes. Values: enumerator UART_HW_FLOWCTRL_DISABLE disable hardware flow control enumerator UART_HW_FLOWCTRL_DISABLE disable hardware flow control enumerator UART_HW_FLOWCTRL_RTS enable RX hardware flow control (rts) enumerator UART_HW_FLOWCTRL_RTS enable RX hardware flow control (rts) enumerator UART_HW_FLOWCTRL_CTS enable TX hardware flow control (cts) enumerator UART_HW_FLOWCTRL_CTS enable TX hardware flow control (cts) enumerator UART_HW_FLOWCTRL_CTS_RTS enable hardware flow control enumerator UART_HW_FLOWCTRL_CTS_RTS enable hardware flow control enumerator UART_HW_FLOWCTRL_MAX enumerator UART_HW_FLOWCTRL_MAX enumerator UART_HW_FLOWCTRL_DISABLE enum uart_signal_inv_t UART signal bit map. Values: enumerator UART_SIGNAL_INV_DISABLE Disable UART signal inverse enumerator UART_SIGNAL_INV_DISABLE Disable UART signal inverse enumerator UART_SIGNAL_IRDA_TX_INV inverse the UART irda_tx signal enumerator UART_SIGNAL_IRDA_TX_INV inverse the UART irda_tx signal enumerator UART_SIGNAL_IRDA_RX_INV inverse the UART irda_rx signal enumerator UART_SIGNAL_IRDA_RX_INV inverse the UART irda_rx signal enumerator UART_SIGNAL_RXD_INV inverse the UART rxd signal enumerator UART_SIGNAL_RXD_INV inverse the UART rxd signal enumerator UART_SIGNAL_CTS_INV inverse the UART cts signal enumerator UART_SIGNAL_CTS_INV inverse the UART cts signal enumerator UART_SIGNAL_DSR_INV inverse the UART dsr signal enumerator UART_SIGNAL_DSR_INV inverse the UART dsr signal enumerator UART_SIGNAL_TXD_INV inverse the UART txd signal enumerator UART_SIGNAL_TXD_INV inverse the UART txd signal enumerator UART_SIGNAL_RTS_INV inverse the UART rts signal enumerator UART_SIGNAL_RTS_INV inverse the UART rts signal enumerator UART_SIGNAL_DTR_INV inverse the UART dtr signal enumerator UART_SIGNAL_DTR_INV inverse the UART dtr signal enumerator UART_SIGNAL_INV_DISABLE GPIO Lookup Macros The UART peripherals have dedicated IO_MUX pins to which they are connected directly. However, signals can also be routed to other pins using the less direct GPIO matrix. To use direct routes, you need to know which pin is a dedicated IO_MUX pin for a UART channel. GPIO Lookup Macros simplify the process of finding and assigning IO_MUX pins. You choose a macro based on either the IO_MUX pin number, or a required UART channel name, and the macro returns the matching counterpart for you. See some examples below. Note These macros are useful if you need very high UART baud rates (over 40 MHz), which means you will have to use IO_MUX pins only. In other cases, these macros can be ignored, and you can use the GPIO Matrix as it allows you to configure any GPIO pin for any UART function. UART_NUM_2_TXD_DIRECT_GPIO_NUM returns the IO_MUX pin number of UART channel 2 TXD pin (pin 17) UART_GPIO19_DIRECT_CHANNEL returns the UART number of GPIO 19 when connected to the UART peripheral via IO_MUX (this is UART_NUM_0) UART_CTS_GPIO19_DIRECT_CHANNEL returns the UART number of GPIO 19 when used as the UART CTS pin via IO_MUX (this is UART_NUM_0). It is similar to the above macro but specifies the pin function which is also part of the IO_MUX assignment. Header File This header file can be included with: #include "soc/uart_channel.h" Macros UART_GPIO1_DIRECT_CHANNEL UART_NUM_0_TXD_DIRECT_GPIO_NUM UART_GPIO3_DIRECT_CHANNEL UART_NUM_0_RXD_DIRECT_GPIO_NUM UART_GPIO19_DIRECT_CHANNEL UART_NUM_0_CTS_DIRECT_GPIO_NUM UART_GPIO22_DIRECT_CHANNEL UART_NUM_0_RTS_DIRECT_GPIO_NUM UART_TXD_GPIO1_DIRECT_CHANNEL UART_RXD_GPIO3_DIRECT_CHANNEL UART_CTS_GPIO19_DIRECT_CHANNEL UART_RTS_GPIO22_DIRECT_CHANNEL UART_GPIO10_DIRECT_CHANNEL UART_NUM_1_TXD_DIRECT_GPIO_NUM UART_GPIO9_DIRECT_CHANNEL UART_NUM_1_RXD_DIRECT_GPIO_NUM UART_GPIO6_DIRECT_CHANNEL UART_NUM_1_CTS_DIRECT_GPIO_NUM UART_GPIO11_DIRECT_CHANNEL UART_NUM_1_RTS_DIRECT_GPIO_NUM UART_TXD_GPIO10_DIRECT_CHANNEL UART_RXD_GPIO9_DIRECT_CHANNEL UART_CTS_GPIO6_DIRECT_CHANNEL UART_RTS_GPIO11_DIRECT_CHANNEL UART_GPIO17_DIRECT_CHANNEL UART_NUM_2_TXD_DIRECT_GPIO_NUM UART_GPIO16_DIRECT_CHANNEL UART_NUM_2_RXD_DIRECT_GPIO_NUM UART_GPIO8_DIRECT_CHANNEL UART_NUM_2_CTS_DIRECT_GPIO_NUM UART_GPIO7_DIRECT_CHANNEL UART_NUM_2_RTS_DIRECT_GPIO_NUM UART_TXD_GPIO17_DIRECT_CHANNEL UART_RXD_GPIO16_DIRECT_CHANNEL UART_CTS_GPIO8_DIRECT_CHANNEL UART_RTS_GPIO7_DIRECT_CHANNEL
Universal Asynchronous Receiver/Transmitter (UART) Introduction A Universal Asynchronous Receiver/Transmitter (UART) is a hardware feature that handles communication (i.e., timing requirements and data framing) using widely-adopted asynchronous serial communication interfaces, such as RS232, RS422, and RS485. A UART provides a widely adopted and cheap method to realize full-duplex or half-duplex data exchange among different devices. The ESP32 chip has 3 UART controllers (also referred to as port), each featuring an identical set of registers to simplify programming and for more flexibility. Each UART controller is independently configurable with parameters such as baud rate, data bit length, bit ordering, number of stop bits, parity bit, etc. All the regular UART controllers are compatible with UART-enabled devices from various manufacturers and can also support Infrared Data Association (IrDA) protocols. Functional Overview The overview describes how to establish communication between an ESP32 and other UART devices using the functions and data types of the UART driver. A typical programming workflow is broken down into the sections provided below: Set Communication Parameters - Setting baud rate, data bits, stop bits, etc. Set Communication Pins - Assigning pins for connection to a device Install Drivers - Allocating ESP32's resources for the UART driver Run UART Communication - Sending/receiving data Use Interrupts - Triggering interrupts on specific communication events Deleting a Driver - Freeing allocated resources if a UART communication is no longer required Steps 1 to 3 comprise the configuration stage. Step 4 is where the UART starts operating. Steps 5 and 6 are optional. The UART driver's functions identify each of the UART controllers using uart_port_t. This identification is needed for all the following function calls. Set Communication Parameters UART communication parameters can be configured all in a single step or individually in multiple steps. Single Step Call the function uart_param_config() and pass to it a uart_config_t structure. The uart_config_t structure should contain all the required parameters. See the example below. const uart_port_t uart_num = UART_NUM_2; uart_config_t uart_config = { .baud_rate = 115200, .data_bits = UART_DATA_8_BITS, .parity = UART_PARITY_DISABLE, .stop_bits = UART_STOP_BITS_1, .flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS, .rx_flow_ctrl_thresh = 122, }; // Configure UART parameters ESP_ERROR_CHECK(uart_param_config(uart_num, &uart_config)); For more information on how to configure the hardware flow control options, please refer to peripherals/uart/uart_echo. Multiple Steps Configure specific parameters individually by calling a dedicated function from the table given below. These functions are also useful if re-configuring a single parameter. | Parameter to Configure | Function | Baud rate | Number of transmitted bits | | Parity control | | Number of stop bits | | Hardware flow control mode | | Communication mode | Each of the above functions has a _get_ counterpart to check the currently set value. For example, to check the current baud rate value, call uart_get_baudrate(). Set Communication Pins After setting communication parameters, configure the physical GPIO pins to which the other UART device will be connected. For this, call the function uart_set_pin() and specify the GPIO pin numbers to which the driver should route the TX, RX, RTS, and CTS signals. If you want to keep a currently allocated pin number for a specific signal, pass the macro UART_PIN_NO_CHANGE. The same macro UART_PIN_NO_CHANGE should be specified for pins that will not be used. // Set UART pins(TX: IO4, RX: IO5, RTS: IO18, CTS: IO19) ESP_ERROR_CHECK(uart_set_pin(UART_NUM_2, 4, 5, 18, 19)); Install Drivers Once the communication pins are set, install the driver by calling uart_driver_install() and specify the following parameters: Size of TX ring buffer Size of RX ring buffer Event queue handle and size Flags to allocate an interrupt The function allocates the required internal resources for the UART driver. // Setup UART buffered IO with event queue const int uart_buffer_size = (1024 * 2); QueueHandle_t uart_queue; // Install UART driver using an event queue here ESP_ERROR_CHECK(uart_driver_install(UART_NUM_2, uart_buffer_size, \ uart_buffer_size, 10, &uart_queue, 0)); Once this step is complete, you can connect the external UART device and check the communication. Run UART Communication Serial communication is controlled by each UART controller's finite state machine (FSM). The process of sending data involves the following steps: Write data into TX FIFO buffer FSM serializes the data FSM sends the data out The process of receiving data is similar, but the steps are reversed: FSM processes an incoming serial stream and parallelizes it FSM writes the data into RX FIFO buffer Read the data from RX FIFO buffer Therefore, an application only writes and reads data from a specific buffer using uart_write_bytes() and uart_read_bytes() respectively, and the FSM does the rest. Transmit Data After preparing the data for transmission, call the function uart_write_bytes() and pass the data buffer's address and data length to it. The function copies the data to the TX ring buffer (either immediately or after enough space is available), and then exit. When there is free space in the TX FIFO buffer, an interrupt service routine (ISR) moves the data from the TX ring buffer to the TX FIFO buffer in the background. The code below demonstrates the use of this function. // Write data to UART. char* test_str = "This is a test string.\n"; uart_write_bytes(uart_num, (const char*)test_str, strlen(test_str)); The function uart_write_bytes_with_break() is similar to uart_write_bytes() but adds a serial break signal at the end of the transmission. A 'serial break signal' means holding the TX line low for a period longer than one data frame. // Write data to UART, end with a break signal. uart_write_bytes_with_break(uart_num, "test break\n",strlen("test break\n"), 100); Another function for writing data to the TX FIFO buffer is uart_tx_chars(). Unlike uart_write_bytes(), this function does not block until space is available. Instead, it writes all data which can immediately fit into the hardware TX FIFO, and then return the number of bytes that were written. There is a 'companion' function uart_wait_tx_done() that monitors the status of the TX FIFO buffer and returns once it is empty. // Wait for packet to be sent const uart_port_t uart_num = UART_NUM_2; ESP_ERROR_CHECK(uart_wait_tx_done(uart_num, 100)); // wait timeout is 100 RTOS ticks (TickType_t) Receive Data Once the data is received by the UART and saved in the RX FIFO buffer, it needs to be retrieved using the function uart_read_bytes(). Before reading data, you can check the number of bytes available in the RX FIFO buffer by calling uart_get_buffered_data_len(). An example of using these functions is given below. // Read data from UART. const uart_port_t uart_num = UART_NUM_2; uint8_t data[128]; int length = 0; ESP_ERROR_CHECK(uart_get_buffered_data_len(uart_num, (size_t*)&length)); length = uart_read_bytes(uart_num, data, length, 100); If the data in the RX FIFO buffer is no longer needed, you can clear the buffer by calling uart_flush(). Software Flow Control If the hardware flow control is disabled, you can manually set the RTS and DTR signal levels by using the functions uart_set_rts() and uart_set_dtr() respectively. Communication Mode Selection The UART controller supports a number of communication modes. A mode can be selected using the function uart_set_mode(). Once a specific mode is selected, the UART driver handles the behavior of a connected UART device accordingly. As an example, it can control the RS485 driver chip using the RTS line to allow half-duplex RS485 communication. // Setup UART in rs485 half duplex mode ESP_ERROR_CHECK(uart_set_mode(uart_num, UART_MODE_RS485_HALF_DUPLEX)); Use Interrupts There are many interrupts that can be generated depending on specific UART states or detected errors. The full list of available interrupts is provided in ESP32 Technical Reference Manual > UART Controller (UART) > UART Interrupts and UHCI Interrupts [PDF]. You can enable or disable specific interrupts by calling uart_enable_intr_mask() or uart_disable_intr_mask() respectively. The uart_driver_install() function installs the driver's internal interrupt handler to manage the TX and RX ring buffers and provides high-level API functions like events (see below). The API provides a convenient way to handle specific interrupts discussed in this document by wrapping them into dedicated functions: Event detection: There are several events defined in uart_event_type_tthat may be reported to a user application using the FreeRTOS queue functionality. You can enable this functionality when calling uart_driver_install()described in Install Drivers. An example of using Event detection can be found in peripherals/uart/uart_events. FIFO space threshold or transmission timeout reached: The TX and RX FIFO buffers can trigger an interrupt when they are filled with a specific number of characters, or on a timeout of sending or receiving data. To use these interrupts, do the following: Configure respective threshold values of the buffer length and timeout by entering them in the structure uart_intr_config_tand calling uart_intr_config() Enable the interrupts using the functions uart_enable_tx_intr()and uart_enable_rx_intr() Disable these interrupts using the corresponding functions uart_disable_tx_intr()or uart_disable_rx_intr() - Pattern detection: An interrupt triggered on detecting a 'pattern' of the same character being received/sent repeatedly. This functionality is demonstrated in the example peripherals/uart/uart_events. It can be used, e.g., to detect a command string with a specific number of identical characters (the 'pattern') at the end. The following functions are available: Configure and enable this interrupt using uart_enable_pattern_det_baud_intr() Disable the interrupt using uart_disable_pattern_det_intr() - Macros The API also defines several macros. For example, UART_HW_FIFO_LEN defines the length of hardware FIFO buffers; UART_BITRATE_MAX gives the maximum baud rate supported by the UART controllers, etc. Deleting a Driver If the communication established with uart_driver_install() is no longer required, the driver can be removed to free allocated resources by calling uart_driver_delete(). Overview of RS485 Specific Communication 0ptions Note The following section uses [UART_REGISTER_NAME].[UART_FIELD_BIT] to refer to UART register fields/bits. For more information on a specific option bit, see ESP32 Technical Reference Manual > UART Controller (UART) > Register Summary [PDF]. Use the register name to navigate to the register description and then find the field/bit. UART_RS485_CONF_REG.UART_RS485_EN: setting this bit enables RS485 communication mode support. UART_RS485_CONF_REG.UART_RS485TX_RX_EN: if this bit is set, the transmitter's output signal loops back to the receiver's input signal. UART_RS485_CONF_REG.UART_RS485RXBY_TX_EN: if this bit is set, the transmitter will still be sending data if the receiver is busy (remove collisions automatically by hardware). The ESP32's RS485 UART hardware can detect signal collisions during transmission of a datagram and generate the interrupt UART_RS485_CLASH_INT if this interrupt is enabled. The term collision means that a transmitted datagram is not equal to the one received on the other end. Data collisions are usually associated with the presence of other active devices on the bus or might occur due to bus errors. The collision detection feature allows handling collisions when their interrupts are activated and triggered. The interrupts UART_RS485_FRM_ERR_INT and UART_RS485_PARITY_ERR_INT can be used with the collision detection feature to control frame errors and parity bit errors accordingly in RS485 mode. This functionality is supported in the UART driver and can be used by selecting the UART_MODE_RS485_APP_CTRL mode (see the function uart_set_mode()). The collision detection feature can work with circuit A and circuit C (see Section Interface Connection Options). In the case of using circuit A or B, the RTS pin connected to the DE pin of the bus driver should be controlled by the user application. Use the function uart_get_collision_flag() to check if the collision detection flag has been raised. The ESP32 UART controllers themselves do not support half-duplex communication as they cannot provide automatic control of the RTS pin connected to the RE/DE input of RS485 bus driver. However, half-duplex communication can be achieved via software control of the RTS pin by the UART driver. This can be enabled by selecting the UART_MODE_RS485_HALF_DUPLEX mode when calling uart_set_mode(). Once the host starts writing data to the TX FIFO buffer, the UART driver automatically asserts the RTS pin (logic 1); once the last bit of the data has been transmitted, the driver de-asserts the RTS pin (logic 0). To use this mode, the software would have to disable the hardware flow control function. This mode works with all the used circuits shown below. Interface Connection Options This section provides example schematics to demonstrate the basic aspects of ESP32's RS485 interface connection. Note The schematics below do not necessarily contain all required elements. The analog devices ADM483 & ADM2483 are examples of common RS485 transceivers and can be replaced with other similar transceivers. Circuit A: Collision Detection Circuit VCC ---------------+ | +-------x-------+ RXD <------| R | | B|----------<> B TXD ------>| D ADM483 | ESP | | RS485 bus side RTS ------>| DE | | A|----------<> A +----| /RE | | +-------x-------+ | | GND GND This circuit is preferable because it allows for collision detection and is quite simple at the same time. The receiver in the line driver is constantly enabled, which allows the UART to monitor the RS485 bus. Echo suppression is performed by the UART peripheral when the bit UART_RS485_CONF_REG.UART_RS485TX_RX_EN is enabled. Circuit B: Manual Switching Transmitter/Receiver Without Collision Detection VCC ---------------+ | +-------x-------+ RXD <------| R | | B|-----------<> B TXD ------>| D ADM483 | ESP | | RS485 bus side RTS --+--->| DE | | | A|-----------<> A +----| /RE | +-------x-------+ | GND This circuit does not allow for collision detection. It suppresses the null bytes that the hardware receives when the bit UART_RS485_CONF_REG.UART_RS485TX_RX_EN is set. The bit UART_RS485_CONF_REG.UART_RS485RXBY_TX_EN is not applicable in this case. Circuit C: Auto Switching Transmitter/Receiver VCC1 <-------------------+-----------+ +-------------------+----> VCC2 10K ____ | | | | +---|____|--+ +---x-----------x---+ 10K ____ | | | | +---|____|--+ RX <----------+-------------------| RXD | | 10K ____ | A|---+---------------<> A (+) +-------|____|------| PV ADM2483 | | ____ 120 | ____ | | +---|____|---+ RS485 bus side VCC1 <--+--|____|--+------->| DE | | 10K | | B|---+------------+--<> B (-) ---+ +-->| /RE | | ____ 10K | | | | +---|____|---+ ____ | /-C +---| TXD | 10K | TX >---|____|--+_B_|/ NPN | | | | |\ | +---x-----------x---+ | | \-E | | | | | | | | | GND1 GND1 GND1 GND2 GND2 This galvanically isolated circuit does not require RTS pin control by a software application or driver because it controls the transceiver direction automatically. However, it requires suppressing null bytes during transmission by setting UART_RS485_CONF_REG.UART_RS485RXBY_TX_EN to 1 and UART_RS485_CONF_REG.UART_RS485TX_RX_EN to 0. This setup can work in any RS485 UART mode or even in UART_MODE_UART. Application Examples The table below describes the code examples available in the directory peripherals/uart/. | Code Example | Description | Configuring UART settings, installing the UART driver, and reading/writing over the UART1 interface. | Reporting various communication events, using pattern detection interrupts. | Transmitting and receiving data in two separate FreeRTOS tasks over the same UART. | Using synchronous I/O multiplexing for UART file descriptors. | Setting up UART driver to communicate over RS485 interface in half-duplex mode. This example is similar to peripherals/uart/uart_echo but allows communication through an RS485 interface chip connected to ESP32 pins. | Obtaining GPS information by parsing NMEA0183 statements received from GPS via the UART peripheral. API Reference Header File This header file can be included with: #include "driver/uart.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Functions - esp_err_t uart_driver_install(uart_port_t uart_num, int rx_buffer_size, int tx_buffer_size, int queue_size, QueueHandle_t *uart_queue, int intr_alloc_flags) Install UART driver and set the UART to the default configuration. UART ISR handler will be attached to the same CPU core that this function is running on. Note Rx_buffer_size should be greater than UART_HW_FIFO_LEN(uart_num). Tx_buffer_size should be either zero or greater than UART_HW_FIFO_LEN(uart_num). - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). rx_buffer_size -- UART RX ring buffer size. tx_buffer_size -- UART TX ring buffer size. If set to zero, driver will not use TX buffer, TX function will block task until all data have been sent out. queue_size -- UART event queue size/depth. uart_queue -- UART event queue handle (out param). On success, a new queue handle is written here to provide access to UART events. If set to NULL, driver will not use an event queue. intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. Do not set ESP_INTR_FLAG_IRAM here (the driver's ISR handler is not located in IRAM) - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_driver_delete(uart_port_t uart_num) Uninstall UART driver. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). - Returns ESP_OK Success ESP_FAIL Parameter error - - bool uart_is_driver_installed(uart_port_t uart_num) Checks whether the driver is installed or not. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). - Returns true driver is installed false driver is not installed - - esp_err_t uart_set_word_length(uart_port_t uart_num, uart_word_length_t data_bit) Set UART data bits. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). data_bit -- UART data bits - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_get_word_length(uart_port_t uart_num, uart_word_length_t *data_bit) Get the UART data bit configuration. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). data_bit -- Pointer to accept value of UART data bits. - - Returns ESP_FAIL Parameter error ESP_OK Success, result will be put in (*data_bit) - - esp_err_t uart_set_stop_bits(uart_port_t uart_num, uart_stop_bits_t stop_bits) Set UART stop bits. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). stop_bits -- UART stop bits - - Returns ESP_OK Success ESP_FAIL Fail - - esp_err_t uart_get_stop_bits(uart_port_t uart_num, uart_stop_bits_t *stop_bits) Get the UART stop bit configuration. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). stop_bits -- Pointer to accept value of UART stop bits. - - Returns ESP_FAIL Parameter error ESP_OK Success, result will be put in (*stop_bit) - - esp_err_t uart_set_parity(uart_port_t uart_num, uart_parity_t parity_mode) Set UART parity mode. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). parity_mode -- the enum of uart parity configuration - - Returns ESP_FAIL Parameter error ESP_OK Success - - esp_err_t uart_get_parity(uart_port_t uart_num, uart_parity_t *parity_mode) Get the UART parity mode configuration. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). parity_mode -- Pointer to accept value of UART parity mode. - - Returns ESP_FAIL Parameter error ESP_OK Success, result will be put in (*parity_mode) - - esp_err_t uart_get_sclk_freq(uart_sclk_t sclk, uint32_t *out_freq_hz) Get the frequency of a clock source for the HP UART port. - Parameters sclk -- Clock source out_freq_hz -- [out] Output of frequency, in Hz - - Returns ESP_ERR_INVALID_ARG: if the clock source is not supported otherwise ESP_OK - - esp_err_t uart_set_baudrate(uart_port_t uart_num, uint32_t baudrate) Set UART baud rate. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). baudrate -- UART baud rate. - - Returns ESP_FAIL Parameter error ESP_OK Success - - esp_err_t uart_get_baudrate(uart_port_t uart_num, uint32_t *baudrate) Get the UART baud rate configuration. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). baudrate -- Pointer to accept value of UART baud rate - - Returns ESP_FAIL Parameter error ESP_OK Success, result will be put in (*baudrate) - - esp_err_t uart_set_line_inverse(uart_port_t uart_num, uint32_t inverse_mask) Set UART line inverse mode. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). inverse_mask -- Choose the wires that need to be inverted. Using the ORred mask of uart_signal_inv_t - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_set_hw_flow_ctrl(uart_port_t uart_num, uart_hw_flowcontrol_t flow_ctrl, uint8_t rx_thresh) Set hardware flow control. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). flow_ctrl -- Hardware flow control mode rx_thresh -- Threshold of Hardware RX flow control (0 ~ UART_HW_FIFO_LEN(uart_num)). Only when UART_HW_FLOWCTRL_RTS is set, will the rx_thresh value be set. - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_set_sw_flow_ctrl(uart_port_t uart_num, bool enable, uint8_t rx_thresh_xon, uint8_t rx_thresh_xoff) Set software flow control. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1) enable -- switch on or off rx_thresh_xon -- low water mark rx_thresh_xoff -- high water mark - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_get_hw_flow_ctrl(uart_port_t uart_num, uart_hw_flowcontrol_t *flow_ctrl) Get the UART hardware flow control configuration. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). flow_ctrl -- Option for different flow control mode. - - Returns ESP_FAIL Parameter error ESP_OK Success, result will be put in (*flow_ctrl) - - esp_err_t uart_clear_intr_status(uart_port_t uart_num, uint32_t clr_mask) Clear UART interrupt status. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). clr_mask -- Bit mask of the interrupt status to be cleared. - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_enable_intr_mask(uart_port_t uart_num, uint32_t enable_mask) Set UART interrupt enable. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). enable_mask -- Bit mask of the enable bits. - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_disable_intr_mask(uart_port_t uart_num, uint32_t disable_mask) Clear UART interrupt enable bits. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). disable_mask -- Bit mask of the disable bits. - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_enable_rx_intr(uart_port_t uart_num) Enable UART RX interrupt (RX_FULL & RX_TIMEOUT INTERRUPT) - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_disable_rx_intr(uart_port_t uart_num) Disable UART RX interrupt (RX_FULL & RX_TIMEOUT INTERRUPT) - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_disable_tx_intr(uart_port_t uart_num) Disable UART TX interrupt (TX_FULL & TX_TIMEOUT INTERRUPT) - Parameters uart_num -- UART port number - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_enable_tx_intr(uart_port_t uart_num, int enable, int thresh) Enable UART TX interrupt (TX_FULL & TX_TIMEOUT INTERRUPT) - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). enable -- 1: enable; 0: disable thresh -- Threshold of TX interrupt, 0 ~ UART_HW_FIFO_LEN(uart_num) - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_set_pin(uart_port_t uart_num, int tx_io_num, int rx_io_num, int rts_io_num, int cts_io_num) Assign signals of a UART peripheral to GPIO pins. Note If the GPIO number configured for a UART signal matches one of the IOMUX signals for that GPIO, the signal will be connected directly via the IOMUX. Otherwise the GPIO and signal will be connected via the GPIO Matrix. For example, if on an ESP32 the call uart_set_pin(0, 1, 3, -1, -1)is performed, as GPIO1 is UART0's default TX pin and GPIO3 is UART0's default RX pin, both will be connected to respectively U0TXD and U0RXD through the IOMUX, totally bypassing the GPIO matrix. The check is performed on a per-pin basis. Thus, it is possible to have RX pin binded to a GPIO through the GPIO matrix, whereas TX is binded to its GPIO through the IOMUX. Note Internal signal can be output to multiple GPIO pads. Only one GPIO pad can connect with input signal. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). tx_io_num -- UART TX pin GPIO number. rx_io_num -- UART RX pin GPIO number. rts_io_num -- UART RTS pin GPIO number. cts_io_num -- UART CTS pin GPIO number. - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_set_rts(uart_port_t uart_num, int level) Manually set the UART RTS pin level. Note UART must be configured with hardware flow control disabled. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). level -- 1: RTS output low (active); 0: RTS output high (block) - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_set_dtr(uart_port_t uart_num, int level) Manually set the UART DTR pin level. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). level -- 1: DTR output low; 0: DTR output high - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_set_tx_idle_num(uart_port_t uart_num, uint16_t idle_num) Set UART idle interval after tx FIFO is empty. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). idle_num -- idle interval after tx FIFO is empty(unit: the time it takes to send one bit under current baudrate) - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_param_config(uart_port_t uart_num, const uart_config_t *uart_config) Set UART configuration parameters. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). uart_config -- UART parameter settings - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_intr_config(uart_port_t uart_num, const uart_intr_config_t *intr_conf) Configure UART interrupts. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). intr_conf -- UART interrupt settings - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_wait_tx_done(uart_port_t uart_num, TickType_t ticks_to_wait) Wait until UART TX FIFO is empty. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). ticks_to_wait -- Timeout, count in RTOS ticks - - Returns ESP_OK Success ESP_FAIL Parameter error ESP_ERR_TIMEOUT Timeout - - int uart_tx_chars(uart_port_t uart_num, const char *buffer, uint32_t len) Send data to the UART port from a given buffer and length. This function will not wait for enough space in TX FIFO. It will just fill the available TX FIFO and return when the FIFO is full. Note This function should only be used when UART TX buffer is not enabled. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). buffer -- data buffer address len -- data length to send - - Returns (-1) Parameter error OTHERS (>=0) The number of bytes pushed to the TX FIFO - - int uart_write_bytes(uart_port_t uart_num, const void *src, size_t size) Send data to the UART port from a given buffer and length,. If the UART driver's parameter 'tx_buffer_size' is set to zero: This function will not return until all the data have been sent out, or at least pushed into TX FIFO. Otherwise, if the 'tx_buffer_size' > 0, this function will return after copying all the data to tx ring buffer, UART ISR will then move data from the ring buffer to TX FIFO gradually. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). src -- data buffer address size -- data length to send - - Returns (-1) Parameter error OTHERS (>=0) The number of bytes pushed to the TX FIFO - - int uart_write_bytes_with_break(uart_port_t uart_num, const void *src, size_t size, int brk_len) Send data to the UART port from a given buffer and length,. If the UART driver's parameter 'tx_buffer_size' is set to zero: This function will not return until all the data and the break signal have been sent out. After all data is sent out, send a break signal. Otherwise, if the 'tx_buffer_size' > 0, this function will return after copying all the data to tx ring buffer, UART ISR will then move data from the ring buffer to TX FIFO gradually. After all data sent out, send a break signal. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). src -- data buffer address size -- data length to send brk_len -- break signal duration(unit: the time it takes to send one bit at current baudrate) - - Returns (-1) Parameter error OTHERS (>=0) The number of bytes pushed to the TX FIFO - - int uart_read_bytes(uart_port_t uart_num, void *buf, uint32_t length, TickType_t ticks_to_wait) UART read bytes from UART buffer. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). buf -- pointer to the buffer. length -- data length ticks_to_wait -- sTimeout, count in RTOS ticks - - Returns (-1) Error OTHERS (>=0) The number of bytes read from UART buffer - - esp_err_t uart_flush(uart_port_t uart_num) Alias of uart_flush_input. UART ring buffer flush. This will discard all data in the UART RX buffer. Note Instead of waiting the data sent out, this function will clear UART rx buffer. In order to send all the data in tx FIFO, we can use uart_wait_tx_done function. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_flush_input(uart_port_t uart_num) Clear input buffer, discard all the data is in the ring-buffer. Note In order to send all the data in tx FIFO, we can use uart_wait_tx_done function. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_get_buffered_data_len(uart_port_t uart_num, size_t *size) UART get RX ring buffer cached data length. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). size -- Pointer of size_t to accept cached data length - - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_get_tx_buffer_free_size(uart_port_t uart_num, size_t *size) UART get TX ring buffer free space size. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). size -- Pointer of size_t to accept the free space size - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t uart_disable_pattern_det_intr(uart_port_t uart_num) UART disable pattern detect function. Designed for applications like 'AT commands'. When the hardware detects a series of one same character, the interrupt will be triggered. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). - Returns ESP_OK Success ESP_FAIL Parameter error - - esp_err_t uart_enable_pattern_det_baud_intr(uart_port_t uart_num, char pattern_chr, uint8_t chr_num, int chr_tout, int post_idle, int pre_idle) UART enable pattern detect function. Designed for applications like 'AT commands'. When the hardware detect a series of one same character, the interrupt will be triggered. - Parameters uart_num -- UART port number. pattern_chr -- character of the pattern. chr_num -- number of the character, 8bit value. chr_tout -- timeout of the interval between each pattern characters, 16bit value, unit is the baud-rate cycle you configured. When the duration is more than this value, it will not take this data as at_cmd char. post_idle -- idle time after the last pattern character, 16bit value, unit is the baud-rate cycle you configured. When the duration is less than this value, it will not take the previous data as the last at_cmd char pre_idle -- idle time before the first pattern character, 16bit value, unit is the baud-rate cycle you configured. When the duration is less than this value, it will not take this data as the first at_cmd char. - - Returns ESP_OK Success ESP_FAIL Parameter error - - int uart_pattern_pop_pos(uart_port_t uart_num) Return the nearest detected pattern position in buffer. The positions of the detected pattern are saved in a queue, this function will dequeue the first pattern position and move the pointer to next pattern position. The following APIs will modify the pattern position info: uart_flush_input, uart_read_bytes, uart_driver_delete, uart_pop_pattern_pos It is the application's responsibility to ensure atomic access to the pattern queue and the rx data buffer when using pattern detect feature. Note If the RX buffer is full and flow control is not enabled, the detected pattern may not be found in the rx buffer due to overflow. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). - Returns (-1) No pattern found for current index or parameter error others the pattern position in rx buffer. - - int uart_pattern_get_pos(uart_port_t uart_num) Return the nearest detected pattern position in buffer. The positions of the detected pattern are saved in a queue, This function do nothing to the queue. The following APIs will modify the pattern position info: uart_flush_input, uart_read_bytes, uart_driver_delete, uart_pop_pattern_pos It is the application's responsibility to ensure atomic access to the pattern queue and the rx data buffer when using pattern detect feature. Note If the RX buffer is full and flow control is not enabled, the detected pattern may not be found in the rx buffer due to overflow. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). - Returns (-1) No pattern found for current index or parameter error others the pattern position in rx buffer. - - esp_err_t uart_pattern_queue_reset(uart_port_t uart_num, int queue_length) Allocate a new memory with the given length to save record the detected pattern position in rx buffer. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1). queue_length -- Max queue length for the detected pattern. If the queue length is not large enough, some pattern positions might be lost. Set this value to the maximum number of patterns that could be saved in data buffer at the same time. - - Returns ESP_ERR_NO_MEM No enough memory ESP_ERR_INVALID_STATE Driver not installed ESP_FAIL Parameter error ESP_OK Success - - esp_err_t uart_set_mode(uart_port_t uart_num, uart_mode_t mode) UART set communication mode. Note This function must be executed after uart_driver_install(), when the driver object is initialized. - Parameters uart_num -- Uart number to configure, the max port number is (UART_NUM_MAX -1). mode -- UART UART mode to set - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t uart_set_rx_full_threshold(uart_port_t uart_num, int threshold) Set uart threshold value for RX fifo full. Note If application is using higher baudrate and it is observed that bytes in hardware RX fifo are overwritten then this threshold can be reduced - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1) threshold -- Threshold value above which RX fifo full interrupt is generated - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Driver is not installed - - esp_err_t uart_set_tx_empty_threshold(uart_port_t uart_num, int threshold) Set uart threshold values for TX fifo empty. - Parameters uart_num -- UART port number, the max port number is (UART_NUM_MAX -1) threshold -- Threshold value below which TX fifo empty interrupt is generated - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Driver is not installed - - esp_err_t uart_set_rx_timeout(uart_port_t uart_num, const uint8_t tout_thresh) UART set threshold timeout for TOUT feature. - Parameters uart_num -- Uart number to configure, the max port number is (UART_NUM_MAX -1). tout_thresh -- This parameter defines timeout threshold in uart symbol periods. The maximum value of threshold is 126. tout_thresh = 1, defines TOUT interrupt timeout equal to transmission time of one symbol (~11 bit) on current baudrate. If the time is expired the UART_RXFIFO_TOUT_INT interrupt is triggered. If tout_thresh == 0, the TOUT feature is disabled. - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_ERR_INVALID_STATE Driver is not installed - - esp_err_t uart_get_collision_flag(uart_port_t uart_num, bool *collision_flag) Returns collision detection flag for RS485 mode Function returns the collision detection flag into variable pointed by collision_flag. *collision_flag = true, if collision detected else it is equal to false. This function should be executed when actual transmission is completed (after uart_write_bytes()). - Parameters uart_num -- Uart number to configure the max port number is (UART_NUM_MAX -1). collision_flag -- Pointer to variable of type bool to return collision flag. - - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - - esp_err_t uart_set_wakeup_threshold(uart_port_t uart_num, int wakeup_threshold) Set the number of RX pin signal edges for light sleep wakeup. UART can be used to wake up the system from light sleep. This feature works by counting the number of positive edges on RX pin and comparing the count to the threshold. When the count exceeds the threshold, system is woken up from light sleep. This function allows setting the threshold value. Stop bit and parity bits (if enabled) also contribute to the number of edges. For example, letter 'a' with ASCII code 97 is encoded as 0100001101 on the wire (with 8n1 configuration), start and stop bits included. This sequence has 3 positive edges (transitions from 0 to 1). Therefore, to wake up the system when 'a' is sent, set wakeup_threshold=3. The character that triggers wakeup is not received by UART (i.e. it can not be obtained from UART FIFO). Depending on the baud rate, a few characters after that will also not be received. Note that when the chip enters and exits light sleep mode, APB frequency will be changing. To ensure that UART has correct Baud rate all the time, it is necessary to select a source clock which has a fixed frequency and remains active during sleep. For the supported clock sources of the chips, please refer to uart_sclk_tor soc_periph_uart_clk_src_legacy_t Note in ESP32, the wakeup signal can only be input via IO_MUX (i.e. GPIO3 should be configured as function_1 to wake up UART0, GPIO9 should be configured as function_5 to wake up UART1), UART2 does not support light sleep wakeup feature. - Parameters uart_num -- UART number, the max port number is (UART_NUM_MAX -1). wakeup_threshold -- number of RX edges for light sleep wakeup, value is 3 .. 0x3ff. - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if uart_num is incorrect or wakeup_threshold is outside of [3, 0x3ff] range. - - esp_err_t uart_get_wakeup_threshold(uart_port_t uart_num, int *out_wakeup_threshold) Get the number of RX pin signal edges for light sleep wakeup. See description of uart_set_wakeup_threshold for the explanation of UART wakeup feature. - Parameters uart_num -- UART number, the max port number is (UART_NUM_MAX -1). out_wakeup_threshold -- [out] output, set to the current value of wakeup threshold for the given UART. - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if out_wakeup_threshold is NULL - - esp_err_t uart_wait_tx_idle_polling(uart_port_t uart_num) Wait until UART tx memory empty and the last char send ok (polling mode). - Returns ESP_OK on success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Driver not installed - - Parameters uart_num -- UART number - esp_err_t uart_set_loop_back(uart_port_t uart_num, bool loop_back_en) Configure TX signal loop back to RX module, just for the test usage. - Returns ESP_OK on success ESP_ERR_INVALID_ARG Parameter error ESP_FAIL Driver not installed - - Parameters uart_num -- UART number loop_back_en -- Set ture to enable the loop back function, else set it false. - - void uart_set_always_rx_timeout(uart_port_t uart_num, bool always_rx_timeout_en) Configure behavior of UART RX timeout interrupt. When always_rx_timeout is true, timeout interrupt is triggered even if FIFO is full. This function can cause extra timeout interrupts triggered only to send the timeout event. Call this function only if you want to ensure timeout interrupt will always happen after a byte stream. - Parameters uart_num -- UART number always_rx_timeout_en -- Set to false enable the default behavior of timeout interrupt, set it to true to always trigger timeout interrupt. - Structures - struct uart_config_t UART configuration parameters for uart_param_config function. Public Members - int baud_rate UART baud rate - uart_word_length_t data_bits UART byte size - uart_parity_t parity UART parity mode - uart_stop_bits_t stop_bits UART stop bits - uart_hw_flowcontrol_t flow_ctrl UART HW flow control mode (cts/rts) - uint8_t rx_flow_ctrl_thresh UART HW RTS threshold - uart_sclk_t source_clk UART source clock selection - int baud_rate - struct uart_intr_config_t UART interrupt configuration parameters for uart_intr_config function. Public Members - uint32_t intr_enable_mask UART interrupt enable mask, choose from UART_XXXX_INT_ENA_M under UART_INT_ENA_REG(i), connect with bit-or operator - uint8_t rx_timeout_thresh UART timeout interrupt threshold (unit: time of sending one byte) - uint8_t txfifo_empty_intr_thresh UART TX empty interrupt threshold. - uint8_t rxfifo_full_thresh UART RX full interrupt threshold. - uint32_t intr_enable_mask - struct uart_event_t Event structure used in UART event queue. Public Members - uart_event_type_t type UART event type - size_t size UART data size for UART_DATA event - bool timeout_flag UART data read timeout flag for UART_DATA event (no new data received during configured RX TOUT) If the event is caused by FIFO-full interrupt, then there will be no event with the timeout flag before the next byte coming. - uart_event_type_t type Macros - UART_PIN_NO_CHANGE - UART_FIFO_LEN Length of the HP UART HW FIFO. - UART_HW_FIFO_LEN(uart_num) Length of the UART HW FIFO. - UART_BITRATE_MAX Maximum configurable bitrate. Type Definitions - typedef intr_handle_t uart_isr_handle_t Enumerations - enum uart_event_type_t UART event types used in the ring buffer. Values: - enumerator UART_DATA UART data event - enumerator UART_BREAK UART break event - enumerator UART_BUFFER_FULL UART RX buffer full event - enumerator UART_FIFO_OVF UART FIFO overflow event - enumerator UART_FRAME_ERR UART RX frame error event - enumerator UART_PARITY_ERR UART RX parity event - enumerator UART_DATA_BREAK UART TX data and break event - enumerator UART_PATTERN_DET UART pattern detected - enumerator UART_EVENT_MAX UART event max index - enumerator UART_DATA Header File This header file can be included with: #include "hal/uart_types.h" Structures - struct uart_at_cmd_t UART AT cmd char configuration parameters Note that this function may different on different chip. Please refer to the TRM at confirguration. Public Members - uint8_t cmd_char UART AT cmd char - uint8_t char_num AT cmd char repeat number - uint32_t gap_tout gap time(in baud-rate) between AT cmd char - uint32_t pre_idle the idle time(in baud-rate) between the non AT char and first AT char - uint32_t post_idle the idle time(in baud-rate) between the last AT char and the none AT char - uint8_t cmd_char - struct uart_sw_flowctrl_t UART software flow control configuration parameters. Public Members - uint8_t xon_char Xon flow control char - uint8_t xoff_char Xoff flow control char - uint8_t xon_thrd If the software flow control is enabled and the data amount in rxfifo is less than xon_thrd, an xon_char will be sent - uint8_t xoff_thrd If the software flow control is enabled and the data amount in rxfifo is more than xoff_thrd, an xoff_char will be sent - uint8_t xon_char Type Definitions - typedef soc_periph_uart_clk_src_legacy_t uart_sclk_t UART source clock. Enumerations - enum uart_port_t UART port number, can be UART_NUM_0 ~ (UART_NUM_MAX -1). Values: - enumerator UART_NUM_0 UART port 0 - enumerator UART_NUM_1 UART port 1 - enumerator UART_NUM_2 UART port 2 - enumerator UART_NUM_MAX UART port max - enumerator UART_NUM_0 - enum uart_mode_t UART mode selection. Values: - enumerator UART_MODE_UART mode: regular UART mode - enumerator UART_MODE_RS485_HALF_DUPLEX mode: half duplex RS485 UART mode control by RTS pin - enumerator UART_MODE_IRDA mode: IRDA UART mode - enumerator UART_MODE_RS485_COLLISION_DETECT mode: RS485 collision detection UART mode (used for test purposes) - enumerator UART_MODE_RS485_APP_CTRL mode: application control RS485 UART mode (used for test purposes) - enumerator UART_MODE_UART - enum uart_word_length_t UART word length constants. Values: - enumerator UART_DATA_5_BITS word length: 5bits - enumerator UART_DATA_6_BITS word length: 6bits - enumerator UART_DATA_7_BITS word length: 7bits - enumerator UART_DATA_8_BITS word length: 8bits - enumerator UART_DATA_BITS_MAX - enumerator UART_DATA_5_BITS - enum uart_stop_bits_t UART stop bits number. Values: - enumerator UART_STOP_BITS_1 stop bit: 1bit - enumerator UART_STOP_BITS_1_5 stop bit: 1.5bits - enumerator UART_STOP_BITS_2 stop bit: 2bits - enumerator UART_STOP_BITS_MAX - enumerator UART_STOP_BITS_1 - enum uart_parity_t UART parity constants. Values: - enumerator UART_PARITY_DISABLE Disable UART parity - enumerator UART_PARITY_EVEN Enable UART even parity - enumerator UART_PARITY_ODD Enable UART odd parity - enumerator UART_PARITY_DISABLE - enum uart_hw_flowcontrol_t UART hardware flow control modes. Values: - enumerator UART_HW_FLOWCTRL_DISABLE disable hardware flow control - enumerator UART_HW_FLOWCTRL_RTS enable RX hardware flow control (rts) - enumerator UART_HW_FLOWCTRL_CTS enable TX hardware flow control (cts) - enumerator UART_HW_FLOWCTRL_CTS_RTS enable hardware flow control - enumerator UART_HW_FLOWCTRL_MAX - enumerator UART_HW_FLOWCTRL_DISABLE - enum uart_signal_inv_t UART signal bit map. Values: - enumerator UART_SIGNAL_INV_DISABLE Disable UART signal inverse - enumerator UART_SIGNAL_IRDA_TX_INV inverse the UART irda_tx signal - enumerator UART_SIGNAL_IRDA_RX_INV inverse the UART irda_rx signal - enumerator UART_SIGNAL_RXD_INV inverse the UART rxd signal - enumerator UART_SIGNAL_CTS_INV inverse the UART cts signal - enumerator UART_SIGNAL_DSR_INV inverse the UART dsr signal - enumerator UART_SIGNAL_TXD_INV inverse the UART txd signal - enumerator UART_SIGNAL_RTS_INV inverse the UART rts signal - enumerator UART_SIGNAL_DTR_INV inverse the UART dtr signal - enumerator UART_SIGNAL_INV_DISABLE GPIO Lookup Macros The UART peripherals have dedicated IO_MUX pins to which they are connected directly. However, signals can also be routed to other pins using the less direct GPIO matrix. To use direct routes, you need to know which pin is a dedicated IO_MUX pin for a UART channel. GPIO Lookup Macros simplify the process of finding and assigning IO_MUX pins. You choose a macro based on either the IO_MUX pin number, or a required UART channel name, and the macro returns the matching counterpart for you. See some examples below. Note These macros are useful if you need very high UART baud rates (over 40 MHz), which means you will have to use IO_MUX pins only. In other cases, these macros can be ignored, and you can use the GPIO Matrix as it allows you to configure any GPIO pin for any UART function. UART_NUM_2_TXD_DIRECT_GPIO_NUMreturns the IO_MUX pin number of UART channel 2 TXD pin (pin 17) UART_GPIO19_DIRECT_CHANNELreturns the UART number of GPIO 19 when connected to the UART peripheral via IO_MUX (this is UART_NUM_0) UART_CTS_GPIO19_DIRECT_CHANNELreturns the UART number of GPIO 19 when used as the UART CTS pin via IO_MUX (this is UART_NUM_0). It is similar to the above macro but specifies the pin function which is also part of the IO_MUX assignment. Header File This header file can be included with: #include "soc/uart_channel.h" Macros - UART_GPIO1_DIRECT_CHANNEL - UART_NUM_0_TXD_DIRECT_GPIO_NUM - UART_GPIO3_DIRECT_CHANNEL - UART_NUM_0_RXD_DIRECT_GPIO_NUM - UART_GPIO19_DIRECT_CHANNEL - UART_NUM_0_CTS_DIRECT_GPIO_NUM - UART_GPIO22_DIRECT_CHANNEL - UART_NUM_0_RTS_DIRECT_GPIO_NUM - UART_TXD_GPIO1_DIRECT_CHANNEL - UART_RXD_GPIO3_DIRECT_CHANNEL - UART_CTS_GPIO19_DIRECT_CHANNEL - UART_RTS_GPIO22_DIRECT_CHANNEL - UART_GPIO10_DIRECT_CHANNEL - UART_NUM_1_TXD_DIRECT_GPIO_NUM - UART_GPIO9_DIRECT_CHANNEL - UART_NUM_1_RXD_DIRECT_GPIO_NUM - UART_GPIO6_DIRECT_CHANNEL - UART_NUM_1_CTS_DIRECT_GPIO_NUM - UART_GPIO11_DIRECT_CHANNEL - UART_NUM_1_RTS_DIRECT_GPIO_NUM - UART_TXD_GPIO10_DIRECT_CHANNEL - UART_RXD_GPIO9_DIRECT_CHANNEL - UART_CTS_GPIO6_DIRECT_CHANNEL - UART_RTS_GPIO11_DIRECT_CHANNEL - UART_GPIO17_DIRECT_CHANNEL - UART_NUM_2_TXD_DIRECT_GPIO_NUM - UART_GPIO16_DIRECT_CHANNEL - UART_NUM_2_RXD_DIRECT_GPIO_NUM - UART_GPIO8_DIRECT_CHANNEL - UART_NUM_2_CTS_DIRECT_GPIO_NUM - UART_GPIO7_DIRECT_CHANNEL - UART_NUM_2_RTS_DIRECT_GPIO_NUM - UART_TXD_GPIO17_DIRECT_CHANNEL - UART_RXD_GPIO16_DIRECT_CHANNEL - UART_CTS_GPIO8_DIRECT_CHANNEL - UART_RTS_GPIO7_DIRECT_CHANNEL
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/peripherals/uart.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Project Configuration
null
espressif.com
2016-01-01
ec57685903926148
null
null
Project Configuration Introduction The esp-idf-kconfig package that ESP-IDF uses is based on kconfiglib, which is a Python extension to the Kconfig system. Kconfig provides a compile-time project configuration mechanism and offers configuration options of several types (e.g., integers, strings, and boolens). Kconfig files specify dependencies between options, default values of options, the way options are grouped together, etc. For the full list of available features, please see Kconfig and kconfiglib extentions. Using sdkconfig.defaults  sdkconfig.defaults  In some cases, for example, when the sdkconfig file is under revision control, it may be inconvenient for the build system to change the sdkconfig file. The build system offers a solution to prevent it from happening, which is to create the sdkconfig.defaults file. This file is never touched by the build system, and can be created manually or automatically. It contains all the options which matter to the given application and are different from the default ones. The format is the same as that of the sdkconfig file. sdkconfig.defaults can be created manually when one remembers all the changed configuration, or it can be generated automatically by running the idf.py save-defconfig command. Once sdkconfig.defaults is created, sdkconfig can be deleted or added to the ignore list of the revision control system (e.g., the .gitignore file for git ). Project build targets will automatically create the sdkconfig file, populate it with the settings from the sdkconfig.defaults file, and configure the rest of the settings to their default values. Note that during the build process, settings from sdkconfig.defaults will not override those already in sdkconfig . For more information, see Custom Sdkconfig Defaults. Kconfig Format Rules Format rules for Kconfig files are as follows: Option names in any menus should have consistent prefixes. The prefix currently should have at least 3 characters. The unit of indentation should be 4 spaces. All sub-items belonging to a parent item are indented by one level deeper. For example, menu is indented by 0 spaces, config menu by 4 spaces, help in config by 8 spaces, and the text under help by 12 spaces. No trailing spaces are allowed at the end of the lines. The maximum length of options is 50 characters. The maximum length of lines is 120 characters. Note The help section of each config in the menu is treated as reStructuredText to generate the reference documentation for each option. Format Checker kconfcheck tool in esp-idf-kconfig package is provided for checking Kconfig files against the above format rules. The checker checks all Kconfig and Kconfig.projbuild files given as arguments, and generates a new file with suffix .new with some suggestions about how to fix issues (if there are any). Please note that the checker cannot correct all format issues and the responsibility of the developer is to final check and make corrections in order to pass the tests. For example, indentations will be corrected if there is not any misleading formatting, but it cannot come up with a common prefix for options inside a menu. The esp-idf-kconfig package is available in ESP-IDF environments, where the checker tool can be invoked by running command python -m kconfcheck <path_to_kconfig_file> . For more information, please refer to esp-idf-kconfig package documentation. Backward Compatibility of Kconfig Options The standard Kconfig tools ignore unknown options in sdkconfig . So if a developer has custom settings for options which are renamed in newer ESP-IDF releases, then the given setting for the option would be silently ignored. Therefore, several features have been adopted to avoid this: kconfgen is used by the tool chain to pre-process sdkconfig files before anything else. For example, menuconfig would read them, so the settings for old options is kept and not ignored. kconfgen recursively finds all sdkconfig.rename files in ESP-IDF directory which contain old and new Kconfig option names. Old options are replaced by new ones in the sdkconfig file. Renames that should only appear for a single target can be placed in a target-specific rename file sdkconfig.rename.TARGET , where TARGET is the target name, e.g., sdkconfig.rename.esp32s2 . kconfgen post-processes sdkconfig files and generates all build outputs ( sdkconfig.h , sdkconfig.cmake , and auto.conf ) by adding a list of compatibility statements, i.e., the values of old options are set for new options after modification. If users still use old options in their code, this will prevent it from breaking. Deprecated options and their replacements are automatically generated by kconfgen . Configuration Options Reference Subsequent sections contain the list of available ESP-IDF options automatically generated from Kconfig files. Note that due to dependencies between options, some options listed here may not be visible by default in menuconfig . By convention, all option names are upper-case letters with underscores. When Kconfig generates sdkconfig and sdkconfig.h files, option names are prefixed with CONFIG_ . So if an option ENABLE_FOO is defined in a Kconfig file and selected in menuconfig , then the sdkconfig and sdkconfig.h files will have CONFIG_ENABLE_FOO defined. In the following sections, option names are also prefixed with CONFIG_ , same as in the source code. Build type Contains: CONFIG_APP_BUILD_TYPE Application build type Found in: Build type Select the way the application is built. By default, the application is built as a binary file in a format compatible with the ESP-IDF bootloader. In addition to this application, 2nd stage bootloader is also built. Application and bootloader binaries can be written into flash and loaded/executed from there. Another option, useful for only very small and limited applications, is to only link the .elf file of the application, such that it can be loaded directly into RAM over JTAG or UART. Note that since IRAM and DRAM sizes are very limited, it is not possible to build any complex application this way. However for some kinds of testing and debugging, this option may provide faster iterations, since the application does not need to be written into flash. Note: when APP_BUILD_TYPE_RAM is selected and loaded with JTAG, ESP-IDF does not contain all the startup code required to initialize the CPUs and ROM memory (data/bss). Therefore it is necessary to execute a bit of ROM code prior to executing the application. A gdbinit file may look as follows (for ESP32): # Connect to a running instance of OpenOCD target remote :3333 # Reset and halt the target mon reset halt # Run to a specific point in ROM code, # where most of initialization is complete. thb *0x40007d54 c # Load the application into RAM load # Run till app_main tb app_main c Execute this gdbinit file as follows: xtensa-esp32-elf-gdb build/app-name.elf -x gdbinit Example gdbinit files for other targets can be found in tools/test_apps/system/gdb_loadable_elf/ When loading the BIN with UART, the ROM will jump to ram and run the app after finishing the ROM startup code, so there's no additional startup initialization required. You can use the load_ram in esptool.py to load the generated .bin file into ram and execute. Example: esptool.py --chip {chip} -p {port} -b {baud} --no-stub load_ram {app.bin} Recommended sdkconfig.defaults for building loadable ELF files is as follows. CONFIG_APP_BUILD_TYPE_RAM is required, other options help reduce application memory footprint. CONFIG_APP_BUILD_TYPE_RAM=y CONFIG_VFS_SUPPORT_TERMIOS= CONFIG_NEWLIB_NANO_FORMAT=y CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT=y CONFIG_ESP_DEBUG_STUBS_ENABLE= CONFIG_ESP_ERR_TO_NAME_LOOKUP= Available options: Default (binary application + 2nd stage bootloader) (CONFIG_APP_BUILD_TYPE_APP_2NDBOOT) Build app runs entirely in RAM (EXPERIMENTAL) (CONFIG_APP_BUILD_TYPE_RAM) CONFIG_APP_BUILD_TYPE_PURE_RAM_APP Build app without SPI_FLASH/PSRAM support (saves ram) Found in: Build type If this option is enabled, external memory and related peripherals, such as Cache, MMU, Flash and PSRAM, won't be initialized. Corresponding drivers won't be introduced either. Components that depend on the spi_flash component will also be unavailable, such as app_update, etc. When this option is enabled, about 26KB of RAM space can be saved. CONFIG_APP_REPRODUCIBLE_BUILD Enable reproducible build Found in: Build type If enabled, all date, time, and path information would be eliminated. A .gdbinit file would be create automatically. (or will be append if you have one already) Default value: No (disabled) CONFIG_APP_NO_BLOBS No Binary Blobs Found in: Build type If enabled, this disables the linking of binary libraries in the application build. Note that after enabling this Wi-Fi/Bluetooth will not work. Default value: No (disabled) CONFIG_APP_COMPATIBLE_PRE_V2_1_BOOTLOADERS App compatible with bootloaders before ESP-IDF v2.1 Found in: Build type Bootloaders before ESP-IDF v2.1 did less initialisation of the system clock. This setting needs to be enabled to build an app which can be booted by these older bootloaders. If this setting is enabled, the app can be booted by any bootloader from IDF v1.0 up to the current version. If this setting is disabled, the app can only be booted by bootloaders from IDF v2.1 or newer. Enabling this setting adds approximately 1KB to the app's IRAM usage. Default value: No (disabled) CONFIG_APP_COMPATIBLE_PRE_V3_1_BOOTLOADERS App compatible with bootloader and partition table before ESP-IDF v3.1 Found in: Build type Partition tables before ESP-IDF V3.1 do not contain an MD5 checksum field, and the bootloader before ESP-IDF v3.1 cannot read a partition table that contains an MD5 checksum field. Enable this option only if your app needs to boot on a bootloader and/or partition table that was generated from a version *before* ESP-IDF v3.1. If this option and Flash Encryption are enabled at the same time, and any data partitions in the partition table are marked Encrypted, then the partition encrypted flag should be manually verified in the app before accessing the partition (see CVE-2021-27926). Default value: No (disabled) Bootloader config Contains: Bootloader manager Contains: CONFIG_BOOTLOADER_COMPILE_TIME_DATE Use time/date stamp for bootloader Found in: Bootloader config > Bootloader manager If set, then the bootloader will be built with the current time/date stamp. It is stored in the bootloader description structure. If not set, time/date stamp will be excluded from bootloader image. This can be useful for getting the same binary image files made from the same source, but at different times. CONFIG_BOOTLOADER_PROJECT_VER Project version Found in: Bootloader config > Bootloader manager Project version. It is placed in "version" field of the esp_bootloader_desc structure. The type of this field is "uint32_t". Range: from 0 to 4294967295 Default value: 1 CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION Bootloader optimization Level Found in: Bootloader config This option sets compiler optimization level (gcc -O argument) for the bootloader. The default "Size" setting will add the -0s flag to CFLAGS. The "Debug" setting will add the -Og flag to CFLAGS. The "Performance" setting will add the -O2 flag to CFLAGS. Note that custom optimization levels may be unsupported. Available options: Size (-Os) (CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE) Debug (-Og) (CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG) Optimize for performance (-O2) (CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_PERF) Debug without optimization (-O0) (Deprecated, will be removed in IDF v6.0) (CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_NONE) CONFIG_BOOTLOADER_LOG_LEVEL Bootloader log verbosity Found in: Bootloader config Specify how much output to see in bootloader logs. Available options: No output (CONFIG_BOOTLOADER_LOG_LEVEL_NONE) Error (CONFIG_BOOTLOADER_LOG_LEVEL_ERROR) Warning (CONFIG_BOOTLOADER_LOG_LEVEL_WARN) Info (CONFIG_BOOTLOADER_LOG_LEVEL_INFO) Debug (CONFIG_BOOTLOADER_LOG_LEVEL_DEBUG) Verbose (CONFIG_BOOTLOADER_LOG_LEVEL_VERBOSE) Serial Flash Configurations Contains: CONFIG_BOOTLOADER_SPI_CUSTOM_WP_PIN Use custom SPI Flash WP Pin when flash pins set in eFuse (read help) Found in: Bootloader config > Serial Flash Configurations This setting is only used if the SPI flash pins have been overridden by setting the eFuses SPI_PAD_CONFIG_xxx, and the SPI flash mode is QIO or QOUT. When this is the case, the eFuse config only defines 3 of the 4 Quad I/O data pins. The WP pin (aka ESP32 pin "SD_DATA_3" or SPI flash pin "IO2") is not specified in eFuse. The same pin is also used for external SPIRAM if it is enabled. If this config item is set to N (default), the correct WP pin will be automatically used for any Espressif chip or module with integrated flash. If a custom setting is needed, set this config item to Y and specify the GPIO number connected to the WP. Default value: No (disabled) if CONFIG_ESPTOOLPY_FLASHMODE_QIO || CONFIG_ESPTOOLPY_FLASHMODE_QOUT CONFIG_BOOTLOADER_SPI_WP_PIN Custom SPI Flash WP Pin Found in: Bootloader config > Serial Flash Configurations The option "Use custom SPI Flash WP Pin" must be set or this value is ignored If burning a customized set of SPI flash pins in eFuse and using QIO or QOUT mode for flash, set this value to the GPIO number of the SPI flash WP pin. Range: from 0 to 33 if CONFIG_ESPTOOLPY_FLASHMODE_QIO || CONFIG_ESPTOOLPY_FLASHMODE_QOUT Default value: CONFIG_BOOTLOADER_FLASH_DC_AWARE Allow app adjust Dummy Cycle bits in SPI Flash for higher frequency (READ HELP FIRST) Found in: Bootloader config > Serial Flash Configurations This will force 2nd bootloader to be loaded by DOUT mode, and will restore Dummy Cycle setting by resetting the Flash CONFIG_BOOTLOADER_FLASH_XMC_SUPPORT Enable the support for flash chips of XMC (READ DOCS FIRST) Found in: Bootloader config > Serial Flash Configurations Perform the startup flow recommended by XMC. Please consult XMC for the details of this flow. XMC chips will be forbidden to be used, when this option is disabled. DON'T DISABLE THIS UNLESS YOU KNOW WHAT YOU ARE DOING. comment "Features below require specific hardware (READ DOCS FIRST!)" Default value: Yes (enabled) CONFIG_BOOTLOADER_VDDSDIO_BOOST VDDSDIO LDO voltage Found in: Bootloader config If this option is enabled, and VDDSDIO LDO is set to 1.8V (using eFuse or MTDI bootstrapping pin), bootloader will change LDO settings to output 1.9V instead. This helps prevent flash chip from browning out during flash programming operations. This option has no effect if VDDSDIO is set to 3.3V, or if the internal VDDSDIO regulator is disabled via eFuse. Available options: 1.8V (CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_8V) 1.9V (CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_9V) CONFIG_BOOTLOADER_FACTORY_RESET GPIO triggers factory reset Found in: Bootloader config Allows to reset the device to factory settings: - clear one or more data partitions; - boot from "factory" partition. The factory reset will occur if there is a GPIO input held at the configured level while device starts up. See settings below. Default value: No (disabled) CONFIG_BOOTLOADER_NUM_PIN_FACTORY_RESET Number of the GPIO input for factory reset Found in: Bootloader config > CONFIG_BOOTLOADER_FACTORY_RESET The selected GPIO will be configured as an input with internal pull-up enabled (note that on some SoCs. not all pins have an internal pull-up, consult the hardware datasheet for details.) To trigger a factory reset, this GPIO must be held high or low (as configured) on startup. Range: from 0 to 39 if CONFIG_BOOTLOADER_FACTORY_RESET Default value: CONFIG_BOOTLOADER_FACTORY_RESET_PIN_LEVEL Factory reset GPIO level Found in: Bootloader config > CONFIG_BOOTLOADER_FACTORY_RESET Pin level for factory reset, can be triggered on low or high. Available options: Reset on GPIO low (CONFIG_BOOTLOADER_FACTORY_RESET_PIN_LOW) Reset on GPIO high (CONFIG_BOOTLOADER_FACTORY_RESET_PIN_HIGH) CONFIG_BOOTLOADER_OTA_DATA_ERASE Clear OTA data on factory reset (select factory partition) Found in: Bootloader config > CONFIG_BOOTLOADER_FACTORY_RESET The device will boot from "factory" partition (or OTA slot 0 if no factory partition is present) after a factory reset. CONFIG_BOOTLOADER_DATA_FACTORY_RESET Comma-separated names of partitions to clear on factory reset Found in: Bootloader config > CONFIG_BOOTLOADER_FACTORY_RESET Allows customers to select which data partitions will be erased while factory reset. Specify the names of partitions as a comma-delimited with optional spaces for readability. (Like this: "nvs, phy_init, ...") Make sure that the name specified in the partition table and here are the same. Partitions of type "app" cannot be specified here. Default value: "nvs" if CONFIG_BOOTLOADER_FACTORY_RESET CONFIG_BOOTLOADER_APP_TEST GPIO triggers boot from test app partition Found in: Bootloader config Allows to run the test app from "TEST" partition. A boot from "test" partition will occur if there is a GPIO input pulled low while device starts up. See settings below. CONFIG_BOOTLOADER_NUM_PIN_APP_TEST Number of the GPIO input to boot TEST partition Found in: Bootloader config > CONFIG_BOOTLOADER_APP_TEST The selected GPIO will be configured as an input with internal pull-up enabled. To trigger a test app, this GPIO must be pulled low on reset. After the GPIO input is deactivated and the device reboots, the old application will boot. (factory or OTA[x]). Note that GPIO34-39 do not have an internal pullup and an external one must be provided. Range: from 0 to 39 if CONFIG_BOOTLOADER_APP_TEST Default value: CONFIG_BOOTLOADER_APP_TEST_PIN_LEVEL App test GPIO level Found in: Bootloader config > CONFIG_BOOTLOADER_APP_TEST Pin level for app test, can be triggered on low or high. Available options: Enter test app on GPIO low (CONFIG_BOOTLOADER_APP_TEST_PIN_LOW) Enter test app on GPIO high (CONFIG_BOOTLOADER_APP_TEST_PIN_HIGH) CONFIG_BOOTLOADER_HOLD_TIME_GPIO Hold time of GPIO for reset/test mode (seconds) Found in: Bootloader config The GPIO must be held low continuously for this period of time after reset before a factory reset or test partition boot (as applicable) is performed. Default value: CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE Enable protection for unmapped memory regions Found in: Bootloader config Protects the unmapped memory regions of the entire address space from unintended accesses. This will ensure that an exception will be triggered whenever the CPU performs a memory operation on unmapped regions of the address space. Default value: Yes (enabled) CONFIG_BOOTLOADER_WDT_ENABLE Use RTC watchdog in start code Found in: Bootloader config Tracks the execution time of startup code. If the execution time is exceeded, the RTC_WDT will restart system. It is also useful to prevent a lock up in start code caused by an unstable power source. NOTE: Tracks the execution time starts from the bootloader code - re-set timeout, while selecting the source for slow_clk - and ends calling app_main. Re-set timeout is needed due to WDT uses a SLOW_CLK clock source. After changing a frequency slow_clk a time of WDT needs to re-set for new frequency. slow_clk depends on RTC_CLK_SRC (INTERNAL_RC or EXTERNAL_CRYSTAL). Default value: Yes (enabled) CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE Allows RTC watchdog disable in user code Found in: Bootloader config > CONFIG_BOOTLOADER_WDT_ENABLE If this option is set, the ESP-IDF app must explicitly reset, feed, or disable the rtc_wdt in the app's own code. If this option is not set (default), then rtc_wdt will be disabled by ESP-IDF before calling the app_main() function. Use function rtc_wdt_feed() for resetting counter of rtc_wdt. Use function rtc_wdt_disable() for disabling rtc_wdt. Default value: No (disabled) CONFIG_BOOTLOADER_WDT_TIME_MS Timeout for RTC watchdog (ms) Found in: Bootloader config > CONFIG_BOOTLOADER_WDT_ENABLE Verify that this parameter is correct and more then the execution time. Pay attention to options such as reset to factory, trigger test partition and encryption on boot - these options can increase the execution time. Note: RTC_WDT will reset while encryption operations will be performed. Range: from 0 to 120000 Default value: 9000 CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE Enable app rollback support Found in: Bootloader config After updating the app, the bootloader runs a new app with the "ESP_OTA_IMG_PENDING_VERIFY" state set. This state prevents the re-run of this app. After the first boot of the new app in the user code, the function should be called to confirm the operability of the app or vice versa about its non-operability. If the app is working, then it is marked as valid. Otherwise, it is marked as not valid and rolls back to the previous working app. A reboot is performed, and the app is booted before the software update. Note: If during the first boot a new app the power goes out or the WDT works, then roll back will happen. Rollback is possible only between the apps with the same security versions. Default value: No (disabled) CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK Enable app anti-rollback support Found in: Bootloader config > CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE This option prevents rollback to previous firmware/application image with lower security version. Default value: No (disabled) if CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE CONFIG_BOOTLOADER_APP_SECURE_VERSION eFuse secure version of app Found in: Bootloader config > CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE > CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK The secure version is the sequence number stored in the header of each firmware. The security version is set in the bootloader, version is recorded in the eFuse field as the number of set ones. The allocated number of bits in the efuse field for storing the security version is limited (see BOOTLOADER_APP_SEC_VER_SIZE_EFUSE_FIELD option). Bootloader: When bootloader selects an app to boot, an app is selected that has a security version greater or equal that recorded in eFuse field. The app is booted with a higher (or equal) secure version. The security version is worth increasing if in previous versions there is a significant vulnerability and their use is not acceptable. Your partition table should has a scheme with ota_0 + ota_1 (without factory). Default value: CONFIG_BOOTLOADER_APP_SEC_VER_SIZE_EFUSE_FIELD Size of the efuse secure version field Found in: Bootloader config > CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE > CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK The size of the efuse secure version field. Its length is limited to 32 bits for ESP32 and 16 bits for ESP32-S2. This determines how many times the security version can be increased. Range: from 1 to 32 if CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK from 1 to 16 if CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK Default value: CONFIG_BOOTLOADER_EFUSE_SECURE_VERSION_EMULATE Emulate operations with efuse secure version(only test) Found in: Bootloader config > CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE > CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK This option allows to emulate read/write operations with all eFuses and efuse secure version. It allows to test anti-rollback implemention without permanent write eFuse bits. There should be an entry in partition table with following details: emul_efuse, data, efuse, , 0x2000. This option enables: EFUSE_VIRTUAL and EFUSE_VIRTUAL_KEEP_IN_FLASH. Default value: No (disabled) if CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP Skip image validation when exiting deep sleep Found in: Bootloader config This option disables the normal validation of an image coming out of deep sleep (checksums, SHA256, and signature). This is a trade-off between wakeup performance from deep sleep, and image integrity checks. Only enable this if you know what you are doing. It should not be used in conjunction with using deep_sleep() entry and changing the active OTA partition as this would skip the validation upon first load of the new OTA partition. It is possible to enable this option with Secure Boot if "allow insecure options" is enabled, however it's strongly recommended to NOT enable it as it may allow a Secure Boot bypass. Default value: No (disabled) if CONFIG_SECURE_BOOT && CONFIG_SECURE_BOOT_INSECURE CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON Skip image validation from power on reset (READ HELP FIRST) Found in: Bootloader config Some applications need to boot very quickly from power on. By default, the entire app binary is read from flash and verified which takes up a significant portion of the boot time. Enabling this option will skip validation of the app when the SoC boots from power on. Note that in this case it's not possible for the bootloader to detect if an app image is corrupted in the flash, therefore it's not possible to safely fall back to a different app partition. Flash corruption of this kind is unlikely but can happen if there is a serious firmware bug or physical damage. Following other reset types, the bootloader will still validate the app image. This increases the chances that flash corruption resulting in a crash can be detected following soft reset, and the bootloader will fall back to a valid app image. To increase the chances of successfully recovering from a flash corruption event, keep the option BOOTLOADER_WDT_ENABLE enabled and consider also enabling BOOTLOADER_WDT_DISABLE_IN_USER_CODE - then manually disable the RTC Watchdog once the app is running. In addition, enable both the Task and Interrupt watchdog timers with reset options set. Default value: No (disabled) CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS Skip image validation always (READ HELP FIRST) Found in: Bootloader config Selecting this option prevents the bootloader from ever validating the app image before booting it. Any flash corruption of the selected app partition will make the entire SoC unbootable. Although flash corruption is a very rare case, it is not recommended to select this option. Consider selecting "Skip image validation from power on reset" instead. However, if boot time is the only important factor then it can be enabled. Default value: No (disabled) CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC Reserve RTC FAST memory for custom purposes Found in: Bootloader config This option allows the customer to place data in the RTC FAST memory, this area remains valid when rebooted, except for power loss. This memory is located at a fixed address and is available for both the bootloader and the application. (The application and bootoloader must be compiled with the same option). The RTC FAST memory has access only through PRO_CPU. Default value: No (disabled) CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC_IN_CRC Include custom memory in the CRC calculation Found in: Bootloader config > CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC This option allows the customer to use the legacy bootloader behavior when the RTC FAST memory CRC calculation takes place. When this option is enabled, the allocated user custom data will be taken into account in the CRC calculcation. This means that any change to the custom data would need a CRC update to prevent the bootloader from marking this data as corrupted. If this option is disabled, the custom data will not be taken into account when calculating the RTC FAST memory CRC. The user custom data can be changed freely, without the need to update the CRC. THIS OPTION MUST BE THE SAME FOR BOTH THE BOOTLOADER AND THE APPLICATION BUILDS. Default value: No (disabled) if CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC_SIZE Size in bytes for custom purposes Found in: Bootloader config > CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC This option reserves in RTC FAST memory the area for custom purposes. If you want to create your own bootloader and save more information in this area of memory, you can increase it. It must be a multiple of 4 bytes. This area (rtc_retain_mem_t) is reserved and has access from the bootloader and an application. Default value: Security features Contains: CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT Require signed app images Found in: Security features Require apps to be signed to verify their integrity. This option uses the same app signature scheme as hardware secure boot, but unlike hardware secure boot it does not prevent the bootloader from being physically updated. This means that the device can be secured against remote network access, but not physical access. Compared to using hardware Secure Boot this option is much simpler to implement. CONFIG_SECURE_SIGNED_APPS_SCHEME App Signing Scheme Found in: Security features Select the Secure App signing scheme. Depends on the Chip Revision. There are two secure boot versions: Secure boot V1 Legacy custom secure boot scheme. Supported in ESP32 SoC. Secure boot V2 RSA based secure boot scheme. Supported in ESP32-ECO3 (ESP32 Chip Revision 3 onwards), ESP32-S2, ESP32-C3, ESP32-S3 SoCs. ECDSA based secure boot scheme. Supported in ESP32-C2 SoC. Available options: ECDSA (CONFIG_SECURE_SIGNED_APPS_ECDSA_SCHEME) Embeds the ECDSA public key in the bootloader and signs the application with an ECDSA key. Refer to the documentation before enabling. RSA (CONFIG_SECURE_SIGNED_APPS_RSA_SCHEME) Appends the RSA-3072 based Signature block to the application. Refer to <Secure Boot Version 2 documentation link> before enabling. ECDSA (V2) (CONFIG_SECURE_SIGNED_APPS_ECDSA_V2_SCHEME) For Secure boot V2 (e.g., ESP32-C2 SoC), appends ECDSA based signature block to the application. Refer to documentation before enabling. CONFIG_SECURE_BOOT_ECDSA_KEY_LEN_SIZE ECDSA key size Found in: Security features Select the ECDSA key size. Two key sizes are supported 192 bit key using NISTP192 curve 256 bit key using NISTP256 curve (Recommended) The advantage of using 256 bit key is the extra randomness which makes it difficult to be bruteforced compared to 192 bit key. At present, both key sizes are practically implausible to bruteforce. Available options: Using ECC curve NISTP192 (CONFIG_SECURE_BOOT_ECDSA_KEY_LEN_192_BITS) Using ECC curve NISTP256 (Recommended) (CONFIG_SECURE_BOOT_ECDSA_KEY_LEN_256_BITS) CONFIG_SECURE_SIGNED_ON_BOOT_NO_SECURE_BOOT Bootloader verifies app signatures Found in: Security features If this option is set, the bootloader will be compiled with code to verify that an app is signed before booting it. If hardware secure boot is enabled, this option is always enabled and cannot be disabled. If hardware secure boot is not enabled, this option doesn't add significant security by itself so most users will want to leave it disabled. Default value: No (disabled) if CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT && CONFIG_SECURE_SIGNED_APPS_ECDSA_SCHEME CONFIG_SECURE_SIGNED_ON_UPDATE_NO_SECURE_BOOT Verify app signature on update Found in: Security features If this option is set, any OTA updated apps will have the signature verified before being considered valid. When enabled, the signature is automatically checked whenever the esp_ota_ops.h APIs are used for OTA updates, or esp_image_format.h APIs are used to verify apps. If hardware secure boot is enabled, this option is always enabled and cannot be disabled. If hardware secure boot is not enabled, this option still adds significant security against network-based attackers by preventing spoofing of OTA updates. Default value: Yes (enabled) if CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT CONFIG_SECURE_BOOT Enable hardware Secure Boot in bootloader (READ DOCS FIRST) Found in: Security features Build a bootloader which enables Secure Boot on first boot. Once enabled, Secure Boot will not boot a modified bootloader. The bootloader will only load a partition table or boot an app if the data has a verified digital signature. There are implications for reflashing updated apps once secure boot is enabled. When enabling secure boot, JTAG and ROM BASIC Interpreter are permanently disabled by default. Default value: No (disabled) CONFIG_SECURE_BOOT_VERSION Select secure boot version Found in: Security features > CONFIG_SECURE_BOOT Select the Secure Boot Version. Depends on the Chip Revision. Secure Boot V2 is the new RSA / ECDSA based secure boot scheme. RSA based scheme is supported in ESP32 (Revision 3 onwards), ESP32-S2, ESP32-C3 (ECO3), ESP32-S3. ECDSA based scheme is supported in ESP32-C2 SoC. Please note that, RSA or ECDSA secure boot is property of specific SoC based on its HW design, supported crypto accelerators, die-size, cost and similar parameters. Please note that RSA scheme has requirement for bigger key sizes but at the same time it is comparatively faster than ECDSA verification. Secure Boot V1 is the AES based (custom) secure boot scheme supported in ESP32 SoC. Available options: Enable Secure Boot version 1 (CONFIG_SECURE_BOOT_V1_ENABLED) Build a bootloader which enables secure boot version 1 on first boot. Refer to the Secure Boot section of the ESP-IDF Programmer's Guide for this version before enabling. Enable Secure Boot version 2 (CONFIG_SECURE_BOOT_V2_ENABLED) Build a bootloader which enables Secure Boot version 2 on first boot. Refer to Secure Boot V2 section of the ESP-IDF Programmer's Guide for this version before enabling. CONFIG_SECURE_BOOTLOADER_MODE Secure bootloader mode Found in: Security features Available options: One-time flash (CONFIG_SECURE_BOOTLOADER_ONE_TIME_FLASH) On first boot, the bootloader will generate a key which is not readable externally or by software. A digest is generated from the bootloader image itself. This digest will be verified on each subsequent boot. Enabling this option means that the bootloader cannot be changed after the first time it is booted. Reflashable (CONFIG_SECURE_BOOTLOADER_REFLASHABLE) Generate a reusable secure bootloader key, derived (via SHA-256) from the secure boot signing key. This allows the secure bootloader to be re-flashed by anyone with access to the secure boot signing key. This option is less secure than one-time flash, because a leak of the digest key from one device allows reflashing of any device that uses it. CONFIG_SECURE_BOOT_BUILD_SIGNED_BINARIES Sign binaries during build Found in: Security features Once secure boot or signed app requirement is enabled, app images are required to be signed. If enabled (default), these binary files are signed as part of the build process. The file named in "Secure boot private signing key" will be used to sign the image. If disabled, unsigned app/partition data will be built. They must be signed manually using espsecure.py. Version 1 to enable ECDSA Based Secure Boot and Version 2 to enable RSA based Secure Boot. (for example, on a remote signing server.) CONFIG_SECURE_BOOT_SIGNING_KEY Secure boot private signing key Found in: Security features > CONFIG_SECURE_BOOT_BUILD_SIGNED_BINARIES Path to the key file used to sign app images. Key file is an ECDSA private key (NIST256p curve) in PEM format for Secure Boot V1. Key file is an RSA private key in PEM format for Secure Boot V2. Path is evaluated relative to the project directory. You can generate a new signing key by running the following command: espsecure.py generate_signing_key secure_boot_signing_key.pem See the Secure Boot section of the ESP-IDF Programmer's Guide for this version for details. Default value: "secure_boot_signing_key.pem" if CONFIG_SECURE_BOOT_BUILD_SIGNED_BINARIES CONFIG_SECURE_BOOT_VERIFICATION_KEY Secure boot public signature verification key Found in: Security features Path to a public key file used to verify signed images. Secure Boot V1: This ECDSA public key is compiled into the bootloader and/or app, to verify app images. Key file is in raw binary format, and can be extracted from a PEM formatted private key using the espsecure.py extract_public_key command. Refer to the Secure Boot section of the ESP-IDF Programmer's Guide for this version before enabling. CONFIG_SECURE_BOOT_ENABLE_AGGRESSIVE_KEY_REVOKE Enable Aggressive key revoke strategy Found in: Security features If this option is set, ROM bootloader will revoke the public key digest burned in efuse block if it fails to verify the signature of software bootloader with it. Revocation of keys does not happen when enabling secure boot. Once secure boot is enabled, key revocation checks will be done on subsequent boot-up, while verifying the software bootloader This feature provides a strong resistance against physical attacks on the device. NOTE: Once a digest slot is revoked, it can never be used again to verify an image This can lead to permanent bricking of the device, in case all keys are revoked because of signature verification failure. Default value: No (disabled) if CONFIG_SECURE_BOOT && SOC_SUPPORT_SECURE_BOOT_REVOKE_KEY CONFIG_SECURE_BOOT_FLASH_BOOTLOADER_DEFAULT Flash bootloader along with other artifacts when using the default flash command Found in: Security features When Secure Boot V2 is enabled, by default the bootloader is not flashed along with other artifacts like the application and the partition table images, i.e. bootloader has to be seperately flashed using the command idf.py bootloader flash, whereas, the application and partition table can be flashed using the command idf.py flash itself. Enabling this option allows flashing the bootloader along with the other artifacts by invocation of the command idf.py flash. If this option is enabled make sure that even the bootloader is signed using the correct secure boot key, otherwise the bootloader signature verification would fail, as hash of the public key which is present in the bootloader signature would not match with the digest stored into the efuses and thus the device will not be able to boot up. Default value: No (disabled) if CONFIG_SECURE_BOOT_V2_ENABLED && CONFIG_SECURE_BOOT_BUILD_SIGNED_BINARIES CONFIG_SECURE_BOOTLOADER_KEY_ENCODING Hardware Key Encoding Found in: Security features In reflashable secure bootloader mode, a hardware key is derived from the signing key (with SHA-256) and can be written to eFuse with espefuse.py. Normally this is a 256-bit key, but if 3/4 Coding Scheme is used on the device then the eFuse key is truncated to 192 bits. This configuration item doesn't change any firmware code, it only changes the size of key binary which is generated at build time. Available options: No encoding (256 bit key) (CONFIG_SECURE_BOOTLOADER_KEY_ENCODING_256BIT) 3/4 encoding (192 bit key) (CONFIG_SECURE_BOOTLOADER_KEY_ENCODING_192BIT) CONFIG_SECURE_BOOT_INSECURE Allow potentially insecure options Found in: Security features You can disable some of the default protections offered by secure boot, in order to enable testing or a custom combination of security features. Only enable these options if you are very sure. Refer to the Secure Boot section of the ESP-IDF Programmer's Guide for this version before enabling. Default value: No (disabled) if CONFIG_SECURE_BOOT CONFIG_SECURE_FLASH_ENC_ENABLED Enable flash encryption on boot (READ DOCS FIRST) Found in: Security features If this option is set, flash contents will be encrypted by the bootloader on first boot. Note: After first boot, the system will be permanently encrypted. Re-flashing an encrypted system is complicated and not always possible. Read Flash Encryption before enabling. Default value: No (disabled) CONFIG_SECURE_FLASH_ENCRYPTION_KEYSIZE Size of generated XTS-AES key Found in: Security features > CONFIG_SECURE_FLASH_ENC_ENABLED Size of generated XTS-AES key. AES-128 uses a 256-bit key (32 bytes) derived from 128 bits (16 bytes) burned in half Efuse key block. Internally, it calculates SHA256(128 bits) AES-128 uses a 256-bit key (32 bytes) which occupies one Efuse key block. AES-256 uses a 512-bit key (64 bytes) which occupies two Efuse key blocks. This setting is ignored if either type of key is already burned to Efuse before the first boot. In this case, the pre-burned key is used and no new key is generated. Available options: AES-128 key derived from 128 bits (SHA256(128 bits)) (CONFIG_SECURE_FLASH_ENCRYPTION_AES128_DERIVED) AES-128 (256-bit key) (CONFIG_SECURE_FLASH_ENCRYPTION_AES128) AES-256 (512-bit key) (CONFIG_SECURE_FLASH_ENCRYPTION_AES256) CONFIG_SECURE_FLASH_ENCRYPTION_MODE Enable usage mode Found in: Security features > CONFIG_SECURE_FLASH_ENC_ENABLED By default Development mode is enabled which allows ROM download mode to perform flash encryption operations (plaintext is sent to the device, and it encrypts it internally and writes ciphertext to flash.) This mode is not secure, it's possible for an attacker to write their own chosen plaintext to flash. Release mode should always be selected for production or manufacturing. Once enabled it's no longer possible for the device in ROM Download Mode to use the flash encryption hardware. When EFUSE_VIRTUAL is enabled, SECURE_FLASH_ENCRYPTION_MODE_RELEASE is not available. For CI tests we use IDF_CI_BUILD to bypass it ("export IDF_CI_BUILD=1"). We do not recommend bypassing it for other purposes. Refer to the Flash Encryption section of the ESP-IDF Programmer's Guide for details. Available options: Development (NOT SECURE) (CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT) Release (CONFIG_SECURE_FLASH_ENCRYPTION_MODE_RELEASE) Potentially insecure options Contains: CONFIG_SECURE_BOOT_ALLOW_ROM_BASIC Leave ROM BASIC Interpreter available on reset Found in: Security features > Potentially insecure options By default, the BASIC ROM Console starts on reset if no valid bootloader is read from the flash. When either flash encryption or secure boot are enabled, the default is to disable this BASIC fallback mode permanently via eFuse. If this option is set, this eFuse is not burned and the BASIC ROM Console may remain accessible. Only set this option in testing environments. Default value: No (disabled) if CONFIG_SECURE_BOOT_INSECURE || CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT CONFIG_SECURE_BOOT_ALLOW_JTAG Allow JTAG Debugging Found in: Security features > Potentially insecure options If not set (default), the bootloader will permanently disable JTAG (across entire chip) on first boot when either secure boot or flash encryption is enabled. Setting this option leaves JTAG on for debugging, which negates all protections of flash encryption and some of the protections of secure boot. Only set this option in testing environments. Default value: No (disabled) if CONFIG_SECURE_BOOT_INSECURE || CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT CONFIG_SECURE_BOOT_ALLOW_SHORT_APP_PARTITION Allow app partition length not 64KB aligned Found in: Security features > Potentially insecure options If not set (default), app partition size must be a multiple of 64KB. App images are padded to 64KB length, and the bootloader checks any trailing bytes after the signature (before the next 64KB boundary) have not been written. This is because flash cache maps entire 64KB pages into the address space. This prevents an attacker from appending unverified data after the app image in the flash, causing it to be mapped into the address space. Setting this option allows the app partition length to be unaligned, and disables padding of the app image to this length. It is generally not recommended to set this option, unless you have a legacy partitioning scheme which doesn't support 64KB aligned partition lengths. CONFIG_SECURE_BOOT_V2_ALLOW_EFUSE_RD_DIS Allow additional read protecting of efuses Found in: Security features > Potentially insecure options If not set (default, recommended), on first boot the bootloader will burn the WR_DIS_RD_DIS efuse when Secure Boot is enabled. This prevents any more efuses from being read protected. If this option is set, it will remain possible to write the EFUSE_RD_DIS efuse field after Secure Boot is enabled. This may allow an attacker to read-protect the BLK2 efuse (for ESP32) and BLOCK4-BLOCK10 (i.e. BLOCK_KEY0-BLOCK_KEY5)(for other chips) holding the public key digest, causing an immediate denial of service and possibly allowing an additional fault injection attack to bypass the signature protection. NOTE: Once a BLOCK is read-protected, the application will read all zeros from that block NOTE: If "UART ROM download mode (Permanently disabled (recommended))" or "UART ROM download mode (Permanently switch to Secure mode (recommended))" is set, then it is __NOT__ possible to read/write efuses using espefuse.py utility. However, efuse can be read/written from the application CONFIG_SECURE_BOOT_ALLOW_UNUSED_DIGEST_SLOTS Leave unused digest slots available (not revoke) Found in: Security features > Potentially insecure options If not set (default), during startup in the app all unused digest slots will be revoked. To revoke unused slot will be called esp_efuse_set_digest_revoke(num_digest) for each digest. Revoking unused digest slots makes ensures that no trusted keys can be added later by an attacker. If set, it means that you have a plan to use unused digests slots later. Default value: No (disabled) if CONFIG_SECURE_BOOT_INSECURE && SOC_EFUSE_REVOKE_BOOT_KEY_DIGESTS CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_ENC Leave UART bootloader encryption enabled Found in: Security features > Potentially insecure options If not set (default), the bootloader will permanently disable UART bootloader encryption access on first boot. If set, the UART bootloader will still be able to access hardware encryption. It is recommended to only set this option in testing environments. Default value: No (disabled) if CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_DEC Leave UART bootloader decryption enabled Found in: Security features > Potentially insecure options If not set (default), the bootloader will permanently disable UART bootloader decryption access on first boot. If set, the UART bootloader will still be able to access hardware decryption. Only set this option in testing environments. Setting this option allows complete bypass of flash encryption. Default value: No (disabled) if CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_CACHE Leave UART bootloader flash cache enabled Found in: Security features > Potentially insecure options If not set (default), the bootloader will permanently disable UART bootloader flash cache access on first boot. If set, the UART bootloader will still be able to access the flash cache. Only set this option in testing environments. Default value: No (disabled) if CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT CONFIG_SECURE_FLASH_REQUIRE_ALREADY_ENABLED Require flash encryption to be already enabled Found in: Security features > Potentially insecure options If not set (default), and flash encryption is not yet enabled in eFuses, the 2nd stage bootloader will enable flash encryption: generate the flash encryption key and program eFuses. If this option is set, and flash encryption is not yet enabled, the bootloader will error out and reboot. If flash encryption is enabled in eFuses, this option does not change the bootloader behavior. Only use this option in testing environments, to avoid accidentally enabling flash encryption on the wrong device. The device needs to have flash encryption already enabled using espefuse.py. Default value: No (disabled) if CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT CONFIG_SECURE_FLASH_SKIP_WRITE_PROTECTION_CACHE Skip write-protection of DIS_CACHE (DIS_ICACHE, DIS_DCACHE) Found in: Security features > Potentially insecure options If not set (default, recommended), on the first boot the bootloader will burn the write-protection of DIS_CACHE(for ESP32) or DIS_ICACHE/DIS_DCACHE(for other chips) eFuse when Flash Encryption is enabled. Write protection for cache disable efuse prevents the chip from being blocked if it is set by accident. App and bootloader use cache so disabling it makes the chip useless for IDF. Due to other eFuses are linked with the same write protection bit (see the list below) then write-protection will not be done if these SECURE_FLASH_UART_BOOTLOADER_ALLOW_ENC, SECURE_BOOT_ALLOW_JTAG or SECURE_FLASH_UART_BOOTLOADER_ALLOW_CACHE options are selected to give a chance to turn on the chip into the release mode later. List of eFuses with the same write protection bit: ESP32: MAC, MAC_CRC, DISABLE_APP_CPU, DISABLE_BT, DIS_CACHE, VOL_LEVEL_HP_INV. ESP32-C3: DIS_ICACHE, DIS_USB_JTAG, DIS_DOWNLOAD_ICACHE, DIS_USB_SERIAL_JTAG, DIS_FORCE_DOWNLOAD, DIS_TWAI, JTAG_SEL_ENABLE, DIS_PAD_JTAG, DIS_DOWNLOAD_MANUAL_ENCRYPT. ESP32-C6: SWAP_UART_SDIO_EN, DIS_ICACHE, DIS_USB_JTAG, DIS_DOWNLOAD_ICACHE, DIS_USB_SERIAL_JTAG, DIS_FORCE_DOWNLOAD, DIS_TWAI, JTAG_SEL_ENABLE, DIS_PAD_JTAG, DIS_DOWNLOAD_MANUAL_ENCRYPT. ESP32-H2: DIS_ICACHE, DIS_USB_JTAG, POWERGLITCH_EN, DIS_FORCE_DOWNLOAD, SPI_DOWNLOAD_MSPI_DIS, DIS_TWAI, JTAG_SEL_ENABLE, DIS_PAD_JTAG, DIS_DOWNLOAD_MANUAL_ENCRYPT. ESP32-S2: DIS_ICACHE, DIS_DCACHE, DIS_DOWNLOAD_ICACHE, DIS_DOWNLOAD_DCACHE, DIS_FORCE_DOWNLOAD, DIS_USB, DIS_TWAI, DIS_BOOT_REMAP, SOFT_DIS_JTAG, HARD_DIS_JTAG, DIS_DOWNLOAD_MANUAL_ENCRYPT. ESP32-S3: DIS_ICACHE, DIS_DCACHE, DIS_DOWNLOAD_ICACHE, DIS_DOWNLOAD_DCACHE, DIS_FORCE_DOWNLOAD, DIS_USB_OTG, DIS_TWAI, DIS_APP_CPU, DIS_PAD_JTAG, DIS_DOWNLOAD_MANUAL_ENCRYPT, DIS_USB_JTAG, DIS_USB_SERIAL_JTAG, STRAP_JTAG_SEL, USB_PHY_SEL. CONFIG_SECURE_FLASH_ENCRYPT_ONLY_IMAGE_LEN_IN_APP_PART Encrypt only the app image that is present in the partition of type app Found in: Security features If set, optimise encryption time for the partition of type APP, by only encrypting the app image that is present in the partition, instead of the whole partition. The image length used for encryption is derived from the image metadata, which includes the size of the app image, checksum, hash and also the signature sector when secure boot is enabled. If not set (default), the whole partition of type APP would be encrypted, which increases the encryption time but might be useful if there is any custom data appended to the firmware image. CONFIG_SECURE_FLASH_CHECK_ENC_EN_IN_APP Check Flash Encryption enabled on app startup Found in: Security features If set (default), in an app during startup code, there is a check of the flash encryption eFuse bit is on (as the bootloader should already have set it). The app requires this bit is on to continue work otherwise abort. If not set, the app does not care if the flash encryption eFuse bit is set or not. Default value: Yes (enabled) if CONFIG_SECURE_FLASH_ENC_ENABLED CONFIG_SECURE_UART_ROM_DL_MODE UART ROM download mode Found in: Security features Available options: UART ROM download mode (Permanently disabled (recommended)) (CONFIG_SECURE_DISABLE_ROM_DL_MODE) If set, during startup the app will burn an eFuse bit to permanently disable the UART ROM Download Mode. This prevents any future use of esptool.py, espefuse.py and similar tools. Once disabled, if the SoC is booted with strapping pins set for ROM Download Mode then an error is printed instead. It is recommended to enable this option in any production application where Flash Encryption and/or Secure Boot is enabled and access to Download Mode is not required. It is also possible to permanently disable Download Mode by calling esp_efuse_disable_rom_download_mode() at runtime. UART ROM download mode (Permanently switch to Secure mode (recommended)) (CONFIG_SECURE_ENABLE_SECURE_ROM_DL_MODE) If set, during startup the app will burn an eFuse bit to permanently switch the UART ROM Download Mode into a separate Secure Download mode. This option can only work if Download Mode is not already disabled by eFuse. Secure Download mode limits the use of Download Mode functions to update SPI config, changing baud rate, basic flash write and a command to return a summary of currently enabled security features (get_security_info). Secure Download mode is not compatible with the esptool.py flasher stub feature, espefuse.py, read/writing memory or registers, encrypted download, or any other features that interact with unsupported Download Mode commands. Secure Download mode should be enabled in any application where Flash Encryption and/or Secure Boot is enabled. Disabling this option does not immediately cancel the benefits of the security features, but it increases the potential "attack surface" for an attacker to try and bypass them with a successful physical attack. It is also possible to enable secure download mode at runtime by calling esp_efuse_enable_rom_secure_download_mode() Note: Secure Download mode is not available for ESP32 (includes revisions till ECO3). UART ROM download mode (Enabled (not recommended)) (CONFIG_SECURE_INSECURE_ALLOW_DL_MODE) This is a potentially insecure option. Enabling this option will allow the full UART download mode to stay enabled. This option SHOULD NOT BE ENABLED for production use cases. Application manager Contains: CONFIG_APP_COMPILE_TIME_DATE Use time/date stamp for app Found in: Application manager If set, then the app will be built with the current time/date stamp. It is stored in the app description structure. If not set, time/date stamp will be excluded from app image. This can be useful for getting the same binary image files made from the same source, but at different times. CONFIG_APP_EXCLUDE_PROJECT_VER_VAR Exclude PROJECT_VER from firmware image Found in: Application manager The PROJECT_VER variable from the build system will not affect the firmware image. This value will not be contained in the esp_app_desc structure. Default value: No (disabled) CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR Exclude PROJECT_NAME from firmware image Found in: Application manager The PROJECT_NAME variable from the build system will not affect the firmware image. This value will not be contained in the esp_app_desc structure. Default value: No (disabled) CONFIG_APP_PROJECT_VER_FROM_CONFIG Get the project version from Kconfig Found in: Application manager If this is enabled, then config item APP_PROJECT_VER will be used for the variable PROJECT_VER. Other ways to set PROJECT_VER will be ignored. Default value: No (disabled) CONFIG_APP_PROJECT_VER Project version Found in: Application manager > CONFIG_APP_PROJECT_VER_FROM_CONFIG Project version Default value: CONFIG_APP_RETRIEVE_LEN_ELF_SHA The length of APP ELF SHA is stored in RAM(chars) Found in: Application manager At startup, the app will read the embedded APP ELF SHA-256 hash value from flash and convert it into a string and store it in a RAM buffer. This ensures the panic handler and core dump will be able to print this string even when cache is disabled. The size of the buffer is APP_RETRIEVE_LEN_ELF_SHA plus the null terminator. Changing this value will change the size of this buffer, in bytes. Range: from 8 to 64 Default value: 9 Serial flasher config Contains: CONFIG_ESPTOOLPY_NO_STUB Disable download stub Found in: Serial flasher config The flasher tool sends a precompiled download stub first by default. That stub allows things like compressed downloads and more. Usually you should not need to disable that feature CONFIG_ESPTOOLPY_FLASHMODE Flash SPI mode Found in: Serial flasher config Mode the flash chip is flashed in, as well as the default mode for the binary to run in. Available options: QIO (CONFIG_ESPTOOLPY_FLASHMODE_QIO) QOUT (CONFIG_ESPTOOLPY_FLASHMODE_QOUT) DIO (CONFIG_ESPTOOLPY_FLASHMODE_DIO) DOUT (CONFIG_ESPTOOLPY_FLASHMODE_DOUT) OPI (CONFIG_ESPTOOLPY_FLASHMODE_OPI) CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE Flash Sampling Mode Found in: Serial flasher config Available options: STR Mode (CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_STR) DTR Mode (CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_DTR) CONFIG_ESPTOOLPY_FLASHFREQ Flash SPI speed Found in: Serial flasher config Available options: 120 MHz (READ DOCS FIRST) (CONFIG_ESPTOOLPY_FLASHFREQ_120M) Optional feature for QSPI Flash. Read docs and enable CONFIG_SPI_FLASH_HPM_ENA first! Flash 120 MHz SDR mode is stable. Flash 120 MHz DDR mode is an experimental feature, it works when the temperature is stable. Risks: If your chip powers on at a certain temperature, then after the temperature increases or decreases by approximately 20 Celsius degrees (depending on the chip), the program will crash randomly. 80 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_80M) 64 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_64M) 60 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_60M) 48 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_48M) 40 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_40M) 32 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_32M) 30 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_30M) 26 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_26M) 24 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_24M) 20 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_20M) 16 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_16M) 15 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_15M) CONFIG_ESPTOOLPY_FLASHSIZE Flash size Found in: Serial flasher config SPI flash size, in megabytes Available options: 1 MB (CONFIG_ESPTOOLPY_FLASHSIZE_1MB) 2 MB (CONFIG_ESPTOOLPY_FLASHSIZE_2MB) 4 MB (CONFIG_ESPTOOLPY_FLASHSIZE_4MB) 8 MB (CONFIG_ESPTOOLPY_FLASHSIZE_8MB) 16 MB (CONFIG_ESPTOOLPY_FLASHSIZE_16MB) 32 MB (CONFIG_ESPTOOLPY_FLASHSIZE_32MB) 64 MB (CONFIG_ESPTOOLPY_FLASHSIZE_64MB) 128 MB (CONFIG_ESPTOOLPY_FLASHSIZE_128MB) CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE Detect flash size when flashing bootloader Found in: Serial flasher config If this option is set, flashing the project will automatically detect the flash size of the target chip and update the bootloader image before it is flashed. Enabling this option turns off the image protection against corruption by a SHA256 digest. Updating the bootloader image before flashing would invalidate the digest. CONFIG_ESPTOOLPY_BEFORE Before flashing Found in: Serial flasher config Configure whether esptool.py should reset the ESP32 before flashing. Automatic resetting depends on the RTS & DTR signals being wired from the serial port to the ESP32. Most USB development boards do this internally. Available options: Reset to bootloader (CONFIG_ESPTOOLPY_BEFORE_RESET) No reset (CONFIG_ESPTOOLPY_BEFORE_NORESET) CONFIG_ESPTOOLPY_AFTER After flashing Found in: Serial flasher config Configure whether esptool.py should reset the ESP32 after flashing. Automatic resetting depends on the RTS & DTR signals being wired from the serial port to the ESP32. Most USB development boards do this internally. Available options: Reset after flashing (CONFIG_ESPTOOLPY_AFTER_RESET) Stay in bootloader (CONFIG_ESPTOOLPY_AFTER_NORESET) Partition Table Contains: CONFIG_PARTITION_TABLE_TYPE Partition Table Found in: Partition Table The partition table to flash to the ESP32. The partition table determines where apps, data and other resources are expected to be found. The predefined partition table CSV descriptions can be found in the components/partition_table directory. These are mostly intended for example and development use, it's expect that for production use you will copy one of these CSV files and create a custom partition CSV for your application. Available options: Single factory app, no OTA (CONFIG_PARTITION_TABLE_SINGLE_APP) This is the default partition table, designed to fit into a 2MB or larger flash with a single 1MB app partition. The corresponding CSV file in the IDF directory is components/partition_table/partitions_singleapp.csv This partition table is not suitable for an app that needs OTA (over the air update) capability. Single factory app (large), no OTA (CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE) This is a variation of the default partition table, that expands the 1MB app partition size to 1.5MB to fit more code. The corresponding CSV file in the IDF directory is components/partition_table/partitions_singleapp_large.csv This partition table is not suitable for an app that needs OTA (over the air update) capability. Factory app, two OTA definitions (CONFIG_PARTITION_TABLE_TWO_OTA) This is a basic OTA-enabled partition table with a factory app partition plus two OTA app partitions. All are 1MB, so this partition table requires 4MB or larger flash size. The corresponding CSV file in the IDF directory is components/partition_table/partitions_two_ota.csv Custom partition table CSV (CONFIG_PARTITION_TABLE_CUSTOM) Specify the path to the partition table CSV to use for your project. Consult the Partition Table section in the ESP-IDF Programmers Guide for more information. Single factory app, no OTA, encrypted NVS (CONFIG_PARTITION_TABLE_SINGLE_APP_ENCRYPTED_NVS) This is a variation of the default "Single factory app, no OTA" partition table that supports encrypted NVS when using flash encryption. See the Flash Encryption section in the ESP-IDF Programmers Guide for more information. The corresponding CSV file in the IDF directory is components/partition_table/partitions_singleapp_encr_nvs.csv Single factory app (large), no OTA, encrypted NVS (CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE_ENC_NVS) This is a variation of the "Single factory app (large), no OTA" partition table that supports encrypted NVS when using flash encryption. See the Flash Encryption section in the ESP-IDF Programmers Guide for more information. The corresponding CSV file in the IDF directory is components/partition_table/partitions_singleapp_large_encr_nvs.csv Factory app, two OTA definitions, encrypted NVS (CONFIG_PARTITION_TABLE_TWO_OTA_ENCRYPTED_NVS) This is a variation of the "Factory app, two OTA definitions" partition table that supports encrypted NVS when using flash encryption. See the Flash Encryption section in the ESP-IDF Programmers Guide for more information. The corresponding CSV file in the IDF directory is components/partition_table/partitions_two_ota_encr_nvs.csv CONFIG_PARTITION_TABLE_CUSTOM_FILENAME Custom partition CSV file Found in: Partition Table Name of the custom partition CSV filename. This path is evaluated relative to the project root directory. Default value: "partitions.csv" CONFIG_PARTITION_TABLE_OFFSET Offset of partition table Found in: Partition Table The address of partition table (by default 0x8000). Allows you to move the partition table, it gives more space for the bootloader. Note that the bootloader and app will both need to be compiled with the same PARTITION_TABLE_OFFSET value. This number should be a multiple of 0x1000. Note that partition offsets in the partition table CSV file may need to be changed if this value is set to a higher value. To have each partition offset adapt to the configured partition table offset, leave all partition offsets blank in the CSV file. Default value: "0x8000" CONFIG_PARTITION_TABLE_MD5 Generate an MD5 checksum for the partition table Found in: Partition Table Generate an MD5 checksum for the partition table for protecting the integrity of the table. The generation should be turned off for legacy bootloaders which cannot recognize the MD5 checksum in the partition table. Compiler options Contains: CONFIG_COMPILER_OPTIMIZATION Optimization Level Found in: Compiler options This option sets compiler optimization level (gcc -O argument) for the app. The "Debug" setting will add the -0g flag to CFLAGS. The "Size" setting will add the -0s flag to CFLAGS. The "Performance" setting will add the -O2 flag to CFLAGS. The "None" setting will add the -O0 flag to CFLAGS. The "Size" setting cause the compiled code to be smaller and faster, but may lead to difficulties of correlating code addresses to source file lines when debugging. The "Performance" setting causes the compiled code to be larger and faster, but will be easier to correlated code addresses to source file lines. "None" with -O0 produces compiled code without optimization. Note that custom optimization levels may be unsupported. Compiler optimization for the IDF bootloader is set separately, see the BOOTLOADER_COMPILER_OPTIMIZATION setting. Available options: Debug (-Og) (CONFIG_COMPILER_OPTIMIZATION_DEBUG) Optimize for size (-Os) (CONFIG_COMPILER_OPTIMIZATION_SIZE) Optimize for performance (-O2) (CONFIG_COMPILER_OPTIMIZATION_PERF) Debug without optimization (-O0) (CONFIG_COMPILER_OPTIMIZATION_NONE) CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL Assertion level Found in: Compiler options Assertions can be: Enabled. Failure will print verbose assertion details. This is the default. Set to "silent" to save code size (failed assertions will abort() but user needs to use the aborting address to find the line number with the failed assertion.) Disabled entirely (not recommended for most configurations.) -DNDEBUG is added to CPPFLAGS in this case. Available options: Enabled (CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE) Enable assertions. Assertion content and line number will be printed on failure. Silent (saves code size) (CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT) Enable silent assertions. Failed assertions will abort(), user needs to use the aborting address to find the line number with the failed assertion. Disabled (sets -DNDEBUG) (CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE) If assertions are disabled, -DNDEBUG is added to CPPFLAGS. CONFIG_COMPILER_FLOAT_LIB_FROM Compiler float lib source Found in: Compiler options In the soft-fp part of libgcc, riscv version is written in C, and handles all edge cases in IEEE754, which makes it larger and performance is slow. RVfplib is an optimized RISC-V library for FP arithmetic on 32-bit integer processors, for single and double-precision FP. RVfplib is "fast", but it has a few exceptions from IEEE 754 compliance. Available options: libgcc (CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB) librvfp (CONFIG_COMPILER_FLOAT_LIB_FROM_RVFPLIB) CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT Disable messages in ESP_RETURN_ON_* and ESP_EXIT_ON_* macros Found in: Compiler options If enabled, the error messages will be discarded in following check macros: - ESP_RETURN_ON_ERROR - ESP_EXIT_ON_ERROR - ESP_RETURN_ON_FALSE - ESP_EXIT_ON_FALSE Default value: No (disabled) CONFIG_COMPILER_HIDE_PATHS_MACROS Replace ESP-IDF and project paths in binaries Found in: Compiler options When expanding the __FILE__ and __BASE_FILE__ macros, replace paths inside ESP-IDF with paths relative to the placeholder string "IDF", and convert paths inside the project directory to relative paths. This allows building the project with assertions or other code that embeds file paths, without the binary containing the exact path to the IDF or project directories. This option passes -fmacro-prefix-map options to the GCC command line. To replace additional paths in your binaries, modify the project CMakeLists.txt file to pass custom -fmacro-prefix-map or -ffile-prefix-map arguments. Default value: Yes (enabled) CONFIG_COMPILER_CXX_EXCEPTIONS Enable C++ exceptions Found in: Compiler options Enabling this option compiles all IDF C++ files with exception support enabled. Disabling this option disables C++ exception support in all compiled files, and any libstdc++ code which throws an exception will abort instead. Enabling this option currently adds an additional ~500 bytes of heap overhead when an exception is thrown in user code for the first time. Default value: No (disabled) Contains: CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE Emergency Pool Size Found in: Compiler options > CONFIG_COMPILER_CXX_EXCEPTIONS Size (in bytes) of the emergency memory pool for C++ exceptions. This pool will be used to allocate memory for thrown exceptions when there is not enough memory on the heap. Default value: CONFIG_COMPILER_CXX_RTTI Enable C++ run-time type info (RTTI) Found in: Compiler options Enabling this option compiles all C++ files with RTTI support enabled. This increases binary size (typically by tens of kB) but allows using dynamic_cast conversion and typeid operator. Default value: No (disabled) CONFIG_COMPILER_STACK_CHECK_MODE Stack smashing protection mode Found in: Compiler options Stack smashing protection mode. Emit extra code to check for buffer overflows, such as stack smashing attacks. This is done by adding a guard variable to functions with vulnerable objects. The guards are initialized when a function is entered and then checked when the function exits. If a guard check fails, program is halted. Protection has the following modes: In NORMAL mode (GCC flag: -fstack-protector) only functions that call alloca, and functions with buffers larger than 8 bytes are protected. STRONG mode (GCC flag: -fstack-protector-strong) is like NORMAL, but includes additional functions to be protected -- those that have local array definitions, or have references to local frame addresses. In OVERALL mode (GCC flag: -fstack-protector-all) all functions are protected. Modes have the following impact on code performance and coverage: performance: NORMAL > STRONG > OVERALL coverage: NORMAL < STRONG < OVERALL The performance impact includes increasing the amount of stack memory required for each task. Available options: None (CONFIG_COMPILER_STACK_CHECK_MODE_NONE) Normal (CONFIG_COMPILER_STACK_CHECK_MODE_NORM) Strong (CONFIG_COMPILER_STACK_CHECK_MODE_STRONG) Overall (CONFIG_COMPILER_STACK_CHECK_MODE_ALL) CONFIG_COMPILER_WARN_WRITE_STRINGS Enable -Wwrite-strings warning flag Found in: Compiler options Adds -Wwrite-strings flag for the C/C++ compilers. For C, this gives string constants the type const char[] so that copying the address of one into a non-const char \* pointer produces a warning. This warning helps to find at compile time code that tries to write into a string constant. For C++, this warns about the deprecated conversion from string literals to char \* . Default value: No (disabled) CONFIG_COMPILER_DISABLE_GCC12_WARNINGS Disable new warnings introduced in GCC 12 Found in: Compiler options Enable this option if use GCC 12 or newer, and want to disable warnings which don't appear with GCC 11. Default value: No (disabled) CONFIG_COMPILER_DISABLE_GCC13_WARNINGS Disable new warnings introduced in GCC 13 Found in: Compiler options Enable this option if use GCC 13 or newer, and want to disable warnings which don't appear with GCC 12. Default value: No (disabled) CONFIG_COMPILER_DUMP_RTL_FILES Dump RTL files during compilation Found in: Compiler options If enabled, RTL files will be produced during compilation. These files can be used by other tools, for example to calculate call graphs. CONFIG_COMPILER_RT_LIB Compiler runtime library Found in: Compiler options Select runtime library to be used by compiler. - GCC toolchain supports libgcc only. - Clang allows to choose between libgcc or libclang_rt. - For host builds ("linux" target), uses the default library. Available options: libgcc (CONFIG_COMPILER_RT_LIB_GCCLIB) libclang_rt (CONFIG_COMPILER_RT_LIB_CLANGRT) Host (CONFIG_COMPILER_RT_LIB_HOST) Component config Contains: Application Level Tracing Contains: CONFIG_APPTRACE_DESTINATION1 Data Destination 1 Found in: Component config > Application Level Tracing Select destination for application trace: JTAG or none (to disable). Available options: JTAG (CONFIG_APPTRACE_DEST_JTAG) None (CONFIG_APPTRACE_DEST_NONE) CONFIG_APPTRACE_DESTINATION2 Data Destination 2 Found in: Component config > Application Level Tracing Select destination for application trace: UART(XX) or none (to disable). Available options: UART0 (CONFIG_APPTRACE_DEST_UART0) UART1 (CONFIG_APPTRACE_DEST_UART1) UART2 (CONFIG_APPTRACE_DEST_UART2) USB_CDC (CONFIG_APPTRACE_DEST_USB_CDC) None (CONFIG_APPTRACE_DEST_UART_NONE) CONFIG_APPTRACE_UART_TX_GPIO UART TX on GPIO# Found in: Component config > Application Level Tracing This GPIO is used for UART TX pin. CONFIG_APPTRACE_UART_RX_GPIO UART RX on GPIO# Found in: Component config > Application Level Tracing This GPIO is used for UART RX pin. CONFIG_APPTRACE_UART_BAUDRATE UART baud rate Found in: Component config > Application Level Tracing This baud rate is used for UART. The app's maximum baud rate depends on the UART clock source. If Power Management is disabled, the UART clock source is the APB clock and all baud rates in the available range will be sufficiently accurate. If Power Management is enabled, REF_TICK clock source is used so the baud rate is divided from 1MHz. Baud rates above 1Mbps are not possible and values between 500Kbps and 1Mbps may not be accurate. CONFIG_APPTRACE_UART_RX_BUFF_SIZE UART RX ring buffer size Found in: Component config > Application Level Tracing Size of the UART input ring buffer. This size related to the baudrate, system tick frequency and amount of data to transfer. The data placed to this buffer before sent out to the interface. CONFIG_APPTRACE_UART_TX_BUFF_SIZE UART TX ring buffer size Found in: Component config > Application Level Tracing Size of the UART output ring buffer. This size related to the baudrate, system tick frequency and amount of data to transfer. CONFIG_APPTRACE_UART_TX_MSG_SIZE UART TX message size Found in: Component config > Application Level Tracing Maximum size of the single message to transfer. CONFIG_APPTRACE_UART_TASK_PRIO UART Task Priority Found in: Component config > Application Level Tracing UART task priority. In case of high events rate, this parameter could be changed up to (configMAX_PRIORITIES-1). Range: from 1 to 32 Default value: 1 CONFIG_APPTRACE_ONPANIC_HOST_FLUSH_TMO Timeout for flushing last trace data to host on panic Found in: Component config > Application Level Tracing Timeout for flushing last trace data to host in case of panic. In ms. Use -1 to disable timeout and wait forever. CONFIG_APPTRACE_POSTMORTEM_FLUSH_THRESH Threshold for flushing last trace data to host on panic Found in: Component config > Application Level Tracing Threshold for flushing last trace data to host on panic in post-mortem mode. This is minimal amount of data needed to perform flush. In bytes. CONFIG_APPTRACE_BUF_SIZE Size of the apptrace buffer Found in: Component config > Application Level Tracing Size of the memory buffer for trace data in bytes. CONFIG_APPTRACE_PENDING_DATA_SIZE_MAX Size of the pending data buffer Found in: Component config > Application Level Tracing Size of the buffer for events in bytes. It is useful for buffering events from the time critical code (scheduler, ISRs etc). If this parameter is 0 then events will be discarded when main HW buffer is full. FreeRTOS SystemView Tracing Contains: CONFIG_APPTRACE_SV_ENABLE SystemView Tracing Enable Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables supporrt for SEGGER SystemView tracing functionality. CONFIG_APPTRACE_SV_DEST SystemView destination Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing > CONFIG_APPTRACE_SV_ENABLE SystemView witt transfer data trough defined interface. Available options: Data destination JTAG (CONFIG_APPTRACE_SV_DEST_JTAG) Send SEGGER SystemView events through JTAG interface. Data destination UART (CONFIG_APPTRACE_SV_DEST_UART) Send SEGGER SystemView events through UART interface. CONFIG_APPTRACE_SV_CPU CPU to trace Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Define the CPU to trace by SystemView. Available options: CPU0 (CONFIG_APPTRACE_SV_DEST_CPU_0) Send SEGGER SystemView events for Pro CPU. CPU1 (CONFIG_APPTRACE_SV_DEST_CPU_1) Send SEGGER SystemView events for App CPU. CONFIG_APPTRACE_SV_TS_SOURCE Timer to use as timestamp source Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing SystemView needs to use a hardware timer as the source of timestamps when tracing. This option selects the timer for it. Available options: CPU cycle counter (CCOUNT) (CONFIG_APPTRACE_SV_TS_SOURCE_CCOUNT) General Purpose Timer (Timer Group) (CONFIG_APPTRACE_SV_TS_SOURCE_GPTIMER) esp_timer high resolution timer (CONFIG_APPTRACE_SV_TS_SOURCE_ESP_TIMER) CONFIG_APPTRACE_SV_MAX_TASKS Maximum supported tasks Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Configures maximum supported tasks in sysview debug CONFIG_APPTRACE_SV_BUF_WAIT_TMO Trace buffer wait timeout Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Configures timeout (in us) to wait for free space in trace buffer. Set to -1 to wait forever and avoid lost events. CONFIG_APPTRACE_SV_EVT_OVERFLOW_ENABLE Trace Buffer Overflow Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Trace Buffer Overflow" event. CONFIG_APPTRACE_SV_EVT_ISR_ENTER_ENABLE ISR Enter Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "ISR Enter" event. CONFIG_APPTRACE_SV_EVT_ISR_EXIT_ENABLE ISR Exit Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "ISR Exit" event. CONFIG_APPTRACE_SV_EVT_ISR_TO_SCHED_ENABLE ISR Exit to Scheduler Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "ISR to Scheduler" event. CONFIG_APPTRACE_SV_EVT_TASK_START_EXEC_ENABLE Task Start Execution Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Task Start Execution" event. CONFIG_APPTRACE_SV_EVT_TASK_STOP_EXEC_ENABLE Task Stop Execution Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Task Stop Execution" event. CONFIG_APPTRACE_SV_EVT_TASK_START_READY_ENABLE Task Start Ready State Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Task Start Ready State" event. CONFIG_APPTRACE_SV_EVT_TASK_STOP_READY_ENABLE Task Stop Ready State Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Task Stop Ready State" event. CONFIG_APPTRACE_SV_EVT_TASK_CREATE_ENABLE Task Create Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Task Create" event. CONFIG_APPTRACE_SV_EVT_TASK_TERMINATE_ENABLE Task Terminate Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Task Terminate" event. CONFIG_APPTRACE_SV_EVT_IDLE_ENABLE System Idle Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "System Idle" event. CONFIG_APPTRACE_SV_EVT_TIMER_ENTER_ENABLE Timer Enter Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Timer Enter" event. CONFIG_APPTRACE_SV_EVT_TIMER_EXIT_ENABLE Timer Exit Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Timer Exit" event. CONFIG_APPTRACE_GCOV_ENABLE GCOV to Host Enable Found in: Component config > Application Level Tracing Enables support for GCOV data transfer to host. CONFIG_APPTRACE_GCOV_DUMP_TASK_STACK_SIZE Gcov dump task stack size Found in: Component config > Application Level Tracing > CONFIG_APPTRACE_GCOV_ENABLE Configures stack size of Gcov dump task Default value: 2048 if CONFIG_APPTRACE_GCOV_ENABLE Bluetooth Contains: CONFIG_BT_ENABLED Bluetooth Found in: Component config > Bluetooth Select this option to enable Bluetooth and show the submenu with Bluetooth configuration choices. CONFIG_BT_HOST Host Found in: Component config > Bluetooth > CONFIG_BT_ENABLED This helps to choose Bluetooth host stack Available options: Bluedroid - Dual-mode (CONFIG_BT_BLUEDROID_ENABLED) This option is recommended for classic Bluetooth or for dual-mode usecases NimBLE - BLE only (CONFIG_BT_NIMBLE_ENABLED) This option is recommended for BLE only usecases to save on memory Disabled (CONFIG_BT_CONTROLLER_ONLY) This option is recommended when you want to communicate directly with the controller (without any host) or when you are using any other host stack not supported by Espressif (not mentioned here). CONFIG_BT_CONTROLLER Controller Found in: Component config > Bluetooth > CONFIG_BT_ENABLED This helps to choose Bluetooth controller stack Available options: Enabled (CONFIG_BT_CONTROLLER_ENABLED) This option is recommended for Bluetooth controller usecases Disabled (CONFIG_BT_CONTROLLER_DISABLED) This option is recommended for Bluetooth Host only usecases Bluedroid Options Contains: CONFIG_BT_BTC_TASK_STACK_SIZE Bluetooth event (callback to application) task stack size Found in: Component config > Bluetooth > Bluedroid Options This select btc task stack size Default value: CONFIG_BT_BLUEDROID_PINNED_TO_CORE_CHOICE The cpu core which Bluedroid run Found in: Component config > Bluetooth > Bluedroid Options Which the cpu core to run Bluedroid. Can choose core0 and core1. Can not specify no-affinity. Available options: Core 0 (PRO CPU) (CONFIG_BT_BLUEDROID_PINNED_TO_CORE_0) Core 1 (APP CPU) (CONFIG_BT_BLUEDROID_PINNED_TO_CORE_1) CONFIG_BT_BTU_TASK_STACK_SIZE Bluetooth Bluedroid Host Stack task stack size Found in: Component config > Bluetooth > Bluedroid Options This select btu task stack size Default value: CONFIG_BT_BLUEDROID_MEM_DEBUG Bluedroid memory debug Found in: Component config > Bluetooth > Bluedroid Options Bluedroid memory debug Default value: No (disabled) if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLUEDROID_ESP_COEX_VSC Enable Espressif Vendor-specific HCI commands for coexist status configuration Found in: Component config > Bluetooth > Bluedroid Options Enable Espressif Vendor-specific HCI commands for coexist status configuration Default value: Yes (enabled) if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_CLASSIC_ENABLED Classic Bluetooth Found in: Component config > Bluetooth > Bluedroid Options For now this option needs "SMP_ENABLE" to be set to yes Default value: No (disabled) if CONFIG_BT_BLUEDROID_ENABLED && (CONFIG_BT_CONTROLLER_ENABLED || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_CLASSIC_BQB_ENABLED Host Qualitifcation support for Classic Bluetooth Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED This enables functionalities of Host qualification for Classic Bluetooth. Default value: No (disabled) if CONFIG_BT_CLASSIC_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_A2DP_ENABLE A2DP Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED Advanced Audio Distrubution Profile Default value: No (disabled) if CONFIG_BT_CLASSIC_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_SPP_ENABLED SPP Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED This enables the Serial Port Profile Default value: No (disabled) if CONFIG_BT_CLASSIC_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_L2CAP_ENABLED BT L2CAP Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED This enables the Logical Link Control and Adaptation Layer Protocol. Only supported classic bluetooth. Default value: No (disabled) if CONFIG_BT_CLASSIC_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_HFP_ENABLE Hands Free/Handset Profile Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED Hands Free Unit and Audio Gateway can be included simultaneously but they cannot run simultaneously due to internal limitations. Default value: No (disabled) if CONFIG_BT_CLASSIC_ENABLED && CONFIG_BT_BLUEDROID_ENABLED Contains: CONFIG_BT_HFP_CLIENT_ENABLE Hands Free Unit Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED > CONFIG_BT_HFP_ENABLE Default value: Yes (enabled) if CONFIG_BT_HFP_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_HFP_AG_ENABLE Audio Gateway Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED > CONFIG_BT_HFP_ENABLE Default value: Yes (enabled) if CONFIG_BT_HFP_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_HFP_AUDIO_DATA_PATH audio(SCO) data path Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED > CONFIG_BT_HFP_ENABLE SCO data path, i.e. HCI or PCM. This option is set using API "esp_bredr_sco_datapath_set" in Bluetooth host. Default SCO data path can also be set in Bluetooth Controller. Available options: PCM (CONFIG_BT_HFP_AUDIO_DATA_PATH_PCM) HCI (CONFIG_BT_HFP_AUDIO_DATA_PATH_HCI) CONFIG_BT_HFP_WBS_ENABLE Wide Band Speech Found in: Component config > Bluetooth > Bluedroid Options This enables Wide Band Speech. Should disable it when SCO data path is PCM. Otherwise there will be no data transmited via GPIOs. Default value: Yes (enabled) if CONFIG_BT_HFP_AUDIO_DATA_PATH_HCI && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_HID_ENABLED Classic BT HID Found in: Component config > Bluetooth > Bluedroid Options This enables the BT HID Host Default value: No (disabled) if CONFIG_BT_CLASSIC_ENABLED && CONFIG_BT_BLUEDROID_ENABLED Contains: CONFIG_BT_HID_HOST_ENABLED Classic BT HID Host Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_HID_ENABLED This enables the BT HID Host Default value: No (disabled) if CONFIG_BT_HID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_HID_DEVICE_ENABLED Classic BT HID Device Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_HID_ENABLED This enables the BT HID Device CONFIG_BT_BLE_ENABLED Bluetooth Low Energy Found in: Component config > Bluetooth > Bluedroid Options This enables Bluetooth Low Energy Default value: Yes (enabled) if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATTS_ENABLE Include GATT server module(GATTS) Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED This option can be disabled when the app work only on gatt client mode Default value: Yes (enabled) if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATTS_PPCP_CHAR_GAP Enable Peripheral Preferred Connection Parameters characteristic in GAP service Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE This enables "Peripheral Preferred Connection Parameters" characteristic (UUID: 0x2A04) in GAP service that has connection parameters like min/max connection interval, slave latency and supervision timeout multiplier Default value: No (disabled) if CONFIG_BT_GATTS_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_BLUFI_ENABLE Include blufi function Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE This option can be close when the app does not require blufi function. Default value: No (disabled) if CONFIG_BT_GATTS_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATT_MAX_SR_PROFILES Max GATT Server Profiles Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE Maximum GATT Server Profiles Count Range: from 1 to 32 if CONFIG_BT_GATTS_ENABLE && CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED Default value: CONFIG_BT_GATT_MAX_SR_ATTRIBUTES Max GATT Service Attributes Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE Maximum GATT Service Attributes Count Range: from 1 to 500 if CONFIG_BT_GATTS_ENABLE && CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED Default value: CONFIG_BT_GATTS_SEND_SERVICE_CHANGE_MODE GATTS Service Change Mode Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE Service change indication mode for GATT Server. Available options: GATTS manually send service change indication (CONFIG_BT_GATTS_SEND_SERVICE_CHANGE_MANUAL) Manually send service change indication through API esp_ble_gatts_send_service_change_indication() GATTS automatically send service change indication (CONFIG_BT_GATTS_SEND_SERVICE_CHANGE_AUTO) Let Bluedroid handle the service change indication internally CONFIG_BT_GATTS_ROBUST_CACHING_ENABLED Enable Robust Caching on Server Side Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE This option enables the GATT robust caching feature on the server. if turned on, the Client Supported Features characteristic, Database Hash characteristic, and Server Supported Features characteristic will be included in the GAP SERVICE. Default value: No (disabled) if CONFIG_BT_GATTS_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATTS_DEVICE_NAME_WRITABLE Allow to write device name by GATT clients Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE Enabling this option allows remote GATT clients to write device name Default value: No (disabled) if CONFIG_BT_GATTS_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATTS_APPEARANCE_WRITABLE Allow to write appearance by GATT clients Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE Enabling this option allows remote GATT clients to write appearance Default value: No (disabled) if CONFIG_BT_GATTS_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATTC_ENABLE Include GATT client module(GATTC) Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED This option can be close when the app work only on gatt server mode Default value: Yes (enabled) if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATTC_MAX_CACHE_CHAR Max gattc cache characteristic for discover Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTC_ENABLE Maximum GATTC cache characteristic count Range: from 1 to 500 if CONFIG_BT_GATTC_ENABLE && CONFIG_BT_BLUEDROID_ENABLED Default value: CONFIG_BT_GATTC_NOTIF_REG_MAX Max gattc notify(indication) register number Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTC_ENABLE Maximum GATTC notify(indication) register number Range: from 1 to 64 if CONFIG_BT_GATTC_ENABLE && CONFIG_BT_BLUEDROID_ENABLED Default value: CONFIG_BT_GATTC_CACHE_NVS_FLASH Save gattc cache data to nvs flash Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTC_ENABLE This select can save gattc cache data to nvs flash Default value: No (disabled) if CONFIG_BT_GATTC_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATTC_CONNECT_RETRY_COUNT The number of attempts to reconnect if the connection establishment failed Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTC_ENABLE The number of attempts to reconnect if the connection establishment failed Range: from 0 to 7 if CONFIG_BT_GATTC_ENABLE && CONFIG_BT_BLUEDROID_ENABLED Default value: CONFIG_BT_BLE_SMP_ENABLE Include BLE security module(SMP) Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED This option can be close when the app not used the ble security connect. Default value: Yes (enabled) if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_SMP_SLAVE_CON_PARAMS_UPD_ENABLE Slave enable connection parameters update during pairing Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_BLE_SMP_ENABLE In order to reduce the pairing time, slave actively initiates connection parameters update during pairing. Default value: No (disabled) if CONFIG_BT_BLE_SMP_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_STACK_NO_LOG Disable BT debug logs (minimize bin size) Found in: Component config > Bluetooth > Bluedroid Options This select can save the rodata code size Default value: No (disabled) if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED BT DEBUG LOG LEVEL Contains: CONFIG_BT_LOG_HCI_TRACE_LEVEL HCI layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for HCI layer Available options: NONE (CONFIG_BT_LOG_HCI_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_HCI_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_HCI_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_HCI_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_HCI_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_HCI_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_HCI_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_BTM_TRACE_LEVEL BTM layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for BTM layer Available options: NONE (CONFIG_BT_LOG_BTM_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_BTM_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_BTM_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_BTM_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_BTM_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_BTM_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_BTM_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_L2CAP_TRACE_LEVEL L2CAP layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for L2CAP layer Available options: NONE (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL RFCOMM layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for RFCOMM layer Available options: NONE (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_SDP_TRACE_LEVEL SDP layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for SDP layer Available options: NONE (CONFIG_BT_LOG_SDP_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_SDP_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_SDP_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_SDP_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_SDP_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_SDP_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_SDP_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_GAP_TRACE_LEVEL GAP layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for GAP layer Available options: NONE (CONFIG_BT_LOG_GAP_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_GAP_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_GAP_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_GAP_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_GAP_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_GAP_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_GAP_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_BNEP_TRACE_LEVEL BNEP layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for BNEP layer Available options: NONE (CONFIG_BT_LOG_BNEP_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_BNEP_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_BNEP_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_BNEP_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_BNEP_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_BNEP_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_BNEP_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_PAN_TRACE_LEVEL PAN layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for PAN layer Available options: NONE (CONFIG_BT_LOG_PAN_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_PAN_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_PAN_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_PAN_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_PAN_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_PAN_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_PAN_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_A2D_TRACE_LEVEL A2D layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for A2D layer Available options: NONE (CONFIG_BT_LOG_A2D_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_A2D_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_A2D_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_A2D_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_A2D_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_A2D_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_A2D_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_AVDT_TRACE_LEVEL AVDT layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for AVDT layer Available options: NONE (CONFIG_BT_LOG_AVDT_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_AVDT_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_AVDT_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_AVDT_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_AVDT_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_AVDT_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_AVDT_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_AVCT_TRACE_LEVEL AVCT layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for AVCT layer Available options: NONE (CONFIG_BT_LOG_AVCT_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_AVCT_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_AVCT_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_AVCT_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_AVCT_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_AVCT_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_AVCT_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_AVRC_TRACE_LEVEL AVRC layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for AVRC layer Available options: NONE (CONFIG_BT_LOG_AVRC_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_AVRC_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_AVRC_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_AVRC_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_AVRC_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_AVRC_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_AVRC_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_MCA_TRACE_LEVEL MCA layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for MCA layer Available options: NONE (CONFIG_BT_LOG_MCA_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_MCA_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_MCA_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_MCA_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_MCA_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_MCA_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_MCA_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_HID_TRACE_LEVEL HID layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for HID layer Available options: NONE (CONFIG_BT_LOG_HID_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_HID_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_HID_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_HID_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_HID_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_HID_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_HID_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_APPL_TRACE_LEVEL APPL layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for APPL layer Available options: NONE (CONFIG_BT_LOG_APPL_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_APPL_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_APPL_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_APPL_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_APPL_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_APPL_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_APPL_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_GATT_TRACE_LEVEL GATT layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for GATT layer Available options: NONE (CONFIG_BT_LOG_GATT_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_GATT_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_GATT_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_GATT_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_GATT_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_GATT_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_GATT_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_SMP_TRACE_LEVEL SMP layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for SMP layer Available options: NONE (CONFIG_BT_LOG_SMP_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_SMP_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_SMP_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_SMP_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_SMP_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_SMP_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_SMP_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_BTIF_TRACE_LEVEL BTIF layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for BTIF layer Available options: NONE (CONFIG_BT_LOG_BTIF_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_BTIF_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_BTIF_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_BTIF_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_BTIF_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_BTIF_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_BTIF_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_BTC_TRACE_LEVEL BTC layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for BTC layer Available options: NONE (CONFIG_BT_LOG_BTC_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_BTC_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_BTC_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_BTC_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_BTC_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_BTC_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_BTC_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_OSI_TRACE_LEVEL OSI layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for OSI layer Available options: NONE (CONFIG_BT_LOG_OSI_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_OSI_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_OSI_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_OSI_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_OSI_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_OSI_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_OSI_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_BLUFI_TRACE_LEVEL BLUFI layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for BLUFI layer Available options: NONE (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_NONE) ERROR (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_ERROR) WARNING (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_WARNING) API (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_API) EVENT (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_EVENT) DEBUG (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_VERBOSE) CONFIG_BT_ACL_CONNECTIONS BT/BLE MAX ACL CONNECTIONS(1~9) Found in: Component config > Bluetooth > Bluedroid Options Maximum BT/BLE connection count. The ESP32-C3/S3 chip supports a maximum of 10 instances, including ADV, SCAN and connections. The ESP32-C3/S3 chip can connect up to 9 devices if ADV or SCAN uses only one. If ADV and SCAN are both used, The ESP32-C3/S3 chip is connected to a maximum of 8 devices. Because Bluetooth cannot reclaim used instances once ADV or SCAN is used. Range: from 1 to 9 if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED Default value: CONFIG_BT_MULTI_CONNECTION_ENBALE Enable BLE multi-conections Found in: Component config > Bluetooth > Bluedroid Options Enable this option if there are multiple connections Default value: Yes (enabled) if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_ALLOCATION_FROM_SPIRAM_FIRST BT/BLE will first malloc the memory from the PSRAM Found in: Component config > Bluetooth > Bluedroid Options This select can save the internal RAM if there have the PSRAM Default value: No (disabled) if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_DYNAMIC_ENV_MEMORY Use dynamic memory allocation in BT/BLE stack Found in: Component config > Bluetooth > Bluedroid Options This select can make the allocation of memory will become more flexible Default value: No (disabled) if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_HOST_QUEUE_CONG_CHECK BLE queue congestion check Found in: Component config > Bluetooth > Bluedroid Options When scanning and scan duplicate is not enabled, if there are a lot of adv packets around or application layer handling adv packets is slow, it will cause the controller memory to run out. if enabled, adv packets will be lost when host queue is congested. Default value: No (disabled) if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_SMP_MAX_BONDS BT/BLE maximum bond device count Found in: Component config > Bluetooth > Bluedroid Options The number of security records for peer devices. CONFIG_BT_BLE_ACT_SCAN_REP_ADV_SCAN Report adv data and scan response individually when BLE active scan Found in: Component config > Bluetooth > Bluedroid Options Originally, when doing BLE active scan, Bluedroid will not report adv to application layer until receive scan response. This option is used to disable the behavior. When enable this option, Bluedroid will report adv data or scan response to application layer immediately. # Memory reserved at start of DRAM for Bluetooth stack Default value: No (disabled) if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_ESTAB_LINK_CONN_TOUT Timeout of BLE connection establishment Found in: Component config > Bluetooth > Bluedroid Options Bluetooth Connection establishment maximum time, if connection time exceeds this value, the connection establishment fails, ESP_GATTC_OPEN_EVT or ESP_GATTS_OPEN_EVT is triggered. Range: from 1 to 60 if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED Default value: CONFIG_BT_MAX_DEVICE_NAME_LEN length of bluetooth device name Found in: Component config > Bluetooth > Bluedroid Options Bluetooth Device name length shall be no larger than 248 octets, If the broadcast data cannot contain the complete device name, then only the shortname will be displayed, the rest parts that can't fit in will be truncated. Range: from 32 to 248 if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED Default value: CONFIG_BT_BLE_RPA_SUPPORTED Update RPA to Controller Found in: Component config > Bluetooth > Bluedroid Options This enables controller RPA list function. For ESP32, ESP32 only support network privacy mode. If this option is enabled, ESP32 will only accept advertising packets from peer devices that contain private address, HW will not receive the advertising packets contain identity address after IRK changed. If this option is disabled, address resolution will be performed in the host, so the functions that require controller to resolve address in the white list cannot be used. This option is disabled by default on ESP32, please enable or disable this option according to your own needs. For other BLE chips, devices support network privacy mode and device privacy mode, users can switch the two modes according to their own needs. So this option is enabled by default. Default value: No (disabled) if CONFIG_BT_CONTROLLER_ENABLED && CONFIG_BT_BLUEDROID_ENABLED && (CONFIG_BT_CONTROLLER_ENABLED || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED Yes (enabled) if CONFIG_BT_CONTROLLER_DISABLED && CONFIG_BT_BLUEDROID_ENABLED && (CONFIG_BT_CONTROLLER_ENABLED || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_RPA_TIMEOUT Timeout of resolvable private address Found in: Component config > Bluetooth > Bluedroid Options This set RPA timeout of Controller and Host. Default is 900 s (15 minutes). Range is 1 s to 1 hour (3600 s). Range: from 1 to 3600 if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED Default value: CONFIG_BT_BLE_50_FEATURES_SUPPORTED Enable BLE 5.0 features Found in: Component config > Bluetooth > Bluedroid Options Enabling this option activates BLE 5.0 features. This option is universally supported in chips that support BLE, except for ESP32. Default value: Yes (enabled) if CONFIG_BT_BLE_ENABLED && ((CONFIG_BT_CONTROLLER_ENABLED && SOC_BLE_50_SUPPORTED) || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_42_FEATURES_SUPPORTED Enable BLE 4.2 features Found in: Component config > Bluetooth > Bluedroid Options This enables BLE 4.2 features. Default value: No (disabled) if CONFIG_BT_BLE_ENABLED && (CONFIG_BT_CONTROLLER_ENABLED || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_FEAT_PERIODIC_ADV_SYNC_TRANSFER Enable BLE periodic advertising sync transfer feature Found in: Component config > Bluetooth > Bluedroid Options This enables BLE periodic advertising sync transfer feature Default value: No (disabled) if CONFIG_BT_BLE_50_FEATURES_SUPPORTED && ((CONFIG_BT_CONTROLLER_ENABLED && SOC_ESP_NIMBLE_CONTROLLER) || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_FEAT_PERIODIC_ADV_ENH Enable periodic adv enhancements(adi support) Found in: Component config > Bluetooth > Bluedroid Options Enable the periodic advertising enhancements Default value: No (disabled) if CONFIG_BT_BLE_50_FEATURES_SUPPORTED && ((CONFIG_BT_CONTROLLER_ENABLED && SOC_ESP_NIMBLE_CONTROLLER) || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_FEAT_CREATE_SYNC_ENH Enable create sync enhancements(reporting disable and duplicate filtering enable support) Found in: Component config > Bluetooth > Bluedroid Options Enable the create sync enhancements Default value: No (disabled) if CONFIG_BT_BLE_50_FEATURES_SUPPORTED && ((CONFIG_BT_CONTROLLER_ENABLED && SOC_ESP_NIMBLE_CONTROLLER) || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_HIGH_DUTY_ADV_INTERVAL Enable BLE high duty advertising interval feature Found in: Component config > Bluetooth > Bluedroid Options This enable BLE high duty advertising interval feature Default value: No (disabled) if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED NimBLE Options Contains: CONFIG_BT_NIMBLE_MEM_ALLOC_MODE Memory allocation strategy Found in: Component config > Bluetooth > NimBLE Options Allocation strategy for NimBLE host stack, essentially provides ability to allocate all required dynamic allocations from, Internal DRAM memory only External SPIRAM memory only Either internal or external memory based on default malloc() behavior in ESP-IDF Internal IRAM memory wherever applicable else internal DRAM Available options: Internal memory (CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_INTERNAL) External SPIRAM (CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_EXTERNAL) Default alloc mode (CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_DEFAULT) Internal IRAM (CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_IRAM_8BIT) Allows to use IRAM memory region as 8bit accessible region. Every unaligned (8bit or 16bit) access will result in an exception and incur penalty of certain clock cycles per unaligned read/write. CONFIG_BT_NIMBLE_LOG_LEVEL NimBLE Host log verbosity Found in: Component config > Bluetooth > NimBLE Options Select NimBLE log level. Please make a note that the selected NimBLE log verbosity can not exceed the level set in "Component config --> Log output --> Default log verbosity". Available options: No logs (CONFIG_BT_NIMBLE_LOG_LEVEL_NONE) Error logs (CONFIG_BT_NIMBLE_LOG_LEVEL_ERROR) Warning logs (CONFIG_BT_NIMBLE_LOG_LEVEL_WARNING) Info logs (CONFIG_BT_NIMBLE_LOG_LEVEL_INFO) Debug logs (CONFIG_BT_NIMBLE_LOG_LEVEL_DEBUG) CONFIG_BT_NIMBLE_MAX_CONNECTIONS Maximum number of concurrent connections Found in: Component config > Bluetooth > NimBLE Options Defines maximum number of concurrent BLE connections. For ESP32, user is expected to configure BTDM_CTRL_BLE_MAX_CONN from controller menu along with this option. Similarly for ESP32-C3 or ESP32-S3, user is expected to configure BT_CTRL_BLE_MAX_ACT from controller menu. For ESP32C2, ESP32C6 and ESP32H2, each connection will take about 1k DRAM. Range: from 1 to 9 if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED Default value: CONFIG_BT_NIMBLE_MAX_BONDS Maximum number of bonds to save across reboots Found in: Component config > Bluetooth > NimBLE Options Defines maximum number of bonds to save for peer security and our security Default value: CONFIG_BT_NIMBLE_MAX_CCCDS Maximum number of CCC descriptors to save across reboots Found in: Component config > Bluetooth > NimBLE Options Defines maximum number of CCC descriptors to save Default value: CONFIG_BT_NIMBLE_L2CAP_COC_MAX_NUM Maximum number of connection oriented channels Found in: Component config > Bluetooth > NimBLE Options Defines maximum number of BLE Connection Oriented Channels. When set to (0), BLE COC is not compiled in Range: from 0 to 9 if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED Default value: CONFIG_BT_NIMBLE_PINNED_TO_CORE_CHOICE The CPU core on which NimBLE host will run Found in: Component config > Bluetooth > NimBLE Options The CPU core on which NimBLE host will run. You can choose Core 0 or Core 1. Cannot specify no-affinity Available options: Core 0 (PRO CPU) (CONFIG_BT_NIMBLE_PINNED_TO_CORE_0) Core 1 (APP CPU) (CONFIG_BT_NIMBLE_PINNED_TO_CORE_1) CONFIG_BT_NIMBLE_HOST_TASK_STACK_SIZE NimBLE Host task stack size Found in: Component config > Bluetooth > NimBLE Options This configures stack size of NimBLE host task Default value: 5120 if CONFIG_BLE_MESH && CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED 4096 if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_ROLE_CENTRAL Enable BLE Central role Found in: Component config > Bluetooth > NimBLE Options Enables central role Default value: Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_ROLE_PERIPHERAL Enable BLE Peripheral role Found in: Component config > Bluetooth > NimBLE Options Enable peripheral role Default value: Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_ROLE_BROADCASTER Enable BLE Broadcaster role Found in: Component config > Bluetooth > NimBLE Options Enables broadcaster role Default value: Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_ROLE_OBSERVER Enable BLE Observer role Found in: Component config > Bluetooth > NimBLE Options Enables observer role Default value: Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_NVS_PERSIST Persist the BLE Bonding keys in NVS Found in: Component config > Bluetooth > NimBLE Options Enable this flag to make bonding persistent across device reboots Default value: No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SECURITY_ENABLE Enable BLE SM feature Found in: Component config > Bluetooth > NimBLE Options Enable BLE sm feature Default value: Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED Contains: CONFIG_BT_NIMBLE_SM_LEGACY Security manager legacy pairing Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_SECURITY_ENABLE Enable security manager legacy pairing Default value: Yes (enabled) if CONFIG_BT_NIMBLE_SECURITY_ENABLE && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SM_SC Security manager secure connections (4.2) Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_SECURITY_ENABLE Enable security manager secure connections Default value: Yes (enabled) if CONFIG_BT_NIMBLE_SECURITY_ENABLE && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SM_SC_DEBUG_KEYS Use predefined public-private key pair Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_SECURITY_ENABLE > CONFIG_BT_NIMBLE_SM_SC If this option is enabled, SM uses predefined DH key pair as described in Core Specification, Vol. 3, Part H, 2.3.5.6.1. This allows to decrypt air traffic easily and thus should only be used for debugging. Default value: No (disabled) if CONFIG_BT_NIMBLE_SECURITY_ENABLE && CONFIG_BT_NIMBLE_SM_SC && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_LL_CFG_FEAT_LE_ENCRYPTION Enable LE encryption Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_SECURITY_ENABLE Enable encryption connection Default value: Yes (enabled) if CONFIG_BT_NIMBLE_SECURITY_ENABLE && CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SM_SC_LVL Security level Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_SECURITY_ENABLE LE Security Mode 1 Levels: 1. No Security 2. Unauthenticated pairing with encryption 3. Authenticated pairing with encryption 4. Authenticated LE Secure Connections pairing with encryption using a 128-bit strength encryption key. Default value: CONFIG_BT_NIMBLE_DEBUG Enable extra runtime asserts and host debugging Found in: Component config > Bluetooth > NimBLE Options This enables extra runtime asserts and host debugging Default value: No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_DYNAMIC_SERVICE Enable dynamic services Found in: Component config > Bluetooth > NimBLE Options This enables user to add/remove Gatt services at runtime CONFIG_BT_NIMBLE_SVC_GAP_DEVICE_NAME BLE GAP default device name Found in: Component config > Bluetooth > NimBLE Options The Device Name characteristic shall contain the name of the device as an UTF-8 string. This name can be changed by using API ble_svc_gap_device_name_set() Default value: "nimble" if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_GAP_DEVICE_NAME_MAX_LEN Maximum length of BLE device name in octets Found in: Component config > Bluetooth > NimBLE Options Device Name characteristic value shall be 0 to 248 octets in length Default value: CONFIG_BT_NIMBLE_ATT_PREFERRED_MTU Preferred MTU size in octets Found in: Component config > Bluetooth > NimBLE Options This is the default value of ATT MTU indicated by the device during an ATT MTU exchange. This value can be changed using API ble_att_set_preferred_mtu() Default value: CONFIG_BT_NIMBLE_SVC_GAP_APPEARANCE External appearance of the device Found in: Component config > Bluetooth > NimBLE Options Standard BLE GAP Appearance value in HEX format e.g. 0x02C0 Default value: Memory Settings Contains: CONFIG_BT_NIMBLE_MSYS_1_BLOCK_COUNT MSYS_1 Block Count Found in: Component config > Bluetooth > NimBLE Options > Memory Settings MSYS is a system level mbuf registry. For prepare write & prepare responses MBUFs are allocated out of msys_1 pool. For NIMBLE_MESH enabled cases, this block count is increased by 8 than user defined count. Default value: 24 if SOC_ESP_NIMBLE_CONTROLLER && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MSYS_1_BLOCK_SIZE MSYS_1 Block Size Found in: Component config > Bluetooth > NimBLE Options > Memory Settings Dynamic memory size of block 1 Default value: 128 if SOC_ESP_NIMBLE_CONTROLLER && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MSYS_2_BLOCK_COUNT MSYS_2 Block Count Found in: Component config > Bluetooth > NimBLE Options > Memory Settings Dynamic memory count Default value: 24 if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MSYS_2_BLOCK_SIZE MSYS_2 Block Size Found in: Component config > Bluetooth > NimBLE Options > Memory Settings Dynamic memory size of block 2 Default value: 320 if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MSYS_BUF_FROM_HEAP Get Msys Mbuf from heap Found in: Component config > Bluetooth > NimBLE Options > Memory Settings This option sets the source of the shared msys mbuf memory between the Host and the Controller. Allocate the memory from the heap if this option is sets, from the mempool otherwise. Default value: Yes (enabled) if BT_LE_MSYS_INIT_IN_CONTROLLER && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_TRANSPORT_ACL_FROM_LL_COUNT ACL Buffer count Found in: Component config > Bluetooth > NimBLE Options > Memory Settings The number of ACL data buffers allocated for host. Default value: CONFIG_BT_NIMBLE_TRANSPORT_ACL_SIZE Transport ACL Buffer size Found in: Component config > Bluetooth > NimBLE Options > Memory Settings This is the maximum size of the data portion of HCI ACL data packets. It does not include the HCI data header (of 4 bytes) Default value: CONFIG_BT_NIMBLE_TRANSPORT_EVT_SIZE Transport Event Buffer size Found in: Component config > Bluetooth > NimBLE Options > Memory Settings This is the size of each HCI event buffer in bytes. In case of extended advertising, packets can be fragmented. 257 bytes is the maximum size of a packet. Default value: CONFIG_BT_NIMBLE_TRANSPORT_EVT_COUNT Transport Event Buffer count Found in: Component config > Bluetooth > NimBLE Options > Memory Settings This is the high priority HCI events' buffer size. High-priority event buffers are for everything except advertising reports. If there are no free high-priority event buffers then host will try to allocate a low-priority buffer instead Default value: CONFIG_BT_NIMBLE_TRANSPORT_EVT_DISCARD_COUNT Discardable Transport Event Buffer count Found in: Component config > Bluetooth > NimBLE Options > Memory Settings This is the low priority HCI events' buffer size. Low-priority event buffers are only used for advertising reports. If there are no free low-priority event buffers, then an incoming advertising report will get dropped Default value: CONFIG_BT_NIMBLE_GATT_MAX_PROCS Maximum number of GATT client procedures Found in: Component config > Bluetooth > NimBLE Options Maximum number of GATT client procedures that can be executed. Default value: CONFIG_BT_NIMBLE_HS_FLOW_CTRL Enable Host Flow control Found in: Component config > Bluetooth > NimBLE Options Enable Host Flow control Default value: Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_HS_FLOW_CTRL_ITVL Host Flow control interval Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_HS_FLOW_CTRL Host flow control interval in msecs Default value: CONFIG_BT_NIMBLE_HS_FLOW_CTRL_THRESH Host Flow control threshold Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_HS_FLOW_CTRL Host flow control threshold, if the number of free buffers are at or below this threshold, send an immediate number-of-completed-packets event Default value: CONFIG_BT_NIMBLE_HS_FLOW_CTRL_TX_ON_DISCONNECT Host Flow control on disconnect Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_HS_FLOW_CTRL Enable this option to send number-of-completed-packets event to controller after disconnection Default value: Yes (enabled) if CONFIG_BT_NIMBLE_HS_FLOW_CTRL && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_RPA_TIMEOUT RPA timeout in seconds Found in: Component config > Bluetooth > NimBLE Options Time interval between RPA address change. This is applicable in case of Host based RPA Range: from 1 to 41400 if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED Default value: CONFIG_BT_NIMBLE_MESH Enable BLE mesh functionality Found in: Component config > Bluetooth > NimBLE Options Enable BLE Mesh example present in upstream mynewt-nimble and not maintained by Espressif. IDF maintains ESP-BLE-MESH as the official Mesh solution. Please refer to ESP-BLE-MESH guide at: :doc:../esp32/api-guides/esp-ble-mesh/ble-mesh-index`` Default value: No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED Contains: CONFIG_BT_NIMBLE_MESH_PROXY Enable mesh proxy functionality Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH Enable proxy. This is automatically set whenever NIMBLE_MESH_PB_GATT or NIMBLE_MESH_GATT_PROXY is set Default value: No (disabled) if CONFIG_BT_NIMBLE_MESH && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_PROV Enable BLE mesh provisioning Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH Enable mesh provisioning Default value: Yes (enabled) if CONFIG_BT_NIMBLE_MESH && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_PB_ADV Enable mesh provisioning over advertising bearer Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH > CONFIG_BT_NIMBLE_MESH_PROV Enable this option to allow the device to be provisioned over the advertising bearer Default value: Yes (enabled) if CONFIG_BT_NIMBLE_MESH_PROV && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_PB_GATT Enable mesh provisioning over GATT bearer Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH > CONFIG_BT_NIMBLE_MESH_PROV Enable this option to allow the device to be provisioned over the GATT bearer Default value: Yes (enabled) if CONFIG_BT_NIMBLE_MESH_PROV && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_GATT_PROXY Enable GATT Proxy functionality Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH This option enables support for the Mesh GATT Proxy Service, i.e. the ability to act as a proxy between a Mesh GATT Client and a Mesh network Default value: Yes (enabled) if CONFIG_BT_NIMBLE_MESH && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_RELAY Enable mesh relay functionality Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH Support for acting as a Mesh Relay Node Default value: No (disabled) if CONFIG_BT_NIMBLE_MESH && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_LOW_POWER Enable mesh low power mode Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH Enable this option to be able to act as a Low Power Node Default value: No (disabled) if CONFIG_BT_NIMBLE_MESH && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_FRIEND Enable mesh friend functionality Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH Enable this option to be able to act as a Friend Node Default value: No (disabled) if CONFIG_BT_NIMBLE_MESH && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_DEVICE_NAME Set mesh device name Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH This value defines Bluetooth Mesh device/node name Default value: "nimble-mesh-node" if CONFIG_BT_NIMBLE_MESH && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_NODE_COUNT Set mesh node count Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH Defines mesh node count. Default value: CONFIG_BT_NIMBLE_MESH_PROVISIONER Enable BLE mesh provisioner Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH Enable mesh provisioner. Default value: CONFIG_BT_NIMBLE_CRYPTO_STACK_MBEDTLS Override TinyCrypt with mbedTLS for crypto computations Found in: Component config > Bluetooth > NimBLE Options Enable this option to choose mbedTLS instead of TinyCrypt for crypto computations. Default value: Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_HS_STOP_TIMEOUT_MS BLE host stop timeout in msec Found in: Component config > Bluetooth > NimBLE Options BLE Host stop procedure timeout in milliseconds. Default value: 2000 if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_HOST_BASED_PRIVACY Enable host based privacy for random address. Found in: Component config > Bluetooth > NimBLE Options Use this option to do host based Random Private Address resolution. If this option is disabled then controller based privacy is used. Default value: No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_ENABLE_CONN_REATTEMPT Enable connection reattempts on connection establishment error Found in: Component config > Bluetooth > NimBLE Options Enable to make the NimBLE host to reattempt GAP connection on connection establishment failure. Default value: Yes (enabled) if SOC_ESP_NIMBLE_CONTROLLER && CONFIG_BT_NIMBLE_ENABLED No (disabled) if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MAX_CONN_REATTEMPT Maximum number connection reattempts Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_ENABLE_CONN_REATTEMPT Defines maximum number of connection reattempts. Range: from 1 to 7 if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLE_CONN_REATTEMPT && CONFIG_BT_NIMBLE_ENABLED Default value: CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Enable BLE 5 feature Found in: Component config > Bluetooth > NimBLE Options Enable BLE 5 feature Default value: Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && SOC_BLE_50_SUPPORTED && CONFIG_BT_NIMBLE_ENABLED Contains: CONFIG_BT_NIMBLE_LL_CFG_FEAT_LE_2M_PHY Enable 2M Phy Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Enable 2M-PHY Default value: Yes (enabled) if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_LL_CFG_FEAT_LE_CODED_PHY Enable coded Phy Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Enable coded-PHY Default value: Yes (enabled) if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_EXT_ADV Enable extended advertising Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Enable this option to do extended advertising. Extended advertising will be supported from BLE 5.0 onwards. Default value: No (disabled) if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MAX_EXT_ADV_INSTANCES Maximum number of extended advertising instances. Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_EXT_ADV Change this option to set maximum number of extended advertising instances. Minimum there is always one instance of advertising. Enter how many more advertising instances you want. For ESP32C2, ESP32C6 and ESP32H2, each extended advertising instance will take about 0.5k DRAM. Range: from 0 to 4 if CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_ENABLED Default value: CONFIG_BT_NIMBLE_EXT_ADV_MAX_SIZE Maximum length of the advertising data. Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_EXT_ADV Defines the length of the extended adv data. The value should not exceed 1650. Range: from 0 to 1650 if CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_ENABLED Default value: CONFIG_BT_NIMBLE_ENABLE_PERIODIC_ADV Enable periodic advertisement. Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_EXT_ADV Enable this option to start periodic advertisement. Default value: Yes (enabled) if CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_PERIODIC_ADV_SYNC_TRANSFER Enable Transer Sync Events Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_EXT_ADV > CONFIG_BT_NIMBLE_ENABLE_PERIODIC_ADV This enables controller transfer periodic sync events to host Default value: Yes (enabled) if CONFIG_BT_NIMBLE_ENABLE_PERIODIC_ADV && CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MAX_PERIODIC_SYNCS Maximum number of periodic advertising syncs Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Set this option to set the upper limit for number of periodic sync connections. This should be less than maximum connections allowed by controller. Range: from 0 to 8 if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && CONFIG_BT_NIMBLE_ENABLED Default value: CONFIG_BT_NIMBLE_MAX_PERIODIC_ADVERTISER_LIST Maximum number of periodic advertiser list Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Set this option to set the upper limit for number of periodic advertiser list. Range: from 1 to 5 if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && SOC_ESP_NIMBLE_CONTROLLER && CONFIG_BT_NIMBLE_ENABLED Default value: 5 if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && SOC_ESP_NIMBLE_CONTROLLER && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_BLE_POWER_CONTROL Enable support for BLE Power Control Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Set this option to enable the Power Control feature Default value: No (disabled) if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && SOC_BLE_POWER_CONTROL_SUPPORTED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_PERIODIC_ADV_ENH Periodic adv enhancements(adi support) Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Enable the periodic advertising enhancements CONFIG_BT_NIMBLE_GATT_CACHING Enable GATT caching Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Enable GATT caching Contains: CONFIG_BT_NIMBLE_GATT_CACHING_MAX_CONNS Maximum connections to be cached Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_GATT_CACHING Set this option to set the upper limit on number of connections to be cached. Default value: CONFIG_BT_NIMBLE_GATT_CACHING_MAX_SVCS Maximum number of services per connection Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_GATT_CACHING Set this option to set the upper limit on number of services per connection to be cached. Default value: CONFIG_BT_NIMBLE_GATT_CACHING_MAX_CHRS Maximum number of characteristics per connection Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_GATT_CACHING Set this option to set the upper limit on number of characteristics per connection to be cached. Default value: CONFIG_BT_NIMBLE_GATT_CACHING_MAX_DSCS Maximum number of descriptors per connection Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_GATT_CACHING Set this option to set the upper limit on number of discriptors per connection to be cached. Default value: CONFIG_BT_NIMBLE_WHITELIST_SIZE BLE white list size Found in: Component config > Bluetooth > NimBLE Options BLE list size Range: from 1 to 15 if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED Default value: CONFIG_BT_NIMBLE_TEST_THROUGHPUT_TEST Throughput Test Mode enable Found in: Component config > Bluetooth > NimBLE Options Enable the throughput test mode Default value: No (disabled) if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_BLUFI_ENABLE Enable blufi functionality Found in: Component config > Bluetooth > NimBLE Options Set this option to enable blufi functionality. Default value: No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_USE_ESP_TIMER Enable Esp Timer for Nimble Found in: Component config > Bluetooth > NimBLE Options Set this option to use Esp Timer which has higher priority timer instead of FreeRTOS timer Default value: Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_BLE_GATT_BLOB_TRANSFER Blob transfer Found in: Component config > Bluetooth > NimBLE Options This option is used when data to be sent is more than 512 bytes. For peripheral role, BT_NIMBLE_MSYS_1_BLOCK_COUNT needs to be increased according to the need. GAP Service Contains: GAP Appearance write permissions Contains: CONFIG_BT_NIMBLE_SVC_GAP_APPEAR_WRITE Write Found in: Component config > Bluetooth > NimBLE Options > GAP Service > GAP Appearance write permissions Enable write permission (BLE_GATT_CHR_F_WRITE) Default value: No (disabled) if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SVC_GAP_APPEAR_WRITE_ENC Write with encryption Found in: Component config > Bluetooth > NimBLE Options > GAP Service > GAP Appearance write permissions > CONFIG_BT_NIMBLE_SVC_GAP_APPEAR_WRITE Enable write with encryption permission (BLE_GATT_CHR_F_WRITE_ENC) Default value: No (disabled) if CONFIG_BT_NIMBLE_SVC_GAP_APPEAR_WRITE && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SVC_GAP_APPEAR_WRITE_AUTHEN Write with authentication Found in: Component config > Bluetooth > NimBLE Options > GAP Service > GAP Appearance write permissions > CONFIG_BT_NIMBLE_SVC_GAP_APPEAR_WRITE Enable write with authentication permission (BLE_GATT_CHR_F_WRITE_AUTHEN) Default value: No (disabled) if CONFIG_BT_NIMBLE_SVC_GAP_APPEAR_WRITE && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SVC_GAP_CENT_ADDR_RESOLUTION GAP Characteristic - Central Address Resolution Found in: Component config > Bluetooth > NimBLE Options > GAP Service Weather or not Central Address Resolution characteristic is supported on the device, and if supported, weather or not Central Address Resolution is supported. Central Address Resolution characteristic not supported Central Address Resolution not supported Central Address Resolution supported Available options: Characteristic not supported (CONFIG_BT_NIMBLE_SVC_GAP_CAR_CHAR_NOT_SUPP) Central Address Resolution not supported (CONFIG_BT_NIMBLE_SVC_GAP_CAR_NOT_SUPP) Central Address Resolution supported (CONFIG_BT_NIMBLE_SVC_GAP_CAR_SUPP) GAP device name write permissions Contains: CONFIG_BT_NIMBLE_SVC_GAP_NAME_WRITE Write Found in: Component config > Bluetooth > NimBLE Options > GAP Service > GAP device name write permissions Enable write permission (BLE_GATT_CHR_F_WRITE) Default value: No (disabled) if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SVC_GAP_NAME_WRITE_ENC Write with encryption Found in: Component config > Bluetooth > NimBLE Options > GAP Service > GAP device name write permissions > CONFIG_BT_NIMBLE_SVC_GAP_NAME_WRITE Enable write with encryption permission (BLE_GATT_CHR_F_WRITE_ENC) Default value: No (disabled) if CONFIG_BT_NIMBLE_SVC_GAP_NAME_WRITE && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SVC_GAP_NAME_WRITE_AUTHEN Write with authentication Found in: Component config > Bluetooth > NimBLE Options > GAP Service > GAP device name write permissions > CONFIG_BT_NIMBLE_SVC_GAP_NAME_WRITE Enable write with authentication permission (BLE_GATT_CHR_F_WRITE_AUTHEN) Default value: No (disabled) if CONFIG_BT_NIMBLE_SVC_GAP_NAME_WRITE && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SVC_GAP_PPCP_MAX_CONN_INTERVAL PPCP Connection Interval Max (Unit: 1.25 ms) Found in: Component config > Bluetooth > NimBLE Options > GAP Service Peripheral Preferred Connection Parameter: Connection Interval maximum value Interval Max = value * 1.25 ms Default value: CONFIG_BT_NIMBLE_SVC_GAP_PPCP_MIN_CONN_INTERVAL PPCP Connection Interval Min (Unit: 1.25 ms) Found in: Component config > Bluetooth > NimBLE Options > GAP Service Peripheral Preferred Connection Parameter: Connection Interval minimum value Interval Min = value * 1.25 ms Default value: CONFIG_BT_NIMBLE_SVC_GAP_PPCP_SLAVE_LATENCY PPCP Slave Latency Found in: Component config > Bluetooth > NimBLE Options > GAP Service Peripheral Preferred Connection Parameter: Slave Latency Default value: CONFIG_BT_NIMBLE_SVC_GAP_PPCP_SUPERVISION_TMO PPCP Supervision Timeout (Uint: 10 ms) Found in: Component config > Bluetooth > NimBLE Options > GAP Service Peripheral Preferred Connection Parameter: Supervision Timeout Timeout = Value * 10 ms Default value: BLE Services Contains: CONFIG_BT_NIMBLE_HID_SERVICE HID service Found in: Component config > Bluetooth > NimBLE Options > BLE Services Enable HID service support Default value: No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED Contains: CONFIG_BT_NIMBLE_SVC_HID_MAX_INSTANCES Maximum HID service instances Found in: Component config > Bluetooth > NimBLE Options > BLE Services > CONFIG_BT_NIMBLE_HID_SERVICE Defines maximum number of HID service instances Default value: CONFIG_BT_NIMBLE_SVC_HID_MAX_RPTS Maximum HID Report characteristics per service instance Found in: Component config > Bluetooth > NimBLE Options > BLE Services > CONFIG_BT_NIMBLE_HID_SERVICE Defines maximum number of report characteristics per service instance Default value: CONFIG_BT_NIMBLE_VS_SUPPORT Enable support for VSC and VSE Found in: Component config > Bluetooth > NimBLE Options This option is used to enable support for sending Vendor Specific HCI commands and handling Vendor Specific HCI Events. CONFIG_BT_NIMBLE_OPTIMIZE_MULTI_CONN Enable the optimization of multi-connection Found in: Component config > Bluetooth > NimBLE Options This option enables the use of vendor-specific APIs for multi-connections, which can greatly enhance the stability of coexistence between numerous central and peripheral devices. It will prohibit the usage of standard APIs. Default value: No (disabled) if SOC_BLE_MULTI_CONN_OPTIMIZATION && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_ENC_ADV_DATA Encrypted Advertising Data Found in: Component config > Bluetooth > NimBLE Options This option is used to enable encrypted advertising data. CONFIG_BT_NIMBLE_MAX_EADS Maximum number of EAD devices to save across reboots Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_ENC_ADV_DATA Defines maximum number of encrypted advertising data key material to save Default value: CONFIG_BT_NIMBLE_HIGH_DUTY_ADV_ITVL Enable BLE high duty advertising interval feature Found in: Component config > Bluetooth > NimBLE Options This enable BLE high duty advertising interval feature CONFIG_BT_NIMBLE_HOST_QUEUE_CONG_CHECK BLE queue congestion check Found in: Component config > Bluetooth > NimBLE Options When scanning and scan duplicate is not enabled, if there are a lot of adv packets around or application layer handling adv packets is slow, it will cause the controller memory to run out. if enabled, adv packets will be lost when host queue is congested. Default value: No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED Host-controller Transport Contains: CONFIG_BT_NIMBLE_TRANSPORT_UART Enable Uart Transport Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport Use UART transport Default value: Yes (enabled) if CONFIG_BT_CONTROLLER_DISABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_TRANSPORT_UART_PORT Uart port Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport > CONFIG_BT_NIMBLE_TRANSPORT_UART Uart port Default value: CONFIG_BT_NIMBLE_USE_HCI_UART_PARITY Uart PARITY Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport Uart Parity Available options: None (CONFIG_UART_PARITY_NONE) Odd (CONFIG_UART_PARITY_ODD) Even (CONFIG_UART_PARITY_EVEN) CONFIG_BT_NIMBLE_UART_RX_PIN UART Rx pin Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport Rx pin for Nimble Transport Default value: CONFIG_BT_NIMBLE_UART_TX_PIN UART Tx pin Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport Tx pin for Nimble Transport Default value: CONFIG_BT_NIMBLE_USE_HCI_UART_FLOW_CTRL Uart Flow Control Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport Uart Flow Control Available options: Disable (CONFIG_UART_HW_FLOWCTRL_DISABLE) Enable hardware flow control (CONFIG_UART_HW_FLOWCTRL_CTS_RTS) CONFIG_BT_NIMBLE_HCI_UART_RTS_PIN UART Rts Pin Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport UART HCI RTS pin Default value: 19 if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_HCI_UART_CTS_PIN UART Cts Pin Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport UART HCI CTS pin Default value: 23 if CONFIG_BT_NIMBLE_ENABLED Controller Options Contains: CONFIG_BTDM_CTRL_MODE Bluetooth controller mode (BR/EDR/BLE/DUALMODE) Found in: Component config > Bluetooth > Controller Options Specify the bluetooth controller mode (BR/EDR, BLE or dual mode). Available options: BLE Only (CONFIG_BTDM_CTRL_MODE_BLE_ONLY) BR/EDR Only (CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY) Bluetooth Dual Mode (CONFIG_BTDM_CTRL_MODE_BTDM) CONFIG_BTDM_CTRL_BLE_MAX_CONN BLE Max Connections Found in: Component config > Bluetooth > Controller Options BLE maximum connections of bluetooth controller. Each connection uses 1KB static DRAM whenever the BT controller is enabled. Range: from 1 to 9 if (CONFIG_BTDM_CTRL_MODE_BLE_ONLY || CONFIG_BTDM_CTRL_MODE_BTDM) && CONFIG_BT_CONTROLLER_ENABLED Default value: CONFIG_BTDM_CTRL_BR_EDR_MAX_ACL_CONN BR/EDR ACL Max Connections Found in: Component config > Bluetooth > Controller Options BR/EDR ACL maximum connections of bluetooth controller. Each connection uses 1.2 KB DRAM whenever the BT controller is enabled. Range: from 1 to 7 if (CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY || CONFIG_BTDM_CTRL_MODE_BTDM) && CONFIG_BT_CONTROLLER_ENABLED Default value: CONFIG_BTDM_CTRL_BR_EDR_MAX_SYNC_CONN BR/EDR Sync(SCO/eSCO) Max Connections Found in: Component config > Bluetooth > Controller Options BR/EDR Synchronize maximum connections of bluetooth controller. Each connection uses 2 KB DRAM whenever the BT controller is enabled. Range: from 0 to 3 if (CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY || CONFIG_BTDM_CTRL_MODE_BTDM) && CONFIG_BT_CONTROLLER_ENABLED Default value: CONFIG_BTDM_CTRL_BR_EDR_SCO_DATA_PATH BR/EDR Sync(SCO/eSCO) default data path Found in: Component config > Bluetooth > Controller Options SCO data path, i.e. HCI or PCM. SCO data can be sent/received through HCI synchronous packets, or the data can be routed to on-chip PCM module on ESP32. PCM input/output signals can be "matrixed" to GPIOs. The default data path can also be set using API "esp_bredr_sco_datapath_set" Available options: HCI (CONFIG_BTDM_CTRL_BR_EDR_SCO_DATA_PATH_HCI) PCM (CONFIG_BTDM_CTRL_BR_EDR_SCO_DATA_PATH_PCM) CONFIG_BTDM_CTRL_PCM_ROLE_EDGE_CONFIG PCM Signal Config (Role and Polar) Found in: Component config > Bluetooth > Controller Options Default value: Yes (enabled) if CONFIG_BTDM_CTRL_BR_EDR_SCO_DATA_PATH_PCM && CONFIG_BT_CONTROLLER_ENABLED Contains: CONFIG_BTDM_CTRL_PCM_ROLE PCM Role Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_CTRL_PCM_ROLE_EDGE_CONFIG PCM role can be configured as PCM master or PCM slave Available options: PCM Master (CONFIG_BTDM_CTRL_PCM_ROLE_MASTER) PCM Slave (CONFIG_BTDM_CTRL_PCM_ROLE_SLAVE) CONFIG_BTDM_CTRL_PCM_POLAR PCM Polar Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_CTRL_PCM_ROLE_EDGE_CONFIG PCM polarity can be configured as Falling Edge or Rising Edge Available options: Falling Edge (CONFIG_BTDM_CTRL_PCM_POLAR_FALLING_EDGE) Rising Edge (CONFIG_BTDM_CTRL_PCM_POLAR_RISING_EDGE) CONFIG_BTDM_CTRL_AUTO_LATENCY Auto latency Found in: Component config > Bluetooth > Controller Options BLE auto latency, used to enhance classic BT performance while classic BT and BLE are enabled at the same time. Default value: No (disabled) if CONFIG_BTDM_CTRL_MODE_BTDM && CONFIG_BT_CONTROLLER_ENABLED CONFIG_BTDM_CTRL_LEGACY_AUTH_VENDOR_EVT Legacy Authentication Vendor Specific Event Enable Found in: Component config > Bluetooth > Controller Options To protect from BIAS attack during Legacy authentication, Legacy authentication Vendor specific event should be enabled Default value: Yes (enabled) if (CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY || CONFIG_BTDM_CTRL_MODE_BTDM) && CONFIG_BT_CONTROLLER_ENABLED CONFIG_BTDM_CTRL_PINNED_TO_CORE_CHOICE The cpu core which bluetooth controller run Found in: Component config > Bluetooth > Controller Options Specify the cpu core to run bluetooth controller. Can not specify no-affinity. Available options: Core 0 (PRO CPU) (CONFIG_BTDM_CTRL_PINNED_TO_CORE_0) Core 1 (APP CPU) (CONFIG_BTDM_CTRL_PINNED_TO_CORE_1) CONFIG_BTDM_CTRL_HCI_MODE_CHOICE HCI mode Found in: Component config > Bluetooth > Controller Options Speicify HCI mode as VHCI or UART(H4) Available options: VHCI (CONFIG_BTDM_CTRL_HCI_MODE_VHCI) Normal option. Mostly, choose this VHCI when bluetooth host run on ESP32, too. UART(H4) (CONFIG_BTDM_CTRL_HCI_MODE_UART_H4) If use external bluetooth host which run on other hardware and use UART as the HCI interface, choose this option. HCI UART(H4) Options Contains: CONFIG_BTDM_CTRL_HCI_UART_NO UART Number for HCI Found in: Component config > Bluetooth > Controller Options > HCI UART(H4) Options Uart number for HCI. The available uart is UART1 and UART2. Range: from 1 to 2 if CONFIG_BTDM_CTRL_HCI_MODE_UART_H4 && CONFIG_BT_CONTROLLER_ENABLED Default value: CONFIG_BTDM_CTRL_HCI_UART_BAUDRATE UART Baudrate for HCI Found in: Component config > Bluetooth > Controller Options > HCI UART(H4) Options UART Baudrate for HCI. Please use standard baudrate. Range: from 115200 to 921600 if CONFIG_BTDM_CTRL_HCI_MODE_UART_H4 && CONFIG_BT_CONTROLLER_ENABLED Default value: CONFIG_BTDM_CTRL_HCI_UART_FLOW_CTRL_EN Enable UART flow control Found in: Component config > Bluetooth > Controller Options > HCI UART(H4) Options Default value: Yes (enabled) if CONFIG_BTDM_CTRL_HCI_MODE_UART_H4 && CONFIG_BT_CONTROLLER_ENABLED MODEM SLEEP Options Contains: CONFIG_BTDM_CTRL_MODEM_SLEEP Bluetooth modem sleep Found in: Component config > Bluetooth > Controller Options > MODEM SLEEP Options Enable/disable bluetooth controller low power mode. Default value: Yes (enabled) if CONFIG_BT_CONTROLLER_ENABLED CONFIG_BTDM_CTRL_MODEM_SLEEP_MODE Bluetooth Modem sleep mode Found in: Component config > Bluetooth > Controller Options > MODEM SLEEP Options > CONFIG_BTDM_CTRL_MODEM_SLEEP To select which strategy to use for modem sleep Available options: ORIG Mode(sleep with low power clock) (CONFIG_BTDM_CTRL_MODEM_SLEEP_MODE_ORIG) ORIG mode is a bluetooth sleep mode that can be used for dual mode controller. In this mode, bluetooth controller sleeps between BR/EDR frames and BLE events. A low power clock is used to maintain bluetooth reference clock. EVED Mode(For internal test only) (CONFIG_BTDM_CTRL_MODEM_SLEEP_MODE_EVED) EVED mode is for BLE only and is only for internal test. Do not use it for production. this mode is not compatible with DFS nor light sleep CONFIG_BTDM_CTRL_LOW_POWER_CLOCK Bluetooth low power clock Found in: Component config > Bluetooth > Controller Options > MODEM SLEEP Options Select the low power clock source for bluetooth controller. Bluetooth low power clock is the clock source to maintain time in sleep mode. "Main crystal" option provides good accuracy and can support Dynamic Frequency Scaling to be used with Bluetooth modem sleep. Light sleep is not supported. "External 32kHz crystal" option allows user to use a 32.768kHz crystal as Bluetooth low power clock. This option is allowed as long as External 32kHz crystal is configured as the system RTC clock source. This option provides good accuracy and supports Bluetooth modem sleep to be used alongside Dynamic Frequency Scaling or light sleep. Available options: Main crystal (CONFIG_BTDM_CTRL_LPCLK_SEL_MAIN_XTAL) Main crystal can be used as low power clock for bluetooth modem sleep. If this option is selected, bluetooth modem sleep can work under Dynamic Frequency Scaling(DFS) enabled, but cannot work when light sleep is enabled. Main crystal has a good performance in accuracy as the bluetooth low power clock source. External 32kHz crystal (CONFIG_BTDM_CTRL_LPCLK_SEL_EXT_32K_XTAL) External 32kHz crystal has a nominal frequency of 32.768kHz and provides good frequency stability. If used as Bluetooth low power clock, External 32kHz can support Bluetooth modem sleep to be used with both DFS and light sleep. CONFIG_BTDM_BLE_SLEEP_CLOCK_ACCURACY BLE Sleep Clock Accuracy Found in: Component config > Bluetooth > Controller Options BLE Sleep Clock Accuracy(SCA) for the local device is used to estimate window widening in BLE connection events. With a lower level of clock accuracy(e.g. 500ppm over 250ppm), the slave needs a larger RX window to synchronize with master in each anchor point, thus resulting in an increase of power consumption but a higher level of robustness in keeping connected. According to the requirements of Bluetooth Core specification 4.2, the worst-case accuracy of Classic Bluetooth low power oscialltor(LPO) is +/-250ppm in STANDBY and in low power modes such as sniff. For BLE the worst-case SCA is +/-500ppm. "151ppm to 250ppm" option is the default value for Bluetooth Dual mode "251ppm to 500ppm" option can be used in BLE only mode when using external 32kHz crystal as low power clock. This option is provided in case that BLE sleep clock has a lower level of accuracy, or other error sources contribute to the inaccurate timing during sleep. Available options: 251ppm to 500ppm (CONFIG_BTDM_BLE_DEFAULT_SCA_500PPM) 151ppm to 250ppm (CONFIG_BTDM_BLE_DEFAULT_SCA_250PPM) CONFIG_BTDM_BLE_SCAN_DUPL BLE Scan Duplicate Options Found in: Component config > Bluetooth > Controller Options This select enables parameters setting of BLE scan duplicate. Default value: Yes (enabled) if (CONFIG_BTDM_CTRL_MODE_BTDM || CONFIG_BTDM_CTRL_MODE_BLE_ONLY) && CONFIG_BT_CONTROLLER_ENABLED CONFIG_BTDM_SCAN_DUPL_TYPE Scan Duplicate Type Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_SCAN_DUPL Scan duplicate have three ways. one is "Scan Duplicate By Device Address", This way is to use advertiser address filtering. The adv packet of the same address is only allowed to be reported once. Another way is "Scan Duplicate By Device Address And Advertising Data". This way is to use advertising data and device address filtering. All different adv packets with the same address are allowed to be reported. The last way is "Scan Duplicate By Advertising Data". This way is to use advertising data filtering. All same advertising data only allow to be reported once even though they are from different devices. Available options: Scan Duplicate By Device Address (CONFIG_BTDM_SCAN_DUPL_TYPE_DEVICE) This way is to use advertiser address filtering. The adv packet of the same address is only allowed to be reported once Scan Duplicate By Advertising Data (CONFIG_BTDM_SCAN_DUPL_TYPE_DATA) This way is to use advertising data filtering. All same advertising data only allow to be reported once even though they are from different devices. Scan Duplicate By Device Address And Advertising Data (CONFIG_BTDM_SCAN_DUPL_TYPE_DATA_DEVICE) This way is to use advertising data and device address filtering. All different adv packets with the same address are allowed to be reported. CONFIG_BTDM_SCAN_DUPL_CACHE_SIZE Maximum number of devices in scan duplicate filter Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_SCAN_DUPL Maximum number of devices which can be recorded in scan duplicate filter. When the maximum amount of device in the filter is reached, the oldest device will be refreshed. Range: from 10 to 1000 if CONFIG_BTDM_BLE_SCAN_DUPL && CONFIG_BT_CONTROLLER_ENABLED Default value: CONFIG_BTDM_SCAN_DUPL_CACHE_REFRESH_PERIOD Duplicate scan list refresh period (seconds) Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_SCAN_DUPL If the period value is non-zero, the controller will periodically clear the device information stored in the scan duuplicate filter. If it is 0, the scan duuplicate filter will not be cleared until the scanning is disabled. Duplicate advertisements for this period should not be sent to the Host in advertising report events. There are two scenarios where the ADV packet will be repeatedly reported: 1. The duplicate scan cache is full, the controller will delete the oldest device information and add new device information. 2. When the refresh period is up, the controller will clear all device information and start filtering again. Range: from 0 to 1000 if CONFIG_BTDM_BLE_SCAN_DUPL && CONFIG_BT_CONTROLLER_ENABLED Default value: CONFIG_BTDM_BLE_MESH_SCAN_DUPL_EN Special duplicate scan mechanism for BLE Mesh scan Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_SCAN_DUPL This enables the BLE scan duplicate for special BLE Mesh scan. Default value: No (disabled) if CONFIG_BTDM_BLE_SCAN_DUPL && CONFIG_BT_CONTROLLER_ENABLED CONFIG_BTDM_MESH_DUPL_SCAN_CACHE_SIZE Maximum number of Mesh adv packets in scan duplicate filter Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_SCAN_DUPL > CONFIG_BTDM_BLE_MESH_SCAN_DUPL_EN Maximum number of adv packets which can be recorded in duplicate scan cache for BLE Mesh. When the maximum amount of device in the filter is reached, the cache will be refreshed. Range: from 10 to 1000 if CONFIG_BTDM_BLE_MESH_SCAN_DUPL_EN && CONFIG_BT_CONTROLLER_ENABLED Default value: CONFIG_BTDM_CTRL_FULL_SCAN_SUPPORTED BLE full scan feature supported Found in: Component config > Bluetooth > Controller Options The full scan function is mainly used to provide BLE scan performance. This is required for scenes with high scan performance requirements, such as BLE Mesh scenes. Default value: Yes (enabled) if (CONFIG_BTDM_CTRL_MODE_BLE_ONLY || CONFIG_BTDM_CTRL_MODE_BTDM) && CONFIG_BT_CONTROLLER_ENABLED CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP BLE adv report flow control supported Found in: Component config > Bluetooth > Controller Options The function is mainly used to enable flow control for advertising reports. When it is enabled, advertising reports will be discarded by the controller if the number of unprocessed advertising reports exceeds the size of BLE adv report flow control. Default value: Yes (enabled) if (CONFIG_BTDM_CTRL_MODE_BTDM || CONFIG_BTDM_CTRL_MODE_BLE_ONLY) && CONFIG_BT_CONTROLLER_ENABLED CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_NUM BLE adv report flow control number Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP The number of unprocessed advertising report that Bluedroid can save.If you set BTDM_BLE_ADV_REPORT_FLOW_CTRL_NUM to a small value, this may cause adv packets lost. If you set BTDM_BLE_ADV_REPORT_FLOW_CTRL_NUM to a large value, Bluedroid may cache a lot of adv packets and this may cause system memory run out. For example, if you set it to 50, the maximum memory consumed by host is 35 * 50 bytes. Please set BTDM_BLE_ADV_REPORT_FLOW_CTRL_NUM according to your system free memory and handle adv packets as fast as possible, otherwise it will cause adv packets lost. Range: from 50 to 1000 if CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP && CONFIG_BT_CONTROLLER_ENABLED Default value: CONFIG_BTDM_BLE_ADV_REPORT_DISCARD_THRSHOLD BLE adv lost event threshold value Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP When adv report flow control is enabled, The ADV lost event will be generated when the number of ADV packets lost in the controller reaches this threshold. It is better to set a larger value. If you set BTDM_BLE_ADV_REPORT_DISCARD_THRSHOLD to a small value or printf every adv lost event, it may cause adv packets lost more. Range: from 1 to 1000 if CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP && CONFIG_BT_CONTROLLER_ENABLED Default value: CONFIG_BTDM_CTRL_HLI High level interrupt Found in: Component config > Bluetooth > Controller Options Using Level 4 interrupt for Bluetooth. Default value: Yes (enabled) if CONFIG_BT_ENABLED && CONFIG_BT_CONTROLLER_ENABLED CONFIG_BT_RELEASE_IRAM Release Bluetooth text (READ DOCS FIRST) Found in: Component config > Bluetooth This option release Bluetooth text section and merge Bluetooth data, bss & text into a large free heap region when esp_bt_mem_release is called, total saving ~21kB or more of IRAM. ESP32-C2 only 3 configurable PMP entries available, rest of them are hard-coded. We cannot split the memory into 3 different regions (IRAM, BLE-IRAM, DRAM). So this option will disable the PMP (ESP_SYSTEM_PMP_IDRAM_SPLIT) Default value: No (disabled) if CONFIG_BT_ENABLED && BT_LE_RELEASE_IRAM_SUPPORTED CONFIG_BLE_MESH ESP BLE Mesh Support Found in: Component config This option enables ESP BLE Mesh support. The specific features that are available may depend on other features that have been enabled in the stack, such as Bluetooth Support, Bluedroid Support & GATT support. Contains: CONFIG_BLE_MESH_HCI_5_0 Support sending 20ms non-connectable adv packets Found in: Component config > CONFIG_BLE_MESH It is a temporary solution and needs further modifications. Default value: Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_RANDOM_ADV_INTERVAL Support using random adv interval for mesh packets Found in: Component config > CONFIG_BLE_MESH Enable this option to allow using random advertising interval for mesh packets. And this could help avoid collision of advertising packets. Default value: No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_USE_DUPLICATE_SCAN Support Duplicate Scan in BLE Mesh Found in: Component config > CONFIG_BLE_MESH Enable this option to allow using specific duplicate scan filter in BLE Mesh, and Scan Duplicate Type must be set by choosing the option in the Bluetooth Controller section in menuconfig, which is "Scan Duplicate By Device Address and Advertising Data". Default value: Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_ACTIVE_SCAN Support Active Scan in BLE Mesh Found in: Component config > CONFIG_BLE_MESH Enable this option to allow using BLE Active Scan for BLE Mesh. CONFIG_BLE_MESH_MEM_ALLOC_MODE Memory allocation strategy Found in: Component config > CONFIG_BLE_MESH Allocation strategy for BLE Mesh stack, essentially provides ability to allocate all required dynamic allocations from, Internal DRAM memory only External SPIRAM memory only Either internal or external memory based on default malloc() behavior in ESP-IDF Internal IRAM memory wherever applicable else internal DRAM Recommended mode here is always internal (*), since that is most preferred from security perspective. But if application requirement does not allow sufficient free internal memory then alternate mode can be selected. (*) In case of ESP32-S2/ESP32-S3, hardware allows encryption of external SPIRAM contents provided hardware flash encryption feature is enabled. In that case, using external SPIRAM allocation strategy is also safe choice from security perspective. Available options: Internal DRAM (CONFIG_BLE_MESH_MEM_ALLOC_MODE_INTERNAL) External SPIRAM (CONFIG_BLE_MESH_MEM_ALLOC_MODE_EXTERNAL) Default alloc mode (CONFIG_BLE_MESH_MEM_ALLOC_MODE_DEFAULT) Enable this option to use the default memory allocation strategy when external SPIRAM is enabled. See the SPIRAM options for more details. Internal IRAM (CONFIG_BLE_MESH_MEM_ALLOC_MODE_IRAM_8BIT) Allows to use IRAM memory region as 8bit accessible region. Every unaligned (8bit or 16bit) access will result in an exception and incur penalty of certain clock cycles per unaligned read/write. CONFIG_BLE_MESH_FREERTOS_STATIC_ALLOC Enable FreeRTOS static allocation Found in: Component config > CONFIG_BLE_MESH Enable this option to use FreeRTOS static allocation APIs for BLE Mesh, which provides the ability to use different dynamic memory (i.e. SPIRAM or IRAM) for FreeRTOS objects. If this option is disabled, the FreeRTOS static allocation APIs will not be used, and internal DRAM will be allocated for FreeRTOS objects. Default value: No (disabled) if (CONFIG_SPIRAM || CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY) && CONFIG_BLE_MESH CONFIG_BLE_MESH_FREERTOS_STATIC_ALLOC_MODE Memory allocation for FreeRTOS objects Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FREERTOS_STATIC_ALLOC Choose the memory to be used for FreeRTOS objects. Available options: External SPIRAM (CONFIG_BLE_MESH_FREERTOS_STATIC_ALLOC_EXTERNAL) If enabled, BLE Mesh allocates dynamic memory from external SPIRAM for FreeRTOS objects, i.e. mutex, queue, and task stack. External SPIRAM can only be used for task stack when SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY is enabled. See the SPIRAM options for more details. Internal IRAM (CONFIG_BLE_MESH_FREERTOS_STATIC_ALLOC_IRAM_8BIT) If enabled, BLE Mesh allocates dynamic memory from internal IRAM for FreeRTOS objects, i.e. mutex, queue. Note: IRAM region cannot be used as task stack. CONFIG_BLE_MESH_DEINIT Support de-initialize BLE Mesh stack Found in: Component config > CONFIG_BLE_MESH If enabled, users can use the function esp_ble_mesh_deinit() to de-initialize the whole BLE Mesh stack. Default value: Yes (enabled) if CONFIG_BLE_MESH BLE Mesh and BLE coexistence support Contains: CONFIG_BLE_MESH_SUPPORT_BLE_ADV Support sending normal BLE advertising packets Found in: Component config > CONFIG_BLE_MESH > BLE Mesh and BLE coexistence support When selected, users can send normal BLE advertising packets with specific API. Default value: No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_BLE_ADV_BUF_COUNT Number of advertising buffers for BLE advertising packets Found in: Component config > CONFIG_BLE_MESH > BLE Mesh and BLE coexistence support > CONFIG_BLE_MESH_SUPPORT_BLE_ADV Number of advertising buffers for BLE packets available. Range: from 1 to 255 if CONFIG_BLE_MESH_SUPPORT_BLE_ADV && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_SUPPORT_BLE_SCAN Support scanning normal BLE advertising packets Found in: Component config > CONFIG_BLE_MESH > BLE Mesh and BLE coexistence support When selected, users can register a callback and receive normal BLE advertising packets in the application layer. Default value: No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_FAST_PROV Enable BLE Mesh Fast Provisioning Found in: Component config > CONFIG_BLE_MESH Enable this option to allow BLE Mesh fast provisioning solution to be used. When there are multiple unprovisioned devices around, fast provisioning can greatly reduce the time consumption of the whole provisioning process. When this option is enabled, and after an unprovisioned device is provisioned into a node successfully, it can be changed to a temporary Provisioner. Default value: No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_NODE Support for BLE Mesh Node Found in: Component config > CONFIG_BLE_MESH Enable the device to be provisioned into a node. This option should be enabled when an unprovisioned device is going to be provisioned into a node and communicate with other nodes in the BLE Mesh network. CONFIG_BLE_MESH_PROVISIONER Support for BLE Mesh Provisioner Found in: Component config > CONFIG_BLE_MESH Enable the device to be a Provisioner. The option should be enabled when a device is going to act as a Provisioner and provision unprovisioned devices into the BLE Mesh network. CONFIG_BLE_MESH_WAIT_FOR_PROV_MAX_DEV_NUM Maximum number of unprovisioned devices that can be added to device queue Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER This option specifies how many unprovisioned devices can be added to device queue for provisioning. Users can use this option to define the size of the queue in the bottom layer which is used to store unprovisioned device information (e.g. Device UUID, address). Range: from 1 to 100 if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_MAX_PROV_NODES Maximum number of devices that can be provisioned by Provisioner Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER This option specifies how many devices can be provisioned by a Provisioner. This value indicates the maximum number of unprovisioned devices which can be provisioned by a Provisioner. For instance, if the value is 6, it means the Provisioner can provision up to 6 unprovisioned devices. Theoretically a Provisioner without the limitation of its memory can provision up to 32766 unprovisioned devices, here we limit the maximum number to 100 just to limit the memory used by a Provisioner. The bigger the value is, the more memory it will cost by a Provisioner to store the information of nodes. Range: from 1 to 1000 if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_PBA_SAME_TIME Maximum number of PB-ADV running at the same time by Provisioner Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER This option specifies how many devices can be provisioned at the same time using PB-ADV. For examples, if the value is 2, it means a Provisioner can provision two unprovisioned devices with PB-ADV at the same time. Range: from 1 to 10 if CONFIG_BLE_MESH_PB_ADV && CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_PBG_SAME_TIME Maximum number of PB-GATT running at the same time by Provisioner Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER This option specifies how many devices can be provisioned at the same time using PB-GATT. For example, if the value is 2, it means a Provisioner can provision two unprovisioned devices with PB-GATT at the same time. Range: from 1 to 5 if CONFIG_BLE_MESH_PB_GATT && CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_PROVISIONER_SUBNET_COUNT Maximum number of mesh subnets that can be created by Provisioner Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER This option specifies how many subnets per network a Provisioner can create. Indeed, this value decides the number of network keys which can be added by a Provisioner. Range: from 1 to 4096 if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_PROVISIONER_APP_KEY_COUNT Maximum number of application keys that can be owned by Provisioner Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER This option specifies how many application keys the Provisioner can have. Indeed, this value decides the number of the application keys which can be added by a Provisioner. Range: from 1 to 4096 if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_PROVISIONER_RECV_HB Support receiving Heartbeat messages Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER When this option is enabled, Provisioner can call specific functions to enable or disable receiving Heartbeat messages and notify them to the application layer. Default value: No (disabled) if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH CONFIG_BLE_MESH_PROVISIONER_RECV_HB_FILTER_SIZE Maximum number of filter entries for receiving Heartbeat messages Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER > CONFIG_BLE_MESH_PROVISIONER_RECV_HB This option specifies how many heartbeat filter entries Provisioner supports. The heartbeat filter (acceptlist or rejectlist) entries are used to store a list of SRC and DST which can be used to decide if a heartbeat message will be processed and notified to the application layer by Provisioner. Note: The filter is an empty rejectlist by default. Range: from 1 to 1000 if CONFIG_BLE_MESH_PROVISIONER_RECV_HB && CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_PROV BLE Mesh Provisioning support Found in: Component config > CONFIG_BLE_MESH Enable this option to support BLE Mesh Provisioning functionality. For BLE Mesh, this option should be always enabled. Default value: Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_PROV_EPA BLE Mesh enhanced provisioning authentication Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROV Enable this option to support BLE Mesh enhanced provisioning authentication functionality. This option can increase the security level of provisioning. It is recommended to enable this option. Default value: Yes (enabled) if CONFIG_BLE_MESH_PROV && CONFIG_BLE_MESH CONFIG_BLE_MESH_CERT_BASED_PROV Support Certificate-based provisioning Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROV Enable this option to support BLE Mesh Certificate-Based Provisioning. Default value: No (disabled) if CONFIG_BLE_MESH_PROV && CONFIG_BLE_MESH CONFIG_BLE_MESH_RECORD_FRAG_MAX_SIZE Maximum size of the provisioning record fragment that Provisioner can receive Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROV > CONFIG_BLE_MESH_CERT_BASED_PROV This option sets the maximum size of the provisioning record fragment that the Provisioner can receive. The range depends on provisioning bearer. Range: from 1 to 57 if CONFIG_BLE_MESH_CERT_BASED_PROV && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_PB_ADV Provisioning support using the advertising bearer (PB-ADV) Found in: Component config > CONFIG_BLE_MESH Enable this option to allow the device to be provisioned over the advertising bearer. This option should be enabled if PB-ADV is going to be used during provisioning procedure. Default value: Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_UNPROVISIONED_BEACON_INTERVAL Interval between two consecutive Unprovisioned Device Beacon Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PB_ADV This option specifies the interval of sending two consecutive unprovisioned device beacon, users can use this option to change the frequency of sending unprovisioned device beacon. For example, if the value is 5, it means the unprovisioned device beacon will send every 5 seconds. When the option of BLE_MESH_FAST_PROV is selected, the value is better to be 3 seconds, or less. Range: from 1 to 100 if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PB_ADV && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_PB_GATT Provisioning support using GATT (PB-GATT) Found in: Component config > CONFIG_BLE_MESH Enable this option to allow the device to be provisioned over GATT. This option should be enabled if PB-GATT is going to be used during provisioning procedure. # Virtual option enabled whenever any Proxy protocol is needed CONFIG_BLE_MESH_PROXY BLE Mesh Proxy protocol support Found in: Component config > CONFIG_BLE_MESH Enable this option to support BLE Mesh Proxy protocol used by PB-GATT and other proxy pdu transmission. Default value: Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_GATT_PROXY_SERVER BLE Mesh GATT Proxy Server Found in: Component config > CONFIG_BLE_MESH This option enables support for Mesh GATT Proxy Service, i.e. the ability to act as a proxy between a Mesh GATT Client and a Mesh network. This option should be enabled if a node is going to be a Proxy Server. Default value: Yes (enabled) if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH CONFIG_BLE_MESH_NODE_ID_TIMEOUT Node Identity advertising timeout Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_SERVER This option determines for how long the local node advertises using Node Identity. The given value is in seconds. The specification limits this to 60 seconds and lists it as the recommended value as well. So leaving the default value is the safest option. When an unprovisioned device is provisioned successfully and becomes a node, it will start to advertise using Node Identity during the time set by this option. And after that, Network ID will be advertised. Range: from 1 to 60 if CONFIG_BLE_MESH_GATT_PROXY_SERVER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_PROXY_FILTER_SIZE Maximum number of filter entries per Proxy Client Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_SERVER This option specifies how many Proxy Filter entries the local node supports. The entries of Proxy filter (whitelist or blacklist) are used to store a list of addresses which can be used to decide which messages will be forwarded to the Proxy Client by the Proxy Server. Range: from 1 to 32767 if CONFIG_BLE_MESH_GATT_PROXY_SERVER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_PROXY_PRIVACY Support Proxy Privacy Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_SERVER The Proxy Privacy parameter controls the privacy of the Proxy Server over the connection. The value of the Proxy Privacy parameter is controlled by the type of proxy connection, which is dependent on the bearer used by the proxy connection. Default value: Yes (enabled) if CONFIG_BLE_MESH_PRB_SRV && CONFIG_BLE_MESH_GATT_PROXY_SERVER && CONFIG_BLE_MESH CONFIG_BLE_MESH_PROXY_SOLIC_PDU_RX Support receiving Proxy Solicitation PDU Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_SERVER Enable this option to support receiving Proxy Solicitation PDU. CONFIG_BLE_MESH_PROXY_SOLIC_RX_CRPL Maximum capacity of solicitation replay protection list Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_SERVER > CONFIG_BLE_MESH_PROXY_SOLIC_PDU_RX This option specifies the maximum capacity of the solicitation replay protection list. The solicitation replay protection list is used to reject Solicitation PDUs that were already processed by a node, which will store the solicitation src and solicitation sequence number of the received Solicitation PDU message. Range: from 1 to 255 if CONFIG_BLE_MESH_PROXY_SOLIC_PDU_RX && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_GATT_PROXY_CLIENT BLE Mesh GATT Proxy Client Found in: Component config > CONFIG_BLE_MESH This option enables support for Mesh GATT Proxy Client. The Proxy Client can use the GATT bearer to send mesh messages to a node that supports the advertising bearer. Default value: No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_PROXY_SOLIC_PDU_TX Support sending Proxy Solicitation PDU Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_CLIENT Enable this option to support sending Proxy Solicitation PDU. CONFIG_BLE_MESH_PROXY_SOLIC_TX_SRC_COUNT Maximum number of SSRC that can be used by Proxy Client Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_CLIENT > CONFIG_BLE_MESH_PROXY_SOLIC_PDU_TX This option specifies the maximum number of Solicitation Source (SSRC) that can be used by Proxy Client for sending a Solicitation PDU. A Proxy Client may use the primary address or any of the secondary addresses as the SSRC for a Solicitation PDU. So for a Proxy Client, it's better to choose the value based on its own element count. Range: from 1 to 16 if CONFIG_BLE_MESH_PROXY_SOLIC_PDU_TX && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_SETTINGS Store BLE Mesh configuration persistently Found in: Component config > CONFIG_BLE_MESH When selected, the BLE Mesh stack will take care of storing/restoring the BLE Mesh configuration persistently in flash. If the device is a BLE Mesh node, when this option is enabled, the configuration of the device will be stored persistently, including unicast address, NetKey, AppKey, etc. And if the device is a BLE Mesh Provisioner, the information of the device will be stored persistently, including the information of provisioned nodes, NetKey, AppKey, etc. Default value: No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_STORE_TIMEOUT Delay (in seconds) before storing anything persistently Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS This value defines in seconds how soon any pending changes are actually written into persistent storage (flash) after a change occurs. The option allows nodes to delay a certain period of time to save proper information to flash. The default value is 0, which means information will be stored immediately once there are updates. Range: from 0 to 1000000 if CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_SEQ_STORE_RATE How often the sequence number gets updated in storage Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS This value defines how often the local sequence number gets updated in persistent storage (i.e. flash). e.g. a value of 100 means that the sequence number will be stored to flash on every 100th increment. If the node sends messages very frequently a higher value makes more sense, whereas if the node sends infrequently a value as low as 0 (update storage for every increment) can make sense. When the stack gets initialized it will add sequence number to the last stored one, so that it starts off with a value that's guaranteed to be larger than the last one used before power off. Range: from 0 to 1000000 if CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_RPL_STORE_TIMEOUT Minimum frequency that the RPL gets updated in storage Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS This value defines in seconds how soon the RPL (Replay Protection List) gets written to persistent storage after a change occurs. If the node receives messages frequently, then a large value is recommended. If the node receives messages rarely, then the value can be as low as 0 (which means the RPL is written into the storage immediately). Note that if the node operates in a security-sensitive case, and there is a risk of sudden power-off, then a value of 0 is strongly recommended. Otherwise, a power loss before RPL being written into the storage may introduce message replay attacks and system security will be in a vulnerable state. Range: from 0 to 1000000 if CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_SETTINGS_BACKWARD_COMPATIBILITY A specific option for settings backward compatibility Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS This option is created to solve the issue of failure in recovering node information after mesh stack updates. In the old version mesh stack, there is no key of "mesh/role" in nvs. In the new version mesh stack, key of "mesh/role" is added in nvs, recovering node information needs to check "mesh/role" key in nvs and implements selective recovery of mesh node information. Therefore, there may be failure in recovering node information during node restarting after OTA. The new version mesh stack adds the option of "mesh/role" because we have added the support of storing Provisioner information, while the old version only supports storing node information. If users are updating their nodes from old version to new version, we recommend enabling this option, so that system could set the flag in advance before recovering node information and make sure the node information recovering could work as expected. Default value: No (disabled) if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH CONFIG_BLE_MESH_SPECIFIC_PARTITION Use a specific NVS partition for BLE Mesh Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS When selected, the mesh stack will use a specified NVS partition instead of default NVS partition. Note that the specified partition must be registered with NVS using nvs_flash_init_partition() API, and the partition must exists in the csv file. When Provisioner needs to store a large amount of nodes' information in the flash (e.g. more than 20), this option is recommended to be enabled. Default value: No (disabled) if CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH CONFIG_BLE_MESH_PARTITION_NAME Name of the NVS partition for BLE Mesh Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS > CONFIG_BLE_MESH_SPECIFIC_PARTITION This value defines the name of the specified NVS partition used by the mesh stack. Default value: "ble_mesh" if CONFIG_BLE_MESH_SPECIFIC_PARTITION && CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH CONFIG_BLE_MESH_USE_MULTIPLE_NAMESPACE Support using multiple NVS namespaces by Provisioner Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS When selected, Provisioner can use different NVS namespaces to store different instances of mesh information. For example, if in the first room, Provisioner uses NetKey A, AppKey A and provisions three devices, these information will be treated as mesh information instance A. When the Provisioner moves to the second room, it uses NetKey B, AppKey B and provisions two devices, then the information will be treated as mesh information instance B. Here instance A and instance B will be stored in different namespaces. With this option enabled, Provisioner needs to use specific functions to open the corresponding NVS namespace, restore the mesh information, release the mesh information or erase the mesh information. Default value: No (disabled) if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH CONFIG_BLE_MESH_MAX_NVS_NAMESPACE Maximum number of NVS namespaces Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS > CONFIG_BLE_MESH_USE_MULTIPLE_NAMESPACE This option specifies the maximum NVS namespaces supported by Provisioner. Range: from 1 to 255 if CONFIG_BLE_MESH_USE_MULTIPLE_NAMESPACE && CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_SUBNET_COUNT Maximum number of mesh subnets per network Found in: Component config > CONFIG_BLE_MESH This option specifies how many subnets a Mesh network can have at the same time. Indeed, this value decides the number of the network keys which can be owned by a node. Range: from 1 to 4096 if CONFIG_BLE_MESH Default value: 3 if CONFIG_BLE_MESH CONFIG_BLE_MESH_APP_KEY_COUNT Maximum number of application keys per network Found in: Component config > CONFIG_BLE_MESH This option specifies how many application keys the device can store per network. Indeed, this value decides the number of the application keys which can be owned by a node. Range: from 1 to 4096 if CONFIG_BLE_MESH Default value: 3 if CONFIG_BLE_MESH CONFIG_BLE_MESH_MODEL_KEY_COUNT Maximum number of application keys per model Found in: Component config > CONFIG_BLE_MESH This option specifies the maximum number of application keys to which each model can be bound. Range: from 1 to 4096 if CONFIG_BLE_MESH Default value: 3 if CONFIG_BLE_MESH CONFIG_BLE_MESH_MODEL_GROUP_COUNT Maximum number of group address subscriptions per model Found in: Component config > CONFIG_BLE_MESH This option specifies the maximum number of addresses to which each model can be subscribed. Range: from 1 to 4096 if CONFIG_BLE_MESH Default value: 3 if CONFIG_BLE_MESH CONFIG_BLE_MESH_LABEL_COUNT Maximum number of Label UUIDs used for Virtual Addresses Found in: Component config > CONFIG_BLE_MESH This option specifies how many Label UUIDs can be stored. Indeed, this value decides the number of the Virtual Addresses can be supported by a node. Range: from 0 to 4096 if CONFIG_BLE_MESH Default value: 3 if CONFIG_BLE_MESH CONFIG_BLE_MESH_CRPL Maximum capacity of the replay protection list Found in: Component config > CONFIG_BLE_MESH This option specifies the maximum capacity of the replay protection list. It is similar to Network message cache size, but has a different purpose. The replay protection list is used to prevent a node from replay attack, which will store the source address and sequence number of the received mesh messages. For Provisioner, the replay protection list size should not be smaller than the maximum number of nodes whose information can be stored. And the element number of each node should also be taken into consideration. For example, if Provisioner can provision up to 20 nodes and each node contains two elements, then the replay protection list size of Provisioner should be at least 40. Range: from 2 to 65535 if CONFIG_BLE_MESH Default value: 10 if CONFIG_BLE_MESH CONFIG_BLE_MESH_NOT_RELAY_REPLAY_MSG Not relay replayed messages in a mesh network Found in: Component config > CONFIG_BLE_MESH There may be many expired messages in a complex mesh network that would be considered replayed messages. Enable this option will refuse to relay such messages, which could help to reduce invalid packets in the mesh network. However, it should be noted that enabling this option may result in packet loss in certain environments. Therefore, users need to decide whether to enable this option according to the actual usage situation. Default value: No (disabled) if CONFIG_BLE_MESH_EXPERIMENTAL && CONFIG_BLE_MESH CONFIG_BLE_MESH_MSG_CACHE_SIZE Network message cache size Found in: Component config > CONFIG_BLE_MESH Number of messages that are cached for the network. This helps prevent unnecessary decryption operations and unnecessary relays. This option is similar to Replay protection list, but has a different purpose. A node is not required to cache the entire Network PDU and may cache only part of it for tracking, such as values for SRC/SEQ or others. Range: from 2 to 65535 if CONFIG_BLE_MESH Default value: 10 if CONFIG_BLE_MESH CONFIG_BLE_MESH_ADV_BUF_COUNT Number of advertising buffers Found in: Component config > CONFIG_BLE_MESH Number of advertising buffers available. The transport layer reserves ADV_BUF_COUNT - 3 buffers for outgoing segments. The maximum outgoing SDU size is 12 times this value (out of which 4 or 8 bytes are used for the Transport Layer MIC). For example, 5 segments means the maximum SDU size is 60 bytes, which leaves 56 bytes for application layer data using a 4-byte MIC, or 52 bytes using an 8-byte MIC. Range: from 6 to 256 if CONFIG_BLE_MESH Default value: 60 if CONFIG_BLE_MESH CONFIG_BLE_MESH_IVU_DIVIDER Divider for IV Update state refresh timer Found in: Component config > CONFIG_BLE_MESH When the IV Update state enters Normal operation or IV Update in Progress, we need to keep track of how many hours has passed in the state, since the specification requires us to remain in the state at least for 96 hours (Update in Progress has an additional upper limit of 144 hours). In order to fulfill the above requirement, even if the node might be powered off once in a while, we need to store persistently how many hours the node has been in the state. This doesn't necessarily need to happen every hour (thanks to the flexible duration range). The exact cadence will depend a lot on the ways that the node will be used and what kind of power source it has. Since there is no single optimal answer, this configuration option allows specifying a divider, i.e. how many intervals the 96 hour minimum gets split into. After each interval the duration that the node has been in the current state gets stored to flash. E.g. the default value of 4 means that the state is saved every 24 hours (96 / 4). Range: from 2 to 96 if CONFIG_BLE_MESH Default value: 4 if CONFIG_BLE_MESH CONFIG_BLE_MESH_IVU_RECOVERY_IVI Recovery the IV index when the latest whole IV update procedure is missed Found in: Component config > CONFIG_BLE_MESH According to Section 3.10.5 of Mesh Specification v1.0.1. If a node in Normal Operation receives a Secure Network beacon with an IV index equal to the last known IV index+1 and the IV Update Flag set to 0, the node may update its IV without going to the IV Update in Progress state, or it may initiate an IV Index Recovery procedure (Section 3.10.6), or it may ignore the Secure Network beacon. The node makes the choice depending on the time since last IV update and the likelihood that the node has missed the Secure Network beacons with the IV update Flag. When the above situation is encountered, this option can be used to decide whether to perform the IV index recovery procedure. Default value: No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_SAR_ENHANCEMENT Segmentation and reassembly enhancement Found in: Component config > CONFIG_BLE_MESH Enable this option to use the enhanced segmentation and reassembly mechanism introduced in Bluetooth Mesh Protocol 1.1. Default value: No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_TX_SEG_MSG_COUNT Maximum number of simultaneous outgoing segmented messages Found in: Component config > CONFIG_BLE_MESH Maximum number of simultaneous outgoing multi-segment and/or reliable messages. The default value is 1, which means the device can only send one segmented message at a time. And if another segmented message is going to be sent, it should wait for the completion of the previous one. If users are going to send multiple segmented messages at the same time, this value should be configured properly. Range: from 1 to if CONFIG_BLE_MESH Default value: 1 if CONFIG_BLE_MESH CONFIG_BLE_MESH_RX_SEG_MSG_COUNT Maximum number of simultaneous incoming segmented messages Found in: Component config > CONFIG_BLE_MESH Maximum number of simultaneous incoming multi-segment and/or reliable messages. The default value is 1, which means the device can only receive one segmented message at a time. And if another segmented message is going to be received, it should wait for the completion of the previous one. If users are going to receive multiple segmented messages at the same time, this value should be configured properly. Range: from 1 to 255 if CONFIG_BLE_MESH Default value: 1 if CONFIG_BLE_MESH CONFIG_BLE_MESH_RX_SDU_MAX Maximum incoming Upper Transport Access PDU length Found in: Component config > CONFIG_BLE_MESH Maximum incoming Upper Transport Access PDU length. Leave this to the default value, unless you really need to optimize memory usage. Range: from 36 to 384 if CONFIG_BLE_MESH Default value: 384 if CONFIG_BLE_MESH CONFIG_BLE_MESH_TX_SEG_MAX Maximum number of segments in outgoing messages Found in: Component config > CONFIG_BLE_MESH Maximum number of segments supported for outgoing messages. This value should typically be fine-tuned based on what models the local node supports, i.e. what's the largest message payload that the node needs to be able to send. This value affects memory and call stack consumption, which is why the default is lower than the maximum that the specification would allow (32 segments). The maximum outgoing SDU size is 12 times this number (out of which 4 or 8 bytes is used for the Transport Layer MIC). For example, 5 segments means the maximum SDU size is 60 bytes, which leaves 56 bytes for application layer data using a 4-byte MIC and 52 bytes using an 8-byte MIC. Be sure to specify a sufficient number of advertising buffers when setting this option to a higher value. There must be at least three more advertising buffers (BLE_MESH_ADV_BUF_COUNT) as there are outgoing segments. Range: from 2 to 32 if CONFIG_BLE_MESH Default value: 32 if CONFIG_BLE_MESH CONFIG_BLE_MESH_RELAY Relay support Found in: Component config > CONFIG_BLE_MESH Support for acting as a Mesh Relay Node. Enabling this option will allow a node to support the Relay feature, and the Relay feature can still be enabled or disabled by proper configuration messages. Disabling this option will let a node not support the Relay feature. Default value: Yes (enabled) if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH CONFIG_BLE_MESH_RELAY_ADV_BUF Use separate advertising buffers for relay packets Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_RELAY When selected, self-send packets will be put in a high-priority queue and relay packets will be put in a low-priority queue. Default value: No (disabled) if CONFIG_BLE_MESH_RELAY && CONFIG_BLE_MESH CONFIG_BLE_MESH_RELAY_ADV_BUF_COUNT Number of advertising buffers for relay packets Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_RELAY > CONFIG_BLE_MESH_RELAY_ADV_BUF Number of advertising buffers for relay packets available. Range: from 6 to 256 if CONFIG_BLE_MESH_RELAY_ADV_BUF && CONFIG_BLE_MESH_RELAY && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_LOW_POWER Support for Low Power features Found in: Component config > CONFIG_BLE_MESH Enable this option to operate as a Low Power Node. If low power consumption is required by a node, this option should be enabled. And once the node enters the mesh network, it will try to find a Friend node and establish a friendship. CONFIG_BLE_MESH_LPN_ESTABLISHMENT Perform Friendship establishment using low power Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER Perform the Friendship establishment using low power with the help of a reduced scan duty cycle. The downside of this is that the node may miss out on messages intended for it until it has successfully set up Friendship with a Friend node. When this option is enabled, the node will stop scanning for a period of time after a Friend Request or Friend Poll is sent, so as to reduce more power consumption. Default value: No (disabled) if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH CONFIG_BLE_MESH_LPN_AUTO Automatically start looking for Friend nodes once provisioned Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER Once provisioned, automatically enable LPN functionality and start looking for Friend nodes. If this option is disabled LPN mode needs to be manually enabled by calling bt_mesh_lpn_set(true). When an unprovisioned device is provisioned successfully and becomes a node, enabling this option will trigger the node starts to send Friend Request at a certain period until it finds a proper Friend node. Default value: No (disabled) if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH CONFIG_BLE_MESH_LPN_AUTO_TIMEOUT Time from last received message before going to LPN mode Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER > CONFIG_BLE_MESH_LPN_AUTO Time in seconds from the last received message, that the node waits out before starting to look for Friend nodes. Range: from 0 to 3600 if CONFIG_BLE_MESH_LPN_AUTO && CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_LPN_RETRY_TIMEOUT Retry timeout for Friend requests Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER Time in seconds between Friend Requests, if a previous Friend Request did not yield any acceptable Friend Offers. Range: from 1 to 3600 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_LPN_RSSI_FACTOR RSSIFactor, used in Friend Offer Delay calculation Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER The contribution of the RSSI, measured by the Friend node, used in Friend Offer Delay calculations. 0 = 1, 1 = 1.5, 2 = 2, 3 = 2.5. RSSIFactor, one of the parameters carried by Friend Request sent by Low Power node, which is used to calculate the Friend Offer Delay. Range: from 0 to 3 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_LPN_RECV_WIN_FACTOR ReceiveWindowFactor, used in Friend Offer Delay calculation Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER The contribution of the supported Receive Window used in Friend Offer Delay calculations. 0 = 1, 1 = 1.5, 2 = 2, 3 = 2.5. ReceiveWindowFactor, one of the parameters carried by Friend Request sent by Low Power node, which is used to calculate the Friend Offer Delay. Range: from 0 to 3 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_LPN_MIN_QUEUE_SIZE Minimum size of the acceptable friend queue (MinQueueSizeLog) Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER The MinQueueSizeLog field is defined as log_2(N), where N is the minimum number of maximum size Lower Transport PDUs that the Friend node can store in its Friend Queue. As an example, MinQueueSizeLog value 1 gives N = 2, and value 7 gives N = 128. Range: from 1 to 7 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_LPN_RECV_DELAY Receive delay requested by the local node Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER The ReceiveDelay is the time between the Low Power node sending a request and listening for a response. This delay allows the Friend node time to prepare the response. The value is in units of milliseconds. Range: from 10 to 255 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH Default value: 100 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH CONFIG_BLE_MESH_LPN_POLL_TIMEOUT The value of the PollTimeout timer Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER PollTimeout timer is used to measure time between two consecutive requests sent by a Low Power node. If no requests are received the Friend node before the PollTimeout timer expires, then the friendship is considered terminated. The value is in units of 100 milliseconds, so e.g. a value of 300 means 30 seconds. The smaller the value, the faster the Low Power node tries to get messages from corresponding Friend node and vice versa. Range: from 10 to 244735 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH Default value: 300 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH CONFIG_BLE_MESH_LPN_INIT_POLL_TIMEOUT The starting value of the PollTimeout timer Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER The initial value of the PollTimeout timer when Friendship is to be established for the first time. After this, the timeout gradually grows toward the actual PollTimeout, doubling in value for each iteration. The value is in units of 100 milliseconds, so e.g. a value of 300 means 30 seconds. Range: from 10 to if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_LPN_SCAN_LATENCY Latency for enabling scanning Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER Latency (in milliseconds) is the time it takes to enable scanning. In practice, it means how much time in advance of the Receive Window, the request to enable scanning is made. Range: from 0 to 50 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH Default value: 10 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH CONFIG_BLE_MESH_LPN_GROUPS Number of groups the LPN can subscribe to Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER Maximum number of groups to which the LPN can subscribe. Range: from 0 to 16384 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_LPN_SUB_ALL_NODES_ADDR Automatically subscribe all nodes address Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER Automatically subscribe all nodes address when friendship established. Default value: No (disabled) if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH CONFIG_BLE_MESH_FRIEND Support for Friend feature Found in: Component config > CONFIG_BLE_MESH Enable this option to be able to act as a Friend Node. CONFIG_BLE_MESH_FRIEND_RECV_WIN Friend Receive Window Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FRIEND Receive Window in milliseconds supported by the Friend node. Range: from 1 to 255 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH Default value: 255 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH CONFIG_BLE_MESH_FRIEND_QUEUE_SIZE Minimum number of buffers supported per Friend Queue Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FRIEND Minimum number of buffers available to be stored for each local Friend Queue. This option decides the size of each buffer which can be used by a Friend node to store messages for each Low Power node. Range: from 2 to 65536 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH Default value: 16 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH CONFIG_BLE_MESH_FRIEND_SUB_LIST_SIZE Friend Subscription List Size Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FRIEND Size of the Subscription List that can be supported by a Friend node for a Low Power node. And Low Power node can send Friend Subscription List Add or Friend Subscription List Remove messages to the Friend node to add or remove subscription addresses. Range: from 0 to 1023 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_FRIEND_LPN_COUNT Number of supported LPN nodes Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FRIEND Number of Low Power Nodes with which a Friend can have Friendship simultaneously. A Friend node can have friendship with multiple Low Power nodes at the same time, while a Low Power node can only establish friendship with only one Friend node at the same time. Range: from 1 to 1000 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_FRIEND_SEG_RX Number of incomplete segment lists per LPN Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FRIEND Number of incomplete segment lists tracked for each Friends' LPN. In other words, this determines from how many elements can segmented messages destined for the Friend queue be received simultaneously. Range: from 1 to 1000 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_NO_LOG Disable BLE Mesh debug logs (minimize bin size) Found in: Component config > CONFIG_BLE_MESH Select this to save the BLE Mesh related rodata code size. Enabling this option will disable the output of BLE Mesh debug log. Default value: No (disabled) if CONFIG_BLE_MESH && CONFIG_BLE_MESH BLE Mesh STACK DEBUG LOG LEVEL Contains: CONFIG_BLE_MESH_STACK_TRACE_LEVEL BLE_MESH_STACK Found in: Component config > CONFIG_BLE_MESH > BLE Mesh STACK DEBUG LOG LEVEL Define BLE Mesh trace level for BLE Mesh stack. Available options: NONE (CONFIG_BLE_MESH_TRACE_LEVEL_NONE) ERROR (CONFIG_BLE_MESH_TRACE_LEVEL_ERROR) WARNING (CONFIG_BLE_MESH_TRACE_LEVEL_WARNING) INFO (CONFIG_BLE_MESH_TRACE_LEVEL_INFO) DEBUG (CONFIG_BLE_MESH_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BLE_MESH_TRACE_LEVEL_VERBOSE) BLE Mesh NET BUF DEBUG LOG LEVEL Contains: CONFIG_BLE_MESH_NET_BUF_TRACE_LEVEL BLE_MESH_NET_BUF Found in: Component config > CONFIG_BLE_MESH > BLE Mesh NET BUF DEBUG LOG LEVEL Define BLE Mesh trace level for BLE Mesh net buffer. Available options: NONE (CONFIG_BLE_MESH_NET_BUF_TRACE_LEVEL_NONE) ERROR (CONFIG_BLE_MESH_NET_BUF_TRACE_LEVEL_ERROR) WARNING (CONFIG_BLE_MESH_NET_BUF_TRACE_LEVEL_WARNING) INFO (CONFIG_BLE_MESH_NET_BUF_TRACE_LEVEL_INFO) DEBUG (CONFIG_BLE_MESH_NET_BUF_TRACE_LEVEL_DEBUG) VERBOSE (CONFIG_BLE_MESH_NET_BUF_TRACE_LEVEL_VERBOSE) CONFIG_BLE_MESH_CLIENT_MSG_TIMEOUT Timeout(ms) for client message response Found in: Component config > CONFIG_BLE_MESH Timeout value used by the node to get response of the acknowledged message which is sent by the client model. This value indicates the maximum time that a client model waits for the response of the sent acknowledged messages. If a client model uses 0 as the timeout value when sending acknowledged messages, then the default value will be used which is four seconds. Range: from 100 to 1200000 if CONFIG_BLE_MESH Default value: 4000 if CONFIG_BLE_MESH Support for BLE Mesh Foundation models Contains: CONFIG_BLE_MESH_CFG_CLI Configuration Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Configuration Client model. CONFIG_BLE_MESH_HEALTH_CLI Health Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Health Client model. CONFIG_BLE_MESH_HEALTH_SRV Health Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Health Server model. Default value: Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_BRC_CLI Bridge Configuration Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Bridge Configuration Client model. CONFIG_BLE_MESH_BRC_SRV Bridge Configuration Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Bridge Configuration Server model. Default value: No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_MAX_BRIDGING_TABLE_ENTRY_COUNT Maximum number of Bridging Table entries Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_BRC_SRV Maximum number of Bridging Table entries that the Bridge Configuration Server can support. Range: from 16 to 65535 if CONFIG_BLE_MESH_BRC_SRV && CONFIG_BLE_MESH Default value: 16 if CONFIG_BLE_MESH_BRC_SRV && CONFIG_BLE_MESH CONFIG_BLE_MESH_BRIDGE_CRPL Maximum capacity of bridge replay protection list Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_BRC_SRV This option specifies the maximum capacity of the bridge replay protection list. The bridge replay protection list is used to prevent a bridged subnet from replay attack, which will store the source address and sequence number of the received bridge messages. Range: from 1 to 255 if CONFIG_BLE_MESH_BRC_SRV && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_PRB_CLI Mesh Private Beacon Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Mesh Private Beacon Client model. CONFIG_BLE_MESH_PRB_SRV Mesh Private Beacon Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Mesh Private Beacon Server model. CONFIG_BLE_MESH_ODP_CLI On-Demand Private Proxy Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for On-Demand Private Proxy Client model. CONFIG_BLE_MESH_ODP_SRV On-Demand Private Proxy Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for On-Demand Private Proxy Server model. CONFIG_BLE_MESH_SRPL_CLI Solicitation PDU RPL Configuration Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Solicitation PDU RPL Configuration Client model. CONFIG_BLE_MESH_SRPL_SRV Solicitation PDU RPL Configuration Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Solicitation PDU RPL Configuration Server model. Note: This option depends on the functionality of receiving Solicitation PDU. If the device doesn't support receiving Solicitation PDU, then there is no need to enable this server model. CONFIG_BLE_MESH_AGG_CLI Opcodes Aggregator Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Opcodes Aggregator Client model. CONFIG_BLE_MESH_AGG_SRV Opcodes Aggregator Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Opcodes Aggregator Server model. CONFIG_BLE_MESH_SAR_CLI SAR Configuration Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for SAR Configuration Client model. CONFIG_BLE_MESH_SAR_SRV SAR Configuration Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for SAR Configuration Server model. CONFIG_BLE_MESH_COMP_DATA_1 Support Composition Data Page 1 Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Composition Data Page 1 contains information about the relationships among models. Each model either can be a root model or can extend other models. CONFIG_BLE_MESH_COMP_DATA_128 Support Composition Data Page 128 Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Composition Data Page 128 is used to indicate the structure of elements, features, and models of a node after the successful execution of the Node Address Refresh procedure or the Node Composition Refresh procedure, or after the execution of the Node Removal procedure followed by the provisioning process. Composition Data Page 128 shall be present if the node supports the Remote Provisioning Server model; otherwise it is optional. CONFIG_BLE_MESH_MODELS_METADATA_0 Support Models Metadata Page 0 Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models The Models Metadata state contains metadata of a node’s models. The Models Metadata state is composed of a number of pages of information. Models Metadata Page 0 shall be present if the node supports the Large Composition Data Server model. CONFIG_BLE_MESH_MODELS_METADATA_128 Support Models Metadata Page 128 Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_MODELS_METADATA_0 The Models Metadata state contains metadata of a node’s models. The Models Metadata state is composed of a number of pages of information. Models Metadata Page 128 contains metadata for the node’s models after the successful execution of the Node Address Refresh procedure or the Node Composition Refresh procedure, or after the execution of the Node Removal procedure followed by the provisioning process. Models Metadata Page 128 shall be present if the node supports the Remote Provisioning Server model and the node supports the Large Composition Data Server model. CONFIG_BLE_MESH_LCD_CLI Large Composition Data Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Large Composition Data Client model. CONFIG_BLE_MESH_LCD_SRV Large Composition Data Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Large Composition Data Server model. CONFIG_BLE_MESH_RPR_CLI Remote Provisioning Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Remote Provisioning Client model CONFIG_BLE_MESH_RPR_CLI_PROV_SAME_TIME Maximum number of PB-Remote running at the same time by Provisioner Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_RPR_CLI This option specifies how many devices can be provisioned at the same time using PB-REMOTE. For example, if the value is 2, it means a Provisioner can provision two unprovisioned devices with PB-REMOTE at the same time. Range: from 1 to 5 if CONFIG_BLE_MESH_RPR_CLI && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_RPR_SRV Remote Provisioning Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Remote Provisioning Server model CONFIG_BLE_MESH_RPR_SRV_MAX_SCANNED_ITEMS Maximum number of device information can be scanned Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_RPR_SRV This option specifies how many device information can a Remote Provisioning Server store each time while scanning. Range: from 4 to 255 if CONFIG_BLE_MESH_RPR_SRV && CONFIG_BLE_MESH Default value: 10 if CONFIG_BLE_MESH_RPR_SRV && CONFIG_BLE_MESH CONFIG_BLE_MESH_RPR_SRV_ACTIVE_SCAN Support Active Scan for remote provisioning Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_RPR_SRV Enable this option to support Active Scan for remote provisioning. CONFIG_BLE_MESH_RPR_SRV_MAX_EXT_SCAN Maximum number of extended scan procedures Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_RPR_SRV This option specifies how many extended scan procedures can be started by the Remote Provisioning Server. Range: from 1 to 10 if CONFIG_BLE_MESH_RPR_SRV && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_DF_CLI Directed Forwarding Configuration Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Directed Forwarding Configuration Client model. CONFIG_BLE_MESH_DF_SRV Directed Forwarding Configuration Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Directed Forwarding Configuration Server model. CONFIG_BLE_MESH_MAX_DISC_TABLE_ENTRY_COUNT Maximum number of discovery table entries in a given subnet Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_DF_SRV Maximum number of Discovery Table entries supported by the node in a given subnet. Range: from 2 to 255 if CONFIG_BLE_MESH_DF_SRV && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_MAX_FORWARD_TABLE_ENTRY_COUNT Maximum number of forward table entries in a given subnet Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_DF_SRV Maximum number of Forward Table entries supported by the node in a given subnet. Range: from 2 to 64 if CONFIG_BLE_MESH_DF_SRV && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_MAX_DEPS_NODES_PER_PATH Maximum number of dependent nodes per path Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_DF_SRV Maximum size of dependent nodes list supported by each forward table entry. Range: from 2 to 64 if CONFIG_BLE_MESH_DF_SRV && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_PATH_MONITOR_TEST Enable Path Monitoring test mode Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_DF_SRV The option only removes the Path Use timer; all other behavior of the device is not changed. If Path Monitoring test mode is going to be used, this option should be enabled. Default value: No (disabled) if CONFIG_BLE_MESH_DF_SRV && CONFIG_BLE_MESH CONFIG_BLE_MESH_SUPPORT_DIRECTED_PROXY Enable Directed Proxy functionality Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_DF_SRV Support Directed Proxy functionality. Default value: Yes (enabled) if CONFIG_BLE_MESH_GATT_PROXY_SERVER && CONFIG_BLE_MESH_DF_SRV && CONFIG_BLE_MESH Support for BLE Mesh Client/Server models Contains: CONFIG_BLE_MESH_GENERIC_ONOFF_CLI Generic OnOff Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic OnOff Client model. CONFIG_BLE_MESH_GENERIC_LEVEL_CLI Generic Level Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic Level Client model. CONFIG_BLE_MESH_GENERIC_DEF_TRANS_TIME_CLI Generic Default Transition Time Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic Default Transition Time Client model. CONFIG_BLE_MESH_GENERIC_POWER_ONOFF_CLI Generic Power OnOff Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic Power OnOff Client model. CONFIG_BLE_MESH_GENERIC_POWER_LEVEL_CLI Generic Power Level Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic Power Level Client model. CONFIG_BLE_MESH_GENERIC_BATTERY_CLI Generic Battery Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic Battery Client model. CONFIG_BLE_MESH_GENERIC_LOCATION_CLI Generic Location Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic Location Client model. CONFIG_BLE_MESH_GENERIC_PROPERTY_CLI Generic Property Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic Property Client model. CONFIG_BLE_MESH_SENSOR_CLI Sensor Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Sensor Client model. CONFIG_BLE_MESH_TIME_CLI Time Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Time Client model. CONFIG_BLE_MESH_SCENE_CLI Scene Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Scene Client model. CONFIG_BLE_MESH_SCHEDULER_CLI Scheduler Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Scheduler Client model. CONFIG_BLE_MESH_LIGHT_LIGHTNESS_CLI Light Lightness Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Light Lightness Client model. CONFIG_BLE_MESH_LIGHT_CTL_CLI Light CTL Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Light CTL Client model. CONFIG_BLE_MESH_LIGHT_HSL_CLI Light HSL Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Light HSL Client model. CONFIG_BLE_MESH_LIGHT_XYL_CLI Light XYL Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Light XYL Client model. CONFIG_BLE_MESH_LIGHT_LC_CLI Light LC Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Light LC Client model. CONFIG_BLE_MESH_GENERIC_SERVER Generic server models Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic server models. Default value: Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_SENSOR_SERVER Sensor server models Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Sensor server models. Default value: Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_TIME_SCENE_SERVER Time and Scenes server models Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Time and Scenes server models. Default value: Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_LIGHTING_SERVER Lighting server models Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Lighting server models. Default value: Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_MBT_CLI BLOB Transfer Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for BLOB Transfer Client model. Default value: No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_MAX_BLOB_RECEIVERS Maximum number of simultaneous blob receivers Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models > CONFIG_BLE_MESH_MBT_CLI Maximum number of BLOB Transfer Server models that can participating in the BLOB transfer with a BLOB Transfer Client model. Range: from 1 to 255 if CONFIG_BLE_MESH_MBT_CLI && CONFIG_BLE_MESH Default value: CONFIG_BLE_MESH_MBT_SRV BLOB Transfer Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for BLOB Transfer Server model. Default value: No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_IV_UPDATE_TEST Test the IV Update Procedure Found in: Component config > CONFIG_BLE_MESH This option removes the 96 hour limit of the IV Update Procedure and lets the state to be changed at any time. If IV Update test mode is going to be used, this option should be enabled. Default value: No (disabled) if CONFIG_BLE_MESH BLE Mesh specific test option Contains: CONFIG_BLE_MESH_SELF_TEST Perform BLE Mesh self-tests Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option This option adds extra self-tests which are run every time BLE Mesh networking is initialized. Default value: No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_BQB_TEST Enable BLE Mesh specific internal test Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option This option is used to enable some internal functions for auto-pts test. Default value: No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_TEST_AUTO_ENTER_NETWORK Unprovisioned device enters mesh network automatically Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option With this option enabled, an unprovisioned device can automatically enters mesh network using a specific test function without the pro- visioning procedure. And on the Provisioner side, a test function needs to be invoked to add the node information into the mesh stack. Default value: Yes (enabled) if CONFIG_BLE_MESH_SELF_TEST && CONFIG_BLE_MESH CONFIG_BLE_MESH_TEST_USE_WHITE_LIST Use white list to filter mesh advertising packets Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option With this option enabled, users can use white list to filter mesh advertising packets while scanning. Default value: No (disabled) if CONFIG_BLE_MESH_SELF_TEST && CONFIG_BLE_MESH CONFIG_BLE_MESH_SHELL Enable BLE Mesh shell Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option Activate shell module that provides BLE Mesh commands to the console. Default value: No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_DEBUG Enable BLE Mesh debug logs Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option Enable debug logs for the BLE Mesh functionality. Default value: No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_DEBUG_NET Network layer debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Network layer debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_TRANS Transport layer debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Transport layer debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_BEACON Beacon debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Beacon-related debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_CRYPTO Crypto debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable cryptographic debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_PROV Provisioning debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Provisioning debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_ACCESS Access layer debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Access layer debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_MODEL Foundation model debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Foundation Models debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_ADV Advertising debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable advertising debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_LOW_POWER Low Power debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Low Power debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_FRIEND Friend debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Friend debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_PROXY Proxy debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Proxy protocol debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_EXPERIMENTAL Make BLE Mesh experimental features visible Found in: Component config > CONFIG_BLE_MESH Make BLE Mesh Experimental features visible. Experimental features list: - CONFIG_BLE_MESH_NOT_RELAY_REPLAY_MSG Default value: No (disabled) if CONFIG_BLE_MESH Driver Configurations Contains: Legacy ADC Configuration Contains: CONFIG_ADC_DISABLE_DAC Disable DAC when ADC2 is used on GPIO 25 and 26 Found in: Component config > Driver Configurations > Legacy ADC Configuration If this is set, the ADC2 driver will disable the output of the DAC corresponding to the specified channel. This is the default value. For testing, disable this option so that we can measure the output of DAC by internal ADC. Default value: Yes (enabled) CONFIG_ADC_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > Legacy ADC Configuration Wether to suppress the deprecation warnings when using legacy adc driver (driver/adc.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. Default value: No (disabled) Legacy ADC Calibration Configuration Contains: CONFIG_ADC_CAL_EFUSE_TP_ENABLE Use Two Point Values Found in: Component config > Driver Configurations > Legacy ADC Configuration > Legacy ADC Calibration Configuration Some ESP32s have Two Point calibration values burned into eFuse BLOCK3. This option will allow the ADC calibration component to characterize the ADC-Voltage curve using Two Point values if they are available. Default value: Yes (enabled) CONFIG_ADC_CAL_EFUSE_VREF_ENABLE Use eFuse Vref Found in: Component config > Driver Configurations > Legacy ADC Configuration > Legacy ADC Calibration Configuration Some ESP32s have Vref burned into eFuse BLOCK0. This option will allow the ADC calibration component to characterize the ADC-Voltage curve using eFuse Vref if it is available. Default value: Yes (enabled) CONFIG_ADC_CAL_LUT_ENABLE Use Lookup Tables Found in: Component config > Driver Configurations > Legacy ADC Configuration > Legacy ADC Calibration Configuration This option will allow the ADC calibration component to use Lookup Tables to correct for non-linear behavior in 11db attenuation. Other attenuations do not exhibit non-linear behavior hence will not be affected by this option. Default value: Yes (enabled) CONFIG_ADC_CALI_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > Legacy ADC Configuration > Legacy ADC Calibration Configuration Wether to suppress the deprecation warnings when using legacy adc calibration driver (esp_adc_cal.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. Default value: No (disabled) SPI Configuration Contains: CONFIG_SPI_MASTER_IN_IRAM Place transmitting functions of SPI master into IRAM Found in: Component config > Driver Configurations > SPI Configuration Normally only the ISR of SPI master is placed in the IRAM, so that it can work without the flash when interrupt is triggered. For other functions, there's some possibility that the flash cache miss when running inside and out of SPI functions, which may increase the interval of SPI transactions. Enable this to put queue\_trans , get\_trans\_result and transmit functions into the IRAM to avoid possible cache miss. This configuration won't be available if CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH is enabled. During unit test, this is enabled to measure the ideal case of api. CONFIG_SPI_MASTER_ISR_IN_IRAM Place SPI master ISR function into IRAM Found in: Component config > Driver Configurations > SPI Configuration Place the SPI master ISR in to IRAM to avoid possible cache miss. Enabling this configuration is possible only when HEAP_PLACE_FUNCTION_INTO_FLASH is disabled since the spi master uses can allocate transactions buffers into DMA memory section using the heap component API that ipso facto has to be placed in IRAM. Also you can forbid the ISR being disabled during flash writing access, by add ESP_INTR_FLAG_IRAM when initializing the driver. CONFIG_SPI_SLAVE_IN_IRAM Place transmitting functions of SPI slave into IRAM Found in: Component config > Driver Configurations > SPI Configuration Normally only the ISR of SPI slave is placed in the IRAM, so that it can work without the flash when interrupt is triggered. For other functions, there's some possibility that the flash cache miss when running inside and out of SPI functions, which may increase the interval of SPI transactions. Enable this to put queue\_trans , get\_trans\_result and transmit functions into the IRAM to avoid possible cache miss. Default value: No (disabled) CONFIG_SPI_SLAVE_ISR_IN_IRAM Place SPI slave ISR function into IRAM Found in: Component config > Driver Configurations > SPI Configuration Place the SPI slave ISR in to IRAM to avoid possible cache miss. Also you can forbid the ISR being disabled during flash writing access, by add ESP_INTR_FLAG_IRAM when initializing the driver. Default value: Yes (enabled) TWAI Configuration Contains: CONFIG_TWAI_ISR_IN_IRAM Place TWAI ISR function into IRAM Found in: Component config > Driver Configurations > TWAI Configuration Place the TWAI ISR in to IRAM. This will allow the ISR to avoid cache misses, and also be able to run whilst the cache is disabled (such as when writing to SPI Flash). Note that if this option is enabled: - Users should also set the ESP_INTR_FLAG_IRAM in the driver configuration structure when installing the driver (see docs for specifics). - Alert logging (i.e., setting of the TWAI_ALERT_AND_LOG flag) will have no effect. Default value: No (disabled) CONFIG_TWAI_ERRATA_FIX_BUS_OFF_REC Add SW workaround for REC change during bus-off Found in: Component config > Driver Configurations > TWAI Configuration When the bus-off condition is reached, the REC should be reset to 0 and frozen (via LOM) by the driver's ISR. However on the ESP32, there is an edge case where the REC will increase before the driver's ISR can respond in time (e.g., due to the rapid occurrence of bus errors), thus causing the REC to be non-zero after bus-off. A non-zero REC can prevent bus-off recovery as the bus-off recovery condition is that both TEC and REC become 0. Enabling this option will add a workaround in the driver to forcibly reset REC to zero on reaching bus-off. Default value: Yes (enabled) CONFIG_TWAI_ERRATA_FIX_TX_INTR_LOST Add SW workaround for TX interrupt lost errata Found in: Component config > Driver Configurations > TWAI Configuration On the ESP32, when a transmit interrupt occurs, and interrupt register is read on the same APB clock cycle, the transmit interrupt could be lost. Enabling this option will add a workaround that checks the transmit buffer status bit to recover any lost transmit interrupt. Default value: Yes (enabled) CONFIG_TWAI_ERRATA_FIX_RX_FRAME_INVALID Add SW workaround for invalid RX frame errata Found in: Component config > Driver Configurations > TWAI Configuration On the ESP32, when receiving a data or remote frame, if a bus error occurs in the data or CRC field, the data of the next received frame could be invalid. Enabling this option will add a workaround that will reset the peripheral on detection of this errata condition. Note that if a frame is transmitted on the bus whilst the reset is ongoing, the message will not be receive by the peripheral sent on the bus during the reset, the message will be lost. Default value: Yes (enabled) CONFIG_TWAI_ERRATA_FIX_RX_FIFO_CORRUPT Add SW workaround for RX FIFO corruption errata Found in: Component config > Driver Configurations > TWAI Configuration On the ESP32, when the RX FIFO overruns and the RX message counter maxes out at 64 messages, the entire RX FIFO is no longer recoverable. Enabling this option will add a workaround that resets the peripheral on detection of this errata condition. Note that if a frame is being sent on the bus during the reset bus during the reset, the message will be lost. Default value: Yes (enabled) CONFIG_TWAI_ERRATA_FIX_LISTEN_ONLY_DOM Add SW workaround for listen only transmits dominant bit errata Found in: Component config > Driver Configurations > TWAI Configuration When in the listen only mode, the TWAI controller must not influence the TWAI bus (i.e., must not send any dominant bits). However, while in listen only mode on the ESP32/ESP32-S2/ESP32-S3/ESP32-C3, the TWAI controller will still transmit dominant bits when it detects an error (i.e., as part of an active error frame). Enabling this option will add a workaround that forces the TWAI controller into an error passive state on initialization, thus preventing any dominant bits from being sent. Default value: Yes (enabled) Temperature sensor Configuration Contains: CONFIG_TEMP_SENSOR_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > Temperature sensor Configuration Wether to suppress the deprecation warnings when using legacy temperature sensor driver (driver/temp_sensor.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. Default value: No (disabled) if SOC_TEMP_SENSOR_SUPPORTED CONFIG_TEMP_SENSOR_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > Temperature sensor Configuration Wether to enable the debug log message for temperature sensor driver. Note that, this option only controls the temperature sensor driver log, won't affect other drivers. Default value: No (disabled) if SOC_TEMP_SENSOR_SUPPORTED CONFIG_TEMP_SENSOR_ISR_IRAM_SAFE Temperature sensor ISR IRAM-Safe Found in: Component config > Driver Configurations > Temperature sensor Configuration Ensure the Temperature Sensor interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). Default value: No (disabled) if SOC_TEMPERATURE_SENSOR_INTR_SUPPORT && SOC_TEMP_SENSOR_SUPPORTED UART Configuration Contains: CONFIG_UART_ISR_IN_IRAM Place UART ISR function into IRAM Found in: Component config > Driver Configurations > UART Configuration If this option is not selected, UART interrupt will be disabled for a long time and may cause data lost when doing spi flash operation. GPIO Configuration Contains: CONFIG_GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL Support light sleep GPIO pullup/pulldown configuration for ESP32 Found in: Component config > Driver Configurations > GPIO Configuration This option is intended to fix the bug that ESP32 is not able to switch to configured pullup/pulldown mode in sleep. If this option is selected, chip will automatically emulate the behaviour of switching, and about 450B of source codes would be placed into IRAM. CONFIG_GPIO_CTRL_FUNC_IN_IRAM Place GPIO control functions into IRAM Found in: Component config > Driver Configurations > GPIO Configuration Place GPIO control functions (like intr_disable/set_level) into IRAM, so that these functions can be IRAM-safe and able to be called in the other IRAM interrupt context. Default value: No (disabled) Sigma Delta Modulator Configuration Contains: CONFIG_SDM_CTRL_FUNC_IN_IRAM Place SDM control functions into IRAM Found in: Component config > Driver Configurations > Sigma Delta Modulator Configuration Place SDM control functions (like set_duty) into IRAM, so that these functions can be IRAM-safe and able to be called in the other IRAM interrupt context. Enabling this option can improve driver performance as well. Default value: No (disabled) CONFIG_SDM_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > Sigma Delta Modulator Configuration Wether to suppress the deprecation warnings when using legacy sigma delta driver. If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. Default value: No (disabled) CONFIG_SDM_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > Sigma Delta Modulator Configuration Wether to enable the debug log message for SDM driver. Note that, this option only controls the SDM driver log, won't affect other drivers. Default value: No (disabled) Analog Comparator Configuration Contains: CONFIG_ANA_CMPR_ISR_IRAM_SAFE Analog comparator ISR IRAM-Safe Found in: Component config > Driver Configurations > Analog Comparator Configuration Ensure the Analog Comparator interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). Default value: No (disabled) if SOC_ANA_CMPR_SUPPORTED CONFIG_ANA_CMPR_CTRL_FUNC_IN_IRAM Place Analog Comparator control functions into IRAM Found in: Component config > Driver Configurations > Analog Comparator Configuration Place Analog Comparator control functions (like ana_cmpr_set_internal_reference) into IRAM, so that these functions can be IRAM-safe and able to be called in an IRAM interrupt context. Enabling this option can improve driver performance as well. Default value: No (disabled) if SOC_ANA_CMPR_SUPPORTED CONFIG_ANA_CMPR_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > Analog Comparator Configuration Wether to enable the debug log message for Analog Comparator driver. Note that, this option only controls the Analog Comparator driver log, won't affect other drivers. Default value: No (disabled) if SOC_ANA_CMPR_SUPPORTED GPTimer Configuration Contains: CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM Place GPTimer ISR handler into IRAM Found in: Component config > Driver Configurations > GPTimer Configuration Place GPTimer ISR handler into IRAM for better performance and fewer cache misses. Default value: Yes (enabled) CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM Place GPTimer control functions into IRAM Found in: Component config > Driver Configurations > GPTimer Configuration Place GPTimer control functions (like start/stop) into IRAM, so that these functions can be IRAM-safe and able to be called in the other IRAM interrupt context. Enabling this option can improve driver performance as well. Default value: No (disabled) CONFIG_GPTIMER_ISR_IRAM_SAFE GPTimer ISR IRAM-Safe Found in: Component config > Driver Configurations > GPTimer Configuration Ensure the GPTimer interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). Default value: No (disabled) CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > GPTimer Configuration Wether to suppress the deprecation warnings when using legacy timer group driver (driver/timer.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. Default value: No (disabled) CONFIG_GPTIMER_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > GPTimer Configuration Wether to enable the debug log message for GPTimer driver. Note that, this option only controls the GPTimer driver log, won't affect other drivers. Default value: No (disabled) PCNT Configuration Contains: CONFIG_PCNT_CTRL_FUNC_IN_IRAM Place PCNT control functions into IRAM Found in: Component config > Driver Configurations > PCNT Configuration Place PCNT control functions (like start/stop) into IRAM, so that these functions can be IRAM-safe and able to be called in the other IRAM interrupt context. Enabling this option can improve driver performance as well. Default value: No (disabled) CONFIG_PCNT_ISR_IRAM_SAFE PCNT ISR IRAM-Safe Found in: Component config > Driver Configurations > PCNT Configuration Ensure the PCNT interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). Default value: No (disabled) CONFIG_PCNT_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > PCNT Configuration Wether to suppress the deprecation warnings when using legacy PCNT driver (driver/pcnt.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. Default value: No (disabled) CONFIG_PCNT_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > PCNT Configuration Wether to enable the debug log message for PCNT driver. Note that, this option only controls the PCNT driver log, won't affect other drivers. Default value: No (disabled) RMT Configuration Contains: CONFIG_RMT_ISR_IRAM_SAFE RMT ISR IRAM-Safe Found in: Component config > Driver Configurations > RMT Configuration Ensure the RMT interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). Default value: No (disabled) CONFIG_RMT_RECV_FUNC_IN_IRAM Place RMT receive function into IRAM Found in: Component config > Driver Configurations > RMT Configuration Place RMT receive function into IRAM, so that the receive function can be IRAM-safe and able to be called when the flash cache is disabled. Enabling this option can improve driver performance as well. Default value: No (disabled) CONFIG_RMT_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > RMT Configuration Wether to suppress the deprecation warnings when using legacy rmt driver (driver/rmt.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. Default value: No (disabled) CONFIG_RMT_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > RMT Configuration Wether to enable the debug log message for RMT driver. Note that, this option only controls the RMT driver log, won't affect other drivers. Default value: No (disabled) MCPWM Configuration Contains: CONFIG_MCPWM_ISR_IRAM_SAFE Place MCPWM ISR function into IRAM Found in: Component config > Driver Configurations > MCPWM Configuration This will ensure the MCPWM interrupt handle is IRAM-Safe, allow to avoid flash cache misses, and also be able to run whilst the cache is disabled. (e.g. SPI Flash write) Default value: No (disabled) CONFIG_MCPWM_CTRL_FUNC_IN_IRAM Place MCPWM control functions into IRAM Found in: Component config > Driver Configurations > MCPWM Configuration Place MCPWM control functions (like set_compare_value) into IRAM, so that these functions can be IRAM-safe and able to be called in the other IRAM interrupt context. Enabling this option can improve driver performance as well. Default value: No (disabled) CONFIG_MCPWM_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > MCPWM Configuration Wether to suppress the deprecation warnings when using legacy MCPWM driver (driver/mcpwm.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. Default value: No (disabled) CONFIG_MCPWM_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > MCPWM Configuration Wether to enable the debug log message for MCPWM driver. Note that, this option only controls the MCPWM driver log, won't affect other drivers. Default value: No (disabled) I2S Configuration Contains: CONFIG_I2S_ISR_IRAM_SAFE I2S ISR IRAM-Safe Found in: Component config > Driver Configurations > I2S Configuration Ensure the I2S interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). Default value: No (disabled) CONFIG_I2S_SUPPRESS_DEPRECATE_WARN Suppress leagcy driver deprecated warning Found in: Component config > Driver Configurations > I2S Configuration Enable this option will suppress the deprecation warnings of using APIs in legacy I2S driver. Default value: No (disabled) CONFIG_I2S_ENABLE_DEBUG_LOG Enable I2S debug log Found in: Component config > Driver Configurations > I2S Configuration Wether to enable the debug log message for I2S driver. Note that, this option only controls the I2S driver log, will not affect other drivers. Default value: No (disabled) DAC Configuration Contains: CONFIG_DAC_CTRL_FUNC_IN_IRAM Place DAC control functions into IRAM Found in: Component config > Driver Configurations > DAC Configuration Place DAC control functions (e.g. 'dac_oneshot_output_voltage') into IRAM, so that this function can be IRAM-safe and able to be called in the other IRAM interrupt context. Enabling this option can improve driver performance as well. Default value: No (disabled) CONFIG_DAC_ISR_IRAM_SAFE DAC ISR IRAM-Safe Found in: Component config > Driver Configurations > DAC Configuration Ensure the DAC interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). Default value: No (disabled) CONFIG_DAC_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > DAC Configuration Wether to suppress the deprecation warnings when using legacy DAC driver (driver/dac.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. Default value: No (disabled) CONFIG_DAC_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > DAC Configuration Wether to enable the debug log message for DAC driver. Note that, this option only controls the DAC driver log, won't affect other drivers. Default value: No (disabled) CONFIG_DAC_DMA_AUTO_16BIT_ALIGN Align the continuous data to 16 bit automatically Found in: Component config > Driver Configurations > DAC Configuration Whether to left shift the continuous data to align every bytes to 16 bits in the driver. On ESP32, although the DAC resolution is only 8 bits, the hardware requires 16 bits data in continuous mode. By enabling this option, the driver will left shift 8 bits for the input data automatically. Only disable this option when you decide to do this step by yourself. Note that the driver will allocate a new piece of memory to save the converted data. Default value: Yes (enabled) USB Serial/JTAG Configuration Contains: CONFIG_USJ_NO_AUTO_LS_ON_CONNECTION Don't enter the automatic light sleep when USB Serial/JTAG port is connected Found in: Component config > Driver Configurations > USB Serial/JTAG Configuration If enabled, the chip will constantly monitor the connection status of the USB Serial/JTAG port. As long as the USB Serial/JTAG is connected, a ESP_PM_NO_LIGHT_SLEEP power management lock will be acquired to prevent the system from entering light sleep. This option can be useful if serial monitoring is needed via USB Serial/JTAG while power management is enabled, as the USB Serial/JTAG cannot work under light sleep and after waking up from light sleep. Note. This option can only control the automatic Light-Sleep behavior. If esp_light_sleep_start() is called manually from the program, enabling this option will not prevent light sleep entry even if the USB Serial/JTAG is in use. Parallel IO Configuration Contains: CONFIG_PARLIO_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > Parallel IO Configuration Wether to enable the debug log message for parallel IO driver. Note that, this option only controls the parallel IO driver log, won't affect other drivers. Default value: No (disabled) if SOC_PARLIO_SUPPORTED CONFIG_PARLIO_ISR_IRAM_SAFE Parallel IO ISR IRAM-Safe Found in: Component config > Driver Configurations > Parallel IO Configuration Ensure the Parallel IO interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). Default value: No (disabled) if SOC_PARLIO_SUPPORTED LEDC Configuration Contains: CONFIG_LEDC_CTRL_FUNC_IN_IRAM Place LEDC control functions into IRAM Found in: Component config > Driver Configurations > LEDC Configuration Place LEDC control functions (ledc_update_duty and ledc_stop) into IRAM, so that these functions can be IRAM-safe and able to be called in an IRAM context. Enabling this option can improve driver performance as well. Default value: No (disabled) I2C Configuration Contains: CONFIG_I2C_ISR_IRAM_SAFE I2C ISR IRAM-Safe Found in: Component config > Driver Configurations > I2C Configuration Ensure the I2C interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). note: This cannot be used in the I2C legacy driver. Default value: No (disabled) CONFIG_I2C_ENABLE_DEBUG_LOG Enable I2C debug log Found in: Component config > Driver Configurations > I2C Configuration Wether to enable the debug log message for I2C driver. Note that this option only controls the I2C driver log, will not affect other drivers. note: This cannot be used in the I2C legacy driver. Default value: No (disabled) eFuse Bit Manager Contains: CONFIG_EFUSE_CUSTOM_TABLE Use custom eFuse table Found in: Component config > eFuse Bit Manager Allows to generate a structure for eFuse from the CSV file. Default value: No (disabled) CONFIG_EFUSE_CUSTOM_TABLE_FILENAME Custom eFuse CSV file Found in: Component config > eFuse Bit Manager > CONFIG_EFUSE_CUSTOM_TABLE Name of the custom eFuse CSV filename. This path is evaluated relative to the project root directory. Default value: "main/esp_efuse_custom_table.csv" if CONFIG_EFUSE_CUSTOM_TABLE CONFIG_EFUSE_VIRTUAL Simulate eFuse operations in RAM Found in: Component config > eFuse Bit Manager If "n" - No virtual mode. All eFuse operations are real and use eFuse registers. If "y" - The virtual mode is enabled and all eFuse operations (read and write) are redirected to RAM instead of eFuse registers, all permanent changes (via eFuse) are disabled. Log output will state changes that would be applied, but they will not be. If it is "y", then SECURE_FLASH_ENCRYPTION_MODE_RELEASE cannot be used. Because the EFUSE VIRT mode is for testing only. During startup, the eFuses are copied into RAM. This mode is useful for fast tests. Default value: No (disabled) CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH Keep eFuses in flash Found in: Component config > eFuse Bit Manager > CONFIG_EFUSE_VIRTUAL In addition to the "Simulate eFuse operations in RAM" option, this option just adds a feature to keep eFuses after reboots in flash memory. To use this mode the partition_table should have the efuse partition. partition.csv: "efuse_em, data, efuse, , 0x2000," During startup, the eFuses are copied from flash or, in case if flash is empty, from real eFuse to RAM and then update flash. This mode is useful when need to keep changes after reboot (testing secure_boot and flash_encryption). CONFIG_EFUSE_VIRTUAL_LOG_ALL_WRITES Log all virtual writes Found in: Component config > eFuse Bit Manager > CONFIG_EFUSE_VIRTUAL If enabled, log efuse burns. This shows changes that would be made. CONFIG_EFUSE_CODE_SCHEME_SELECTOR Coding Scheme Compatibility Found in: Component config > eFuse Bit Manager Selector eFuse code scheme. Available options: None Only (CONFIG_EFUSE_CODE_SCHEME_COMPAT_NONE) 3/4 and None (CONFIG_EFUSE_CODE_SCHEME_COMPAT_3_4) Repeat, 3/4 and None (common table does not support it) (CONFIG_EFUSE_CODE_SCHEME_COMPAT_REPEAT) ESP-TLS Contains: CONFIG_ESP_TLS_LIBRARY_CHOOSE Choose SSL/TLS library for ESP-TLS (See help for more Info) Found in: Component config > ESP-TLS The ESP-TLS APIs support multiple backend TLS libraries. Currently mbedTLS and WolfSSL are supported. Different TLS libraries may support different features and have different resource usage. Consult the ESP-TLS documentation in ESP-IDF Programming guide for more details. Available options: mbedTLS (CONFIG_ESP_TLS_USING_MBEDTLS) wolfSSL (License info in wolfSSL directory README) (CONFIG_ESP_TLS_USING_WOLFSSL) CONFIG_ESP_TLS_USE_SECURE_ELEMENT Use Secure Element (ATECC608A) with ESP-TLS Found in: Component config > ESP-TLS Enable use of Secure Element for ESP-TLS, this enables internal support for ATECC608A peripheral on ESPWROOM32SE, which can be used for TLS connection. CONFIG_ESP_TLS_USE_DS_PERIPHERAL Use Digital Signature (DS) Peripheral with ESP-TLS Found in: Component config > ESP-TLS Enable use of the Digital Signature Peripheral for ESP-TLS.The DS peripheral can only be used when it is appropriately configured for TLS. Consult the ESP-TLS documentation in ESP-IDF Programming Guide for more details. Default value: Yes (enabled) if CONFIG_ESP_TLS_USING_MBEDTLS && SOC_DIG_SIGN_SUPPORTED CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS Enable client session tickets Found in: Component config > ESP-TLS Enable session ticket support as specified in RFC5077. CONFIG_ESP_TLS_SERVER Enable ESP-TLS Server Found in: Component config > ESP-TLS Enable support for creating server side SSL/TLS session, available for mbedTLS as well as wolfSSL TLS library. CONFIG_ESP_TLS_SERVER_SESSION_TICKETS Enable server session tickets Found in: Component config > ESP-TLS > CONFIG_ESP_TLS_SERVER Enable session ticket support as specified in RFC5077 CONFIG_ESP_TLS_SERVER_SESSION_TICKET_TIMEOUT Server session ticket timeout in seconds Found in: Component config > ESP-TLS > CONFIG_ESP_TLS_SERVER > CONFIG_ESP_TLS_SERVER_SESSION_TICKETS Sets the session ticket timeout used in the tls server. Default value: CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK Certificate selection hook Found in: Component config > ESP-TLS > CONFIG_ESP_TLS_SERVER Ability to configure and use a certificate selection callback during server handshake, to select a certificate to present to the client based on the TLS extensions supplied in the client hello (alpn, sni, etc). CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL ESP-TLS Server: Set minimum Certificate Verification mode to Optional Found in: Component config > ESP-TLS > CONFIG_ESP_TLS_SERVER When this option is enabled, the peer (here, the client) certificate is checked by the server, however the handshake continues even if verification failed. By default, the peer certificate is not checked and ignored by the server. mbedtls_ssl_get_verify_result() can be called after the handshake is complete to retrieve status of verification. CONFIG_ESP_TLS_PSK_VERIFICATION Enable PSK verification Found in: Component config > ESP-TLS Enable support for pre shared key ciphers, supported for both mbedTLS as well as wolfSSL TLS library. CONFIG_ESP_TLS_INSECURE Allow potentially insecure options Found in: Component config > ESP-TLS You can enable some potentially insecure options. These options should only be used for testing pusposes. Only enable these options if you are very sure. CONFIG_ESP_TLS_SKIP_SERVER_CERT_VERIFY Skip server certificate verification by default (WARNING: ONLY FOR TESTING PURPOSE, READ HELP) Found in: Component config > ESP-TLS > CONFIG_ESP_TLS_INSECURE After enabling this option the esp-tls client will skip the server certificate verification by default. Note that this option will only modify the default behaviour of esp-tls client regarding server cert verification. The default behaviour should only be applicable when no other option regarding the server cert verification is opted in the esp-tls config (e.g. crt_bundle_attach, use_global_ca_store etc.). WARNING : Enabling this option comes with a potential risk of establishing a TLS connection with a server which has a fake identity, provided that the server certificate is not provided either through API or other mechanism like ca_store etc. CONFIG_ESP_WOLFSSL_SMALL_CERT_VERIFY Enable SMALL_CERT_VERIFY Found in: Component config > ESP-TLS Enables server verification with Intermediate CA cert, does not authenticate full chain of trust upto the root CA cert (After Enabling this option client only needs to have Intermediate CA certificate of the server to authenticate server, root CA cert is not necessary). Default value: Yes (enabled) if CONFIG_ESP_TLS_USING_WOLFSSL CONFIG_ESP_DEBUG_WOLFSSL Enable debug logs for wolfSSL Found in: Component config > ESP-TLS Enable detailed debug prints for wolfSSL SSL library. ADC and ADC Calibration Contains: CONFIG_ADC_ONESHOT_CTRL_FUNC_IN_IRAM Place ISR version ADC oneshot mode read function into IRAM Found in: Component config > ADC and ADC Calibration Place ISR version ADC oneshot mode read function into IRAM. Default value: No (disabled) CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE ADC continuous mode driver ISR IRAM-Safe Found in: Component config > ADC and ADC Calibration Ensure the ADC continuous mode ISR is IRAM-Safe. When enabled, the ISR handler will be available when the cache is disabled. Default value: No (disabled) ADC Calibration Configurations Contains: CONFIG_ADC_CALI_EFUSE_TP_ENABLE Use Two Point Values Found in: Component config > ADC and ADC Calibration > ADC Calibration Configurations Some ESP32s have Two Point calibration values burned into eFuse BLOCK3. This option will allow the ADC calibration component to characterize the ADC-Voltage curve using Two Point values if they are available. Default value: Yes (enabled) CONFIG_ADC_CALI_EFUSE_VREF_ENABLE Use eFuse Vref Found in: Component config > ADC and ADC Calibration > ADC Calibration Configurations Some ESP32s have Vref burned into eFuse BLOCK0. This option will allow the ADC calibration component to characterize the ADC-Voltage curve using eFuse Vref if it is available. Default value: Yes (enabled) CONFIG_ADC_CALI_LUT_ENABLE Use Lookup Tables Found in: Component config > ADC and ADC Calibration > ADC Calibration Configurations This option will allow the ADC calibration component to use Lookup Tables to correct for non-linear behavior in 11db attenuation. Other attenuations do not exhibit non-linear behavior hence will not be affected by this option. Default value: Yes (enabled) CONFIG_ADC_DISABLE_DAC_OUTPUT Disable DAC when ADC2 is in use Found in: Component config > ADC and ADC Calibration By default, this is set. The ADC oneshot driver will disable the output of the corresponding DAC channels: ESP32: IO25 and IO26 ESP32S2: IO17 and IO18 Disable this option so as to measure the output of DAC by internal ADC, for test usage. Default value: Yes (enabled) Wireless Coexistence Contains: CONFIG_ESP_COEX_SW_COEXIST_ENABLE Software controls WiFi/Bluetooth coexistence Found in: Component config > Wireless Coexistence If enabled, WiFi & Bluetooth coexistence is controlled by software rather than hardware. Recommended for heavy traffic scenarios. Both coexistence configuration options are automatically managed, no user intervention is required. If only Bluetooth is used, it is recommended to disable this option to reduce binary file size. Default value: Yes (enabled) if CONFIG_BT_ENABLED || CONFIG_IEEE802154_ENABLED || (CONFIG_IEEE802154_ENABLED && CONFIG_BT_ENABLED) Ethernet Contains: CONFIG_ETH_USE_ESP32_EMAC Support ESP32 internal EMAC controller Found in: Component config > Ethernet ESP32 integrates a 10/100M Ethernet MAC controller. Default value: Yes (enabled) Contains: CONFIG_ETH_PHY_INTERFACE PHY interface Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC Select the communication interface between MAC and PHY chip. Available options: Reduced Media Independent Interface (RMII) (CONFIG_ETH_PHY_INTERFACE_RMII) CONFIG_ETH_RMII_CLK_MODE RMII clock mode Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC Select external or internal RMII clock. Available options: Input RMII clock from external (CONFIG_ETH_RMII_CLK_INPUT) MAC will get RMII clock from outside. Note that ESP32 only supports GPIO0 to input the RMII clock. Output RMII clock from internal (CONFIG_ETH_RMII_CLK_OUTPUT) ESP32 can generate RMII clock by internal APLL. This clock can be routed to the external PHY device. ESP32 supports to route the RMII clock to GPIO0/16/17. CONFIG_ETH_RMII_CLK_OUTPUT_GPIO0 Output RMII clock from GPIO0 (Experimental!) Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC GPIO0 can be set to output a pre-divided PLL clock (test only!). Enabling this option will configure GPIO0 to output a 50MHz clock. In fact this clock doesn't have directly relationship with EMAC peripheral. Sometimes this clock won't work well with your PHY chip. You might need to add some extra devices after GPIO0 (e.g. inverter). Note that outputting RMII clock on GPIO0 is an experimental practice. If you want the Ethernet to work with WiFi, don't select GPIO0 output mode for stability. Default value: No (disabled) if CONFIG_ETH_RMII_CLK_OUTPUT && CONFIG_ETH_USE_ESP32_EMAC CONFIG_ETH_RMII_CLK_OUT_GPIO RMII clock GPIO number Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC Set the GPIO number to output RMII Clock. CONFIG_ETH_DMA_BUFFER_SIZE Ethernet DMA buffer size (Byte) Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC Set the size of each buffer used by Ethernet MAC DMA. Range: from 256 to 1600 Default value: 512 CONFIG_ETH_DMA_RX_BUFFER_NUM Amount of Ethernet DMA Rx buffers Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC Number of DMA receive buffers. Each buffer's size is ETH_DMA_BUFFER_SIZE. Larger number of buffers could increase throughput somehow. Range: from 3 to 30 Default value: 10 CONFIG_ETH_DMA_TX_BUFFER_NUM Amount of Ethernet DMA Tx buffers Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC Number of DMA transmit buffers. Each buffer's size is ETH_DMA_BUFFER_SIZE. Larger number of buffers could increase throughput somehow. Range: from 3 to 30 Default value: 10 CONFIG_ETH_SOFT_FLOW_CONTROL Enable software flow control Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC Ethernet MAC engine on ESP32 doesn't feature a flow control logic. The MAC driver can perform a software flow control if you enable this option. Note that, if the RX buffer number is small, enabling software flow control will cause obvious performance loss. Default value: No (disabled) if CONFIG_ETH_DMA_RX_BUFFER_NUM > 15 && CONFIG_ETH_USE_ESP32_EMAC CONFIG_ETH_IRAM_OPTIMIZATION Enable IRAM optimization Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC If enabled, functions related to RX/TX are placed into IRAM. It can improve Ethernet throughput. If disabled, all functions are placed into FLASH. Default value: No (disabled) CONFIG_ETH_USE_SPI_ETHERNET Support SPI to Ethernet Module Found in: Component config > Ethernet ESP-IDF can also support some SPI-Ethernet modules. Default value: Yes (enabled) Contains: CONFIG_ETH_SPI_ETHERNET_DM9051 Use DM9051 Found in: Component config > Ethernet > CONFIG_ETH_USE_SPI_ETHERNET DM9051 is a fast Ethernet controller with an SPI interface. It's also integrated with a 10/100M PHY and MAC. Select this to enable DM9051 driver. CONFIG_ETH_SPI_ETHERNET_W5500 Use W5500 (MAC RAW) Found in: Component config > Ethernet > CONFIG_ETH_USE_SPI_ETHERNET W5500 is a HW TCP/IP embedded Ethernet controller. TCP/IP stack, 10/100 Ethernet MAC and PHY are embedded in a single chip. However the driver in ESP-IDF only enables the RAW MAC mode, making it compatible with the software TCP/IP stack. Say yes to enable W5500 driver. CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL Use KSZ8851SNL Found in: Component config > Ethernet > CONFIG_ETH_USE_SPI_ETHERNET The KSZ8851SNL is a single-chip Fast Ethernet controller consisting of a 10/100 physical layer transceiver (PHY), a MAC, and a Serial Peripheral Interface (SPI). Select this to enable KSZ8851SNL driver. CONFIG_ETH_USE_OPENETH Support OpenCores Ethernet MAC (for use with QEMU) Found in: Component config > Ethernet OpenCores Ethernet MAC driver can be used when an ESP-IDF application is executed in QEMU. This driver is not supported when running on a real chip. Default value: No (disabled) Contains: CONFIG_ETH_OPENETH_DMA_RX_BUFFER_NUM Number of Ethernet DMA Rx buffers Found in: Component config > Ethernet > CONFIG_ETH_USE_OPENETH Number of DMA receive buffers, each buffer is 1600 bytes. Range: from 1 to 64 if CONFIG_ETH_USE_OPENETH Default value: CONFIG_ETH_OPENETH_DMA_TX_BUFFER_NUM Number of Ethernet DMA Tx buffers Found in: Component config > Ethernet > CONFIG_ETH_USE_OPENETH Number of DMA transmit buffers, each buffer is 1600 bytes. Range: from 1 to 64 if CONFIG_ETH_USE_OPENETH Default value: CONFIG_ETH_TRANSMIT_MUTEX Enable Transmit Mutex Found in: Component config > Ethernet Prevents multiple accesses when Ethernet interface is used as shared resource and multiple functionalities might try to access it at a time. Default value: No (disabled) Event Loop Library Contains: CONFIG_ESP_EVENT_LOOP_PROFILING Enable event loop profiling Found in: Component config > Event Loop Library Enables collections of statistics in the event loop library such as the number of events posted to/recieved by an event loop, number of callbacks involved, number of events dropped to to a full event loop queue, run time of event handlers, and number of times/run time of each event handler. Default value: No (disabled) CONFIG_ESP_EVENT_POST_FROM_ISR Support posting events from ISRs Found in: Component config > Event Loop Library Enable posting events from interrupt handlers. Default value: Yes (enabled) CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR Support posting events from ISRs placed in IRAM Found in: Component config > Event Loop Library > CONFIG_ESP_EVENT_POST_FROM_ISR Enable posting events from interrupt handlers placed in IRAM. Enabling this option places API functions esp_event_post and esp_event_post_to in IRAM. Default value: Yes (enabled) GDB Stub Contains: CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME GDBStub at runtime Found in: Component config > GDB Stub Enable builtin GDBStub. This allows to debug the target device using serial port: - Run 'idf.py monitor'. - Wait for the device to initialize. - Press Ctrl+C to interrupt the execution and enter GDB attached to your device for debugging. NOTE: all UART input will be handled by GDBStub. CONFIG_ESP_GDBSTUB_SUPPORT_TASKS Enable listing FreeRTOS tasks through GDB Stub Found in: Component config > GDB Stub If enabled, GDBStub can supply the list of FreeRTOS tasks to GDB. Thread list can be queried from GDB using 'info threads' command. Note that if GDB task lists were corrupted, this feature may not work. If GDBStub fails, try disabling this feature. CONFIG_ESP_GDBSTUB_MAX_TASKS Maximum number of tasks supported by GDB Stub Found in: Component config > GDB Stub > CONFIG_ESP_GDBSTUB_SUPPORT_TASKS Set the number of tasks which GDB Stub will support. Default value: ESP HTTP client Contains: CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS Enable https Found in: Component config > ESP HTTP client This option will enable https protocol by linking esp-tls library and initializing SSL transport Default value: Yes (enabled) CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH Enable HTTP Basic Authentication Found in: Component config > ESP HTTP client This option will enable HTTP Basic Authentication. It is disabled by default as Basic auth uses unencrypted encoding, so it introduces a vulnerability when not using TLS Default value: No (disabled) CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH Enable HTTP Digest Authentication Found in: Component config > ESP HTTP client This option will enable HTTP Digest Authentication. It is enabled by default, but use of this configuration is not recommended as the password can be derived from the exchange, so it introduces a vulnerability when not using TLS Default value: No (disabled) HTTP Server Contains: CONFIG_HTTPD_MAX_REQ_HDR_LEN Max HTTP Request Header Length Found in: Component config > HTTP Server This sets the maximum supported size of headers section in HTTP request packet to be processed by the server Default value: 512 CONFIG_HTTPD_MAX_URI_LEN Max HTTP URI Length Found in: Component config > HTTP Server This sets the maximum supported size of HTTP request URI to be processed by the server Default value: 512 CONFIG_HTTPD_ERR_RESP_NO_DELAY Use TCP_NODELAY socket option when sending HTTP error responses Found in: Component config > HTTP Server Using TCP_NODEALY socket option ensures that HTTP error response reaches the client before the underlying socket is closed. Please note that turning this off may cause multiple test failures Default value: Yes (enabled) CONFIG_HTTPD_PURGE_BUF_LEN Length of temporary buffer for purging data Found in: Component config > HTTP Server This sets the size of the temporary buffer used to receive and discard any remaining data that is received from the HTTP client in the request, but not processed as part of the server HTTP request handler. If the remaining data is larger than the available buffer size, the buffer will be filled in multiple iterations. The buffer should be small enough to fit on the stack, but large enough to avoid excessive iterations. Default value: 32 CONFIG_HTTPD_LOG_PURGE_DATA Log purged content data at Debug level Found in: Component config > HTTP Server Enabling this will log discarded binary HTTP request data at Debug level. For large content data this may not be desirable as it will clutter the log. Default value: No (disabled) CONFIG_HTTPD_WS_SUPPORT WebSocket server support Found in: Component config > HTTP Server This sets the WebSocket server support. Default value: No (disabled) CONFIG_HTTPD_QUEUE_WORK_BLOCKING httpd_queue_work as blocking API Found in: Component config > HTTP Server This makes httpd_queue_work() API to wait until a message space is available on UDP control socket. It internally uses a counting semaphore with count set to LWIP_UDP_RECVMBOX_SIZE to achieve this. This config will slightly change API behavior to block until message gets delivered on control socket. ESP HTTPS OTA Contains: CONFIG_ESP_HTTPS_OTA_DECRYPT_CB Provide decryption callback Found in: Component config > ESP HTTPS OTA Exposes an additional callback whereby firmware data could be decrypted before being processed by OTA update component. This can help to integrate external encryption related format and removal of such encapsulation layer from firmware image. Default value: No (disabled) CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP Allow HTTP for OTA (WARNING: ONLY FOR TESTING PURPOSE, READ HELP) Found in: Component config > ESP HTTPS OTA It is highly recommended to keep HTTPS (along with server certificate validation) enabled. Enabling this option comes with potential risk of: - Non-encrypted communication channel with server - Accepting firmware upgrade image from server with fake identity Default value: No (disabled) ESP HTTPS server Contains: CONFIG_ESP_HTTPS_SERVER_ENABLE Enable ESP_HTTPS_SERVER component Found in: Component config > ESP HTTPS server Enable ESP HTTPS server component Hardware Settings Contains: Chip revision Contains: CONFIG_ESP32_REV_MIN Minimum Supported ESP32 Revision Found in: Component config > Hardware Settings > Chip revision Required minimum chip revision. ESP-IDF will check for it and reject to boot if the chip revision fails the check. This ensures the chip used will have some modifications (features, or bugfixes). The complied binary will only support chips above this revision, this will also help to reduce binary size. Available options: Rev v0.0 (ECO0) (CONFIG_ESP32_REV_MIN_0) Rev v1.0 (ECO1) (CONFIG_ESP32_REV_MIN_1) Rev v1.1 (ECO1.1) (CONFIG_ESP32_REV_MIN_1_1) Rev v2.0 (ECO2) (CONFIG_ESP32_REV_MIN_2) Rev v3.0 (ECO3) (CONFIG_ESP32_REV_MIN_3) Rev v3.1 (ECO4) (CONFIG_ESP32_REV_MIN_3_1) CONFIG_ESP_REV_NEW_CHIP_TEST Internal test mode Found in: Component config > Hardware Settings > Chip revision For internal chip testing, a small number of new versions chips didn't update the version field in eFuse, you can enable this option to force the software recognize the chip version based on the rev selected in menuconfig. Default value: No (disabled) MAC Config Contains: CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES Number of universally administered (by IEEE) MAC address Found in: Component config > Hardware Settings > MAC Config Configure the number of universally administered (by IEEE) MAC addresses. During initialization, MAC addresses for each network interface are generated or derived from a single base MAC address. If the number of universal MAC addresses is four, all four interfaces (WiFi station, WiFi softap, Bluetooth and Ethernet) receive a universally administered MAC address. These are generated sequentially by adding 0, 1, 2 and 3 (respectively) to the final octet of the base MAC address. If the number of universal MAC addresses is two, only two interfaces (WiFi station and Bluetooth) receive a universally administered MAC address. These are generated sequentially by adding 0 and 1 (respectively) to the base MAC address. The remaining two interfaces (WiFi softap and Ethernet) receive local MAC addresses. These are derived from the universal WiFi station and Bluetooth MAC addresses, respectively. When using the default (Espressif-assigned) base MAC address, either setting can be used. When using a custom universal MAC address range, the correct setting will depend on the allocation of MAC addresses in this range (either 2 or 4 per device.) Available options: Two (CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES_TWO) Four (CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES_FOUR) CONFIG_ESP_MAC_IGNORE_MAC_CRC_ERROR Ignore MAC CRC error (not recommended) Found in: Component config > Hardware Settings > MAC Config If you have an invalid MAC CRC (ESP_ERR_INVALID_CRC) problem and you still want to use this chip, you can enable this option to bypass such an error. This applies to both MAC_FACTORY and CUSTOM_MAC efuses. Default value: No (disabled) CONFIG_ESP_MAC_USE_CUSTOM_MAC_AS_BASE_MAC Enable using custom mac as base mac Found in: Component config > Hardware Settings > MAC Config When this configuration is enabled, the user can invoke esp_read_mac to obtain the desired type of MAC using a custom MAC as the base MAC. Default value: No (disabled) Sleep Config Contains: CONFIG_ESP_SLEEP_POWER_DOWN_FLASH Power down flash in light sleep when there is no SPIRAM Found in: Component config > Hardware Settings > Sleep Config If enabled, chip will try to power down flash as part of esp_light_sleep_start(), which costs more time when chip wakes up. Can only be enabled if there is no SPIRAM configured. This option will power down flash under a strict but relatively safe condition. Also, it is possible to power down flash under a relaxed condition by using esp_sleep_pd_config() to set ESP_PD_DOMAIN_VDDSDIO to ESP_PD_OPTION_OFF. It should be noted that there is a risk in powering down flash, you can refer ESP-IDF Programming Guide/API Reference/System API/Sleep Modes/Power-down of Flash for more details. CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND Pull-up Flash CS pin in light sleep Found in: Component config > Hardware Settings > Sleep Config All IOs will be set to isolate(floating) state by default during sleep. Since the power supply of SPI Flash is not lost during lightsleep, if its CS pin is recognized as low level(selected state) in the floating state, there will be a large current leakage, and the data in Flash may be corrupted by random signals on other SPI pins. Select this option will set the CS pin of Flash to PULL-UP state during sleep, but this will increase the sleep current about 10 uA. If you are developing with esp32xx modules, you must select this option, but if you are developing with chips, you can also pull up the CS pin of SPI Flash in the external circuit to save power consumption caused by internal pull-up during sleep. (!!! Don't deselect this option if you don't have external SPI Flash CS pin pullups.) CONFIG_ESP_SLEEP_PSRAM_LEAKAGE_WORKAROUND Pull-up PSRAM CS pin in light sleep Found in: Component config > Hardware Settings > Sleep Config All IOs will be set to isolate(floating) state by default during sleep. Since the power supply of PSRAM is not lost during lightsleep, if its CS pin is recognized as low level(selected state) in the floating state, there will be a large current leakage, and the data in PSRAM may be corrupted by random signals on other SPI pins. Select this option will set the CS pin of PSRAM to PULL-UP state during sleep, but this will increase the sleep current about 10 uA. If you are developing with esp32xx modules, you must select this option, but if you are developing with chips, you can also pull up the CS pin of PSRAM in the external circuit to save power consumption caused by internal pull-up during sleep. (!!! Don't deselect this option if you don't have external PSRAM CS pin pullups.) Default value: Yes (enabled) if CONFIG_SPIRAM CONFIG_ESP_SLEEP_MSPI_NEED_ALL_IO_PU Pull-up all SPI pins in light sleep Found in: Component config > Hardware Settings > Sleep Config To reduce leakage current, some types of SPI Flash/RAM only need to pull up the CS pin during light sleep. But there are also some kinds of SPI Flash/RAM that need to pull up all pins. It depends on the SPI Flash/RAM chip used. CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND light sleep GPIO reset workaround Found in: Component config > Hardware Settings > Sleep Config esp32c2, esp32c3, esp32s3, esp32c6 and esp32h2 will reset at wake-up if GPIO is received a small electrostatic pulse during light sleep, with specific condition GPIO needs to be configured as input-mode only The pin receives a small electrostatic pulse, and reset occurs when the pulse voltage is higher than 6 V For GPIO set to input mode only, it is not a good practice to leave it open/floating, The hardware design needs to controlled it with determined supply or ground voltage is necessary. This option provides a software workaround for this issue. Configure to isolate all GPIO pins in sleep state. CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY Extra delay (in us) after flash powerdown sleep wakeup to wait flash ready Found in: Component config > Hardware Settings > Sleep Config When the chip exits sleep, the CPU and the flash chip are powered on at the same time. CPU will run rom code (deepsleep) or ram code (lightsleep) first, and then load or execute code from flash. Some flash chips need sufficient time to pass between power on and first read operation. By default, without any extra delay, this time is approximately 900us, although some flash chip types need more than that. (!!! Please adjust this value according to the Data Sheet of SPI Flash used in your project.) In Flash Data Sheet, the parameters that define the Flash ready timing after power-up (minimum time from Vcc(min) to CS activeare) usually named tVSL in ELECTRICAL CHARACTERISTICS chapter, and the configuration value here should be: ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY = tVSL - 900 For esp32 and esp32s3, the default extra delay is set to 2000us. When optimizing startup time for applications which require it, this value may be reduced. If you are seeing "flash read err, 1000" message printed to the console after deep sleep reset on esp32, or triggered RTC_WDT/LP_WDT after lightsleep wakeup, try increasing this value. (For esp32, the delay will be executed in both deep sleep and light sleep wake up flow. For chips after esp32, the delay will be executed only in light sleep flow, the delay controlled by the EFUSE_FLASH_TPUW in ROM will be executed in deepsleep wake up flow.) Range: from 0 to 5000 Default value: 2000 0 CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION Check the cache safety of the sleep wakeup code in sleep process Found in: Component config > Hardware Settings > Sleep Config Enabling it will check the cache safety of the code before the flash power is ready after light sleep wakeup, and check PM_SLP_IRAM_OPT related code cache safety. This option is only for code quality inspection. Enabling it will increase the time overhead of entering and exiting sleep. It is not recommended to enable it in the release version. Default value: No (disabled) CONFIG_ESP_SLEEP_DEBUG esp sleep debug Found in: Component config > Hardware Settings > Sleep Config Enable esp sleep debug. Default value: No (disabled) CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS Allow to enable internal pull-up/downs for the Deep-Sleep wakeup IOs Found in: Component config > Hardware Settings > Sleep Config When using rtc gpio wakeup source during deepsleep without external pull-up/downs, you may want to make use of the internal ones. Default value: Yes (enabled) CONFIG_ESP_SLEEP_EVENT_CALLBACKS Enable registration of sleep event callbacks Found in: Component config > Hardware Settings > Sleep Config If enabled, it allows user to register sleep event callbacks. It is primarily designed for internal developers and customers can use PM_LIGHT_SLEEP_CALLBACKS as an alternative. NOTE: These callbacks are executed from the IDLE task context hence you cannot have any blocking calls in your callbacks. NOTE: Enabling these callbacks may change sleep duration calculations based on time spent in callback and hence it is highly recommended to keep them as short as possible. Default value: No (disabled) if CONFIG_FREERTOS_USE_TICKLESS_IDLE ESP_SLEEP_WORKAROUND RTC Clock Config Contains: CONFIG_RTC_CLK_SRC RTC clock source Found in: Component config > Hardware Settings > RTC Clock Config Choose which clock is used as RTC clock source. "Internal 150kHz oscillator" option provides lowest deep sleep current consumption, and does not require extra external components. However frequency stability with respect to temperature is poor, so time may drift in deep/light sleep modes. "External 32kHz crystal" provides better frequency stability, at the expense of slightly higher (1uA) deep sleep current consumption. "External 32kHz oscillator" allows using 32kHz clock generated by an external circuit. In this case, external clock signal must be connected to 32K_XN pin. Amplitude should be <1.2V in case of sine wave signal, and <1V in case of square wave signal. Common mode voltage should be 0.1 < Vcm < 0.5Vamp, where Vamp is the signal amplitude. Additionally, 1nF capacitor must be connected between 32K_XP pin and ground. 32K_XP pin can not be used as a GPIO in this case. "Internal 8.5MHz oscillator divided by 256" option results in higher deep sleep current (by 5uA) but has better frequency stability than the internal 150kHz oscillator. It does not require external components. Available options: Internal 150 kHz RC oscillator (CONFIG_RTC_CLK_SRC_INT_RC) External 32kHz crystal (CONFIG_RTC_CLK_SRC_EXT_CRYS) External 32kHz oscillator at 32K_XN pin (CONFIG_RTC_CLK_SRC_EXT_OSC) Internal 8.5MHz oscillator, divided by 256 (~33kHz) (CONFIG_RTC_CLK_SRC_INT_8MD256) CONFIG_RTC_EXT_CRYST_ADDIT_CURRENT_METHOD Additional current for external 32kHz crystal Found in: Component config > Hardware Settings > RTC Clock Config With some 32kHz crystal configurations, the X32N and X32P pins may not have enough drive strength to keep the crystal oscillating. Choose the method to provide additional current from touchpad 9 to the external 32kHz crystal. Note that the deep sleep current is slightly high (4-5uA) and the touchpad and the wakeup sources of both touchpad and ULP are not available in method 1 and method 2. This problem is fixed in ESP32 ECO 3, so this workaround is not needed. Setting the project configuration to minimum revision ECO3 will disable this option, , allow all wakeup sources, and save some code size. "None" option will not provide additional current to external crystal "Method 1" option can't ensure 100% to solve the external 32k crystal start failed issue, but the touchpad can work in this method. "Method 2" option can solve the external 32k issue, but the touchpad can't work in this method. Available options: None (CONFIG_RTC_EXT_CRYST_ADDIT_CURRENT_NONE) Method 1 (CONFIG_RTC_EXT_CRYST_ADDIT_CURRENT) Method 2 (CONFIG_RTC_EXT_CRYST_ADDIT_CURRENT_V2) CONFIG_RTC_CLK_CAL_CYCLES Number of cycles for RTC_SLOW_CLK calibration Found in: Component config > Hardware Settings > RTC Clock Config When the startup code initializes RTC_SLOW_CLK, it can perform calibration by comparing the RTC_SLOW_CLK frequency with main XTAL frequency. This option sets the number of RTC_SLOW_CLK cycles measured by the calibration routine. Higher numbers increase calibration precision, which may be important for applications which spend a lot of time in deep sleep. Lower numbers reduce startup time. When this option is set to 0, clock calibration will not be performed at startup, and approximate clock frequencies will be assumed: 150000 Hz if internal RC oscillator is used as clock source. For this use value 1024. 32768 Hz if the 32k crystal oscillator is used. For this use value 3000 or more. In case more value will help improve the definition of the launch of the crystal. If the crystal could not start, it will be switched to internal RC. Range: from 0 to 27000 if CONFIG_RTC_CLK_SRC_EXT_CRYS || CONFIG_RTC_CLK_SRC_EXT_OSC || CONFIG_RTC_CLK_SRC_INT_8MD256 from 0 to 32766 Default value: 3000 if CONFIG_RTC_CLK_SRC_EXT_CRYS || CONFIG_RTC_CLK_SRC_EXT_OSC || CONFIG_RTC_CLK_SRC_INT_8MD256 1024 CONFIG_RTC_XTAL_CAL_RETRY Number of attempts to repeat 32k XTAL calibration Found in: Component config > Hardware Settings > RTC Clock Config Number of attempts to repeat 32k XTAL calibration before giving up and switching to the internal RC. Increase this option if the 32k crystal oscillator does not start and switches to internal RC. Default value: Peripheral Control Contains: CONFIG_PERIPH_CTRL_FUNC_IN_IRAM Place peripheral control functions into IRAM Found in: Component config > Hardware Settings > Peripheral Control Place peripheral control functions (e.g. periph_module_reset) into IRAM, so that these functions can be IRAM-safe and able to be called in the other IRAM interrupt context. Default value: No (disabled) ETM Configuration Contains: CONFIG_ETM_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Hardware Settings > ETM Configuration Wether to enable the debug log message for ETM core driver. Note that, this option only controls the ETM related driver log, won't affect other drivers. Default value: No (disabled) if SOC_ETM_SUPPORTED GDMA Configuration Contains: CONFIG_GDMA_CTRL_FUNC_IN_IRAM Place GDMA control functions into IRAM Found in: Component config > Hardware Settings > GDMA Configuration Place GDMA control functions (like start/stop/append/reset) into IRAM, so that these functions can be IRAM-safe and able to be called in the other IRAM interrupt context. Enabling this option can improve driver performance as well. Default value: No (disabled) if SOC_GDMA_SUPPORTED CONFIG_GDMA_ISR_IRAM_SAFE GDMA ISR IRAM-Safe Found in: Component config > Hardware Settings > GDMA Configuration This will ensure the GDMA interrupt handler is IRAM-Safe, allow to avoid flash cache misses, and also be able to run whilst the cache is disabled. (e.g. SPI Flash write). Default value: No (disabled) if SOC_GDMA_SUPPORTED CONFIG_GDMA_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Hardware Settings > GDMA Configuration Wether to enable the debug log message for GDMA driver. Note that, this option only controls the GDMA driver log, won't affect other drivers. Default value: No (disabled) if SOC_GDMA_SUPPORTED Main XTAL Config Contains: CONFIG_XTAL_FREQ_SEL Main XTAL frequency Found in: Component config > Hardware Settings > Main XTAL Config This option selects the operating frequency of the XTAL (crystal) clock used to drive the ESP target. The selected value MUST reflect the frequency of the given hardware. Note: The XTAL_FREQ_AUTO option allows the ESP target to automatically estimating XTAL clock's operating frequency. However, this feature is only supported on the ESP32. The ESP32 uses the internal 8MHZ as a reference when estimating. Due to the internal oscillator's frequency being temperature dependent, usage of the XTAL_FREQ_AUTO is not recommended in applications that operate in high ambient temperatures or use high-temperature qualified chips and modules. Available options: 24 MHz (CONFIG_XTAL_FREQ_24) 26 MHz (CONFIG_XTAL_FREQ_26) 32 MHz (CONFIG_XTAL_FREQ_32) 40 MHz (CONFIG_XTAL_FREQ_40) Autodetect (CONFIG_XTAL_FREQ_AUTO) Crypto DPA Protection Contains: CONFIG_ESP_CRYPTO_DPA_PROTECTION_AT_STARTUP Enable crypto DPA protection at startup Found in: Component config > Hardware Settings > Crypto DPA Protection This config controls the DPA (Differential Power Analysis) protection knob for the crypto peripherals. DPA protection dynamically adjusts the clock frequency of the crypto peripheral. DPA protection helps to make it difficult to perform SCA attacks on the crypto peripherals. However, there is also associated performance impact based on the security level set. Please refer to the TRM for more details. Default value: Yes (enabled) if SOC_CRYPTO_DPA_PROTECTION_SUPPORTED CONFIG_ESP_CRYPTO_DPA_PROTECTION_LEVEL DPA protection level Found in: Component config > Hardware Settings > Crypto DPA Protection > CONFIG_ESP_CRYPTO_DPA_PROTECTION_AT_STARTUP Configure the DPA protection security level Available options: Security level low (CONFIG_ESP_CRYPTO_DPA_PROTECTION_LEVEL_LOW) Security level medium (CONFIG_ESP_CRYPTO_DPA_PROTECTION_LEVEL_MEDIUM) Security level high (CONFIG_ESP_CRYPTO_DPA_PROTECTION_LEVEL_HIGH) LCD and Touch Panel Contains: LCD Peripheral Configuration Contains: CONFIG_LCD_PANEL_IO_FORMAT_BUF_SIZE LCD panel io format buffer size Found in: Component config > LCD and Touch Panel > LCD Peripheral Configuration LCD driver allocates an internal buffer to transform the data into a proper format, because of the endian order mismatch. This option is to set the size of the buffer, in bytes. Default value: 32 CONFIG_LCD_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > LCD and Touch Panel > LCD Peripheral Configuration Wether to enable the debug log message for LCD driver. Note that, this option only controls the LCD driver log, won't affect other drivers. Default value: No (disabled) CONFIG_LCD_RGB_ISR_IRAM_SAFE RGB LCD ISR IRAM-Safe Found in: Component config > LCD and Touch Panel > LCD Peripheral Configuration Ensure the LCD interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). If you want the LCD driver to keep flushing the screen even when cache ops disabled, you can enable this option. Note, this will also increase the IRAM usage. Default value: No (disabled) if SOC_LCD_RGB_SUPPORTED CONFIG_LCD_RGB_RESTART_IN_VSYNC Restart transmission in VSYNC Found in: Component config > LCD and Touch Panel > LCD Peripheral Configuration Reset the GDMA channel every VBlank to stop permanent desyncs from happening. Only need to enable it when in your application, the DMA can't deliver data as fast as the LCD consumes it. Default value: No (disabled) if SOC_LCD_RGB_SUPPORTED ESP NETIF Adapter Contains: CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL IP Address lost timer interval (seconds) Found in: Component config > ESP NETIF Adapter The value of 0 indicates the IP lost timer is disabled, otherwise the timer is enabled. The IP address may be lost because of some reasons, e.g. when the station disconnects from soft-AP, or when DHCP IP renew fails etc. If the IP lost timer is enabled, it will be started everytime the IP is lost. Event SYSTEM_EVENT_STA_LOST_IP will be raised if the timer expires. The IP lost timer is stopped if the station get the IP again before the timer expires. Range: from 0 to 65535 Default value: 120 CONFIG_ESP_NETIF_USE_TCPIP_STACK_LIB TCP/IP Stack Library Found in: Component config > ESP NETIF Adapter Choose the TCP/IP Stack to work, for example, LwIP, uIP, etc. Available options: LwIP (CONFIG_ESP_NETIF_TCPIP_LWIP) lwIP is a small independent implementation of the TCP/IP protocol suite. Loopback (CONFIG_ESP_NETIF_LOOPBACK) Dummy implementation of esp-netif functionality which connects driver transmit to receive function. This option is for testing purpose only CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS Use esp_err_t to report errors from esp_netif_receive Found in: Component config > ESP NETIF Adapter Enable if esp_netif_receive() should return error code. This is useful to inform upper layers that packet input to TCP/IP stack failed, so the upper layers could implement flow control. This option is disabled by default due to backward compatibility and will be enabled in v6.0 (IDF-7194) Default value: No (disabled) CONFIG_ESP_NETIF_L2_TAP Enable netif L2 TAP support Found in: Component config > ESP NETIF Adapter A user program can read/write link layer (L2) frames from/to ESP TAP device. The ESP TAP device can be currently associated only with Ethernet physical interfaces. CONFIG_ESP_NETIF_L2_TAP_MAX_FDS Maximum number of opened L2 TAP File descriptors Found in: Component config > ESP NETIF Adapter > CONFIG_ESP_NETIF_L2_TAP Maximum number of opened File descriptors (FD's) associated with ESP TAP device. ESP TAP FD's take up a certain amount of memory, and allowing fewer FD's to be opened at the same time conserves memory. Range: from 1 to 10 if CONFIG_ESP_NETIF_L2_TAP Default value: CONFIG_ESP_NETIF_L2_TAP_RX_QUEUE_SIZE Size of L2 TAP Rx queue Found in: Component config > ESP NETIF Adapter > CONFIG_ESP_NETIF_L2_TAP Maximum number of frames queued in opened File descriptor. Once the queue is full, the newly arriving frames are dropped until the queue has enough room to accept incoming traffic (Tail Drop queue management). Range: from 1 to 100 if CONFIG_ESP_NETIF_L2_TAP Default value: 20 if CONFIG_ESP_NETIF_L2_TAP CONFIG_ESP_NETIF_BRIDGE_EN Enable LwIP IEEE 802.1D bridge Found in: Component config > ESP NETIF Adapter Enable LwIP IEEE 802.1D bridge support in ESP-NETIF. Note that "Number of clients store data in netif" (LWIP_NUM_NETIF_CLIENT_DATA) option needs to be properly configured to be LwIP bridge avaiable! Default value: No (disabled) Partition API Configuration PHY Contains: CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE Store phy calibration data in NVS Found in: Component config > PHY If this option is enabled, NVS will be initialized and calibration data will be loaded from there. PHY calibration will be skipped on deep sleep wakeup. If calibration data is not found, full calibration will be performed and stored in NVS. Normally, only partial calibration will be performed. If this option is disabled, full calibration will be performed. If it's easy that your board calibrate bad data, choose 'n'. Two cases for example, you should choose 'n': 1.If your board is easy to be booted up with antenna disconnected. 2.Because of your board design, each time when you do calibration, the result are too unstable. If unsure, choose 'y'. Default value: Yes (enabled) CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION Use a partition to store PHY init data Found in: Component config > PHY If enabled, PHY init data will be loaded from a partition. When using a custom partition table, make sure that PHY data partition is included (type: 'data', subtype: 'phy'). With default partition tables, this is done automatically. If PHY init data is stored in a partition, it has to be flashed there, otherwise runtime error will occur. If this option is not enabled, PHY init data will be embedded into the application binary. If unsure, choose 'n'. Default value: No (disabled) Contains: CONFIG_ESP_PHY_DEFAULT_INIT_IF_INVALID Reset default PHY init data if invalid Found in: Component config > PHY > CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION If enabled, PHY init data will be restored to default if it cannot be verified successfully to avoid endless bootloops. If unsure, choose 'n'. Default value: No (disabled) if CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN Support multiple PHY init data bin Found in: Component config > PHY > CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION If enabled, the corresponding PHY init data type can be automatically switched according to the country code. China's PHY init data bin is used by default. Can be modified by country information in API esp_wifi_set_country(). The priority of switching the PHY init data type is: 1. Country configured by API esp_wifi_set_country() and the parameter policy is WIFI_COUNTRY_POLICY_MANUAL. 2. Country notified by the connected AP. 3. Country configured by API esp_wifi_set_country() and the parameter policy is WIFI_COUNTRY_POLICY_AUTO. Default value: No (disabled) if CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION && CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN_EMBED Support embedded multiple phy init data bin to app bin Found in: Component config > PHY > CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION > CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN If enabled, multiple phy init data bin will embedded into app bin If not enabled, multiple phy init data bin will still leave alone, and need to be flashed by users. Default value: No (disabled) if CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN && CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION CONFIG_ESP_PHY_INIT_DATA_ERROR Terminate operation when PHY init data error Found in: Component config > PHY > CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION > CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN If enabled, when an error occurs while the PHY init data is updated, the program will terminate and restart. If not enabled, the PHY init data will not be updated when an error occurs. Default value: No (disabled) if CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN && CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION CONFIG_ESP_PHY_MAX_WIFI_TX_POWER Max WiFi TX power (dBm) Found in: Component config > PHY Set maximum transmit power for WiFi radio. Actual transmit power for high data rates may be lower than this setting. Range: from 10 to 20 Default value: 20 CONFIG_ESP_PHY_MAC_BB_PD Power down MAC and baseband of Wi-Fi and Bluetooth when PHY is disabled Found in: Component config > PHY If enabled, the MAC and baseband of Wi-Fi and Bluetooth will be powered down when PHY is disabled. Enabling this setting reduces power consumption by a small amount but increases RAM use by approximately 4 KB(Wi-Fi only), 2 KB(Bluetooth only) or 5.3 KB(Wi-Fi + Bluetooth). Default value: No (disabled) if SOC_PM_SUPPORT_MAC_BB_PD && CONFIG_FREERTOS_USE_TICKLESS_IDLE CONFIG_ESP_PHY_REDUCE_TX_POWER Reduce PHY TX power when brownout reset Found in: Component config > PHY When brownout reset occurs, reduce PHY TX power to keep the code running. Default value: No (disabled) CONFIG_ESP_PHY_ENABLE_USB Enable USB when phy init Found in: Component config > PHY When using USB Serial/JTAG/OTG/CDC, PHY should enable USB, otherwise USB module can not work properly. Notice: Enabling this configuration option will slightly impact wifi performance. Default value: No (disabled) if SOC_USB_OTG_SUPPORTED || CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG || CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG CONFIG_ESP_PHY_CALIBRATION_MODE Calibration mode Found in: Component config > PHY Select PHY calibration mode. During RF initialization, the partial calibration method is used by default for RF calibration. Full calibration takes about 100ms more than partial calibration. If boot duration is not critical, it is suggested to use the full calibration method. No calibration method is only used when the device wakes up from deep sleep. Available options: Calibration partial (CONFIG_ESP_PHY_RF_CAL_PARTIAL) Calibration none (CONFIG_ESP_PHY_RF_CAL_NONE) Calibration full (CONFIG_ESP_PHY_RF_CAL_FULL) CONFIG_ESP_PHY_IMPROVE_RX_11B Improve Wi-Fi receive 11b pkts Found in: Component config > PHY This is a workaround to improve Wi-Fi receive 11b pkts for some modules using AC-DC power supply with high interference, enable this option will sacrifice Wi-Fi OFDM receive performance. But to guarantee 11b receive performance serves as a bottom line in this case. Default value: No (disabled) if SOC_PHY_IMPROVE_RX_11B Power Management Contains: CONFIG_PM_ENABLE Support for power management Found in: Component config > Power Management If enabled, application is compiled with support for power management. This option has run-time overhead (increased interrupt latency, longer time to enter idle state), and it also reduces accuracy of RTOS ticks and timers used for timekeeping. Enable this option if application uses power management APIs. Default value: No (disabled) if __DOXYGEN__ CONFIG_PM_DFS_INIT_AUTO Enable dynamic frequency scaling (DFS) at startup Found in: Component config > Power Management > CONFIG_PM_ENABLE If enabled, startup code configures dynamic frequency scaling. Max CPU frequency is set to DEFAULT_CPU_FREQ_MHZ setting, min frequency is set to XTAL frequency. If disabled, DFS will not be active until the application configures it using esp_pm_configure function. Default value: No (disabled) if CONFIG_PM_ENABLE CONFIG_PM_PROFILING Enable profiling counters for PM locks Found in: Component config > Power Management > CONFIG_PM_ENABLE If enabled, esp_pm_* functions will keep track of the amount of time each of the power management locks has been held, and esp_pm_dump_locks function will print this information. This feature can be used to analyze which locks are preventing the chip from going into a lower power state, and see what time the chip spends in each power saving mode. This feature does incur some run-time overhead, so should typically be disabled in production builds. Default value: No (disabled) if CONFIG_PM_ENABLE CONFIG_PM_TRACE Enable debug tracing of PM using GPIOs Found in: Component config > Power Management > CONFIG_PM_ENABLE If enabled, some GPIOs will be used to signal events such as RTOS ticks, frequency switching, entry/exit from idle state. Refer to pm_trace.c file for the list of GPIOs. This feature is intended to be used when analyzing/debugging behavior of power management implementation, and should be kept disabled in applications. Default value: No (disabled) if CONFIG_PM_ENABLE CONFIG_PM_SLP_IRAM_OPT Put lightsleep related codes in internal RAM Found in: Component config > Power Management If enabled, about 2.1KB of lightsleep related source code would be in IRAM and chip would sleep longer for 310us at 160MHz CPU frequency most each time. This feature is intended to be used when lower power consumption is needed while there is enough place in IRAM to place source code. CONFIG_PM_RTOS_IDLE_OPT Put RTOS IDLE related codes in internal RAM Found in: Component config > Power Management If enabled, about 180Bytes of RTOS_IDLE related source code would be in IRAM and chip would sleep longer for 20us at 160MHz CPU frequency most each time. This feature is intended to be used when lower power consumption is needed while there is enough place in IRAM to place source code. CONFIG_PM_SLP_DISABLE_GPIO Disable all GPIO when chip at sleep Found in: Component config > Power Management This feature is intended to disable all GPIO pins at automantic sleep to get a lower power mode. If enabled, chips will disable all GPIO pins at automantic sleep to reduce about 200~300 uA current. If you want to specifically use some pins normally as chip wakes when chip sleeps, you can call 'gpio_sleep_sel_dis' to disable this feature on those pins. You can also keep this feature on and call 'gpio_sleep_set_direction' and 'gpio_sleep_set_pull_mode' to have a different GPIO configuration at sleep. Waring: If you want to enable this option on ESP32, you should enable GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL at first, otherwise you will not be able to switch pullup/pulldown mode. CONFIG_PM_LIGHTSLEEP_RTC_OSC_CAL_INTERVAL Calibrate the RTC_FAST/SLOW clock every N times of light sleep Found in: Component config > Power Management The value of this option determines the calibration interval of the RTC_FAST/SLOW clock during sleep when power management is enabled. When it is configured as N, the RTC_FAST/SLOW clock will be calibrated every N times of lightsleep. Decreasing this value will increase the time the chip is in the active state, thereby increasing the average power consumption of the chip. Increasing this value can reduce the average power consumption, but when the external environment changes drastically and the chip RTC_FAST/SLOW oscillator frequency drifts, it may cause system instability. Range: from 1 to 128 if CONFIG_PM_ENABLE Default value: 1 if CONFIG_PM_ENABLE CONFIG_PM_POWER_DOWN_CPU_IN_LIGHT_SLEEP Power down CPU in light sleep Found in: Component config > Power Management If enabled, the CPU will be powered down in light sleep, ESP chips supports saving and restoring CPU's running context before and after light sleep, the feature provides applications with seamless CPU powerdowned lightsleep without user awareness. But this will takes up some internal memory. On esp32c3 soc, enabling this option will consume 1.68 KB of internal RAM and will reduce sleep current consumption by about 100 uA. On esp32s3 soc, enabling this option will consume 8.58 KB of internal RAM and will reduce sleep current consumption by about 650 uA. Default value: Yes (enabled) if SOC_PM_SUPPORT_CPU_PD CONFIG_PM_POWER_DOWN_PERIPHERAL_IN_LIGHT_SLEEP Power down Digital Peripheral in light sleep (EXPERIMENTAL) Found in: Component config > Power Management If enabled, digital peripherals will be powered down in light sleep, it will reduce sleep current consumption by about 100 uA. Chip will save/restore register context at sleep/wake time to keep the system running. Enabling this option will increase static RAM and heap usage, the actual cost depends on the peripherals you have initialized. In order to save/restore the context of the necessary hardware for FreeRTOS to run, it will need at least 4.55 KB free heap at sleep time. Otherwise sleep will not power down the peripherals. Note1: Please use this option with caution, the current IDF does not support the retention of all peripherals. When the digital peripherals are powered off and a sleep and wake-up is completed, the peripherals that have not saved the running context are equivalent to performing a reset. !!! Please confirm the peripherals used in your application and their sleep retention support status before enabling this option, peripherals sleep retention driver support status is tracked in power_management.rst Note2: When this option is enabled simultaneously with FREERTOS_USE_TICKLESS_IDLE, since the UART will be powered down, the uart FIFO will be flushed before sleep to avoid data loss, however, this has the potential to block the sleep process and cause the wakeup time to be skipped, which will cause the tick of freertos to not be compensated correctly when returning from sleep and cause the system to crash. To avoid this, you can increase FREERTOS_IDLE_TIME_BEFORE_SLEEP threshold in menuconfig. Default value: No (disabled) if SOC_PAU_SUPPORTED CONFIG_PM_LIGHT_SLEEP_CALLBACKS Enable registration of pm light sleep callbacks Found in: Component config > Power Management If enabled, it allows user to register entry and exit callbacks which are called before and after entering auto light sleep. NOTE: These callbacks are executed from the IDLE task context hence you cannot have any blocking calls in your callbacks. NOTE: Enabling these callbacks may change sleep duration calculations based on time spent in callback and hence it is highly recommended to keep them as short as possible Default value: No (disabled) if CONFIG_FREERTOS_USE_TICKLESS_IDLE ESP PSRAM Contains: CONFIG_SPIRAM Support for external, SPI-connected RAM Found in: Component config > ESP PSRAM This enables support for an external SPI RAM chip, connected in parallel with the main SPI flash chip. SPI RAM config Contains: CONFIG_SPIRAM_TYPE Type of SPI RAM chip in use Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Available options: Auto-detect (CONFIG_SPIRAM_TYPE_AUTO) ESP-PSRAM16 or APS1604 (CONFIG_SPIRAM_TYPE_ESPPSRAM16) ESP-PSRAM32 (CONFIG_SPIRAM_TYPE_ESPPSRAM32) ESP-PSRAM64 or LY68L6400 (CONFIG_SPIRAM_TYPE_ESPPSRAM64) CONFIG_SPIRAM_SPEED Set RAM clock speed Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Select the speed for the SPI RAM chip. If SPI RAM is enabled, we only support three combinations of SPI speed mode we supported now: Flash SPI running at 40Mhz and RAM SPI running at 40Mhz Flash SPI running at 80Mhz and RAM SPI running at 40Mhz Flash SPI running at 80Mhz and RAM SPI running at 80Mhz Note: If the third mode(80Mhz+80Mhz) is enabled for SPI RAM of type 32MBit, one of the HSPI/VSPI host will be occupied by the system. Which SPI host to use can be selected by the config item SPIRAM_OCCUPY_SPI_HOST. Application code should never touch HSPI/VSPI hardware in this case. The option to select 80MHz will only be visible if the flash SPI speed is also 80MHz. (ESPTOOLPY_FLASHFREQ_80M is true) Available options: 40MHz clock speed (CONFIG_SPIRAM_SPEED_40M) 80MHz clock speed (CONFIG_SPIRAM_SPEED_80M) CONFIG_SPIRAM_BOOT_INIT Initialize SPI RAM during startup Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config If this is enabled, the SPI RAM will be enabled during initial boot. Unless you have specific requirements, you'll want to leave this enabled so memory allocated during boot-up can also be placed in SPI RAM. CONFIG_SPIRAM_IGNORE_NOTFOUND Ignore PSRAM when not found Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > CONFIG_SPIRAM_BOOT_INIT Normally, if psram initialization is enabled during compile time but not found at runtime, it is seen as an error making the CPU panic. If this is enabled, booting will complete but no PSRAM will be available. If PSRAM failed to initialize, the following configs may be affected and may need to be corrected manually. SPIRAM_TRY_ALLOCATE_WIFI_LWIP will affect some LWIP and WiFi buffer default values and range values. Enable SPIRAM_TRY_ALLOCATE_WIFI_LWIP, ESP_WIFI_AMSDU_TX_ENABLED, ESP_WIFI_CACHE_TX_BUFFER_NUM and use static WiFi Tx buffer may cause potential memory exhaustion issues. Suggest disable SPIRAM_TRY_ALLOCATE_WIFI_LWIP. Suggest disable ESP_WIFI_AMSDU_TX_ENABLED. Suggest disable ESP_WIFI_CACHE_TX_BUFFER_NUM, need clear CONFIG_FEATURE_CACHE_TX_BUF_BIT of config->feature_caps. Suggest change ESP_WIFI_TX_BUFFER from static to dynamic. Also suggest to adjust some buffer numbers to the values used without PSRAM case. Such as, ESP_WIFI_STATIC_TX_BUFFER_NUM, ESP_WIFI_DYNAMIC_TX_BUFFER_NUM. CONFIG_SPIRAM_USE SPI RAM access method Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config The SPI RAM can be accessed in multiple methods: by just having it available as an unmanaged memory region in the CPU's memory map, by integrating it in the heap as 'special' memory needing heap_caps_malloc to allocate, or by fully integrating it making malloc() also able to return SPI RAM pointers. Available options: Integrate RAM into memory map (CONFIG_SPIRAM_USE_MEMMAP) Make RAM allocatable using heap_caps_malloc(..., MALLOC_CAP_SPIRAM) (CONFIG_SPIRAM_USE_CAPS_ALLOC) Make RAM allocatable using malloc() as well (CONFIG_SPIRAM_USE_MALLOC) CONFIG_SPIRAM_MEMTEST Run memory test on SPI RAM initialization Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Runs a rudimentary memory test on initialization. Aborts when memory test fails. Disable this for slightly faster startup. CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL Maximum malloc() size, in bytes, to always put in internal memory Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config If malloc() is capable of also allocating SPI-connected ram, its allocation strategy will prefer to allocate chunks less than this size in internal memory, while allocations larger than this will be done from external RAM. If allocation from the preferred region fails, an attempt is made to allocate from the non-preferred region instead, so malloc() will not suddenly fail when either internal or external memory is full. CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP Try to allocate memories of WiFi and LWIP in SPIRAM firstly. If failed, allocate internal memory Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Try to allocate memories of WiFi and LWIP in SPIRAM firstly. If failed, try to allocate internal memory then. CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL Reserve this amount of bytes for data that specifically needs to be in DMA or internal memory Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Because the external/internal RAM allocation strategy is not always perfect, it sometimes may happen that the internal memory is entirely filled up. This causes allocations that are specifically done in internal memory, for example the stack for new tasks or memory to service DMA or have memory that's also available when SPI cache is down, to fail. This option reserves a pool specifically for requests like that; the memory in this pool is not given out when a normal malloc() is called. Set this to 0 to disable this feature. Note that because FreeRTOS stacks are forced to internal memory, they will also use this memory pool; be sure to keep this in mind when adjusting this value. Note also that the DMA reserved pool may not be one single contiguous memory region, depending on the configured size and the static memory usage of the app. CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY Allow .bss segment placed in external memory Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config If enabled, variables with EXT_RAM_BSS_ATTR attribute will be placed in SPIRAM instead of internal DRAM. BSS section of lwip, net80211, pp, bt libraries will be automatically placed in SPIRAM. BSS sections from other object files and libraries can also be placed in SPIRAM through linker fragment scheme extram_bss. Note that the variables placed in SPIRAM using EXT_RAM_BSS_ATTR will be zero initialized. CONFIG_SPIRAM_ALLOW_NOINIT_SEG_EXTERNAL_MEMORY Allow .noinit segment placed in external memory Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config If enabled, noinit variables can be placed in PSRAM using EXT_RAM_NOINIT_ATTR. Note the values placed into this section will not be initialized at startup and should keep its value after software restart. CONFIG_SPIRAM_CACHE_WORKAROUND Enable workaround for bug in SPI RAM cache for Rev1 ESP32s Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Revision 1 of the ESP32 has a bug that can cause a write to PSRAM not to take place in some situations when the cache line needs to be fetched from external RAM and an interrupt occurs. This enables a fix in the compiler (-mfix-esp32-psram-cache-issue) that makes sure the specific code that is vulnerable to this will not be emitted. This will also not use any bits of newlib that are located in ROM, opting for a version that is compiled with the workaround and located in flash instead. The workaround is not required for ESP32 revision 3 and above. SPIRAM cache workaround debugging Contains: CONFIG_SPIRAM_CACHE_WORKAROUND_STRATEGY Workaround strategy Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM cache workaround debugging Select the workaround strategy. Note that the strategy for precompiled libraries (libgcc, newlib, bt, wifi) is not affected by this selection. Unless you know you need a different strategy, it's suggested you stay with the default MEMW strategy. Note that DUPLDST can interfere with hardware encryption and this will be automatically disabled if this workaround is selected. 'Insert nops' is the workaround that was used in older esp-idf versions. This workaround still can cause faulty data transfers from/to SPI RAM in some situation. Available options: Insert memw after vulnerable instructions (default) (CONFIG_SPIRAM_CACHE_WORKAROUND_STRATEGY_MEMW) Duplicate LD/ST for 32-bit, memw for 8/16 bit (CONFIG_SPIRAM_CACHE_WORKAROUND_STRATEGY_DUPLDST) Insert nops between vulnerable loads/stores (old strategy, obsolete) (CONFIG_SPIRAM_CACHE_WORKAROUND_STRATEGY_NOPS) SPIRAM workaround libraries placement Contains: CONFIG_SPIRAM_CACHE_LIBJMP_IN_IRAM Put libc's jump related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: longjmp and setjmp. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBMATH_IN_IRAM Put libc's math related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: abs, div, labs, ldiv, quorem, fpclassify, and nan. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBNUMPARSER_IN_IRAM Put libc's number parsing related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: utoa, itoa, atoi, atol, strtol, and strtoul. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBIO_IN_IRAM Put libc's I/O related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: wcrtomb, fvwrite, wbuf, wsetup, fputwc, wctomb_r, ungetc, makebuf, fflush, refill, and sccl. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBTIME_IN_IRAM Put libc's time related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: asctime, asctime_r, ctime, ctime_r, lcltime, lcltime_r, gmtime, gmtime_r, strftime, mktime, tzset_r, tzset, time, gettzinfo, systimes, month_lengths, timelocal, tzvars, tzlock, tzcalc_limits, and strptime. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBCHAR_IN_IRAM Put libc's characters related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: ctype_, toupper, tolower, toascii, strupr, bzero, isalnum, isalpha, isascii, isblank, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, and isupper. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBMEM_IN_IRAM Put libc's memory related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: memccpy, memchr memmove, and memrchr. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBSTR_IN_IRAM Put libc's string related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: strcasecmp, strcasestr, strchr, strcoll, strcpy, strcspn, strdup, strdup_r, strlcat, strlcpy, strlen, strlwr, strncasecmp, strncat, strncmp, strncpy, strndup, strndup_r, strrchr, strsep, strspn, strstr, strtok_r, and strupr. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBRAND_IN_IRAM Put libc's random related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: srand, rand, and rand_r. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBENV_IN_IRAM Put libc's environment related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: environ, envlock, and getenv_r. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBFILE_IN_IRAM Put libc's file related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: lock, isatty, fclose, open, close, creat, read, rshift, sbrk, stdio, syssbrk, sysclose, sysopen, creat, sysread, syswrite, impure, fwalk, and findfp. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBMISC_IN_IRAM Put libc's miscellaneous functions in IRAM, see help Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: raise and system Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_BANKSWITCH_ENABLE Enable bank switching for >4MiB external RAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config The ESP32 only supports 4MiB of external RAM in its address space. The hardware does support larger memories, but these have to be bank-switched in and out of this address space. Enabling this allows you to reserve some MMU pages for this, which allows the use of the esp_himem api to manage these banks. #Note that this is limited to 62 banks, as esp_psram_extram_writeback_cache needs some kind of mapping of #some banks below that mark to work. We cannot at this moment guarantee this to exist when himem is #enabled. If spiram 2T mode is enabled, the size of 64Mbit psram will be changed as 32Mbit, so himem will be unusable. CONFIG_SPIRAM_BANKSWITCH_RESERVE Amount of 32K pages to reserve for bank switching Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > CONFIG_SPIRAM_BANKSWITCH_ENABLE Select the amount of banks reserved for bank switching. Note that the amount of RAM allocatable with malloc/esp_heap_alloc_caps will decrease by 32K for each page reserved here. Note that this reservation is only actually done if your program actually uses the himem API. Without any himem calls, the reservation is not done and the original amount of memory will be available to malloc/esp_heap_alloc_caps. CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY Allow external memory as an argument to xTaskCreateStatic Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Because some bits of the ESP32 code environment cannot be recompiled with the cache workaround, normally tasks cannot be safely run with their stack residing in external memory; for this reason xTaskCreate (and related task creaton functions) always allocate stack in internal memory and xTaskCreateStatic will check if the memory passed to it is in internal memory. If you have a task that needs a large amount of stack and does not call on ROM code in any way (no direct calls, but also no Bluetooth/WiFi), you can try enable this to cause xTaskCreateStatic to allow tasks stack in external memory. CONFIG_SPIRAM_OCCUPY_SPI_HOST SPI host to use for 32MBit PSRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config When both flash and PSRAM is working under 80MHz, and the PSRAM is of type 32MBit, one of the HSPI/VSPI host will be used to output the clock. Select which one to use here. Available options: HSPI host (SPI2) (CONFIG_SPIRAM_OCCUPY_HSPI_HOST) VSPI host (SPI3) (CONFIG_SPIRAM_OCCUPY_VSPI_HOST) Will not try to use any host, will abort if not able to use the PSRAM (CONFIG_SPIRAM_OCCUPY_NO_HOST) PSRAM clock and cs IO for ESP32-DOWD Contains: CONFIG_D0WD_PSRAM_CLK_IO PSRAM CLK IO number Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > PSRAM clock and cs IO for ESP32-DOWD The PSRAM CLOCK IO can be any unused GPIO, user can config it based on hardware design. If user use 1.8V flash and 1.8V psram, this value can only be one of 6, 7, 8, 9, 10, 11, 16, 17. If configured to the same pin as Flash, PSRAM shouldn't be rev0. Contact Espressif for more information. CONFIG_D0WD_PSRAM_CS_IO PSRAM CS IO number Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > PSRAM clock and cs IO for ESP32-DOWD The PSRAM CS IO can be any unused GPIO, user can config it based on hardware design. If user use 1.8V flash and 1.8V psram, this value can only be one of 6, 7, 8, 9, 10, 11, 16, 17. PSRAM clock and cs IO for ESP32-D2WD Contains: CONFIG_D2WD_PSRAM_CLK_IO PSRAM CLK IO number Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > PSRAM clock and cs IO for ESP32-D2WD User can config it based on hardware design. For ESP32-D2WD chip, the psram can only be 1.8V psram, so this value can only be one of 6, 7, 8, 9, 10, 11, 16, 17. If configured to the same pin (GPIO6) as Flash, PSRAM shouldn't be rev0. Contact Espressif for more information. CONFIG_D2WD_PSRAM_CS_IO PSRAM CS IO number Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > PSRAM clock and cs IO for ESP32-D2WD User can config it based on hardware design. For ESP32-D2WD chip, the psram can only be 1.8V psram, so this value can only be one of 6, 7, 8, 9, 10, 11, 16, 17. PSRAM clock and cs IO for ESP32-PICO-D4 Contains: CONFIG_PICO_PSRAM_CS_IO PSRAM CS IO number Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > PSRAM clock and cs IO for ESP32-PICO-D4 The PSRAM CS IO can be any unused GPIO, user can config it based on hardware design. For ESP32-PICO chip, the psram share clock with flash, so user do not need to configure the clock IO. For the reference hardware design, please refer to https://www.espressif.com/sites/default/files/documentation/esp32-pico-d4_datasheet_en.pdf CONFIG_SPIRAM_CUSTOM_SPIWP_SD3_PIN Use custom SPI PSRAM WP(SD3) Pin when flash pins set in eFuse (read help) Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config This setting is only used if the SPI flash pins have been overridden by setting the eFuses SPI_PAD_CONFIG_xxx, and the SPI flash mode is DIO or DOUT. When this is the case, the eFuse config only defines 3 of the 4 Quad I/O data pins. The WP pin (aka ESP32 pin "SD_DATA_3" or SPI flash pin "IO2") is not specified in eFuse. The psram only has QPI mode, so a WP pin setting is necessary. If this config item is set to N (default), the correct WP pin will be automatically used for any Espressif chip or module with integrated flash. If a custom setting is needed, set this config item to Y and specify the GPIO number connected to the WP pin. When flash mode is set to QIO or QOUT, the PSRAM WP pin will be set the same as the SPI Flash WP pin configured in the bootloader. CONFIG_SPIRAM_SPIWP_SD3_PIN Custom SPI PSRAM WP(SD3) Pin Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config The option "Use custom SPI PSRAM WP(SD3) pin" must be set or this value is ignored If burning a customized set of SPI flash pins in eFuse and using DIO or DOUT mode for flash, set this value to the GPIO number of the SPIRAM WP pin. CONFIG_SPIRAM_2T_MODE Enable SPI PSRAM 2T mode Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Enable this option to fix single bit errors inside 64Mbit PSRAM. Some 64Mbit PSRAM chips have a hardware issue in the RAM which causes bit errors at multiple fixed bit positions. Note: If this option is enabled, the 64Mbit PSRAM chip will appear to be 32Mbit in size. Applications will not be affected unless the use the esp_himem APIs, which are not supported in 2T mode. ESP Ringbuf Contains: CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH Place non-ISR ringbuf functions into flash Found in: Component config > ESP Ringbuf Place non-ISR ringbuf functions (like xRingbufferCreate/xRingbufferSend) into flash. This frees up IRAM, but the functions can no longer be called when the cache is disabled. Default value: No (disabled) CONFIG_RINGBUF_PLACE_ISR_FUNCTIONS_INTO_FLASH Place ISR ringbuf functions into flash Found in: Component config > ESP Ringbuf > CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH Place ISR ringbuf functions (like xRingbufferSendFromISR/xRingbufferReceiveFromISR) into flash. This frees up IRAM, but the functions can no longer be called when the cache is disabled or from an IRAM interrupt context. This option is not compatible with ESP-IDF drivers which are configured to run the ISR from an IRAM context, e.g. CONFIG_UART_ISR_IN_IRAM. Default value: No (disabled) if CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH ESP System Settings Contains: CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ CPU frequency Found in: Component config > ESP System Settings CPU frequency to be set on application startup. Available options: 40 MHz (CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_40) 80 MHz (CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_80) 160 MHz (CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160) 240 MHz (CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240) Memory Contains: CONFIG_ESP32_RTCDATA_IN_FAST_MEM Place RTC_DATA_ATTR and RTC_RODATA_ATTR variables into RTC fast memory segment Found in: Component config > ESP System Settings > Memory This option allows to place .rtc_data and .rtc_rodata sections into RTC fast memory segment to free the slow memory region for ULP programs. This option depends on the CONFIG_FREERTOS_UNICORE option because RTC fast memory can be accessed only by PRO_CPU core. Default value: No (disabled) if CONFIG_FREERTOS_UNICORE CONFIG_ESP32_USE_FIXED_STATIC_RAM_SIZE Use fixed static RAM size Found in: Component config > ESP System Settings > Memory If this option is disabled, the DRAM part of the heap starts right after the .bss section, within the dram0_0 region. As a result, adding or removing some static variables will change the available heap size. If this option is enabled, the DRAM part of the heap starts right after the dram0_0 region, where its length is set with ESP32_FIXED_STATIC_RAM_SIZE Default value: No (disabled) CONFIG_ESP32_FIXED_STATIC_RAM_SIZE Fixed Static RAM size Found in: Component config > ESP System Settings > Memory > CONFIG_ESP32_USE_FIXED_STATIC_RAM_SIZE RAM size dedicated for static variables (.data & .bss sections). Please note that the actual length will be reduced by BTDM_RESERVE_DRAM if Bluetooth controller is enabled. Range: from 0 to 0x2c200 if CONFIG_ESP32_USE_FIXED_STATIC_RAM_SIZE Default value: "0x1E000" if CONFIG_ESP32_USE_FIXED_STATIC_RAM_SIZE CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY Enable IRAM as 8 bit accessible memory Found in: Component config > ESP System Settings > Memory If enabled, application can use IRAM as byte accessible region for storing data (Note: IRAM region cannot be used as task stack) This is possible due to handling of exceptions LoadStoreError (3) and LoadStoreAlignmentError (9) Each unaligned read/write access will incur a penalty of maximum of 167 CPU cycles. Non-backward compatible options Contains: CONFIG_ESP_SYSTEM_ESP32_SRAM1_REGION_AS_IRAM Reserve parts of SRAM1 for app IRAM (WARNING, read help before enabling) Found in: Component config > ESP System Settings > Memory > Non-backward compatible options Reserve parts of SRAM1 for app IRAM which was previously reserved for bootloader DRAM. If booting an app on an older bootloader from before this option was introduced, the app will fail to boot due to not recognizing the new IRAM memory area. If this is the case please test carefully before pushing out any OTA updates. Trace memory Contains: CONFIG_ESP32_TRAX Use TRAX tracing feature Found in: Component config > ESP System Settings > Trace memory The ESP32 contains a feature which allows you to trace the execution path the processor has taken through the program. This is stored in a chunk of 32K (16K for single-processor) of memory that can't be used for general purposes anymore. Disable this if you do not know what this is. Default value: No (disabled) CONFIG_ESP32_TRAX_TWOBANKS Reserve memory for tracing both pro as well as app cpu execution Found in: Component config > ESP System Settings > Trace memory > CONFIG_ESP32_TRAX The ESP32 contains a feature which allows you to trace the execution path the processor has taken through the program. This is stored in a chunk of 32K (16K for single-processor) of memory that can't be used for general purposes anymore. Disable this if you do not know what this is. # Memory to reverse for trace, used in linker script CONFIG_ESP_SYSTEM_PANIC Panic handler behaviour Found in: Component config > ESP System Settings If FreeRTOS detects unexpected behaviour or an unhandled exception, the panic handler is invoked. Configure the panic handler's action here. Available options: Print registers and halt (CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT) Outputs the relevant registers over the serial port and halt the processor. Needs a manual reset to restart. Print registers and reboot (CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT) Outputs the relevant registers over the serial port and immediately reset the processor. Silent reboot (CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT) Just resets the processor without outputting anything GDBStub on panic (CONFIG_ESP_SYSTEM_PANIC_GDBSTUB) Invoke gdbstub on the serial port, allowing for gdb to attach to it to do a postmortem of the crash. CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS Panic reboot delay (Seconds) Found in: Component config > ESP System Settings After the panic handler executes, you can specify a number of seconds to wait before the device reboots. Range: from 0 to 99 Default value: 0 CONFIG_ESP_SYSTEM_RTC_EXT_XTAL_BOOTSTRAP_CYCLES Bootstrap cycles for external 32kHz crystal Found in: Component config > ESP System Settings To reduce the startup time of an external RTC crystal, we bootstrap it with a 32kHz square wave for a fixed number of cycles. Setting 0 will disable bootstrapping (if disabled, the crystal may take longer to start up or fail to oscillate under some conditions). If this value is too high, a faulty crystal may initially start and then fail. If this value is too low, an otherwise good crystal may not start. To accurately determine if the crystal has started, set a larger "Number of cycles for RTC_SLOW_CLK calibration" (about 3000). CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP Enable RTC fast memory for dynamic allocations Found in: Component config > ESP System Settings This config option allows to add RTC fast memory region to system heap with capability similar to that of DRAM region but without DMA. This memory will be consumed first per heap initialization order by early startup services and scheduler related code. Speed wise RTC fast memory operates on APB clock and hence does not have much performance impact. Memory protection Contains: CONFIG_ESP_SYSTEM_PMP_IDRAM_SPLIT Enable IRAM/DRAM split protection Found in: Component config > ESP System Settings > Memory protection If enabled, the CPU watches all the memory access and raises an exception in case of any memory violation. This feature automatically splits the SRAM memory, using PMP, into data and instruction segments and sets Read/Execute permissions for the instruction part (below given splitting address) and Read/Write permissions for the data part (above the splitting address). The memory protection is effective on all access through the IRAM0 and DRAM0 buses. Default value: Yes (enabled) if SOC_CPU_IDRAM_SPLIT_USING_PMP CONFIG_ESP_SYSTEM_MEMPROT_FEATURE Enable memory protection Found in: Component config > ESP System Settings > Memory protection If enabled, the permission control module watches all the memory access and fires the panic handler if a permission violation is detected. This feature automatically splits the SRAM memory into data and instruction segments and sets Read/Execute permissions for the instruction part (below given splitting address) and Read/Write permissions for the data part (above the splitting address). The memory protection is effective on all access through the IRAM0 and DRAM0 buses. Default value: Yes (enabled) if SOC_MEMPROT_SUPPORTED CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_LOCK Lock memory protection settings Found in: Component config > ESP System Settings > Memory protection > CONFIG_ESP_SYSTEM_MEMPROT_FEATURE Once locked, memory protection settings cannot be changed anymore. The lock is reset only on the chip startup. Default value: Yes (enabled) if CONFIG_ESP_SYSTEM_MEMPROT_FEATURE CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE System event queue size Found in: Component config > ESP System Settings Config system event queue size in different application. Default value: 32 CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE Event loop task stack size Found in: Component config > ESP System Settings Config system event task stack size in different application. Default value: 2304 CONFIG_ESP_MAIN_TASK_STACK_SIZE Main task stack size Found in: Component config > ESP System Settings Configure the "main task" stack size. This is the stack of the task which calls app_main(). If app_main() returns then this task is deleted and its stack memory is freed. Default value: 3584 CONFIG_ESP_MAIN_TASK_AFFINITY Main task core affinity Found in: Component config > ESP System Settings Configure the "main task" core affinity. This is the used core of the task which calls app_main(). If app_main() returns then this task is deleted. Available options: CPU0 (CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0) CPU1 (CONFIG_ESP_MAIN_TASK_AFFINITY_CPU1) No affinity (CONFIG_ESP_MAIN_TASK_AFFINITY_NO_AFFINITY) CONFIG_ESP_CONSOLE_UART Channel for console output Found in: Component config > ESP System Settings Select where to send console output (through stdout and stderr). Default is to use UART0 on pre-defined GPIOs. If "Custom" is selected, UART0 or UART1 can be chosen, and any pins can be selected. If "None" is selected, there will be no console output on any UART, except for initial output from ROM bootloader. This ROM output can be suppressed by GPIO strapping or EFUSE, refer to chip datasheet for details. On chips with USB OTG peripheral, "USB CDC" option redirects output to the CDC port. This option uses the CDC driver in the chip ROM. This option is incompatible with TinyUSB stack. On chips with an USB serial/JTAG debug controller, selecting the option for that redirects output to the CDC/ACM (serial port emulation) component of that device. Available options: Default: UART0 (CONFIG_ESP_CONSOLE_UART_DEFAULT) USB CDC (CONFIG_ESP_CONSOLE_USB_CDC) USB Serial/JTAG Controller (CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG) Custom UART (CONFIG_ESP_CONSOLE_UART_CUSTOM) None (CONFIG_ESP_CONSOLE_NONE) CONFIG_ESP_CONSOLE_SECONDARY Channel for console secondary output Found in: Component config > ESP System Settings This secondary option supports output through other specific port like USB_SERIAL_JTAG when UART0 port as a primary is selected but not connected. This secondary output currently only supports non-blocking mode without using REPL. If you want to output in blocking mode with REPL or input through this secondary port, please change the primary config to this port in Channel for console output menu. Available options: No secondary console (CONFIG_ESP_CONSOLE_SECONDARY_NONE) USB_SERIAL_JTAG PORT (CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG) This option supports output through USB_SERIAL_JTAG port when the UART0 port is not connected. The output currently only supports non-blocking mode without using the console. If you want to output in blocking mode with REPL or input through USB_SERIAL_JTAG port, please change the primary config to ESP_CONSOLE_USB_SERIAL_JTAG above. CONFIG_ESP_CONSOLE_UART_NUM UART peripheral to use for console output (0-1) Found in: Component config > ESP System Settings This UART peripheral is used for console output from the ESP-IDF Bootloader and the app. If the configuration is different in the Bootloader binary compared to the app binary, UART is reconfigured after the bootloader exits and the app starts. Due to an ESP32 ROM bug, UART2 is not supported for console output via esp_rom_printf. Available options: UART0 (CONFIG_ESP_CONSOLE_UART_CUSTOM_NUM_0) UART1 (CONFIG_ESP_CONSOLE_UART_CUSTOM_NUM_1) CONFIG_ESP_CONSOLE_UART_TX_GPIO UART TX on GPIO# Found in: Component config > ESP System Settings This GPIO is used for console UART TX output in the ESP-IDF Bootloader and the app (including boot log output and default standard output and standard error of the app). If the configuration is different in the Bootloader binary compared to the app binary, UART is reconfigured after the bootloader exits and the app starts. Range: from 0 to 33 if CONFIG_ESP_CONSOLE_UART_CUSTOM Default value: CONFIG_ESP_CONSOLE_UART_RX_GPIO UART RX on GPIO# Found in: Component config > ESP System Settings This GPIO is used for UART RX input in the ESP-IDF Bootloader and the app (including default default standard input of the app). Note: The default ESP-IDF Bootloader configures this pin but doesn't read anything from the UART. If the configuration is different in the Bootloader binary compared to the app binary, UART is reconfigured after the bootloader exits and the app starts. Range: from 0 to 39 if CONFIG_ESP_CONSOLE_UART_CUSTOM Default value: CONFIG_ESP_CONSOLE_UART_BAUDRATE UART console baud rate Found in: Component config > ESP System Settings This baud rate is used by both the ESP-IDF Bootloader and the app (including boot log output and default standard input/output/error of the app). The app's maximum baud rate depends on the UART clock source. If Power Management is disabled, the UART clock source is the APB clock and all baud rates in the available range will be sufficiently accurate. If Power Management is enabled, REF_TICK clock source is used so the baud rate is divided from 1MHz. Baud rates above 1Mbps are not possible and values between 500Kbps and 1Mbps may not be accurate. If the configuration is different in the Bootloader binary compared to the app binary, UART is reconfigured after the bootloader exits and the app starts. Range: from 1200 to 1000000 if CONFIG_PM_ENABLE Default value: 115200 CONFIG_ESP_INT_WDT Interrupt watchdog Found in: Component config > ESP System Settings This watchdog timer can detect if the FreeRTOS tick interrupt has not been called for a certain time, either because a task turned off interrupts and did not turn them on for a long time, or because an interrupt handler did not return. It will try to invoke the panic handler first and failing that reset the SoC. Default value: Yes (enabled) CONFIG_ESP_INT_WDT_TIMEOUT_MS Interrupt watchdog timeout (ms) Found in: Component config > ESP System Settings > CONFIG_ESP_INT_WDT The timeout of the watchdog, in miliseconds. Make this higher than the FreeRTOS tick rate. Range: from 10 to 10000 Default value: 800 if CONFIG_SPIRAM && CONFIG_ESP_INT_WDT CONFIG_ESP_INT_WDT_CHECK_CPU1 Also watch CPU1 tick interrupt Found in: Component config > ESP System Settings > CONFIG_ESP_INT_WDT Also detect if interrupts on CPU 1 are disabled for too long. CONFIG_ESP_TASK_WDT_EN Enable Task Watchdog Timer Found in: Component config > ESP System Settings The Task Watchdog Timer can be used to make sure individual tasks are still running. Enabling this option will enable the Task Watchdog Timer. It can be either initialized automatically at startup or initialized after startup (see Task Watchdog Timer API Reference) Default value: Yes (enabled) CONFIG_ESP_TASK_WDT_INIT Initialize Task Watchdog Timer on startup Found in: Component config > ESP System Settings > CONFIG_ESP_TASK_WDT_EN Enabling this option will cause the Task Watchdog Timer to be initialized automatically at startup. Default value: Yes (enabled) CONFIG_ESP_TASK_WDT_PANIC Invoke panic handler on Task Watchdog timeout Found in: Component config > ESP System Settings > CONFIG_ESP_TASK_WDT_EN > CONFIG_ESP_TASK_WDT_INIT If this option is enabled, the Task Watchdog Timer will be configured to trigger the panic handler when it times out. This can also be configured at run time (see Task Watchdog Timer API Reference) Default value: No (disabled) CONFIG_ESP_TASK_WDT_TIMEOUT_S Task Watchdog timeout period (seconds) Found in: Component config > ESP System Settings > CONFIG_ESP_TASK_WDT_EN > CONFIG_ESP_TASK_WDT_INIT Timeout period configuration for the Task Watchdog Timer in seconds. This is also configurable at run time (see Task Watchdog Timer API Reference) Range: from 1 to 60 Default value: 5 CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0 Watch CPU0 Idle Task Found in: Component config > ESP System Settings > CONFIG_ESP_TASK_WDT_EN > CONFIG_ESP_TASK_WDT_INIT If this option is enabled, the Task Watchdog Timer will watch the CPU0 Idle Task. Having the Task Watchdog watch the Idle Task allows for detection of CPU starvation as the Idle Task not being called is usually a symptom of CPU starvation. Starvation of the Idle Task is detrimental as FreeRTOS household tasks depend on the Idle Task getting some runtime every now and then. Default value: Yes (enabled) CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1 Watch CPU1 Idle Task Found in: Component config > ESP System Settings > CONFIG_ESP_TASK_WDT_EN > CONFIG_ESP_TASK_WDT_INIT If this option is enabled, the Task Watchdog Timer will wach the CPU1 Idle Task. CONFIG_ESP_PANIC_HANDLER_IRAM Place panic handler code in IRAM Found in: Component config > ESP System Settings If this option is disabled (default), the panic handler code is placed in flash not IRAM. This means that if ESP-IDF crashes while flash cache is disabled, the panic handler will automatically re-enable flash cache before running GDB Stub or Core Dump. This adds some minor risk, if the flash cache status is also corrupted during the crash. If this option is enabled, the panic handler code (including required UART functions) is placed in IRAM. This may be necessary to debug some complex issues with crashes while flash cache is disabled (for example, when writing to SPI flash) or when flash cache is corrupted when an exception is triggered. Default value: No (disabled) CONFIG_ESP_DEBUG_STUBS_ENABLE OpenOCD debug stubs Found in: Component config > ESP System Settings Debug stubs are used by OpenOCD to execute pre-compiled onboard code which does some useful debugging stuff, e.g. GCOV data dump. CONFIG_ESP_DEBUG_OCDAWARE Make exception and panic handlers JTAG/OCD aware Found in: Component config > ESP System Settings The FreeRTOS panic and unhandled exception handers can detect a JTAG OCD debugger and instead of panicking, have the debugger stop on the offending instruction. Default value: Yes (enabled) CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL Interrupt level to use for Interrupt Watchdog and other system checks Found in: Component config > ESP System Settings Interrupt level to use for Interrupt Watchdog, IPC_ISR and other system checks. Available options: Level 5 interrupt (CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_5) Using level 5 interrupt for Interrupt Watchdog, IPC_ISR and other system checks. Level 4 interrupt (CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4) Using level 4 interrupt for Interrupt Watchdog, IPC_ISR and other system checks. Brownout Detector Contains: CONFIG_ESP_BROWNOUT_DET Hardware brownout detect & reset Found in: Component config > ESP System Settings > Brownout Detector The ESP has a built-in brownout detector which can detect if the voltage is lower than a specific value. If this happens, it will reset the chip in order to prevent unintended behaviour. Default value: Yes (enabled) CONFIG_ESP_BROWNOUT_DET_LVL_SEL Brownout voltage level Found in: Component config > ESP System Settings > Brownout Detector > CONFIG_ESP_BROWNOUT_DET The brownout detector will reset the chip when the supply voltage is approximately below this level. Note that there may be some variation of brownout voltage level between each ESP chip. #The voltage levels here are estimates, more work needs to be done to figure out the exact voltages #of the brownout threshold levels. Available options: 2.43V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_0) 2.48V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_1) 2.58V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_2) 2.62V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_3) 2.67V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_4) 2.70V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5) 2.77V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6) 2.80V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7) CONFIG_ESP32_DISABLE_BASIC_ROM_CONSOLE Permanently disable BASIC ROM Console Found in: Component config > ESP System Settings If set, the first time the app boots it will disable the BASIC ROM Console permanently (by burning an eFuse). Otherwise, the BASIC ROM Console starts on reset if no valid bootloader is read from the flash. (Enabling secure boot also disables the BASIC ROM Console by default.) Default value: No (disabled) CONFIG_ESP_SYSTEM_HW_STACK_GUARD Hardware stack guard Found in: Component config > ESP System Settings This config allows to trigger a panic interrupt when Stack Pointer register goes out of allocated stack memory bounds. Default value: Yes (enabled) if SOC_ASSIST_DEBUG_SUPPORTED IPC (Inter-Processor Call) Contains: CONFIG_ESP_IPC_TASK_STACK_SIZE Inter-Processor Call (IPC) task stack size Found in: Component config > IPC (Inter-Processor Call) Configure the IPC tasks stack size. An IPC task runs on each core (in dual core mode), and allows for cross-core function calls. See IPC documentation for more details. The default IPC stack size should be enough for most common simple use cases. However, users can increase/decrease the stack size to their needs. Range: from 512 to 65536 Default value: 1024 CONFIG_ESP_IPC_USES_CALLERS_PRIORITY IPC runs at caller's priority Found in: Component config > IPC (Inter-Processor Call) If this option is not enabled then the IPC task will keep behavior same as prior to that of ESP-IDF v4.0, hence IPC task will run at (configMAX_PRIORITIES - 1) priority. High resolution timer (esp_timer) Contains: CONFIG_ESP_TIMER_PROFILING Enable esp_timer profiling features Found in: Component config > High resolution timer (esp_timer) If enabled, esp_timer_dump will dump information such as number of times the timer was started, number of times the timer has triggered, and the total time it took for the callback to run. This option has some effect on timer performance and the amount of memory used for timer storage, and should only be used for debugging/testing purposes. Default value: No (disabled) CONFIG_ESP_TIMER_TASK_STACK_SIZE High-resolution timer task stack size Found in: Component config > High resolution timer (esp_timer) Configure the stack size of "timer_task" task. This task is used to dispatch callbacks of timers created using ets_timer and esp_timer APIs. If you are seing stack overflow errors in timer task, increase this value. Note that this is not the same as FreeRTOS timer task. To configure FreeRTOS timer task size, see "FreeRTOS timer task stack size" option in "FreeRTOS". Range: from 2048 to 65536 Default value: 3584 CONFIG_ESP_TIMER_INTERRUPT_LEVEL Interrupt level Found in: Component config > High resolution timer (esp_timer) It sets the interrupt level for esp_timer ISR in range 1..3. A higher level (3) helps to decrease the ISR esp_timer latency. Range: from 1 to 3 Default value: 1 CONFIG_ESP_TIMER_SHOW_EXPERIMENTAL show esp_timer's experimental features Found in: Component config > High resolution timer (esp_timer) This shows some hidden features of esp_timer. Note that they may break other features, use them with care. CONFIG_ESP_TIMER_TASK_AFFINITY esp_timer task core affinity Found in: Component config > High resolution timer (esp_timer) The default settings: timer TASK on CPU0 and timer ISR on CPU0. Other settings may help in certain cases, but note that they may break other features, use them with care. - "CPU0": (default) esp_timer task is processed by CPU0. - "CPU1": esp_timer task is processed by CPU1. - "No affinity": esp_timer task can be processed by any CPU. Available options: CPU0 (CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0) CPU1 (CONFIG_ESP_TIMER_TASK_AFFINITY_CPU1) No affinity (CONFIG_ESP_TIMER_TASK_AFFINITY_NO_AFFINITY) CONFIG_ESP_TIMER_ISR_AFFINITY timer interrupt core affinity Found in: Component config > High resolution timer (esp_timer) The default settings: timer TASK on CPU0 and timer ISR on CPU0. Other settings may help in certain cases, but note that they may break other features, use them with care. - "CPU0": (default) timer interrupt is processed by CPU0. - "CPU1": timer interrupt is processed by CPU1. - "No affinity": timer interrupt can be processed by any CPU. It helps to reduce latency but there is a disadvantage it leads to the timer ISR running on every core. It increases the CPU time usage for timer ISRs by N on an N-core system. Available options: CPU0 (CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0) CPU1 (CONFIG_ESP_TIMER_ISR_AFFINITY_CPU1) No affinity (CONFIG_ESP_TIMER_ISR_AFFINITY_NO_AFFINITY) CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD Support ISR dispatch method Found in: Component config > High resolution timer (esp_timer) Allows using ESP_TIMER_ISR dispatch method (ESP_TIMER_TASK dispatch method is also avalible). - ESP_TIMER_TASK - Timer callbacks are dispatched from a high-priority esp_timer task. - ESP_TIMER_ISR - Timer callbacks are dispatched directly from the timer interrupt handler. The ISR dispatch can be used, in some cases, when a callback is very simple or need a lower-latency. Default value: No (disabled) Wi-Fi Contains: CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM Max number of WiFi static RX buffers Found in: Component config > Wi-Fi Set the number of WiFi static RX buffers. Each buffer takes approximately 1.6KB of RAM. The static rx buffers are allocated when esp_wifi_init is called, they are not freed until esp_wifi_deinit is called. WiFi hardware use these buffers to receive all 802.11 frames. A higher number may allow higher throughput but increases memory use. If ESP_WIFI_AMPDU_RX_ENABLED is enabled, this value is recommended to set equal or bigger than ESP_WIFI_RX_BA_WIN in order to achieve better throughput and compatibility with both stations and APs. Range: from 2 to 128 if SOC_WIFI_HE_SUPPORT Default value: CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM Max number of WiFi dynamic RX buffers Found in: Component config > Wi-Fi Set the number of WiFi dynamic RX buffers, 0 means unlimited RX buffers will be allocated (provided sufficient free RAM). The size of each dynamic RX buffer depends on the size of the received data frame. For each received data frame, the WiFi driver makes a copy to an RX buffer and then delivers it to the high layer TCP/IP stack. The dynamic RX buffer is freed after the higher layer has successfully received the data frame. For some applications, WiFi data frames may be received faster than the application can process them. In these cases we may run out of memory if RX buffer number is unlimited (0). If a dynamic RX buffer limit is set, it should be at least the number of static RX buffers. Range: from 0 to 1024 if CONFIG_LWIP_WND_SCALE Default value: 32 CONFIG_ESP_WIFI_TX_BUFFER Type of WiFi TX buffers Found in: Component config > Wi-Fi Select type of WiFi TX buffers: If "Static" is selected, WiFi TX buffers are allocated when WiFi is initialized and released when WiFi is de-initialized. The size of each static TX buffer is fixed to about 1.6KB. If "Dynamic" is selected, each WiFi TX buffer is allocated as needed when a data frame is delivered to the Wifi driver from the TCP/IP stack. The buffer is freed after the data frame has been sent by the WiFi driver. The size of each dynamic TX buffer depends on the length of each data frame sent by the TCP/IP layer. If PSRAM is enabled, "Static" should be selected to guarantee enough WiFi TX buffers. If PSRAM is disabled, "Dynamic" should be selected to improve the utilization of RAM. Available options: Static (CONFIG_ESP_WIFI_STATIC_TX_BUFFER) Dynamic (CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER) CONFIG_ESP_WIFI_STATIC_TX_BUFFER_NUM Max number of WiFi static TX buffers Found in: Component config > Wi-Fi Set the number of WiFi static TX buffers. Each buffer takes approximately 1.6KB of RAM. The static RX buffers are allocated when esp_wifi_init() is called, they are not released until esp_wifi_deinit() is called. For each transmitted data frame from the higher layer TCP/IP stack, the WiFi driver makes a copy of it in a TX buffer. For some applications especially UDP applications, the upper layer can deliver frames faster than WiFi layer can transmit. In these cases, we may run out of TX buffers. Range: from 1 to 64 if CONFIG_ESP_WIFI_STATIC_TX_BUFFER Default value: CONFIG_ESP_WIFI_CACHE_TX_BUFFER_NUM Max number of WiFi cache TX buffers Found in: Component config > Wi-Fi Set the number of WiFi cache TX buffer number. For each TX packet from uplayer, such as LWIP etc, WiFi driver needs to allocate a static TX buffer and makes a copy of uplayer packet. If WiFi driver fails to allocate the static TX buffer, it caches the uplayer packets to a dedicated buffer queue, this option is used to configure the size of the cached TX queue. Range: from 16 to 128 if CONFIG_SPIRAM Default value: 32 if CONFIG_SPIRAM CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM Max number of WiFi dynamic TX buffers Found in: Component config > Wi-Fi Set the number of WiFi dynamic TX buffers. The size of each dynamic TX buffer is not fixed, it depends on the size of each transmitted data frame. For each transmitted frame from the higher layer TCP/IP stack, the WiFi driver makes a copy of it in a TX buffer. For some applications, especially UDP applications, the upper layer can deliver frames faster than WiFi layer can transmit. In these cases, we may run out of TX buffers. Range: from 1 to 128 Default value: 32 CONFIG_ESP_WIFI_MGMT_RX_BUFFER Type of WiFi RX MGMT buffers Found in: Component config > Wi-Fi Select type of WiFi RX MGMT buffers: If "Static" is selected, WiFi RX MGMT buffers are allocated when WiFi is initialized and released when WiFi is de-initialized. The size of each static RX MGMT buffer is fixed to about 500 Bytes. If "Dynamic" is selected, each WiFi RX MGMT buffer is allocated as needed when a MGMT data frame is received. The MGMT buffer is freed after the MGMT data frame has been processed by the WiFi driver. Available options: Static (CONFIG_ESP_WIFI_STATIC_RX_MGMT_BUFFER) Dynamic (CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUFFER) CONFIG_ESP_WIFI_RX_MGMT_BUF_NUM_DEF Max number of WiFi RX MGMT buffers Found in: Component config > Wi-Fi Set the number of WiFi RX_MGMT buffers. For Management buffers, the number of dynamic and static management buffers is the same. In order to prevent memory fragmentation, the management buffer type should be set to static first. Range: from 1 to 10 Default value: 5 CONFIG_ESP_WIFI_CSI_ENABLED WiFi CSI(Channel State Information) Found in: Component config > Wi-Fi Select this option to enable CSI(Channel State Information) feature. CSI takes about CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM KB of RAM. If CSI is not used, it is better to disable this feature in order to save memory. Default value: No (disabled) CONFIG_ESP_WIFI_AMPDU_TX_ENABLED WiFi AMPDU TX Found in: Component config > Wi-Fi Select this option to enable AMPDU TX feature Default value: Yes (enabled) CONFIG_ESP_WIFI_TX_BA_WIN WiFi AMPDU TX BA window size Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_AMPDU_TX_ENABLED Set the size of WiFi Block Ack TX window. Generally a bigger value means higher throughput but more memory. Most of time we should NOT change the default value unless special reason, e.g. test the maximum UDP TX throughput with iperf etc. For iperf test in shieldbox, the recommended value is 9~12. Range: from 2 to 64 if SOC_WIFI_HE_SUPPORT && CONFIG_ESP_WIFI_AMPDU_TX_ENABLED Default value: 6 CONFIG_ESP_WIFI_AMPDU_RX_ENABLED WiFi AMPDU RX Found in: Component config > Wi-Fi Select this option to enable AMPDU RX feature Default value: Yes (enabled) CONFIG_ESP_WIFI_RX_BA_WIN WiFi AMPDU RX BA window size Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_AMPDU_RX_ENABLED Set the size of WiFi Block Ack RX window. Generally a bigger value means higher throughput and better compatibility but more memory. Most of time we should NOT change the default value unless special reason, e.g. test the maximum UDP RX throughput with iperf etc. For iperf test in shieldbox, the recommended value is 9~12. If PSRAM is used and WiFi memory is prefered to allocat in PSRAM first, the default and minimum value should be 16 to achieve better throughput and compatibility with both stations and APs. Range: from 2 to 64 if SOC_WIFI_HE_SUPPORT && CONFIG_ESP_WIFI_AMPDU_RX_ENABLED Default value: CONFIG_ESP_WIFI_AMSDU_TX_ENABLED WiFi AMSDU TX Found in: Component config > Wi-Fi Select this option to enable AMSDU TX feature Default value: No (disabled) if CONFIG_SPIRAM CONFIG_ESP_WIFI_NVS_ENABLED WiFi NVS flash Found in: Component config > Wi-Fi Select this option to enable WiFi NVS flash Default value: Yes (enabled) CONFIG_ESP_WIFI_TASK_CORE_ID WiFi Task Core ID Found in: Component config > Wi-Fi Pinned WiFi task to core 0 or core 1. Available options: Core 0 (CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0) Core 1 (CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_1) CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN Max length of WiFi SoftAP Beacon Found in: Component config > Wi-Fi ESP-MESH utilizes beacon frames to detect and resolve root node conflicts (see documentation). However the default length of a beacon frame can simultaneously hold only five root node identifier structures, meaning that a root node conflict of up to five nodes can be detected at one time. In the occurence of more root nodes conflict involving more than five root nodes, the conflict resolution process will detect five of the root nodes, resolve the conflict, and re-detect more root nodes. This process will repeat until all root node conflicts are resolved. However this process can generally take a very long time. To counter this situation, the beacon frame length can be increased such that more root nodes can be detected simultaneously. Each additional root node will require 36 bytes and should be added ontop of the default beacon frame length of 752 bytes. For example, if you want to detect 10 root nodes simultaneously, you need to set the beacon frame length as 932 (752+36*5). Setting a longer beacon length also assists with debugging as the conflicting root nodes can be identified more quickly. Range: from 752 to 1256 Default value: 752 CONFIG_ESP_WIFI_MGMT_SBUF_NUM WiFi mgmt short buffer number Found in: Component config > Wi-Fi Set the number of WiFi management short buffer. Range: from 6 to 32 Default value: 32 CONFIG_ESP_WIFI_IRAM_OPT WiFi IRAM speed optimization Found in: Component config > Wi-Fi Select this option to place frequently called Wi-Fi library functions in IRAM. When this option is disabled, more than 10Kbytes of IRAM memory will be saved but Wi-Fi throughput will be reduced. Default value: No (disabled) if CONFIG_BT_ENABLED && CONFIG_SPIRAM Yes (enabled) CONFIG_ESP_WIFI_EXTRA_IRAM_OPT WiFi EXTRA IRAM speed optimization Found in: Component config > Wi-Fi Select this option to place additional frequently called Wi-Fi library functions in IRAM. When this option is disabled, more than 5Kbytes of IRAM memory will be saved but Wi-Fi throughput will be reduced. Default value: No (disabled) CONFIG_ESP_WIFI_RX_IRAM_OPT WiFi RX IRAM speed optimization Found in: Component config > Wi-Fi Select this option to place frequently called Wi-Fi library RX functions in IRAM. When this option is disabled, more than 17Kbytes of IRAM memory will be saved but Wi-Fi performance will be reduced. Default value: No (disabled) if CONFIG_BT_ENABLED && CONFIG_SPIRAM Yes (enabled) CONFIG_ESP_WIFI_ENABLE_WPA3_SAE Enable WPA3-Personal Found in: Component config > Wi-Fi Select this option to allow the device to establish a WPA3-Personal connection with eligible AP's. PMF (Protected Management Frames) is a prerequisite feature for a WPA3 connection, it needs to be explicitly configured before attempting connection. Please refer to the Wi-Fi Driver API Guide for details. Default value: Yes (enabled) CONFIG_ESP_WIFI_ENABLE_SAE_PK Enable SAE-PK Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_ENABLE_WPA3_SAE Select this option to enable SAE-PK Default value: Yes (enabled) CONFIG_ESP_WIFI_SOFTAP_SAE_SUPPORT Enable WPA3 Personal(SAE) SoftAP Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_ENABLE_WPA3_SAE Select this option to enable SAE support in softAP mode. Default value: Yes (enabled) CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA Enable OWE STA Found in: Component config > Wi-Fi Select this option to allow the device to establish OWE connection with eligible AP's. PMF (Protected Management Frames) is a prerequisite feature for a WPA3 connection, it needs to be explicitly configured before attempting connection. Please refer to the Wi-Fi Driver API Guide for details. Default value: Yes (enabled) CONFIG_ESP_WIFI_SLP_IRAM_OPT WiFi SLP IRAM speed optimization Found in: Component config > Wi-Fi Select this option to place called Wi-Fi library TBTT process and receive beacon functions in IRAM. Some functions can be put in IRAM either by ESP_WIFI_IRAM_OPT and ESP_WIFI_RX_IRAM_OPT, or this one. If already enabled ESP_WIFI_IRAM_OPT, the other 7.3KB IRAM memory would be taken by this option. If already enabled ESP_WIFI_RX_IRAM_OPT, the other 1.3KB IRAM memory would be taken by this option. If neither of them are enabled, the other 7.4KB IRAM memory would be taken by this option. Wi-Fi power-save mode average current would be reduced if this option is enabled. CONFIG_ESP_WIFI_SLP_DEFAULT_MIN_ACTIVE_TIME Minimum active time Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_IRAM_OPT The minimum timeout for waiting to receive data, unit: milliseconds. Range: from 8 to 60 if CONFIG_ESP_WIFI_SLP_IRAM_OPT Default value: CONFIG_ESP_WIFI_SLP_DEFAULT_MAX_ACTIVE_TIME Maximum keep alive time Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_IRAM_OPT The maximum time that wifi keep alive, unit: seconds. Range: from 10 to 60 if CONFIG_ESP_WIFI_SLP_IRAM_OPT Default value: CONFIG_ESP_WIFI_FTM_ENABLE WiFi FTM Found in: Component config > Wi-Fi Enable feature Fine Timing Measurement for calculating WiFi Round-Trip-Time (RTT). Default value: No (disabled) if SOC_WIFI_FTM_SUPPORT CONFIG_ESP_WIFI_FTM_INITIATOR_SUPPORT FTM Initiator support Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_FTM_ENABLE Default value: Yes (enabled) if CONFIG_ESP_WIFI_FTM_ENABLE CONFIG_ESP_WIFI_FTM_RESPONDER_SUPPORT FTM Responder support Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_FTM_ENABLE Default value: Yes (enabled) if CONFIG_ESP_WIFI_FTM_ENABLE CONFIG_ESP_WIFI_STA_DISCONNECTED_PM_ENABLE Power Management for station at disconnected Found in: Component config > Wi-Fi Select this option to enable power_management for station when disconnected. Chip will do modem-sleep when rf module is not in use any more. Default value: Yes (enabled) CONFIG_ESP_WIFI_GCMP_SUPPORT WiFi GCMP Support(GCMP128 and GCMP256) Found in: Component config > Wi-Fi Select this option to enable GCMP support. GCMP support is compulsory for WiFi Suite-B support. Default value: No (disabled) if SOC_WIFI_GCMP_SUPPORT CONFIG_ESP_WIFI_GMAC_SUPPORT WiFi GMAC Support(GMAC128 and GMAC256) Found in: Component config > Wi-Fi Select this option to enable GMAC support. GMAC support is compulsory for WiFi 192 bit certification. Default value: No (disabled) CONFIG_ESP_WIFI_SOFTAP_SUPPORT WiFi SoftAP Support Found in: Component config > Wi-Fi WiFi module can be compiled without SoftAP to save code size. Default value: Yes (enabled) CONFIG_ESP_WIFI_ENHANCED_LIGHT_SLEEP WiFi modem automatically receives the beacon Found in: Component config > Wi-Fi The wifi modem automatically receives the beacon frame during light sleep. Default value: No (disabled) if CONFIG_ESP_PHY_MAC_BB_PD && SOC_PM_SUPPORT_BEACON_WAKEUP CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT Wifi sleep optimize when beacon lost Found in: Component config > Wi-Fi Enable wifi sleep optimization when beacon loss occurs and immediately enter sleep mode when the WiFi module detects beacon loss. CONFIG_ESP_WIFI_SLP_BEACON_LOST_TIMEOUT Beacon loss timeout Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT Timeout time for close rf phy when beacon loss occurs, Unit: 1024 microsecond. Range: from 5 to 100 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT Default value: CONFIG_ESP_WIFI_SLP_BEACON_LOST_THRESHOLD Maximum number of consecutive lost beacons allowed Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT Maximum number of consecutive lost beacons allowed, WiFi keeps Rx state when the number of consecutive beacons lost is greater than the given threshold. Range: from 0 to 8 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT Default value: CONFIG_ESP_WIFI_SLP_PHY_ON_DELTA_EARLY_TIME Delta early time for RF PHY on Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT Delta early time for rf phy on, When the beacon is lost, the next rf phy on will be earlier the time specified by the configuration item, Unit: 32 microsecond. Range: from 0 to 100 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT Default value: CONFIG_ESP_WIFI_SLP_PHY_OFF_DELTA_TIMEOUT_TIME Delta timeout time for RF PHY off Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT Delta timeout time for rf phy off, When the beacon is lost, the next rf phy off will be delayed for the time specified by the configuration item. Unit: 1024 microsecond. Range: from 0 to 8 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT Default value: CONFIG_ESP_WIFI_ESPNOW_MAX_ENCRYPT_NUM Maximum espnow encrypt peers number Found in: Component config > Wi-Fi Maximum number of encrypted peers supported by espnow. The number of hardware keys for encryption is fixed. And the espnow and SoftAP share the same hardware keys. So this configuration will affect the maximum connection number of SoftAP. Maximum espnow encrypted peers number + maximum number of connections of SoftAP = Max hardware keys number. When using ESP mesh, this value should be set to a maximum of 6. Range: from 0 to 17 Default value: 7 CONFIG_ESP_WIFI_NAN_ENABLE WiFi Aware Found in: Component config > Wi-Fi Enable WiFi Aware (NAN) feature. Default value: No (disabled) CONFIG_ESP_WIFI_ENABLE_WIFI_TX_STATS Enable Wi-Fi transmission statistics Found in: Component config > Wi-Fi Enable Wi-Fi transmission statistics. Total support 4 access category. Each access category will use 346 bytes memory. Default value: Yes (enabled) if SOC_WIFI_HE_SUPPORT CONFIG_ESP_WIFI_MBEDTLS_CRYPTO Use MbedTLS crypto APIs Found in: Component config > Wi-Fi Select this option to enable the use of MbedTLS crypto APIs. The internal crypto support within the supplicant is limited and may not suffice for all new security features, including WPA3. It is recommended to always keep this option enabled. Additionally, note that MbedTLS can leverage hardware acceleration if available, resulting in significantly faster cryptographic operations. Default value: Yes (enabled) CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT Use MbedTLS TLS client for WiFi Enterprise connection Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_MBEDTLS_CRYPTO Select this option to use MbedTLS TLS client for WPA2 enterprise connection. Please note that from MbedTLS-3.0 onwards, MbedTLS does not support SSL-3.0 TLS-v1.0, TLS-v1.1 versions. Incase your server is using one of these version, it is advisable to update your server. Please disable this option for compatibilty with older TLS versions. Default value: Yes (enabled) CONFIG_ESP_WIFI_WAPI_PSK Enable WAPI PSK support Found in: Component config > Wi-Fi Select this option to enable WAPI-PSK which is a Chinese National Standard Encryption for Wireless LANs (GB 15629.11-2003). Default value: No (disabled) CONFIG_ESP_WIFI_SUITE_B_192 Enable NSA suite B support with 192 bit key Found in: Component config > Wi-Fi Select this option to enable 192 bit NSA suite-B. This is necessary to support WPA3 192 bit security. Default value: No (disabled) if SOC_WIFI_GCMP_SUPPORT CONFIG_ESP_WIFI_11KV_SUPPORT Enable 802.11k, 802.11v APIs Support Found in: Component config > Wi-Fi Select this option to enable 802.11k 802.11v APIs(RRM and BTM support). Only APIs which are helpful for network assisted roaming are supported for now. Enable this option with BTM and RRM enabled in sta config to make device ready for network assisted roaming. BTM: BSS transition management enables an AP to request a station to transition to a specific AP, or to indicate to a station a set of preferred APs. RRM: Radio measurements enable STAs to understand the radio environment, it enables STAs to observe and gather data on radio link performance and on the radio environment. Current implementation adds beacon report, link measurement, neighbor report. Default value: No (disabled) CONFIG_ESP_WIFI_SCAN_CACHE Keep scan results in cache Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_11KV_SUPPORT Keep scan results in cache, if not enabled, those will be flushed immediately. Default value: No (disabled) if CONFIG_ESP_WIFI_11KV_SUPPORT CONFIG_ESP_WIFI_MBO_SUPPORT Enable Multi Band Operation Certification Support Found in: Component config > Wi-Fi Select this option to enable WiFi Multiband operation certification support. Default value: No (disabled) CONFIG_ESP_WIFI_DPP_SUPPORT Enable DPP support Found in: Component config > Wi-Fi Select this option to enable WiFi Easy Connect Support. Default value: No (disabled) CONFIG_ESP_WIFI_11R_SUPPORT Enable 802.11R (Fast Transition) Support Found in: Component config > Wi-Fi Select this option to enable WiFi Fast Transition Support. Default value: No (disabled) CONFIG_ESP_WIFI_WPS_SOFTAP_REGISTRAR Add WPS Registrar support in SoftAP mode Found in: Component config > Wi-Fi Select this option to enable WPS registrar support in softAP mode. Default value: No (disabled) CONFIG_ESP_WIFI_ENABLE_WIFI_RX_STATS Enable Wi-Fi reception statistics Found in: Component config > Wi-Fi Enable Wi-Fi reception statistics. Total support 2 access category. Each access category will use 190 bytes memory. Default value: Yes (enabled) if SOC_WIFI_HE_SUPPORT CONFIG_ESP_WIFI_ENABLE_WIFI_RX_MU_STATS Enable Wi-Fi DL MU-MIMO and DL OFDMA reception statistics Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_ENABLE_WIFI_RX_STATS Enable Wi-Fi DL MU-MIMO and DL OFDMA reception statistics. Will use 10932 bytes memory. Default value: Yes (enabled) if CONFIG_ESP_WIFI_ENABLE_WIFI_RX_STATS WPS Configuration Options Contains: CONFIG_ESP_WIFI_WPS_STRICT Strictly validate all WPS attributes Found in: Component config > Wi-Fi > WPS Configuration Options Select this option to enable validate each WPS attribute rigorously. Disabling this add the workaorunds with various APs. Enabling this may cause inter operability issues with some APs. Default value: No (disabled) CONFIG_ESP_WIFI_WPS_PASSPHRASE Get WPA2 passphrase in WPS config Found in: Component config > Wi-Fi > WPS Configuration Options Select this option to get passphrase during WPS configuration. This option fakes the virtual display capabilites to get the configuration in passphrase mode. Not recommanded to be used since WPS credentials should not be shared to other devices, making it in readable format increases that risk, also passphrase requires pbkdf2 to convert in psk. Default value: No (disabled) CONFIG_ESP_WIFI_DEBUG_PRINT Print debug messages from WPA Supplicant Found in: Component config > Wi-Fi Select this option to print logging information from WPA supplicant, this includes handshake information and key hex dumps depending on the project logging level. Enabling this could increase the build size ~60kb depending on the project logging level. Default value: No (disabled) CONFIG_ESP_WIFI_TESTING_OPTIONS Add DPP testing code Found in: Component config > Wi-Fi Select this to enable unity test for DPP. Default value: No (disabled) CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT Enable enterprise option Found in: Component config > Wi-Fi Select this to enable/disable enterprise connection support. disabling this will reduce binary size. disabling this will disable the use of any esp_wifi_sta_wpa2_ent_* (as APIs will be meaningless) Default value: Yes (enabled) CONFIG_ESP_WIFI_ENT_FREE_DYNAMIC_BUFFER Free dynamic buffers during WiFi enterprise connection Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT Select this configuration to free dynamic buffers during WiFi enterprise connection. This will enable chip to reduce heap consumption during WiFi enterprise connection. Default value: No (disabled) Core dump Contains: CONFIG_ESP_COREDUMP_TO_FLASH_OR_UART Data destination Found in: Component config > Core dump Select place to store core dump: flash, uart or none (to disable core dumps generation). Core dumps to Flash are not available if PSRAM is used for task stacks. If core dump is configured to be stored in flash and custom partition table is used add corresponding entry to your CSV. For examples, please see predefined partition table CSV descriptions in the components/partition_table directory. Available options: Flash (CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH) UART (CONFIG_ESP_COREDUMP_ENABLE_TO_UART) None (CONFIG_ESP_COREDUMP_ENABLE_TO_NONE) CONFIG_ESP_COREDUMP_DATA_FORMAT Core dump data format Found in: Component config > Core dump Select the data format for core dump. Available options: Binary format (CONFIG_ESP_COREDUMP_DATA_FORMAT_BIN) ELF format (CONFIG_ESP_COREDUMP_DATA_FORMAT_ELF) CONFIG_ESP_COREDUMP_CHECKSUM Core dump data integrity check Found in: Component config > Core dump Select the integrity check for the core dump. Available options: Use CRC32 for integrity verification (CONFIG_ESP_COREDUMP_CHECKSUM_CRC32) Use SHA256 for integrity verification (CONFIG_ESP_COREDUMP_CHECKSUM_SHA256) CONFIG_ESP_COREDUMP_CHECK_BOOT Check core dump data integrity on boot Found in: Component config > Core dump When enabled, if any data are found on the flash core dump partition, they will be checked by calculating their checksum. Default value: Yes (enabled) if CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH CONFIG_ESP_COREDUMP_LOGS Enable coredump logs for debugging Found in: Component config > Core dump Enable/disable coredump logs. Logs strings from espcoredump component are placed in DRAM. Disabling these helps to save ~5KB of internal memory. CONFIG_ESP_COREDUMP_MAX_TASKS_NUM Maximum number of tasks Found in: Component config > Core dump Maximum number of tasks snapshots in core dump. CONFIG_ESP_COREDUMP_UART_DELAY Delay before print to UART Found in: Component config > Core dump Config delay (in ms) before printing core dump to UART. Delay can be interrupted by pressing Enter key. Default value: CONFIG_ESP_COREDUMP_STACK_SIZE Reserved stack size Found in: Component config > Core dump Size of the memory to be reserved for core dump stack. If 0 core dump process will run on the stack of crashed task/ISR, otherwise special stack will be allocated. To ensure that core dump itself will not overflow task/ISR stack set this to the value above 800. NOTE: It eats DRAM. CONFIG_ESP_COREDUMP_DECODE Handling of UART core dumps in IDF Monitor Found in: Component config > Core dump Available options: Decode and show summary (info_corefile) (CONFIG_ESP_COREDUMP_DECODE_INFO) Don't decode (CONFIG_ESP_COREDUMP_DECODE_DISABLE) FAT Filesystem support Contains: CONFIG_FATFS_VOLUME_COUNT Number of volumes Found in: Component config > FAT Filesystem support Number of volumes (logical drives) to use. Range: from 1 to 10 Default value: 2 CONFIG_FATFS_LONG_FILENAMES Long filename support Found in: Component config > FAT Filesystem support Support long filenames in FAT. Long filename data increases memory usage. FATFS can be configured to store the buffer for long filename data in stack or heap. Available options: No long filenames (CONFIG_FATFS_LFN_NONE) Long filename buffer in heap (CONFIG_FATFS_LFN_HEAP) Long filename buffer on stack (CONFIG_FATFS_LFN_STACK) CONFIG_FATFS_SECTOR_SIZE Sector size Found in: Component config > FAT Filesystem support Specify the size of the sector in bytes for FATFS partition generator. Available options: 512 (CONFIG_FATFS_SECTOR_512) 4096 (CONFIG_FATFS_SECTOR_4096) CONFIG_FATFS_CHOOSE_CODEPAGE OEM Code Page Found in: Component config > FAT Filesystem support OEM code page used for file name encodings. If "Dynamic" is selected, code page can be chosen at runtime using f_setcp function. Note that choosing this option will increase application size by ~480kB. Available options: Dynamic (all code pages supported) (CONFIG_FATFS_CODEPAGE_DYNAMIC) US (CP437) (CONFIG_FATFS_CODEPAGE_437) Arabic (CP720) (CONFIG_FATFS_CODEPAGE_720) Greek (CP737) (CONFIG_FATFS_CODEPAGE_737) KBL (CP771) (CONFIG_FATFS_CODEPAGE_771) Baltic (CP775) (CONFIG_FATFS_CODEPAGE_775) Latin 1 (CP850) (CONFIG_FATFS_CODEPAGE_850) Latin 2 (CP852) (CONFIG_FATFS_CODEPAGE_852) Cyrillic (CP855) (CONFIG_FATFS_CODEPAGE_855) Turkish (CP857) (CONFIG_FATFS_CODEPAGE_857) Portugese (CP860) (CONFIG_FATFS_CODEPAGE_860) Icelandic (CP861) (CONFIG_FATFS_CODEPAGE_861) Hebrew (CP862) (CONFIG_FATFS_CODEPAGE_862) Canadian French (CP863) (CONFIG_FATFS_CODEPAGE_863) Arabic (CP864) (CONFIG_FATFS_CODEPAGE_864) Nordic (CP865) (CONFIG_FATFS_CODEPAGE_865) Russian (CP866) (CONFIG_FATFS_CODEPAGE_866) Greek 2 (CP869) (CONFIG_FATFS_CODEPAGE_869) Japanese (DBCS) (CP932) (CONFIG_FATFS_CODEPAGE_932) Simplified Chinese (DBCS) (CP936) (CONFIG_FATFS_CODEPAGE_936) Korean (DBCS) (CP949) (CONFIG_FATFS_CODEPAGE_949) Traditional Chinese (DBCS) (CP950) (CONFIG_FATFS_CODEPAGE_950) CONFIG_FATFS_MAX_LFN Max long filename length Found in: Component config > FAT Filesystem support Maximum long filename length. Can be reduced to save RAM. CONFIG_FATFS_API_ENCODING API character encoding Found in: Component config > FAT Filesystem support Choose encoding for character and string arguments/returns when using FATFS APIs. The encoding of arguments will usually depend on text editor settings. Available options: API uses ANSI/OEM encoding (CONFIG_FATFS_API_ENCODING_ANSI_OEM) API uses UTF-8 encoding (CONFIG_FATFS_API_ENCODING_UTF_8) CONFIG_FATFS_FS_LOCK Number of simultaneously open files protected by lock function Found in: Component config > FAT Filesystem support This option sets the FATFS configuration value _FS_LOCK. The option _FS_LOCK switches file lock function to control duplicated file open and illegal operation to open objects. * 0: Disable file lock function. To avoid volume corruption, application should avoid illegal open, remove and rename to the open objects. * >0: Enable file lock function. The value defines how many files/sub-directories can be opened simultaneously under file lock control. Note that the file lock control is independent of re-entrancy. Range: from 0 to 65535 Default value: 0 CONFIG_FATFS_TIMEOUT_MS Timeout for acquiring a file lock, ms Found in: Component config > FAT Filesystem support This option sets FATFS configuration value _FS_TIMEOUT, scaled to milliseconds. Sets the number of milliseconds FATFS will wait to acquire a mutex when operating on an open file. For example, if one task is performing a lenghty operation, another task will wait for the first task to release the lock, and time out after amount of time set by this option. Default value: 10000 CONFIG_FATFS_PER_FILE_CACHE Use separate cache for each file Found in: Component config > FAT Filesystem support This option affects FATFS configuration value _FS_TINY. If this option is set, _FS_TINY is 0, and each open file has its own cache, size of the cache is equal to the _MAX_SS variable (512 or 4096 bytes). This option uses more RAM if more than 1 file is open, but needs less reads and writes to the storage for some operations. If this option is not set, _FS_TINY is 1, and single cache is used for all open files, size is also equal to _MAX_SS variable. This reduces the amount of heap used when multiple files are open, but increases the number of read and write operations which FATFS needs to make. Default value: Yes (enabled) CONFIG_FATFS_ALLOC_PREFER_EXTRAM Perfer external RAM when allocating FATFS buffers Found in: Component config > FAT Filesystem support When the option is enabled, internal buffers used by FATFS will be allocated from external RAM. If the allocation from external RAM fails, the buffer will be allocated from the internal RAM. Disable this option if optimizing for performance. Enable this option if optimizing for internal memory size. Default value: Yes (enabled) if CONFIG_SPIRAM_USE_CAPS_ALLOC || CONFIG_SPIRAM_USE_MALLOC CONFIG_FATFS_USE_FASTSEEK Enable fast seek algorithm when using lseek function through VFS FAT Found in: Component config > FAT Filesystem support The fast seek feature enables fast backward/long seek operations without FAT access by using an in-memory CLMT (cluster link map table). Please note, fast-seek is only allowed for read-mode files, if a file is opened in write-mode, the seek mechanism will automatically fallback to the default implementation. Default value: No (disabled) CONFIG_FATFS_FAST_SEEK_BUFFER_SIZE Fast seek CLMT buffer size Found in: Component config > FAT Filesystem support > CONFIG_FATFS_USE_FASTSEEK If fast seek algorithm is enabled, this defines the size of CLMT buffer used by this algorithm in 32-bit word units. This value should be chosen based on prior knowledge of maximum elements of each file entry would store. Default value: CONFIG_FATFS_VFS_FSTAT_BLKSIZE Default block size Found in: Component config > FAT Filesystem support If set to 0, the 'newlib' library's default size (BLKSIZ) is used (128 B). If set to a non-zero value, the value is used as the block size. Default file buffer size is set to this value and the buffer is allocated when first attempt of reading/writing to a file is made. Increasing this value improves fread() speed, however the heap usage is increased as well. NOTE: The block size value is shared by all the filesystem functions accessing target media for given file descriptor! See 'Improving I/O performance' section of 'Maximizing Execution Speed' documentation page for more details. Default value: 0 CONFIG_FATFS_IMMEDIATE_FSYNC Enable automatic f_sync Found in: Component config > FAT Filesystem support Enables automatic calling of f_sync() to flush recent file changes after each call of vfs_fat_write(), vfs_fat_pwrite(), vfs_fat_link(), vfs_fat_truncate() and vfs_fat_ftruncate() functions. This feature improves file-consistency and size reporting accuracy for the FatFS, at a price on decreased performance due to frequent disk operations Default value: No (disabled) FreeRTOS Contains: Kernel Contains: CONFIG_FREERTOS_SMP Run the Amazon SMP FreeRTOS kernel instead (FEATURE UNDER DEVELOPMENT) Found in: Component config > FreeRTOS > Kernel Amazon has released an SMP version of the FreeRTOS Kernel which can be found via the following link: https://github.com/FreeRTOS/FreeRTOS-Kernel/tree/smp IDF has added an experimental port of this SMP kernel located in components/freertos/FreeRTOS-Kernel-SMP. Enabling this option will cause IDF to use the Amazon SMP kernel. Note that THIS FEATURE IS UNDER ACTIVE DEVELOPMENT, users use this at their own risk. Leaving this option disabled will mean the IDF FreeRTOS kernel is used instead, which is located in: components/freertos/FreeRTOS-Kernel. Both kernel versions are SMP capable, but differ in their implementation and features. Default value: No (disabled) CONFIG_FREERTOS_UNICORE Run FreeRTOS only on first core Found in: Component config > FreeRTOS > Kernel This version of FreeRTOS normally takes control of all cores of the CPU. Select this if you only want to start it on the first core. This is needed when e.g. another process needs complete control over the second core. CONFIG_FREERTOS_HZ configTICK_RATE_HZ Found in: Component config > FreeRTOS > Kernel Sets the FreeRTOS tick interrupt frequency in Hz (see configTICK_RATE_HZ documentation for more details). Range: from 1 to 1000 Default value: 100 CONFIG_FREERTOS_OPTIMIZED_SCHEDULER configUSE_PORT_OPTIMISED_TASK_SELECTION Found in: Component config > FreeRTOS > Kernel Enables port specific task selection method. This option can speed up the search of ready tasks when scheduling (see configUSE_PORT_OPTIMISED_TASK_SELECTION documentation for more details). CONFIG_FREERTOS_CHECK_STACKOVERFLOW configCHECK_FOR_STACK_OVERFLOW Found in: Component config > FreeRTOS > Kernel Enables FreeRTOS to check for stack overflows (see configCHECK_FOR_STACK_OVERFLOW documentation for more details). Note: If users do not provide their own vApplicationStackOverflowHook() function, a default function will be provided by ESP-IDF. Available options: No checking (CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE) Do not check for stack overflows (configCHECK_FOR_STACK_OVERFLOW = 0) Check by stack pointer value (Method 1) (CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL) Check for stack overflows on each context switch by checking if the stack pointer is in a valid range. Quick but does not detect stack overflows that happened between context switches (configCHECK_FOR_STACK_OVERFLOW = 1) Check using canary bytes (Method 2) (CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY) Places some magic bytes at the end of the stack area and on each context switch, check if these bytes are still intact. More thorough than just checking the pointer, but also slightly slower. (configCHECK_FOR_STACK_OVERFLOW = 2) CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS configNUM_THREAD_LOCAL_STORAGE_POINTERS Found in: Component config > FreeRTOS > Kernel Set the number of thread local storage pointers in each task (see configNUM_THREAD_LOCAL_STORAGE_POINTERS documentation for more details). Note: In ESP-IDF, this value must be at least 1. Index 0 is reserved for use by the pthreads API thread-local-storage. Other indexes can be used for any desired purpose. Range: from 1 to 256 Default value: 1 CONFIG_FREERTOS_IDLE_TASK_STACKSIZE configMINIMAL_STACK_SIZE (Idle task stack size) Found in: Component config > FreeRTOS > Kernel Sets the idle task stack size in bytes (see configMINIMAL_STACK_SIZE documentation for more details). Note: ESP-IDF specifies stack sizes in bytes instead of words. The default size is enough for most use cases. The stack size may need to be increased above the default if the app installs idle or thread local storage cleanup hooks that use a lot of stack memory. Conversely, the stack size can be reduced to the minimum if non of the idle features are used. Range: from 768 to 32768 Default value: 1536 CONFIG_FREERTOS_USE_IDLE_HOOK configUSE_IDLE_HOOK Found in: Component config > FreeRTOS > Kernel Enables the idle task application hook (see configUSE_IDLE_HOOK documentation for more details). Note: The application must provide the hook function void vApplicationIdleHook( void ); vApplicationIdleHook() is called from FreeRTOS idle task(s) The FreeRTOS idle hook is NOT the same as the ESP-IDF Idle Hook, but both can be enabled simultaneously. Default value: No (disabled) CONFIG_FREERTOS_USE_MINIMAL_IDLE_HOOK Use FreeRTOS minimal idle hook Found in: Component config > FreeRTOS > Kernel Enables the minimal idle task application hook (see configUSE_IDLE_HOOK documentation for more details). Note: The application must provide the hook function void vApplicationMinimalIdleHook( void ); vApplicationMinimalIdleHook() is called from FreeRTOS minimal idle task(s) Default value: No (disabled) if CONFIG_FREERTOS_SMP CONFIG_FREERTOS_USE_TICK_HOOK configUSE_TICK_HOOK Found in: Component config > FreeRTOS > Kernel Enables the tick hook (see configUSE_TICK_HOOK documentation for more details). Note: The application must provide the hook function void vApplicationTickHook( void ); vApplicationTickHook() is called from FreeRTOS's tick handling function xTaskIncrementTick() The FreeRTOS tick hook is NOT the same as the ESP-IDF Tick Interrupt Hook, but both can be enabled simultaneously. Default value: No (disabled) CONFIG_FREERTOS_MAX_TASK_NAME_LEN configMAX_TASK_NAME_LEN Found in: Component config > FreeRTOS > Kernel Sets the maximum number of characters for task names (see configMAX_TASK_NAME_LEN documentation for more details). Note: For most uses, the default of 16 characters is sufficient. Range: from 1 to 256 Default value: 16 CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY configENABLE_BACKWARD_COMPATIBILITY Found in: Component config > FreeRTOS > Kernel Enable backward compatibility with APIs prior to FreeRTOS v8.0.0. (see configENABLE_BACKWARD_COMPATIBILITY documentation for more details). Default value: No (disabled) CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME configTIMER_SERVICE_TASK_NAME Found in: Component config > FreeRTOS > Kernel Sets the timer task's name (see configTIMER_SERVICE_TASK_NAME documentation for more details). Default value: "Tmr Svc" CONFIG_FREERTOS_TIMER_TASK_PRIORITY configTIMER_TASK_PRIORITY Found in: Component config > FreeRTOS > Kernel Sets the timer task's priority (see configTIMER_TASK_PRIORITY documentation for more details). Range: from 1 to 25 Default value: 1 CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH configTIMER_TASK_STACK_DEPTH Found in: Component config > FreeRTOS > Kernel Set the timer task's stack size (see configTIMER_TASK_STACK_DEPTH documentation for more details). Range: from 1536 to 32768 Default value: 2048 CONFIG_FREERTOS_TIMER_QUEUE_LENGTH configTIMER_QUEUE_LENGTH Found in: Component config > FreeRTOS > Kernel Set the timer task's command queue length (see configTIMER_QUEUE_LENGTH documentation for more details). Range: from 5 to 20 Default value: 10 CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE configQUEUE_REGISTRY_SIZE Found in: Component config > FreeRTOS > Kernel Set the size of the queue registry (see configQUEUE_REGISTRY_SIZE documentation for more details). Note: A value of 0 will disable queue registry functionality Range: from 0 to 20 Default value: 0 CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES configTASK_NOTIFICATION_ARRAY_ENTRIES Found in: Component config > FreeRTOS > Kernel Set the size of the task notification array of each task. When increasing this value, keep in mind that this means additional memory for each and every task on the system. However, task notifications in general are more light weight compared to alternatives such as semaphores. Range: from 1 to 32 Default value: 1 CONFIG_FREERTOS_USE_TRACE_FACILITY configUSE_TRACE_FACILITY Found in: Component config > FreeRTOS > Kernel Enables additional structure members and functions to assist with execution visualization and tracing (see configUSE_TRACE_FACILITY documentation for more details). Default value: No (disabled) CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS configUSE_STATS_FORMATTING_FUNCTIONS Found in: Component config > FreeRTOS > Kernel > CONFIG_FREERTOS_USE_TRACE_FACILITY Set configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS to 1 to include the vTaskList() and vTaskGetRunTimeStats() functions in the build (see configUSE_STATS_FORMATTING_FUNCTIONS documentation for more details). Default value: No (disabled) if CONFIG_FREERTOS_USE_TRACE_FACILITY CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID Enable display of xCoreID in vTaskList Found in: Component config > FreeRTOS > Kernel > CONFIG_FREERTOS_USE_TRACE_FACILITY > CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS If enabled, this will include an extra column when vTaskList is called to display the CoreID the task is pinned to (0,1) or -1 if not pinned. CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS configGENERATE_RUN_TIME_STATS Found in: Component config > FreeRTOS > Kernel Enables collection of run time statistics for each task (see configGENERATE_RUN_TIME_STATS documentation for more details). Note: The clock used for run time statistics can be configured in FREERTOS_RUN_TIME_STATS_CLK. Default value: No (disabled) CONFIG_FREERTOS_RUN_TIME_COUNTER_TYPE configRUN_TIME_COUNTER_TYPE Found in: Component config > FreeRTOS > Kernel > CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS Sets the data type used for the FreeRTOS run time stats. A larger data type can be used to reduce the frequency of the counter overflowing. Available options: uint32_t (CONFIG_FREERTOS_RUN_TIME_COUNTER_TYPE_U32) configRUN_TIME_COUNTER_TYPE is set to uint32_t uint64_t (CONFIG_FREERTOS_RUN_TIME_COUNTER_TYPE_U64) configRUN_TIME_COUNTER_TYPE is set to uint64_t CONFIG_FREERTOS_USE_TICKLESS_IDLE configUSE_TICKLESS_IDLE Found in: Component config > FreeRTOS > Kernel If power management support is enabled, FreeRTOS will be able to put the system into light sleep mode when no tasks need to run for a number of ticks. This number can be set using FREERTOS_IDLE_TIME_BEFORE_SLEEP option. This feature is also known as "automatic light sleep". Note that timers created using esp_timer APIs may prevent the system from entering sleep mode, even when no tasks need to run. To skip unnecessary wake-up initialize a timer with the "skip_unhandled_events" option as true. If disabled, automatic light sleep support will be disabled. Default value: No (disabled) if CONFIG_PM_ENABLE CONFIG_FREERTOS_IDLE_TIME_BEFORE_SLEEP configEXPECTED_IDLE_TIME_BEFORE_SLEEP Found in: Component config > FreeRTOS > Kernel > CONFIG_FREERTOS_USE_TICKLESS_IDLE FreeRTOS will enter light sleep mode if no tasks need to run for this number of ticks. You can enable PM_PROFILING feature in esp_pm components and dump the sleep status with esp_pm_dump_locks, if the proportion of rejected sleeps is too high, please increase this value to improve scheduling efficiency Range: from 2 to 4294967295 if CONFIG_FREERTOS_USE_TICKLESS_IDLE Default value: Port Contains: CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER Wrap task functions Found in: Component config > FreeRTOS > Port If enabled, all FreeRTOS task functions will be enclosed in a wrapper function. If a task function mistakenly returns (i.e. does not delete), the call flow will return to the wrapper function. The wrapper function will then log an error and abort the application. This option is also required for GDB backtraces and C++ exceptions to work correctly inside top-level task functions. Default value: Yes (enabled) CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK Enable stack overflow debug watchpoint Found in: Component config > FreeRTOS > Port FreeRTOS can check if a stack has overflown its bounds by checking either the value of the stack pointer or by checking the integrity of canary bytes. (See FREERTOS_CHECK_STACKOVERFLOW for more information.) These checks only happen on a context switch, and the situation that caused the stack overflow may already be long gone by then. This option will use the last debug memory watchpoint to allow breaking into the debugger (or panic'ing) as soon as any of the last 32 bytes on the stack of a task are overwritten. The side effect is that using gdb, you effectively have one hardware watchpoint less because the last one is overwritten as soon as a task switch happens. Another consequence is that due to alignment requirements of the watchpoint, the usable stack size decreases by up to 60 bytes. This is because the watchpoint region has to be aligned to its size and the size for the stack watchpoint in IDF is 32 bytes. This check only triggers if the stack overflow writes within 32 bytes near the end of the stack, rather than overshooting further, so it is worth combining this approach with one of the other stack overflow check methods. When this watchpoint is hit, gdb will stop with a SIGTRAP message. When no JTAG OCD is attached, esp-idf will panic on an unhandled debug exception. Default value: No (disabled) CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS Enable thread local storage pointers deletion callbacks Found in: Component config > FreeRTOS > Port ESP-IDF provides users with the ability to free TLSP memory by registering TLSP deletion callbacks. These callbacks are automatically called by FreeRTOS when a task is deleted. When this option is turned on, the memory reserved for TLSPs in the TCB is doubled to make space for storing the deletion callbacks. If the user does not wish to use TLSP deletion callbacks then this option could be turned off to save space in the TCB memory. Default value: Yes (enabled) CONFIG_FREERTOS_TASK_PRE_DELETION_HOOK Enable task pre-deletion hook Found in: Component config > FreeRTOS > Port Enable this option to make FreeRTOS call a user provided hook function right before it deletes a task (i.e., frees/releases a dynamically/statically allocated task's memory). This is useful if users want to know when a task is actually deleted (in case the task's deletion is delegated to the IDLE task). If this config option is enabled, users must define a void vTaskPreDeletionHook( void \* pxTCB ) hook function in their application. CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP Enable static task clean up hook (DEPRECATED) Found in: Component config > FreeRTOS > Port THIS OPTION IS DEPRECATED. Use FREERTOS_TASK_PRE_DELETION_HOOK instead. Enable this option to make FreeRTOS call the static task clean up hook when a task is deleted. Note: Users will need to provide a void vPortCleanUpTCB ( void \*pxTCB ) callback Default value: No (disabled) CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER Check that mutex semaphore is given by owner task Found in: Component config > FreeRTOS > Port If enabled, assert that when a mutex semaphore is given, the task giving the semaphore is the task which is currently holding the mutex. CONFIG_FREERTOS_ISR_STACKSIZE ISR stack size Found in: Component config > FreeRTOS > Port The interrupt handlers have their own stack. The size of the stack can be defined here. Each processor has its own stack, so the total size occupied will be twice this. Range: from 2096 to 32768 if CONFIG_ESP_COREDUMP_DATA_FORMAT_ELF from 1536 to 32768 Default value: 1536 CONFIG_FREERTOS_INTERRUPT_BACKTRACE Enable backtrace from interrupt to task context Found in: Component config > FreeRTOS > Port If this option is enabled, interrupt stack frame will be modified to point to the code of the interrupted task as its return address. This helps the debugger (or the panic handler) show a backtrace from the interrupt to the task which was interrupted. This also works for nested interrupts: higher level interrupt stack can be traced back to the lower level interrupt. This option adds 4 instructions to the interrupt dispatching code. Default value: Yes (enabled) CONFIG_FREERTOS_FPU_IN_ISR Use float in Level 1 ISR Found in: Component config > FreeRTOS > Port When enabled, the usage of float type is allowed inside Level 1 ISRs. Note that usage of float types in higher level interrupts is still not permitted. Default value: No (disabled) CONFIG_FREERTOS_CORETIMER Tick timer source (Xtensa Only) Found in: Component config > FreeRTOS > Port FreeRTOS needs a timer with an associated interrupt to use as the main tick source to increase counters, run timers and do pre-emptive multitasking with. There are multiple timers available to do this, with different interrupt priorities. Available options: Timer 0 (int 6, level 1) (CONFIG_FREERTOS_CORETIMER_0) Select this to use timer 0 Timer 1 (int 15, level 3) (CONFIG_FREERTOS_CORETIMER_1) Select this to use timer 1 SYSTIMER 0 (level 1) (CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL1) Select this to use systimer with the 1 interrupt priority. SYSTIMER 0 (level 3) (CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL3) Select this to use systimer with the 3 interrupt priority. CONFIG_FREERTOS_RUN_TIME_STATS_CLK Choose the clock source for run time stats Found in: Component config > FreeRTOS > Port Choose the clock source for FreeRTOS run time stats. Options are CPU0's CPU Clock or the ESP Timer. Both clock sources are 32 bits. The CPU Clock can run at a higher frequency hence provide a finer resolution but will overflow much quicker. Note that run time stats are only valid until the clock source overflows. Available options: Use ESP TIMER for run time stats (CONFIG_FREERTOS_RUN_TIME_STATS_USING_ESP_TIMER) ESP Timer will be used as the clock source for FreeRTOS run time stats. The ESP Timer runs at a frequency of 1MHz regardless of Dynamic Frequency Scaling. Therefore the ESP Timer will overflow in approximately 4290 seconds. Use CPU Clock for run time stats (CONFIG_FREERTOS_RUN_TIME_STATS_USING_CPU_CLK) CPU Clock will be used as the clock source for the generation of run time stats. The CPU Clock has a frequency dependent on ESP_DEFAULT_CPU_FREQ_MHZ and Dynamic Frequency Scaling (DFS). Therefore the CPU Clock frequency can fluctuate between 80 to 240MHz. Run time stats generated using the CPU Clock represents the number of CPU cycles each task is allocated and DOES NOT reflect the amount of time each task runs for (as CPU clock frequency can change). If the CPU clock consistently runs at the maximum frequency of 240MHz, it will overflow in approximately 17 seconds. CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH Place FreeRTOS functions into Flash Found in: Component config > FreeRTOS > Port When enabled the selected Non-ISR FreeRTOS functions will be placed into Flash memory instead of IRAM. This saves up to 8KB of IRAM depending on which functions are used. Default value: No (disabled) CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE Tests compliance with Vanilla FreeRTOS port*_CRITICAL calls Found in: Component config > FreeRTOS > Port If enabled, context of port*_CRITICAL calls (ISR or Non-ISR) would be checked to be in compliance with Vanilla FreeRTOS. e.g Calling port*_CRITICAL from ISR context would cause assert failure Default value: No (disabled) Hardware Abstraction Layer (HAL) and Low Level (LL) Contains: CONFIG_HAL_DEFAULT_ASSERTION_LEVEL Default HAL assertion level Found in: Component config > Hardware Abstraction Layer (HAL) and Low Level (LL) Set the assert behavior / level for HAL component. HAL component assert level can be set separately, but the level can't exceed the system assertion level. e.g. If the system assertion is disabled, then the HAL assertion can't be enabled either. If the system assertion is enable, then the HAL assertion can still be disabled by this Kconfig option. Available options: Same as system assertion level (CONFIG_HAL_ASSERTION_EQUALS_SYSTEM) Disabled (CONFIG_HAL_ASSERTION_DISABLE) Silent (CONFIG_HAL_ASSERTION_SILENT) Enabled (CONFIG_HAL_ASSERTION_ENABLE) CONFIG_HAL_LOG_LEVEL HAL layer log verbosity Found in: Component config > Hardware Abstraction Layer (HAL) and Low Level (LL) Specify how much output to see in HAL logs. Available options: No output (CONFIG_HAL_LOG_LEVEL_NONE) Error (CONFIG_HAL_LOG_LEVEL_ERROR) Warning (CONFIG_HAL_LOG_LEVEL_WARN) Info (CONFIG_HAL_LOG_LEVEL_INFO) Debug (CONFIG_HAL_LOG_LEVEL_DEBUG) Verbose (CONFIG_HAL_LOG_LEVEL_VERBOSE) CONFIG_HAL_SYSTIMER_USE_ROM_IMPL Use ROM implementation of SysTimer HAL driver Found in: Component config > Hardware Abstraction Layer (HAL) and Low Level (LL) Enable this flag to use HAL functions from ROM instead of ESP-IDF. If keeping this as "n" in your project, you will have less free IRAM. If making this as "y" in your project, you will increase free IRAM, but you will lose the possibility to debug this module, and some new features will be added and bugs will be fixed in the IDF source but cannot be synced to ROM. Default value: Yes (enabled) if ESP_ROM_HAS_HAL_SYSTIMER CONFIG_HAL_WDT_USE_ROM_IMPL Use ROM implementation of WDT HAL driver Found in: Component config > Hardware Abstraction Layer (HAL) and Low Level (LL) Enable this flag to use HAL functions from ROM instead of ESP-IDF. If keeping this as "n" in your project, you will have less free IRAM. If making this as "y" in your project, you will increase free IRAM, but you will lose the possibility to debug this module, and some new features will be added and bugs will be fixed in the IDF source but cannot be synced to ROM. Default value: Yes (enabled) if ESP_ROM_HAS_HAL_WDT Heap memory debugging Contains: CONFIG_HEAP_CORRUPTION_DETECTION Heap corruption detection Found in: Component config > Heap memory debugging Enable heap poisoning features to detect heap corruption caused by out-of-bounds access to heap memory. See the "Heap Memory Debugging" page of the IDF documentation for a description of each level of heap corruption detection. Available options: Basic (no poisoning) (CONFIG_HEAP_POISONING_DISABLED) Light impact (CONFIG_HEAP_POISONING_LIGHT) Comprehensive (CONFIG_HEAP_POISONING_COMPREHENSIVE) CONFIG_HEAP_TRACING_DEST Heap tracing Found in: Component config > Heap memory debugging Enables the heap tracing API defined in esp_heap_trace.h. This function causes a moderate increase in IRAM code side and a minor increase in heap function (malloc/free/realloc) CPU overhead, even when the tracing feature is not used. So it's best to keep it disabled unless tracing is being used. Available options: Disabled (CONFIG_HEAP_TRACING_OFF) Standalone (CONFIG_HEAP_TRACING_STANDALONE) Host-based (CONFIG_HEAP_TRACING_TOHOST) CONFIG_HEAP_TRACING_STACK_DEPTH Heap tracing stack depth Found in: Component config > Heap memory debugging Number of stack frames to save when tracing heap operation callers. More stack frames uses more memory in the heap trace buffer (and slows down allocation), but can provide useful information. CONFIG_HEAP_USE_HOOKS Use allocation and free hooks Found in: Component config > Heap memory debugging Enable the user to implement function hooks triggered for each successful allocation and free. CONFIG_HEAP_TASK_TRACKING Enable heap task tracking Found in: Component config > Heap memory debugging Enables tracking the task responsible for each heap allocation. This function depends on heap poisoning being enabled and adds four more bytes of overhead for each block allocated. CONFIG_HEAP_TRACE_HASH_MAP Use hash map mechanism to access heap trace records Found in: Component config > Heap memory debugging Enable this flag to use a hash map to increase performance in handling heap trace records. Heap trace standalone supports storing records as a list, or a list + hash map. Using only a list takes less memory, but calls to 'free' will get slower as the list grows. This is particularly affected when using HEAP_TRACE_ALL mode. By using a list + hash map, calls to 'free' remain fast, at the cost of additional memory to store the hash map. Default value: No (disabled) if CONFIG_HEAP_TRACING_STANDALONE CONFIG_HEAP_TRACE_HASH_MAP_IN_EXT_RAM Place hash map in external RAM Found in: Component config > Heap memory debugging > CONFIG_HEAP_TRACE_HASH_MAP When enabled this configuration forces the hash map to be placed in external RAM. Default value: No (disabled) if CONFIG_HEAP_TRACE_HASH_MAP CONFIG_HEAP_TRACE_HASH_MAP_SIZE The number of entries in the hash map Found in: Component config > Heap memory debugging > CONFIG_HEAP_TRACE_HASH_MAP Defines the number of entries in the heap trace hashmap. Each entry takes 8 bytes. The bigger this number is, the better the performance. Recommended range: 200 - 2000. Default value: 512 if CONFIG_HEAP_TRACE_HASH_MAP CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS Abort if memory allocation fails Found in: Component config > Heap memory debugging When enabled, if a memory allocation operation fails it will cause a system abort. Default value: No (disabled) CONFIG_HEAP_TLSF_USE_ROM_IMPL Use ROM implementation of heap tlsf library Found in: Component config > Heap memory debugging Enable this flag to use heap functions from ROM instead of ESP-IDF. If keeping this as "n" in your project, you will have less free IRAM. If making this as "y" in your project, you will increase free IRAM, but you will lose the possibility to debug this module, and some new features will be added and bugs will be fixed in the IDF source but cannot be synced to ROM. Default value: Yes (enabled) if ESP_ROM_HAS_HEAP_TLSF CONFIG_HEAP_PLACE_FUNCTION_INTO_FLASH Force the entire heap component to be placed in flash memory Found in: Component config > Heap memory debugging Enable this flag to save up RAM space by placing the heap component in the flash memory Note that it is only safe to enable this configuration if no functions from esp_heap_caps.h or esp_heap_trace.h are called from ISR. IEEE 802.15.4 Contains: CONFIG_IEEE802154_ENABLED IEEE802154 Enable Found in: Component config > IEEE 802.15.4 Default value: Yes (enabled) if SOC_IEEE802154_SUPPORTED CONFIG_IEEE802154_RX_BUFFER_SIZE The number of 802.15.4 receive buffers Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED The number of 802.15.4 receive buffers Range: from 2 to 100 if CONFIG_IEEE802154_ENABLED Default value: CONFIG_IEEE802154_CCA_MODE Clear Channel Assessment (CCA) mode Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED configure the CCA mode Available options: Carrier sense only (CONFIG_IEEE802154_CCA_CARRIER) configure the CCA mode to Energy above threshold Energy above threshold (CONFIG_IEEE802154_CCA_ED) configure the CCA mode to Energy above threshold Carrier sense OR energy above threshold (CONFIG_IEEE802154_CCA_CARRIER_OR_ED) configure the CCA mode to Carrier sense OR energy above threshold Carrier sense AND energy above threshold (CONFIG_IEEE802154_CCA_CARRIER_AND_ED) configure the CCA mode to Carrier sense AND energy above threshold CONFIG_IEEE802154_CCA_THRESHOLD CCA detection threshold Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED set the CCA threshold, in dB Range: from -120 to 0 if CONFIG_IEEE802154_ENABLED Default value: "-60" if CONFIG_IEEE802154_ENABLED CONFIG_IEEE802154_PENDING_TABLE_SIZE Pending table size Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED set the pending table size Range: from 1 to 100 if CONFIG_IEEE802154_ENABLED Default value: CONFIG_IEEE802154_MULTI_PAN_ENABLE Enable multi-pan feature for frame filter Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED Enable IEEE802154 multi-pan Default value: No (disabled) if CONFIG_IEEE802154_ENABLED CONFIG_IEEE802154_TIMING_OPTIMIZATION Enable throughput optimization Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED Enabling this option increases throughput by ~5% at the expense of ~2.1k IRAM code size increase. Default value: No (disabled) if CONFIG_IEEE802154_ENABLED CONFIG_IEEE802154_SLEEP_ENABLE Enable IEEE802154 light sleep Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED Enabling this option allows the IEEE802.15.4 module to be powered down during automatic light sleep, which reduces current consumption. Default value: No (disabled) if CONFIG_PM_ENABLE && CONFIG_IEEE802154_ENABLED CONFIG_IEEE802154_DEBUG Enable IEEE802154 Debug Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED Enabling this option allows different kinds of IEEE802154 debug output. All IEEE802154 debug features increase the size of the final binary. Default value: No (disabled) if CONFIG_IEEE802154_ENABLED Contains: CONFIG_IEEE802154_ASSERT Enrich the assert information with IEEE802154 state and event Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG Enabling this option to add some probe codes in the driver, and these informations will be printed when assert. Default value: No (disabled) if CONFIG_IEEE802154_DEBUG CONFIG_IEEE802154_RECORD_EVENT Enable record event information for debugging Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG Enabling this option to record event, when assert, the recorded event will be printed. Default value: No (disabled) if CONFIG_IEEE802154_DEBUG CONFIG_IEEE802154_RECORD_EVENT_SIZE Record event table size Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG > CONFIG_IEEE802154_RECORD_EVENT set the record event table size Range: from 1 to 50 if CONFIG_IEEE802154_RECORD_EVENT Default value: CONFIG_IEEE802154_RECORD_STATE Enable record state information for debugging Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG Enabling this option to record state, when assert, the recorded state will be printed. Default value: No (disabled) if CONFIG_IEEE802154_DEBUG CONFIG_IEEE802154_RECORD_STATE_SIZE Record state table size Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG > CONFIG_IEEE802154_RECORD_STATE set the record state table size Range: from 1 to 50 if CONFIG_IEEE802154_RECORD_STATE Default value: CONFIG_IEEE802154_RECORD_CMD Enable record command information for debugging Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG Enabling this option to record the command, when assert, the recorded command will be printed. Default value: No (disabled) if CONFIG_IEEE802154_DEBUG CONFIG_IEEE802154_RECORD_CMD_SIZE Record command table size Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG > CONFIG_IEEE802154_RECORD_CMD set the record command table size Range: from 1 to 50 if CONFIG_IEEE802154_RECORD_CMD Default value: CONFIG_IEEE802154_RECORD_ABORT Enable record abort information for debugging Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG Enabling this option to record the abort, when assert, the recorded abort will be printed. Default value: No (disabled) if CONFIG_IEEE802154_DEBUG CONFIG_IEEE802154_RECORD_ABORT_SIZE Record abort table size Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG > CONFIG_IEEE802154_RECORD_ABORT set the record abort table size Range: from 1 to 50 if CONFIG_IEEE802154_RECORD_ABORT Default value: CONFIG_IEEE802154_TXRX_STATISTIC Enable record tx/rx packets information for debugging Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG Enabling this option to record the tx and rx Default value: No (disabled) if CONFIG_IEEE802154_DEBUG Log output Contains: CONFIG_LOG_DEFAULT_LEVEL Default log verbosity Found in: Component config > Log output Specify how much output to see in logs by default. You can set lower verbosity level at runtime using esp_log_level_set function. By default, this setting limits which log statements are compiled into the program. For example, selecting "Warning" would mean that changing log level to "Debug" at runtime will not be possible. To allow increasing log level above the default at runtime, see the next option. Available options: No output (CONFIG_LOG_DEFAULT_LEVEL_NONE) Error (CONFIG_LOG_DEFAULT_LEVEL_ERROR) Warning (CONFIG_LOG_DEFAULT_LEVEL_WARN) Info (CONFIG_LOG_DEFAULT_LEVEL_INFO) Debug (CONFIG_LOG_DEFAULT_LEVEL_DEBUG) Verbose (CONFIG_LOG_DEFAULT_LEVEL_VERBOSE) CONFIG_LOG_MAXIMUM_LEVEL Maximum log verbosity Found in: Component config > Log output This config option sets the highest log verbosity that it's possible to select at runtime by calling esp_log_level_set(). This level may be higher than the default verbosity level which is set when the app starts up. This can be used enable debugging output only at a critical point, for a particular tag, or to minimize startup time but then enable more logs once the firmware has loaded. Note that increasing the maximum available log level will increase the firmware binary size. This option only applies to logging from the app, the bootloader log level is fixed at compile time to the separate "Bootloader log verbosity" setting. Available options: Same as default (CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT) Error (CONFIG_LOG_MAXIMUM_LEVEL_ERROR) Warning (CONFIG_LOG_MAXIMUM_LEVEL_WARN) Info (CONFIG_LOG_MAXIMUM_LEVEL_INFO) Debug (CONFIG_LOG_MAXIMUM_LEVEL_DEBUG) Verbose (CONFIG_LOG_MAXIMUM_LEVEL_VERBOSE) CONFIG_LOG_MASTER_LEVEL Enable global master log level Found in: Component config > Log output Enables an additional global "master" log level check that occurs before a log tag cache lookup. This is useful if you want to compile in a lot of logs that are selectable at runtime, but avoid the performance hit during periods where you don't want log output. Examples include remote log forwarding, or disabling logs during a time-critical or CPU-intensive section and re-enabling them later. Results in larger program size depending on number of logs compiled in. If enabled, defaults to LOG_DEFAULT_LEVEL and can be set using esp_log_set_level_master(). This check takes precedence over ESP_LOG_LEVEL_LOCAL. Default value: No (disabled) CONFIG_LOG_COLORS Use ANSI terminal colors in log output Found in: Component config > Log output Enable ANSI terminal color codes in bootloader output. In order to view these, your terminal program must support ANSI color codes. Default value: Yes (enabled) CONFIG_LOG_TIMESTAMP_SOURCE Log Timestamps Found in: Component config > Log output Choose what sort of timestamp is displayed in the log output: Milliseconds since boot is calulated from the RTOS tick count multiplied by the tick period. This time will reset after a software reboot. e.g. (90000) System time is taken from POSIX time functions which use the chip's RTC and high resoultion timers to maintain an accurate time. The system time is initialized to 0 on startup, it can be set with an SNTP sync, or with POSIX time functions. This time will not reset after a software reboot. e.g. (00:01:30.000) NOTE: Currently this will not get used in logging from binary blobs (i.e WiFi & Bluetooth libraries), these will always print milliseconds since boot. Available options: Milliseconds Since Boot (CONFIG_LOG_TIMESTAMP_SOURCE_RTOS) System Time (CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM) LWIP Contains: CONFIG_LWIP_ENABLE Enable LwIP stack Found in: Component config > LWIP Builds normally if selected. Excludes LwIP from build if unselected, even if it is a dependency of a component or application. Some applications can switch their IP stacks, e.g., when switching between chip and Linux targets (LwIP stack vs. Linux IP stack). Since the LwIP dependency cannot easily be excluded based on a Kconfig option, it has to be a dependency in all cases. This switch allows the LwIP stack to be built selectively, even if it is a dependency. Default value: Yes (enabled) CONFIG_LWIP_LOCAL_HOSTNAME Local netif hostname Found in: Component config > LWIP The default name this device will report to other devices on the network. Could be updated at runtime with esp_netif_set_hostname() Default value: "espressif" CONFIG_LWIP_NETIF_API Enable usage of standard POSIX APIs in LWIP Found in: Component config > LWIP If this feature is enabled, standard POSIX APIs: if_indextoname(), if_nametoindex() could be used to convert network interface index to name instead of IDF specific esp-netif APIs (such as esp_netif_get_netif_impl_name()) Default value: No (disabled) CONFIG_LWIP_TCPIP_TASK_PRIO LWIP TCP/IP Task Priority Found in: Component config > LWIP LWIP tcpip task priority. In case of high throughput, this parameter could be changed up to (configMAX_PRIORITIES-1). Range: from 1 to 24 Default value: 18 CONFIG_LWIP_TCPIP_CORE_LOCKING Enable tcpip core locking Found in: Component config > LWIP If Enable tcpip core locking,Creates a global mutex that is held during TCPIP thread operations.Can be locked by client code to perform lwIP operations without changing into TCPIP thread using callbacks. See LOCK_TCPIP_CORE() and UNLOCK_TCPIP_CORE(). If disable tcpip core locking,TCP IP will perform tasks through context switching Default value: No (disabled) CONFIG_LWIP_TCPIP_CORE_LOCKING_INPUT Enable tcpip core locking input Found in: Component config > LWIP > CONFIG_LWIP_TCPIP_CORE_LOCKING when LWIP_TCPIP_CORE_LOCKING is enabled, this lets tcpip_input() grab the mutex for input packets as well, instead of allocating a message and passing it to tcpip_thread. Default value: No (disabled) if CONFIG_LWIP_TCPIP_CORE_LOCKING CONFIG_LWIP_CHECK_THREAD_SAFETY Checks that lwip API runs in expected context Found in: Component config > LWIP Enable to check that the project does not violate lwip thread safety. If enabled, all lwip functions that require thread awareness run an assertion to verify that the TCP/IP core functionality is either locked or accessed from the correct thread. Default value: No (disabled) CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES Enable mDNS queries in resolving host name Found in: Component config > LWIP If this feature is enabled, standard API such as gethostbyname support .local addresses by sending one shot multicast mDNS query Default value: Yes (enabled) CONFIG_LWIP_L2_TO_L3_COPY Enable copy between Layer2 and Layer3 packets Found in: Component config > LWIP If this feature is enabled, all traffic from layer2(WIFI Driver) will be copied to a new buffer before sending it to layer3(LWIP stack), freeing the layer2 buffer. Please be notified that the total layer2 receiving buffer is fixed and ESP32 currently supports 25 layer2 receiving buffer, when layer2 buffer runs out of memory, then the incoming packets will be dropped in hardware. The layer3 buffer is allocated from the heap, so the total layer3 receiving buffer depends on the available heap size, when heap runs out of memory, no copy will be sent to layer3 and packet will be dropped in layer2. Please make sure you fully understand the impact of this feature before enabling it. Default value: No (disabled) CONFIG_LWIP_IRAM_OPTIMIZATION Enable LWIP IRAM optimization Found in: Component config > LWIP If this feature is enabled, some functions relating to RX/TX in LWIP will be put into IRAM, it can improve UDP/TCP throughput by >10% for single core mode, it doesn't help too much for dual core mode. On the other hand, it needs about 10KB IRAM for these optimizations. If this feature is disabled, all lwip functions will be put into FLASH. Default value: No (disabled) CONFIG_LWIP_EXTRA_IRAM_OPTIMIZATION Enable LWIP IRAM optimization for TCP part Found in: Component config > LWIP If this feature is enabled, some tcp part functions relating to RX/TX in LWIP will be put into IRAM, it can improve TCP throughput. On the other hand, it needs about 17KB IRAM for these optimizations. Default value: No (disabled) CONFIG_LWIP_TIMERS_ONDEMAND Enable LWIP Timers on demand Found in: Component config > LWIP If this feature is enabled, IGMP and MLD6 timers will be activated only when joining groups or receiving QUERY packets. This feature will reduce the power consumption for applications which do not use IGMP and MLD6. Default value: Yes (enabled) CONFIG_LWIP_ND6 LWIP NDP6 Enable/Disable Found in: Component config > LWIP This option is used to disable the Network Discovery Protocol (NDP) if it is not required. Please use this option with caution, as the NDP is essential for IPv6 functionality within a local network. Default value: Yes (enabled) CONFIG_LWIP_FORCE_ROUTER_FORWARDING LWIP Force Router Forwarding Enable/Disable Found in: Component config > LWIP > CONFIG_LWIP_ND6 This option is used to set the the router flag for the NA packets. When enabled, the router flag in NA packet will always set to 1, otherwise, never set router flag for NA packets. Default value: No (disabled) CONFIG_LWIP_MAX_SOCKETS Max number of open sockets Found in: Component config > LWIP Sockets take up a certain amount of memory, and allowing fewer sockets to be open at the same time conserves memory. Specify the maximum amount of sockets here. The valid value is from 1 to 16. Range: from 1 to 16 Default value: 10 CONFIG_LWIP_USE_ONLY_LWIP_SELECT Support LWIP socket select() only (DEPRECATED) Found in: Component config > LWIP This option is deprecated. Do not use this option, use VFS_SUPPORT_SELECT instead. Default value: No (disabled) CONFIG_LWIP_SO_LINGER Enable SO_LINGER processing Found in: Component config > LWIP Enabling this option allows SO_LINGER processing. l_onoff = 1,l_linger can set the timeout. If l_linger=0, When a connection is closed, TCP will terminate the connection. This means that TCP will discard any data packets stored in the socket send buffer and send an RST to the peer. If l_linger!=0,Then closesocket() calls to block the process until the remaining data packets has been sent or timed out. Default value: No (disabled) CONFIG_LWIP_SO_REUSE Enable SO_REUSEADDR option Found in: Component config > LWIP Enabling this option allows binding to a port which remains in TIME_WAIT. Default value: Yes (enabled) CONFIG_LWIP_SO_REUSE_RXTOALL SO_REUSEADDR copies broadcast/multicast to all matches Found in: Component config > LWIP > CONFIG_LWIP_SO_REUSE Enabling this option means that any incoming broadcast or multicast packet will be copied to all of the local sockets that it matches (may be more than one if SO_REUSEADDR is set on the socket.) This increases memory overhead as the packets need to be copied, however they are only copied per matching socket. You can safely disable it if you don't plan to receive broadcast or multicast traffic on more than one socket at a time. Default value: Yes (enabled) CONFIG_LWIP_SO_RCVBUF Enable SO_RCVBUF option Found in: Component config > LWIP Enabling this option allows checking for available data on a netconn. Default value: No (disabled) CONFIG_LWIP_NETBUF_RECVINFO Enable IP_PKTINFO option Found in: Component config > LWIP Enabling this option allows checking for the destination address of a received IPv4 Packet. Default value: No (disabled) CONFIG_LWIP_IP_DEFAULT_TTL The value for Time-To-Live used by transport layers Found in: Component config > LWIP Set value for Time-To-Live used by transport layers. Range: from 1 to 255 Default value: 64 CONFIG_LWIP_IP4_FRAG Enable fragment outgoing IP4 packets Found in: Component config > LWIP Enabling this option allows fragmenting outgoing IP4 packets if their size exceeds MTU. Default value: Yes (enabled) CONFIG_LWIP_IP6_FRAG Enable fragment outgoing IP6 packets Found in: Component config > LWIP Enabling this option allows fragmenting outgoing IP6 packets if their size exceeds MTU. Default value: Yes (enabled) CONFIG_LWIP_IP4_REASSEMBLY Enable reassembly incoming fragmented IP4 packets Found in: Component config > LWIP Enabling this option allows reassemblying incoming fragmented IP4 packets. Default value: No (disabled) CONFIG_LWIP_IP6_REASSEMBLY Enable reassembly incoming fragmented IP6 packets Found in: Component config > LWIP Enabling this option allows reassemblying incoming fragmented IP6 packets. Default value: No (disabled) CONFIG_LWIP_IP_REASS_MAX_PBUFS The maximum amount of pbufs waiting to be reassembled Found in: Component config > LWIP Set the maximum amount of pbufs waiting to be reassembled. Range: from 10 to 100 Default value: 10 CONFIG_LWIP_IP_FORWARD Enable IP forwarding Found in: Component config > LWIP Enabling this option allows packets forwarding across multiple interfaces. Default value: No (disabled) CONFIG_LWIP_IPV4_NAPT Enable NAT (new/experimental) Found in: Component config > LWIP > CONFIG_LWIP_IP_FORWARD Enabling this option allows Network Address and Port Translation. Default value: No (disabled) if CONFIG_LWIP_IP_FORWARD CONFIG_LWIP_IPV4_NAPT_PORTMAP Enable NAT Port Mapping (new/experimental) Found in: Component config > LWIP > CONFIG_LWIP_IP_FORWARD > CONFIG_LWIP_IPV4_NAPT Enabling this option allows Port Forwarding or Port mapping. Default value: Yes (enabled) if CONFIG_LWIP_IPV4_NAPT CONFIG_LWIP_STATS Enable LWIP statistics Found in: Component config > LWIP Enabling this option allows LWIP statistics Default value: No (disabled) CONFIG_LWIP_ESP_GRATUITOUS_ARP Send gratuitous ARP periodically Found in: Component config > LWIP Enable this option allows to send gratuitous ARP periodically. This option solve the compatibility issues.If the ARP table of the AP is old, and the AP doesn't send ARP request to update it's ARP table, this will lead to the STA sending IP packet fail. Thus we send gratuitous ARP periodically to let AP update it's ARP table. Default value: Yes (enabled) CONFIG_LWIP_GARP_TMR_INTERVAL GARP timer interval(seconds) Found in: Component config > LWIP > CONFIG_LWIP_ESP_GRATUITOUS_ARP Set the timer interval for gratuitous ARP. The default value is 60s Default value: 60 CONFIG_LWIP_ESP_MLDV6_REPORT Send mldv6 report periodically Found in: Component config > LWIP Enable this option allows to send mldv6 report periodically. This option solve the issue that failed to receive multicast data. Some routers fail to forward multicast packets. To solve this problem, send multicast mdlv6 report to routers regularly. Default value: Yes (enabled) CONFIG_LWIP_MLDV6_TMR_INTERVAL mldv6 report timer interval(seconds) Found in: Component config > LWIP > CONFIG_LWIP_ESP_MLDV6_REPORT Set the timer interval for mldv6 report. The default value is 30s Default value: 40 CONFIG_LWIP_TCPIP_RECVMBOX_SIZE TCPIP task receive mail box size Found in: Component config > LWIP Set TCPIP task receive mail box size. Generally bigger value means higher throughput but more memory. The value should be bigger than UDP/TCP mail box size. Range: from 6 to 1024 if CONFIG_LWIP_WND_SCALE Default value: 32 CONFIG_LWIP_DHCP_DOES_ARP_CHECK DHCP: Perform ARP check on any offered address Found in: Component config > LWIP Enabling this option performs a check (via ARP request) if the offered IP address is not already in use by another host on the network. Default value: Yes (enabled) CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID DHCP: Disable Use of HW address as client identification Found in: Component config > LWIP This option could be used to disable DHCP client identification with its MAC address. (Client id is used by DHCP servers to uniquely identify clients and are included in the DHCP packets as an option 61) Set this option to "y" in order to exclude option 61 from DHCP packets. Default value: No (disabled) CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID DHCP: Disable Use of vendor class identification Found in: Component config > LWIP This option could be used to disable DHCP client vendor class identification. Set this option to "y" in order to exclude option 60 from DHCP packets. Default value: Yes (enabled) CONFIG_LWIP_DHCP_RESTORE_LAST_IP DHCP: Restore last IP obtained from DHCP server Found in: Component config > LWIP When this option is enabled, DHCP client tries to re-obtain last valid IP address obtained from DHCP server. Last valid DHCP configuration is stored in nvs and restored after reset/power-up. If IP is still available, there is no need for sending discovery message to DHCP server and save some time. Default value: No (disabled) CONFIG_LWIP_DHCP_OPTIONS_LEN DHCP total option length Found in: Component config > LWIP Set total length of outgoing DHCP option msg. Generally bigger value means it can carry more options and values. If your code meets LWIP_ASSERT due to option value is too long. Please increase the LWIP_DHCP_OPTIONS_LEN value. Range: from 68 to 255 Default value: 68 CONFIG_LWIP_NUM_NETIF_CLIENT_DATA Number of clients store data in netif Found in: Component config > LWIP Number of clients that may store data in client_data member array of struct netif. Range: from 0 to 256 Default value: 0 CONFIG_LWIP_DHCP_COARSE_TIMER_SECS DHCP coarse timer interval(s) Found in: Component config > LWIP Set DHCP coarse interval in seconds. A higher value will be less precise but cost less power consumption. Range: from 1 to 10 Default value: 1 DHCP server Contains: CONFIG_LWIP_DHCPS DHCPS: Enable IPv4 Dynamic Host Configuration Protocol Server (DHCPS) Found in: Component config > LWIP > DHCP server Enabling this option allows the device to run the DHCP server (to dynamically assign IPv4 addresses to clients). Default value: Yes (enabled) CONFIG_LWIP_DHCPS_LEASE_UNIT Multiplier for lease time, in seconds Found in: Component config > LWIP > DHCP server > CONFIG_LWIP_DHCPS The DHCP server is calculating lease time multiplying the sent and received times by this number of seconds per unit. The default is 60, that equals one minute. Range: from 1 to 3600 Default value: 60 CONFIG_LWIP_DHCPS_MAX_STATION_NUM Maximum number of stations Found in: Component config > LWIP > DHCP server > CONFIG_LWIP_DHCPS The maximum number of DHCP clients that are connected to the server. After this number is exceeded, DHCP server removes of the oldest device from it's address pool, without notification. Range: from 1 to 64 Default value: 8 CONFIG_LWIP_DHCPS_STATIC_ENTRIES Enable ARP static entries Found in: Component config > LWIP > DHCP server > CONFIG_LWIP_DHCPS Enabling this option allows DHCP server to support temporary static ARP entries for DHCP Client. This will help the DHCP server to send the DHCP OFFER and DHCP ACK using IP unicast. Default value: Yes (enabled) CONFIG_LWIP_AUTOIP Enable IPV4 Link-Local Addressing (AUTOIP) Found in: Component config > LWIP Enabling this option allows the device to self-assign an address in the 169.256/16 range if none is assigned statically or via DHCP. See RFC 3927. Default value: No (disabled) Contains: CONFIG_LWIP_AUTOIP_TRIES DHCP Probes before self-assigning IPv4 LL address Found in: Component config > LWIP > CONFIG_LWIP_AUTOIP DHCP client will send this many probes before self-assigning a link local address. From LWIP help: "This can be set as low as 1 to get an AutoIP address very quickly, but you should be prepared to handle a changing IP address when DHCP overrides AutoIP." (In the case of ESP-IDF, this means multiple SYSTEM_EVENT_STA_GOT_IP events.) Range: from 1 to 100 if CONFIG_LWIP_AUTOIP Default value: 2 if CONFIG_LWIP_AUTOIP CONFIG_LWIP_AUTOIP_MAX_CONFLICTS Max IP conflicts before rate limiting Found in: Component config > LWIP > CONFIG_LWIP_AUTOIP If the AUTOIP functionality detects this many IP conflicts while self-assigning an address, it will go into a rate limited mode. Range: from 1 to 100 if CONFIG_LWIP_AUTOIP Default value: 9 if CONFIG_LWIP_AUTOIP CONFIG_LWIP_AUTOIP_RATE_LIMIT_INTERVAL Rate limited interval (seconds) Found in: Component config > LWIP > CONFIG_LWIP_AUTOIP If rate limiting self-assignment requests, wait this long between each request. Range: from 5 to 120 if CONFIG_LWIP_AUTOIP Default value: 20 if CONFIG_LWIP_AUTOIP CONFIG_LWIP_IPV4 Enable IPv4 Found in: Component config > LWIP Enable IPv4 stack. If you want to use IPv6 only TCP/IP stack, disable this. Default value: Yes (enabled) CONFIG_LWIP_IPV6 Enable IPv6 Found in: Component config > LWIP Enable IPv6 function. If not use IPv6 function, set this option to n. If disabling LWIP_IPV6 then some other components (coap and asio) will no longer be available. Default value: Yes (enabled) CONFIG_LWIP_IPV6_AUTOCONFIG Enable IPV6 stateless address autoconfiguration (SLAAC) Found in: Component config > LWIP > CONFIG_LWIP_IPV6 Enabling this option allows the devices to IPV6 stateless address autoconfiguration (SLAAC). See RFC 4862. Default value: No (disabled) CONFIG_LWIP_IPV6_NUM_ADDRESSES Number of IPv6 addresses on each network interface Found in: Component config > LWIP > CONFIG_LWIP_IPV6 The maximum number of IPv6 addresses on each interface. Any additional addresses will be discarded. Default value: 3 CONFIG_LWIP_IPV6_FORWARD Enable IPv6 forwarding between interfaces Found in: Component config > LWIP > CONFIG_LWIP_IPV6 Forwarding IPv6 packets between interfaces is only required when acting as a router. Default value: No (disabled) CONFIG_LWIP_IPV6_RDNSS_MAX_DNS_SERVERS Use IPv6 Router Advertisement Recursive DNS Server Option Found in: Component config > LWIP Use IPv6 Router Advertisement Recursive DNS Server Option (as per RFC 6106) to copy a defined maximum number of DNS servers to the DNS module. Set this option to a number of desired DNS servers advertised in the RA protocol. This feature is disabled when set to 0. Default value: CONFIG_LWIP_IPV6_DHCP6 Enable DHCPv6 stateless address autoconfiguration Found in: Component config > LWIP Enable DHCPv6 for IPv6 stateless address autoconfiguration. Note that the dhcpv6 client has to be started using dhcp6_enable_stateless(netif); Note that the stateful address autoconfiguration is not supported. Default value: No (disabled) if CONFIG_LWIP_IPV6_AUTOCONFIG CONFIG_LWIP_NETIF_STATUS_CALLBACK Enable status callback for network interfaces Found in: Component config > LWIP Enable callbacks when the network interface is up/down and addresses are changed. Default value: No (disabled) CONFIG_LWIP_NETIF_LOOPBACK Support per-interface loopback Found in: Component config > LWIP Enabling this option means that if a packet is sent with a destination address equal to the interface's own IP address, it will "loop back" and be received by this interface. Disabling this option disables support of loopback interface in lwIP Default value: Yes (enabled) Contains: CONFIG_LWIP_LOOPBACK_MAX_PBUFS Max queued loopback packets per interface Found in: Component config > LWIP > CONFIG_LWIP_NETIF_LOOPBACK Configure the maximum number of packets which can be queued for loopback on a given interface. Reducing this number may cause packets to be dropped, but will avoid filling memory with queued packet data. Range: from 0 to 16 Default value: 8 TCP Contains: CONFIG_LWIP_MAX_ACTIVE_TCP Maximum active TCP Connections Found in: Component config > LWIP > TCP The maximum number of simultaneously active TCP connections. The practical maximum limit is determined by available heap memory at runtime. Changing this value by itself does not substantially change the memory usage of LWIP, except for preventing new TCP connections after the limit is reached. Range: from 1 to 1024 Default value: 16 CONFIG_LWIP_MAX_LISTENING_TCP Maximum listening TCP Connections Found in: Component config > LWIP > TCP The maximum number of simultaneously listening TCP connections. The practical maximum limit is determined by available heap memory at runtime. Changing this value by itself does not substantially change the memory usage of LWIP, except for preventing new listening TCP connections after the limit is reached. Range: from 1 to 1024 Default value: 16 CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION TCP high speed retransmissions Found in: Component config > LWIP > TCP Speed up the TCP retransmission interval. If disabled, it is recommended to change the number of SYN retransmissions to 6, and TCP initial rto time to 3000. Default value: Yes (enabled) CONFIG_LWIP_TCP_MAXRTX Maximum number of retransmissions of data segments Found in: Component config > LWIP > TCP Set maximum number of retransmissions of data segments. Range: from 3 to 12 Default value: 12 CONFIG_LWIP_TCP_SYNMAXRTX Maximum number of retransmissions of SYN segments Found in: Component config > LWIP > TCP Set maximum number of retransmissions of SYN segments. Range: from 3 to 12 Default value: 12 CONFIG_LWIP_TCP_MSS Maximum Segment Size (MSS) Found in: Component config > LWIP > TCP Set maximum segment size for TCP transmission. Can be set lower to save RAM, the default value 1460(ipv4)/1440(ipv6) will give best throughput. IPv4 TCP_MSS Range: 576 <= TCP_MSS <= 1460 IPv6 TCP_MSS Range: 1220<= TCP_MSS <= 1440 Range: from 536 to 1460 Default value: 1440 CONFIG_LWIP_TCP_TMR_INTERVAL TCP timer interval(ms) Found in: Component config > LWIP > TCP Set TCP timer interval in milliseconds. Can be used to speed connections on bad networks. A lower value will redeliver unacked packets faster. Default value: 250 CONFIG_LWIP_TCP_MSL Maximum segment lifetime (MSL) Found in: Component config > LWIP > TCP Set maximum segment lifetime in milliseconds. Default value: 60000 CONFIG_LWIP_TCP_FIN_WAIT_TIMEOUT Maximum FIN segment lifetime Found in: Component config > LWIP > TCP Set maximum segment lifetime in milliseconds. Default value: 20000 CONFIG_LWIP_TCP_SND_BUF_DEFAULT Default send buffer size Found in: Component config > LWIP > TCP Set default send buffer size for new TCP sockets. Per-socket send buffer size can be changed at runtime with lwip_setsockopt(s, TCP_SNDBUF, ...). This value must be at least 2x the MSS size, and the default is 4x the default MSS size. Setting a smaller default SNDBUF size can save some RAM, but will decrease performance. Range: from 2440 to 1024000 if CONFIG_LWIP_WND_SCALE Default value: 5760 CONFIG_LWIP_TCP_WND_DEFAULT Default receive window size Found in: Component config > LWIP > TCP Set default TCP receive window size for new TCP sockets. Per-socket receive window size can be changed at runtime with lwip_setsockopt(s, TCP_WINDOW, ...). Setting a smaller default receive window size can save some RAM, but will significantly decrease performance. Range: from 2440 to 1024000 if CONFIG_LWIP_WND_SCALE Default value: 5760 CONFIG_LWIP_TCP_RECVMBOX_SIZE Default TCP receive mail box size Found in: Component config > LWIP > TCP Set TCP receive mail box size. Generally bigger value means higher throughput but more memory. The recommended value is: LWIP_TCP_WND_DEFAULT/TCP_MSS + 2, e.g. if LWIP_TCP_WND_DEFAULT=14360, TCP_MSS=1436, then the recommended receive mail box size is (14360/1436 + 2) = 12. TCP receive mail box is a per socket mail box, when the application receives packets from TCP socket, LWIP core firstly posts the packets to TCP receive mail box and the application then fetches the packets from mail box. It means LWIP can caches maximum LWIP_TCP_RECCVMBOX_SIZE packets for each TCP socket, so the maximum possible cached TCP packets for all TCP sockets is LWIP_TCP_RECCVMBOX_SIZE multiples the maximum TCP socket number. In other words, the bigger LWIP_TCP_RECVMBOX_SIZE means more memory. On the other hand, if the receiv mail box is too small, the mail box may be full. If the mail box is full, the LWIP drops the packets. So generally we need to make sure the TCP receive mail box is big enough to avoid packet drop between LWIP core and application. Range: from 6 to 1024 if CONFIG_LWIP_WND_SCALE Default value: 6 CONFIG_LWIP_TCP_QUEUE_OOSEQ Queue incoming out-of-order segments Found in: Component config > LWIP > TCP Queue incoming out-of-order segments for later use. Disable this option to save some RAM during TCP sessions, at the expense of increased retransmissions if segments arrive out of order. Default value: Yes (enabled) CONFIG_LWIP_TCP_OOSEQ_TIMEOUT Timeout for each pbuf queued in TCP OOSEQ, in RTOs. Found in: Component config > LWIP > TCP > CONFIG_LWIP_TCP_QUEUE_OOSEQ The timeout value is TCP_OOSEQ_TIMEOUT * RTO. Range: from 1 to 30 Default value: 6 CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS The maximum number of pbufs queued on OOSEQ per pcb Found in: Component config > LWIP > TCP > CONFIG_LWIP_TCP_QUEUE_OOSEQ If LWIP_TCP_OOSEQ_MAX_PBUFS = 0, TCP will not control the number of OOSEQ pbufs. In a poor network environment, many out-of-order tcp pbufs will be received. These out-of-order pbufs will be cached in the TCP out-of-order queue which will cause Wi-Fi/Ethernet fail to release RX buffer in time. It is possible that all RX buffers for MAC layer are used by OOSEQ. Control the number of out-of-order pbufs to ensure that the MAC layer has enough RX buffer to receive packets. In the Wi-Fi scenario, recommended OOSEQ PBUFS Range: 0 <= TCP_OOSEQ_MAX_PBUFS <= CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM/(MAX_TCP_NUMBER + 1) In the Ethernet scenario,recommended Ethernet OOSEQ PBUFS Range: 0 <= TCP_OOSEQ_MAX_PBUFS <= CONFIG_ETH_DMA_RX_BUFFER_NUM/(MAX_TCP_NUMBER + 1) Within the recommended value range, the larger the value, the better the performance. MAX_TCP_NUMBER represent Maximum number of TCP connections in Wi-Fi(STA+SoftAP) and Ethernet scenario. Range: from 0 to 12 Default value: CONFIG_LWIP_TCP_SACK_OUT Support sending selective acknowledgements Found in: Component config > LWIP > TCP > CONFIG_LWIP_TCP_QUEUE_OOSEQ TCP will support sending selective acknowledgements (SACKs). Default value: No (disabled) CONFIG_LWIP_TCP_OVERSIZE Pre-allocate transmit PBUF size Found in: Component config > LWIP > TCP Allows enabling "oversize" allocation of TCP transmission pbufs ahead of time, which can reduce the length of pbuf chains used for transmission. This will not make a difference to sockets where Nagle's algorithm is disabled. Default value of MSS is fine for most applications, 25% MSS may save some RAM when only transmitting small amounts of data. Disabled will have worst performance and fragmentation characteristics, but uses least RAM overall. Available options: MSS (CONFIG_LWIP_TCP_OVERSIZE_MSS) 25% MSS (CONFIG_LWIP_TCP_OVERSIZE_QUARTER_MSS) Disabled (CONFIG_LWIP_TCP_OVERSIZE_DISABLE) CONFIG_LWIP_WND_SCALE Support TCP window scale Found in: Component config > LWIP > TCP Enable this feature to support TCP window scaling. Default value: No (disabled) if CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP CONFIG_LWIP_TCP_RCV_SCALE Set TCP receiving window scaling factor Found in: Component config > LWIP > TCP > CONFIG_LWIP_WND_SCALE Enable this feature to support TCP window scaling. Range: from 0 to 14 if CONFIG_LWIP_WND_SCALE Default value: CONFIG_LWIP_TCP_RTO_TIME Default TCP rto time Found in: Component config > LWIP > TCP Set default TCP rto time for a reasonable initial rto. In bad network environment, recommend set value of rto time to 1500. Default value: 1500 UDP Contains: CONFIG_LWIP_MAX_UDP_PCBS Maximum active UDP control blocks Found in: Component config > LWIP > UDP The maximum number of active UDP "connections" (ie UDP sockets sending/receiving data). The practical maximum limit is determined by available heap memory at runtime. Range: from 1 to 1024 Default value: 16 CONFIG_LWIP_UDP_RECVMBOX_SIZE Default UDP receive mail box size Found in: Component config > LWIP > UDP Set UDP receive mail box size. The recommended value is 6. UDP receive mail box is a per socket mail box, when the application receives packets from UDP socket, LWIP core firstly posts the packets to UDP receive mail box and the application then fetches the packets from mail box. It means LWIP can caches maximum UDP_RECCVMBOX_SIZE packets for each UDP socket, so the maximum possible cached UDP packets for all UDP sockets is UDP_RECCVMBOX_SIZE multiples the maximum UDP socket number. In other words, the bigger UDP_RECVMBOX_SIZE means more memory. On the other hand, if the receiv mail box is too small, the mail box may be full. If the mail box is full, the LWIP drops the packets. So generally we need to make sure the UDP receive mail box is big enough to avoid packet drop between LWIP core and application. Range: from 6 to 64 Default value: 6 Checksums Contains: CONFIG_LWIP_CHECKSUM_CHECK_IP Enable LWIP IP checksums Found in: Component config > LWIP > Checksums Enable checksum checking for received IP messages Default value: No (disabled) CONFIG_LWIP_CHECKSUM_CHECK_UDP Enable LWIP UDP checksums Found in: Component config > LWIP > Checksums Enable checksum checking for received UDP messages Default value: No (disabled) CONFIG_LWIP_CHECKSUM_CHECK_ICMP Enable LWIP ICMP checksums Found in: Component config > LWIP > Checksums Enable checksum checking for received ICMP messages Default value: Yes (enabled) CONFIG_LWIP_TCPIP_TASK_STACK_SIZE TCP/IP Task Stack Size Found in: Component config > LWIP Configure TCP/IP task stack size, used by LWIP to process multi-threaded TCP/IP operations. Setting this stack too small will result in stack overflow crashes. Range: from 2048 to 65536 Default value: 3072 CONFIG_LWIP_TCPIP_TASK_AFFINITY TCP/IP task affinity Found in: Component config > LWIP Allows setting LwIP tasks affinity, i.e. whether the task is pinned to CPU0, pinned to CPU1, or allowed to run on any CPU. Currently this applies to "TCP/IP" task and "Ping" task. Available options: No affinity (CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY) CPU0 (CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0) CPU1 (CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU1) CONFIG_LWIP_PPP_SUPPORT Enable PPP support Found in: Component config > LWIP Enable PPP stack. Now only PPP over serial is possible. Default value: No (disabled) Contains: CONFIG_LWIP_PPP_ENABLE_IPV6 Enable IPV6 support for PPP connections (IPV6CP) Found in: Component config > LWIP > CONFIG_LWIP_PPP_SUPPORT Enable IPV6 support in PPP for the local link between the DTE (processor) and DCE (modem). There are some modems which do not support the IPV6 addressing in the local link. If they are requested for IPV6CP negotiation, they may time out. This would in turn fail the configuration for the whole link. If your modem is not responding correctly to PPP Phase Network, try to disable IPV6 support. Default value: Yes (enabled) if CONFIG_LWIP_PPP_SUPPORT && CONFIG_LWIP_IPV6 CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE Max number of IPv6 packets to queue during MAC resolution Found in: Component config > LWIP Config max number of IPv6 packets to queue during MAC resolution. Range: from 3 to 20 Default value: 3 CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS Max number of entries in IPv6 neighbor cache Found in: Component config > LWIP Config max number of entries in IPv6 neighbor cache Range: from 3 to 10 Default value: 5 CONFIG_LWIP_PPP_NOTIFY_PHASE_SUPPORT Enable Notify Phase Callback Found in: Component config > LWIP Enable to set a callback which is called on change of the internal PPP state machine. Default value: No (disabled) if CONFIG_LWIP_PPP_SUPPORT CONFIG_LWIP_PPP_PAP_SUPPORT Enable PAP support Found in: Component config > LWIP Enable Password Authentication Protocol (PAP) support Default value: No (disabled) if CONFIG_LWIP_PPP_SUPPORT CONFIG_LWIP_PPP_CHAP_SUPPORT Enable CHAP support Found in: Component config > LWIP Enable Challenge Handshake Authentication Protocol (CHAP) support Default value: No (disabled) if CONFIG_LWIP_PPP_SUPPORT CONFIG_LWIP_PPP_MSCHAP_SUPPORT Enable MSCHAP support Found in: Component config > LWIP Enable Microsoft version of the Challenge-Handshake Authentication Protocol (MSCHAP) support Default value: No (disabled) if CONFIG_LWIP_PPP_SUPPORT CONFIG_LWIP_PPP_MPPE_SUPPORT Enable MPPE support Found in: Component config > LWIP Enable Microsoft Point-to-Point Encryption (MPPE) support Default value: No (disabled) if CONFIG_LWIP_PPP_SUPPORT CONFIG_LWIP_ENABLE_LCP_ECHO Enable LCP ECHO Found in: Component config > LWIP Enable LCP echo keepalive requests Default value: No (disabled) if CONFIG_LWIP_PPP_SUPPORT CONFIG_LWIP_LCP_ECHOINTERVAL Echo interval (s) Found in: Component config > LWIP > CONFIG_LWIP_ENABLE_LCP_ECHO Interval in seconds between keepalive LCP echo requests, 0 to disable. Range: from 0 to 1000000 if CONFIG_LWIP_ENABLE_LCP_ECHO Default value: CONFIG_LWIP_LCP_MAXECHOFAILS Maximum echo failures Found in: Component config > LWIP > CONFIG_LWIP_ENABLE_LCP_ECHO Number of consecutive unanswered echo requests before failure is indicated. Range: from 0 to 100000 if CONFIG_LWIP_ENABLE_LCP_ECHO Default value: CONFIG_LWIP_PPP_DEBUG_ON Enable PPP debug log output Found in: Component config > LWIP Enable PPP debug log output Default value: No (disabled) if CONFIG_LWIP_PPP_SUPPORT CONFIG_LWIP_SLIP_SUPPORT Enable SLIP support (new/experimental) Found in: Component config > LWIP Enable SLIP stack. Now only SLIP over serial is possible. SLIP over serial support is experimental and unsupported. Default value: No (disabled) Contains: CONFIG_LWIP_SLIP_DEBUG_ON Enable SLIP debug log output Found in: Component config > LWIP > CONFIG_LWIP_SLIP_SUPPORT Enable SLIP debug log output Default value: No (disabled) if CONFIG_LWIP_SLIP_SUPPORT ICMP Contains: CONFIG_LWIP_ICMP ICMP: Enable ICMP Found in: Component config > LWIP > ICMP Enable ICMP module for check network stability Default value: Yes (enabled) CONFIG_LWIP_MULTICAST_PING Respond to multicast pings Found in: Component config > LWIP > ICMP Default value: No (disabled) CONFIG_LWIP_BROADCAST_PING Respond to broadcast pings Found in: Component config > LWIP > ICMP Default value: No (disabled) LWIP RAW API Contains: CONFIG_LWIP_MAX_RAW_PCBS Maximum LWIP RAW PCBs Found in: Component config > LWIP > LWIP RAW API The maximum number of simultaneously active LWIP RAW protocol control blocks. The practical maximum limit is determined by available heap memory at runtime. Range: from 1 to 1024 Default value: 16 SNTP Contains: CONFIG_LWIP_SNTP_MAX_SERVERS Maximum number of NTP servers Found in: Component config > LWIP > SNTP Set maximum number of NTP servers used by LwIP SNTP module. First argument of sntp_setserver/sntp_setservername functions is limited to this value. Range: from 1 to 16 Default value: 1 CONFIG_LWIP_DHCP_GET_NTP_SRV Request NTP servers from DHCP Found in: Component config > LWIP > SNTP If enabled, LWIP will add 'NTP' to Parameter-Request Option sent via DHCP-request. DHCP server might reply with an NTP server address in option 42. SNTP callback for such replies should be set accordingly (see sntp_servermode_dhcp() func.) Default value: No (disabled) CONFIG_LWIP_DHCP_MAX_NTP_SERVERS Maximum number of NTP servers aquired via DHCP Found in: Component config > LWIP > SNTP > CONFIG_LWIP_DHCP_GET_NTP_SRV Set maximum number of NTP servers aquired via DHCP-offer. Should be less or equal to "Maximum number of NTP servers", any extra servers would be just ignored. Range: from 1 to 16 if CONFIG_LWIP_DHCP_GET_NTP_SRV Default value: CONFIG_LWIP_SNTP_UPDATE_DELAY Request interval to update time (ms) Found in: Component config > LWIP > SNTP This option allows you to set the time update period via SNTP. Default is 1 hour. Must not be below 15 seconds by specification. (SNTPv4 RFC 4330 enforces a minimum update time of 15 seconds). Range: from 15000 to 4294967295 Default value: 3600000 DNS Contains: CONFIG_LWIP_DNS_MAX_SERVERS Maximum number of DNS servers Found in: Component config > LWIP > DNS Set maximum number of DNS servers. If fallback DNS servers are supported, the number of DNS servers needs to be greater than or equal to 3. Range: from 1 to 4 Default value: 3 CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT Enable DNS fallback server support Found in: Component config > LWIP > DNS Enable this feature to support DNS fallback server. Default value: No (disabled) CONFIG_LWIP_FALLBACK_DNS_SERVER_ADDRESS DNS fallback server address Found in: Component config > LWIP > DNS > CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT This option allows you to config dns fallback server address. Default value: "114.114.114.114" if CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT CONFIG_LWIP_BRIDGEIF_MAX_PORTS Maximum number of bridge ports Found in: Component config > LWIP Set maximum number of ports a bridge can consists of. Range: from 1 to 63 Default value: 7 CONFIG_LWIP_ESP_LWIP_ASSERT Enable LWIP ASSERT checks Found in: Component config > LWIP Enable this option keeps LWIP assertion checks enabled. It is recommended to keep this option enabled. If asserts are disabled for the entire project, they are also disabled for LWIP and this option is ignored. Hooks Contains: CONFIG_LWIP_HOOK_TCP_ISN TCP ISN Hook Found in: Component config > LWIP > Hooks Enables to define a TCP ISN hook to randomize initial sequence number in TCP connection. The default TCP ISN algorithm used in IDF (standardized in RFC 6528) produces ISN by combining an MD5 of the new TCP id and a stable secret with the current time. This is because the lwIP implementation (tcp_next_iss) is not very strong, as it does not take into consideration any platform specific entropy source. Set to LWIP_HOOK_TCP_ISN_CUSTOM to provide custom implementation. Set to LWIP_HOOK_TCP_ISN_NONE to use lwIP implementation. Available options: No hook declared (CONFIG_LWIP_HOOK_TCP_ISN_NONE) Default implementation (CONFIG_LWIP_HOOK_TCP_ISN_DEFAULT) Custom implementation (CONFIG_LWIP_HOOK_TCP_ISN_CUSTOM) CONFIG_LWIP_HOOK_IP6_ROUTE IPv6 route Hook Found in: Component config > LWIP > Hooks Enables custom IPv6 route hook. Setting this to "default" provides weak implementation stub that could be overwritten in application code. Setting this to "custom" provides hook's declaration only and expects the application to implement it. Available options: No hook declared (CONFIG_LWIP_HOOK_IP6_ROUTE_NONE) Default (weak) implementation (CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT) Custom implementation (CONFIG_LWIP_HOOK_IP6_ROUTE_CUSTOM) CONFIG_LWIP_HOOK_ND6_GET_GW IPv6 get gateway Hook Found in: Component config > LWIP > Hooks Enables custom IPv6 route hook. Setting this to "default" provides weak implementation stub that could be overwritten in application code. Setting this to "custom" provides hook's declaration only and expects the application to implement it. Available options: No hook declared (CONFIG_LWIP_HOOK_ND6_GET_GW_NONE) Default (weak) implementation (CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT) Custom implementation (CONFIG_LWIP_HOOK_ND6_GET_GW_CUSTOM) CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR IPv6 source address selection Hook Found in: Component config > LWIP > Hooks Enables custom IPv6 source address selection. Setting this to "default" provides weak implementation stub that could be overwritten in application code. Setting this to "custom" provides hook's declaration only and expects the application to implement it. Available options: No hook declared (CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE) Default (weak) implementation (CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_DEFAULT) Custom implementation (CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_CUSTOM) CONFIG_LWIP_HOOK_NETCONN_EXTERNAL_RESOLVE Netconn external resolve Hook Found in: Component config > LWIP > Hooks Enables custom DNS resolve hook. Setting this to "default" provides weak implementation stub that could be overwritten in application code. Setting this to "custom" provides hook's declaration only and expects the application to implement it. Available options: No hook declared (CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE) Default (weak) implementation (CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_DEFAULT) Custom implementation (CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM) CONFIG_LWIP_HOOK_IP6_INPUT IPv6 packet input Found in: Component config > LWIP > Hooks Enables custom IPv6 packet input. Setting this to "default" provides weak implementation stub that could be overwritten in application code. Setting this to "custom" provides hook's declaration only and expects the application to implement it. Available options: No hook declared (CONFIG_LWIP_HOOK_IP6_INPUT_NONE) Default (weak) implementation (CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT) Custom implementation (CONFIG_LWIP_HOOK_IP6_INPUT_CUSTOM) CONFIG_LWIP_DEBUG Enable LWIP Debug Found in: Component config > LWIP Enabling this option allows different kinds of lwIP debug output. All lwIP debug features increase the size of the final binary. Default value: No (disabled) Contains: CONFIG_LWIP_DEBUG_ESP_LOG Route LWIP debugs through ESP_LOG interface Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Enabling this option routes all enabled LWIP debugs through ESP_LOGD. Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_NETIF_DEBUG Enable netif debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_PBUF_DEBUG Enable pbuf debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_ETHARP_DEBUG Enable etharp debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_API_LIB_DEBUG Enable api lib debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_SOCKETS_DEBUG Enable socket debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_IP_DEBUG Enable IP debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_ICMP_DEBUG Enable ICMP debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG && CONFIG_LWIP_ICMP CONFIG_LWIP_DHCP_STATE_DEBUG Enable DHCP state tracking Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_DHCP_DEBUG Enable DHCP debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_IP6_DEBUG Enable IP6 debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_ICMP6_DEBUG Enable ICMP6 debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_TCP_DEBUG Enable TCP debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_UDP_DEBUG Enable UDP debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_SNTP_DEBUG Enable SNTP debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_DNS_DEBUG Enable DNS debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_NAPT_DEBUG Enable NAPT debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG && CONFIG_LWIP_IPV4_NAPT CONFIG_LWIP_BRIDGEIF_DEBUG Enable bridge generic debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_BRIDGEIF_FDB_DEBUG Enable bridge FDB debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_BRIDGEIF_FW_DEBUG Enable bridge forwarding debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Default value: No (disabled) if CONFIG_LWIP_DEBUG mbedTLS Contains: CONFIG_MBEDTLS_MEM_ALLOC_MODE Memory allocation strategy Found in: Component config > mbedTLS Allocation strategy for mbedTLS, essentially provides ability to allocate all required dynamic allocations from, Internal DRAM memory only External SPIRAM memory only Either internal or external memory based on default malloc() behavior in ESP-IDF Custom allocation mode, by overwriting calloc()/free() using mbedtls_platform_set_calloc_free() function Internal IRAM memory wherever applicable else internal DRAM Recommended mode here is always internal (*), since that is most preferred from security perspective. But if application requirement does not allow sufficient free internal memory then alternate mode can be selected. (*) In case of ESP32-S2/ESP32-S3, hardware allows encryption of external SPIRAM contents provided hardware flash encryption feature is enabled. In that case, using external SPIRAM allocation strategy is also safe choice from security perspective. Available options: Internal memory (CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC) External SPIRAM (CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC) Default alloc mode (CONFIG_MBEDTLS_DEFAULT_MEM_ALLOC) Custom alloc mode (CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC) Internal IRAM (CONFIG_MBEDTLS_IRAM_8BIT_MEM_ALLOC) Allows to use IRAM memory region as 8bit accessible region. TLS input and output buffers will be allocated in IRAM section which is 32bit aligned memory. Every unaligned (8bit or 16bit) access will result in an exception and incur penalty of certain clock cycles per unaligned read/write. CONFIG_MBEDTLS_SSL_MAX_CONTENT_LEN TLS maximum message content length Found in: Component config > mbedTLS Maximum TLS message length (in bytes) supported by mbedTLS. 16384 is the default and this value is required to comply fully with TLS standards. However you can set a lower value in order to save RAM. This is safe if the other end of the connection supports Maximum Fragment Length Negotiation Extension (max_fragment_length, see RFC6066) or you know for certain that it will never send a message longer than a certain number of bytes. If the value is set too low, symptoms are a failed TLS handshake or a return value of MBEDTLS_ERR_SSL_INVALID_RECORD (-0x7200). CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN Asymmetric in/out fragment length Found in: Component config > mbedTLS If enabled, this option allows customizing TLS in/out fragment length in asymmetric way. Please note that enabling this with default values saves 12KB of dynamic memory per TLS connection. Default value: Yes (enabled) CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN TLS maximum incoming fragment length Found in: Component config > mbedTLS > CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN This defines maximum incoming fragment length, overriding default maximum content length (MBEDTLS_SSL_MAX_CONTENT_LEN). Range: from 512 to 16384 Default value: 16384 CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN TLS maximum outgoing fragment length Found in: Component config > mbedTLS > CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN This defines maximum outgoing fragment length, overriding default maximum content length (MBEDTLS_SSL_MAX_CONTENT_LEN). Range: from 512 to 16384 Default value: 4096 CONFIG_MBEDTLS_DYNAMIC_BUFFER Using dynamic TX/RX buffer Found in: Component config > mbedTLS Using dynamic TX/RX buffer. After enabling this option, mbedTLS will allocate TX buffer when need to send data and then free it if all data is sent, allocate RX buffer when need to receive data and then free it when all data is used or read by upper layer. By default, when SSL is initialized, mbedTLS also allocate TX and RX buffer with the default value of "MBEDTLS_SSL_OUT_CONTENT_LEN" or "MBEDTLS_SSL_IN_CONTENT_LEN", so to save more heap, users can set the options to be an appropriate value. CONFIG_MBEDTLS_DYNAMIC_FREE_CONFIG_DATA Free private key and DHM data after its usage Found in: Component config > mbedTLS > CONFIG_MBEDTLS_DYNAMIC_BUFFER Free private key and DHM data after its usage in handshake process. The option will decrease heap cost when handshake, but also lead to problem: Becasue all certificate, private key and DHM data are freed so users should register certificate and private key to ssl config object again. Default value: No (disabled) if CONFIG_MBEDTLS_DYNAMIC_BUFFER CONFIG_MBEDTLS_DYNAMIC_FREE_CA_CERT Free SSL CA certificate after its usage Found in: Component config > mbedTLS > CONFIG_MBEDTLS_DYNAMIC_BUFFER > CONFIG_MBEDTLS_DYNAMIC_FREE_CONFIG_DATA Free CA certificate after its usage in the handshake process. This option will decrease the heap footprint for the TLS handshake, but may lead to a problem: If the respective ssl object needs to perform the TLS handshake again, the CA certificate should once again be registered to the ssl object. Default value: Yes (enabled) if CONFIG_MBEDTLS_DYNAMIC_FREE_CONFIG_DATA CONFIG_MBEDTLS_DEBUG Enable mbedTLS debugging Found in: Component config > mbedTLS Enable mbedTLS debugging functions at compile time. If this option is enabled, you can include "mbedtls/esp_debug.h" and call mbedtls_esp_enable_debug_log() at runtime in order to enable mbedTLS debug output via the ESP log mechanism. Default value: No (disabled) CONFIG_MBEDTLS_DEBUG_LEVEL Set mbedTLS debugging level Found in: Component config > mbedTLS > CONFIG_MBEDTLS_DEBUG Set mbedTLS debugging level Available options: Warning (CONFIG_MBEDTLS_DEBUG_LEVEL_WARN) Info (CONFIG_MBEDTLS_DEBUG_LEVEL_INFO) Debug (CONFIG_MBEDTLS_DEBUG_LEVEL_DEBUG) Verbose (CONFIG_MBEDTLS_DEBUG_LEVEL_VERBOSE) Certificate Bundle Contains: CONFIG_MBEDTLS_CERTIFICATE_BUNDLE Enable trusted root certificate bundle Found in: Component config > mbedTLS > Certificate Bundle Enable support for large number of default root certificates When enabled this option allows user to store default as well as customer specific root certificates in compressed format rather than storing full certificate. For the root certificates the public key and the subject name will be stored. Default value: Yes (enabled) CONFIG_MBEDTLS_DEFAULT_CERTIFICATE_BUNDLE Default certificate bundle options Found in: Component config > mbedTLS > Certificate Bundle > CONFIG_MBEDTLS_CERTIFICATE_BUNDLE Available options: Use the full default certificate bundle (CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL) Use only the most common certificates from the default bundles (CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN) Use only the most common certificates from the default bundles, reducing the size with 50%, while still having around 99% coverage. Do not use the default certificate bundle (CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE) CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE Add custom certificates to the default bundle Found in: Component config > mbedTLS > Certificate Bundle > CONFIG_MBEDTLS_CERTIFICATE_BUNDLE Default value: No (disabled) CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE_PATH Custom certificate bundle path Found in: Component config > mbedTLS > Certificate Bundle > CONFIG_MBEDTLS_CERTIFICATE_BUNDLE > CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE Name of the custom certificate directory or file. This path is evaluated relative to the project root directory. CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS Maximum no of certificates allowed in certificate bundle Found in: Component config > mbedTLS > Certificate Bundle > CONFIG_MBEDTLS_CERTIFICATE_BUNDLE Default value: 200 CONFIG_MBEDTLS_ECP_RESTARTABLE Enable mbedTLS ecp restartable Found in: Component config > mbedTLS Enable "non-blocking" ECC operations that can return early and be resumed. Default value: No (disabled) CONFIG_MBEDTLS_CMAC_C Enable CMAC mode for block ciphers Found in: Component config > mbedTLS Enable the CMAC (Cipher-based Message Authentication Code) mode for block ciphers. Default value: No (disabled) CONFIG_MBEDTLS_HARDWARE_AES Enable hardware AES acceleration Found in: Component config > mbedTLS Enable hardware accelerated AES encryption & decryption. Note that if the ESP32 CPU is running at 240MHz, hardware AES does not offer any speed boost over software AES. CONFIG_MBEDTLS_HARDWARE_GCM Enable partially hardware accelerated GCM Found in: Component config > mbedTLS > CONFIG_MBEDTLS_HARDWARE_AES Enable partially hardware accelerated GCM. GHASH calculation is still done in software. If MBEDTLS_HARDWARE_GCM is disabled and MBEDTLS_HARDWARE_AES is enabled then mbedTLS will still use the hardware accelerated AES block operation, but on a single block at a time. Default value: Yes (enabled) if SOC_AES_SUPPORT_GCM && CONFIG_MBEDTLS_HARDWARE_AES CONFIG_MBEDTLS_HARDWARE_MPI Enable hardware MPI (bignum) acceleration Found in: Component config > mbedTLS Enable hardware accelerated multiple precision integer operations. Hardware accelerated multiplication, modulo multiplication, and modular exponentiation for up to SOC_RSA_MAX_BIT_LEN bit results. These operations are used by RSA. CONFIG_MBEDTLS_HARDWARE_SHA Enable hardware SHA acceleration Found in: Component config > mbedTLS Enable hardware accelerated SHA1, SHA256, SHA384 & SHA512 in mbedTLS. Due to a hardware limitation, on the ESP32 hardware acceleration is only guaranteed if SHA digests are calculated one at a time. If more than one SHA digest is calculated at the same time, one will be calculated fully in hardware and the rest will be calculated (at least partially calculated) in software. This happens automatically. SHA hardware acceleration is faster than software in some situations but slower in others. You should benchmark to find the best setting for you. CONFIG_MBEDTLS_HARDWARE_ECC Enable hardware ECC acceleration Found in: Component config > mbedTLS Enable hardware accelerated ECC point multiplication and point verification for points on curve SECP192R1 and SECP256R1 in mbedTLS Default value: Yes (enabled) if SOC_ECC_SUPPORTED CONFIG_MBEDTLS_ECC_OTHER_CURVES_SOFT_FALLBACK Fallback to software implementation for curves not supported in hardware Found in: Component config > mbedTLS > CONFIG_MBEDTLS_HARDWARE_ECC Fallback to software implementation of ECC point multiplication and point verification for curves not supported in hardware. Default value: Yes (enabled) if CONFIG_MBEDTLS_HARDWARE_ECC CONFIG_MBEDTLS_ROM_MD5 Use MD5 implementation in ROM Found in: Component config > mbedTLS Use ROM MD5 in mbedTLS. Default value: Yes (enabled) CONFIG_MBEDTLS_HARDWARE_ECDSA_SIGN Enable ECDSA signing using on-chip ECDSA peripheral Found in: Component config > mbedTLS Enable hardware accelerated ECDSA peripheral to sign data on curve SECP192R1 and SECP256R1 in mbedTLS. Note that for signing, the private key has to be burnt in an efuse key block with key purpose set to ECDSA_KEY. If no key is burnt, it will report an error The key should be burnt in little endian format. espefuse.py utility handles it internally but care needs to be taken while burning using esp_efuse APIs Default value: No (disabled) if SOC_ECDSA_SUPPORTED CONFIG_MBEDTLS_HARDWARE_ECDSA_VERIFY Enable ECDSA signature verification using on-chip ECDSA peripheral Found in: Component config > mbedTLS Enable hardware accelerated ECDSA peripheral to verify signature on curve SECP192R1 and SECP256R1 in mbedTLS. Default value: Yes (enabled) if SOC_ECDSA_SUPPORTED CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN Enable hardware ECDSA sign acceleration when using ATECC608A Found in: Component config > mbedTLS This option enables hardware acceleration for ECDSA sign function, only when using ATECC608A cryptoauth chip (integrated with ESP32-WROOM-32SE) Default value: No (disabled) CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY Enable hardware ECDSA verify acceleration when using ATECC608A Found in: Component config > mbedTLS This option enables hardware acceleration for ECDSA sign function, only when using ATECC608A cryptoauth chip (integrated with ESP32-WROOM-32SE) Default value: No (disabled) CONFIG_MBEDTLS_HAVE_TIME Enable mbedtls time support Found in: Component config > mbedTLS Enable use of time.h functions (time() and gmtime()) by mbedTLS. This option doesn't require the system time to be correct, but enables functionality that requires relative timekeeping - for example periodic expiry of TLS session tickets or session cache entries. Disabling this option will save some firmware size, particularly if the rest of the firmware doesn't call any standard timekeeeping functions. Default value: Yes (enabled) CONFIG_MBEDTLS_PLATFORM_TIME_ALT Enable mbedtls time support: platform-specific Found in: Component config > mbedTLS > CONFIG_MBEDTLS_HAVE_TIME Enabling this config will provide users with a function "mbedtls_platform_set_time()" that allows to set an alternative time function pointer. Default value: No (disabled) CONFIG_MBEDTLS_HAVE_TIME_DATE Enable mbedtls certificate expiry check Found in: Component config > mbedTLS > CONFIG_MBEDTLS_HAVE_TIME Enables X.509 certificate expiry checks in mbedTLS. If this option is disabled (default) then X.509 certificate "valid from" and "valid to" timestamp fields are ignored. If this option is enabled, these fields are compared with the current system date and time. The time is retrieved using the standard time() and gmtime() functions. If the certificate is not valid for the current system time then verification will fail with code MBEDTLS_X509_BADCERT_FUTURE or MBEDTLS_X509_BADCERT_EXPIRED. Enabling this option requires adding functionality in the firmware to set the system clock to a valid timestamp before using TLS. The recommended way to do this is via ESP-IDF's SNTP functionality, but any method can be used. In the case where only a small number of certificates are trusted by the device, please carefully consider the tradeoffs of enabling this option. There may be undesired consequences, for example if all trusted certificates expire while the device is offline and a TLS connection is required to update. Or if an issue with the SNTP server means that the system time is invalid for an extended period after a reset. Default value: No (disabled) CONFIG_MBEDTLS_ECDSA_DETERMINISTIC Enable deterministic ECDSA Found in: Component config > mbedTLS Standard ECDSA is "fragile" in the sense that lack of entropy when signing may result in a compromise of the long-term signing key. Default value: Yes (enabled) CONFIG_MBEDTLS_SHA512_C Enable the SHA-384 and SHA-512 cryptographic hash algorithms Found in: Component config > mbedTLS Enable MBEDTLS_SHA512_C adds support for SHA-384 and SHA-512. Default value: Yes (enabled) CONFIG_MBEDTLS_TLS_MODE TLS Protocol Role Found in: Component config > mbedTLS mbedTLS can be compiled with protocol support for the TLS server, TLS client, or both server and client. Reducing the number of TLS roles supported saves code size. Available options: Server & Client (CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT) Server (CONFIG_MBEDTLS_TLS_SERVER_ONLY) Client (CONFIG_MBEDTLS_TLS_CLIENT_ONLY) None (CONFIG_MBEDTLS_TLS_DISABLED) TLS Key Exchange Methods Contains: CONFIG_MBEDTLS_PSK_MODES Enable pre-shared-key ciphersuites Found in: Component config > mbedTLS > TLS Key Exchange Methods Enable to show configuration for different types of pre-shared-key TLS authentatication methods. Leaving this options disabled will save code size if they are not used. Default value: No (disabled) CONFIG_MBEDTLS_KEY_EXCHANGE_PSK Enable PSK based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_PSK_MODES Enable to support symmetric key PSK (pre-shared-key) TLS key exchange modes. Default value: No (disabled) if CONFIG_MBEDTLS_PSK_MODES CONFIG_MBEDTLS_KEY_EXCHANGE_DHE_PSK Enable DHE-PSK based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_PSK_MODES Enable to support Diffie-Hellman PSK (pre-shared-key) TLS authentication modes. Default value: Yes (enabled) if CONFIG_MBEDTLS_PSK_MODES && CONFIG_MBEDTLS_DHM_C CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_PSK Enable ECDHE-PSK based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_PSK_MODES Enable to support Elliptic-Curve-Diffie-Hellman PSK (pre-shared-key) TLS authentication modes. Default value: Yes (enabled) if CONFIG_MBEDTLS_PSK_MODES && CONFIG_MBEDTLS_ECDH_C CONFIG_MBEDTLS_KEY_EXCHANGE_RSA_PSK Enable RSA-PSK based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_PSK_MODES Enable to support RSA PSK (pre-shared-key) TLS authentication modes. Default value: Yes (enabled) if CONFIG_MBEDTLS_PSK_MODES CONFIG_MBEDTLS_KEY_EXCHANGE_RSA Enable RSA-only based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods Enable to support ciphersuites with prefix TLS-RSA-WITH- Default value: Yes (enabled) CONFIG_MBEDTLS_KEY_EXCHANGE_DHE_RSA Enable DHE-RSA based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods Enable to support ciphersuites with prefix TLS-DHE-RSA-WITH- Default value: Yes (enabled) if CONFIG_MBEDTLS_DHM_C CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE Support Elliptic Curve based ciphersuites Found in: Component config > mbedTLS > TLS Key Exchange Methods Enable to show Elliptic Curve based ciphersuite mode options. Disabling all Elliptic Curve ciphersuites saves code size and can give slightly faster TLS handshakes, provided the server supports RSA-only ciphersuite modes. Default value: Yes (enabled) CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA Enable ECDHE-RSA based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE Enable to support ciphersuites with prefix TLS-ECDHE-RSA-WITH- Default value: Yes (enabled) CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA Enable ECDHE-ECDSA based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE Enable to support ciphersuites with prefix TLS-ECDHE-RSA-WITH- Default value: Yes (enabled) CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA Enable ECDH-ECDSA based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE Enable to support ciphersuites with prefix TLS-ECDHE-RSA-WITH- Default value: Yes (enabled) CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA Enable ECDH-RSA based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE Enable to support ciphersuites with prefix TLS-ECDHE-RSA-WITH- Default value: Yes (enabled) CONFIG_MBEDTLS_KEY_EXCHANGE_ECJPAKE Enable ECJPAKE based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods Enable to support ciphersuites with prefix TLS-ECJPAKE-WITH- Default value: No (disabled) if CONFIG_MBEDTLS_ECJPAKE_C && CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED CONFIG_MBEDTLS_SSL_RENEGOTIATION Support TLS renegotiation Found in: Component config > mbedTLS The two main uses of renegotiation are (1) refresh keys on long-lived connections and (2) client authentication after the initial handshake. If you don't need renegotiation, disabling it will save code size and reduce the possibility of abuse/vulnerability. Default value: Yes (enabled) CONFIG_MBEDTLS_SSL_PROTO_TLS1_2 Support TLS 1.2 protocol Found in: Component config > mbedTLS Default value: Yes (enabled) CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 Support GM/T SSL 1.1 protocol Found in: Component config > mbedTLS Provisions for GM/T SSL 1.1 support Default value: No (disabled) CONFIG_MBEDTLS_SSL_PROTO_DTLS Support DTLS protocol (all versions) Found in: Component config > mbedTLS Requires TLS 1.2 to be enabled for DTLS 1.2 Default value: No (disabled) CONFIG_MBEDTLS_SSL_ALPN Support ALPN (Application Layer Protocol Negotiation) Found in: Component config > mbedTLS Disabling this option will save some code size if it is not needed. Default value: Yes (enabled) CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS TLS: Client Support for RFC 5077 SSL session tickets Found in: Component config > mbedTLS Client support for RFC 5077 session tickets. See mbedTLS documentation for more details. Disabling this option will save some code size. Default value: Yes (enabled) CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS TLS: Server Support for RFC 5077 SSL session tickets Found in: Component config > mbedTLS Server support for RFC 5077 session tickets. See mbedTLS documentation for more details. Disabling this option will save some code size. Default value: Yes (enabled) Symmetric Ciphers Contains: CONFIG_MBEDTLS_AES_C AES block cipher Found in: Component config > mbedTLS > Symmetric Ciphers Default value: Yes (enabled) CONFIG_MBEDTLS_CAMELLIA_C Camellia block cipher Found in: Component config > mbedTLS > Symmetric Ciphers Default value: No (disabled) CONFIG_MBEDTLS_DES_C DES block cipher (legacy, insecure) Found in: Component config > mbedTLS > Symmetric Ciphers Enables the DES block cipher to support 3DES-based TLS ciphersuites. 3DES is vulnerable to the Sweet32 attack and should only be enabled if absolutely necessary. Default value: No (disabled) CONFIG_MBEDTLS_BLOWFISH_C Blowfish block cipher (read help) Found in: Component config > mbedTLS > Symmetric Ciphers Enables the Blowfish block cipher (not used for TLS sessions.) The Blowfish cipher is not used for mbedTLS TLS sessions but can be used for other purposes. Read up on the limitations of Blowfish (including Sweet32) before enabling. Default value: No (disabled) CONFIG_MBEDTLS_XTEA_C XTEA block cipher Found in: Component config > mbedTLS > Symmetric Ciphers Enables the XTEA block cipher. Default value: No (disabled) CONFIG_MBEDTLS_CCM_C CCM (Counter with CBC-MAC) block cipher modes Found in: Component config > mbedTLS > Symmetric Ciphers Enable Counter with CBC-MAC (CCM) modes for AES and/or Camellia ciphers. Disabling this option saves some code size. Default value: Yes (enabled) CONFIG_MBEDTLS_GCM_C GCM (Galois/Counter) block cipher modes Found in: Component config > mbedTLS > Symmetric Ciphers Enable Galois/Counter Mode for AES and/or Camellia ciphers. This option is generally faster than CCM. Default value: Yes (enabled) CONFIG_MBEDTLS_NIST_KW_C NIST key wrapping (KW) and KW padding (KWP) Found in: Component config > mbedTLS > Symmetric Ciphers Enable NIST key wrapping and key wrapping padding. Default value: No (disabled) CONFIG_MBEDTLS_RIPEMD160_C Enable RIPEMD-160 hash algorithm Found in: Component config > mbedTLS Enable the RIPEMD-160 hash algorithm. Default value: No (disabled) Certificates Contains: CONFIG_MBEDTLS_PEM_PARSE_C Read & Parse PEM formatted certificates Found in: Component config > mbedTLS > Certificates Enable decoding/parsing of PEM formatted certificates. If your certificates are all in the simpler DER format, disabling this option will save some code size. Default value: Yes (enabled) CONFIG_MBEDTLS_PEM_WRITE_C Write PEM formatted certificates Found in: Component config > mbedTLS > Certificates Enable writing of PEM formatted certificates. If writing certificate data only in DER format, disabling this option will save some code size. Default value: Yes (enabled) CONFIG_MBEDTLS_X509_CRL_PARSE_C X.509 CRL parsing Found in: Component config > mbedTLS > Certificates Support for parsing X.509 Certifificate Revocation Lists. Default value: Yes (enabled) CONFIG_MBEDTLS_X509_CSR_PARSE_C X.509 CSR parsing Found in: Component config > mbedTLS > Certificates Support for parsing X.509 Certifificate Signing Requests Default value: Yes (enabled) CONFIG_MBEDTLS_ECP_C Elliptic Curve Ciphers Found in: Component config > mbedTLS Default value: Yes (enabled) CONFIG_MBEDTLS_DHM_C Diffie-Hellman-Merkle key exchange (DHM) Found in: Component config > mbedTLS Enable DHM. Needed to use DHE-xxx TLS ciphersuites. Note that the security of Diffie-Hellman key exchanges depends on a suitable prime being used for the exchange. Please see detailed warning text about this in file mbedtls/dhm.h file. Default value: No (disabled) CONFIG_MBEDTLS_ECDH_C Elliptic Curve Diffie-Hellman (ECDH) Found in: Component config > mbedTLS Enable ECDH. Needed to use ECDHE-xxx TLS ciphersuites. Default value: Yes (enabled) CONFIG_MBEDTLS_ECDSA_C Elliptic Curve DSA Found in: Component config > mbedTLS > CONFIG_MBEDTLS_ECDH_C Enable ECDSA. Needed to use ECDSA-xxx TLS ciphersuites. Default value: Yes (enabled) CONFIG_MBEDTLS_ECJPAKE_C Elliptic curve J-PAKE Found in: Component config > mbedTLS Enable ECJPAKE. Needed to use ECJPAKE-xxx TLS ciphersuites. Default value: No (disabled) CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED Enable SECP192R1 curve Found in: Component config > mbedTLS Enable support for SECP192R1 Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED Enable SECP224R1 curve Found in: Component config > mbedTLS Enable support for SECP224R1 Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED Enable SECP256R1 curve Found in: Component config > mbedTLS Enable support for SECP256R1 Elliptic Curve. Default value: Yes (enabled) CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED Enable SECP384R1 curve Found in: Component config > mbedTLS Enable support for SECP384R1 Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED Enable SECP521R1 curve Found in: Component config > mbedTLS Enable support for SECP521R1 Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED Enable SECP192K1 curve Found in: Component config > mbedTLS Enable support for SECP192K1 Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED Enable SECP224K1 curve Found in: Component config > mbedTLS Enable support for SECP224K1 Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED Enable SECP256K1 curve Found in: Component config > mbedTLS Enable support for SECP256K1 Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED Enable BP256R1 curve Found in: Component config > mbedTLS support for DP Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED Enable BP384R1 curve Found in: Component config > mbedTLS support for DP Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED Enable BP512R1 curve Found in: Component config > mbedTLS support for DP Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED Enable CURVE25519 curve Found in: Component config > mbedTLS Enable support for CURVE25519 Elliptic Curve. CONFIG_MBEDTLS_ECP_NIST_OPTIM NIST 'modulo p' optimisations Found in: Component config > mbedTLS NIST 'modulo p' optimisations increase Elliptic Curve operation performance. Disabling this option saves some code size. Default value: Yes (enabled) CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM Enable fixed-point multiplication optimisations Found in: Component config > mbedTLS This configuration option enables optimizations to speedup (about 3 ~ 4 times) the ECP fixed point multiplication using pre-computed tables in the flash memory. Disabling this configuration option saves flash footprint (about 29KB if all Elliptic Curve selected) in the application binary. # end of Elliptic Curve options Default value: Yes (enabled) CONFIG_MBEDTLS_POLY1305_C Poly1305 MAC algorithm Found in: Component config > mbedTLS Enable support for Poly1305 MAC algorithm. Default value: No (disabled) CONFIG_MBEDTLS_CHACHA20_C Chacha20 stream cipher Found in: Component config > mbedTLS Enable support for Chacha20 stream cipher. Default value: No (disabled) CONFIG_MBEDTLS_CHACHAPOLY_C ChaCha20-Poly1305 AEAD algorithm Found in: Component config > mbedTLS > CONFIG_MBEDTLS_CHACHA20_C Enable support for ChaCha20-Poly1305 AEAD algorithm. Default value: No (disabled) if CONFIG_MBEDTLS_CHACHA20_C && CONFIG_MBEDTLS_POLY1305_C CONFIG_MBEDTLS_HKDF_C HKDF algorithm (RFC 5869) Found in: Component config > mbedTLS Enable support for the Hashed Message Authentication Code (HMAC)-based key derivation function (HKDF). Default value: No (disabled) CONFIG_MBEDTLS_THREADING_C Enable the threading abstraction layer Found in: Component config > mbedTLS If you do intend to use contexts between threads, you will need to enable this layer to prevent race conditions. Default value: No (disabled) CONFIG_MBEDTLS_THREADING_ALT Enable threading alternate implementation Found in: Component config > mbedTLS > CONFIG_MBEDTLS_THREADING_C Enable threading alt to allow your own alternate threading implementation. Default value: Yes (enabled) if CONFIG_MBEDTLS_THREADING_C CONFIG_MBEDTLS_THREADING_PTHREAD Enable threading pthread implementation Found in: Component config > mbedTLS > CONFIG_MBEDTLS_THREADING_C Enable the pthread wrapper layer for the threading layer. Default value: No (disabled) if CONFIG_MBEDTLS_THREADING_C CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI Fallback to software implementation for larger MPI values Found in: Component config > mbedTLS Fallback to software implementation for RSA key lengths larger than SOC_RSA_MAX_BIT_LEN. If this is not active then the ESP will be unable to process keys greater than SOC_RSA_MAX_BIT_LEN. Default value: No (disabled) CONFIG_MBEDTLS_USE_CRYPTO_ROM_IMPL Use ROM implementation of the crypto algorithm Found in: Component config > mbedTLS Enable this flag to use mbedtls crypto algorithm from ROM instead of ESP-IDF. This configuration option saves flash footprint in the application binary. Note that the version of mbedtls crypto algorithm library in ROM is v2.16.12. We have done the security analysis of the mbedtls revision in ROM (v2.16.12) and ensured that affected symbols have been patched (removed). If in the future mbedtls revisions there are security issues that also affects the version in ROM (v2.16.12) then we shall patch the relevant symbols. This would increase the flash footprint and hence care must be taken to keep some reserved space for the application binary in flash layout. Default value: No (disabled) if ESP_ROM_HAS_MBEDTLS_CRYPTO_LIB && CONFIG_IDF_EXPERIMENTAL_FEATURES ESP-MQTT Configurations Contains: CONFIG_MQTT_PROTOCOL_311 Enable MQTT protocol 3.1.1 Found in: Component config > ESP-MQTT Configurations If not, this library will use MQTT protocol 3.1 Default value: Yes (enabled) CONFIG_MQTT_PROTOCOL_5 Enable MQTT protocol 5.0 Found in: Component config > ESP-MQTT Configurations If not, this library will not support MQTT 5.0 Default value: No (disabled) CONFIG_MQTT_TRANSPORT_SSL Enable MQTT over SSL Found in: Component config > ESP-MQTT Configurations Enable MQTT transport over SSL with mbedtls Default value: Yes (enabled) CONFIG_MQTT_TRANSPORT_WEBSOCKET Enable MQTT over Websocket Found in: Component config > ESP-MQTT Configurations Enable MQTT transport over Websocket. Default value: Yes (enabled) CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE Enable MQTT over Websocket Secure Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_TRANSPORT_WEBSOCKET Enable MQTT transport over Websocket Secure. Default value: Yes (enabled) CONFIG_MQTT_MSG_ID_INCREMENTAL Use Incremental Message Id Found in: Component config > ESP-MQTT Configurations Set this to true for the message id (2.3.1 Packet Identifier) to be generated as an incremental number rather then a random value (used by default) Default value: No (disabled) CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED Skip publish if disconnected Found in: Component config > ESP-MQTT Configurations Set this to true to avoid publishing (enqueueing messages) if the client is disconnected. The MQTT client tries to publish all messages by default, even in the disconnected state (where the qos1 and qos2 packets are stored in the internal outbox to be published later) The MQTT_SKIP_PUBLISH_IF_DISCONNECTED option allows applications to override this behaviour and not enqueue publish packets in the disconnected state. Default value: No (disabled) CONFIG_MQTT_REPORT_DELETED_MESSAGES Report deleted messages Found in: Component config > ESP-MQTT Configurations Set this to true to post events for all messages which were deleted from the outbox before being correctly sent and confirmed. Default value: No (disabled) CONFIG_MQTT_USE_CUSTOM_CONFIG MQTT Using custom configurations Found in: Component config > ESP-MQTT Configurations Custom MQTT configurations. Default value: No (disabled) CONFIG_MQTT_TCP_DEFAULT_PORT Default MQTT over TCP port Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG Default MQTT over TCP port Default value: 1883 if CONFIG_MQTT_USE_CUSTOM_CONFIG CONFIG_MQTT_SSL_DEFAULT_PORT Default MQTT over SSL port Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG Default MQTT over SSL port Default value: CONFIG_MQTT_WS_DEFAULT_PORT Default MQTT over Websocket port Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG Default MQTT over Websocket port Default value: CONFIG_MQTT_WSS_DEFAULT_PORT Default MQTT over Websocket Secure port Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG Default MQTT over Websocket Secure port Default value: CONFIG_MQTT_BUFFER_SIZE Default MQTT Buffer Size Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG This buffer size using for both transmit and receive Default value: 1024 if CONFIG_MQTT_USE_CUSTOM_CONFIG CONFIG_MQTT_TASK_STACK_SIZE MQTT task stack size Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG MQTT task stack size Default value: 6144 if CONFIG_MQTT_USE_CUSTOM_CONFIG CONFIG_MQTT_DISABLE_API_LOCKS Disable API locks Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG Default config employs API locks to protect internal structures. It is possible to disable these locks if the user code doesn't access MQTT API from multiple concurrent tasks Default value: No (disabled) if CONFIG_MQTT_USE_CUSTOM_CONFIG CONFIG_MQTT_TASK_PRIORITY MQTT task priority Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG MQTT task priority. Higher number denotes higher priority. Default value: CONFIG_MQTT_POLL_READ_TIMEOUT_MS MQTT transport poll read timeut Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG Timeout when polling underlying transport for read. Default value: 1000 if CONFIG_MQTT_USE_CUSTOM_CONFIG CONFIG_MQTT_EVENT_QUEUE_SIZE Number of queued events. Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG A value higher than 1 enables multiple queued events. Default value: CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED Enable MQTT task core selection Found in: Component config > ESP-MQTT Configurations This will enable core selection CONFIG_MQTT_TASK_CORE_SELECTION Core to use ? Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED Available options: Core 0 (CONFIG_MQTT_USE_CORE_0) Core 1 (CONFIG_MQTT_USE_CORE_1) CONFIG_MQTT_OUTBOX_DATA_ON_EXTERNAL_MEMORY Use external memory for outbox data Found in: Component config > ESP-MQTT Configurations Set to true to use external memory for outbox data. Default value: No (disabled) if CONFIG_MQTT_USE_CUSTOM_CONFIG CONFIG_MQTT_CUSTOM_OUTBOX Enable custom outbox implementation Found in: Component config > ESP-MQTT Configurations Set to true if a specific implementation of message outbox is needed (e.g. persistent outbox in NVM or similar). Note: Implementation of the custom outbox must be added to the mqtt component. These CMake commands could be used to append the custom implementation to lib-mqtt sources: idf_component_get_property(mqtt mqtt COMPONENT_LIB) set_property(TARGET ${mqtt} PROPERTY SOURCES ${PROJECT_DIR}/custom_outbox.c APPEND) Default value: No (disabled) CONFIG_MQTT_OUTBOX_EXPIRED_TIMEOUT_MS Outbox message expired timeout[ms] Found in: Component config > ESP-MQTT Configurations Messages which stays in the outbox longer than this value before being published will be discarded. Default value: 30000 if CONFIG_MQTT_USE_CUSTOM_CONFIG Newlib Contains: CONFIG_NEWLIB_STDOUT_LINE_ENDING Line ending for UART output Found in: Component config > Newlib This option allows configuring the desired line endings sent to UART when a newline ('n', LF) appears on stdout. Three options are possible: CRLF: whenever LF is encountered, prepend it with CR LF: no modification is applied, stdout is sent as is CR: each occurence of LF is replaced with CR This option doesn't affect behavior of the UART driver (drivers/uart.h). Available options: CRLF (CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF) LF (CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF) CR (CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR) CONFIG_NEWLIB_STDIN_LINE_ENDING Line ending for UART input Found in: Component config > Newlib This option allows configuring which input sequence on UART produces a newline ('n', LF) on stdin. Three options are possible: CRLF: CRLF is converted to LF LF: no modification is applied, input is sent to stdin as is CR: each occurence of CR is replaced with LF This option doesn't affect behavior of the UART driver (drivers/uart.h). Available options: CRLF (CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF) LF (CONFIG_NEWLIB_STDIN_LINE_ENDING_LF) CR (CONFIG_NEWLIB_STDIN_LINE_ENDING_CR) CONFIG_NEWLIB_NANO_FORMAT Enable 'nano' formatting options for printf/scanf family Found in: Component config > Newlib In most chips the ROM contains parts of newlib C library, including printf/scanf family of functions. These functions have been compiled with so-called "nano" formatting option. This option doesn't support 64-bit integer formats and C99 features, such as positional arguments. For more details about "nano" formatting option, please see newlib readme file, search for '--enable-newlib-nano-formatted-io': https://sourceware.org/newlib/README If this option is enabled and the ROM contains functions from newlib-nano, the build system will use functions available in ROM, reducing the application binary size. Functions available in ROM run faster than functions which run from flash. Functions available in ROM can also run when flash instruction cache is disabled. Some chips (e.g. ESP32-C6) has the full formatting versions of printf/scanf in ROM instead of the nano versions and in this building with newlib nano might actually increase the size of the binary. Which functions are present in ROM can be seen from ROM caps: ESP_ROM_HAS_NEWLIB_NANO_FORMAT and ESP_ROM_HAS_NEWLIB_NORMAL_FORMAT. If you need 64-bit integer formatting support or C99 features, keep this option disabled. CONFIG_NEWLIB_TIME_SYSCALL Timers used for gettimeofday function Found in: Component config > Newlib This setting defines which hardware timers are used to implement 'gettimeofday' and 'time' functions in C library. If both high-resolution (systimer for all targets except ESP32) and RTC timers are used, timekeeping will continue in deep sleep. Time will be reported at 1 microsecond resolution. This is the default, and the recommended option. If only high-resolution timer (systimer) is used, gettimeofday will provide time at microsecond resolution. Time will not be preserved when going into deep sleep mode. If only RTC timer is used, timekeeping will continue in deep sleep, but time will be measured at 6.(6) microsecond resolution. Also the gettimeofday function itself may take longer to run. If no timers are used, gettimeofday and time functions return -1 and set errno to ENOSYS. When RTC is used for timekeeping, two RTC_STORE registers are used to keep time in deep sleep mode. Available options: RTC and high-resolution timer (CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT) RTC (CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC) High-resolution timer (CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT) None (CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE) NVS Contains: CONFIG_NVS_ENCRYPTION Enable NVS encryption Found in: Component config > NVS This option enables encryption for NVS. When enabled, XTS-AES is used to encrypt the complete NVS data, except the page headers. It requires XTS encryption keys to be stored in an encrypted partition (enabling flash encryption is mandatory here) or to be derived from an HMAC key burnt in eFuse. Default value: Yes (enabled) if CONFIG_SECURE_FLASH_ENC_ENABLED && (CONFIG_SECURE_FLASH_ENC_ENABLED || SOC_HMAC_SUPPORTED) CONFIG_NVS_COMPATIBLE_PRE_V4_3_ENCRYPTION_FLAG NVS partition encrypted flag compatible with ESP-IDF before v4.3 Found in: Component config > NVS Enabling this will ignore "encrypted" flag for NVS partitions. NVS encryption scheme is different than hardware flash encryption and hence it is not recommended to have "encrypted" flag for NVS partitions. This was not being checked in pre v4.3 IDF. Hence, if you have any devices where this flag is kept enabled in partition table then enabling this config will allow to have same behavior as pre v4.3 IDF. CONFIG_NVS_ASSERT_ERROR_CHECK Use assertions for error checking Found in: Component config > NVS This option switches error checking type between assertions (y) or return codes (n). Default value: No (disabled) CONFIG_NVS_LEGACY_DUP_KEYS_COMPATIBILITY Enable legacy nvs_set function behavior when same key is reused with different data types Found in: Component config > NVS Enabling this option will switch the nvs_set() family of functions to the legacy mode: when called repeatedly with the same key but different data type, the existing value in the NVS remains active and the new value is just stored, actually not accessible through corresponding nvs_get() call for the key given. Use this option only when your application relies on such NVS API behaviour. Default value: No (disabled) NVS Security Provider Contains: CONFIG_NVS_SEC_KEY_PROTECTION_SCHEME NVS Encryption: Key Protection Scheme Found in: Component config > NVS Security Provider This choice defines the default NVS encryption keys protection scheme; which will be used for the default NVS partition. Users can use the corresponding scheme registration APIs to register other schemes for the default as well as other NVS partitions. Available options: Using Flash Encryption (CONFIG_NVS_SEC_KEY_PROTECT_USING_FLASH_ENC) Protect the NVS Encryption Keys using Flash Encryption Requires a separate 'nvs_keys' partition (which will be encrypted by flash encryption) for storing the NVS encryption keys Using HMAC peripheral (CONFIG_NVS_SEC_KEY_PROTECT_USING_HMAC) Derive and protect the NVS Encryption Keys using the HMAC peripheral Requires the specified eFuse block (NVS_SEC_HMAC_EFUSE_KEY_ID or the v2 API argument) to be empty or pre-written with a key with the purpose ESP_EFUSE_KEY_PURPOSE_HMAC_UP CONFIG_NVS_SEC_HMAC_EFUSE_KEY_ID eFuse key ID storing the HMAC key Found in: Component config > NVS Security Provider eFuse block key ID storing the HMAC key for deriving the NVS encryption keys Note: The eFuse block key ID required by the HMAC scheme (CONFIG_NVS_SEC_KEY_PROTECT_USING_HMAC) is set using this config when the default NVS partition is initialized with nvs_flash_init(). The eFuse block key ID can also be set at runtime by passing the appropriate value to the NVS security scheme registration APIs. Range: from 0 to 6 if CONFIG_NVS_SEC_KEY_PROTECT_USING_HMAC Default value: OpenThread Contains: CONFIG_OPENTHREAD_ENABLED OpenThread Found in: Component config > OpenThread Select this option to enable OpenThread and show the submenu with OpenThread configuration choices. Default value: No (disabled) CONFIG_OPENTHREAD_LOG_LEVEL_DYNAMIC Enable dynamic log level control Found in: Component config > OpenThread > CONFIG_OPENTHREAD_ENABLED Select this option to enable dynamic log level control for OpenThread Default value: Yes (enabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_CONSOLE_TYPE OpenThread console type Found in: Component config > OpenThread > CONFIG_OPENTHREAD_ENABLED Select OpenThread console type Available options: OpenThread console type UART (CONFIG_OPENTHREAD_CONSOLE_TYPE_UART) OpenThread console type USB Serial/JTAG Controller (CONFIG_OPENTHREAD_CONSOLE_TYPE_USB_SERIAL_JTAG) CONFIG_OPENTHREAD_LOG_LEVEL OpenThread log verbosity Found in: Component config > OpenThread > CONFIG_OPENTHREAD_ENABLED Select OpenThread log level. Available options: No logs (CONFIG_OPENTHREAD_LOG_LEVEL_NONE) Error logs (CONFIG_OPENTHREAD_LOG_LEVEL_CRIT) Warning logs (CONFIG_OPENTHREAD_LOG_LEVEL_WARN) Notice logs (CONFIG_OPENTHREAD_LOG_LEVEL_NOTE) Info logs (CONFIG_OPENTHREAD_LOG_LEVEL_INFO) Debug logs (CONFIG_OPENTHREAD_LOG_LEVEL_DEBG) Thread Operational Dataset Contains: CONFIG_OPENTHREAD_NETWORK_NAME OpenThread network name Found in: Component config > OpenThread > Thread Operational Dataset Default value: "OpenThread-ESP" CONFIG_OPENTHREAD_MESH_LOCAL_PREFIX OpenThread mesh local prefix, format <address>/<plen> Found in: Component config > OpenThread > Thread Operational Dataset A string in the format "<address>/<plen>", where <address> is an IPv6 address and <plen> is a prefix length. For example "fd00:db8:a0:0::/64" Default value: "fd00:db8:a0:0::/64" CONFIG_OPENTHREAD_NETWORK_CHANNEL OpenThread network channel Found in: Component config > OpenThread > Thread Operational Dataset Range: from 11 to 26 Default value: 15 CONFIG_OPENTHREAD_NETWORK_PANID OpenThread network pan id Found in: Component config > OpenThread > Thread Operational Dataset Range: from 0 to 0xFFFE Default value: "0x1234" CONFIG_OPENTHREAD_NETWORK_EXTPANID OpenThread extended pan id Found in: Component config > OpenThread > Thread Operational Dataset The OpenThread network extended pan id in hex string format Default value: dead00beef00cafe CONFIG_OPENTHREAD_NETWORK_MASTERKEY OpenThread network key Found in: Component config > OpenThread > Thread Operational Dataset The OpenThread network network key in hex string format Default value: 00112233445566778899aabbccddeeff CONFIG_OPENTHREAD_NETWORK_PSKC OpenThread pre-shared commissioner key Found in: Component config > OpenThread > Thread Operational Dataset The OpenThread pre-shared commissioner key in hex string format Default value: 104810e2315100afd6bc9215a6bfac53 CONFIG_OPENTHREAD_RADIO_TYPE Config the Thread radio type Found in: Component config > OpenThread Configure how OpenThread connects to the 15.4 radio Available options: Native 15.4 radio (CONFIG_OPENTHREAD_RADIO_NATIVE) Select this to use the native 15.4 radio. Connect via UART (CONFIG_OPENTHREAD_RADIO_SPINEL_UART) Select this to connect to a Radio Co-Processor via UART. Connect via SPI (CONFIG_OPENTHREAD_RADIO_SPINEL_SPI) Select this to connect to a Radio Co-Processor via SPI. CONFIG_OPENTHREAD_DEVICE_TYPE Config the Thread device type Found in: Component config > OpenThread OpenThread can be configured to different device types (FTD, MTD, Radio) Available options: Full Thread Device (CONFIG_OPENTHREAD_FTD) Select this to enable Full Thread Device which can act as router and leader in a Thread network. Minimal Thread Device (CONFIG_OPENTHREAD_MTD) Select this to enable Minimal Thread Device which can only act as end device in a Thread network. This will reduce the code size of the OpenThread stack. Radio Only Device (CONFIG_OPENTHREAD_RADIO) Select this to enable Radio Only Device which can only forward 15.4 packets to the host. The OpenThread stack will be run on the host and OpenThread will have minimal footprint on the radio only device. CONFIG_OPENTHREAD_RCP_TRANSPORT The RCP transport type Found in: Component config > OpenThread Available options: UART RCP (CONFIG_OPENTHREAD_RCP_UART) Select this to enable UART connection to host. SPI RCP (CONFIG_OPENTHREAD_RCP_SPI) Select this to enable SPI connection to host. CONFIG_OPENTHREAD_NCP_VENDOR_HOOK Enable vendor command for RCP Found in: Component config > OpenThread Select this to enable OpenThread NCP vendor commands. Default value: No (disabled) if CONFIG_OPENTHREAD_RADIO CONFIG_OPENTHREAD_CLI Enable Openthread Command-Line Interface Found in: Component config > OpenThread Select this option to enable Command-Line Interface in OpenThread. Default value: Yes (enabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_DIAG Enable diag Found in: Component config > OpenThread Select this option to enable Diag in OpenThread. This will enable diag mode and a series of diag commands in the OpenThread command line. These commands allow users to manipulate low-level features of the storage and 15.4 radio. Default value: Yes (enabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_COMMISSIONER Enable Commissioner Found in: Component config > OpenThread Select this option to enable commissioner in OpenThread. This will enable the device to act as a commissioner in the Thread network. A commissioner checks the pre-shared key from a joining device with the Thread commissioning protocol and shares the network parameter with the joining device upon success. Default value: No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_COMM_MAX_JOINER_ENTRIES The size of max commissioning joiner entries Found in: Component config > OpenThread > CONFIG_OPENTHREAD_COMMISSIONER Range: from 2 to 50 if CONFIG_OPENTHREAD_COMMISSIONER Default value: CONFIG_OPENTHREAD_JOINER Enable Joiner Found in: Component config > OpenThread Select this option to enable Joiner in OpenThread. This allows a device to join the Thread network with a pre-shared key using the Thread commissioning protocol. Default value: No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_SRP_CLIENT Enable SRP Client Found in: Component config > OpenThread Select this option to enable SRP Client in OpenThread. This allows a device to register SRP services to SRP Server. Default value: Yes (enabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_SRP_CLIENT_MAX_SERVICES Specifies number of service entries in the SRP client service pool Found in: Component config > OpenThread > CONFIG_OPENTHREAD_SRP_CLIENT Set the max buffer size of service entries in the SRP client service pool. Range: from 2 to 20 if CONFIG_OPENTHREAD_SRP_CLIENT Default value: CONFIG_OPENTHREAD_DNS_CLIENT Enable DNS Client Found in: Component config > OpenThread Select this option to enable DNS Client in OpenThread. Default value: Yes (enabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_BORDER_ROUTER Enable Border Router Found in: Component config > OpenThread Select this option to enable border router features in OpenThread. Default value: No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_PLATFORM_MSGPOOL_MANAGEMENT Allocate message pool buffer from PSRAM Found in: Component config > OpenThread If enabled, the message pool is managed by platform defined logic. Default value: No (disabled) if CONFIG_OPENTHREAD_ENABLED && (CONFIG_SPIRAM_USE_CAPS_ALLOC || CONFIG_SPIRAM_USE_MALLOC) CONFIG_OPENTHREAD_NUM_MESSAGE_BUFFERS The number of openthread message buffers Found in: Component config > OpenThread Range: from 10 to 8191 if CONFIG_OPENTHREAD_PLATFORM_MSGPOOL_MANAGEMENT && CONFIG_OPENTHREAD_ENABLED Default value: CONFIG_OPENTHREAD_SPINEL_RX_FRAME_BUFFER_SIZE The size of openthread spinel rx frame buffer Found in: Component config > OpenThread Range: from 512 to 8192 if CONFIG_OPENTHREAD_ENABLED || CONFIG_OPENTHREAD_SPINEL_ONLY Default value: CONFIG_OPENTHREAD_MLE_MAX_CHILDREN The size of max MLE children entries Found in: Component config > OpenThread Range: from 5 to 50 if CONFIG_OPENTHREAD_ENABLED Default value: CONFIG_OPENTHREAD_TMF_ADDR_CACHE_ENTRIES The size of max TMF address cache entries Found in: Component config > OpenThread Range: from 5 to 50 if CONFIG_OPENTHREAD_ENABLED Default value: CONFIG_OPENTHREAD_DNS64_CLIENT Use dns64 client Found in: Component config > OpenThread Select this option to acquire NAT64 address from dns servers. Default value: No (disabled) if CONFIG_OPENTHREAD_ENABLED && CONFIG_LWIP_IPV4 CONFIG_OPENTHREAD_DNS_SERVER_ADDR DNS server address (IPv4) Found in: Component config > OpenThread > CONFIG_OPENTHREAD_DNS64_CLIENT Set the DNS server IPv4 address. Default value: "8.8.8.8" if CONFIG_OPENTHREAD_DNS64_CLIENT CONFIG_OPENTHREAD_UART_BUFFER_SIZE The uart received buffer size of openthread Found in: Component config > OpenThread Set the OpenThread UART buffer size. Range: from 128 to 1024 if CONFIG_OPENTHREAD_ENABLED Default value: 768 if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_LINK_METRICS Enable link metrics feature Found in: Component config > OpenThread Select this option to enable link metrics feature Default value: No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_MACFILTER_ENABLE Enable mac filter feature Found in: Component config > OpenThread Select this option to enable mac filter feature Default value: No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_CSL_ENABLE Enable CSL feature Found in: Component config > OpenThread Select this option to enable CSL feature Default value: No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_XTAL_ACCURACY The accuracy of the XTAL Found in: Component config > OpenThread The device's XTAL accuracy, in ppm. Default value: 130 CONFIG_OPENTHREAD_CSL_ACCURACY The current CSL rx/tx scheduling drift, in units of ± ppm Found in: Component config > OpenThread The current accuracy of the clock used for scheduling CSL operations Default value: CONFIG_OPENTHREAD_CSL_UNCERTAIN The CSL Uncertainty in units of 10 us. Found in: Component config > OpenThread The fixed uncertainty of the Device for scheduling CSL Transmissions in units of 10 microseconds. Default value: CONFIG_OPENTHREAD_CSL_DEBUG_ENABLE Enable CSL debug Found in: Component config > OpenThread Select this option to set rx on when sleep in CSL feature, only for debug Default value: No (disabled) if CONFIG_OPENTHREAD_CSL_ENABLE CONFIG_OPENTHREAD_DUA_ENABLE Enable Domain Unicast Address feature Found in: Component config > OpenThread Only used for Thread1.2 certification Default value: No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_TIME_SYNC Enable the time synchronization service feature Found in: Component config > OpenThread Select this option to enable time synchronization feature, the devices in the same Thread network could sync to the same network time. Default value: No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_RADIO_STATS_ENABLE Enable Radio Statistics feature Found in: Component config > OpenThread Select this option to enable the radio statistics feature, you can use radio command to print some radio Statistics informations. Default value: No (disabled) if CONFIG_OPENTHREAD_FTD || CONFIG_OPENTHREAD_MTD CONFIG_OPENTHREAD_SPINEL_ONLY Enable OpenThread External Radio Spinel feature Found in: Component config > OpenThread Select this option to enable the OpenThread Radio Spinel for external protocol stack, such as Zigbee. Default value: No (disabled) CONFIG_OPENTHREAD_RX_ON_WHEN_IDLE Enable OpenThread radio capibility rx on when idle Found in: Component config > OpenThread Select this option to enable OpenThread radio capibility rx on when idle. Do not support this feature when SW coexistence is enabled. Default value: No (disabled) if CONFIG_ESP_COEX_SW_COEXIST_ENABLE Thread Address Query Config Contains: CONFIG_OPENTHREAD_ADDRESS_QUERY_TIMEOUT Timeout value (in seconds) for a address notification response after sending an address query. Found in: Component config > OpenThread > Thread Address Query Config Range: from 1 to 10 if CONFIG_OPENTHREAD_FTD || CONFIG_OPENTHREAD_MTD Default value: CONFIG_OPENTHREAD_ADDRESS_QUERY_RETRY_DELAY Initial retry delay for address query (in seconds). Found in: Component config > OpenThread > Thread Address Query Config Range: from 1 to 120 if CONFIG_OPENTHREAD_FTD || CONFIG_OPENTHREAD_MTD Default value: CONFIG_OPENTHREAD_ADDRESS_QUERY_MAX_RETRY_DELAY Maximum retry delay for address query (in seconds). Found in: Component config > OpenThread > Thread Address Query Config Range: from to 960 if CONFIG_OPENTHREAD_FTD || CONFIG_OPENTHREAD_MTD Default value: 120 if CONFIG_OPENTHREAD_FTD || CONFIG_OPENTHREAD_MTD Protocomm Contains: CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0 Support protocomm security version 0 (no security) Found in: Component config > Protocomm Enable support of security version 0. Disabling this option saves some code size. Consult the Enabling protocomm security version section of the Protocomm documentation in ESP-IDF Programming guide for more details. Default value: Yes (enabled) CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1 Support protocomm security version 1 (Curve25519 key exchange + AES-CTR encryption/decryption) Found in: Component config > Protocomm Enable support of security version 1. Disabling this option saves some code size. Consult the Enabling protocomm security version section of the Protocomm documentation in ESP-IDF Programming guide for more details. Default value: Yes (enabled) CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2 Support protocomm security version 2 (SRP6a-based key exchange + AES-GCM encryption/decryption) Found in: Component config > Protocomm Enable support of security version 2. Disabling this option saves some code size. Consult the Enabling protocomm security version section of the Protocomm documentation in ESP-IDF Programming guide for more details. Default value: Yes (enabled) PThreads Contains: CONFIG_PTHREAD_TASK_PRIO_DEFAULT Default task priority Found in: Component config > PThreads Priority used to create new tasks with default pthread parameters. Range: from 0 to 255 Default value: 5 CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT Default task stack size Found in: Component config > PThreads Stack size used to create new tasks with default pthread parameters. Default value: 3072 CONFIG_PTHREAD_STACK_MIN Minimum allowed pthread stack size Found in: Component config > PThreads Minimum allowed pthread stack size set in attributes passed to pthread_create Default value: 768 CONFIG_PTHREAD_TASK_CORE_DEFAULT Default pthread core affinity Found in: Component config > PThreads The default core to which pthreads are pinned. Available options: No affinity (CONFIG_PTHREAD_DEFAULT_CORE_NO_AFFINITY) Core 0 (CONFIG_PTHREAD_DEFAULT_CORE_0) Core 1 (CONFIG_PTHREAD_DEFAULT_CORE_1) CONFIG_PTHREAD_TASK_NAME_DEFAULT Default name of pthreads Found in: Component config > PThreads The default name of pthreads. Default value: "pthread" SoC Settings Contains: MMU Config Main Flash configuration Contains: SPI Flash behavior when brownout Contains: CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC Enable sending reset when brownout for XMC flash chips Found in: Component config > Main Flash configuration > SPI Flash behavior when brownout When this option is selected, the patch will be enabled for XMC. Follow the recommended flow by XMC for better stability. DO NOT DISABLE UNLESS YOU KNOW WHAT YOU ARE DOING. Optional and Experimental Features (READ DOCS FIRST) Contains: CONFIG_SPI_FLASH_HPM_DC Support HPM using DC (READ DOCS FIRST) Found in: Component config > Main Flash configuration > Optional and Experimental Features (READ DOCS FIRST) This feature needs your bootloader to be compiled DC-aware (BOOTLOADER_FLASH_DC_AWARE=y). Otherwise the chip will not be able to boot after a reset. Available options: Auto (Enable when bootloader support enabled (BOOTLOADER_FLASH_DC_AWARE)) (CONFIG_SPI_FLASH_HPM_DC_AUTO) Disable (READ DOCS FIRST) (CONFIG_SPI_FLASH_HPM_DC_DISABLE) CONFIG_SPI_FLASH_AUTO_SUSPEND Auto suspend long erase/write operations (READ DOCS FIRST) Found in: Component config > Main Flash configuration > Optional and Experimental Features (READ DOCS FIRST) This option is disabled by default because it is supported only for specific flash chips and for specific Espressif chips. To evaluate if you can use this feature refer to Optional Features for Flash > Auto Suspend & Resume of the ESP-IDF Programming Guide. CAUTION: If you want to OTA to an app with this feature turned on, please make sure the bootloader has the support for it. (later than IDF v4.3) If you are using an official Espressif module, please contact Espressif Business support to check if the module has the flash that support this feature installed. Also refer to Concurrency Constraints for Flash on SPI1 > Flash Auto Suspend Feature before enabling this option. SPI Flash driver Contains: CONFIG_SPI_FLASH_VERIFY_WRITE Verify SPI flash writes Found in: Component config > SPI Flash driver If this option is enabled, any time SPI flash is written then the data will be read back and verified. This can catch hardware problems with SPI flash, or flash which was not erased before verification. CONFIG_SPI_FLASH_LOG_FAILED_WRITE Log errors if verification fails Found in: Component config > SPI Flash driver > CONFIG_SPI_FLASH_VERIFY_WRITE If this option is enabled, if SPI flash write verification fails then a log error line will be written with the address, expected & actual values. This can be useful when debugging hardware SPI flash problems. CONFIG_SPI_FLASH_WARN_SETTING_ZERO_TO_ONE Log warning if writing zero bits to ones Found in: Component config > SPI Flash driver > CONFIG_SPI_FLASH_VERIFY_WRITE If this option is enabled, any SPI flash write which tries to set zero bits in the flash to ones will log a warning. Such writes will not result in the requested data appearing identically in flash once written, as SPI NOR flash can only set bits to one when an entire sector is erased. After erasing, individual bits can only be written from one to zero. Note that some software (such as SPIFFS) which is aware of SPI NOR flash may write one bits as an optimisation, relying on the data in flash becoming a bitwise AND of the new data and any existing data. Such software will log spurious warnings if this option is enabled. CONFIG_SPI_FLASH_ENABLE_COUNTERS Enable operation counters Found in: Component config > SPI Flash driver This option enables the following APIs: esp_flash_reset_counters esp_flash_dump_counters esp_flash_get_counters These APIs may be used to collect performance data for spi_flash APIs and to help understand behaviour of libraries which use SPI flash. CONFIG_SPI_FLASH_ROM_DRIVER_PATCH Enable SPI flash ROM driver patched functions Found in: Component config > SPI Flash driver Enable this flag to use patched versions of SPI flash ROM driver functions. This option should be enabled, if any one of the following is true: (1) need to write to flash on ESP32-D2WD; (2) main SPI flash is connected to non-default pins; (3) main SPI flash chip is manufactured by ISSI. CONFIG_SPI_FLASH_ROM_IMPL Use esp_flash implementation in ROM Found in: Component config > SPI Flash driver Enable this flag to use new SPI flash driver functions from ROM instead of ESP-IDF. If keeping this as "n" in your project, you will have less free IRAM. But you can use all of our flash features. If making this as "y" in your project, you will increase free IRAM. But you may miss out on some flash features and support for new flash chips. Currently the ROM cannot support the following features: SPI_FLASH_AUTO_SUSPEND (C3, S3) CONFIG_SPI_FLASH_DANGEROUS_WRITE Writing to dangerous flash regions Found in: Component config > SPI Flash driver SPI flash APIs can optionally abort or return a failure code if erasing or writing addresses that fall at the beginning of flash (covering the bootloader and partition table) or that overlap the app partition that contains the running app. It is not recommended to ever write to these regions from an IDF app, and this check prevents logic errors or corrupted firmware memory from damaging these regions. Note that this feature *does not* check calls to the esp_rom_xxx SPI flash ROM functions. These functions should not be called directly from IDF applications. Available options: Aborts (CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS) Fails (CONFIG_SPI_FLASH_DANGEROUS_WRITE_FAILS) Allowed (CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED) CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE Bypass a block erase and always do sector erase Found in: Component config > SPI Flash driver Some flash chips can have very high "max" erase times, especially for block erase (32KB or 64KB). This option allows to bypass "block erase" and always do sector erase commands. This will be much slower overall in most cases, but improves latency for other code to run. CONFIG_SPI_FLASH_YIELD_DURING_ERASE Enables yield operation during flash erase Found in: Component config > SPI Flash driver This allows to yield the CPUs between erase commands. Prevents starvation of other tasks. Please use this configuration together with SPI\_FLASH\_ERASE\_YIELD\_DURATION\_MS and SPI\_FLASH\_ERASE\_YIELD\_TICKS after carefully checking flash datasheet to avoid a watchdog timeout. For more information, please check SPI Flash API reference documenation under section OS Function. CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS Duration of erasing to yield CPUs (ms) Found in: Component config > SPI Flash driver > CONFIG_SPI_FLASH_YIELD_DURING_ERASE If a duration of one erase command is large then it will yield CPUs after finishing a current command. CONFIG_SPI_FLASH_ERASE_YIELD_TICKS CPU release time (tick) for an erase operation Found in: Component config > SPI Flash driver > CONFIG_SPI_FLASH_YIELD_DURING_ERASE Defines how many ticks will be before returning to continue a erasing. CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE Flash write chunk size Found in: Component config > SPI Flash driver Flash write is broken down in terms of multiple (smaller) write operations. This configuration options helps to set individual write chunk size, smaller value here ensures that cache (and non-IRAM resident interrupts) remains disabled for shorter duration. CONFIG_SPI_FLASH_SIZE_OVERRIDE Override flash size in bootloader header by ESPTOOLPY_FLASHSIZE Found in: Component config > SPI Flash driver SPI Flash driver uses the flash size configured in bootloader header by default. Enable this option to override flash size with latest ESPTOOLPY_FLASHSIZE value from the app header if the size in the bootloader header is incorrect. CONFIG_SPI_FLASH_CHECK_ERASE_TIMEOUT_DISABLED Flash timeout checkout disabled Found in: Component config > SPI Flash driver This option is helpful if you are using a flash chip whose timeout is quite large or unpredictable. CONFIG_SPI_FLASH_OVERRIDE_CHIP_DRIVER_LIST Override default chip driver list Found in: Component config > SPI Flash driver This option allows the chip driver list to be customized, instead of using the default list provided by ESP-IDF. When this option is enabled, the default list is no longer compiled or linked. Instead, the default_registered_chips structure must be provided by the user. See example: custom_chip_driver under examples/storage for more details. Auto-detect flash chips Contains: CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP ISSI Found in: Component config > SPI Flash driver > Auto-detect flash chips Enable this to support auto detection of ISSI chips if chip vendor not directly given by chip\_drv member of the chip struct. This adds support for variant chips, however will extend detecting time. CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP MXIC Found in: Component config > SPI Flash driver > Auto-detect flash chips Enable this to support auto detection of MXIC chips if chip vendor not directly given by chip\_drv member of the chip struct. This adds support for variant chips, however will extend detecting time. CONFIG_SPI_FLASH_SUPPORT_GD_CHIP GigaDevice Found in: Component config > SPI Flash driver > Auto-detect flash chips Enable this to support auto detection of GD (GigaDevice) chips if chip vendor not directly given by chip\_drv member of the chip struct. If you are using Wrover modules, please don't disable this, otherwise your flash may not work in 4-bit mode. This adds support for variant chips, however will extend detecting time and image size. Note that the default chip driver supports the GD chips with product ID 60H. CONFIG_SPI_FLASH_SUPPORT_WINBOND_CHIP Winbond Found in: Component config > SPI Flash driver > Auto-detect flash chips Enable this to support auto detection of Winbond chips if chip vendor not directly given by chip\_drv member of the chip struct. This adds support for variant chips, however will extend detecting time. CONFIG_SPI_FLASH_SUPPORT_BOYA_CHIP BOYA Found in: Component config > SPI Flash driver > Auto-detect flash chips Enable this to support auto detection of BOYA chips if chip vendor not directly given by chip\_drv member of the chip struct. This adds support for variant chips, however will extend detecting time. CONFIG_SPI_FLASH_SUPPORT_TH_CHIP TH Found in: Component config > SPI Flash driver > Auto-detect flash chips Enable this to support auto detection of TH chips if chip vendor not directly given by chip\_drv member of the chip struct. This adds support for variant chips, however will extend detecting time. CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE Enable encrypted partition read/write operations Found in: Component config > SPI Flash driver This option enables flash read/write operations to encrypted partition/s. This option is kept enabled irrespective of state of flash encryption feature. However, in case application is not using flash encryption feature and is in need of some additional memory from IRAM region (~1KB) then this config can be disabled. SPIFFS Configuration Contains: CONFIG_SPIFFS_MAX_PARTITIONS Maximum Number of Partitions Found in: Component config > SPIFFS Configuration Define maximum number of partitions that can be mounted. Range: from 1 to 10 Default value: 3 SPIFFS Cache Configuration Contains: CONFIG_SPIFFS_CACHE Enable SPIFFS Cache Found in: Component config > SPIFFS Configuration > SPIFFS Cache Configuration Enables/disable memory read caching of nucleus file system operations. Default value: Yes (enabled) CONFIG_SPIFFS_CACHE_WR Enable SPIFFS Write Caching Found in: Component config > SPIFFS Configuration > SPIFFS Cache Configuration > CONFIG_SPIFFS_CACHE Enables memory write caching for file descriptors in hydrogen. Default value: Yes (enabled) CONFIG_SPIFFS_CACHE_STATS Enable SPIFFS Cache Statistics Found in: Component config > SPIFFS Configuration > SPIFFS Cache Configuration > CONFIG_SPIFFS_CACHE Enable/disable statistics on caching. Debug/test purpose only. Default value: No (disabled) CONFIG_SPIFFS_PAGE_CHECK Enable SPIFFS Page Check Found in: Component config > SPIFFS Configuration Always check header of each accessed page to ensure consistent state. If enabled it will increase number of reads from flash, especially if cache is disabled. Default value: Yes (enabled) CONFIG_SPIFFS_GC_MAX_RUNS Set Maximum GC Runs Found in: Component config > SPIFFS Configuration Define maximum number of GC runs to perform to reach desired free pages. Range: from 1 to 10000 Default value: 10 CONFIG_SPIFFS_GC_STATS Enable SPIFFS GC Statistics Found in: Component config > SPIFFS Configuration Enable/disable statistics on gc. Debug/test purpose only. Default value: No (disabled) CONFIG_SPIFFS_PAGE_SIZE SPIFFS logical page size Found in: Component config > SPIFFS Configuration Logical page size of SPIFFS partition, in bytes. Must be multiple of flash page size (which is usually 256 bytes). Larger page sizes reduce overhead when storing large files, and improve filesystem performance when reading large files. Smaller page sizes reduce overhead when storing small (< page size) files. Range: from 256 to 1024 Default value: 256 CONFIG_SPIFFS_OBJ_NAME_LEN Set SPIFFS Maximum Name Length Found in: Component config > SPIFFS Configuration Object name maximum length. Note that this length include the zero-termination character, meaning maximum string of characters can at most be SPIFFS_OBJ_NAME_LEN - 1. SPIFFS_OBJ_NAME_LEN + SPIFFS_META_LENGTH should not exceed SPIFFS_PAGE_SIZE - 64. Range: from 1 to 256 Default value: 32 CONFIG_SPIFFS_FOLLOW_SYMLINKS Enable symbolic links for image creation Found in: Component config > SPIFFS Configuration If this option is enabled, symbolic links are taken into account during partition image creation. Default value: No (disabled) CONFIG_SPIFFS_USE_MAGIC Enable SPIFFS Filesystem Magic Found in: Component config > SPIFFS Configuration Enable this to have an identifiable spiffs filesystem. This will look for a magic in all sectors to determine if this is a valid spiffs system or not at mount time. Default value: Yes (enabled) CONFIG_SPIFFS_USE_MAGIC_LENGTH Enable SPIFFS Filesystem Length Magic Found in: Component config > SPIFFS Configuration > CONFIG_SPIFFS_USE_MAGIC If this option is enabled, the magic will also be dependent on the length of the filesystem. For example, a filesystem configured and formatted for 4 megabytes will not be accepted for mounting with a configuration defining the filesystem as 2 megabytes. Default value: Yes (enabled) CONFIG_SPIFFS_META_LENGTH Size of per-file metadata field Found in: Component config > SPIFFS Configuration This option sets the number of extra bytes stored in the file header. These bytes can be used in an application-specific manner. Set this to at least 4 bytes to enable support for saving file modification time. SPIFFS_OBJ_NAME_LEN + SPIFFS_META_LENGTH should not exceed SPIFFS_PAGE_SIZE - 64. Default value: 4 CONFIG_SPIFFS_USE_MTIME Save file modification time Found in: Component config > SPIFFS Configuration If enabled, then the first 4 bytes of per-file metadata will be used to store file modification time (mtime), accessible through stat/fstat functions. Modification time is updated when the file is opened. Default value: Yes (enabled) CONFIG_SPIFFS_MTIME_WIDE_64_BITS The time field occupies 64 bits in the image instead of 32 bits Found in: Component config > SPIFFS Configuration If this option is not set, the time field is 32 bits (up to 2106 year), otherwise it is 64 bits and make sure it matches SPIFFS_META_LENGTH. If the chip already has the spiffs image with the time field = 32 bits then this option cannot be applied in this case. Erase it first before using this option. To resolve the Y2K38 problem for the spiffs, use a toolchain with 64-bit time_t support. Default value: No (disabled) if CONFIG_SPIFFS_META_LENGTH >= 8 Debug Configuration Contains: CONFIG_SPIFFS_DBG Enable general SPIFFS debug Found in: Component config > SPIFFS Configuration > Debug Configuration Enabling this option will print general debug mesages to the console. Default value: No (disabled) CONFIG_SPIFFS_API_DBG Enable SPIFFS API debug Found in: Component config > SPIFFS Configuration > Debug Configuration Enabling this option will print API debug mesages to the console. Default value: No (disabled) CONFIG_SPIFFS_GC_DBG Enable SPIFFS Garbage Cleaner debug Found in: Component config > SPIFFS Configuration > Debug Configuration Enabling this option will print GC debug mesages to the console. Default value: No (disabled) CONFIG_SPIFFS_CACHE_DBG Enable SPIFFS Cache debug Found in: Component config > SPIFFS Configuration > Debug Configuration Enabling this option will print cache debug mesages to the console. Default value: No (disabled) CONFIG_SPIFFS_CHECK_DBG Enable SPIFFS Filesystem Check debug Found in: Component config > SPIFFS Configuration > Debug Configuration Enabling this option will print Filesystem Check debug mesages to the console. Default value: No (disabled) CONFIG_SPIFFS_TEST_VISUALISATION Enable SPIFFS Filesystem Visualization Found in: Component config > SPIFFS Configuration > Debug Configuration Enable this option to enable SPIFFS_vis function in the API. Default value: No (disabled) TCP Transport Contains: Websocket Contains: CONFIG_WS_TRANSPORT Enable Websocket Transport Found in: Component config > TCP Transport > Websocket Enable support for creating websocket transport. Default value: Yes (enabled) CONFIG_WS_BUFFER_SIZE Websocket transport buffer size Found in: Component config > TCP Transport > Websocket > CONFIG_WS_TRANSPORT Size of the buffer used for constructing the HTTP Upgrade request during connect Default value: 1024 CONFIG_WS_DYNAMIC_BUFFER Using dynamic websocket transport buffer Found in: Component config > TCP Transport > Websocket > CONFIG_WS_TRANSPORT If enable this option, websocket transport buffer will be freed after connection succeed to save more heap. Default value: No (disabled) Ultra Low Power (ULP) Co-processor Contains: CONFIG_ULP_COPROC_ENABLED Enable Ultra Low Power (ULP) Co-processor Found in: Component config > Ultra Low Power (ULP) Co-processor Enable this feature if you plan to use the ULP Co-processor. Once this option is enabled, further ULP co-processor configuration will appear in the menu. Default value: No (disabled) CONFIG_ULP_COPROC_TYPE ULP Co-processor type Found in: Component config > Ultra Low Power (ULP) Co-processor > CONFIG_ULP_COPROC_ENABLED Choose the ULP Coprocessor type: ULP FSM (Finite State Machine) or ULP RISC-V. Available options: ULP FSM (Finite State Machine) (CONFIG_ULP_COPROC_TYPE_FSM) ULP RISC-V (CONFIG_ULP_COPROC_TYPE_RISCV) LP core RISC-V (CONFIG_ULP_COPROC_TYPE_LP_CORE) CONFIG_ULP_COPROC_RESERVE_MEM RTC slow memory reserved for coprocessor Found in: Component config > Ultra Low Power (ULP) Co-processor > CONFIG_ULP_COPROC_ENABLED Bytes of memory to reserve for ULP Co-processor firmware & data. Data is reserved at the beginning of RTC slow memory. Range: from 32 to 8176 if CONFIG_ULP_COPROC_ENABLED Default value: 512 if CONFIG_ULP_COPROC_ENABLED ULP RISC-V Settings Contains: CONFIG_ULP_RISCV_UART_BAUDRATE Baudrate used by the bitbanged ULP RISC-V UART driver Found in: Component config > Ultra Low Power (ULP) Co-processor > ULP RISC-V Settings The accuracy of the bitbanged UART driver is limited, it is not recommend to increase the value above 19200. Default value: 9600 if CONFIG_ULP_COPROC_TYPE_RISCV CONFIG_ULP_RISCV_I2C_RW_TIMEOUT Set timeout for ULP RISC-V I2C transaction timeout in ticks. Found in: Component config > Ultra Low Power (ULP) Co-processor > ULP RISC-V Settings Set the ULP RISC-V I2C read/write timeout. Set this value to -1 if the ULP RISC-V I2C read and write APIs should wait forever. Please note that the tick rate of the ULP co-processor would be different than the OS tick rate of the main core and therefore can have different timeout value depending on which core the API is invoked on. Range: from -1 to 4294967295 if CONFIG_ULP_COPROC_TYPE_RISCV Default value: 500 if CONFIG_ULP_COPROC_TYPE_RISCV Unity unit testing library Contains: CONFIG_UNITY_ENABLE_FLOAT Support for float type Found in: Component config > Unity unit testing library If not set, assertions on float arguments will not be available. Default value: Yes (enabled) CONFIG_UNITY_ENABLE_DOUBLE Support for double type Found in: Component config > Unity unit testing library If not set, assertions on double arguments will not be available. Default value: Yes (enabled) CONFIG_UNITY_ENABLE_64BIT Support for 64-bit integer types Found in: Component config > Unity unit testing library If not set, assertions on 64-bit integer types will always fail. If this feature is enabled, take care not to pass pointers (which are 32 bit) to UNITY_ASSERT_EQUAL, as that will cause pointer-to-int-cast warnings. Default value: No (disabled) CONFIG_UNITY_ENABLE_COLOR Colorize test output Found in: Component config > Unity unit testing library If set, Unity will colorize test results using console escape sequences. Default value: No (disabled) CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER Include ESP-IDF test registration/running helpers Found in: Component config > Unity unit testing library If set, then the following features will be available: TEST_CASE macro which performs automatic registration of test functions Functions to run registered test functions: unity_run_all_tests, unity_run_tests_with_filter, unity_run_single_test_by_name. Interactive menu which lists test cases and allows choosing the tests to be run, available via unity_run_menu function. Disable if a different test registration mechanism is used. Default value: Yes (enabled) CONFIG_UNITY_ENABLE_FIXTURE Include Unity test fixture Found in: Component config > Unity unit testing library If set, unity_fixture.h header file and associated source files are part of the build. These provide an optional set of macros and functions to implement test groups. Default value: No (disabled) CONFIG_UNITY_ENABLE_BACKTRACE_ON_FAIL Print a backtrace when a unit test fails Found in: Component config > Unity unit testing library If set, the unity framework will print the backtrace information before jumping back to the test menu. The jumping is usually occurs in assert functions such as TEST_ASSERT, TEST_FAIL etc. Default value: No (disabled) USB-OTG Contains: CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE Largest size (in bytes) of transfers to/from default endpoints Found in: Component config > USB-OTG Each USB device attached is allocated a dedicated buffer for its OUT/IN transfers to/from the device's control endpoint. The maximum size of that buffer is determined by this option. The limited size of the transfer buffer have the following implications: - The maximum length of control transfers is limited - Device's with configuration descriptors larger than this limit cannot be supported Default value: 256 if SOC_USB_OTG_SUPPORTED CONFIG_USB_HOST_HW_BUFFER_BIAS Hardware FIFO size biasing Found in: Component config > USB-OTG The underlying hardware has size adjustable FIFOs to cache USB packets on reception (IN) or for transmission (OUT). The size of these FIFOs will affect the largest MPS (maximum packet size) and the maximum number of packets that can be cached at any one time. The hardware contains the following FIFOS: RX (for all IN packets), Non-periodic TX (for Bulk and Control OUT packets), and Periodic TX (for Interrupt and Isochronous OUT packets). This configuration option allows biasing the FIFO sizes towards a particular use case, which may be necessary for devices that have endpoints with large MPS. The MPS limits for each biasing are listed below: Balanced: - IN (all transfer types), 408 bytes - OUT non-periodic (Bulk/Control), 192 bytes (i.e., 3 x 64 byte packets) - OUT periodic (Interrupt/Isochronous), 192 bytes Bias IN: - IN (all transfer types), 600 bytes - OUT non-periodic (Bulk/Control), 64 bytes (i.e., 1 x 64 byte packets) - OUT periodic (Interrupt/Isochronous), 128 bytes Bias Periodic OUT: - IN (all transfer types), 128 bytes - OUT non-periodic (Bulk/Control), 64 bytes (i.e., 1 x 64 byte packets) - OUT periodic (Interrupt/Isochronous), 600 bytes Available options: Balanced (CONFIG_USB_HOST_HW_BUFFER_BIAS_BALANCED) Bias IN (CONFIG_USB_HOST_HW_BUFFER_BIAS_IN) Periodic OUT (CONFIG_USB_HOST_HW_BUFFER_BIAS_PERIODIC_OUT) Root Hub configuration Contains: CONFIG_USB_HOST_DEBOUNCE_DELAY_MS Debounce delay in ms Found in: Component config > USB-OTG > Root Hub configuration On connection of a USB device, the USB 2.0 specification requires a "debounce interval with a minimum duration of 100ms" to allow the connection to stabilize (see USB 2.0 chapter 7.1.7.3 for more details). During the debounce interval, no new connection/disconnection events are registered. The default value is set to 250 ms to be safe. Default value: 250 if SOC_USB_OTG_SUPPORTED CONFIG_USB_HOST_RESET_HOLD_MS Reset hold in ms Found in: Component config > USB-OTG > Root Hub configuration The reset signaling can be generated on any Hub or Host Controller port by request from the USB System Software. The USB 2.0 specification requires that "the reset signaling must be driven for a minimum of 10ms" (see USB 2.0 chapter 7.1.7.5 for more details). After the reset, the hub port will transition to the Enabled state (refer to Section 11.5). The default value is set to 30 ms to be safe. Default value: 30 if SOC_USB_OTG_SUPPORTED CONFIG_USB_HOST_RESET_RECOVERY_MS Reset recovery delay in ms Found in: Component config > USB-OTG > Root Hub configuration After a port stops driving the reset signal, the USB 2.0 specification requires that the "USB System Software guarantees a minimum of 10 ms for reset recovery" before the attached device is expected to respond to data transfers (see USB 2.0 chapter 7.1.7.3 for more details). The device may ignore any data transfers during the recovery interval. The default value is set to 30 ms to be safe. Default value: 30 if SOC_USB_OTG_SUPPORTED CONFIG_USB_HOST_SET_ADDR_RECOVERY_MS SetAddress() recovery time in ms Found in: Component config > USB-OTG > Root Hub configuration "After successful completion of the Status stage, the device is allowed a SetAddress() recovery interval of 2 ms. At the end of this interval, the device must be able to accept Setup packets addressed to the new address. Also, at the end of the recovery interval, the device must not respond to tokens sent to the old address (unless, of course, the old and new address is the same)." See USB 2.0 chapter 9.2.6.3 for more details. The default value is set to 10 ms to be safe. Default value: 10 if SOC_USB_OTG_SUPPORTED CONFIG_USB_HOST_ENABLE_ENUM_FILTER_CALLBACK Enable enumeration filter callback Found in: Component config > USB-OTG The enumeration filter callback is called before enumeration of each newly attached device. This callback allows users to control whether a device should be enumerated, and what configuration number to use when enumerating a device. If enabled, the enumeration filter callback can be set via 'usb_host_config_t' when calling 'usb_host_install()'. Default value: No (disabled) if SOC_USB_OTG_SUPPORTED Virtual file system Contains: CONFIG_VFS_SUPPORT_IO Provide basic I/O functions Found in: Component config > Virtual file system If enabled, the following functions are provided by the VFS component. open, close, read, write, pread, pwrite, lseek, fstat, fsync, ioctl, fcntl Filesystem drivers can then be registered to handle these functions for specific paths. Disabling this option can save memory when the support for these functions is not required. Note that the following functions can still be used with socket file descriptors when this option is disabled: close, read, write, ioctl, fcntl. Default value: Yes (enabled) CONFIG_VFS_SUPPORT_DIR Provide directory related functions Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO If enabled, the following functions are provided by the VFS component. stat, link, unlink, rename, utime, access, truncate, rmdir, mkdir, opendir, closedir, readdir, readdir_r, seekdir, telldir, rewinddir Filesystem drivers can then be registered to handle these functions for specific paths. Disabling this option can save memory when the support for these functions is not required. Default value: Yes (enabled) CONFIG_VFS_SUPPORT_SELECT Provide select function Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO If enabled, select function is provided by the VFS component, and can be used on peripheral file descriptors (such as UART) and sockets at the same time. If disabled, the default select implementation will be provided by LWIP for sockets only. Disabling this option can reduce code size if support for "select" on UART file descriptors is not required. CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT Suppress select() related debug outputs Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO > CONFIG_VFS_SUPPORT_SELECT Select() related functions might produce an unconveniently lot of debug outputs when one sets the default log level to DEBUG or higher. It is possible to suppress these debug outputs by enabling this option. Default value: Yes (enabled) CONFIG_VFS_SELECT_IN_RAM Make VFS driver select() callbacks IRAM-safe Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO > CONFIG_VFS_SUPPORT_SELECT If enabled, VFS driver select() callback function will be placed in IRAM. Default value: No (disabled) CONFIG_VFS_SUPPORT_TERMIOS Provide termios.h functions Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO Disabling this option can save memory when the support for termios.h is not required. Default value: Yes (enabled) CONFIG_VFS_MAX_COUNT Maximum Number of Virtual Filesystems Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO Define maximum number of virtual filesystems that can be registered. Range: from 1 to 20 Default value: 8 Host File System I/O (Semihosting) Contains: CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS Host FS: Maximum number of the host filesystem mount points Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO > Host File System I/O (Semihosting) Define maximum number of host filesystem mount points. Default value: 1 Wear Levelling Contains: CONFIG_WL_SECTOR_SIZE Wear Levelling library sector size Found in: Component config > Wear Levelling Sector size used by wear levelling library. You can set default sector size or size that will fit to the flash device sector size. With sector size set to 4096 bytes, wear levelling library is more efficient. However if FAT filesystem is used on top of wear levelling library, it will need more temporary storage: 4096 bytes for each mounted filesystem and 4096 bytes for each opened file. With sector size set to 512 bytes, wear levelling library will perform more operations with flash memory, but less RAM will be used by FAT filesystem library (512 bytes for the filesystem and 512 bytes for each file opened). Available options: 512 (CONFIG_WL_SECTOR_SIZE_512) 4096 (CONFIG_WL_SECTOR_SIZE_4096) CONFIG_WL_SECTOR_MODE Sector store mode Found in: Component config > Wear Levelling Specify the mode to store data into flash: In Performance mode a data will be stored to the RAM and then stored back to the flash. Compared to the Safety mode, this operation is faster, but if power will be lost when erase sector operation is in progress, then the data from complete flash device sector will be lost. In Safety mode data from complete flash device sector will be read from flash, modified, and then stored back to flash. Compared to the Performance mode, this operation is slower, but if power is lost during erase sector operation, then the data from full flash device sector will not be lost. Available options: Perfomance (CONFIG_WL_SECTOR_MODE_PERF) Safety (CONFIG_WL_SECTOR_MODE_SAFE) Wi-Fi Provisioning Manager Contains: CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES Max Wi-Fi Scan Result Entries Found in: Component config > Wi-Fi Provisioning Manager This sets the maximum number of entries of Wi-Fi scan results that will be kept by the provisioning manager Range: from 1 to 255 Default value: 16 CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT Provisioning auto-stop timeout Found in: Component config > Wi-Fi Provisioning Manager Time (in seconds) after which the Wi-Fi provisioning manager will auto-stop after connecting to a Wi-Fi network successfully. Range: from 5 to 600 Default value: 30 CONFIG_WIFI_PROV_BLE_BONDING Enable BLE bonding Found in: Component config > Wi-Fi Provisioning Manager This option is applicable only when provisioning transport is BLE. CONFIG_WIFI_PROV_BLE_SEC_CONN Enable BLE Secure connection flag Found in: Component config > Wi-Fi Provisioning Manager Used to enable Secure connection support when provisioning transport is BLE. Default value: Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED CONFIG_WIFI_PROV_BLE_FORCE_ENCRYPTION Force Link Encryption during characteristic Read / Write Found in: Component config > Wi-Fi Provisioning Manager Used to enforce link encryption when attempting to read / write characteristic CONFIG_WIFI_PROV_KEEP_BLE_ON_AFTER_PROV Keep BT on after provisioning is done Found in: Component config > Wi-Fi Provisioning Manager CONFIG_WIFI_PROV_DISCONNECT_AFTER_PROV Terminate connection after provisioning is done Found in: Component config > Wi-Fi Provisioning Manager > CONFIG_WIFI_PROV_KEEP_BLE_ON_AFTER_PROV Default value: Yes (enabled) if CONFIG_WIFI_PROV_KEEP_BLE_ON_AFTER_PROV CONFIG_WIFI_PROV_STA_SCAN_METHOD Wifi Provisioning Scan Method Found in: Component config > Wi-Fi Provisioning Manager Available options: All Channel Scan (CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN) Scan will end after scanning the entire channel. This option is useful in Mesh WiFi Systems. Fast Scan (CONFIG_WIFI_PROV_STA_FAST_SCAN) Scan will end after an AP matching with the SSID has been detected. CONFIG_IDF_EXPERIMENTAL_FEATURES Make experimental features visible Found in: By enabling this option, ESP-IDF experimental feature options will be visible. Note you should still enable a certain experimental feature option to use it, and you should read the corresponding risk warning and known issue list carefully. Current experimental feature list: CONFIG_ESPTOOLPY_FLASHFREQ_120M && CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_DTR CONFIG_SPIRAM_SPEED_120M && CONFIG_SPIRAM_MODE_OCT CONFIG_BOOTLOADER_CACHE_32BIT_ADDR_QUAD_FLASH CONFIG_MBEDTLS_USE_CRYPTO_ROM_IMPL Default value: No (disabled) Deprecated options and their replacements CONFIG_A2DP_ENABLE (CONFIG_BT_A2DP_ENABLE) CONFIG_A2D_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_A2D_TRACE_LEVEL) CONFIG_A2D_TRACE_LEVEL_NONE CONFIG_A2D_TRACE_LEVEL_ERROR CONFIG_A2D_TRACE_LEVEL_WARNING CONFIG_A2D_TRACE_LEVEL_API CONFIG_A2D_TRACE_LEVEL_EVENT CONFIG_A2D_TRACE_LEVEL_DEBUG CONFIG_A2D_TRACE_LEVEL_VERBOSE CONFIG_A2D_TRACE_LEVEL_NONE CONFIG_A2D_TRACE_LEVEL_ERROR CONFIG_A2D_TRACE_LEVEL_WARNING CONFIG_A2D_TRACE_LEVEL_API CONFIG_A2D_TRACE_LEVEL_EVENT CONFIG_A2D_TRACE_LEVEL_DEBUG CONFIG_A2D_TRACE_LEVEL_VERBOSE CONFIG_A2D_TRACE_LEVEL_NONE CONFIG_A2D_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_A2D_TRACE_LEVEL) CONFIG_A2D_TRACE_LEVEL_NONE CONFIG_A2D_TRACE_LEVEL_ERROR CONFIG_A2D_TRACE_LEVEL_WARNING CONFIG_A2D_TRACE_LEVEL_API CONFIG_A2D_TRACE_LEVEL_EVENT CONFIG_A2D_TRACE_LEVEL_DEBUG CONFIG_A2D_TRACE_LEVEL_VERBOSE CONFIG_ADC2_DISABLE_DAC (CONFIG_ADC_DISABLE_DAC) CONFIG_APPL_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_APPL_TRACE_LEVEL) CONFIG_APPL_TRACE_LEVEL_NONE CONFIG_APPL_TRACE_LEVEL_ERROR CONFIG_APPL_TRACE_LEVEL_WARNING CONFIG_APPL_TRACE_LEVEL_API CONFIG_APPL_TRACE_LEVEL_EVENT CONFIG_APPL_TRACE_LEVEL_DEBUG CONFIG_APPL_TRACE_LEVEL_VERBOSE CONFIG_APPL_TRACE_LEVEL_NONE CONFIG_APPL_TRACE_LEVEL_ERROR CONFIG_APPL_TRACE_LEVEL_WARNING CONFIG_APPL_TRACE_LEVEL_API CONFIG_APPL_TRACE_LEVEL_EVENT CONFIG_APPL_TRACE_LEVEL_DEBUG CONFIG_APPL_TRACE_LEVEL_VERBOSE CONFIG_APPL_TRACE_LEVEL_NONE CONFIG_APPL_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_APPL_TRACE_LEVEL) CONFIG_APPL_TRACE_LEVEL_NONE CONFIG_APPL_TRACE_LEVEL_ERROR CONFIG_APPL_TRACE_LEVEL_WARNING CONFIG_APPL_TRACE_LEVEL_API CONFIG_APPL_TRACE_LEVEL_EVENT CONFIG_APPL_TRACE_LEVEL_DEBUG CONFIG_APPL_TRACE_LEVEL_VERBOSE CONFIG_APP_ANTI_ROLLBACK (CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK) CONFIG_APP_ROLLBACK_ENABLE (CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE) CONFIG_APP_SECURE_VERSION (CONFIG_BOOTLOADER_APP_SECURE_VERSION) CONFIG_APP_SECURE_VERSION_SIZE_EFUSE_FIELD (CONFIG_BOOTLOADER_APP_SEC_VER_SIZE_EFUSE_FIELD) CONFIG_AVCT_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_AVCT_TRACE_LEVEL) CONFIG_AVCT_TRACE_LEVEL_NONE CONFIG_AVCT_TRACE_LEVEL_ERROR CONFIG_AVCT_TRACE_LEVEL_WARNING CONFIG_AVCT_TRACE_LEVEL_API CONFIG_AVCT_TRACE_LEVEL_EVENT CONFIG_AVCT_TRACE_LEVEL_DEBUG CONFIG_AVCT_TRACE_LEVEL_VERBOSE CONFIG_AVCT_TRACE_LEVEL_NONE CONFIG_AVCT_TRACE_LEVEL_ERROR CONFIG_AVCT_TRACE_LEVEL_WARNING CONFIG_AVCT_TRACE_LEVEL_API CONFIG_AVCT_TRACE_LEVEL_EVENT CONFIG_AVCT_TRACE_LEVEL_DEBUG CONFIG_AVCT_TRACE_LEVEL_VERBOSE CONFIG_AVCT_TRACE_LEVEL_NONE CONFIG_AVCT_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_AVCT_TRACE_LEVEL) CONFIG_AVCT_TRACE_LEVEL_NONE CONFIG_AVCT_TRACE_LEVEL_ERROR CONFIG_AVCT_TRACE_LEVEL_WARNING CONFIG_AVCT_TRACE_LEVEL_API CONFIG_AVCT_TRACE_LEVEL_EVENT CONFIG_AVCT_TRACE_LEVEL_DEBUG CONFIG_AVCT_TRACE_LEVEL_VERBOSE CONFIG_AVDT_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_AVDT_TRACE_LEVEL) CONFIG_AVDT_TRACE_LEVEL_NONE CONFIG_AVDT_TRACE_LEVEL_ERROR CONFIG_AVDT_TRACE_LEVEL_WARNING CONFIG_AVDT_TRACE_LEVEL_API CONFIG_AVDT_TRACE_LEVEL_EVENT CONFIG_AVDT_TRACE_LEVEL_DEBUG CONFIG_AVDT_TRACE_LEVEL_VERBOSE CONFIG_AVDT_TRACE_LEVEL_NONE CONFIG_AVDT_TRACE_LEVEL_ERROR CONFIG_AVDT_TRACE_LEVEL_WARNING CONFIG_AVDT_TRACE_LEVEL_API CONFIG_AVDT_TRACE_LEVEL_EVENT CONFIG_AVDT_TRACE_LEVEL_DEBUG CONFIG_AVDT_TRACE_LEVEL_VERBOSE CONFIG_AVDT_TRACE_LEVEL_NONE CONFIG_AVDT_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_AVDT_TRACE_LEVEL) CONFIG_AVDT_TRACE_LEVEL_NONE CONFIG_AVDT_TRACE_LEVEL_ERROR CONFIG_AVDT_TRACE_LEVEL_WARNING CONFIG_AVDT_TRACE_LEVEL_API CONFIG_AVDT_TRACE_LEVEL_EVENT CONFIG_AVDT_TRACE_LEVEL_DEBUG CONFIG_AVDT_TRACE_LEVEL_VERBOSE CONFIG_AVRC_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_AVRC_TRACE_LEVEL) CONFIG_AVRC_TRACE_LEVEL_NONE CONFIG_AVRC_TRACE_LEVEL_ERROR CONFIG_AVRC_TRACE_LEVEL_WARNING CONFIG_AVRC_TRACE_LEVEL_API CONFIG_AVRC_TRACE_LEVEL_EVENT CONFIG_AVRC_TRACE_LEVEL_DEBUG CONFIG_AVRC_TRACE_LEVEL_VERBOSE CONFIG_AVRC_TRACE_LEVEL_NONE CONFIG_AVRC_TRACE_LEVEL_ERROR CONFIG_AVRC_TRACE_LEVEL_WARNING CONFIG_AVRC_TRACE_LEVEL_API CONFIG_AVRC_TRACE_LEVEL_EVENT CONFIG_AVRC_TRACE_LEVEL_DEBUG CONFIG_AVRC_TRACE_LEVEL_VERBOSE CONFIG_AVRC_TRACE_LEVEL_NONE CONFIG_AVRC_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_AVRC_TRACE_LEVEL) CONFIG_AVRC_TRACE_LEVEL_NONE CONFIG_AVRC_TRACE_LEVEL_ERROR CONFIG_AVRC_TRACE_LEVEL_WARNING CONFIG_AVRC_TRACE_LEVEL_API CONFIG_AVRC_TRACE_LEVEL_EVENT CONFIG_AVRC_TRACE_LEVEL_DEBUG CONFIG_AVRC_TRACE_LEVEL_VERBOSE CONFIG_BLE_ACTIVE_SCAN_REPORT_ADV_SCAN_RSP_INDIVIDUALLY (CONFIG_BT_BLE_ACT_SCAN_REP_ADV_SCAN) CONFIG_BLE_ADV_REPORT_DISCARD_THRSHOLD (CONFIG_BTDM_BLE_ADV_REPORT_DISCARD_THRSHOLD) CONFIG_BLE_ADV_REPORT_FLOW_CONTROL_NUM (CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_NUM) CONFIG_BLE_ADV_REPORT_FLOW_CONTROL_SUPPORTED (CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP) CONFIG_BLE_ESTABLISH_LINK_CONNECTION_TIMEOUT (CONFIG_BT_BLE_ESTAB_LINK_CONN_TOUT) CONFIG_BLE_HOST_QUEUE_CONGESTION_CHECK (CONFIG_BT_BLE_HOST_QUEUE_CONG_CHECK) CONFIG_BLE_MESH_GATT_PROXY (CONFIG_BLE_MESH_GATT_PROXY_SERVER) CONFIG_BLE_MESH_SCAN_DUPLICATE_EN (CONFIG_BTDM_BLE_MESH_SCAN_DUPL_EN) CONFIG_BLE_SCAN_DUPLICATE (CONFIG_BTDM_BLE_SCAN_DUPL) CONFIG_BLE_SMP_ENABLE (CONFIG_BT_BLE_SMP_ENABLE) CONFIG_BLUEDROID_MEM_DEBUG (CONFIG_BT_BLUEDROID_MEM_DEBUG) CONFIG_BLUEDROID_PINNED_TO_CORE_CHOICE (CONFIG_BT_BLUEDROID_PINNED_TO_CORE_CHOICE) CONFIG_BLUEDROID_PINNED_TO_CORE_0 CONFIG_BLUEDROID_PINNED_TO_CORE_1 CONFIG_BLUEDROID_PINNED_TO_CORE_0 CONFIG_BLUEDROID_PINNED_TO_CORE_1 CONFIG_BLUEDROID_PINNED_TO_CORE_0 CONFIG_BLUEDROID_PINNED_TO_CORE_CHOICE (CONFIG_BT_BLUEDROID_PINNED_TO_CORE_CHOICE) CONFIG_BLUEDROID_PINNED_TO_CORE_0 CONFIG_BLUEDROID_PINNED_TO_CORE_1 CONFIG_BLUFI_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL) CONFIG_BLUFI_TRACE_LEVEL_NONE CONFIG_BLUFI_TRACE_LEVEL_ERROR CONFIG_BLUFI_TRACE_LEVEL_WARNING CONFIG_BLUFI_TRACE_LEVEL_API CONFIG_BLUFI_TRACE_LEVEL_EVENT CONFIG_BLUFI_TRACE_LEVEL_DEBUG CONFIG_BLUFI_TRACE_LEVEL_VERBOSE CONFIG_BLUFI_TRACE_LEVEL_NONE CONFIG_BLUFI_TRACE_LEVEL_ERROR CONFIG_BLUFI_TRACE_LEVEL_WARNING CONFIG_BLUFI_TRACE_LEVEL_API CONFIG_BLUFI_TRACE_LEVEL_EVENT CONFIG_BLUFI_TRACE_LEVEL_DEBUG CONFIG_BLUFI_TRACE_LEVEL_VERBOSE CONFIG_BLUFI_TRACE_LEVEL_NONE CONFIG_BLUFI_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL) CONFIG_BLUFI_TRACE_LEVEL_NONE CONFIG_BLUFI_TRACE_LEVEL_ERROR CONFIG_BLUFI_TRACE_LEVEL_WARNING CONFIG_BLUFI_TRACE_LEVEL_API CONFIG_BLUFI_TRACE_LEVEL_EVENT CONFIG_BLUFI_TRACE_LEVEL_DEBUG CONFIG_BLUFI_TRACE_LEVEL_VERBOSE CONFIG_BNEP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BNEP_TRACE_LEVEL) CONFIG_BROWNOUT_DET (CONFIG_ESP_BROWNOUT_DET) CONFIG_BROWNOUT_DET_LVL_SEL (CONFIG_ESP_BROWNOUT_DET_LVL_SEL) CONFIG_BROWNOUT_DET_LVL_SEL_0 CONFIG_BROWNOUT_DET_LVL_SEL_1 CONFIG_BROWNOUT_DET_LVL_SEL_2 CONFIG_BROWNOUT_DET_LVL_SEL_3 CONFIG_BROWNOUT_DET_LVL_SEL_4 CONFIG_BROWNOUT_DET_LVL_SEL_5 CONFIG_BROWNOUT_DET_LVL_SEL_6 CONFIG_BROWNOUT_DET_LVL_SEL_7 CONFIG_BROWNOUT_DET_LVL_SEL_0 CONFIG_BROWNOUT_DET_LVL_SEL_1 CONFIG_BROWNOUT_DET_LVL_SEL_2 CONFIG_BROWNOUT_DET_LVL_SEL_3 CONFIG_BROWNOUT_DET_LVL_SEL_4 CONFIG_BROWNOUT_DET_LVL_SEL_5 CONFIG_BROWNOUT_DET_LVL_SEL_6 CONFIG_BROWNOUT_DET_LVL_SEL_7 CONFIG_BROWNOUT_DET_LVL_SEL_0 CONFIG_BROWNOUT_DET_LVL_SEL (CONFIG_ESP_BROWNOUT_DET_LVL_SEL) CONFIG_BROWNOUT_DET_LVL_SEL_0 CONFIG_BROWNOUT_DET_LVL_SEL_1 CONFIG_BROWNOUT_DET_LVL_SEL_2 CONFIG_BROWNOUT_DET_LVL_SEL_3 CONFIG_BROWNOUT_DET_LVL_SEL_4 CONFIG_BROWNOUT_DET_LVL_SEL_5 CONFIG_BROWNOUT_DET_LVL_SEL_6 CONFIG_BROWNOUT_DET_LVL_SEL_7 CONFIG_BTC_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BTC_TRACE_LEVEL) CONFIG_BTC_TRACE_LEVEL_NONE CONFIG_BTC_TRACE_LEVEL_ERROR CONFIG_BTC_TRACE_LEVEL_WARNING CONFIG_BTC_TRACE_LEVEL_API CONFIG_BTC_TRACE_LEVEL_EVENT CONFIG_BTC_TRACE_LEVEL_DEBUG CONFIG_BTC_TRACE_LEVEL_VERBOSE CONFIG_BTC_TRACE_LEVEL_NONE CONFIG_BTC_TRACE_LEVEL_ERROR CONFIG_BTC_TRACE_LEVEL_WARNING CONFIG_BTC_TRACE_LEVEL_API CONFIG_BTC_TRACE_LEVEL_EVENT CONFIG_BTC_TRACE_LEVEL_DEBUG CONFIG_BTC_TRACE_LEVEL_VERBOSE CONFIG_BTC_TRACE_LEVEL_NONE CONFIG_BTC_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BTC_TRACE_LEVEL) CONFIG_BTC_TRACE_LEVEL_NONE CONFIG_BTC_TRACE_LEVEL_ERROR CONFIG_BTC_TRACE_LEVEL_WARNING CONFIG_BTC_TRACE_LEVEL_API CONFIG_BTC_TRACE_LEVEL_EVENT CONFIG_BTC_TRACE_LEVEL_DEBUG CONFIG_BTC_TRACE_LEVEL_VERBOSE CONFIG_BTC_TASK_STACK_SIZE (CONFIG_BT_BTC_TASK_STACK_SIZE) CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN (CONFIG_BTDM_CTRL_BLE_MAX_CONN) CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN (CONFIG_BTDM_CTRL_BR_EDR_MAX_ACL_CONN) CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN (CONFIG_BTDM_CTRL_BR_EDR_MAX_SYNC_CONN) CONFIG_BTDM_CONTROLLER_FULL_SCAN_SUPPORTED (CONFIG_BTDM_CTRL_FULL_SCAN_SUPPORTED) CONFIG_BTDM_CONTROLLER_HCI_MODE_CHOICE (CONFIG_BTDM_CTRL_HCI_MODE_CHOICE) CONFIG_BTDM_CONTROLLER_HCI_MODE_VHCI CONFIG_BTDM_CONTROLLER_HCI_MODE_UART_H4 CONFIG_BTDM_CONTROLLER_HCI_MODE_VHCI CONFIG_BTDM_CONTROLLER_HCI_MODE_UART_H4 CONFIG_BTDM_CONTROLLER_HCI_MODE_VHCI CONFIG_BTDM_CONTROLLER_HCI_MODE_CHOICE (CONFIG_BTDM_CTRL_HCI_MODE_CHOICE) CONFIG_BTDM_CONTROLLER_HCI_MODE_VHCI CONFIG_BTDM_CONTROLLER_HCI_MODE_UART_H4 CONFIG_BTDM_CONTROLLER_MODE (CONFIG_BTDM_CTRL_MODE) CONFIG_BTDM_CONTROLLER_MODE_BLE_ONLY CONFIG_BTDM_CONTROLLER_MODE_BR_EDR_ONLY CONFIG_BTDM_CONTROLLER_MODE_BTDM CONFIG_BTDM_CONTROLLER_MODE_BLE_ONLY CONFIG_BTDM_CONTROLLER_MODE_BR_EDR_ONLY CONFIG_BTDM_CONTROLLER_MODE_BTDM CONFIG_BTDM_CONTROLLER_MODE_BLE_ONLY CONFIG_BTDM_CONTROLLER_MODE (CONFIG_BTDM_CTRL_MODE) CONFIG_BTDM_CONTROLLER_MODE_BLE_ONLY CONFIG_BTDM_CONTROLLER_MODE_BR_EDR_ONLY CONFIG_BTDM_CONTROLLER_MODE_BTDM CONFIG_BTDM_CONTROLLER_MODEM_SLEEP (CONFIG_BTDM_CTRL_MODEM_SLEEP) CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE_CHOICE (CONFIG_BTDM_CTRL_PINNED_TO_CORE_CHOICE) CONFIG_BTH_LOG_SDP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_SDP_TRACE_LEVEL) CONFIG_SDP_TRACE_LEVEL_NONE CONFIG_SDP_TRACE_LEVEL_ERROR CONFIG_SDP_TRACE_LEVEL_WARNING CONFIG_SDP_TRACE_LEVEL_API CONFIG_SDP_TRACE_LEVEL_EVENT CONFIG_SDP_TRACE_LEVEL_DEBUG CONFIG_SDP_TRACE_LEVEL_VERBOSE CONFIG_SDP_TRACE_LEVEL_NONE CONFIG_SDP_TRACE_LEVEL_ERROR CONFIG_SDP_TRACE_LEVEL_WARNING CONFIG_SDP_TRACE_LEVEL_API CONFIG_SDP_TRACE_LEVEL_EVENT CONFIG_SDP_TRACE_LEVEL_DEBUG CONFIG_SDP_TRACE_LEVEL_VERBOSE CONFIG_SDP_TRACE_LEVEL_NONE CONFIG_BTH_LOG_SDP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_SDP_TRACE_LEVEL) CONFIG_SDP_TRACE_LEVEL_NONE CONFIG_SDP_TRACE_LEVEL_ERROR CONFIG_SDP_TRACE_LEVEL_WARNING CONFIG_SDP_TRACE_LEVEL_API CONFIG_SDP_TRACE_LEVEL_EVENT CONFIG_SDP_TRACE_LEVEL_DEBUG CONFIG_SDP_TRACE_LEVEL_VERBOSE CONFIG_BTIF_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BTIF_TRACE_LEVEL) CONFIG_BTIF_TRACE_LEVEL_NONE CONFIG_BTIF_TRACE_LEVEL_ERROR CONFIG_BTIF_TRACE_LEVEL_WARNING CONFIG_BTIF_TRACE_LEVEL_API CONFIG_BTIF_TRACE_LEVEL_EVENT CONFIG_BTIF_TRACE_LEVEL_DEBUG CONFIG_BTIF_TRACE_LEVEL_VERBOSE CONFIG_BTIF_TRACE_LEVEL_NONE CONFIG_BTIF_TRACE_LEVEL_ERROR CONFIG_BTIF_TRACE_LEVEL_WARNING CONFIG_BTIF_TRACE_LEVEL_API CONFIG_BTIF_TRACE_LEVEL_EVENT CONFIG_BTIF_TRACE_LEVEL_DEBUG CONFIG_BTIF_TRACE_LEVEL_VERBOSE CONFIG_BTIF_TRACE_LEVEL_NONE CONFIG_BTIF_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BTIF_TRACE_LEVEL) CONFIG_BTIF_TRACE_LEVEL_NONE CONFIG_BTIF_TRACE_LEVEL_ERROR CONFIG_BTIF_TRACE_LEVEL_WARNING CONFIG_BTIF_TRACE_LEVEL_API CONFIG_BTIF_TRACE_LEVEL_EVENT CONFIG_BTIF_TRACE_LEVEL_DEBUG CONFIG_BTIF_TRACE_LEVEL_VERBOSE CONFIG_BTM_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BTM_TRACE_LEVEL) CONFIG_BTM_TRACE_LEVEL_NONE CONFIG_BTM_TRACE_LEVEL_ERROR CONFIG_BTM_TRACE_LEVEL_WARNING CONFIG_BTM_TRACE_LEVEL_API CONFIG_BTM_TRACE_LEVEL_EVENT CONFIG_BTM_TRACE_LEVEL_DEBUG CONFIG_BTM_TRACE_LEVEL_VERBOSE CONFIG_BTM_TRACE_LEVEL_NONE CONFIG_BTM_TRACE_LEVEL_ERROR CONFIG_BTM_TRACE_LEVEL_WARNING CONFIG_BTM_TRACE_LEVEL_API CONFIG_BTM_TRACE_LEVEL_EVENT CONFIG_BTM_TRACE_LEVEL_DEBUG CONFIG_BTM_TRACE_LEVEL_VERBOSE CONFIG_BTM_TRACE_LEVEL_NONE CONFIG_BTM_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BTM_TRACE_LEVEL) CONFIG_BTM_TRACE_LEVEL_NONE CONFIG_BTM_TRACE_LEVEL_ERROR CONFIG_BTM_TRACE_LEVEL_WARNING CONFIG_BTM_TRACE_LEVEL_API CONFIG_BTM_TRACE_LEVEL_EVENT CONFIG_BTM_TRACE_LEVEL_DEBUG CONFIG_BTM_TRACE_LEVEL_VERBOSE CONFIG_BTU_TASK_STACK_SIZE (CONFIG_BT_BTU_TASK_STACK_SIZE) CONFIG_BT_NIMBLE_ACL_BUF_COUNT (CONFIG_BT_NIMBLE_TRANSPORT_ACL_FROM_LL_COUNT) CONFIG_BT_NIMBLE_ACL_BUF_SIZE (CONFIG_BT_NIMBLE_TRANSPORT_ACL_SIZE) CONFIG_BT_NIMBLE_HCI_EVT_BUF_SIZE (CONFIG_BT_NIMBLE_TRANSPORT_EVT_SIZE) CONFIG_BT_NIMBLE_HCI_EVT_HI_BUF_COUNT (CONFIG_BT_NIMBLE_TRANSPORT_EVT_COUNT) CONFIG_BT_NIMBLE_HCI_EVT_LO_BUF_COUNT (CONFIG_BT_NIMBLE_TRANSPORT_EVT_DISCARD_COUNT) CONFIG_BT_NIMBLE_MSYS1_BLOCK_COUNT (CONFIG_BT_NIMBLE_MSYS_1_BLOCK_COUNT) CONFIG_BT_NIMBLE_TASK_STACK_SIZE (CONFIG_BT_NIMBLE_HOST_TASK_STACK_SIZE) CONFIG_CLASSIC_BT_ENABLED (CONFIG_BT_CLASSIC_ENABLED) CONFIG_CONSOLE_UART (CONFIG_ESP_CONSOLE_UART) CONFIG_CONSOLE_UART_DEFAULT CONFIG_CONSOLE_UART_CUSTOM CONFIG_CONSOLE_UART_NONE, CONFIG_ESP_CONSOLE_UART_NONE CONFIG_CONSOLE_UART_DEFAULT CONFIG_CONSOLE_UART_CUSTOM CONFIG_CONSOLE_UART_NONE, CONFIG_ESP_CONSOLE_UART_NONE CONFIG_CONSOLE_UART_DEFAULT CONFIG_CONSOLE_UART (CONFIG_ESP_CONSOLE_UART) CONFIG_CONSOLE_UART_DEFAULT CONFIG_CONSOLE_UART_CUSTOM CONFIG_CONSOLE_UART_NONE, CONFIG_ESP_CONSOLE_UART_NONE CONFIG_CONSOLE_UART_BAUDRATE (CONFIG_ESP_CONSOLE_UART_BAUDRATE) CONFIG_CONSOLE_UART_NUM (CONFIG_ESP_CONSOLE_UART_NUM) CONFIG_CONSOLE_UART_CUSTOM_NUM_0 CONFIG_CONSOLE_UART_CUSTOM_NUM_1 CONFIG_CONSOLE_UART_CUSTOM_NUM_0 CONFIG_CONSOLE_UART_CUSTOM_NUM_1 CONFIG_CONSOLE_UART_CUSTOM_NUM_0 CONFIG_CONSOLE_UART_NUM (CONFIG_ESP_CONSOLE_UART_NUM) CONFIG_CONSOLE_UART_CUSTOM_NUM_0 CONFIG_CONSOLE_UART_CUSTOM_NUM_1 CONFIG_CONSOLE_UART_RX_GPIO (CONFIG_ESP_CONSOLE_UART_RX_GPIO) CONFIG_CONSOLE_UART_TX_GPIO (CONFIG_ESP_CONSOLE_UART_TX_GPIO) CONFIG_CXX_EXCEPTIONS (CONFIG_COMPILER_CXX_EXCEPTIONS) CONFIG_CXX_EXCEPTIONS_EMG_POOL_SIZE (CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE) CONFIG_DUPLICATE_SCAN_CACHE_SIZE (CONFIG_BTDM_SCAN_DUPL_CACHE_SIZE) CONFIG_EFUSE_SECURE_VERSION_EMULATE (CONFIG_BOOTLOADER_EFUSE_SECURE_VERSION_EMULATE) CONFIG_ENABLE_STATIC_TASK_CLEAN_UP_HOOK (CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP) CONFIG_ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TMO (CONFIG_APPTRACE_ONPANIC_HOST_FLUSH_TMO) CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX (CONFIG_APPTRACE_PENDING_DATA_SIZE_MAX) CONFIG_ESP32_APPTRACE_POSTMORTEM_FLUSH_TRAX_THRESH (CONFIG_APPTRACE_POSTMORTEM_FLUSH_THRESH) CONFIG_ESP32_COMPATIBLE_PRE_V2_1_BOOTLOADERS (CONFIG_APP_COMPATIBLE_PRE_V2_1_BOOTLOADERS) CONFIG_ESP32_COMPATIBLE_PRE_V3_1_BOOTLOADERS (CONFIG_APP_COMPATIBLE_PRE_V3_1_BOOTLOADERS) CONFIG_ESP32_CORE_DUMP_DECODE (CONFIG_ESP_COREDUMP_DECODE) CONFIG_ESP32_CORE_DUMP_DECODE_INFO CONFIG_ESP32_CORE_DUMP_DECODE_DISABLE CONFIG_ESP32_CORE_DUMP_DECODE_INFO CONFIG_ESP32_CORE_DUMP_DECODE_DISABLE CONFIG_ESP32_CORE_DUMP_DECODE_INFO CONFIG_ESP32_CORE_DUMP_DECODE (CONFIG_ESP_COREDUMP_DECODE) CONFIG_ESP32_CORE_DUMP_DECODE_INFO CONFIG_ESP32_CORE_DUMP_DECODE_DISABLE CONFIG_ESP32_CORE_DUMP_MAX_TASKS_NUM (CONFIG_ESP_COREDUMP_MAX_TASKS_NUM) CONFIG_ESP32_CORE_DUMP_STACK_SIZE (CONFIG_ESP_COREDUMP_STACK_SIZE) CONFIG_ESP32_CORE_DUMP_UART_DELAY (CONFIG_ESP_COREDUMP_UART_DELAY) CONFIG_ESP32_DEBUG_STUBS_ENABLE (CONFIG_ESP_DEBUG_STUBS_ENABLE) CONFIG_ESP32_GCOV_ENABLE (CONFIG_APPTRACE_GCOV_ENABLE) CONFIG_ESP32_PHY_CALIBRATION_AND_DATA_STORAGE (CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE) CONFIG_ESP32_PHY_DEFAULT_INIT_IF_INVALID (CONFIG_ESP_PHY_DEFAULT_INIT_IF_INVALID) CONFIG_ESP32_PHY_INIT_DATA_ERROR (CONFIG_ESP_PHY_INIT_DATA_ERROR) CONFIG_ESP32_PHY_INIT_DATA_IN_PARTITION (CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION) CONFIG_ESP32_PHY_MAC_BB_PD (CONFIG_ESP_PHY_MAC_BB_PD) CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER (CONFIG_ESP_PHY_MAX_WIFI_TX_POWER) CONFIG_ESP32_PTHREAD_STACK_MIN (CONFIG_PTHREAD_STACK_MIN) CONFIG_ESP32_PTHREAD_TASK_CORE_DEFAULT (CONFIG_PTHREAD_TASK_CORE_DEFAULT) CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY CONFIG_ESP32_DEFAULT_PTHREAD_CORE_0 CONFIG_ESP32_DEFAULT_PTHREAD_CORE_1 CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY CONFIG_ESP32_DEFAULT_PTHREAD_CORE_0 CONFIG_ESP32_DEFAULT_PTHREAD_CORE_1 CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY CONFIG_ESP32_PTHREAD_TASK_CORE_DEFAULT (CONFIG_PTHREAD_TASK_CORE_DEFAULT) CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY CONFIG_ESP32_DEFAULT_PTHREAD_CORE_0 CONFIG_ESP32_DEFAULT_PTHREAD_CORE_1 CONFIG_ESP32_PTHREAD_TASK_NAME_DEFAULT (CONFIG_PTHREAD_TASK_NAME_DEFAULT) CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT (CONFIG_PTHREAD_TASK_PRIO_DEFAULT) CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT (CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT) CONFIG_ESP32_REDUCE_PHY_TX_POWER (CONFIG_ESP_PHY_REDUCE_TX_POWER) CONFIG_ESP32_RTC_XTAL_BOOTSTRAP_CYCLES (CONFIG_ESP_SYSTEM_RTC_EXT_XTAL_BOOTSTRAP_CYCLES) CONFIG_ESP32_SUPPORT_MULTIPLE_PHY_INIT_DATA_BIN (CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN) CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED (CONFIG_ESP_WIFI_AMPDU_RX_ENABLED) CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED (CONFIG_ESP_WIFI_AMPDU_TX_ENABLED) CONFIG_ESP32_WIFI_AMSDU_TX_ENABLED (CONFIG_ESP_WIFI_AMSDU_TX_ENABLED) CONFIG_ESP32_WIFI_CACHE_TX_BUFFER_NUM (CONFIG_ESP_WIFI_CACHE_TX_BUFFER_NUM) CONFIG_ESP32_WIFI_CSI_ENABLED (CONFIG_ESP_WIFI_CSI_ENABLED) CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM (CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM) CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM (CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM) CONFIG_ESP32_WIFI_ENABLE_WPA3_OWE_STA (CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA) CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE (CONFIG_ESP_WIFI_ENABLE_WPA3_SAE) CONFIG_ESP32_WIFI_IRAM_OPT (CONFIG_ESP_WIFI_IRAM_OPT) CONFIG_ESP32_WIFI_MGMT_SBUF_NUM (CONFIG_ESP_WIFI_MGMT_SBUF_NUM) CONFIG_ESP32_WIFI_NVS_ENABLED (CONFIG_ESP_WIFI_NVS_ENABLED) CONFIG_ESP32_WIFI_RX_BA_WIN (CONFIG_ESP_WIFI_RX_BA_WIN) CONFIG_ESP32_WIFI_RX_IRAM_OPT (CONFIG_ESP_WIFI_RX_IRAM_OPT) CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN (CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN) CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM (CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM) CONFIG_ESP32_WIFI_STATIC_TX_BUFFER_NUM (CONFIG_ESP_WIFI_STATIC_TX_BUFFER_NUM) CONFIG_ESP32_WIFI_SW_COEXIST_ENABLE (CONFIG_ESP_COEX_SW_COEXIST_ENABLE) CONFIG_ESP32_WIFI_TASK_CORE_ID (CONFIG_ESP_WIFI_TASK_CORE_ID) CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0 CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1 CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0 CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1 CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0 CONFIG_ESP32_WIFI_TASK_CORE_ID (CONFIG_ESP_WIFI_TASK_CORE_ID) CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0 CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1 CONFIG_ESP32_WIFI_TX_BA_WIN (CONFIG_ESP_WIFI_TX_BA_WIN) CONFIG_ESP32_WIFI_TX_BUFFER (CONFIG_ESP_WIFI_TX_BUFFER) CONFIG_ESP32_WIFI_STATIC_TX_BUFFER CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER CONFIG_ESP32_WIFI_STATIC_TX_BUFFER CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER CONFIG_ESP32_WIFI_STATIC_TX_BUFFER CONFIG_ESP32_WIFI_TX_BUFFER (CONFIG_ESP_WIFI_TX_BUFFER) CONFIG_ESP32_WIFI_STATIC_TX_BUFFER CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER CONFIG_ESP_GRATUITOUS_ARP (CONFIG_LWIP_ESP_GRATUITOUS_ARP) CONFIG_ESP_SYSTEM_PD_FLASH (CONFIG_ESP_SLEEP_POWER_DOWN_FLASH) CONFIG_ESP_SYSTEM_PM_POWER_DOWN_CPU (CONFIG_PM_POWER_DOWN_CPU_IN_LIGHT_SLEEP) CONFIG_ESP_TASK_WDT (CONFIG_ESP_TASK_WDT_INIT) CONFIG_ESP_WIFI_SW_COEXIST_ENABLE (CONFIG_ESP_COEX_SW_COEXIST_ENABLE) CONFIG_EVENT_LOOP_PROFILING (CONFIG_ESP_EVENT_LOOP_PROFILING) CONFIG_FLASH_ENCRYPTION_ENABLED (CONFIG_SECURE_FLASH_ENC_ENABLED) CONFIG_FLASH_ENCRYPTION_UART_BOOTLOADER_ALLOW_CACHE (CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_CACHE) CONFIG_FLASH_ENCRYPTION_UART_BOOTLOADER_ALLOW_DECRYPT (CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_DEC) CONFIG_FLASH_ENCRYPTION_UART_BOOTLOADER_ALLOW_ENCRYPT (CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_ENC) CONFIG_GAP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_GAP_TRACE_LEVEL) CONFIG_GAP_TRACE_LEVEL_NONE CONFIG_GAP_TRACE_LEVEL_ERROR CONFIG_GAP_TRACE_LEVEL_WARNING CONFIG_GAP_TRACE_LEVEL_API CONFIG_GAP_TRACE_LEVEL_EVENT CONFIG_GAP_TRACE_LEVEL_DEBUG CONFIG_GAP_TRACE_LEVEL_VERBOSE CONFIG_GAP_TRACE_LEVEL_NONE CONFIG_GAP_TRACE_LEVEL_ERROR CONFIG_GAP_TRACE_LEVEL_WARNING CONFIG_GAP_TRACE_LEVEL_API CONFIG_GAP_TRACE_LEVEL_EVENT CONFIG_GAP_TRACE_LEVEL_DEBUG CONFIG_GAP_TRACE_LEVEL_VERBOSE CONFIG_GAP_TRACE_LEVEL_NONE CONFIG_GAP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_GAP_TRACE_LEVEL) CONFIG_GAP_TRACE_LEVEL_NONE CONFIG_GAP_TRACE_LEVEL_ERROR CONFIG_GAP_TRACE_LEVEL_WARNING CONFIG_GAP_TRACE_LEVEL_API CONFIG_GAP_TRACE_LEVEL_EVENT CONFIG_GAP_TRACE_LEVEL_DEBUG CONFIG_GAP_TRACE_LEVEL_VERBOSE CONFIG_GARP_TMR_INTERVAL (CONFIG_LWIP_GARP_TMR_INTERVAL) CONFIG_GATTC_CACHE_NVS_FLASH (CONFIG_BT_GATTC_CACHE_NVS_FLASH) CONFIG_GATTC_ENABLE (CONFIG_BT_GATTC_ENABLE) CONFIG_GATTS_ENABLE (CONFIG_BT_GATTS_ENABLE) CONFIG_GATTS_SEND_SERVICE_CHANGE_MODE (CONFIG_BT_GATTS_SEND_SERVICE_CHANGE_MODE) CONFIG_GATTS_SEND_SERVICE_CHANGE_MANUAL CONFIG_GATTS_SEND_SERVICE_CHANGE_AUTO CONFIG_GATTS_SEND_SERVICE_CHANGE_MANUAL CONFIG_GATTS_SEND_SERVICE_CHANGE_AUTO CONFIG_GATTS_SEND_SERVICE_CHANGE_MANUAL CONFIG_GATTS_SEND_SERVICE_CHANGE_MODE (CONFIG_BT_GATTS_SEND_SERVICE_CHANGE_MODE) CONFIG_GATTS_SEND_SERVICE_CHANGE_MANUAL CONFIG_GATTS_SEND_SERVICE_CHANGE_AUTO CONFIG_GATT_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_GATT_TRACE_LEVEL) CONFIG_GATT_TRACE_LEVEL_NONE CONFIG_GATT_TRACE_LEVEL_ERROR CONFIG_GATT_TRACE_LEVEL_WARNING CONFIG_GATT_TRACE_LEVEL_API CONFIG_GATT_TRACE_LEVEL_EVENT CONFIG_GATT_TRACE_LEVEL_DEBUG CONFIG_GATT_TRACE_LEVEL_VERBOSE CONFIG_GATT_TRACE_LEVEL_NONE CONFIG_GATT_TRACE_LEVEL_ERROR CONFIG_GATT_TRACE_LEVEL_WARNING CONFIG_GATT_TRACE_LEVEL_API CONFIG_GATT_TRACE_LEVEL_EVENT CONFIG_GATT_TRACE_LEVEL_DEBUG CONFIG_GATT_TRACE_LEVEL_VERBOSE CONFIG_GATT_TRACE_LEVEL_NONE CONFIG_GATT_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_GATT_TRACE_LEVEL) CONFIG_GATT_TRACE_LEVEL_NONE CONFIG_GATT_TRACE_LEVEL_ERROR CONFIG_GATT_TRACE_LEVEL_WARNING CONFIG_GATT_TRACE_LEVEL_API CONFIG_GATT_TRACE_LEVEL_EVENT CONFIG_GATT_TRACE_LEVEL_DEBUG CONFIG_GATT_TRACE_LEVEL_VERBOSE CONFIG_GDBSTUB_MAX_TASKS (CONFIG_ESP_GDBSTUB_MAX_TASKS) CONFIG_GDBSTUB_SUPPORT_TASKS (CONFIG_ESP_GDBSTUB_SUPPORT_TASKS) CONFIG_HCI_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_HCI_TRACE_LEVEL) CONFIG_HCI_TRACE_LEVEL_NONE CONFIG_HCI_TRACE_LEVEL_ERROR CONFIG_HCI_TRACE_LEVEL_WARNING CONFIG_HCI_TRACE_LEVEL_API CONFIG_HCI_TRACE_LEVEL_EVENT CONFIG_HCI_TRACE_LEVEL_DEBUG CONFIG_HCI_TRACE_LEVEL_VERBOSE CONFIG_HCI_TRACE_LEVEL_NONE CONFIG_HCI_TRACE_LEVEL_ERROR CONFIG_HCI_TRACE_LEVEL_WARNING CONFIG_HCI_TRACE_LEVEL_API CONFIG_HCI_TRACE_LEVEL_EVENT CONFIG_HCI_TRACE_LEVEL_DEBUG CONFIG_HCI_TRACE_LEVEL_VERBOSE CONFIG_HCI_TRACE_LEVEL_NONE CONFIG_HCI_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_HCI_TRACE_LEVEL) CONFIG_HCI_TRACE_LEVEL_NONE CONFIG_HCI_TRACE_LEVEL_ERROR CONFIG_HCI_TRACE_LEVEL_WARNING CONFIG_HCI_TRACE_LEVEL_API CONFIG_HCI_TRACE_LEVEL_EVENT CONFIG_HCI_TRACE_LEVEL_DEBUG CONFIG_HCI_TRACE_LEVEL_VERBOSE CONFIG_HFP_AG_ENABLE (CONFIG_BT_HFP_AG_ENABLE) CONFIG_HFP_AUDIO_DATA_PATH (CONFIG_BT_HFP_AUDIO_DATA_PATH) CONFIG_HFP_AUDIO_DATA_PATH_PCM CONFIG_HFP_AUDIO_DATA_PATH_HCI CONFIG_HFP_AUDIO_DATA_PATH_PCM CONFIG_HFP_AUDIO_DATA_PATH_HCI CONFIG_HFP_AUDIO_DATA_PATH_PCM CONFIG_HFP_AUDIO_DATA_PATH (CONFIG_BT_HFP_AUDIO_DATA_PATH) CONFIG_HFP_AUDIO_DATA_PATH_PCM CONFIG_HFP_AUDIO_DATA_PATH_HCI CONFIG_HFP_CLIENT_ENABLE (CONFIG_BT_HFP_CLIENT_ENABLE) CONFIG_HFP_ENABLE (CONFIG_BT_HFP_ENABLE) CONFIG_HID_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_HID_TRACE_LEVEL) CONFIG_HID_TRACE_LEVEL_NONE CONFIG_HID_TRACE_LEVEL_ERROR CONFIG_HID_TRACE_LEVEL_WARNING CONFIG_HID_TRACE_LEVEL_API CONFIG_HID_TRACE_LEVEL_EVENT CONFIG_HID_TRACE_LEVEL_DEBUG CONFIG_HID_TRACE_LEVEL_VERBOSE CONFIG_HID_TRACE_LEVEL_NONE CONFIG_HID_TRACE_LEVEL_ERROR CONFIG_HID_TRACE_LEVEL_WARNING CONFIG_HID_TRACE_LEVEL_API CONFIG_HID_TRACE_LEVEL_EVENT CONFIG_HID_TRACE_LEVEL_DEBUG CONFIG_HID_TRACE_LEVEL_VERBOSE CONFIG_HID_TRACE_LEVEL_NONE CONFIG_HID_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_HID_TRACE_LEVEL) CONFIG_HID_TRACE_LEVEL_NONE CONFIG_HID_TRACE_LEVEL_ERROR CONFIG_HID_TRACE_LEVEL_WARNING CONFIG_HID_TRACE_LEVEL_API CONFIG_HID_TRACE_LEVEL_EVENT CONFIG_HID_TRACE_LEVEL_DEBUG CONFIG_HID_TRACE_LEVEL_VERBOSE CONFIG_INT_WDT (CONFIG_ESP_INT_WDT) CONFIG_INT_WDT_CHECK_CPU1 (CONFIG_ESP_INT_WDT_CHECK_CPU1) CONFIG_INT_WDT_TIMEOUT_MS (CONFIG_ESP_INT_WDT_TIMEOUT_MS) CONFIG_IPC_TASK_STACK_SIZE (CONFIG_ESP_IPC_TASK_STACK_SIZE) CONFIG_L2CAP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL) CONFIG_L2CAP_TRACE_LEVEL_NONE CONFIG_L2CAP_TRACE_LEVEL_ERROR CONFIG_L2CAP_TRACE_LEVEL_WARNING CONFIG_L2CAP_TRACE_LEVEL_API CONFIG_L2CAP_TRACE_LEVEL_EVENT CONFIG_L2CAP_TRACE_LEVEL_DEBUG CONFIG_L2CAP_TRACE_LEVEL_VERBOSE CONFIG_L2CAP_TRACE_LEVEL_NONE CONFIG_L2CAP_TRACE_LEVEL_ERROR CONFIG_L2CAP_TRACE_LEVEL_WARNING CONFIG_L2CAP_TRACE_LEVEL_API CONFIG_L2CAP_TRACE_LEVEL_EVENT CONFIG_L2CAP_TRACE_LEVEL_DEBUG CONFIG_L2CAP_TRACE_LEVEL_VERBOSE CONFIG_L2CAP_TRACE_LEVEL_NONE CONFIG_L2CAP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL) CONFIG_L2CAP_TRACE_LEVEL_NONE CONFIG_L2CAP_TRACE_LEVEL_ERROR CONFIG_L2CAP_TRACE_LEVEL_WARNING CONFIG_L2CAP_TRACE_LEVEL_API CONFIG_L2CAP_TRACE_LEVEL_EVENT CONFIG_L2CAP_TRACE_LEVEL_DEBUG CONFIG_L2CAP_TRACE_LEVEL_VERBOSE CONFIG_L2_TO_L3_COPY (CONFIG_LWIP_L2_TO_L3_COPY) CONFIG_LOG_BOOTLOADER_LEVEL (CONFIG_BOOTLOADER_LOG_LEVEL) CONFIG_LOG_BOOTLOADER_LEVEL_NONE CONFIG_LOG_BOOTLOADER_LEVEL_ERROR CONFIG_LOG_BOOTLOADER_LEVEL_WARN CONFIG_LOG_BOOTLOADER_LEVEL_INFO CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE CONFIG_LOG_BOOTLOADER_LEVEL_NONE CONFIG_LOG_BOOTLOADER_LEVEL_ERROR CONFIG_LOG_BOOTLOADER_LEVEL_WARN CONFIG_LOG_BOOTLOADER_LEVEL_INFO CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE CONFIG_LOG_BOOTLOADER_LEVEL_NONE CONFIG_LOG_BOOTLOADER_LEVEL (CONFIG_BOOTLOADER_LOG_LEVEL) CONFIG_LOG_BOOTLOADER_LEVEL_NONE CONFIG_LOG_BOOTLOADER_LEVEL_ERROR CONFIG_LOG_BOOTLOADER_LEVEL_WARN CONFIG_LOG_BOOTLOADER_LEVEL_INFO CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE CONFIG_MAC_BB_PD (CONFIG_ESP_PHY_MAC_BB_PD) CONFIG_MAIN_TASK_STACK_SIZE (CONFIG_ESP_MAIN_TASK_STACK_SIZE) CONFIG_MCA_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_MCA_TRACE_LEVEL) CONFIG_MCA_TRACE_LEVEL_NONE CONFIG_MCA_TRACE_LEVEL_ERROR CONFIG_MCA_TRACE_LEVEL_WARNING CONFIG_MCA_TRACE_LEVEL_API CONFIG_MCA_TRACE_LEVEL_EVENT CONFIG_MCA_TRACE_LEVEL_DEBUG CONFIG_MCA_TRACE_LEVEL_VERBOSE CONFIG_MCA_TRACE_LEVEL_NONE CONFIG_MCA_TRACE_LEVEL_ERROR CONFIG_MCA_TRACE_LEVEL_WARNING CONFIG_MCA_TRACE_LEVEL_API CONFIG_MCA_TRACE_LEVEL_EVENT CONFIG_MCA_TRACE_LEVEL_DEBUG CONFIG_MCA_TRACE_LEVEL_VERBOSE CONFIG_MCA_TRACE_LEVEL_NONE CONFIG_MCA_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_MCA_TRACE_LEVEL) CONFIG_MCA_TRACE_LEVEL_NONE CONFIG_MCA_TRACE_LEVEL_ERROR CONFIG_MCA_TRACE_LEVEL_WARNING CONFIG_MCA_TRACE_LEVEL_API CONFIG_MCA_TRACE_LEVEL_EVENT CONFIG_MCA_TRACE_LEVEL_DEBUG CONFIG_MCA_TRACE_LEVEL_VERBOSE CONFIG_MCPWM_ISR_IN_IRAM (CONFIG_MCPWM_ISR_IRAM_SAFE) CONFIG_MESH_DUPLICATE_SCAN_CACHE_SIZE (CONFIG_BTDM_MESH_DUPL_SCAN_CACHE_SIZE) CONFIG_NIMBLE_ATT_PREFERRED_MTU (CONFIG_BT_NIMBLE_ATT_PREFERRED_MTU) CONFIG_NIMBLE_CRYPTO_STACK_MBEDTLS (CONFIG_BT_NIMBLE_CRYPTO_STACK_MBEDTLS) CONFIG_NIMBLE_DEBUG (CONFIG_BT_NIMBLE_DEBUG) CONFIG_NIMBLE_GAP_DEVICE_NAME_MAX_LEN (CONFIG_BT_NIMBLE_GAP_DEVICE_NAME_MAX_LEN) CONFIG_NIMBLE_HS_FLOW_CTRL (CONFIG_BT_NIMBLE_HS_FLOW_CTRL) CONFIG_NIMBLE_HS_FLOW_CTRL_ITVL (CONFIG_BT_NIMBLE_HS_FLOW_CTRL_ITVL) CONFIG_NIMBLE_HS_FLOW_CTRL_THRESH (CONFIG_BT_NIMBLE_HS_FLOW_CTRL_THRESH) CONFIG_NIMBLE_HS_FLOW_CTRL_TX_ON_DISCONNECT (CONFIG_BT_NIMBLE_HS_FLOW_CTRL_TX_ON_DISCONNECT) CONFIG_NIMBLE_L2CAP_COC_MAX_NUM (CONFIG_BT_NIMBLE_L2CAP_COC_MAX_NUM) CONFIG_NIMBLE_MAX_BONDS (CONFIG_BT_NIMBLE_MAX_BONDS) CONFIG_NIMBLE_MAX_CCCDS (CONFIG_BT_NIMBLE_MAX_CCCDS) CONFIG_NIMBLE_MAX_CONNECTIONS (CONFIG_BT_NIMBLE_MAX_CONNECTIONS) CONFIG_NIMBLE_MEM_ALLOC_MODE (CONFIG_BT_NIMBLE_MEM_ALLOC_MODE) CONFIG_NIMBLE_MEM_ALLOC_MODE_INTERNAL CONFIG_NIMBLE_MEM_ALLOC_MODE_EXTERNAL CONFIG_NIMBLE_MEM_ALLOC_MODE_DEFAULT CONFIG_NIMBLE_MEM_ALLOC_MODE_INTERNAL CONFIG_NIMBLE_MEM_ALLOC_MODE_EXTERNAL CONFIG_NIMBLE_MEM_ALLOC_MODE_DEFAULT CONFIG_NIMBLE_MEM_ALLOC_MODE_INTERNAL CONFIG_NIMBLE_MEM_ALLOC_MODE (CONFIG_BT_NIMBLE_MEM_ALLOC_MODE) CONFIG_NIMBLE_MEM_ALLOC_MODE_INTERNAL CONFIG_NIMBLE_MEM_ALLOC_MODE_EXTERNAL CONFIG_NIMBLE_MEM_ALLOC_MODE_DEFAULT CONFIG_NIMBLE_MESH (CONFIG_BT_NIMBLE_MESH) CONFIG_NIMBLE_MESH_DEVICE_NAME (CONFIG_BT_NIMBLE_MESH_DEVICE_NAME) CONFIG_NIMBLE_MESH_FRIEND (CONFIG_BT_NIMBLE_MESH_FRIEND) CONFIG_NIMBLE_MESH_GATT_PROXY (CONFIG_BT_NIMBLE_MESH_GATT_PROXY) CONFIG_NIMBLE_MESH_LOW_POWER (CONFIG_BT_NIMBLE_MESH_LOW_POWER) CONFIG_NIMBLE_MESH_PB_ADV (CONFIG_BT_NIMBLE_MESH_PB_ADV) CONFIG_NIMBLE_MESH_PB_GATT (CONFIG_BT_NIMBLE_MESH_PB_GATT) CONFIG_NIMBLE_MESH_PROV (CONFIG_BT_NIMBLE_MESH_PROV) CONFIG_NIMBLE_MESH_PROXY (CONFIG_BT_NIMBLE_MESH_PROXY) CONFIG_NIMBLE_MESH_RELAY (CONFIG_BT_NIMBLE_MESH_RELAY) CONFIG_NIMBLE_NVS_PERSIST (CONFIG_BT_NIMBLE_NVS_PERSIST) CONFIG_NIMBLE_PINNED_TO_CORE_CHOICE (CONFIG_BT_NIMBLE_PINNED_TO_CORE_CHOICE) CONFIG_NIMBLE_PINNED_TO_CORE_0 CONFIG_NIMBLE_PINNED_TO_CORE_1 CONFIG_NIMBLE_PINNED_TO_CORE_0 CONFIG_NIMBLE_PINNED_TO_CORE_1 CONFIG_NIMBLE_PINNED_TO_CORE_0 CONFIG_NIMBLE_PINNED_TO_CORE_CHOICE (CONFIG_BT_NIMBLE_PINNED_TO_CORE_CHOICE) CONFIG_NIMBLE_PINNED_TO_CORE_0 CONFIG_NIMBLE_PINNED_TO_CORE_1 CONFIG_NIMBLE_ROLE_BROADCASTER (CONFIG_BT_NIMBLE_ROLE_BROADCASTER) CONFIG_NIMBLE_ROLE_CENTRAL (CONFIG_BT_NIMBLE_ROLE_CENTRAL) CONFIG_NIMBLE_ROLE_OBSERVER (CONFIG_BT_NIMBLE_ROLE_OBSERVER) CONFIG_NIMBLE_ROLE_PERIPHERAL (CONFIG_BT_NIMBLE_ROLE_PERIPHERAL) CONFIG_NIMBLE_RPA_TIMEOUT (CONFIG_BT_NIMBLE_RPA_TIMEOUT) CONFIG_NIMBLE_SM_LEGACY (CONFIG_BT_NIMBLE_SM_LEGACY) CONFIG_NIMBLE_SM_SC (CONFIG_BT_NIMBLE_SM_SC) CONFIG_NIMBLE_SM_SC_DEBUG_KEYS (CONFIG_BT_NIMBLE_SM_SC_DEBUG_KEYS) CONFIG_NIMBLE_SVC_GAP_APPEARANCE (CONFIG_BT_NIMBLE_SVC_GAP_APPEARANCE) CONFIG_NIMBLE_SVC_GAP_DEVICE_NAME (CONFIG_BT_NIMBLE_SVC_GAP_DEVICE_NAME) CONFIG_NIMBLE_TASK_STACK_SIZE (CONFIG_BT_NIMBLE_HOST_TASK_STACK_SIZE) CONFIG_NO_BLOBS (CONFIG_APP_NO_BLOBS) CONFIG_NUMBER_OF_UNIVERSAL_MAC_ADDRESS (CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES) CONFIG_TWO_UNIVERSAL_MAC_ADDRESS CONFIG_FOUR_UNIVERSAL_MAC_ADDRESS CONFIG_TWO_UNIVERSAL_MAC_ADDRESS CONFIG_FOUR_UNIVERSAL_MAC_ADDRESS CONFIG_TWO_UNIVERSAL_MAC_ADDRESS CONFIG_NUMBER_OF_UNIVERSAL_MAC_ADDRESS (CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES) CONFIG_TWO_UNIVERSAL_MAC_ADDRESS CONFIG_FOUR_UNIVERSAL_MAC_ADDRESS CONFIG_OPTIMIZATION_ASSERTION_LEVEL (CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL) CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED CONFIG_OPTIMIZATION_ASSERTIONS_SILENT CONFIG_OPTIMIZATION_ASSERTIONS_DISABLED CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED CONFIG_OPTIMIZATION_ASSERTIONS_SILENT CONFIG_OPTIMIZATION_ASSERTIONS_DISABLED CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED CONFIG_OPTIMIZATION_ASSERTION_LEVEL (CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL) CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED CONFIG_OPTIMIZATION_ASSERTIONS_SILENT CONFIG_OPTIMIZATION_ASSERTIONS_DISABLED CONFIG_OPTIMIZATION_COMPILER (CONFIG_COMPILER_OPTIMIZATION) CONFIG_OPTIMIZATION_LEVEL_DEBUG, CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG, CONFIG_COMPILER_OPTIMIZATION_DEFAULT CONFIG_OPTIMIZATION_LEVEL_RELEASE, CONFIG_COMPILER_OPTIMIZATION_LEVEL_RELEASE CONFIG_OPTIMIZATION_LEVEL_DEBUG, CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG, CONFIG_COMPILER_OPTIMIZATION_DEFAULT CONFIG_OPTIMIZATION_LEVEL_RELEASE, CONFIG_COMPILER_OPTIMIZATION_LEVEL_RELEASE CONFIG_OPTIMIZATION_LEVEL_DEBUG, CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG, CONFIG_COMPILER_OPTIMIZATION_DEFAULT CONFIG_OPTIMIZATION_COMPILER (CONFIG_COMPILER_OPTIMIZATION) CONFIG_OPTIMIZATION_LEVEL_DEBUG, CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG, CONFIG_COMPILER_OPTIMIZATION_DEFAULT CONFIG_OPTIMIZATION_LEVEL_RELEASE, CONFIG_COMPILER_OPTIMIZATION_LEVEL_RELEASE CONFIG_OSI_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_OSI_TRACE_LEVEL) CONFIG_OSI_TRACE_LEVEL_NONE CONFIG_OSI_TRACE_LEVEL_ERROR CONFIG_OSI_TRACE_LEVEL_WARNING CONFIG_OSI_TRACE_LEVEL_API CONFIG_OSI_TRACE_LEVEL_EVENT CONFIG_OSI_TRACE_LEVEL_DEBUG CONFIG_OSI_TRACE_LEVEL_VERBOSE CONFIG_OSI_TRACE_LEVEL_NONE CONFIG_OSI_TRACE_LEVEL_ERROR CONFIG_OSI_TRACE_LEVEL_WARNING CONFIG_OSI_TRACE_LEVEL_API CONFIG_OSI_TRACE_LEVEL_EVENT CONFIG_OSI_TRACE_LEVEL_DEBUG CONFIG_OSI_TRACE_LEVEL_VERBOSE CONFIG_OSI_TRACE_LEVEL_NONE CONFIG_OSI_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_OSI_TRACE_LEVEL) CONFIG_OSI_TRACE_LEVEL_NONE CONFIG_OSI_TRACE_LEVEL_ERROR CONFIG_OSI_TRACE_LEVEL_WARNING CONFIG_OSI_TRACE_LEVEL_API CONFIG_OSI_TRACE_LEVEL_EVENT CONFIG_OSI_TRACE_LEVEL_DEBUG CONFIG_OSI_TRACE_LEVEL_VERBOSE CONFIG_OTA_ALLOW_HTTP (CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP) CONFIG_PAN_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_PAN_TRACE_LEVEL) CONFIG_PAN_TRACE_LEVEL_NONE CONFIG_PAN_TRACE_LEVEL_ERROR CONFIG_PAN_TRACE_LEVEL_WARNING CONFIG_PAN_TRACE_LEVEL_API CONFIG_PAN_TRACE_LEVEL_EVENT CONFIG_PAN_TRACE_LEVEL_DEBUG CONFIG_PAN_TRACE_LEVEL_VERBOSE CONFIG_PAN_TRACE_LEVEL_NONE CONFIG_PAN_TRACE_LEVEL_ERROR CONFIG_PAN_TRACE_LEVEL_WARNING CONFIG_PAN_TRACE_LEVEL_API CONFIG_PAN_TRACE_LEVEL_EVENT CONFIG_PAN_TRACE_LEVEL_DEBUG CONFIG_PAN_TRACE_LEVEL_VERBOSE CONFIG_PAN_TRACE_LEVEL_NONE CONFIG_PAN_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_PAN_TRACE_LEVEL) CONFIG_PAN_TRACE_LEVEL_NONE CONFIG_PAN_TRACE_LEVEL_ERROR CONFIG_PAN_TRACE_LEVEL_WARNING CONFIG_PAN_TRACE_LEVEL_API CONFIG_PAN_TRACE_LEVEL_EVENT CONFIG_PAN_TRACE_LEVEL_DEBUG CONFIG_PAN_TRACE_LEVEL_VERBOSE CONFIG_POST_EVENTS_FROM_IRAM_ISR (CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR) CONFIG_POST_EVENTS_FROM_ISR (CONFIG_ESP_EVENT_POST_FROM_ISR) CONFIG_PPP_CHAP_SUPPORT (CONFIG_LWIP_PPP_CHAP_SUPPORT) CONFIG_PPP_DEBUG_ON (CONFIG_LWIP_PPP_DEBUG_ON) CONFIG_PPP_MPPE_SUPPORT (CONFIG_LWIP_PPP_MPPE_SUPPORT) CONFIG_PPP_MSCHAP_SUPPORT (CONFIG_LWIP_PPP_MSCHAP_SUPPORT) CONFIG_PPP_NOTIFY_PHASE_SUPPORT (CONFIG_LWIP_PPP_NOTIFY_PHASE_SUPPORT) CONFIG_PPP_PAP_SUPPORT (CONFIG_LWIP_PPP_PAP_SUPPORT) CONFIG_PPP_SUPPORT (CONFIG_LWIP_PPP_SUPPORT) CONFIG_REDUCE_PHY_TX_POWER (CONFIG_ESP_PHY_REDUCE_TX_POWER) CONFIG_RFCOMM_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL) CONFIG_RFCOMM_TRACE_LEVEL_NONE CONFIG_RFCOMM_TRACE_LEVEL_ERROR CONFIG_RFCOMM_TRACE_LEVEL_WARNING CONFIG_RFCOMM_TRACE_LEVEL_API CONFIG_RFCOMM_TRACE_LEVEL_EVENT CONFIG_RFCOMM_TRACE_LEVEL_DEBUG CONFIG_RFCOMM_TRACE_LEVEL_VERBOSE CONFIG_RFCOMM_TRACE_LEVEL_NONE CONFIG_RFCOMM_TRACE_LEVEL_ERROR CONFIG_RFCOMM_TRACE_LEVEL_WARNING CONFIG_RFCOMM_TRACE_LEVEL_API CONFIG_RFCOMM_TRACE_LEVEL_EVENT CONFIG_RFCOMM_TRACE_LEVEL_DEBUG CONFIG_RFCOMM_TRACE_LEVEL_VERBOSE CONFIG_RFCOMM_TRACE_LEVEL_NONE CONFIG_RFCOMM_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL) CONFIG_RFCOMM_TRACE_LEVEL_NONE CONFIG_RFCOMM_TRACE_LEVEL_ERROR CONFIG_RFCOMM_TRACE_LEVEL_WARNING CONFIG_RFCOMM_TRACE_LEVEL_API CONFIG_RFCOMM_TRACE_LEVEL_EVENT CONFIG_RFCOMM_TRACE_LEVEL_DEBUG CONFIG_RFCOMM_TRACE_LEVEL_VERBOSE CONFIG_SCAN_DUPLICATE_TYPE (CONFIG_BTDM_SCAN_DUPL_TYPE) CONFIG_SCAN_DUPLICATE_BY_DEVICE_ADDR CONFIG_SCAN_DUPLICATE_BY_ADV_DATA CONFIG_SCAN_DUPLICATE_BY_ADV_DATA_AND_DEVICE_ADDR CONFIG_SCAN_DUPLICATE_BY_DEVICE_ADDR CONFIG_SCAN_DUPLICATE_BY_ADV_DATA CONFIG_SCAN_DUPLICATE_BY_ADV_DATA_AND_DEVICE_ADDR CONFIG_SCAN_DUPLICATE_BY_DEVICE_ADDR CONFIG_SCAN_DUPLICATE_TYPE (CONFIG_BTDM_SCAN_DUPL_TYPE) CONFIG_SCAN_DUPLICATE_BY_DEVICE_ADDR CONFIG_SCAN_DUPLICATE_BY_ADV_DATA CONFIG_SCAN_DUPLICATE_BY_ADV_DATA_AND_DEVICE_ADDR CONFIG_SEMIHOSTFS_MAX_MOUNT_POINTS (CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS) CONFIG_SMP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_SMP_TRACE_LEVEL) CONFIG_SMP_TRACE_LEVEL_NONE CONFIG_SMP_TRACE_LEVEL_ERROR CONFIG_SMP_TRACE_LEVEL_WARNING CONFIG_SMP_TRACE_LEVEL_API CONFIG_SMP_TRACE_LEVEL_EVENT CONFIG_SMP_TRACE_LEVEL_DEBUG CONFIG_SMP_TRACE_LEVEL_VERBOSE CONFIG_SMP_TRACE_LEVEL_NONE CONFIG_SMP_TRACE_LEVEL_ERROR CONFIG_SMP_TRACE_LEVEL_WARNING CONFIG_SMP_TRACE_LEVEL_API CONFIG_SMP_TRACE_LEVEL_EVENT CONFIG_SMP_TRACE_LEVEL_DEBUG CONFIG_SMP_TRACE_LEVEL_VERBOSE CONFIG_SMP_TRACE_LEVEL_NONE CONFIG_SMP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_SMP_TRACE_LEVEL) CONFIG_SMP_TRACE_LEVEL_NONE CONFIG_SMP_TRACE_LEVEL_ERROR CONFIG_SMP_TRACE_LEVEL_WARNING CONFIG_SMP_TRACE_LEVEL_API CONFIG_SMP_TRACE_LEVEL_EVENT CONFIG_SMP_TRACE_LEVEL_DEBUG CONFIG_SMP_TRACE_LEVEL_VERBOSE CONFIG_SMP_SLAVE_CON_PARAMS_UPD_ENABLE (CONFIG_BT_SMP_SLAVE_CON_PARAMS_UPD_ENABLE) CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS (CONFIG_SPI_FLASH_DANGEROUS_WRITE) CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_FAILS CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_FAILS CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS (CONFIG_SPI_FLASH_DANGEROUS_WRITE) CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_FAILS CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED CONFIG_STACK_CHECK_MODE (CONFIG_COMPILER_STACK_CHECK_MODE) CONFIG_STACK_CHECK_NONE CONFIG_STACK_CHECK_NORM CONFIG_STACK_CHECK_STRONG CONFIG_STACK_CHECK_ALL CONFIG_STACK_CHECK_NONE CONFIG_STACK_CHECK_NORM CONFIG_STACK_CHECK_STRONG CONFIG_STACK_CHECK_ALL CONFIG_STACK_CHECK_NONE CONFIG_STACK_CHECK_MODE (CONFIG_COMPILER_STACK_CHECK_MODE) CONFIG_STACK_CHECK_NONE CONFIG_STACK_CHECK_NORM CONFIG_STACK_CHECK_STRONG CONFIG_STACK_CHECK_ALL CONFIG_SUPPORT_TERMIOS (CONFIG_VFS_SUPPORT_TERMIOS) CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT (CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT) CONFIG_SW_COEXIST_ENABLE (CONFIG_ESP_COEX_SW_COEXIST_ENABLE) CONFIG_SYSTEM_EVENT_QUEUE_SIZE (CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE) CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE (CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE) CONFIG_SYSVIEW_BUF_WAIT_TMO (CONFIG_APPTRACE_SV_BUF_WAIT_TMO) CONFIG_SYSVIEW_ENABLE (CONFIG_APPTRACE_SV_ENABLE) CONFIG_SYSVIEW_EVT_IDLE_ENABLE (CONFIG_APPTRACE_SV_EVT_IDLE_ENABLE) CONFIG_SYSVIEW_EVT_ISR_ENTER_ENABLE (CONFIG_APPTRACE_SV_EVT_ISR_ENTER_ENABLE) CONFIG_SYSVIEW_EVT_ISR_EXIT_ENABLE (CONFIG_APPTRACE_SV_EVT_ISR_EXIT_ENABLE) CONFIG_SYSVIEW_EVT_ISR_TO_SCHEDULER_ENABLE (CONFIG_APPTRACE_SV_EVT_ISR_TO_SCHED_ENABLE) CONFIG_SYSVIEW_EVT_OVERFLOW_ENABLE (CONFIG_APPTRACE_SV_EVT_OVERFLOW_ENABLE) CONFIG_SYSVIEW_EVT_TASK_CREATE_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_CREATE_ENABLE) CONFIG_SYSVIEW_EVT_TASK_START_EXEC_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_START_EXEC_ENABLE) CONFIG_SYSVIEW_EVT_TASK_START_READY_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_START_READY_ENABLE) CONFIG_SYSVIEW_EVT_TASK_STOP_EXEC_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_STOP_EXEC_ENABLE) CONFIG_SYSVIEW_EVT_TASK_STOP_READY_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_STOP_READY_ENABLE) CONFIG_SYSVIEW_EVT_TASK_TERMINATE_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_TERMINATE_ENABLE) CONFIG_SYSVIEW_EVT_TIMER_ENTER_ENABLE (CONFIG_APPTRACE_SV_EVT_TIMER_ENTER_ENABLE) CONFIG_SYSVIEW_EVT_TIMER_EXIT_ENABLE (CONFIG_APPTRACE_SV_EVT_TIMER_EXIT_ENABLE) CONFIG_SYSVIEW_MAX_TASKS (CONFIG_APPTRACE_SV_MAX_TASKS) CONFIG_SYSVIEW_TS_SOURCE (CONFIG_APPTRACE_SV_TS_SOURCE) CONFIG_SYSVIEW_TS_SOURCE_CCOUNT CONFIG_SYSVIEW_TS_SOURCE_ESP_TIMER CONFIG_SYSVIEW_TS_SOURCE_CCOUNT CONFIG_SYSVIEW_TS_SOURCE_ESP_TIMER CONFIG_SYSVIEW_TS_SOURCE_CCOUNT CONFIG_SYSVIEW_TS_SOURCE (CONFIG_APPTRACE_SV_TS_SOURCE) CONFIG_SYSVIEW_TS_SOURCE_CCOUNT CONFIG_SYSVIEW_TS_SOURCE_ESP_TIMER CONFIG_TASK_WDT (CONFIG_ESP_TASK_WDT_INIT) CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0 (CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0) CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1 (CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1) CONFIG_TASK_WDT_PANIC (CONFIG_ESP_TASK_WDT_PANIC) CONFIG_TASK_WDT_TIMEOUT_S (CONFIG_ESP_TASK_WDT_TIMEOUT_S) CONFIG_TCPIP_RECVMBOX_SIZE (CONFIG_LWIP_TCPIP_RECVMBOX_SIZE) CONFIG_TCPIP_TASK_AFFINITY (CONFIG_LWIP_TCPIP_TASK_AFFINITY) CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY CONFIG_TCPIP_TASK_AFFINITY_CPU0 CONFIG_TCPIP_TASK_AFFINITY_CPU1 CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY CONFIG_TCPIP_TASK_AFFINITY_CPU0 CONFIG_TCPIP_TASK_AFFINITY_CPU1 CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY CONFIG_TCPIP_TASK_AFFINITY (CONFIG_LWIP_TCPIP_TASK_AFFINITY) CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY CONFIG_TCPIP_TASK_AFFINITY_CPU0 CONFIG_TCPIP_TASK_AFFINITY_CPU1 CONFIG_TCPIP_TASK_STACK_SIZE (CONFIG_LWIP_TCPIP_TASK_STACK_SIZE) CONFIG_TCP_MAXRTX (CONFIG_LWIP_TCP_MAXRTX) CONFIG_TCP_MSL (CONFIG_LWIP_TCP_MSL) CONFIG_TCP_MSS (CONFIG_LWIP_TCP_MSS) CONFIG_TCP_OVERSIZE (CONFIG_LWIP_TCP_OVERSIZE) CONFIG_TCP_OVERSIZE_MSS CONFIG_TCP_OVERSIZE_QUARTER_MSS CONFIG_TCP_OVERSIZE_DISABLE CONFIG_TCP_OVERSIZE_MSS CONFIG_TCP_OVERSIZE_QUARTER_MSS CONFIG_TCP_OVERSIZE_DISABLE CONFIG_TCP_OVERSIZE_MSS CONFIG_TCP_OVERSIZE (CONFIG_LWIP_TCP_OVERSIZE) CONFIG_TCP_OVERSIZE_MSS CONFIG_TCP_OVERSIZE_QUARTER_MSS CONFIG_TCP_OVERSIZE_DISABLE CONFIG_TCP_QUEUE_OOSEQ (CONFIG_LWIP_TCP_QUEUE_OOSEQ) CONFIG_TCP_RECVMBOX_SIZE (CONFIG_LWIP_TCP_RECVMBOX_SIZE) CONFIG_TCP_SND_BUF_DEFAULT (CONFIG_LWIP_TCP_SND_BUF_DEFAULT) CONFIG_TCP_SYNMAXRTX (CONFIG_LWIP_TCP_SYNMAXRTX) CONFIG_TCP_WND_DEFAULT (CONFIG_LWIP_TCP_WND_DEFAULT) CONFIG_TIMER_QUEUE_LENGTH (CONFIG_FREERTOS_TIMER_QUEUE_LENGTH) CONFIG_TIMER_TASK_PRIORITY (CONFIG_FREERTOS_TIMER_TASK_PRIORITY) CONFIG_TIMER_TASK_STACK_DEPTH (CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH) CONFIG_TIMER_TASK_STACK_SIZE (CONFIG_ESP_TIMER_TASK_STACK_SIZE) CONFIG_UDP_RECVMBOX_SIZE (CONFIG_LWIP_UDP_RECVMBOX_SIZE) CONFIG_WARN_WRITE_STRINGS (CONFIG_COMPILER_WARN_WRITE_STRINGS) CONFIG_WPA_11KV_SUPPORT (CONFIG_ESP_WIFI_11KV_SUPPORT) CONFIG_WPA_11R_SUPPORT (CONFIG_ESP_WIFI_11R_SUPPORT) CONFIG_WPA_DEBUG_PRINT (CONFIG_ESP_WIFI_DEBUG_PRINT) CONFIG_WPA_DPP_SUPPORT (CONFIG_ESP_WIFI_DPP_SUPPORT) CONFIG_WPA_MBEDTLS_CRYPTO (CONFIG_ESP_WIFI_MBEDTLS_CRYPTO) CONFIG_WPA_MBEDTLS_TLS_CLIENT (CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT) CONFIG_WPA_MBO_SUPPORT (CONFIG_ESP_WIFI_MBO_SUPPORT) CONFIG_WPA_SCAN_CACHE (CONFIG_ESP_WIFI_SCAN_CACHE) CONFIG_WPA_SUITE_B_192 (CONFIG_ESP_WIFI_SUITE_B_192) CONFIG_WPA_TESTING_OPTIONS (CONFIG_ESP_WIFI_TESTING_OPTIONS) CONFIG_WPA_WAPI_PSK (CONFIG_ESP_WIFI_WAPI_PSK) CONFIG_WPA_WPS_SOFTAP_REGISTRAR (CONFIG_ESP_WIFI_WPS_SOFTAP_REGISTRAR) CONFIG_WPA_WPS_STRICT (CONFIG_ESP_WIFI_WPS_STRICT)
Project Configuration Introduction The esp-idf-kconfig package that ESP-IDF uses is based on kconfiglib, which is a Python extension to the Kconfig system. Kconfig provides a compile-time project configuration mechanism and offers configuration options of several types (e.g., integers, strings, and boolens). Kconfig files specify dependencies between options, default values of options, the way options are grouped together, etc. For the full list of available features, please see Kconfig and kconfiglib extentions. Using sdkconfig.defaults In some cases, for example, when the sdkconfig file is under revision control, it may be inconvenient for the build system to change the sdkconfig file. The build system offers a solution to prevent it from happening, which is to create the sdkconfig.defaults file. This file is never touched by the build system, and can be created manually or automatically. It contains all the options which matter to the given application and are different from the default ones. The format is the same as that of the sdkconfig file. sdkconfig.defaults can be created manually when one remembers all the changed configuration, or it can be generated automatically by running the idf.py save-defconfig command. Once sdkconfig.defaults is created, sdkconfig can be deleted or added to the ignore list of the revision control system (e.g., the .gitignore file for git). Project build targets will automatically create the sdkconfig file, populate it with the settings from the sdkconfig.defaults file, and configure the rest of the settings to their default values. Note that during the build process, settings from sdkconfig.defaults will not override those already in sdkconfig. For more information, see Custom Sdkconfig Defaults. Kconfig Format Rules Format rules for Kconfig files are as follows: Option names in any menus should have consistent prefixes. The prefix currently should have at least 3 characters. The unit of indentation should be 4 spaces. All sub-items belonging to a parent item are indented by one level deeper. For example, menuis indented by 0 spaces, config menuby 4 spaces, helpin configby 8 spaces, and the text under helpby 12 spaces. No trailing spaces are allowed at the end of the lines. The maximum length of options is 50 characters. The maximum length of lines is 120 characters. Note The help section of each config in the menu is treated as reStructuredText to generate the reference documentation for each option. Format Checker kconfcheck tool in esp-idf-kconfig package is provided for checking Kconfig files against the above format rules. The checker checks all Kconfig and Kconfig.projbuild files given as arguments, and generates a new file with suffix .new with some suggestions about how to fix issues (if there are any). Please note that the checker cannot correct all format issues and the responsibility of the developer is to final check and make corrections in order to pass the tests. For example, indentations will be corrected if there is not any misleading formatting, but it cannot come up with a common prefix for options inside a menu. The esp-idf-kconfig package is available in ESP-IDF environments, where the checker tool can be invoked by running command python -m kconfcheck <path_to_kconfig_file>. For more information, please refer to esp-idf-kconfig package documentation. Backward Compatibility of Kconfig Options The standard Kconfig tools ignore unknown options in sdkconfig. So if a developer has custom settings for options which are renamed in newer ESP-IDF releases, then the given setting for the option would be silently ignored. Therefore, several features have been adopted to avoid this: kconfgenis used by the tool chain to pre-process sdkconfigfiles before anything else. For example, menuconfigwould read them, so the settings for old options is kept and not ignored. kconfgenrecursively finds all sdkconfig.renamefiles in ESP-IDF directory which contain old and new Kconfigoption names. Old options are replaced by new ones in the sdkconfigfile. Renames that should only appear for a single target can be placed in a target-specific rename file sdkconfig.rename.TARGET, where TARGETis the target name, e.g., sdkconfig.rename.esp32s2. kconfgenpost-processes sdkconfigfiles and generates all build outputs ( sdkconfig.h, sdkconfig.cmake, and auto.conf) by adding a list of compatibility statements, i.e., the values of old options are set for new options after modification. If users still use old options in their code, this will prevent it from breaking. Deprecated options and their replacements are automatically generated by kconfgen. Configuration Options Reference Subsequent sections contain the list of available ESP-IDF options automatically generated from Kconfig files. Note that due to dependencies between options, some options listed here may not be visible by default in menuconfig. By convention, all option names are upper-case letters with underscores. When Kconfig generates sdkconfig and sdkconfig.h files, option names are prefixed with CONFIG_. So if an option ENABLE_FOO is defined in a Kconfig file and selected in menuconfig, then the sdkconfig and sdkconfig.h files will have CONFIG_ENABLE_FOO defined. In the following sections, option names are also prefixed with CONFIG_, same as in the source code. Build type Contains: CONFIG_APP_BUILD_TYPE Application build type Found in: Build type Select the way the application is built. By default, the application is built as a binary file in a format compatible with the ESP-IDF bootloader. In addition to this application, 2nd stage bootloader is also built. Application and bootloader binaries can be written into flash and loaded/executed from there. Another option, useful for only very small and limited applications, is to only link the .elf file of the application, such that it can be loaded directly into RAM over JTAG or UART. Note that since IRAM and DRAM sizes are very limited, it is not possible to build any complex application this way. However for some kinds of testing and debugging, this option may provide faster iterations, since the application does not need to be written into flash. Note: when APP_BUILD_TYPE_RAM is selected and loaded with JTAG, ESP-IDF does not contain all the startup code required to initialize the CPUs and ROM memory (data/bss). Therefore it is necessary to execute a bit of ROM code prior to executing the application. A gdbinit file may look as follows (for ESP32): # Connect to a running instance of OpenOCD target remote :3333 # Reset and halt the target mon reset halt # Run to a specific point in ROM code, # where most of initialization is complete. thb *0x40007d54 c # Load the application into RAM load # Run till app_main tb app_main c Execute this gdbinit file as follows: xtensa-esp32-elf-gdb build/app-name.elf -x gdbinit Example gdbinit files for other targets can be found in tools/test_apps/system/gdb_loadable_elf/ When loading the BIN with UART, the ROM will jump to ram and run the app after finishing the ROM startup code, so there's no additional startup initialization required. You can use the load_ram in esptool.py to load the generated .bin file into ram and execute. - Example: - esptool.py --chip {chip} -p {port} -b {baud} --no-stub load_ram {app.bin} Recommended sdkconfig.defaults for building loadable ELF files is as follows. CONFIG_APP_BUILD_TYPE_RAM is required, other options help reduce application memory footprint. CONFIG_APP_BUILD_TYPE_RAM=y CONFIG_VFS_SUPPORT_TERMIOS= CONFIG_NEWLIB_NANO_FORMAT=y CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT=y CONFIG_ESP_DEBUG_STUBS_ENABLE= CONFIG_ESP_ERR_TO_NAME_LOOKUP= Available options: - Default (binary application + 2nd stage bootloader) (CONFIG_APP_BUILD_TYPE_APP_2NDBOOT) - Build app runs entirely in RAM (EXPERIMENTAL) (CONFIG_APP_BUILD_TYPE_RAM) CONFIG_APP_BUILD_TYPE_PURE_RAM_APP Build app without SPI_FLASH/PSRAM support (saves ram) Found in: Build type If this option is enabled, external memory and related peripherals, such as Cache, MMU, Flash and PSRAM, won't be initialized. Corresponding drivers won't be introduced either. Components that depend on the spi_flash component will also be unavailable, such as app_update, etc. When this option is enabled, about 26KB of RAM space can be saved. CONFIG_APP_REPRODUCIBLE_BUILD Enable reproducible build Found in: Build type If enabled, all date, time, and path information would be eliminated. A .gdbinit file would be create automatically. (or will be append if you have one already) - Default value: - - No (disabled) CONFIG_APP_NO_BLOBS No Binary Blobs Found in: Build type If enabled, this disables the linking of binary libraries in the application build. Note that after enabling this Wi-Fi/Bluetooth will not work. - Default value: - - No (disabled) CONFIG_APP_COMPATIBLE_PRE_V2_1_BOOTLOADERS App compatible with bootloaders before ESP-IDF v2.1 Found in: Build type Bootloaders before ESP-IDF v2.1 did less initialisation of the system clock. This setting needs to be enabled to build an app which can be booted by these older bootloaders. If this setting is enabled, the app can be booted by any bootloader from IDF v1.0 up to the current version. If this setting is disabled, the app can only be booted by bootloaders from IDF v2.1 or newer. Enabling this setting adds approximately 1KB to the app's IRAM usage. - Default value: - - No (disabled) CONFIG_APP_COMPATIBLE_PRE_V3_1_BOOTLOADERS App compatible with bootloader and partition table before ESP-IDF v3.1 Found in: Build type Partition tables before ESP-IDF V3.1 do not contain an MD5 checksum field, and the bootloader before ESP-IDF v3.1 cannot read a partition table that contains an MD5 checksum field. Enable this option only if your app needs to boot on a bootloader and/or partition table that was generated from a version *before* ESP-IDF v3.1. If this option and Flash Encryption are enabled at the same time, and any data partitions in the partition table are marked Encrypted, then the partition encrypted flag should be manually verified in the app before accessing the partition (see CVE-2021-27926). - Default value: - - No (disabled) Bootloader config Contains: Bootloader manager Contains: CONFIG_BOOTLOADER_COMPILE_TIME_DATE Use time/date stamp for bootloader Found in: Bootloader config > Bootloader manager If set, then the bootloader will be built with the current time/date stamp. It is stored in the bootloader description structure. If not set, time/date stamp will be excluded from bootloader image. This can be useful for getting the same binary image files made from the same source, but at different times. CONFIG_BOOTLOADER_PROJECT_VER Project version Found in: Bootloader config > Bootloader manager Project version. It is placed in "version" field of the esp_bootloader_desc structure. The type of this field is "uint32_t". - Range: - - from 0 to 4294967295 - Default value: - - 1 CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION Bootloader optimization Level Found in: Bootloader config This option sets compiler optimization level (gcc -O argument) for the bootloader. - The default "Size" setting will add the -0s flag to CFLAGS. - The "Debug" setting will add the -Og flag to CFLAGS. - The "Performance" setting will add the -O2 flag to CFLAGS. Note that custom optimization levels may be unsupported. Available options: - Size (-Os) (CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE) - Debug (-Og) (CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG) - Optimize for performance (-O2) (CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_PERF) - Debug without optimization (-O0) (Deprecated, will be removed in IDF v6.0) (CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_NONE) CONFIG_BOOTLOADER_LOG_LEVEL Bootloader log verbosity Found in: Bootloader config Specify how much output to see in bootloader logs. Available options: - No output (CONFIG_BOOTLOADER_LOG_LEVEL_NONE) - Error (CONFIG_BOOTLOADER_LOG_LEVEL_ERROR) - Warning (CONFIG_BOOTLOADER_LOG_LEVEL_WARN) - Info (CONFIG_BOOTLOADER_LOG_LEVEL_INFO) - Debug (CONFIG_BOOTLOADER_LOG_LEVEL_DEBUG) - Verbose (CONFIG_BOOTLOADER_LOG_LEVEL_VERBOSE) Serial Flash Configurations Contains: CONFIG_BOOTLOADER_SPI_CUSTOM_WP_PIN Use custom SPI Flash WP Pin when flash pins set in eFuse (read help) Found in: Bootloader config > Serial Flash Configurations This setting is only used if the SPI flash pins have been overridden by setting the eFuses SPI_PAD_CONFIG_xxx, and the SPI flash mode is QIO or QOUT. When this is the case, the eFuse config only defines 3 of the 4 Quad I/O data pins. The WP pin (aka ESP32 pin "SD_DATA_3" or SPI flash pin "IO2") is not specified in eFuse. The same pin is also used for external SPIRAM if it is enabled. If this config item is set to N (default), the correct WP pin will be automatically used for any Espressif chip or module with integrated flash. If a custom setting is needed, set this config item to Y and specify the GPIO number connected to the WP. - Default value: - - No (disabled) if CONFIG_ESPTOOLPY_FLASHMODE_QIO || CONFIG_ESPTOOLPY_FLASHMODE_QOUT CONFIG_BOOTLOADER_SPI_WP_PIN Custom SPI Flash WP Pin Found in: Bootloader config > Serial Flash Configurations The option "Use custom SPI Flash WP Pin" must be set or this value is ignored If burning a customized set of SPI flash pins in eFuse and using QIO or QOUT mode for flash, set this value to the GPIO number of the SPI flash WP pin. - Range: - - from 0 to 33 if CONFIG_ESPTOOLPY_FLASHMODE_QIO || CONFIG_ESPTOOLPY_FLASHMODE_QOUT - Default value: - CONFIG_BOOTLOADER_FLASH_DC_AWARE Allow app adjust Dummy Cycle bits in SPI Flash for higher frequency (READ HELP FIRST) Found in: Bootloader config > Serial Flash Configurations This will force 2nd bootloader to be loaded by DOUT mode, and will restore Dummy Cycle setting by resetting the Flash CONFIG_BOOTLOADER_FLASH_XMC_SUPPORT Enable the support for flash chips of XMC (READ DOCS FIRST) Found in: Bootloader config > Serial Flash Configurations Perform the startup flow recommended by XMC. Please consult XMC for the details of this flow. XMC chips will be forbidden to be used, when this option is disabled. DON'T DISABLE THIS UNLESS YOU KNOW WHAT YOU ARE DOING. comment "Features below require specific hardware (READ DOCS FIRST!)" - Default value: - - Yes (enabled) CONFIG_BOOTLOADER_VDDSDIO_BOOST VDDSDIO LDO voltage Found in: Bootloader config If this option is enabled, and VDDSDIO LDO is set to 1.8V (using eFuse or MTDI bootstrapping pin), bootloader will change LDO settings to output 1.9V instead. This helps prevent flash chip from browning out during flash programming operations. This option has no effect if VDDSDIO is set to 3.3V, or if the internal VDDSDIO regulator is disabled via eFuse. Available options: - 1.8V (CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_8V) - 1.9V (CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_9V) CONFIG_BOOTLOADER_FACTORY_RESET GPIO triggers factory reset Found in: Bootloader config Allows to reset the device to factory settings: - clear one or more data partitions; - boot from "factory" partition. The factory reset will occur if there is a GPIO input held at the configured level while device starts up. See settings below. - Default value: - - No (disabled) CONFIG_BOOTLOADER_NUM_PIN_FACTORY_RESET Number of the GPIO input for factory reset Found in: Bootloader config > CONFIG_BOOTLOADER_FACTORY_RESET The selected GPIO will be configured as an input with internal pull-up enabled (note that on some SoCs. not all pins have an internal pull-up, consult the hardware datasheet for details.) To trigger a factory reset, this GPIO must be held high or low (as configured) on startup. - Range: - - from 0 to 39 if CONFIG_BOOTLOADER_FACTORY_RESET - Default value: - CONFIG_BOOTLOADER_FACTORY_RESET_PIN_LEVEL Factory reset GPIO level Found in: Bootloader config > CONFIG_BOOTLOADER_FACTORY_RESET Pin level for factory reset, can be triggered on low or high. Available options: - Reset on GPIO low (CONFIG_BOOTLOADER_FACTORY_RESET_PIN_LOW) - Reset on GPIO high (CONFIG_BOOTLOADER_FACTORY_RESET_PIN_HIGH) CONFIG_BOOTLOADER_OTA_DATA_ERASE Clear OTA data on factory reset (select factory partition) Found in: Bootloader config > CONFIG_BOOTLOADER_FACTORY_RESET The device will boot from "factory" partition (or OTA slot 0 if no factory partition is present) after a factory reset. CONFIG_BOOTLOADER_DATA_FACTORY_RESET Comma-separated names of partitions to clear on factory reset Found in: Bootloader config > CONFIG_BOOTLOADER_FACTORY_RESET Allows customers to select which data partitions will be erased while factory reset. Specify the names of partitions as a comma-delimited with optional spaces for readability. (Like this: "nvs, phy_init, ...") Make sure that the name specified in the partition table and here are the same. Partitions of type "app" cannot be specified here. - Default value: - - "nvs" if CONFIG_BOOTLOADER_FACTORY_RESET CONFIG_BOOTLOADER_APP_TEST GPIO triggers boot from test app partition Found in: Bootloader config Allows to run the test app from "TEST" partition. A boot from "test" partition will occur if there is a GPIO input pulled low while device starts up. See settings below. CONFIG_BOOTLOADER_NUM_PIN_APP_TEST Number of the GPIO input to boot TEST partition Found in: Bootloader config > CONFIG_BOOTLOADER_APP_TEST The selected GPIO will be configured as an input with internal pull-up enabled. To trigger a test app, this GPIO must be pulled low on reset. After the GPIO input is deactivated and the device reboots, the old application will boot. (factory or OTA[x]). Note that GPIO34-39 do not have an internal pullup and an external one must be provided. - Range: - - from 0 to 39 if CONFIG_BOOTLOADER_APP_TEST - Default value: - CONFIG_BOOTLOADER_APP_TEST_PIN_LEVEL App test GPIO level Found in: Bootloader config > CONFIG_BOOTLOADER_APP_TEST Pin level for app test, can be triggered on low or high. Available options: - Enter test app on GPIO low (CONFIG_BOOTLOADER_APP_TEST_PIN_LOW) - Enter test app on GPIO high (CONFIG_BOOTLOADER_APP_TEST_PIN_HIGH) CONFIG_BOOTLOADER_HOLD_TIME_GPIO Hold time of GPIO for reset/test mode (seconds) Found in: Bootloader config The GPIO must be held low continuously for this period of time after reset before a factory reset or test partition boot (as applicable) is performed. - Default value: - CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE Enable protection for unmapped memory regions Found in: Bootloader config Protects the unmapped memory regions of the entire address space from unintended accesses. This will ensure that an exception will be triggered whenever the CPU performs a memory operation on unmapped regions of the address space. - Default value: - - Yes (enabled) CONFIG_BOOTLOADER_WDT_ENABLE Use RTC watchdog in start code Found in: Bootloader config Tracks the execution time of startup code. If the execution time is exceeded, the RTC_WDT will restart system. It is also useful to prevent a lock up in start code caused by an unstable power source. NOTE: Tracks the execution time starts from the bootloader code - re-set timeout, while selecting the source for slow_clk - and ends calling app_main. Re-set timeout is needed due to WDT uses a SLOW_CLK clock source. After changing a frequency slow_clk a time of WDT needs to re-set for new frequency. slow_clk depends on RTC_CLK_SRC (INTERNAL_RC or EXTERNAL_CRYSTAL). - Default value: - - Yes (enabled) CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE Allows RTC watchdog disable in user code Found in: Bootloader config > CONFIG_BOOTLOADER_WDT_ENABLE If this option is set, the ESP-IDF app must explicitly reset, feed, or disable the rtc_wdt in the app's own code. If this option is not set (default), then rtc_wdt will be disabled by ESP-IDF before calling the app_main() function. Use function rtc_wdt_feed() for resetting counter of rtc_wdt. Use function rtc_wdt_disable() for disabling rtc_wdt. - Default value: - - No (disabled) CONFIG_BOOTLOADER_WDT_TIME_MS Timeout for RTC watchdog (ms) Found in: Bootloader config > CONFIG_BOOTLOADER_WDT_ENABLE Verify that this parameter is correct and more then the execution time. Pay attention to options such as reset to factory, trigger test partition and encryption on boot - these options can increase the execution time. Note: RTC_WDT will reset while encryption operations will be performed. - Range: - - from 0 to 120000 - Default value: - - 9000 CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE Enable app rollback support Found in: Bootloader config After updating the app, the bootloader runs a new app with the "ESP_OTA_IMG_PENDING_VERIFY" state set. This state prevents the re-run of this app. After the first boot of the new app in the user code, the function should be called to confirm the operability of the app or vice versa about its non-operability. If the app is working, then it is marked as valid. Otherwise, it is marked as not valid and rolls back to the previous working app. A reboot is performed, and the app is booted before the software update. Note: If during the first boot a new app the power goes out or the WDT works, then roll back will happen. Rollback is possible only between the apps with the same security versions. - Default value: - - No (disabled) CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK Enable app anti-rollback support Found in: Bootloader config > CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE This option prevents rollback to previous firmware/application image with lower security version. - Default value: - - No (disabled) if CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE CONFIG_BOOTLOADER_APP_SECURE_VERSION eFuse secure version of app Found in: Bootloader config > CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE > CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK The secure version is the sequence number stored in the header of each firmware. The security version is set in the bootloader, version is recorded in the eFuse field as the number of set ones. The allocated number of bits in the efuse field for storing the security version is limited (see BOOTLOADER_APP_SEC_VER_SIZE_EFUSE_FIELD option). Bootloader: When bootloader selects an app to boot, an app is selected that has a security version greater or equal that recorded in eFuse field. The app is booted with a higher (or equal) secure version. The security version is worth increasing if in previous versions there is a significant vulnerability and their use is not acceptable. Your partition table should has a scheme with ota_0 + ota_1 (without factory). - Default value: - CONFIG_BOOTLOADER_APP_SEC_VER_SIZE_EFUSE_FIELD Size of the efuse secure version field Found in: Bootloader config > CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE > CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK The size of the efuse secure version field. Its length is limited to 32 bits for ESP32 and 16 bits for ESP32-S2. This determines how many times the security version can be increased. - Range: - - from 1 to 32 if CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK - from 1 to 16 if CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK - Default value: - CONFIG_BOOTLOADER_EFUSE_SECURE_VERSION_EMULATE Emulate operations with efuse secure version(only test) Found in: Bootloader config > CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE > CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK This option allows to emulate read/write operations with all eFuses and efuse secure version. It allows to test anti-rollback implemention without permanent write eFuse bits. There should be an entry in partition table with following details: emul_efuse, data, efuse, , 0x2000. This option enables: EFUSE_VIRTUAL and EFUSE_VIRTUAL_KEEP_IN_FLASH. - Default value: - - No (disabled) if CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP Skip image validation when exiting deep sleep Found in: Bootloader config This option disables the normal validation of an image coming out of deep sleep (checksums, SHA256, and signature). This is a trade-off between wakeup performance from deep sleep, and image integrity checks. Only enable this if you know what you are doing. It should not be used in conjunction with using deep_sleep() entry and changing the active OTA partition as this would skip the validation upon first load of the new OTA partition. It is possible to enable this option with Secure Boot if "allow insecure options" is enabled, however it's strongly recommended to NOT enable it as it may allow a Secure Boot bypass. - Default value: - - No (disabled) if CONFIG_SECURE_BOOT && CONFIG_SECURE_BOOT_INSECURE CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON Skip image validation from power on reset (READ HELP FIRST) Found in: Bootloader config Some applications need to boot very quickly from power on. By default, the entire app binary is read from flash and verified which takes up a significant portion of the boot time. Enabling this option will skip validation of the app when the SoC boots from power on. Note that in this case it's not possible for the bootloader to detect if an app image is corrupted in the flash, therefore it's not possible to safely fall back to a different app partition. Flash corruption of this kind is unlikely but can happen if there is a serious firmware bug or physical damage. Following other reset types, the bootloader will still validate the app image. This increases the chances that flash corruption resulting in a crash can be detected following soft reset, and the bootloader will fall back to a valid app image. To increase the chances of successfully recovering from a flash corruption event, keep the option BOOTLOADER_WDT_ENABLE enabled and consider also enabling BOOTLOADER_WDT_DISABLE_IN_USER_CODE - then manually disable the RTC Watchdog once the app is running. In addition, enable both the Task and Interrupt watchdog timers with reset options set. - Default value: - - No (disabled) CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS Skip image validation always (READ HELP FIRST) Found in: Bootloader config Selecting this option prevents the bootloader from ever validating the app image before booting it. Any flash corruption of the selected app partition will make the entire SoC unbootable. Although flash corruption is a very rare case, it is not recommended to select this option. Consider selecting "Skip image validation from power on reset" instead. However, if boot time is the only important factor then it can be enabled. - Default value: - - No (disabled) CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC Reserve RTC FAST memory for custom purposes Found in: Bootloader config This option allows the customer to place data in the RTC FAST memory, this area remains valid when rebooted, except for power loss. This memory is located at a fixed address and is available for both the bootloader and the application. (The application and bootoloader must be compiled with the same option). The RTC FAST memory has access only through PRO_CPU. - Default value: - - No (disabled) CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC_IN_CRC Include custom memory in the CRC calculation Found in: Bootloader config > CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC This option allows the customer to use the legacy bootloader behavior when the RTC FAST memory CRC calculation takes place. When this option is enabled, the allocated user custom data will be taken into account in the CRC calculcation. This means that any change to the custom data would need a CRC update to prevent the bootloader from marking this data as corrupted. If this option is disabled, the custom data will not be taken into account when calculating the RTC FAST memory CRC. The user custom data can be changed freely, without the need to update the CRC. THIS OPTION MUST BE THE SAME FOR BOTH THE BOOTLOADER AND THE APPLICATION BUILDS. - Default value: - - No (disabled) if CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC_SIZE Size in bytes for custom purposes Found in: Bootloader config > CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC This option reserves in RTC FAST memory the area for custom purposes. If you want to create your own bootloader and save more information in this area of memory, you can increase it. It must be a multiple of 4 bytes. This area (rtc_retain_mem_t) is reserved and has access from the bootloader and an application. - Default value: - Security features Contains: CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT Require signed app images Found in: Security features Require apps to be signed to verify their integrity. This option uses the same app signature scheme as hardware secure boot, but unlike hardware secure boot it does not prevent the bootloader from being physically updated. This means that the device can be secured against remote network access, but not physical access. Compared to using hardware Secure Boot this option is much simpler to implement. CONFIG_SECURE_SIGNED_APPS_SCHEME App Signing Scheme Found in: Security features Select the Secure App signing scheme. Depends on the Chip Revision. There are two secure boot versions: - - Secure boot V1 - - Legacy custom secure boot scheme. Supported in ESP32 SoC. - - Secure boot V2 - - RSA based secure boot scheme. Supported in ESP32-ECO3 (ESP32 Chip Revision 3 onwards), ESP32-S2, ESP32-C3, ESP32-S3 SoCs. - ECDSA based secure boot scheme. Supported in ESP32-C2 SoC. Available options: - ECDSA (CONFIG_SECURE_SIGNED_APPS_ECDSA_SCHEME) Embeds the ECDSA public key in the bootloader and signs the application with an ECDSA key. Refer to the documentation before enabling. - RSA (CONFIG_SECURE_SIGNED_APPS_RSA_SCHEME) Appends the RSA-3072 based Signature block to the application. Refer to <Secure Boot Version 2 documentation link> before enabling. - ECDSA (V2) (CONFIG_SECURE_SIGNED_APPS_ECDSA_V2_SCHEME) For Secure boot V2 (e.g., ESP32-C2 SoC), appends ECDSA based signature block to the application. Refer to documentation before enabling. CONFIG_SECURE_BOOT_ECDSA_KEY_LEN_SIZE ECDSA key size Found in: Security features Select the ECDSA key size. Two key sizes are supported - 192 bit key using NISTP192 curve - 256 bit key using NISTP256 curve (Recommended) The advantage of using 256 bit key is the extra randomness which makes it difficult to be bruteforced compared to 192 bit key. At present, both key sizes are practically implausible to bruteforce. Available options: - Using ECC curve NISTP192 (CONFIG_SECURE_BOOT_ECDSA_KEY_LEN_192_BITS) - Using ECC curve NISTP256 (Recommended) (CONFIG_SECURE_BOOT_ECDSA_KEY_LEN_256_BITS) CONFIG_SECURE_SIGNED_ON_BOOT_NO_SECURE_BOOT Bootloader verifies app signatures Found in: Security features If this option is set, the bootloader will be compiled with code to verify that an app is signed before booting it. If hardware secure boot is enabled, this option is always enabled and cannot be disabled. If hardware secure boot is not enabled, this option doesn't add significant security by itself so most users will want to leave it disabled. - Default value: - - No (disabled) if CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT && CONFIG_SECURE_SIGNED_APPS_ECDSA_SCHEME CONFIG_SECURE_SIGNED_ON_UPDATE_NO_SECURE_BOOT Verify app signature on update Found in: Security features If this option is set, any OTA updated apps will have the signature verified before being considered valid. When enabled, the signature is automatically checked whenever the esp_ota_ops.h APIs are used for OTA updates, or esp_image_format.h APIs are used to verify apps. If hardware secure boot is enabled, this option is always enabled and cannot be disabled. If hardware secure boot is not enabled, this option still adds significant security against network-based attackers by preventing spoofing of OTA updates. - Default value: - - Yes (enabled) if CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT CONFIG_SECURE_BOOT Enable hardware Secure Boot in bootloader (READ DOCS FIRST) Found in: Security features Build a bootloader which enables Secure Boot on first boot. Once enabled, Secure Boot will not boot a modified bootloader. The bootloader will only load a partition table or boot an app if the data has a verified digital signature. There are implications for reflashing updated apps once secure boot is enabled. When enabling secure boot, JTAG and ROM BASIC Interpreter are permanently disabled by default. - Default value: - - No (disabled) CONFIG_SECURE_BOOT_VERSION Select secure boot version Found in: Security features > CONFIG_SECURE_BOOT Select the Secure Boot Version. Depends on the Chip Revision. Secure Boot V2 is the new RSA / ECDSA based secure boot scheme. - RSA based scheme is supported in ESP32 (Revision 3 onwards), ESP32-S2, ESP32-C3 (ECO3), ESP32-S3. - ECDSA based scheme is supported in ESP32-C2 SoC. Please note that, RSA or ECDSA secure boot is property of specific SoC based on its HW design, supported crypto accelerators, die-size, cost and similar parameters. Please note that RSA scheme has requirement for bigger key sizes but at the same time it is comparatively faster than ECDSA verification. Secure Boot V1 is the AES based (custom) secure boot scheme supported in ESP32 SoC. Available options: - Enable Secure Boot version 1 (CONFIG_SECURE_BOOT_V1_ENABLED) Build a bootloader which enables secure boot version 1 on first boot. Refer to the Secure Boot section of the ESP-IDF Programmer's Guide for this version before enabling. - Enable Secure Boot version 2 (CONFIG_SECURE_BOOT_V2_ENABLED) Build a bootloader which enables Secure Boot version 2 on first boot. Refer to Secure Boot V2 section of the ESP-IDF Programmer's Guide for this version before enabling. CONFIG_SECURE_BOOTLOADER_MODE Secure bootloader mode Found in: Security features Available options: - One-time flash (CONFIG_SECURE_BOOTLOADER_ONE_TIME_FLASH) On first boot, the bootloader will generate a key which is not readable externally or by software. A digest is generated from the bootloader image itself. This digest will be verified on each subsequent boot. Enabling this option means that the bootloader cannot be changed after the first time it is booted. - Reflashable (CONFIG_SECURE_BOOTLOADER_REFLASHABLE) Generate a reusable secure bootloader key, derived (via SHA-256) from the secure boot signing key. This allows the secure bootloader to be re-flashed by anyone with access to the secure boot signing key. This option is less secure than one-time flash, because a leak of the digest key from one device allows reflashing of any device that uses it. CONFIG_SECURE_BOOT_BUILD_SIGNED_BINARIES Sign binaries during build Found in: Security features Once secure boot or signed app requirement is enabled, app images are required to be signed. If enabled (default), these binary files are signed as part of the build process. The file named in "Secure boot private signing key" will be used to sign the image. If disabled, unsigned app/partition data will be built. They must be signed manually using espsecure.py. Version 1 to enable ECDSA Based Secure Boot and Version 2 to enable RSA based Secure Boot. (for example, on a remote signing server.) CONFIG_SECURE_BOOT_SIGNING_KEY Secure boot private signing key Found in: Security features > CONFIG_SECURE_BOOT_BUILD_SIGNED_BINARIES Path to the key file used to sign app images. Key file is an ECDSA private key (NIST256p curve) in PEM format for Secure Boot V1. Key file is an RSA private key in PEM format for Secure Boot V2. Path is evaluated relative to the project directory. You can generate a new signing key by running the following command: espsecure.py generate_signing_key secure_boot_signing_key.pem See the Secure Boot section of the ESP-IDF Programmer's Guide for this version for details. - Default value: - - "secure_boot_signing_key.pem" if CONFIG_SECURE_BOOT_BUILD_SIGNED_BINARIES CONFIG_SECURE_BOOT_VERIFICATION_KEY Secure boot public signature verification key Found in: Security features Path to a public key file used to verify signed images. Secure Boot V1: This ECDSA public key is compiled into the bootloader and/or app, to verify app images. Key file is in raw binary format, and can be extracted from a PEM formatted private key using the espsecure.py extract_public_key command. Refer to the Secure Boot section of the ESP-IDF Programmer's Guide for this version before enabling. CONFIG_SECURE_BOOT_ENABLE_AGGRESSIVE_KEY_REVOKE Enable Aggressive key revoke strategy Found in: Security features If this option is set, ROM bootloader will revoke the public key digest burned in efuse block if it fails to verify the signature of software bootloader with it. Revocation of keys does not happen when enabling secure boot. Once secure boot is enabled, key revocation checks will be done on subsequent boot-up, while verifying the software bootloader This feature provides a strong resistance against physical attacks on the device. NOTE: Once a digest slot is revoked, it can never be used again to verify an image This can lead to permanent bricking of the device, in case all keys are revoked because of signature verification failure. - Default value: - - No (disabled) if CONFIG_SECURE_BOOT && SOC_SUPPORT_SECURE_BOOT_REVOKE_KEY CONFIG_SECURE_BOOT_FLASH_BOOTLOADER_DEFAULT Flash bootloader along with other artifacts when using the default flash command Found in: Security features When Secure Boot V2 is enabled, by default the bootloader is not flashed along with other artifacts like the application and the partition table images, i.e. bootloader has to be seperately flashed using the command idf.py bootloader flash, whereas, the application and partition table can be flashed using the command idf.py flash itself. Enabling this option allows flashing the bootloader along with the other artifacts by invocation of the command idf.py flash. If this option is enabled make sure that even the bootloader is signed using the correct secure boot key, otherwise the bootloader signature verification would fail, as hash of the public key which is present in the bootloader signature would not match with the digest stored into the efuses and thus the device will not be able to boot up. - Default value: - - No (disabled) if CONFIG_SECURE_BOOT_V2_ENABLED && CONFIG_SECURE_BOOT_BUILD_SIGNED_BINARIES CONFIG_SECURE_BOOTLOADER_KEY_ENCODING Hardware Key Encoding Found in: Security features In reflashable secure bootloader mode, a hardware key is derived from the signing key (with SHA-256) and can be written to eFuse with espefuse.py. Normally this is a 256-bit key, but if 3/4 Coding Scheme is used on the device then the eFuse key is truncated to 192 bits. This configuration item doesn't change any firmware code, it only changes the size of key binary which is generated at build time. Available options: - No encoding (256 bit key) (CONFIG_SECURE_BOOTLOADER_KEY_ENCODING_256BIT) - 3/4 encoding (192 bit key) (CONFIG_SECURE_BOOTLOADER_KEY_ENCODING_192BIT) CONFIG_SECURE_BOOT_INSECURE Allow potentially insecure options Found in: Security features You can disable some of the default protections offered by secure boot, in order to enable testing or a custom combination of security features. Only enable these options if you are very sure. Refer to the Secure Boot section of the ESP-IDF Programmer's Guide for this version before enabling. - Default value: - - No (disabled) if CONFIG_SECURE_BOOT CONFIG_SECURE_FLASH_ENC_ENABLED Enable flash encryption on boot (READ DOCS FIRST) Found in: Security features If this option is set, flash contents will be encrypted by the bootloader on first boot. Note: After first boot, the system will be permanently encrypted. Re-flashing an encrypted system is complicated and not always possible. Read Flash Encryption before enabling. - Default value: - - No (disabled) CONFIG_SECURE_FLASH_ENCRYPTION_KEYSIZE Size of generated XTS-AES key Found in: Security features > CONFIG_SECURE_FLASH_ENC_ENABLED Size of generated XTS-AES key. - AES-128 uses a 256-bit key (32 bytes) derived from 128 bits (16 bytes) burned in half Efuse key block. Internally, it calculates SHA256(128 bits) - AES-128 uses a 256-bit key (32 bytes) which occupies one Efuse key block. - AES-256 uses a 512-bit key (64 bytes) which occupies two Efuse key blocks. This setting is ignored if either type of key is already burned to Efuse before the first boot. In this case, the pre-burned key is used and no new key is generated. Available options: - AES-128 key derived from 128 bits (SHA256(128 bits)) (CONFIG_SECURE_FLASH_ENCRYPTION_AES128_DERIVED) - AES-128 (256-bit key) (CONFIG_SECURE_FLASH_ENCRYPTION_AES128) - AES-256 (512-bit key) (CONFIG_SECURE_FLASH_ENCRYPTION_AES256) CONFIG_SECURE_FLASH_ENCRYPTION_MODE Enable usage mode Found in: Security features > CONFIG_SECURE_FLASH_ENC_ENABLED By default Development mode is enabled which allows ROM download mode to perform flash encryption operations (plaintext is sent to the device, and it encrypts it internally and writes ciphertext to flash.) This mode is not secure, it's possible for an attacker to write their own chosen plaintext to flash. Release mode should always be selected for production or manufacturing. Once enabled it's no longer possible for the device in ROM Download Mode to use the flash encryption hardware. When EFUSE_VIRTUAL is enabled, SECURE_FLASH_ENCRYPTION_MODE_RELEASE is not available. For CI tests we use IDF_CI_BUILD to bypass it ("export IDF_CI_BUILD=1"). We do not recommend bypassing it for other purposes. Refer to the Flash Encryption section of the ESP-IDF Programmer's Guide for details. Available options: - Development (NOT SECURE) (CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT) - Release (CONFIG_SECURE_FLASH_ENCRYPTION_MODE_RELEASE) Potentially insecure options Contains: CONFIG_SECURE_BOOT_ALLOW_ROM_BASIC Leave ROM BASIC Interpreter available on reset Found in: Security features > Potentially insecure options By default, the BASIC ROM Console starts on reset if no valid bootloader is read from the flash. When either flash encryption or secure boot are enabled, the default is to disable this BASIC fallback mode permanently via eFuse. If this option is set, this eFuse is not burned and the BASIC ROM Console may remain accessible. Only set this option in testing environments. - Default value: - - No (disabled) if CONFIG_SECURE_BOOT_INSECURE || CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT CONFIG_SECURE_BOOT_ALLOW_JTAG Allow JTAG Debugging Found in: Security features > Potentially insecure options If not set (default), the bootloader will permanently disable JTAG (across entire chip) on first boot when either secure boot or flash encryption is enabled. Setting this option leaves JTAG on for debugging, which negates all protections of flash encryption and some of the protections of secure boot. Only set this option in testing environments. - Default value: - - No (disabled) if CONFIG_SECURE_BOOT_INSECURE || CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT CONFIG_SECURE_BOOT_ALLOW_SHORT_APP_PARTITION Allow app partition length not 64KB aligned Found in: Security features > Potentially insecure options If not set (default), app partition size must be a multiple of 64KB. App images are padded to 64KB length, and the bootloader checks any trailing bytes after the signature (before the next 64KB boundary) have not been written. This is because flash cache maps entire 64KB pages into the address space. This prevents an attacker from appending unverified data after the app image in the flash, causing it to be mapped into the address space. Setting this option allows the app partition length to be unaligned, and disables padding of the app image to this length. It is generally not recommended to set this option, unless you have a legacy partitioning scheme which doesn't support 64KB aligned partition lengths. CONFIG_SECURE_BOOT_V2_ALLOW_EFUSE_RD_DIS Allow additional read protecting of efuses Found in: Security features > Potentially insecure options If not set (default, recommended), on first boot the bootloader will burn the WR_DIS_RD_DIS efuse when Secure Boot is enabled. This prevents any more efuses from being read protected. If this option is set, it will remain possible to write the EFUSE_RD_DIS efuse field after Secure Boot is enabled. This may allow an attacker to read-protect the BLK2 efuse (for ESP32) and BLOCK4-BLOCK10 (i.e. BLOCK_KEY0-BLOCK_KEY5)(for other chips) holding the public key digest, causing an immediate denial of service and possibly allowing an additional fault injection attack to bypass the signature protection. NOTE: Once a BLOCK is read-protected, the application will read all zeros from that block NOTE: If "UART ROM download mode (Permanently disabled (recommended))" or "UART ROM download mode (Permanently switch to Secure mode (recommended))" is set, then it is __NOT__ possible to read/write efuses using espefuse.py utility. However, efuse can be read/written from the application CONFIG_SECURE_BOOT_ALLOW_UNUSED_DIGEST_SLOTS Leave unused digest slots available (not revoke) Found in: Security features > Potentially insecure options If not set (default), during startup in the app all unused digest slots will be revoked. To revoke unused slot will be called esp_efuse_set_digest_revoke(num_digest) for each digest. Revoking unused digest slots makes ensures that no trusted keys can be added later by an attacker. If set, it means that you have a plan to use unused digests slots later. - Default value: - - No (disabled) if CONFIG_SECURE_BOOT_INSECURE && SOC_EFUSE_REVOKE_BOOT_KEY_DIGESTS CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_ENC Leave UART bootloader encryption enabled Found in: Security features > Potentially insecure options If not set (default), the bootloader will permanently disable UART bootloader encryption access on first boot. If set, the UART bootloader will still be able to access hardware encryption. It is recommended to only set this option in testing environments. - Default value: - - No (disabled) if CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_DEC Leave UART bootloader decryption enabled Found in: Security features > Potentially insecure options If not set (default), the bootloader will permanently disable UART bootloader decryption access on first boot. If set, the UART bootloader will still be able to access hardware decryption. Only set this option in testing environments. Setting this option allows complete bypass of flash encryption. - Default value: - - No (disabled) if CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_CACHE Leave UART bootloader flash cache enabled Found in: Security features > Potentially insecure options If not set (default), the bootloader will permanently disable UART bootloader flash cache access on first boot. If set, the UART bootloader will still be able to access the flash cache. Only set this option in testing environments. - Default value: - - No (disabled) if CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT CONFIG_SECURE_FLASH_REQUIRE_ALREADY_ENABLED Require flash encryption to be already enabled Found in: Security features > Potentially insecure options If not set (default), and flash encryption is not yet enabled in eFuses, the 2nd stage bootloader will enable flash encryption: generate the flash encryption key and program eFuses. If this option is set, and flash encryption is not yet enabled, the bootloader will error out and reboot. If flash encryption is enabled in eFuses, this option does not change the bootloader behavior. Only use this option in testing environments, to avoid accidentally enabling flash encryption on the wrong device. The device needs to have flash encryption already enabled using espefuse.py. - Default value: - - No (disabled) if CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT CONFIG_SECURE_FLASH_SKIP_WRITE_PROTECTION_CACHE Skip write-protection of DIS_CACHE (DIS_ICACHE, DIS_DCACHE) Found in: Security features > Potentially insecure options If not set (default, recommended), on the first boot the bootloader will burn the write-protection of DIS_CACHE(for ESP32) or DIS_ICACHE/DIS_DCACHE(for other chips) eFuse when Flash Encryption is enabled. Write protection for cache disable efuse prevents the chip from being blocked if it is set by accident. App and bootloader use cache so disabling it makes the chip useless for IDF. Due to other eFuses are linked with the same write protection bit (see the list below) then write-protection will not be done if these SECURE_FLASH_UART_BOOTLOADER_ALLOW_ENC, SECURE_BOOT_ALLOW_JTAG or SECURE_FLASH_UART_BOOTLOADER_ALLOW_CACHE options are selected to give a chance to turn on the chip into the release mode later. List of eFuses with the same write protection bit: ESP32: MAC, MAC_CRC, DISABLE_APP_CPU, DISABLE_BT, DIS_CACHE, VOL_LEVEL_HP_INV. ESP32-C3: DIS_ICACHE, DIS_USB_JTAG, DIS_DOWNLOAD_ICACHE, DIS_USB_SERIAL_JTAG, DIS_FORCE_DOWNLOAD, DIS_TWAI, JTAG_SEL_ENABLE, DIS_PAD_JTAG, DIS_DOWNLOAD_MANUAL_ENCRYPT. ESP32-C6: SWAP_UART_SDIO_EN, DIS_ICACHE, DIS_USB_JTAG, DIS_DOWNLOAD_ICACHE, DIS_USB_SERIAL_JTAG, DIS_FORCE_DOWNLOAD, DIS_TWAI, JTAG_SEL_ENABLE, DIS_PAD_JTAG, DIS_DOWNLOAD_MANUAL_ENCRYPT. ESP32-H2: DIS_ICACHE, DIS_USB_JTAG, POWERGLITCH_EN, DIS_FORCE_DOWNLOAD, SPI_DOWNLOAD_MSPI_DIS, DIS_TWAI, JTAG_SEL_ENABLE, DIS_PAD_JTAG, DIS_DOWNLOAD_MANUAL_ENCRYPT. ESP32-S2: DIS_ICACHE, DIS_DCACHE, DIS_DOWNLOAD_ICACHE, DIS_DOWNLOAD_DCACHE, DIS_FORCE_DOWNLOAD, DIS_USB, DIS_TWAI, DIS_BOOT_REMAP, SOFT_DIS_JTAG, HARD_DIS_JTAG, DIS_DOWNLOAD_MANUAL_ENCRYPT. ESP32-S3: DIS_ICACHE, DIS_DCACHE, DIS_DOWNLOAD_ICACHE, DIS_DOWNLOAD_DCACHE, DIS_FORCE_DOWNLOAD, DIS_USB_OTG, DIS_TWAI, DIS_APP_CPU, DIS_PAD_JTAG, DIS_DOWNLOAD_MANUAL_ENCRYPT, DIS_USB_JTAG, DIS_USB_SERIAL_JTAG, STRAP_JTAG_SEL, USB_PHY_SEL. CONFIG_SECURE_FLASH_ENCRYPT_ONLY_IMAGE_LEN_IN_APP_PART Encrypt only the app image that is present in the partition of type app Found in: Security features If set, optimise encryption time for the partition of type APP, by only encrypting the app image that is present in the partition, instead of the whole partition. The image length used for encryption is derived from the image metadata, which includes the size of the app image, checksum, hash and also the signature sector when secure boot is enabled. If not set (default), the whole partition of type APP would be encrypted, which increases the encryption time but might be useful if there is any custom data appended to the firmware image. CONFIG_SECURE_FLASH_CHECK_ENC_EN_IN_APP Check Flash Encryption enabled on app startup Found in: Security features If set (default), in an app during startup code, there is a check of the flash encryption eFuse bit is on (as the bootloader should already have set it). The app requires this bit is on to continue work otherwise abort. If not set, the app does not care if the flash encryption eFuse bit is set or not. - Default value: - - Yes (enabled) if CONFIG_SECURE_FLASH_ENC_ENABLED CONFIG_SECURE_UART_ROM_DL_MODE UART ROM download mode Found in: Security features Available options: - UART ROM download mode (Permanently disabled (recommended)) (CONFIG_SECURE_DISABLE_ROM_DL_MODE) If set, during startup the app will burn an eFuse bit to permanently disable the UART ROM Download Mode. This prevents any future use of esptool.py, espefuse.py and similar tools. Once disabled, if the SoC is booted with strapping pins set for ROM Download Mode then an error is printed instead. It is recommended to enable this option in any production application where Flash Encryption and/or Secure Boot is enabled and access to Download Mode is not required. It is also possible to permanently disable Download Mode by calling esp_efuse_disable_rom_download_mode() at runtime. - UART ROM download mode (Permanently switch to Secure mode (recommended)) (CONFIG_SECURE_ENABLE_SECURE_ROM_DL_MODE) If set, during startup the app will burn an eFuse bit to permanently switch the UART ROM Download Mode into a separate Secure Download mode. This option can only work if Download Mode is not already disabled by eFuse. Secure Download mode limits the use of Download Mode functions to update SPI config, changing baud rate, basic flash write and a command to return a summary of currently enabled security features (get_security_info). Secure Download mode is not compatible with the esptool.py flasher stub feature, espefuse.py, read/writing memory or registers, encrypted download, or any other features that interact with unsupported Download Mode commands. Secure Download mode should be enabled in any application where Flash Encryption and/or Secure Boot is enabled. Disabling this option does not immediately cancel the benefits of the security features, but it increases the potential "attack surface" for an attacker to try and bypass them with a successful physical attack. It is also possible to enable secure download mode at runtime by calling esp_efuse_enable_rom_secure_download_mode() Note: Secure Download mode is not available for ESP32 (includes revisions till ECO3). - UART ROM download mode (Enabled (not recommended)) (CONFIG_SECURE_INSECURE_ALLOW_DL_MODE) This is a potentially insecure option. Enabling this option will allow the full UART download mode to stay enabled. This option SHOULD NOT BE ENABLED for production use cases. Application manager Contains: CONFIG_APP_COMPILE_TIME_DATE Use time/date stamp for app Found in: Application manager If set, then the app will be built with the current time/date stamp. It is stored in the app description structure. If not set, time/date stamp will be excluded from app image. This can be useful for getting the same binary image files made from the same source, but at different times. CONFIG_APP_EXCLUDE_PROJECT_VER_VAR Exclude PROJECT_VER from firmware image Found in: Application manager The PROJECT_VER variable from the build system will not affect the firmware image. This value will not be contained in the esp_app_desc structure. - Default value: - - No (disabled) CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR Exclude PROJECT_NAME from firmware image Found in: Application manager The PROJECT_NAME variable from the build system will not affect the firmware image. This value will not be contained in the esp_app_desc structure. - Default value: - - No (disabled) CONFIG_APP_PROJECT_VER_FROM_CONFIG Get the project version from Kconfig Found in: Application manager If this is enabled, then config item APP_PROJECT_VER will be used for the variable PROJECT_VER. Other ways to set PROJECT_VER will be ignored. - Default value: - - No (disabled) CONFIG_APP_PROJECT_VER Project version Found in: Application manager > CONFIG_APP_PROJECT_VER_FROM_CONFIG Project version - Default value: - CONFIG_APP_RETRIEVE_LEN_ELF_SHA The length of APP ELF SHA is stored in RAM(chars) Found in: Application manager At startup, the app will read the embedded APP ELF SHA-256 hash value from flash and convert it into a string and store it in a RAM buffer. This ensures the panic handler and core dump will be able to print this string even when cache is disabled. The size of the buffer is APP_RETRIEVE_LEN_ELF_SHA plus the null terminator. Changing this value will change the size of this buffer, in bytes. - Range: - - from 8 to 64 - Default value: - - 9 Serial flasher config Contains: CONFIG_ESPTOOLPY_NO_STUB Disable download stub Found in: Serial flasher config The flasher tool sends a precompiled download stub first by default. That stub allows things like compressed downloads and more. Usually you should not need to disable that feature CONFIG_ESPTOOLPY_FLASHMODE Flash SPI mode Found in: Serial flasher config Mode the flash chip is flashed in, as well as the default mode for the binary to run in. Available options: - QIO (CONFIG_ESPTOOLPY_FLASHMODE_QIO) - QOUT (CONFIG_ESPTOOLPY_FLASHMODE_QOUT) - DIO (CONFIG_ESPTOOLPY_FLASHMODE_DIO) - DOUT (CONFIG_ESPTOOLPY_FLASHMODE_DOUT) - OPI (CONFIG_ESPTOOLPY_FLASHMODE_OPI) CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE Flash Sampling Mode Found in: Serial flasher config Available options: - STR Mode (CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_STR) - DTR Mode (CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_DTR) CONFIG_ESPTOOLPY_FLASHFREQ Flash SPI speed Found in: Serial flasher config Available options: - 120 MHz (READ DOCS FIRST) (CONFIG_ESPTOOLPY_FLASHFREQ_120M) - Optional feature for QSPI Flash. Read docs and enable CONFIG_SPI_FLASH_HPM_ENA first! - Flash 120 MHz SDR mode is stable. - Flash 120 MHz DDR mode is an experimental feature, it works when the temperature is stable. - Risks: - If your chip powers on at a certain temperature, then after the temperature increases or decreases by approximately 20 Celsius degrees (depending on the chip), the program will crash randomly. - 80 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_80M) - 64 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_64M) - 60 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_60M) - 48 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_48M) - 40 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_40M) - 32 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_32M) - 30 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_30M) - 26 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_26M) - 24 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_24M) - 20 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_20M) - 16 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_16M) - 15 MHz (CONFIG_ESPTOOLPY_FLASHFREQ_15M) CONFIG_ESPTOOLPY_FLASHSIZE Flash size Found in: Serial flasher config SPI flash size, in megabytes Available options: - 1 MB (CONFIG_ESPTOOLPY_FLASHSIZE_1MB) - 2 MB (CONFIG_ESPTOOLPY_FLASHSIZE_2MB) - 4 MB (CONFIG_ESPTOOLPY_FLASHSIZE_4MB) - 8 MB (CONFIG_ESPTOOLPY_FLASHSIZE_8MB) - 16 MB (CONFIG_ESPTOOLPY_FLASHSIZE_16MB) - 32 MB (CONFIG_ESPTOOLPY_FLASHSIZE_32MB) - 64 MB (CONFIG_ESPTOOLPY_FLASHSIZE_64MB) - 128 MB (CONFIG_ESPTOOLPY_FLASHSIZE_128MB) CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE Detect flash size when flashing bootloader Found in: Serial flasher config If this option is set, flashing the project will automatically detect the flash size of the target chip and update the bootloader image before it is flashed. Enabling this option turns off the image protection against corruption by a SHA256 digest. Updating the bootloader image before flashing would invalidate the digest. CONFIG_ESPTOOLPY_BEFORE Before flashing Found in: Serial flasher config Configure whether esptool.py should reset the ESP32 before flashing. Automatic resetting depends on the RTS & DTR signals being wired from the serial port to the ESP32. Most USB development boards do this internally. Available options: - Reset to bootloader (CONFIG_ESPTOOLPY_BEFORE_RESET) - No reset (CONFIG_ESPTOOLPY_BEFORE_NORESET) CONFIG_ESPTOOLPY_AFTER After flashing Found in: Serial flasher config Configure whether esptool.py should reset the ESP32 after flashing. Automatic resetting depends on the RTS & DTR signals being wired from the serial port to the ESP32. Most USB development boards do this internally. Available options: - Reset after flashing (CONFIG_ESPTOOLPY_AFTER_RESET) - Stay in bootloader (CONFIG_ESPTOOLPY_AFTER_NORESET) Partition Table Contains: CONFIG_PARTITION_TABLE_TYPE Partition Table Found in: Partition Table The partition table to flash to the ESP32. The partition table determines where apps, data and other resources are expected to be found. The predefined partition table CSV descriptions can be found in the components/partition_table directory. These are mostly intended for example and development use, it's expect that for production use you will copy one of these CSV files and create a custom partition CSV for your application. Available options: - Single factory app, no OTA (CONFIG_PARTITION_TABLE_SINGLE_APP) This is the default partition table, designed to fit into a 2MB or larger flash with a single 1MB app partition. The corresponding CSV file in the IDF directory is components/partition_table/partitions_singleapp.csv This partition table is not suitable for an app that needs OTA (over the air update) capability. - Single factory app (large), no OTA (CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE) This is a variation of the default partition table, that expands the 1MB app partition size to 1.5MB to fit more code. The corresponding CSV file in the IDF directory is components/partition_table/partitions_singleapp_large.csv This partition table is not suitable for an app that needs OTA (over the air update) capability. - Factory app, two OTA definitions (CONFIG_PARTITION_TABLE_TWO_OTA) This is a basic OTA-enabled partition table with a factory app partition plus two OTA app partitions. All are 1MB, so this partition table requires 4MB or larger flash size. The corresponding CSV file in the IDF directory is components/partition_table/partitions_two_ota.csv - Custom partition table CSV (CONFIG_PARTITION_TABLE_CUSTOM) Specify the path to the partition table CSV to use for your project. Consult the Partition Table section in the ESP-IDF Programmers Guide for more information. - Single factory app, no OTA, encrypted NVS (CONFIG_PARTITION_TABLE_SINGLE_APP_ENCRYPTED_NVS) This is a variation of the default "Single factory app, no OTA" partition table that supports encrypted NVS when using flash encryption. See the Flash Encryption section in the ESP-IDF Programmers Guide for more information. The corresponding CSV file in the IDF directory is components/partition_table/partitions_singleapp_encr_nvs.csv - Single factory app (large), no OTA, encrypted NVS (CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE_ENC_NVS) This is a variation of the "Single factory app (large), no OTA" partition table that supports encrypted NVS when using flash encryption. See the Flash Encryption section in the ESP-IDF Programmers Guide for more information. The corresponding CSV file in the IDF directory is components/partition_table/partitions_singleapp_large_encr_nvs.csv - Factory app, two OTA definitions, encrypted NVS (CONFIG_PARTITION_TABLE_TWO_OTA_ENCRYPTED_NVS) This is a variation of the "Factory app, two OTA definitions" partition table that supports encrypted NVS when using flash encryption. See the Flash Encryption section in the ESP-IDF Programmers Guide for more information. The corresponding CSV file in the IDF directory is components/partition_table/partitions_two_ota_encr_nvs.csv CONFIG_PARTITION_TABLE_CUSTOM_FILENAME Custom partition CSV file Found in: Partition Table Name of the custom partition CSV filename. This path is evaluated relative to the project root directory. - Default value: - - "partitions.csv" CONFIG_PARTITION_TABLE_OFFSET Offset of partition table Found in: Partition Table The address of partition table (by default 0x8000). Allows you to move the partition table, it gives more space for the bootloader. Note that the bootloader and app will both need to be compiled with the same PARTITION_TABLE_OFFSET value. This number should be a multiple of 0x1000. Note that partition offsets in the partition table CSV file may need to be changed if this value is set to a higher value. To have each partition offset adapt to the configured partition table offset, leave all partition offsets blank in the CSV file. - Default value: - - "0x8000" CONFIG_PARTITION_TABLE_MD5 Generate an MD5 checksum for the partition table Found in: Partition Table Generate an MD5 checksum for the partition table for protecting the integrity of the table. The generation should be turned off for legacy bootloaders which cannot recognize the MD5 checksum in the partition table. Compiler options Contains: CONFIG_COMPILER_OPTIMIZATION Optimization Level Found in: Compiler options This option sets compiler optimization level (gcc -O argument) for the app. - The "Debug" setting will add the -0g flag to CFLAGS. - The "Size" setting will add the -0s flag to CFLAGS. - The "Performance" setting will add the -O2 flag to CFLAGS. - The "None" setting will add the -O0 flag to CFLAGS. The "Size" setting cause the compiled code to be smaller and faster, but may lead to difficulties of correlating code addresses to source file lines when debugging. The "Performance" setting causes the compiled code to be larger and faster, but will be easier to correlated code addresses to source file lines. "None" with -O0 produces compiled code without optimization. Note that custom optimization levels may be unsupported. Compiler optimization for the IDF bootloader is set separately, see the BOOTLOADER_COMPILER_OPTIMIZATION setting. Available options: - Debug (-Og) (CONFIG_COMPILER_OPTIMIZATION_DEBUG) - Optimize for size (-Os) (CONFIG_COMPILER_OPTIMIZATION_SIZE) - Optimize for performance (-O2) (CONFIG_COMPILER_OPTIMIZATION_PERF) - Debug without optimization (-O0) (CONFIG_COMPILER_OPTIMIZATION_NONE) CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL Assertion level Found in: Compiler options Assertions can be: - Enabled. Failure will print verbose assertion details. This is the default. - Set to "silent" to save code size (failed assertions will abort() but user needs to use the aborting address to find the line number with the failed assertion.) - Disabled entirely (not recommended for most configurations.) -DNDEBUG is added to CPPFLAGS in this case. Available options: - Enabled (CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE) Enable assertions. Assertion content and line number will be printed on failure. - Silent (saves code size) (CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT) Enable silent assertions. Failed assertions will abort(), user needs to use the aborting address to find the line number with the failed assertion. - Disabled (sets -DNDEBUG) (CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE) If assertions are disabled, -DNDEBUG is added to CPPFLAGS. CONFIG_COMPILER_FLOAT_LIB_FROM Compiler float lib source Found in: Compiler options In the soft-fp part of libgcc, riscv version is written in C, and handles all edge cases in IEEE754, which makes it larger and performance is slow. RVfplib is an optimized RISC-V library for FP arithmetic on 32-bit integer processors, for single and double-precision FP. RVfplib is "fast", but it has a few exceptions from IEEE 754 compliance. Available options: - libgcc (CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB) - librvfp (CONFIG_COMPILER_FLOAT_LIB_FROM_RVFPLIB) CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT Disable messages in ESP_RETURN_ON_* and ESP_EXIT_ON_* macros Found in: Compiler options If enabled, the error messages will be discarded in following check macros: - ESP_RETURN_ON_ERROR - ESP_EXIT_ON_ERROR - ESP_RETURN_ON_FALSE - ESP_EXIT_ON_FALSE - Default value: - - No (disabled) CONFIG_COMPILER_HIDE_PATHS_MACROS Replace ESP-IDF and project paths in binaries Found in: Compiler options When expanding the __FILE__ and __BASE_FILE__ macros, replace paths inside ESP-IDF with paths relative to the placeholder string "IDF", and convert paths inside the project directory to relative paths. This allows building the project with assertions or other code that embeds file paths, without the binary containing the exact path to the IDF or project directories. This option passes -fmacro-prefix-map options to the GCC command line. To replace additional paths in your binaries, modify the project CMakeLists.txt file to pass custom -fmacro-prefix-map or -ffile-prefix-map arguments. - Default value: - - Yes (enabled) CONFIG_COMPILER_CXX_EXCEPTIONS Enable C++ exceptions Found in: Compiler options Enabling this option compiles all IDF C++ files with exception support enabled. Disabling this option disables C++ exception support in all compiled files, and any libstdc++ code which throws an exception will abort instead. Enabling this option currently adds an additional ~500 bytes of heap overhead when an exception is thrown in user code for the first time. - Default value: - - No (disabled) Contains: CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE Emergency Pool Size Found in: Compiler options > CONFIG_COMPILER_CXX_EXCEPTIONS Size (in bytes) of the emergency memory pool for C++ exceptions. This pool will be used to allocate memory for thrown exceptions when there is not enough memory on the heap. - Default value: - CONFIG_COMPILER_CXX_RTTI Enable C++ run-time type info (RTTI) Found in: Compiler options Enabling this option compiles all C++ files with RTTI support enabled. This increases binary size (typically by tens of kB) but allows using dynamic_cast conversion and typeid operator. - Default value: - - No (disabled) CONFIG_COMPILER_STACK_CHECK_MODE Stack smashing protection mode Found in: Compiler options Stack smashing protection mode. Emit extra code to check for buffer overflows, such as stack smashing attacks. This is done by adding a guard variable to functions with vulnerable objects. The guards are initialized when a function is entered and then checked when the function exits. If a guard check fails, program is halted. Protection has the following modes: - In NORMAL mode (GCC flag: -fstack-protector) only functions that call alloca, and functions with buffers larger than 8 bytes are protected. - STRONG mode (GCC flag: -fstack-protector-strong) is like NORMAL, but includes additional functions to be protected -- those that have local array definitions, or have references to local frame addresses. - In OVERALL mode (GCC flag: -fstack-protector-all) all functions are protected. Modes have the following impact on code performance and coverage: - performance: NORMAL > STRONG > OVERALL - coverage: NORMAL < STRONG < OVERALL The performance impact includes increasing the amount of stack memory required for each task. Available options: - None (CONFIG_COMPILER_STACK_CHECK_MODE_NONE) - Normal (CONFIG_COMPILER_STACK_CHECK_MODE_NORM) - Strong (CONFIG_COMPILER_STACK_CHECK_MODE_STRONG) - Overall (CONFIG_COMPILER_STACK_CHECK_MODE_ALL) CONFIG_COMPILER_WARN_WRITE_STRINGS Enable -Wwrite-strings warning flag Found in: Compiler options Adds -Wwrite-strings flag for the C/C++ compilers. For C, this gives string constants the type const char[]so that copying the address of one into a non-const char \*pointer produces a warning. This warning helps to find at compile time code that tries to write into a string constant. For C++, this warns about the deprecated conversion from string literals to char \*. - Default value: - - No (disabled) CONFIG_COMPILER_DISABLE_GCC12_WARNINGS Disable new warnings introduced in GCC 12 Found in: Compiler options Enable this option if use GCC 12 or newer, and want to disable warnings which don't appear with GCC 11. - Default value: - - No (disabled) CONFIG_COMPILER_DISABLE_GCC13_WARNINGS Disable new warnings introduced in GCC 13 Found in: Compiler options Enable this option if use GCC 13 or newer, and want to disable warnings which don't appear with GCC 12. - Default value: - - No (disabled) CONFIG_COMPILER_DUMP_RTL_FILES Dump RTL files during compilation Found in: Compiler options If enabled, RTL files will be produced during compilation. These files can be used by other tools, for example to calculate call graphs. CONFIG_COMPILER_RT_LIB Compiler runtime library Found in: Compiler options Select runtime library to be used by compiler. - GCC toolchain supports libgcc only. - Clang allows to choose between libgcc or libclang_rt. - For host builds ("linux" target), uses the default library. Available options: - libgcc (CONFIG_COMPILER_RT_LIB_GCCLIB) - libclang_rt (CONFIG_COMPILER_RT_LIB_CLANGRT) - Host (CONFIG_COMPILER_RT_LIB_HOST) Component config Contains: Application Level Tracing Contains: CONFIG_APPTRACE_DESTINATION1 Data Destination 1 Found in: Component config > Application Level Tracing Select destination for application trace: JTAG or none (to disable). Available options: - JTAG (CONFIG_APPTRACE_DEST_JTAG) - None (CONFIG_APPTRACE_DEST_NONE) CONFIG_APPTRACE_DESTINATION2 Data Destination 2 Found in: Component config > Application Level Tracing Select destination for application trace: UART(XX) or none (to disable). Available options: - UART0 (CONFIG_APPTRACE_DEST_UART0) - UART1 (CONFIG_APPTRACE_DEST_UART1) - UART2 (CONFIG_APPTRACE_DEST_UART2) - USB_CDC (CONFIG_APPTRACE_DEST_USB_CDC) - None (CONFIG_APPTRACE_DEST_UART_NONE) CONFIG_APPTRACE_UART_TX_GPIO UART TX on GPIO# Found in: Component config > Application Level Tracing This GPIO is used for UART TX pin. CONFIG_APPTRACE_UART_RX_GPIO UART RX on GPIO# Found in: Component config > Application Level Tracing This GPIO is used for UART RX pin. CONFIG_APPTRACE_UART_BAUDRATE UART baud rate Found in: Component config > Application Level Tracing This baud rate is used for UART. The app's maximum baud rate depends on the UART clock source. If Power Management is disabled, the UART clock source is the APB clock and all baud rates in the available range will be sufficiently accurate. If Power Management is enabled, REF_TICK clock source is used so the baud rate is divided from 1MHz. Baud rates above 1Mbps are not possible and values between 500Kbps and 1Mbps may not be accurate. CONFIG_APPTRACE_UART_RX_BUFF_SIZE UART RX ring buffer size Found in: Component config > Application Level Tracing Size of the UART input ring buffer. This size related to the baudrate, system tick frequency and amount of data to transfer. The data placed to this buffer before sent out to the interface. CONFIG_APPTRACE_UART_TX_BUFF_SIZE UART TX ring buffer size Found in: Component config > Application Level Tracing Size of the UART output ring buffer. This size related to the baudrate, system tick frequency and amount of data to transfer. CONFIG_APPTRACE_UART_TX_MSG_SIZE UART TX message size Found in: Component config > Application Level Tracing Maximum size of the single message to transfer. CONFIG_APPTRACE_UART_TASK_PRIO UART Task Priority Found in: Component config > Application Level Tracing UART task priority. In case of high events rate, this parameter could be changed up to (configMAX_PRIORITIES-1). - Range: - - from 1 to 32 - Default value: - - 1 CONFIG_APPTRACE_ONPANIC_HOST_FLUSH_TMO Timeout for flushing last trace data to host on panic Found in: Component config > Application Level Tracing Timeout for flushing last trace data to host in case of panic. In ms. Use -1 to disable timeout and wait forever. CONFIG_APPTRACE_POSTMORTEM_FLUSH_THRESH Threshold for flushing last trace data to host on panic Found in: Component config > Application Level Tracing Threshold for flushing last trace data to host on panic in post-mortem mode. This is minimal amount of data needed to perform flush. In bytes. CONFIG_APPTRACE_BUF_SIZE Size of the apptrace buffer Found in: Component config > Application Level Tracing Size of the memory buffer for trace data in bytes. CONFIG_APPTRACE_PENDING_DATA_SIZE_MAX Size of the pending data buffer Found in: Component config > Application Level Tracing Size of the buffer for events in bytes. It is useful for buffering events from the time critical code (scheduler, ISRs etc). If this parameter is 0 then events will be discarded when main HW buffer is full. FreeRTOS SystemView Tracing Contains: CONFIG_APPTRACE_SV_ENABLE SystemView Tracing Enable Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables supporrt for SEGGER SystemView tracing functionality. CONFIG_APPTRACE_SV_DEST SystemView destination Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing > CONFIG_APPTRACE_SV_ENABLE SystemView witt transfer data trough defined interface. Available options: - Data destination JTAG (CONFIG_APPTRACE_SV_DEST_JTAG) Send SEGGER SystemView events through JTAG interface. - Data destination UART (CONFIG_APPTRACE_SV_DEST_UART) Send SEGGER SystemView events through UART interface. CONFIG_APPTRACE_SV_CPU CPU to trace Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Define the CPU to trace by SystemView. Available options: - CPU0 (CONFIG_APPTRACE_SV_DEST_CPU_0) Send SEGGER SystemView events for Pro CPU. - CPU1 (CONFIG_APPTRACE_SV_DEST_CPU_1) Send SEGGER SystemView events for App CPU. CONFIG_APPTRACE_SV_TS_SOURCE Timer to use as timestamp source Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing SystemView needs to use a hardware timer as the source of timestamps when tracing. This option selects the timer for it. Available options: - CPU cycle counter (CCOUNT) (CONFIG_APPTRACE_SV_TS_SOURCE_CCOUNT) - General Purpose Timer (Timer Group) (CONFIG_APPTRACE_SV_TS_SOURCE_GPTIMER) - esp_timer high resolution timer (CONFIG_APPTRACE_SV_TS_SOURCE_ESP_TIMER) CONFIG_APPTRACE_SV_MAX_TASKS Maximum supported tasks Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Configures maximum supported tasks in sysview debug CONFIG_APPTRACE_SV_BUF_WAIT_TMO Trace buffer wait timeout Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Configures timeout (in us) to wait for free space in trace buffer. Set to -1 to wait forever and avoid lost events. CONFIG_APPTRACE_SV_EVT_OVERFLOW_ENABLE Trace Buffer Overflow Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Trace Buffer Overflow" event. CONFIG_APPTRACE_SV_EVT_ISR_ENTER_ENABLE ISR Enter Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "ISR Enter" event. CONFIG_APPTRACE_SV_EVT_ISR_EXIT_ENABLE ISR Exit Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "ISR Exit" event. CONFIG_APPTRACE_SV_EVT_ISR_TO_SCHED_ENABLE ISR Exit to Scheduler Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "ISR to Scheduler" event. CONFIG_APPTRACE_SV_EVT_TASK_START_EXEC_ENABLE Task Start Execution Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Task Start Execution" event. CONFIG_APPTRACE_SV_EVT_TASK_STOP_EXEC_ENABLE Task Stop Execution Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Task Stop Execution" event. CONFIG_APPTRACE_SV_EVT_TASK_START_READY_ENABLE Task Start Ready State Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Task Start Ready State" event. CONFIG_APPTRACE_SV_EVT_TASK_STOP_READY_ENABLE Task Stop Ready State Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Task Stop Ready State" event. CONFIG_APPTRACE_SV_EVT_TASK_CREATE_ENABLE Task Create Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Task Create" event. CONFIG_APPTRACE_SV_EVT_TASK_TERMINATE_ENABLE Task Terminate Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Task Terminate" event. CONFIG_APPTRACE_SV_EVT_IDLE_ENABLE System Idle Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "System Idle" event. CONFIG_APPTRACE_SV_EVT_TIMER_ENTER_ENABLE Timer Enter Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Timer Enter" event. CONFIG_APPTRACE_SV_EVT_TIMER_EXIT_ENABLE Timer Exit Event Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing Enables "Timer Exit" event. CONFIG_APPTRACE_GCOV_ENABLE GCOV to Host Enable Found in: Component config > Application Level Tracing Enables support for GCOV data transfer to host. CONFIG_APPTRACE_GCOV_DUMP_TASK_STACK_SIZE Gcov dump task stack size Found in: Component config > Application Level Tracing > CONFIG_APPTRACE_GCOV_ENABLE Configures stack size of Gcov dump task - Default value: - - 2048 if CONFIG_APPTRACE_GCOV_ENABLE Bluetooth Contains: CONFIG_BT_ENABLED Bluetooth Found in: Component config > Bluetooth Select this option to enable Bluetooth and show the submenu with Bluetooth configuration choices. CONFIG_BT_HOST Host Found in: Component config > Bluetooth > CONFIG_BT_ENABLED This helps to choose Bluetooth host stack Available options: - Bluedroid - Dual-mode (CONFIG_BT_BLUEDROID_ENABLED) This option is recommended for classic Bluetooth or for dual-mode usecases - NimBLE - BLE only (CONFIG_BT_NIMBLE_ENABLED) This option is recommended for BLE only usecases to save on memory - Disabled (CONFIG_BT_CONTROLLER_ONLY) This option is recommended when you want to communicate directly with the controller (without any host) or when you are using any other host stack not supported by Espressif (not mentioned here). CONFIG_BT_CONTROLLER Controller Found in: Component config > Bluetooth > CONFIG_BT_ENABLED This helps to choose Bluetooth controller stack Available options: - Enabled (CONFIG_BT_CONTROLLER_ENABLED) This option is recommended for Bluetooth controller usecases - Disabled (CONFIG_BT_CONTROLLER_DISABLED) This option is recommended for Bluetooth Host only usecases Bluedroid Options Contains: CONFIG_BT_BTC_TASK_STACK_SIZE Bluetooth event (callback to application) task stack size Found in: Component config > Bluetooth > Bluedroid Options This select btc task stack size - Default value: - CONFIG_BT_BLUEDROID_PINNED_TO_CORE_CHOICE The cpu core which Bluedroid run Found in: Component config > Bluetooth > Bluedroid Options Which the cpu core to run Bluedroid. Can choose core0 and core1. Can not specify no-affinity. Available options: - Core 0 (PRO CPU) (CONFIG_BT_BLUEDROID_PINNED_TO_CORE_0) - Core 1 (APP CPU) (CONFIG_BT_BLUEDROID_PINNED_TO_CORE_1) CONFIG_BT_BTU_TASK_STACK_SIZE Bluetooth Bluedroid Host Stack task stack size Found in: Component config > Bluetooth > Bluedroid Options This select btu task stack size - Default value: - CONFIG_BT_BLUEDROID_MEM_DEBUG Bluedroid memory debug Found in: Component config > Bluetooth > Bluedroid Options Bluedroid memory debug - Default value: - - No (disabled) if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLUEDROID_ESP_COEX_VSC Enable Espressif Vendor-specific HCI commands for coexist status configuration Found in: Component config > Bluetooth > Bluedroid Options Enable Espressif Vendor-specific HCI commands for coexist status configuration - Default value: - - Yes (enabled) if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_CLASSIC_ENABLED Classic Bluetooth Found in: Component config > Bluetooth > Bluedroid Options For now this option needs "SMP_ENABLE" to be set to yes - Default value: - - No (disabled) if CONFIG_BT_BLUEDROID_ENABLED && (CONFIG_BT_CONTROLLER_ENABLED || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_CLASSIC_BQB_ENABLED Host Qualitifcation support for Classic Bluetooth Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED This enables functionalities of Host qualification for Classic Bluetooth. - Default value: - - No (disabled) if CONFIG_BT_CLASSIC_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_A2DP_ENABLE A2DP Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED Advanced Audio Distrubution Profile - Default value: - - No (disabled) if CONFIG_BT_CLASSIC_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_SPP_ENABLED SPP Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED This enables the Serial Port Profile - Default value: - - No (disabled) if CONFIG_BT_CLASSIC_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_L2CAP_ENABLED BT L2CAP Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED This enables the Logical Link Control and Adaptation Layer Protocol. Only supported classic bluetooth. - Default value: - - No (disabled) if CONFIG_BT_CLASSIC_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_HFP_ENABLE Hands Free/Handset Profile Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED Hands Free Unit and Audio Gateway can be included simultaneously but they cannot run simultaneously due to internal limitations. - Default value: - - No (disabled) if CONFIG_BT_CLASSIC_ENABLED && CONFIG_BT_BLUEDROID_ENABLED Contains: CONFIG_BT_HFP_CLIENT_ENABLE Hands Free Unit Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED > CONFIG_BT_HFP_ENABLE - Default value: - - Yes (enabled) if CONFIG_BT_HFP_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_HFP_AG_ENABLE Audio Gateway Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED > CONFIG_BT_HFP_ENABLE - Default value: - - Yes (enabled) if CONFIG_BT_HFP_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_HFP_AUDIO_DATA_PATH audio(SCO) data path Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED > CONFIG_BT_HFP_ENABLE SCO data path, i.e. HCI or PCM. This option is set using API "esp_bredr_sco_datapath_set" in Bluetooth host. Default SCO data path can also be set in Bluetooth Controller. Available options: - PCM (CONFIG_BT_HFP_AUDIO_DATA_PATH_PCM) - HCI (CONFIG_BT_HFP_AUDIO_DATA_PATH_HCI) CONFIG_BT_HFP_WBS_ENABLE Wide Band Speech Found in: Component config > Bluetooth > Bluedroid Options This enables Wide Band Speech. Should disable it when SCO data path is PCM. Otherwise there will be no data transmited via GPIOs. - Default value: - - Yes (enabled) if CONFIG_BT_HFP_AUDIO_DATA_PATH_HCI && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_HID_ENABLED Classic BT HID Found in: Component config > Bluetooth > Bluedroid Options This enables the BT HID Host - Default value: - - No (disabled) if CONFIG_BT_CLASSIC_ENABLED && CONFIG_BT_BLUEDROID_ENABLED Contains: CONFIG_BT_HID_HOST_ENABLED Classic BT HID Host Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_HID_ENABLED This enables the BT HID Host - Default value: - - No (disabled) if CONFIG_BT_HID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_HID_DEVICE_ENABLED Classic BT HID Device Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_HID_ENABLED This enables the BT HID Device CONFIG_BT_BLE_ENABLED Bluetooth Low Energy Found in: Component config > Bluetooth > Bluedroid Options This enables Bluetooth Low Energy - Default value: - - Yes (enabled) if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATTS_ENABLE Include GATT server module(GATTS) Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED This option can be disabled when the app work only on gatt client mode - Default value: - - Yes (enabled) if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATTS_PPCP_CHAR_GAP Enable Peripheral Preferred Connection Parameters characteristic in GAP service Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE This enables "Peripheral Preferred Connection Parameters" characteristic (UUID: 0x2A04) in GAP service that has connection parameters like min/max connection interval, slave latency and supervision timeout multiplier - Default value: - - No (disabled) if CONFIG_BT_GATTS_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_BLUFI_ENABLE Include blufi function Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE This option can be close when the app does not require blufi function. - Default value: - - No (disabled) if CONFIG_BT_GATTS_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATT_MAX_SR_PROFILES Max GATT Server Profiles Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE Maximum GATT Server Profiles Count - Range: - - from 1 to 32 if CONFIG_BT_GATTS_ENABLE && CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED - Default value: - CONFIG_BT_GATT_MAX_SR_ATTRIBUTES Max GATT Service Attributes Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE Maximum GATT Service Attributes Count - Range: - - from 1 to 500 if CONFIG_BT_GATTS_ENABLE && CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED - Default value: - CONFIG_BT_GATTS_SEND_SERVICE_CHANGE_MODE GATTS Service Change Mode Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE Service change indication mode for GATT Server. Available options: - GATTS manually send service change indication (CONFIG_BT_GATTS_SEND_SERVICE_CHANGE_MANUAL) Manually send service change indication through API esp_ble_gatts_send_service_change_indication() - GATTS automatically send service change indication (CONFIG_BT_GATTS_SEND_SERVICE_CHANGE_AUTO) Let Bluedroid handle the service change indication internally CONFIG_BT_GATTS_ROBUST_CACHING_ENABLED Enable Robust Caching on Server Side Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE This option enables the GATT robust caching feature on the server. if turned on, the Client Supported Features characteristic, Database Hash characteristic, and Server Supported Features characteristic will be included in the GAP SERVICE. - Default value: - - No (disabled) if CONFIG_BT_GATTS_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATTS_DEVICE_NAME_WRITABLE Allow to write device name by GATT clients Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE Enabling this option allows remote GATT clients to write device name - Default value: - - No (disabled) if CONFIG_BT_GATTS_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATTS_APPEARANCE_WRITABLE Allow to write appearance by GATT clients Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTS_ENABLE Enabling this option allows remote GATT clients to write appearance - Default value: - - No (disabled) if CONFIG_BT_GATTS_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATTC_ENABLE Include GATT client module(GATTC) Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED This option can be close when the app work only on gatt server mode - Default value: - - Yes (enabled) if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATTC_MAX_CACHE_CHAR Max gattc cache characteristic for discover Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTC_ENABLE Maximum GATTC cache characteristic count - Range: - - from 1 to 500 if CONFIG_BT_GATTC_ENABLE && CONFIG_BT_BLUEDROID_ENABLED - Default value: - CONFIG_BT_GATTC_NOTIF_REG_MAX Max gattc notify(indication) register number Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTC_ENABLE Maximum GATTC notify(indication) register number - Range: - - from 1 to 64 if CONFIG_BT_GATTC_ENABLE && CONFIG_BT_BLUEDROID_ENABLED - Default value: - CONFIG_BT_GATTC_CACHE_NVS_FLASH Save gattc cache data to nvs flash Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTC_ENABLE This select can save gattc cache data to nvs flash - Default value: - - No (disabled) if CONFIG_BT_GATTC_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_GATTC_CONNECT_RETRY_COUNT The number of attempts to reconnect if the connection establishment failed Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_GATTC_ENABLE The number of attempts to reconnect if the connection establishment failed - Range: - - from 0 to 7 if CONFIG_BT_GATTC_ENABLE && CONFIG_BT_BLUEDROID_ENABLED - Default value: - CONFIG_BT_BLE_SMP_ENABLE Include BLE security module(SMP) Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED This option can be close when the app not used the ble security connect. - Default value: - - Yes (enabled) if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_SMP_SLAVE_CON_PARAMS_UPD_ENABLE Slave enable connection parameters update during pairing Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CONFIG_BT_BLE_SMP_ENABLE In order to reduce the pairing time, slave actively initiates connection parameters update during pairing. - Default value: - - No (disabled) if CONFIG_BT_BLE_SMP_ENABLE && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_STACK_NO_LOG Disable BT debug logs (minimize bin size) Found in: Component config > Bluetooth > Bluedroid Options This select can save the rodata code size - Default value: - - No (disabled) if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED BT DEBUG LOG LEVEL Contains: CONFIG_BT_LOG_HCI_TRACE_LEVEL HCI layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for HCI layer Available options: - NONE (CONFIG_BT_LOG_HCI_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_HCI_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_HCI_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_HCI_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_HCI_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_HCI_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_HCI_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_BTM_TRACE_LEVEL BTM layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for BTM layer Available options: - NONE (CONFIG_BT_LOG_BTM_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_BTM_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_BTM_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_BTM_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_BTM_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_BTM_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_BTM_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_L2CAP_TRACE_LEVEL L2CAP layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for L2CAP layer Available options: - NONE (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL RFCOMM layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for RFCOMM layer Available options: - NONE (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_SDP_TRACE_LEVEL SDP layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for SDP layer Available options: - NONE (CONFIG_BT_LOG_SDP_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_SDP_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_SDP_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_SDP_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_SDP_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_SDP_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_SDP_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_GAP_TRACE_LEVEL GAP layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for GAP layer Available options: - NONE (CONFIG_BT_LOG_GAP_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_GAP_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_GAP_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_GAP_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_GAP_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_GAP_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_GAP_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_BNEP_TRACE_LEVEL BNEP layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for BNEP layer Available options: - NONE (CONFIG_BT_LOG_BNEP_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_BNEP_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_BNEP_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_BNEP_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_BNEP_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_BNEP_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_BNEP_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_PAN_TRACE_LEVEL PAN layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for PAN layer Available options: - NONE (CONFIG_BT_LOG_PAN_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_PAN_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_PAN_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_PAN_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_PAN_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_PAN_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_PAN_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_A2D_TRACE_LEVEL A2D layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for A2D layer Available options: - NONE (CONFIG_BT_LOG_A2D_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_A2D_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_A2D_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_A2D_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_A2D_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_A2D_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_A2D_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_AVDT_TRACE_LEVEL AVDT layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for AVDT layer Available options: - NONE (CONFIG_BT_LOG_AVDT_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_AVDT_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_AVDT_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_AVDT_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_AVDT_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_AVDT_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_AVDT_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_AVCT_TRACE_LEVEL AVCT layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for AVCT layer Available options: - NONE (CONFIG_BT_LOG_AVCT_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_AVCT_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_AVCT_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_AVCT_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_AVCT_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_AVCT_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_AVCT_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_AVRC_TRACE_LEVEL AVRC layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for AVRC layer Available options: - NONE (CONFIG_BT_LOG_AVRC_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_AVRC_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_AVRC_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_AVRC_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_AVRC_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_AVRC_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_AVRC_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_MCA_TRACE_LEVEL MCA layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for MCA layer Available options: - NONE (CONFIG_BT_LOG_MCA_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_MCA_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_MCA_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_MCA_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_MCA_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_MCA_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_MCA_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_HID_TRACE_LEVEL HID layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for HID layer Available options: - NONE (CONFIG_BT_LOG_HID_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_HID_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_HID_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_HID_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_HID_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_HID_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_HID_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_APPL_TRACE_LEVEL APPL layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for APPL layer Available options: - NONE (CONFIG_BT_LOG_APPL_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_APPL_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_APPL_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_APPL_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_APPL_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_APPL_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_APPL_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_GATT_TRACE_LEVEL GATT layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for GATT layer Available options: - NONE (CONFIG_BT_LOG_GATT_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_GATT_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_GATT_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_GATT_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_GATT_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_GATT_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_GATT_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_SMP_TRACE_LEVEL SMP layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for SMP layer Available options: - NONE (CONFIG_BT_LOG_SMP_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_SMP_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_SMP_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_SMP_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_SMP_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_SMP_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_SMP_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_BTIF_TRACE_LEVEL BTIF layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for BTIF layer Available options: - NONE (CONFIG_BT_LOG_BTIF_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_BTIF_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_BTIF_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_BTIF_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_BTIF_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_BTIF_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_BTIF_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_BTC_TRACE_LEVEL BTC layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for BTC layer Available options: - NONE (CONFIG_BT_LOG_BTC_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_BTC_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_BTC_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_BTC_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_BTC_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_BTC_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_BTC_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_OSI_TRACE_LEVEL OSI layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for OSI layer Available options: - NONE (CONFIG_BT_LOG_OSI_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_OSI_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_OSI_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_OSI_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_OSI_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_OSI_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_OSI_TRACE_LEVEL_VERBOSE) CONFIG_BT_LOG_BLUFI_TRACE_LEVEL BLUFI layer Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL Define BT trace level for BLUFI layer Available options: - NONE (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_NONE) - ERROR (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_WARNING) - API (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_API) - EVENT (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_EVENT) - DEBUG (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_VERBOSE) CONFIG_BT_ACL_CONNECTIONS BT/BLE MAX ACL CONNECTIONS(1~9) Found in: Component config > Bluetooth > Bluedroid Options Maximum BT/BLE connection count. The ESP32-C3/S3 chip supports a maximum of 10 instances, including ADV, SCAN and connections. The ESP32-C3/S3 chip can connect up to 9 devices if ADV or SCAN uses only one. If ADV and SCAN are both used, The ESP32-C3/S3 chip is connected to a maximum of 8 devices. Because Bluetooth cannot reclaim used instances once ADV or SCAN is used. - Range: - - from 1 to 9 if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED - Default value: - CONFIG_BT_MULTI_CONNECTION_ENBALE Enable BLE multi-conections Found in: Component config > Bluetooth > Bluedroid Options Enable this option if there are multiple connections - Default value: - - Yes (enabled) if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_ALLOCATION_FROM_SPIRAM_FIRST BT/BLE will first malloc the memory from the PSRAM Found in: Component config > Bluetooth > Bluedroid Options This select can save the internal RAM if there have the PSRAM - Default value: - - No (disabled) if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_DYNAMIC_ENV_MEMORY Use dynamic memory allocation in BT/BLE stack Found in: Component config > Bluetooth > Bluedroid Options This select can make the allocation of memory will become more flexible - Default value: - - No (disabled) if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_HOST_QUEUE_CONG_CHECK BLE queue congestion check Found in: Component config > Bluetooth > Bluedroid Options When scanning and scan duplicate is not enabled, if there are a lot of adv packets around or application layer handling adv packets is slow, it will cause the controller memory to run out. if enabled, adv packets will be lost when host queue is congested. - Default value: - - No (disabled) if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_SMP_MAX_BONDS BT/BLE maximum bond device count Found in: Component config > Bluetooth > Bluedroid Options The number of security records for peer devices. CONFIG_BT_BLE_ACT_SCAN_REP_ADV_SCAN Report adv data and scan response individually when BLE active scan Found in: Component config > Bluetooth > Bluedroid Options Originally, when doing BLE active scan, Bluedroid will not report adv to application layer until receive scan response. This option is used to disable the behavior. When enable this option, Bluedroid will report adv data or scan response to application layer immediately. # Memory reserved at start of DRAM for Bluetooth stack - Default value: - - No (disabled) if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_ESTAB_LINK_CONN_TOUT Timeout of BLE connection establishment Found in: Component config > Bluetooth > Bluedroid Options Bluetooth Connection establishment maximum time, if connection time exceeds this value, the connection establishment fails, ESP_GATTC_OPEN_EVT or ESP_GATTS_OPEN_EVT is triggered. - Range: - - from 1 to 60 if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED - Default value: - CONFIG_BT_MAX_DEVICE_NAME_LEN length of bluetooth device name Found in: Component config > Bluetooth > Bluedroid Options Bluetooth Device name length shall be no larger than 248 octets, If the broadcast data cannot contain the complete device name, then only the shortname will be displayed, the rest parts that can't fit in will be truncated. - Range: - - from 32 to 248 if CONFIG_BT_BLUEDROID_ENABLED && CONFIG_BT_BLUEDROID_ENABLED - Default value: - CONFIG_BT_BLE_RPA_SUPPORTED Update RPA to Controller Found in: Component config > Bluetooth > Bluedroid Options This enables controller RPA list function. For ESP32, ESP32 only support network privacy mode. If this option is enabled, ESP32 will only accept advertising packets from peer devices that contain private address, HW will not receive the advertising packets contain identity address after IRK changed. If this option is disabled, address resolution will be performed in the host, so the functions that require controller to resolve address in the white list cannot be used. This option is disabled by default on ESP32, please enable or disable this option according to your own needs. For other BLE chips, devices support network privacy mode and device privacy mode, users can switch the two modes according to their own needs. So this option is enabled by default. - Default value: - - No (disabled) if CONFIG_BT_CONTROLLER_ENABLED && CONFIG_BT_BLUEDROID_ENABLED && (CONFIG_BT_CONTROLLER_ENABLED || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED - Yes (enabled) if CONFIG_BT_CONTROLLER_DISABLED && CONFIG_BT_BLUEDROID_ENABLED && (CONFIG_BT_CONTROLLER_ENABLED || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_RPA_TIMEOUT Timeout of resolvable private address Found in: Component config > Bluetooth > Bluedroid Options This set RPA timeout of Controller and Host. Default is 900 s (15 minutes). Range is 1 s to 1 hour (3600 s). - Range: - - from 1 to 3600 if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED - Default value: - CONFIG_BT_BLE_50_FEATURES_SUPPORTED Enable BLE 5.0 features Found in: Component config > Bluetooth > Bluedroid Options Enabling this option activates BLE 5.0 features. This option is universally supported in chips that support BLE, except for ESP32. - Default value: - - Yes (enabled) if CONFIG_BT_BLE_ENABLED && ((CONFIG_BT_CONTROLLER_ENABLED && SOC_BLE_50_SUPPORTED) || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_42_FEATURES_SUPPORTED Enable BLE 4.2 features Found in: Component config > Bluetooth > Bluedroid Options This enables BLE 4.2 features. - Default value: - - No (disabled) if CONFIG_BT_BLE_ENABLED && (CONFIG_BT_CONTROLLER_ENABLED || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_FEAT_PERIODIC_ADV_SYNC_TRANSFER Enable BLE periodic advertising sync transfer feature Found in: Component config > Bluetooth > Bluedroid Options This enables BLE periodic advertising sync transfer feature - Default value: - - No (disabled) if CONFIG_BT_BLE_50_FEATURES_SUPPORTED && ((CONFIG_BT_CONTROLLER_ENABLED && SOC_ESP_NIMBLE_CONTROLLER) || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_FEAT_PERIODIC_ADV_ENH Enable periodic adv enhancements(adi support) Found in: Component config > Bluetooth > Bluedroid Options Enable the periodic advertising enhancements - Default value: - - No (disabled) if CONFIG_BT_BLE_50_FEATURES_SUPPORTED && ((CONFIG_BT_CONTROLLER_ENABLED && SOC_ESP_NIMBLE_CONTROLLER) || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_FEAT_CREATE_SYNC_ENH Enable create sync enhancements(reporting disable and duplicate filtering enable support) Found in: Component config > Bluetooth > Bluedroid Options Enable the create sync enhancements - Default value: - - No (disabled) if CONFIG_BT_BLE_50_FEATURES_SUPPORTED && ((CONFIG_BT_CONTROLLER_ENABLED && SOC_ESP_NIMBLE_CONTROLLER) || CONFIG_BT_CONTROLLER_DISABLED) && CONFIG_BT_BLUEDROID_ENABLED CONFIG_BT_BLE_HIGH_DUTY_ADV_INTERVAL Enable BLE high duty advertising interval feature Found in: Component config > Bluetooth > Bluedroid Options This enable BLE high duty advertising interval feature - Default value: - - No (disabled) if CONFIG_BT_BLE_ENABLED && CONFIG_BT_BLUEDROID_ENABLED NimBLE Options Contains: CONFIG_BT_NIMBLE_MEM_ALLOC_MODE Memory allocation strategy Found in: Component config > Bluetooth > NimBLE Options Allocation strategy for NimBLE host stack, essentially provides ability to allocate all required dynamic allocations from, - Internal DRAM memory only - External SPIRAM memory only - Either internal or external memory based on default malloc() behavior in ESP-IDF - Internal IRAM memory wherever applicable else internal DRAM Available options: - Internal memory (CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_INTERNAL) - External SPIRAM (CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_EXTERNAL) - Default alloc mode (CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_DEFAULT) - Internal IRAM (CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_IRAM_8BIT) Allows to use IRAM memory region as 8bit accessible region. Every unaligned (8bit or 16bit) access will result in an exception and incur penalty of certain clock cycles per unaligned read/write. CONFIG_BT_NIMBLE_LOG_LEVEL NimBLE Host log verbosity Found in: Component config > Bluetooth > NimBLE Options Select NimBLE log level. Please make a note that the selected NimBLE log verbosity can not exceed the level set in "Component config --> Log output --> Default log verbosity". Available options: - No logs (CONFIG_BT_NIMBLE_LOG_LEVEL_NONE) - Error logs (CONFIG_BT_NIMBLE_LOG_LEVEL_ERROR) - Warning logs (CONFIG_BT_NIMBLE_LOG_LEVEL_WARNING) - Info logs (CONFIG_BT_NIMBLE_LOG_LEVEL_INFO) - Debug logs (CONFIG_BT_NIMBLE_LOG_LEVEL_DEBUG) CONFIG_BT_NIMBLE_MAX_CONNECTIONS Maximum number of concurrent connections Found in: Component config > Bluetooth > NimBLE Options Defines maximum number of concurrent BLE connections. For ESP32, user is expected to configure BTDM_CTRL_BLE_MAX_CONN from controller menu along with this option. Similarly for ESP32-C3 or ESP32-S3, user is expected to configure BT_CTRL_BLE_MAX_ACT from controller menu. For ESP32C2, ESP32C6 and ESP32H2, each connection will take about 1k DRAM. - Range: - - from 1 to 9 if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED - Default value: - CONFIG_BT_NIMBLE_MAX_BONDS Maximum number of bonds to save across reboots Found in: Component config > Bluetooth > NimBLE Options Defines maximum number of bonds to save for peer security and our security - Default value: - CONFIG_BT_NIMBLE_MAX_CCCDS Maximum number of CCC descriptors to save across reboots Found in: Component config > Bluetooth > NimBLE Options Defines maximum number of CCC descriptors to save - Default value: - CONFIG_BT_NIMBLE_L2CAP_COC_MAX_NUM Maximum number of connection oriented channels Found in: Component config > Bluetooth > NimBLE Options Defines maximum number of BLE Connection Oriented Channels. When set to (0), BLE COC is not compiled in - Range: - - from 0 to 9 if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED - Default value: - CONFIG_BT_NIMBLE_PINNED_TO_CORE_CHOICE The CPU core on which NimBLE host will run Found in: Component config > Bluetooth > NimBLE Options The CPU core on which NimBLE host will run. You can choose Core 0 or Core 1. Cannot specify no-affinity Available options: - Core 0 (PRO CPU) (CONFIG_BT_NIMBLE_PINNED_TO_CORE_0) - Core 1 (APP CPU) (CONFIG_BT_NIMBLE_PINNED_TO_CORE_1) CONFIG_BT_NIMBLE_HOST_TASK_STACK_SIZE NimBLE Host task stack size Found in: Component config > Bluetooth > NimBLE Options This configures stack size of NimBLE host task - Default value: - - 5120 if CONFIG_BLE_MESH && CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED - 4096 if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_ROLE_CENTRAL Enable BLE Central role Found in: Component config > Bluetooth > NimBLE Options Enables central role - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_ROLE_PERIPHERAL Enable BLE Peripheral role Found in: Component config > Bluetooth > NimBLE Options Enable peripheral role - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_ROLE_BROADCASTER Enable BLE Broadcaster role Found in: Component config > Bluetooth > NimBLE Options Enables broadcaster role - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_ROLE_OBSERVER Enable BLE Observer role Found in: Component config > Bluetooth > NimBLE Options Enables observer role - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_NVS_PERSIST Persist the BLE Bonding keys in NVS Found in: Component config > Bluetooth > NimBLE Options Enable this flag to make bonding persistent across device reboots - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SECURITY_ENABLE Enable BLE SM feature Found in: Component config > Bluetooth > NimBLE Options Enable BLE sm feature - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED Contains: CONFIG_BT_NIMBLE_SM_LEGACY Security manager legacy pairing Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_SECURITY_ENABLE Enable security manager legacy pairing - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_SECURITY_ENABLE && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SM_SC Security manager secure connections (4.2) Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_SECURITY_ENABLE Enable security manager secure connections - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_SECURITY_ENABLE && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SM_SC_DEBUG_KEYS Use predefined public-private key pair Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_SECURITY_ENABLE > CONFIG_BT_NIMBLE_SM_SC If this option is enabled, SM uses predefined DH key pair as described in Core Specification, Vol. 3, Part H, 2.3.5.6.1. This allows to decrypt air traffic easily and thus should only be used for debugging. - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_SECURITY_ENABLE && CONFIG_BT_NIMBLE_SM_SC && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_LL_CFG_FEAT_LE_ENCRYPTION Enable LE encryption Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_SECURITY_ENABLE Enable encryption connection - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_SECURITY_ENABLE && CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SM_SC_LVL Security level Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_SECURITY_ENABLE LE Security Mode 1 Levels: 1. No Security 2. Unauthenticated pairing with encryption 3. Authenticated pairing with encryption 4. Authenticated LE Secure Connections pairing with encryption using a 128-bit strength encryption key. - Default value: - CONFIG_BT_NIMBLE_DEBUG Enable extra runtime asserts and host debugging Found in: Component config > Bluetooth > NimBLE Options This enables extra runtime asserts and host debugging - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_DYNAMIC_SERVICE Enable dynamic services Found in: Component config > Bluetooth > NimBLE Options This enables user to add/remove Gatt services at runtime CONFIG_BT_NIMBLE_SVC_GAP_DEVICE_NAME BLE GAP default device name Found in: Component config > Bluetooth > NimBLE Options The Device Name characteristic shall contain the name of the device as an UTF-8 string. This name can be changed by using API ble_svc_gap_device_name_set() - Default value: - - "nimble" if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_GAP_DEVICE_NAME_MAX_LEN Maximum length of BLE device name in octets Found in: Component config > Bluetooth > NimBLE Options Device Name characteristic value shall be 0 to 248 octets in length - Default value: - CONFIG_BT_NIMBLE_ATT_PREFERRED_MTU Preferred MTU size in octets Found in: Component config > Bluetooth > NimBLE Options This is the default value of ATT MTU indicated by the device during an ATT MTU exchange. This value can be changed using API ble_att_set_preferred_mtu() - Default value: - CONFIG_BT_NIMBLE_SVC_GAP_APPEARANCE External appearance of the device Found in: Component config > Bluetooth > NimBLE Options Standard BLE GAP Appearance value in HEX format e.g. 0x02C0 - Default value: - Memory Settings Contains: CONFIG_BT_NIMBLE_MSYS_1_BLOCK_COUNT MSYS_1 Block Count Found in: Component config > Bluetooth > NimBLE Options > Memory Settings MSYS is a system level mbuf registry. For prepare write & prepare responses MBUFs are allocated out of msys_1 pool. For NIMBLE_MESH enabled cases, this block count is increased by 8 than user defined count. - Default value: - - 24 if SOC_ESP_NIMBLE_CONTROLLER && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MSYS_1_BLOCK_SIZE MSYS_1 Block Size Found in: Component config > Bluetooth > NimBLE Options > Memory Settings Dynamic memory size of block 1 - Default value: - - 128 if SOC_ESP_NIMBLE_CONTROLLER && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MSYS_2_BLOCK_COUNT MSYS_2 Block Count Found in: Component config > Bluetooth > NimBLE Options > Memory Settings Dynamic memory count - Default value: - - 24 if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MSYS_2_BLOCK_SIZE MSYS_2 Block Size Found in: Component config > Bluetooth > NimBLE Options > Memory Settings Dynamic memory size of block 2 - Default value: - - 320 if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MSYS_BUF_FROM_HEAP Get Msys Mbuf from heap Found in: Component config > Bluetooth > NimBLE Options > Memory Settings This option sets the source of the shared msys mbuf memory between the Host and the Controller. Allocate the memory from the heap if this option is sets, from the mempool otherwise. - Default value: - - Yes (enabled) if BT_LE_MSYS_INIT_IN_CONTROLLER && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_TRANSPORT_ACL_FROM_LL_COUNT ACL Buffer count Found in: Component config > Bluetooth > NimBLE Options > Memory Settings The number of ACL data buffers allocated for host. - Default value: - CONFIG_BT_NIMBLE_TRANSPORT_ACL_SIZE Transport ACL Buffer size Found in: Component config > Bluetooth > NimBLE Options > Memory Settings This is the maximum size of the data portion of HCI ACL data packets. It does not include the HCI data header (of 4 bytes) - Default value: - CONFIG_BT_NIMBLE_TRANSPORT_EVT_SIZE Transport Event Buffer size Found in: Component config > Bluetooth > NimBLE Options > Memory Settings This is the size of each HCI event buffer in bytes. In case of extended advertising, packets can be fragmented. 257 bytes is the maximum size of a packet. - Default value: - CONFIG_BT_NIMBLE_TRANSPORT_EVT_COUNT Transport Event Buffer count Found in: Component config > Bluetooth > NimBLE Options > Memory Settings This is the high priority HCI events' buffer size. High-priority event buffers are for everything except advertising reports. If there are no free high-priority event buffers then host will try to allocate a low-priority buffer instead - Default value: - CONFIG_BT_NIMBLE_TRANSPORT_EVT_DISCARD_COUNT Discardable Transport Event Buffer count Found in: Component config > Bluetooth > NimBLE Options > Memory Settings This is the low priority HCI events' buffer size. Low-priority event buffers are only used for advertising reports. If there are no free low-priority event buffers, then an incoming advertising report will get dropped - Default value: - CONFIG_BT_NIMBLE_GATT_MAX_PROCS Maximum number of GATT client procedures Found in: Component config > Bluetooth > NimBLE Options Maximum number of GATT client procedures that can be executed. - Default value: - CONFIG_BT_NIMBLE_HS_FLOW_CTRL Enable Host Flow control Found in: Component config > Bluetooth > NimBLE Options Enable Host Flow control - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED - No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_HS_FLOW_CTRL_ITVL Host Flow control interval Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_HS_FLOW_CTRL Host flow control interval in msecs - Default value: - CONFIG_BT_NIMBLE_HS_FLOW_CTRL_THRESH Host Flow control threshold Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_HS_FLOW_CTRL Host flow control threshold, if the number of free buffers are at or below this threshold, send an immediate number-of-completed-packets event - Default value: - CONFIG_BT_NIMBLE_HS_FLOW_CTRL_TX_ON_DISCONNECT Host Flow control on disconnect Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_HS_FLOW_CTRL Enable this option to send number-of-completed-packets event to controller after disconnection - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_HS_FLOW_CTRL && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_RPA_TIMEOUT RPA timeout in seconds Found in: Component config > Bluetooth > NimBLE Options Time interval between RPA address change. This is applicable in case of Host based RPA - Range: - - from 1 to 41400 if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED - Default value: - CONFIG_BT_NIMBLE_MESH Enable BLE mesh functionality Found in: Component config > Bluetooth > NimBLE Options Enable BLE Mesh example present in upstream mynewt-nimble and not maintained by Espressif. IDF maintains ESP-BLE-MESH as the official Mesh solution. Please refer to ESP-BLE-MESH guide at: :doc:../esp32/api-guides/esp-ble-mesh/ble-mesh-index`` - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED Contains: CONFIG_BT_NIMBLE_MESH_PROXY Enable mesh proxy functionality Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH Enable proxy. This is automatically set whenever NIMBLE_MESH_PB_GATT or NIMBLE_MESH_GATT_PROXY is set - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_MESH && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_PROV Enable BLE mesh provisioning Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH Enable mesh provisioning - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_MESH && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_PB_ADV Enable mesh provisioning over advertising bearer Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH > CONFIG_BT_NIMBLE_MESH_PROV Enable this option to allow the device to be provisioned over the advertising bearer - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_MESH_PROV && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_PB_GATT Enable mesh provisioning over GATT bearer Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH > CONFIG_BT_NIMBLE_MESH_PROV Enable this option to allow the device to be provisioned over the GATT bearer - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_MESH_PROV && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_GATT_PROXY Enable GATT Proxy functionality Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH This option enables support for the Mesh GATT Proxy Service, i.e. the ability to act as a proxy between a Mesh GATT Client and a Mesh network - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_MESH && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_RELAY Enable mesh relay functionality Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH Support for acting as a Mesh Relay Node - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_MESH && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_LOW_POWER Enable mesh low power mode Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH Enable this option to be able to act as a Low Power Node - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_MESH && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_FRIEND Enable mesh friend functionality Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH Enable this option to be able to act as a Friend Node - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_MESH && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_DEVICE_NAME Set mesh device name Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH This value defines Bluetooth Mesh device/node name - Default value: - - "nimble-mesh-node" if CONFIG_BT_NIMBLE_MESH && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MESH_NODE_COUNT Set mesh node count Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH Defines mesh node count. - Default value: - CONFIG_BT_NIMBLE_MESH_PROVISIONER Enable BLE mesh provisioner Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH Enable mesh provisioner. - Default value: - CONFIG_BT_NIMBLE_CRYPTO_STACK_MBEDTLS Override TinyCrypt with mbedTLS for crypto computations Found in: Component config > Bluetooth > NimBLE Options Enable this option to choose mbedTLS instead of TinyCrypt for crypto computations. - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_HS_STOP_TIMEOUT_MS BLE host stop timeout in msec Found in: Component config > Bluetooth > NimBLE Options BLE Host stop procedure timeout in milliseconds. - Default value: - - 2000 if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_HOST_BASED_PRIVACY Enable host based privacy for random address. Found in: Component config > Bluetooth > NimBLE Options Use this option to do host based Random Private Address resolution. If this option is disabled then controller based privacy is used. - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_ENABLE_CONN_REATTEMPT Enable connection reattempts on connection establishment error Found in: Component config > Bluetooth > NimBLE Options Enable to make the NimBLE host to reattempt GAP connection on connection establishment failure. - Default value: - - Yes (enabled) if SOC_ESP_NIMBLE_CONTROLLER && CONFIG_BT_NIMBLE_ENABLED - No (disabled) if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MAX_CONN_REATTEMPT Maximum number connection reattempts Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_ENABLE_CONN_REATTEMPT Defines maximum number of connection reattempts. - Range: - - from 1 to 7 if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLE_CONN_REATTEMPT && CONFIG_BT_NIMBLE_ENABLED - Default value: - CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Enable BLE 5 feature Found in: Component config > Bluetooth > NimBLE Options Enable BLE 5 feature - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED && SOC_BLE_50_SUPPORTED && CONFIG_BT_NIMBLE_ENABLED Contains: CONFIG_BT_NIMBLE_LL_CFG_FEAT_LE_2M_PHY Enable 2M Phy Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Enable 2M-PHY - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_LL_CFG_FEAT_LE_CODED_PHY Enable coded Phy Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Enable coded-PHY - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_EXT_ADV Enable extended advertising Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Enable this option to do extended advertising. Extended advertising will be supported from BLE 5.0 onwards. - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MAX_EXT_ADV_INSTANCES Maximum number of extended advertising instances. Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_EXT_ADV Change this option to set maximum number of extended advertising instances. Minimum there is always one instance of advertising. Enter how many more advertising instances you want. For ESP32C2, ESP32C6 and ESP32H2, each extended advertising instance will take about 0.5k DRAM. - Range: - - from 0 to 4 if CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_ENABLED - Default value: - CONFIG_BT_NIMBLE_EXT_ADV_MAX_SIZE Maximum length of the advertising data. Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_EXT_ADV Defines the length of the extended adv data. The value should not exceed 1650. - Range: - - from 0 to 1650 if CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_ENABLED - Default value: - CONFIG_BT_NIMBLE_ENABLE_PERIODIC_ADV Enable periodic advertisement. Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_EXT_ADV Enable this option to start periodic advertisement. - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_PERIODIC_ADV_SYNC_TRANSFER Enable Transer Sync Events Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_EXT_ADV > CONFIG_BT_NIMBLE_ENABLE_PERIODIC_ADV This enables controller transfer periodic sync events to host - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_ENABLE_PERIODIC_ADV && CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_MAX_PERIODIC_SYNCS Maximum number of periodic advertising syncs Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Set this option to set the upper limit for number of periodic sync connections. This should be less than maximum connections allowed by controller. - Range: - - from 0 to 8 if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && CONFIG_BT_NIMBLE_ENABLED - Default value: - CONFIG_BT_NIMBLE_MAX_PERIODIC_ADVERTISER_LIST Maximum number of periodic advertiser list Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Set this option to set the upper limit for number of periodic advertiser list. - Range: - - from 1 to 5 if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && SOC_ESP_NIMBLE_CONTROLLER && CONFIG_BT_NIMBLE_ENABLED - Default value: - - 5 if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && SOC_ESP_NIMBLE_CONTROLLER && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_BLE_POWER_CONTROL Enable support for BLE Power Control Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Set this option to enable the Power Control feature - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && SOC_BLE_POWER_CONTROL_SUPPORTED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_PERIODIC_ADV_ENH Periodic adv enhancements(adi support) Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Enable the periodic advertising enhancements CONFIG_BT_NIMBLE_GATT_CACHING Enable GATT caching Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT Enable GATT caching Contains: CONFIG_BT_NIMBLE_GATT_CACHING_MAX_CONNS Maximum connections to be cached Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_GATT_CACHING Set this option to set the upper limit on number of connections to be cached. - Default value: - CONFIG_BT_NIMBLE_GATT_CACHING_MAX_SVCS Maximum number of services per connection Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_GATT_CACHING Set this option to set the upper limit on number of services per connection to be cached. - Default value: - CONFIG_BT_NIMBLE_GATT_CACHING_MAX_CHRS Maximum number of characteristics per connection Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_GATT_CACHING Set this option to set the upper limit on number of characteristics per connection to be cached. - Default value: - CONFIG_BT_NIMBLE_GATT_CACHING_MAX_DSCS Maximum number of descriptors per connection Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_GATT_CACHING Set this option to set the upper limit on number of discriptors per connection to be cached. - Default value: - CONFIG_BT_NIMBLE_WHITELIST_SIZE BLE white list size Found in: Component config > Bluetooth > NimBLE Options BLE list size - Range: - - from 1 to 15 if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED - Default value: - CONFIG_BT_NIMBLE_TEST_THROUGHPUT_TEST Throughput Test Mode enable Found in: Component config > Bluetooth > NimBLE Options Enable the throughput test mode - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_BLUFI_ENABLE Enable blufi functionality Found in: Component config > Bluetooth > NimBLE Options Set this option to enable blufi functionality. - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_USE_ESP_TIMER Enable Esp Timer for Nimble Found in: Component config > Bluetooth > NimBLE Options Set this option to use Esp Timer which has higher priority timer instead of FreeRTOS timer - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_BLE_GATT_BLOB_TRANSFER Blob transfer Found in: Component config > Bluetooth > NimBLE Options This option is used when data to be sent is more than 512 bytes. For peripheral role, BT_NIMBLE_MSYS_1_BLOCK_COUNT needs to be increased according to the need. GAP Service Contains: GAP Appearance write permissions Contains: CONFIG_BT_NIMBLE_SVC_GAP_APPEAR_WRITE Write Found in: Component config > Bluetooth > NimBLE Options > GAP Service > GAP Appearance write permissions Enable write permission (BLE_GATT_CHR_F_WRITE) - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SVC_GAP_APPEAR_WRITE_ENC Write with encryption Found in: Component config > Bluetooth > NimBLE Options > GAP Service > GAP Appearance write permissions > CONFIG_BT_NIMBLE_SVC_GAP_APPEAR_WRITE Enable write with encryption permission (BLE_GATT_CHR_F_WRITE_ENC) - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_SVC_GAP_APPEAR_WRITE && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SVC_GAP_APPEAR_WRITE_AUTHEN Write with authentication Found in: Component config > Bluetooth > NimBLE Options > GAP Service > GAP Appearance write permissions > CONFIG_BT_NIMBLE_SVC_GAP_APPEAR_WRITE Enable write with authentication permission (BLE_GATT_CHR_F_WRITE_AUTHEN) - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_SVC_GAP_APPEAR_WRITE && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SVC_GAP_CENT_ADDR_RESOLUTION GAP Characteristic - Central Address Resolution Found in: Component config > Bluetooth > NimBLE Options > GAP Service Weather or not Central Address Resolution characteristic is supported on the device, and if supported, weather or not Central Address Resolution is supported. - Central Address Resolution characteristic not supported - Central Address Resolution not supported - Central Address Resolution supported Available options: - Characteristic not supported (CONFIG_BT_NIMBLE_SVC_GAP_CAR_CHAR_NOT_SUPP) - Central Address Resolution not supported (CONFIG_BT_NIMBLE_SVC_GAP_CAR_NOT_SUPP) - Central Address Resolution supported (CONFIG_BT_NIMBLE_SVC_GAP_CAR_SUPP) GAP device name write permissions Contains: CONFIG_BT_NIMBLE_SVC_GAP_NAME_WRITE Write Found in: Component config > Bluetooth > NimBLE Options > GAP Service > GAP device name write permissions Enable write permission (BLE_GATT_CHR_F_WRITE) - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SVC_GAP_NAME_WRITE_ENC Write with encryption Found in: Component config > Bluetooth > NimBLE Options > GAP Service > GAP device name write permissions > CONFIG_BT_NIMBLE_SVC_GAP_NAME_WRITE Enable write with encryption permission (BLE_GATT_CHR_F_WRITE_ENC) - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_SVC_GAP_NAME_WRITE && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SVC_GAP_NAME_WRITE_AUTHEN Write with authentication Found in: Component config > Bluetooth > NimBLE Options > GAP Service > GAP device name write permissions > CONFIG_BT_NIMBLE_SVC_GAP_NAME_WRITE Enable write with authentication permission (BLE_GATT_CHR_F_WRITE_AUTHEN) - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_SVC_GAP_NAME_WRITE && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_SVC_GAP_PPCP_MAX_CONN_INTERVAL PPCP Connection Interval Max (Unit: 1.25 ms) Found in: Component config > Bluetooth > NimBLE Options > GAP Service Peripheral Preferred Connection Parameter: Connection Interval maximum value Interval Max = value * 1.25 ms - Default value: - CONFIG_BT_NIMBLE_SVC_GAP_PPCP_MIN_CONN_INTERVAL PPCP Connection Interval Min (Unit: 1.25 ms) Found in: Component config > Bluetooth > NimBLE Options > GAP Service Peripheral Preferred Connection Parameter: Connection Interval minimum value Interval Min = value * 1.25 ms - Default value: - CONFIG_BT_NIMBLE_SVC_GAP_PPCP_SLAVE_LATENCY PPCP Slave Latency Found in: Component config > Bluetooth > NimBLE Options > GAP Service Peripheral Preferred Connection Parameter: Slave Latency - Default value: - CONFIG_BT_NIMBLE_SVC_GAP_PPCP_SUPERVISION_TMO PPCP Supervision Timeout (Uint: 10 ms) Found in: Component config > Bluetooth > NimBLE Options > GAP Service Peripheral Preferred Connection Parameter: Supervision Timeout Timeout = Value * 10 ms - Default value: - BLE Services Contains: CONFIG_BT_NIMBLE_HID_SERVICE HID service Found in: Component config > Bluetooth > NimBLE Options > BLE Services Enable HID service support - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED Contains: CONFIG_BT_NIMBLE_SVC_HID_MAX_INSTANCES Maximum HID service instances Found in: Component config > Bluetooth > NimBLE Options > BLE Services > CONFIG_BT_NIMBLE_HID_SERVICE Defines maximum number of HID service instances - Default value: - CONFIG_BT_NIMBLE_SVC_HID_MAX_RPTS Maximum HID Report characteristics per service instance Found in: Component config > Bluetooth > NimBLE Options > BLE Services > CONFIG_BT_NIMBLE_HID_SERVICE Defines maximum number of report characteristics per service instance - Default value: - CONFIG_BT_NIMBLE_VS_SUPPORT Enable support for VSC and VSE Found in: Component config > Bluetooth > NimBLE Options This option is used to enable support for sending Vendor Specific HCI commands and handling Vendor Specific HCI Events. CONFIG_BT_NIMBLE_OPTIMIZE_MULTI_CONN Enable the optimization of multi-connection Found in: Component config > Bluetooth > NimBLE Options This option enables the use of vendor-specific APIs for multi-connections, which can greatly enhance the stability of coexistence between numerous central and peripheral devices. It will prohibit the usage of standard APIs. - Default value: - - No (disabled) if SOC_BLE_MULTI_CONN_OPTIMIZATION && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_ENC_ADV_DATA Encrypted Advertising Data Found in: Component config > Bluetooth > NimBLE Options This option is used to enable encrypted advertising data. CONFIG_BT_NIMBLE_MAX_EADS Maximum number of EAD devices to save across reboots Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_ENC_ADV_DATA Defines maximum number of encrypted advertising data key material to save - Default value: - CONFIG_BT_NIMBLE_HIGH_DUTY_ADV_ITVL Enable BLE high duty advertising interval feature Found in: Component config > Bluetooth > NimBLE Options This enable BLE high duty advertising interval feature CONFIG_BT_NIMBLE_HOST_QUEUE_CONG_CHECK BLE queue congestion check Found in: Component config > Bluetooth > NimBLE Options When scanning and scan duplicate is not enabled, if there are a lot of adv packets around or application layer handling adv packets is slow, it will cause the controller memory to run out. if enabled, adv packets will be lost when host queue is congested. - Default value: - - No (disabled) if CONFIG_BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLED Host-controller Transport Contains: CONFIG_BT_NIMBLE_TRANSPORT_UART Enable Uart Transport Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport Use UART transport - Default value: - - Yes (enabled) if CONFIG_BT_CONTROLLER_DISABLED && CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_TRANSPORT_UART_PORT Uart port Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport > CONFIG_BT_NIMBLE_TRANSPORT_UART Uart port - Default value: - CONFIG_BT_NIMBLE_USE_HCI_UART_PARITY Uart PARITY Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport Uart Parity Available options: - None (CONFIG_UART_PARITY_NONE) - Odd (CONFIG_UART_PARITY_ODD) - Even (CONFIG_UART_PARITY_EVEN) CONFIG_BT_NIMBLE_UART_RX_PIN UART Rx pin Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport Rx pin for Nimble Transport - Default value: - CONFIG_BT_NIMBLE_UART_TX_PIN UART Tx pin Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport Tx pin for Nimble Transport - Default value: - CONFIG_BT_NIMBLE_USE_HCI_UART_FLOW_CTRL Uart Flow Control Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport Uart Flow Control Available options: - Disable (CONFIG_UART_HW_FLOWCTRL_DISABLE) - Enable hardware flow control (CONFIG_UART_HW_FLOWCTRL_CTS_RTS) CONFIG_BT_NIMBLE_HCI_UART_RTS_PIN UART Rts Pin Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport UART HCI RTS pin - Default value: - - 19 if CONFIG_BT_NIMBLE_ENABLED CONFIG_BT_NIMBLE_HCI_UART_CTS_PIN UART Cts Pin Found in: Component config > Bluetooth > NimBLE Options > Host-controller Transport UART HCI CTS pin - Default value: - - 23 if CONFIG_BT_NIMBLE_ENABLED Controller Options Contains: CONFIG_BTDM_CTRL_MODE Bluetooth controller mode (BR/EDR/BLE/DUALMODE) Found in: Component config > Bluetooth > Controller Options Specify the bluetooth controller mode (BR/EDR, BLE or dual mode). Available options: - BLE Only (CONFIG_BTDM_CTRL_MODE_BLE_ONLY) - BR/EDR Only (CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY) - Bluetooth Dual Mode (CONFIG_BTDM_CTRL_MODE_BTDM) CONFIG_BTDM_CTRL_BLE_MAX_CONN BLE Max Connections Found in: Component config > Bluetooth > Controller Options BLE maximum connections of bluetooth controller. Each connection uses 1KB static DRAM whenever the BT controller is enabled. - Range: - - from 1 to 9 if (CONFIG_BTDM_CTRL_MODE_BLE_ONLY || CONFIG_BTDM_CTRL_MODE_BTDM) && CONFIG_BT_CONTROLLER_ENABLED - Default value: - CONFIG_BTDM_CTRL_BR_EDR_MAX_ACL_CONN BR/EDR ACL Max Connections Found in: Component config > Bluetooth > Controller Options BR/EDR ACL maximum connections of bluetooth controller. Each connection uses 1.2 KB DRAM whenever the BT controller is enabled. - Range: - - from 1 to 7 if (CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY || CONFIG_BTDM_CTRL_MODE_BTDM) && CONFIG_BT_CONTROLLER_ENABLED - Default value: - CONFIG_BTDM_CTRL_BR_EDR_MAX_SYNC_CONN BR/EDR Sync(SCO/eSCO) Max Connections Found in: Component config > Bluetooth > Controller Options BR/EDR Synchronize maximum connections of bluetooth controller. Each connection uses 2 KB DRAM whenever the BT controller is enabled. - Range: - - from 0 to 3 if (CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY || CONFIG_BTDM_CTRL_MODE_BTDM) && CONFIG_BT_CONTROLLER_ENABLED - Default value: - CONFIG_BTDM_CTRL_BR_EDR_SCO_DATA_PATH BR/EDR Sync(SCO/eSCO) default data path Found in: Component config > Bluetooth > Controller Options SCO data path, i.e. HCI or PCM. SCO data can be sent/received through HCI synchronous packets, or the data can be routed to on-chip PCM module on ESP32. PCM input/output signals can be "matrixed" to GPIOs. The default data path can also be set using API "esp_bredr_sco_datapath_set" Available options: - HCI (CONFIG_BTDM_CTRL_BR_EDR_SCO_DATA_PATH_HCI) - PCM (CONFIG_BTDM_CTRL_BR_EDR_SCO_DATA_PATH_PCM) CONFIG_BTDM_CTRL_PCM_ROLE_EDGE_CONFIG PCM Signal Config (Role and Polar) Found in: Component config > Bluetooth > Controller Options - Default value: - - Yes (enabled) if CONFIG_BTDM_CTRL_BR_EDR_SCO_DATA_PATH_PCM && CONFIG_BT_CONTROLLER_ENABLED Contains: CONFIG_BTDM_CTRL_PCM_ROLE PCM Role Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_CTRL_PCM_ROLE_EDGE_CONFIG PCM role can be configured as PCM master or PCM slave Available options: - PCM Master (CONFIG_BTDM_CTRL_PCM_ROLE_MASTER) - PCM Slave (CONFIG_BTDM_CTRL_PCM_ROLE_SLAVE) CONFIG_BTDM_CTRL_PCM_POLAR PCM Polar Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_CTRL_PCM_ROLE_EDGE_CONFIG PCM polarity can be configured as Falling Edge or Rising Edge Available options: - Falling Edge (CONFIG_BTDM_CTRL_PCM_POLAR_FALLING_EDGE) - Rising Edge (CONFIG_BTDM_CTRL_PCM_POLAR_RISING_EDGE) CONFIG_BTDM_CTRL_AUTO_LATENCY Auto latency Found in: Component config > Bluetooth > Controller Options BLE auto latency, used to enhance classic BT performance while classic BT and BLE are enabled at the same time. - Default value: - - No (disabled) if CONFIG_BTDM_CTRL_MODE_BTDM && CONFIG_BT_CONTROLLER_ENABLED CONFIG_BTDM_CTRL_LEGACY_AUTH_VENDOR_EVT Legacy Authentication Vendor Specific Event Enable Found in: Component config > Bluetooth > Controller Options To protect from BIAS attack during Legacy authentication, Legacy authentication Vendor specific event should be enabled - Default value: - - Yes (enabled) if (CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY || CONFIG_BTDM_CTRL_MODE_BTDM) && CONFIG_BT_CONTROLLER_ENABLED CONFIG_BTDM_CTRL_PINNED_TO_CORE_CHOICE The cpu core which bluetooth controller run Found in: Component config > Bluetooth > Controller Options Specify the cpu core to run bluetooth controller. Can not specify no-affinity. Available options: - Core 0 (PRO CPU) (CONFIG_BTDM_CTRL_PINNED_TO_CORE_0) - Core 1 (APP CPU) (CONFIG_BTDM_CTRL_PINNED_TO_CORE_1) CONFIG_BTDM_CTRL_HCI_MODE_CHOICE HCI mode Found in: Component config > Bluetooth > Controller Options Speicify HCI mode as VHCI or UART(H4) Available options: - VHCI (CONFIG_BTDM_CTRL_HCI_MODE_VHCI) Normal option. Mostly, choose this VHCI when bluetooth host run on ESP32, too. - UART(H4) (CONFIG_BTDM_CTRL_HCI_MODE_UART_H4) If use external bluetooth host which run on other hardware and use UART as the HCI interface, choose this option. HCI UART(H4) Options Contains: CONFIG_BTDM_CTRL_HCI_UART_NO UART Number for HCI Found in: Component config > Bluetooth > Controller Options > HCI UART(H4) Options Uart number for HCI. The available uart is UART1 and UART2. - Range: - - from 1 to 2 if CONFIG_BTDM_CTRL_HCI_MODE_UART_H4 && CONFIG_BT_CONTROLLER_ENABLED - Default value: - CONFIG_BTDM_CTRL_HCI_UART_BAUDRATE UART Baudrate for HCI Found in: Component config > Bluetooth > Controller Options > HCI UART(H4) Options UART Baudrate for HCI. Please use standard baudrate. - Range: - - from 115200 to 921600 if CONFIG_BTDM_CTRL_HCI_MODE_UART_H4 && CONFIG_BT_CONTROLLER_ENABLED - Default value: - CONFIG_BTDM_CTRL_HCI_UART_FLOW_CTRL_EN Enable UART flow control Found in: Component config > Bluetooth > Controller Options > HCI UART(H4) Options - Default value: - - Yes (enabled) if CONFIG_BTDM_CTRL_HCI_MODE_UART_H4 && CONFIG_BT_CONTROLLER_ENABLED MODEM SLEEP Options Contains: CONFIG_BTDM_CTRL_MODEM_SLEEP Bluetooth modem sleep Found in: Component config > Bluetooth > Controller Options > MODEM SLEEP Options Enable/disable bluetooth controller low power mode. - Default value: - - Yes (enabled) if CONFIG_BT_CONTROLLER_ENABLED CONFIG_BTDM_CTRL_MODEM_SLEEP_MODE Bluetooth Modem sleep mode Found in: Component config > Bluetooth > Controller Options > MODEM SLEEP Options > CONFIG_BTDM_CTRL_MODEM_SLEEP To select which strategy to use for modem sleep Available options: - ORIG Mode(sleep with low power clock) (CONFIG_BTDM_CTRL_MODEM_SLEEP_MODE_ORIG) ORIG mode is a bluetooth sleep mode that can be used for dual mode controller. In this mode, bluetooth controller sleeps between BR/EDR frames and BLE events. A low power clock is used to maintain bluetooth reference clock. - EVED Mode(For internal test only) (CONFIG_BTDM_CTRL_MODEM_SLEEP_MODE_EVED) EVED mode is for BLE only and is only for internal test. Do not use it for production. this mode is not compatible with DFS nor light sleep CONFIG_BTDM_CTRL_LOW_POWER_CLOCK Bluetooth low power clock Found in: Component config > Bluetooth > Controller Options > MODEM SLEEP Options Select the low power clock source for bluetooth controller. Bluetooth low power clock is the clock source to maintain time in sleep mode. - "Main crystal" option provides good accuracy and can support Dynamic Frequency Scaling to be used with Bluetooth modem sleep. Light sleep is not supported. - "External 32kHz crystal" option allows user to use a 32.768kHz crystal as Bluetooth low power clock. This option is allowed as long as External 32kHz crystal is configured as the system RTC clock source. This option provides good accuracy and supports Bluetooth modem sleep to be used alongside Dynamic Frequency Scaling or light sleep. Available options: - Main crystal (CONFIG_BTDM_CTRL_LPCLK_SEL_MAIN_XTAL) Main crystal can be used as low power clock for bluetooth modem sleep. If this option is selected, bluetooth modem sleep can work under Dynamic Frequency Scaling(DFS) enabled, but cannot work when light sleep is enabled. Main crystal has a good performance in accuracy as the bluetooth low power clock source. - External 32kHz crystal (CONFIG_BTDM_CTRL_LPCLK_SEL_EXT_32K_XTAL) External 32kHz crystal has a nominal frequency of 32.768kHz and provides good frequency stability. If used as Bluetooth low power clock, External 32kHz can support Bluetooth modem sleep to be used with both DFS and light sleep. CONFIG_BTDM_BLE_SLEEP_CLOCK_ACCURACY BLE Sleep Clock Accuracy Found in: Component config > Bluetooth > Controller Options BLE Sleep Clock Accuracy(SCA) for the local device is used to estimate window widening in BLE connection events. With a lower level of clock accuracy(e.g. 500ppm over 250ppm), the slave needs a larger RX window to synchronize with master in each anchor point, thus resulting in an increase of power consumption but a higher level of robustness in keeping connected. According to the requirements of Bluetooth Core specification 4.2, the worst-case accuracy of Classic Bluetooth low power oscialltor(LPO) is +/-250ppm in STANDBY and in low power modes such as sniff. For BLE the worst-case SCA is +/-500ppm. - "151ppm to 250ppm" option is the default value for Bluetooth Dual mode - - "251ppm to 500ppm" option can be used in BLE only mode when using external 32kHz crystal as - low power clock. This option is provided in case that BLE sleep clock has a lower level of accuracy, or other error sources contribute to the inaccurate timing during sleep. Available options: - 251ppm to 500ppm (CONFIG_BTDM_BLE_DEFAULT_SCA_500PPM) - 151ppm to 250ppm (CONFIG_BTDM_BLE_DEFAULT_SCA_250PPM) CONFIG_BTDM_BLE_SCAN_DUPL BLE Scan Duplicate Options Found in: Component config > Bluetooth > Controller Options This select enables parameters setting of BLE scan duplicate. - Default value: - - Yes (enabled) if (CONFIG_BTDM_CTRL_MODE_BTDM || CONFIG_BTDM_CTRL_MODE_BLE_ONLY) && CONFIG_BT_CONTROLLER_ENABLED CONFIG_BTDM_SCAN_DUPL_TYPE Scan Duplicate Type Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_SCAN_DUPL Scan duplicate have three ways. one is "Scan Duplicate By Device Address", This way is to use advertiser address filtering. The adv packet of the same address is only allowed to be reported once. Another way is "Scan Duplicate By Device Address And Advertising Data". This way is to use advertising data and device address filtering. All different adv packets with the same address are allowed to be reported. The last way is "Scan Duplicate By Advertising Data". This way is to use advertising data filtering. All same advertising data only allow to be reported once even though they are from different devices. Available options: - Scan Duplicate By Device Address (CONFIG_BTDM_SCAN_DUPL_TYPE_DEVICE) This way is to use advertiser address filtering. The adv packet of the same address is only allowed to be reported once - Scan Duplicate By Advertising Data (CONFIG_BTDM_SCAN_DUPL_TYPE_DATA) This way is to use advertising data filtering. All same advertising data only allow to be reported once even though they are from different devices. - Scan Duplicate By Device Address And Advertising Data (CONFIG_BTDM_SCAN_DUPL_TYPE_DATA_DEVICE) This way is to use advertising data and device address filtering. All different adv packets with the same address are allowed to be reported. CONFIG_BTDM_SCAN_DUPL_CACHE_SIZE Maximum number of devices in scan duplicate filter Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_SCAN_DUPL Maximum number of devices which can be recorded in scan duplicate filter. When the maximum amount of device in the filter is reached, the oldest device will be refreshed. - Range: - - from 10 to 1000 if CONFIG_BTDM_BLE_SCAN_DUPL && CONFIG_BT_CONTROLLER_ENABLED - Default value: - CONFIG_BTDM_SCAN_DUPL_CACHE_REFRESH_PERIOD Duplicate scan list refresh period (seconds) Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_SCAN_DUPL If the period value is non-zero, the controller will periodically clear the device information stored in the scan duuplicate filter. If it is 0, the scan duuplicate filter will not be cleared until the scanning is disabled. Duplicate advertisements for this period should not be sent to the Host in advertising report events. There are two scenarios where the ADV packet will be repeatedly reported: 1. The duplicate scan cache is full, the controller will delete the oldest device information and add new device information. 2. When the refresh period is up, the controller will clear all device information and start filtering again. - Range: - - from 0 to 1000 if CONFIG_BTDM_BLE_SCAN_DUPL && CONFIG_BT_CONTROLLER_ENABLED - Default value: - CONFIG_BTDM_BLE_MESH_SCAN_DUPL_EN Special duplicate scan mechanism for BLE Mesh scan Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_SCAN_DUPL This enables the BLE scan duplicate for special BLE Mesh scan. - Default value: - - No (disabled) if CONFIG_BTDM_BLE_SCAN_DUPL && CONFIG_BT_CONTROLLER_ENABLED CONFIG_BTDM_MESH_DUPL_SCAN_CACHE_SIZE Maximum number of Mesh adv packets in scan duplicate filter Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_SCAN_DUPL > CONFIG_BTDM_BLE_MESH_SCAN_DUPL_EN Maximum number of adv packets which can be recorded in duplicate scan cache for BLE Mesh. When the maximum amount of device in the filter is reached, the cache will be refreshed. - Range: - - from 10 to 1000 if CONFIG_BTDM_BLE_MESH_SCAN_DUPL_EN && CONFIG_BT_CONTROLLER_ENABLED - Default value: - CONFIG_BTDM_CTRL_FULL_SCAN_SUPPORTED BLE full scan feature supported Found in: Component config > Bluetooth > Controller Options The full scan function is mainly used to provide BLE scan performance. This is required for scenes with high scan performance requirements, such as BLE Mesh scenes. - Default value: - - Yes (enabled) if (CONFIG_BTDM_CTRL_MODE_BLE_ONLY || CONFIG_BTDM_CTRL_MODE_BTDM) && CONFIG_BT_CONTROLLER_ENABLED CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP BLE adv report flow control supported Found in: Component config > Bluetooth > Controller Options The function is mainly used to enable flow control for advertising reports. When it is enabled, advertising reports will be discarded by the controller if the number of unprocessed advertising reports exceeds the size of BLE adv report flow control. - Default value: - - Yes (enabled) if (CONFIG_BTDM_CTRL_MODE_BTDM || CONFIG_BTDM_CTRL_MODE_BLE_ONLY) && CONFIG_BT_CONTROLLER_ENABLED CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_NUM BLE adv report flow control number Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP The number of unprocessed advertising report that Bluedroid can save.If you set BTDM_BLE_ADV_REPORT_FLOW_CTRL_NUM to a small value, this may cause adv packets lost. If you set BTDM_BLE_ADV_REPORT_FLOW_CTRL_NUM to a large value, Bluedroid may cache a lot of adv packets and this may cause system memory run out. For example, if you set it to 50, the maximum memory consumed by host is 35 * 50 bytes. Please set BTDM_BLE_ADV_REPORT_FLOW_CTRL_NUM according to your system free memory and handle adv packets as fast as possible, otherwise it will cause adv packets lost. - Range: - - from 50 to 1000 if CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP && CONFIG_BT_CONTROLLER_ENABLED - Default value: - CONFIG_BTDM_BLE_ADV_REPORT_DISCARD_THRSHOLD BLE adv lost event threshold value Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP When adv report flow control is enabled, The ADV lost event will be generated when the number of ADV packets lost in the controller reaches this threshold. It is better to set a larger value. If you set BTDM_BLE_ADV_REPORT_DISCARD_THRSHOLD to a small value or printf every adv lost event, it may cause adv packets lost more. - Range: - - from 1 to 1000 if CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP && CONFIG_BT_CONTROLLER_ENABLED - Default value: - CONFIG_BTDM_CTRL_HLI High level interrupt Found in: Component config > Bluetooth > Controller Options Using Level 4 interrupt for Bluetooth. - Default value: - - Yes (enabled) if CONFIG_BT_ENABLED && CONFIG_BT_CONTROLLER_ENABLED CONFIG_BT_RELEASE_IRAM Release Bluetooth text (READ DOCS FIRST) Found in: Component config > Bluetooth This option release Bluetooth text section and merge Bluetooth data, bss & text into a large free heap region when esp_bt_mem_release is called, total saving ~21kB or more of IRAM. ESP32-C2 only 3 configurable PMP entries available, rest of them are hard-coded. We cannot split the memory into 3 different regions (IRAM, BLE-IRAM, DRAM). So this option will disable the PMP (ESP_SYSTEM_PMP_IDRAM_SPLIT) - Default value: - - No (disabled) if CONFIG_BT_ENABLED && BT_LE_RELEASE_IRAM_SUPPORTED CONFIG_BLE_MESH ESP BLE Mesh Support Found in: Component config This option enables ESP BLE Mesh support. The specific features that are available may depend on other features that have been enabled in the stack, such as Bluetooth Support, Bluedroid Support & GATT support. Contains: CONFIG_BLE_MESH_HCI_5_0 Support sending 20ms non-connectable adv packets Found in: Component config > CONFIG_BLE_MESH It is a temporary solution and needs further modifications. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_RANDOM_ADV_INTERVAL Support using random adv interval for mesh packets Found in: Component config > CONFIG_BLE_MESH Enable this option to allow using random advertising interval for mesh packets. And this could help avoid collision of advertising packets. - Default value: - - No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_USE_DUPLICATE_SCAN Support Duplicate Scan in BLE Mesh Found in: Component config > CONFIG_BLE_MESH Enable this option to allow using specific duplicate scan filter in BLE Mesh, and Scan Duplicate Type must be set by choosing the option in the Bluetooth Controller section in menuconfig, which is "Scan Duplicate By Device Address and Advertising Data". - Default value: - - Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_ACTIVE_SCAN Support Active Scan in BLE Mesh Found in: Component config > CONFIG_BLE_MESH Enable this option to allow using BLE Active Scan for BLE Mesh. CONFIG_BLE_MESH_MEM_ALLOC_MODE Memory allocation strategy Found in: Component config > CONFIG_BLE_MESH Allocation strategy for BLE Mesh stack, essentially provides ability to allocate all required dynamic allocations from, - Internal DRAM memory only - External SPIRAM memory only - Either internal or external memory based on default malloc() behavior in ESP-IDF - Internal IRAM memory wherever applicable else internal DRAM Recommended mode here is always internal (*), since that is most preferred from security perspective. But if application requirement does not allow sufficient free internal memory then alternate mode can be selected. (*) In case of ESP32-S2/ESP32-S3, hardware allows encryption of external SPIRAM contents provided hardware flash encryption feature is enabled. In that case, using external SPIRAM allocation strategy is also safe choice from security perspective. Available options: - Internal DRAM (CONFIG_BLE_MESH_MEM_ALLOC_MODE_INTERNAL) - External SPIRAM (CONFIG_BLE_MESH_MEM_ALLOC_MODE_EXTERNAL) - Default alloc mode (CONFIG_BLE_MESH_MEM_ALLOC_MODE_DEFAULT) Enable this option to use the default memory allocation strategy when external SPIRAM is enabled. See the SPIRAM options for more details. - Internal IRAM (CONFIG_BLE_MESH_MEM_ALLOC_MODE_IRAM_8BIT) Allows to use IRAM memory region as 8bit accessible region. Every unaligned (8bit or 16bit) access will result in an exception and incur penalty of certain clock cycles per unaligned read/write. CONFIG_BLE_MESH_FREERTOS_STATIC_ALLOC Enable FreeRTOS static allocation Found in: Component config > CONFIG_BLE_MESH Enable this option to use FreeRTOS static allocation APIs for BLE Mesh, which provides the ability to use different dynamic memory (i.e. SPIRAM or IRAM) for FreeRTOS objects. If this option is disabled, the FreeRTOS static allocation APIs will not be used, and internal DRAM will be allocated for FreeRTOS objects. - Default value: - - No (disabled) if (CONFIG_SPIRAM || CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY) && CONFIG_BLE_MESH CONFIG_BLE_MESH_FREERTOS_STATIC_ALLOC_MODE Memory allocation for FreeRTOS objects Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FREERTOS_STATIC_ALLOC Choose the memory to be used for FreeRTOS objects. Available options: - External SPIRAM (CONFIG_BLE_MESH_FREERTOS_STATIC_ALLOC_EXTERNAL) If enabled, BLE Mesh allocates dynamic memory from external SPIRAM for FreeRTOS objects, i.e. mutex, queue, and task stack. External SPIRAM can only be used for task stack when SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY is enabled. See the SPIRAM options for more details. - Internal IRAM (CONFIG_BLE_MESH_FREERTOS_STATIC_ALLOC_IRAM_8BIT) If enabled, BLE Mesh allocates dynamic memory from internal IRAM for FreeRTOS objects, i.e. mutex, queue. Note: IRAM region cannot be used as task stack. CONFIG_BLE_MESH_DEINIT Support de-initialize BLE Mesh stack Found in: Component config > CONFIG_BLE_MESH If enabled, users can use the function esp_ble_mesh_deinit() to de-initialize the whole BLE Mesh stack. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH BLE Mesh and BLE coexistence support Contains: CONFIG_BLE_MESH_SUPPORT_BLE_ADV Support sending normal BLE advertising packets Found in: Component config > CONFIG_BLE_MESH > BLE Mesh and BLE coexistence support When selected, users can send normal BLE advertising packets with specific API. - Default value: - - No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_BLE_ADV_BUF_COUNT Number of advertising buffers for BLE advertising packets Found in: Component config > CONFIG_BLE_MESH > BLE Mesh and BLE coexistence support > CONFIG_BLE_MESH_SUPPORT_BLE_ADV Number of advertising buffers for BLE packets available. - Range: - - from 1 to 255 if CONFIG_BLE_MESH_SUPPORT_BLE_ADV && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_SUPPORT_BLE_SCAN Support scanning normal BLE advertising packets Found in: Component config > CONFIG_BLE_MESH > BLE Mesh and BLE coexistence support When selected, users can register a callback and receive normal BLE advertising packets in the application layer. - Default value: - - No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_FAST_PROV Enable BLE Mesh Fast Provisioning Found in: Component config > CONFIG_BLE_MESH Enable this option to allow BLE Mesh fast provisioning solution to be used. When there are multiple unprovisioned devices around, fast provisioning can greatly reduce the time consumption of the whole provisioning process. When this option is enabled, and after an unprovisioned device is provisioned into a node successfully, it can be changed to a temporary Provisioner. - Default value: - - No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_NODE Support for BLE Mesh Node Found in: Component config > CONFIG_BLE_MESH Enable the device to be provisioned into a node. This option should be enabled when an unprovisioned device is going to be provisioned into a node and communicate with other nodes in the BLE Mesh network. CONFIG_BLE_MESH_PROVISIONER Support for BLE Mesh Provisioner Found in: Component config > CONFIG_BLE_MESH Enable the device to be a Provisioner. The option should be enabled when a device is going to act as a Provisioner and provision unprovisioned devices into the BLE Mesh network. CONFIG_BLE_MESH_WAIT_FOR_PROV_MAX_DEV_NUM Maximum number of unprovisioned devices that can be added to device queue Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER This option specifies how many unprovisioned devices can be added to device queue for provisioning. Users can use this option to define the size of the queue in the bottom layer which is used to store unprovisioned device information (e.g. Device UUID, address). - Range: - - from 1 to 100 if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_MAX_PROV_NODES Maximum number of devices that can be provisioned by Provisioner Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER This option specifies how many devices can be provisioned by a Provisioner. This value indicates the maximum number of unprovisioned devices which can be provisioned by a Provisioner. For instance, if the value is 6, it means the Provisioner can provision up to 6 unprovisioned devices. Theoretically a Provisioner without the limitation of its memory can provision up to 32766 unprovisioned devices, here we limit the maximum number to 100 just to limit the memory used by a Provisioner. The bigger the value is, the more memory it will cost by a Provisioner to store the information of nodes. - Range: - - from 1 to 1000 if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_PBA_SAME_TIME Maximum number of PB-ADV running at the same time by Provisioner Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER This option specifies how many devices can be provisioned at the same time using PB-ADV. For examples, if the value is 2, it means a Provisioner can provision two unprovisioned devices with PB-ADV at the same time. - Range: - - from 1 to 10 if CONFIG_BLE_MESH_PB_ADV && CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_PBG_SAME_TIME Maximum number of PB-GATT running at the same time by Provisioner Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER This option specifies how many devices can be provisioned at the same time using PB-GATT. For example, if the value is 2, it means a Provisioner can provision two unprovisioned devices with PB-GATT at the same time. - Range: - - from 1 to 5 if CONFIG_BLE_MESH_PB_GATT && CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_PROVISIONER_SUBNET_COUNT Maximum number of mesh subnets that can be created by Provisioner Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER This option specifies how many subnets per network a Provisioner can create. Indeed, this value decides the number of network keys which can be added by a Provisioner. - Range: - - from 1 to 4096 if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_PROVISIONER_APP_KEY_COUNT Maximum number of application keys that can be owned by Provisioner Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER This option specifies how many application keys the Provisioner can have. Indeed, this value decides the number of the application keys which can be added by a Provisioner. - Range: - - from 1 to 4096 if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_PROVISIONER_RECV_HB Support receiving Heartbeat messages Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER When this option is enabled, Provisioner can call specific functions to enable or disable receiving Heartbeat messages and notify them to the application layer. - Default value: - - No (disabled) if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH CONFIG_BLE_MESH_PROVISIONER_RECV_HB_FILTER_SIZE Maximum number of filter entries for receiving Heartbeat messages Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER > CONFIG_BLE_MESH_PROVISIONER_RECV_HB This option specifies how many heartbeat filter entries Provisioner supports. The heartbeat filter (acceptlist or rejectlist) entries are used to store a list of SRC and DST which can be used to decide if a heartbeat message will be processed and notified to the application layer by Provisioner. Note: The filter is an empty rejectlist by default. - Range: - - from 1 to 1000 if CONFIG_BLE_MESH_PROVISIONER_RECV_HB && CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_PROV BLE Mesh Provisioning support Found in: Component config > CONFIG_BLE_MESH Enable this option to support BLE Mesh Provisioning functionality. For BLE Mesh, this option should be always enabled. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_PROV_EPA BLE Mesh enhanced provisioning authentication Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROV Enable this option to support BLE Mesh enhanced provisioning authentication functionality. This option can increase the security level of provisioning. It is recommended to enable this option. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH_PROV && CONFIG_BLE_MESH CONFIG_BLE_MESH_CERT_BASED_PROV Support Certificate-based provisioning Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROV Enable this option to support BLE Mesh Certificate-Based Provisioning. - Default value: - - No (disabled) if CONFIG_BLE_MESH_PROV && CONFIG_BLE_MESH CONFIG_BLE_MESH_RECORD_FRAG_MAX_SIZE Maximum size of the provisioning record fragment that Provisioner can receive Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROV > CONFIG_BLE_MESH_CERT_BASED_PROV This option sets the maximum size of the provisioning record fragment that the Provisioner can receive. The range depends on provisioning bearer. - Range: - - from 1 to 57 if CONFIG_BLE_MESH_CERT_BASED_PROV && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_PB_ADV Provisioning support using the advertising bearer (PB-ADV) Found in: Component config > CONFIG_BLE_MESH Enable this option to allow the device to be provisioned over the advertising bearer. This option should be enabled if PB-ADV is going to be used during provisioning procedure. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_UNPROVISIONED_BEACON_INTERVAL Interval between two consecutive Unprovisioned Device Beacon Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PB_ADV This option specifies the interval of sending two consecutive unprovisioned device beacon, users can use this option to change the frequency of sending unprovisioned device beacon. For example, if the value is 5, it means the unprovisioned device beacon will send every 5 seconds. When the option of BLE_MESH_FAST_PROV is selected, the value is better to be 3 seconds, or less. - Range: - - from 1 to 100 if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PB_ADV && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_PB_GATT Provisioning support using GATT (PB-GATT) Found in: Component config > CONFIG_BLE_MESH Enable this option to allow the device to be provisioned over GATT. This option should be enabled if PB-GATT is going to be used during provisioning procedure. # Virtual option enabled whenever any Proxy protocol is needed CONFIG_BLE_MESH_PROXY BLE Mesh Proxy protocol support Found in: Component config > CONFIG_BLE_MESH Enable this option to support BLE Mesh Proxy protocol used by PB-GATT and other proxy pdu transmission. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_GATT_PROXY_SERVER BLE Mesh GATT Proxy Server Found in: Component config > CONFIG_BLE_MESH This option enables support for Mesh GATT Proxy Service, i.e. the ability to act as a proxy between a Mesh GATT Client and a Mesh network. This option should be enabled if a node is going to be a Proxy Server. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH CONFIG_BLE_MESH_NODE_ID_TIMEOUT Node Identity advertising timeout Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_SERVER This option determines for how long the local node advertises using Node Identity. The given value is in seconds. The specification limits this to 60 seconds and lists it as the recommended value as well. So leaving the default value is the safest option. When an unprovisioned device is provisioned successfully and becomes a node, it will start to advertise using Node Identity during the time set by this option. And after that, Network ID will be advertised. - Range: - - from 1 to 60 if CONFIG_BLE_MESH_GATT_PROXY_SERVER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_PROXY_FILTER_SIZE Maximum number of filter entries per Proxy Client Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_SERVER This option specifies how many Proxy Filter entries the local node supports. The entries of Proxy filter (whitelist or blacklist) are used to store a list of addresses which can be used to decide which messages will be forwarded to the Proxy Client by the Proxy Server. - Range: - - from 1 to 32767 if CONFIG_BLE_MESH_GATT_PROXY_SERVER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_PROXY_PRIVACY Support Proxy Privacy Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_SERVER The Proxy Privacy parameter controls the privacy of the Proxy Server over the connection. The value of the Proxy Privacy parameter is controlled by the type of proxy connection, which is dependent on the bearer used by the proxy connection. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH_PRB_SRV && CONFIG_BLE_MESH_GATT_PROXY_SERVER && CONFIG_BLE_MESH CONFIG_BLE_MESH_PROXY_SOLIC_PDU_RX Support receiving Proxy Solicitation PDU Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_SERVER Enable this option to support receiving Proxy Solicitation PDU. CONFIG_BLE_MESH_PROXY_SOLIC_RX_CRPL Maximum capacity of solicitation replay protection list Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_SERVER > CONFIG_BLE_MESH_PROXY_SOLIC_PDU_RX This option specifies the maximum capacity of the solicitation replay protection list. The solicitation replay protection list is used to reject Solicitation PDUs that were already processed by a node, which will store the solicitation src and solicitation sequence number of the received Solicitation PDU message. - Range: - - from 1 to 255 if CONFIG_BLE_MESH_PROXY_SOLIC_PDU_RX && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_GATT_PROXY_CLIENT BLE Mesh GATT Proxy Client Found in: Component config > CONFIG_BLE_MESH This option enables support for Mesh GATT Proxy Client. The Proxy Client can use the GATT bearer to send mesh messages to a node that supports the advertising bearer. - Default value: - - No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_PROXY_SOLIC_PDU_TX Support sending Proxy Solicitation PDU Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_CLIENT Enable this option to support sending Proxy Solicitation PDU. CONFIG_BLE_MESH_PROXY_SOLIC_TX_SRC_COUNT Maximum number of SSRC that can be used by Proxy Client Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_CLIENT > CONFIG_BLE_MESH_PROXY_SOLIC_PDU_TX This option specifies the maximum number of Solicitation Source (SSRC) that can be used by Proxy Client for sending a Solicitation PDU. A Proxy Client may use the primary address or any of the secondary addresses as the SSRC for a Solicitation PDU. So for a Proxy Client, it's better to choose the value based on its own element count. - Range: - - from 1 to 16 if CONFIG_BLE_MESH_PROXY_SOLIC_PDU_TX && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_SETTINGS Store BLE Mesh configuration persistently Found in: Component config > CONFIG_BLE_MESH When selected, the BLE Mesh stack will take care of storing/restoring the BLE Mesh configuration persistently in flash. If the device is a BLE Mesh node, when this option is enabled, the configuration of the device will be stored persistently, including unicast address, NetKey, AppKey, etc. And if the device is a BLE Mesh Provisioner, the information of the device will be stored persistently, including the information of provisioned nodes, NetKey, AppKey, etc. - Default value: - - No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_STORE_TIMEOUT Delay (in seconds) before storing anything persistently Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS This value defines in seconds how soon any pending changes are actually written into persistent storage (flash) after a change occurs. The option allows nodes to delay a certain period of time to save proper information to flash. The default value is 0, which means information will be stored immediately once there are updates. - Range: - - from 0 to 1000000 if CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_SEQ_STORE_RATE How often the sequence number gets updated in storage Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS This value defines how often the local sequence number gets updated in persistent storage (i.e. flash). e.g. a value of 100 means that the sequence number will be stored to flash on every 100th increment. If the node sends messages very frequently a higher value makes more sense, whereas if the node sends infrequently a value as low as 0 (update storage for every increment) can make sense. When the stack gets initialized it will add sequence number to the last stored one, so that it starts off with a value that's guaranteed to be larger than the last one used before power off. - Range: - - from 0 to 1000000 if CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_RPL_STORE_TIMEOUT Minimum frequency that the RPL gets updated in storage Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS This value defines in seconds how soon the RPL (Replay Protection List) gets written to persistent storage after a change occurs. If the node receives messages frequently, then a large value is recommended. If the node receives messages rarely, then the value can be as low as 0 (which means the RPL is written into the storage immediately). Note that if the node operates in a security-sensitive case, and there is a risk of sudden power-off, then a value of 0 is strongly recommended. Otherwise, a power loss before RPL being written into the storage may introduce message replay attacks and system security will be in a vulnerable state. - Range: - - from 0 to 1000000 if CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_SETTINGS_BACKWARD_COMPATIBILITY A specific option for settings backward compatibility Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS This option is created to solve the issue of failure in recovering node information after mesh stack updates. In the old version mesh stack, there is no key of "mesh/role" in nvs. In the new version mesh stack, key of "mesh/role" is added in nvs, recovering node information needs to check "mesh/role" key in nvs and implements selective recovery of mesh node information. Therefore, there may be failure in recovering node information during node restarting after OTA. The new version mesh stack adds the option of "mesh/role" because we have added the support of storing Provisioner information, while the old version only supports storing node information. If users are updating their nodes from old version to new version, we recommend enabling this option, so that system could set the flag in advance before recovering node information and make sure the node information recovering could work as expected. - Default value: - - No (disabled) if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH CONFIG_BLE_MESH_SPECIFIC_PARTITION Use a specific NVS partition for BLE Mesh Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS When selected, the mesh stack will use a specified NVS partition instead of default NVS partition. Note that the specified partition must be registered with NVS using nvs_flash_init_partition() API, and the partition must exists in the csv file. When Provisioner needs to store a large amount of nodes' information in the flash (e.g. more than 20), this option is recommended to be enabled. - Default value: - - No (disabled) if CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH CONFIG_BLE_MESH_PARTITION_NAME Name of the NVS partition for BLE Mesh Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS > CONFIG_BLE_MESH_SPECIFIC_PARTITION This value defines the name of the specified NVS partition used by the mesh stack. - Default value: - - "ble_mesh" if CONFIG_BLE_MESH_SPECIFIC_PARTITION && CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH CONFIG_BLE_MESH_USE_MULTIPLE_NAMESPACE Support using multiple NVS namespaces by Provisioner Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS When selected, Provisioner can use different NVS namespaces to store different instances of mesh information. For example, if in the first room, Provisioner uses NetKey A, AppKey A and provisions three devices, these information will be treated as mesh information instance A. When the Provisioner moves to the second room, it uses NetKey B, AppKey B and provisions two devices, then the information will be treated as mesh information instance B. Here instance A and instance B will be stored in different namespaces. With this option enabled, Provisioner needs to use specific functions to open the corresponding NVS namespace, restore the mesh information, release the mesh information or erase the mesh information. - Default value: - - No (disabled) if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH CONFIG_BLE_MESH_MAX_NVS_NAMESPACE Maximum number of NVS namespaces Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS > CONFIG_BLE_MESH_USE_MULTIPLE_NAMESPACE This option specifies the maximum NVS namespaces supported by Provisioner. - Range: - - from 1 to 255 if CONFIG_BLE_MESH_USE_MULTIPLE_NAMESPACE && CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_SUBNET_COUNT Maximum number of mesh subnets per network Found in: Component config > CONFIG_BLE_MESH This option specifies how many subnets a Mesh network can have at the same time. Indeed, this value decides the number of the network keys which can be owned by a node. - Range: - - from 1 to 4096 if CONFIG_BLE_MESH - Default value: - - 3 if CONFIG_BLE_MESH CONFIG_BLE_MESH_APP_KEY_COUNT Maximum number of application keys per network Found in: Component config > CONFIG_BLE_MESH This option specifies how many application keys the device can store per network. Indeed, this value decides the number of the application keys which can be owned by a node. - Range: - - from 1 to 4096 if CONFIG_BLE_MESH - Default value: - - 3 if CONFIG_BLE_MESH CONFIG_BLE_MESH_MODEL_KEY_COUNT Maximum number of application keys per model Found in: Component config > CONFIG_BLE_MESH This option specifies the maximum number of application keys to which each model can be bound. - Range: - - from 1 to 4096 if CONFIG_BLE_MESH - Default value: - - 3 if CONFIG_BLE_MESH CONFIG_BLE_MESH_MODEL_GROUP_COUNT Maximum number of group address subscriptions per model Found in: Component config > CONFIG_BLE_MESH This option specifies the maximum number of addresses to which each model can be subscribed. - Range: - - from 1 to 4096 if CONFIG_BLE_MESH - Default value: - - 3 if CONFIG_BLE_MESH CONFIG_BLE_MESH_LABEL_COUNT Maximum number of Label UUIDs used for Virtual Addresses Found in: Component config > CONFIG_BLE_MESH This option specifies how many Label UUIDs can be stored. Indeed, this value decides the number of the Virtual Addresses can be supported by a node. - Range: - - from 0 to 4096 if CONFIG_BLE_MESH - Default value: - - 3 if CONFIG_BLE_MESH CONFIG_BLE_MESH_CRPL Maximum capacity of the replay protection list Found in: Component config > CONFIG_BLE_MESH This option specifies the maximum capacity of the replay protection list. It is similar to Network message cache size, but has a different purpose. The replay protection list is used to prevent a node from replay attack, which will store the source address and sequence number of the received mesh messages. For Provisioner, the replay protection list size should not be smaller than the maximum number of nodes whose information can be stored. And the element number of each node should also be taken into consideration. For example, if Provisioner can provision up to 20 nodes and each node contains two elements, then the replay protection list size of Provisioner should be at least 40. - Range: - - from 2 to 65535 if CONFIG_BLE_MESH - Default value: - - 10 if CONFIG_BLE_MESH CONFIG_BLE_MESH_NOT_RELAY_REPLAY_MSG Not relay replayed messages in a mesh network Found in: Component config > CONFIG_BLE_MESH There may be many expired messages in a complex mesh network that would be considered replayed messages. Enable this option will refuse to relay such messages, which could help to reduce invalid packets in the mesh network. However, it should be noted that enabling this option may result in packet loss in certain environments. Therefore, users need to decide whether to enable this option according to the actual usage situation. - Default value: - - No (disabled) if CONFIG_BLE_MESH_EXPERIMENTAL && CONFIG_BLE_MESH CONFIG_BLE_MESH_MSG_CACHE_SIZE Network message cache size Found in: Component config > CONFIG_BLE_MESH Number of messages that are cached for the network. This helps prevent unnecessary decryption operations and unnecessary relays. This option is similar to Replay protection list, but has a different purpose. A node is not required to cache the entire Network PDU and may cache only part of it for tracking, such as values for SRC/SEQ or others. - Range: - - from 2 to 65535 if CONFIG_BLE_MESH - Default value: - - 10 if CONFIG_BLE_MESH CONFIG_BLE_MESH_ADV_BUF_COUNT Number of advertising buffers Found in: Component config > CONFIG_BLE_MESH Number of advertising buffers available. The transport layer reserves ADV_BUF_COUNT - 3 buffers for outgoing segments. The maximum outgoing SDU size is 12 times this value (out of which 4 or 8 bytes are used for the Transport Layer MIC). For example, 5 segments means the maximum SDU size is 60 bytes, which leaves 56 bytes for application layer data using a 4-byte MIC, or 52 bytes using an 8-byte MIC. - Range: - - from 6 to 256 if CONFIG_BLE_MESH - Default value: - - 60 if CONFIG_BLE_MESH CONFIG_BLE_MESH_IVU_DIVIDER Divider for IV Update state refresh timer Found in: Component config > CONFIG_BLE_MESH When the IV Update state enters Normal operation or IV Update in Progress, we need to keep track of how many hours has passed in the state, since the specification requires us to remain in the state at least for 96 hours (Update in Progress has an additional upper limit of 144 hours). In order to fulfill the above requirement, even if the node might be powered off once in a while, we need to store persistently how many hours the node has been in the state. This doesn't necessarily need to happen every hour (thanks to the flexible duration range). The exact cadence will depend a lot on the ways that the node will be used and what kind of power source it has. Since there is no single optimal answer, this configuration option allows specifying a divider, i.e. how many intervals the 96 hour minimum gets split into. After each interval the duration that the node has been in the current state gets stored to flash. E.g. the default value of 4 means that the state is saved every 24 hours (96 / 4). - Range: - - from 2 to 96 if CONFIG_BLE_MESH - Default value: - - 4 if CONFIG_BLE_MESH CONFIG_BLE_MESH_IVU_RECOVERY_IVI Recovery the IV index when the latest whole IV update procedure is missed Found in: Component config > CONFIG_BLE_MESH According to Section 3.10.5 of Mesh Specification v1.0.1. If a node in Normal Operation receives a Secure Network beacon with an IV index equal to the last known IV index+1 and the IV Update Flag set to 0, the node may update its IV without going to the IV Update in Progress state, or it may initiate an IV Index Recovery procedure (Section 3.10.6), or it may ignore the Secure Network beacon. The node makes the choice depending on the time since last IV update and the likelihood that the node has missed the Secure Network beacons with the IV update Flag. When the above situation is encountered, this option can be used to decide whether to perform the IV index recovery procedure. - Default value: - - No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_SAR_ENHANCEMENT Segmentation and reassembly enhancement Found in: Component config > CONFIG_BLE_MESH Enable this option to use the enhanced segmentation and reassembly mechanism introduced in Bluetooth Mesh Protocol 1.1. - Default value: - - No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_TX_SEG_MSG_COUNT Maximum number of simultaneous outgoing segmented messages Found in: Component config > CONFIG_BLE_MESH Maximum number of simultaneous outgoing multi-segment and/or reliable messages. The default value is 1, which means the device can only send one segmented message at a time. And if another segmented message is going to be sent, it should wait for the completion of the previous one. If users are going to send multiple segmented messages at the same time, this value should be configured properly. - Range: - - from 1 to if CONFIG_BLE_MESH - Default value: - - 1 if CONFIG_BLE_MESH CONFIG_BLE_MESH_RX_SEG_MSG_COUNT Maximum number of simultaneous incoming segmented messages Found in: Component config > CONFIG_BLE_MESH Maximum number of simultaneous incoming multi-segment and/or reliable messages. The default value is 1, which means the device can only receive one segmented message at a time. And if another segmented message is going to be received, it should wait for the completion of the previous one. If users are going to receive multiple segmented messages at the same time, this value should be configured properly. - Range: - - from 1 to 255 if CONFIG_BLE_MESH - Default value: - - 1 if CONFIG_BLE_MESH CONFIG_BLE_MESH_RX_SDU_MAX Maximum incoming Upper Transport Access PDU length Found in: Component config > CONFIG_BLE_MESH Maximum incoming Upper Transport Access PDU length. Leave this to the default value, unless you really need to optimize memory usage. - Range: - - from 36 to 384 if CONFIG_BLE_MESH - Default value: - - 384 if CONFIG_BLE_MESH CONFIG_BLE_MESH_TX_SEG_MAX Maximum number of segments in outgoing messages Found in: Component config > CONFIG_BLE_MESH Maximum number of segments supported for outgoing messages. This value should typically be fine-tuned based on what models the local node supports, i.e. what's the largest message payload that the node needs to be able to send. This value affects memory and call stack consumption, which is why the default is lower than the maximum that the specification would allow (32 segments). The maximum outgoing SDU size is 12 times this number (out of which 4 or 8 bytes is used for the Transport Layer MIC). For example, 5 segments means the maximum SDU size is 60 bytes, which leaves 56 bytes for application layer data using a 4-byte MIC and 52 bytes using an 8-byte MIC. Be sure to specify a sufficient number of advertising buffers when setting this option to a higher value. There must be at least three more advertising buffers (BLE_MESH_ADV_BUF_COUNT) as there are outgoing segments. - Range: - - from 2 to 32 if CONFIG_BLE_MESH - Default value: - - 32 if CONFIG_BLE_MESH CONFIG_BLE_MESH_RELAY Relay support Found in: Component config > CONFIG_BLE_MESH Support for acting as a Mesh Relay Node. Enabling this option will allow a node to support the Relay feature, and the Relay feature can still be enabled or disabled by proper configuration messages. Disabling this option will let a node not support the Relay feature. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH CONFIG_BLE_MESH_RELAY_ADV_BUF Use separate advertising buffers for relay packets Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_RELAY When selected, self-send packets will be put in a high-priority queue and relay packets will be put in a low-priority queue. - Default value: - - No (disabled) if CONFIG_BLE_MESH_RELAY && CONFIG_BLE_MESH CONFIG_BLE_MESH_RELAY_ADV_BUF_COUNT Number of advertising buffers for relay packets Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_RELAY > CONFIG_BLE_MESH_RELAY_ADV_BUF Number of advertising buffers for relay packets available. - Range: - - from 6 to 256 if CONFIG_BLE_MESH_RELAY_ADV_BUF && CONFIG_BLE_MESH_RELAY && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_LOW_POWER Support for Low Power features Found in: Component config > CONFIG_BLE_MESH Enable this option to operate as a Low Power Node. If low power consumption is required by a node, this option should be enabled. And once the node enters the mesh network, it will try to find a Friend node and establish a friendship. CONFIG_BLE_MESH_LPN_ESTABLISHMENT Perform Friendship establishment using low power Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER Perform the Friendship establishment using low power with the help of a reduced scan duty cycle. The downside of this is that the node may miss out on messages intended for it until it has successfully set up Friendship with a Friend node. When this option is enabled, the node will stop scanning for a period of time after a Friend Request or Friend Poll is sent, so as to reduce more power consumption. - Default value: - - No (disabled) if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH CONFIG_BLE_MESH_LPN_AUTO Automatically start looking for Friend nodes once provisioned Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER Once provisioned, automatically enable LPN functionality and start looking for Friend nodes. If this option is disabled LPN mode needs to be manually enabled by calling bt_mesh_lpn_set(true). When an unprovisioned device is provisioned successfully and becomes a node, enabling this option will trigger the node starts to send Friend Request at a certain period until it finds a proper Friend node. - Default value: - - No (disabled) if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH CONFIG_BLE_MESH_LPN_AUTO_TIMEOUT Time from last received message before going to LPN mode Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER > CONFIG_BLE_MESH_LPN_AUTO Time in seconds from the last received message, that the node waits out before starting to look for Friend nodes. - Range: - - from 0 to 3600 if CONFIG_BLE_MESH_LPN_AUTO && CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_LPN_RETRY_TIMEOUT Retry timeout for Friend requests Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER Time in seconds between Friend Requests, if a previous Friend Request did not yield any acceptable Friend Offers. - Range: - - from 1 to 3600 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_LPN_RSSI_FACTOR RSSIFactor, used in Friend Offer Delay calculation Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER The contribution of the RSSI, measured by the Friend node, used in Friend Offer Delay calculations. 0 = 1, 1 = 1.5, 2 = 2, 3 = 2.5. RSSIFactor, one of the parameters carried by Friend Request sent by Low Power node, which is used to calculate the Friend Offer Delay. - Range: - - from 0 to 3 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_LPN_RECV_WIN_FACTOR ReceiveWindowFactor, used in Friend Offer Delay calculation Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER The contribution of the supported Receive Window used in Friend Offer Delay calculations. 0 = 1, 1 = 1.5, 2 = 2, 3 = 2.5. ReceiveWindowFactor, one of the parameters carried by Friend Request sent by Low Power node, which is used to calculate the Friend Offer Delay. - Range: - - from 0 to 3 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_LPN_MIN_QUEUE_SIZE Minimum size of the acceptable friend queue (MinQueueSizeLog) Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER The MinQueueSizeLog field is defined as log_2(N), where N is the minimum number of maximum size Lower Transport PDUs that the Friend node can store in its Friend Queue. As an example, MinQueueSizeLog value 1 gives N = 2, and value 7 gives N = 128. - Range: - - from 1 to 7 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_LPN_RECV_DELAY Receive delay requested by the local node Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER The ReceiveDelay is the time between the Low Power node sending a request and listening for a response. This delay allows the Friend node time to prepare the response. The value is in units of milliseconds. - Range: - - from 10 to 255 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH - Default value: - - 100 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH CONFIG_BLE_MESH_LPN_POLL_TIMEOUT The value of the PollTimeout timer Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER PollTimeout timer is used to measure time between two consecutive requests sent by a Low Power node. If no requests are received the Friend node before the PollTimeout timer expires, then the friendship is considered terminated. The value is in units of 100 milliseconds, so e.g. a value of 300 means 30 seconds. The smaller the value, the faster the Low Power node tries to get messages from corresponding Friend node and vice versa. - Range: - - from 10 to 244735 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH - Default value: - - 300 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH CONFIG_BLE_MESH_LPN_INIT_POLL_TIMEOUT The starting value of the PollTimeout timer Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER The initial value of the PollTimeout timer when Friendship is to be established for the first time. After this, the timeout gradually grows toward the actual PollTimeout, doubling in value for each iteration. The value is in units of 100 milliseconds, so e.g. a value of 300 means 30 seconds. - Range: - - from 10 to if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_LPN_SCAN_LATENCY Latency for enabling scanning Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER Latency (in milliseconds) is the time it takes to enable scanning. In practice, it means how much time in advance of the Receive Window, the request to enable scanning is made. - Range: - - from 0 to 50 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH - Default value: - - 10 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH CONFIG_BLE_MESH_LPN_GROUPS Number of groups the LPN can subscribe to Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER Maximum number of groups to which the LPN can subscribe. - Range: - - from 0 to 16384 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_LPN_SUB_ALL_NODES_ADDR Automatically subscribe all nodes address Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER Automatically subscribe all nodes address when friendship established. - Default value: - - No (disabled) if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH CONFIG_BLE_MESH_FRIEND Support for Friend feature Found in: Component config > CONFIG_BLE_MESH Enable this option to be able to act as a Friend Node. CONFIG_BLE_MESH_FRIEND_RECV_WIN Friend Receive Window Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FRIEND Receive Window in milliseconds supported by the Friend node. - Range: - - from 1 to 255 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH - Default value: - - 255 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH CONFIG_BLE_MESH_FRIEND_QUEUE_SIZE Minimum number of buffers supported per Friend Queue Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FRIEND Minimum number of buffers available to be stored for each local Friend Queue. This option decides the size of each buffer which can be used by a Friend node to store messages for each Low Power node. - Range: - - from 2 to 65536 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH - Default value: - - 16 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH CONFIG_BLE_MESH_FRIEND_SUB_LIST_SIZE Friend Subscription List Size Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FRIEND Size of the Subscription List that can be supported by a Friend node for a Low Power node. And Low Power node can send Friend Subscription List Add or Friend Subscription List Remove messages to the Friend node to add or remove subscription addresses. - Range: - - from 0 to 1023 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_FRIEND_LPN_COUNT Number of supported LPN nodes Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FRIEND Number of Low Power Nodes with which a Friend can have Friendship simultaneously. A Friend node can have friendship with multiple Low Power nodes at the same time, while a Low Power node can only establish friendship with only one Friend node at the same time. - Range: - - from 1 to 1000 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_FRIEND_SEG_RX Number of incomplete segment lists per LPN Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FRIEND Number of incomplete segment lists tracked for each Friends' LPN. In other words, this determines from how many elements can segmented messages destined for the Friend queue be received simultaneously. - Range: - - from 1 to 1000 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_NO_LOG Disable BLE Mesh debug logs (minimize bin size) Found in: Component config > CONFIG_BLE_MESH Select this to save the BLE Mesh related rodata code size. Enabling this option will disable the output of BLE Mesh debug log. - Default value: - - No (disabled) if CONFIG_BLE_MESH && CONFIG_BLE_MESH BLE Mesh STACK DEBUG LOG LEVEL Contains: CONFIG_BLE_MESH_STACK_TRACE_LEVEL BLE_MESH_STACK Found in: Component config > CONFIG_BLE_MESH > BLE Mesh STACK DEBUG LOG LEVEL Define BLE Mesh trace level for BLE Mesh stack. Available options: - NONE (CONFIG_BLE_MESH_TRACE_LEVEL_NONE) - ERROR (CONFIG_BLE_MESH_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BLE_MESH_TRACE_LEVEL_WARNING) - INFO (CONFIG_BLE_MESH_TRACE_LEVEL_INFO) - DEBUG (CONFIG_BLE_MESH_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BLE_MESH_TRACE_LEVEL_VERBOSE) BLE Mesh NET BUF DEBUG LOG LEVEL Contains: CONFIG_BLE_MESH_NET_BUF_TRACE_LEVEL BLE_MESH_NET_BUF Found in: Component config > CONFIG_BLE_MESH > BLE Mesh NET BUF DEBUG LOG LEVEL Define BLE Mesh trace level for BLE Mesh net buffer. Available options: - NONE (CONFIG_BLE_MESH_NET_BUF_TRACE_LEVEL_NONE) - ERROR (CONFIG_BLE_MESH_NET_BUF_TRACE_LEVEL_ERROR) - WARNING (CONFIG_BLE_MESH_NET_BUF_TRACE_LEVEL_WARNING) - INFO (CONFIG_BLE_MESH_NET_BUF_TRACE_LEVEL_INFO) - DEBUG (CONFIG_BLE_MESH_NET_BUF_TRACE_LEVEL_DEBUG) - VERBOSE (CONFIG_BLE_MESH_NET_BUF_TRACE_LEVEL_VERBOSE) CONFIG_BLE_MESH_CLIENT_MSG_TIMEOUT Timeout(ms) for client message response Found in: Component config > CONFIG_BLE_MESH Timeout value used by the node to get response of the acknowledged message which is sent by the client model. This value indicates the maximum time that a client model waits for the response of the sent acknowledged messages. If a client model uses 0 as the timeout value when sending acknowledged messages, then the default value will be used which is four seconds. - Range: - - from 100 to 1200000 if CONFIG_BLE_MESH - Default value: - - 4000 if CONFIG_BLE_MESH Support for BLE Mesh Foundation models Contains: CONFIG_BLE_MESH_CFG_CLI Configuration Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Configuration Client model. CONFIG_BLE_MESH_HEALTH_CLI Health Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Health Client model. CONFIG_BLE_MESH_HEALTH_SRV Health Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Health Server model. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_BRC_CLI Bridge Configuration Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Bridge Configuration Client model. CONFIG_BLE_MESH_BRC_SRV Bridge Configuration Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Bridge Configuration Server model. - Default value: - - No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_MAX_BRIDGING_TABLE_ENTRY_COUNT Maximum number of Bridging Table entries Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_BRC_SRV Maximum number of Bridging Table entries that the Bridge Configuration Server can support. - Range: - - from 16 to 65535 if CONFIG_BLE_MESH_BRC_SRV && CONFIG_BLE_MESH - Default value: - - 16 if CONFIG_BLE_MESH_BRC_SRV && CONFIG_BLE_MESH CONFIG_BLE_MESH_BRIDGE_CRPL Maximum capacity of bridge replay protection list Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_BRC_SRV This option specifies the maximum capacity of the bridge replay protection list. The bridge replay protection list is used to prevent a bridged subnet from replay attack, which will store the source address and sequence number of the received bridge messages. - Range: - - from 1 to 255 if CONFIG_BLE_MESH_BRC_SRV && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_PRB_CLI Mesh Private Beacon Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Mesh Private Beacon Client model. CONFIG_BLE_MESH_PRB_SRV Mesh Private Beacon Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Mesh Private Beacon Server model. CONFIG_BLE_MESH_ODP_CLI On-Demand Private Proxy Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for On-Demand Private Proxy Client model. CONFIG_BLE_MESH_ODP_SRV On-Demand Private Proxy Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for On-Demand Private Proxy Server model. CONFIG_BLE_MESH_SRPL_CLI Solicitation PDU RPL Configuration Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Solicitation PDU RPL Configuration Client model. CONFIG_BLE_MESH_SRPL_SRV Solicitation PDU RPL Configuration Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Solicitation PDU RPL Configuration Server model. Note: This option depends on the functionality of receiving Solicitation PDU. If the device doesn't support receiving Solicitation PDU, then there is no need to enable this server model. CONFIG_BLE_MESH_AGG_CLI Opcodes Aggregator Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Opcodes Aggregator Client model. CONFIG_BLE_MESH_AGG_SRV Opcodes Aggregator Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Opcodes Aggregator Server model. CONFIG_BLE_MESH_SAR_CLI SAR Configuration Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for SAR Configuration Client model. CONFIG_BLE_MESH_SAR_SRV SAR Configuration Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for SAR Configuration Server model. CONFIG_BLE_MESH_COMP_DATA_1 Support Composition Data Page 1 Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Composition Data Page 1 contains information about the relationships among models. Each model either can be a root model or can extend other models. CONFIG_BLE_MESH_COMP_DATA_128 Support Composition Data Page 128 Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Composition Data Page 128 is used to indicate the structure of elements, features, and models of a node after the successful execution of the Node Address Refresh procedure or the Node Composition Refresh procedure, or after the execution of the Node Removal procedure followed by the provisioning process. Composition Data Page 128 shall be present if the node supports the Remote Provisioning Server model; otherwise it is optional. CONFIG_BLE_MESH_MODELS_METADATA_0 Support Models Metadata Page 0 Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models The Models Metadata state contains metadata of a node’s models. The Models Metadata state is composed of a number of pages of information. Models Metadata Page 0 shall be present if the node supports the Large Composition Data Server model. CONFIG_BLE_MESH_MODELS_METADATA_128 Support Models Metadata Page 128 Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_MODELS_METADATA_0 The Models Metadata state contains metadata of a node’s models. The Models Metadata state is composed of a number of pages of information. Models Metadata Page 128 contains metadata for the node’s models after the successful execution of the Node Address Refresh procedure or the Node Composition Refresh procedure, or after the execution of the Node Removal procedure followed by the provisioning process. Models Metadata Page 128 shall be present if the node supports the Remote Provisioning Server model and the node supports the Large Composition Data Server model. CONFIG_BLE_MESH_LCD_CLI Large Composition Data Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Large Composition Data Client model. CONFIG_BLE_MESH_LCD_SRV Large Composition Data Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Large Composition Data Server model. CONFIG_BLE_MESH_RPR_CLI Remote Provisioning Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Remote Provisioning Client model CONFIG_BLE_MESH_RPR_CLI_PROV_SAME_TIME Maximum number of PB-Remote running at the same time by Provisioner Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_RPR_CLI This option specifies how many devices can be provisioned at the same time using PB-REMOTE. For example, if the value is 2, it means a Provisioner can provision two unprovisioned devices with PB-REMOTE at the same time. - Range: - - from 1 to 5 if CONFIG_BLE_MESH_RPR_CLI && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_RPR_SRV Remote Provisioning Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Remote Provisioning Server model CONFIG_BLE_MESH_RPR_SRV_MAX_SCANNED_ITEMS Maximum number of device information can be scanned Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_RPR_SRV This option specifies how many device information can a Remote Provisioning Server store each time while scanning. - Range: - - from 4 to 255 if CONFIG_BLE_MESH_RPR_SRV && CONFIG_BLE_MESH - Default value: - - 10 if CONFIG_BLE_MESH_RPR_SRV && CONFIG_BLE_MESH CONFIG_BLE_MESH_RPR_SRV_ACTIVE_SCAN Support Active Scan for remote provisioning Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_RPR_SRV Enable this option to support Active Scan for remote provisioning. CONFIG_BLE_MESH_RPR_SRV_MAX_EXT_SCAN Maximum number of extended scan procedures Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_RPR_SRV This option specifies how many extended scan procedures can be started by the Remote Provisioning Server. - Range: - - from 1 to 10 if CONFIG_BLE_MESH_RPR_SRV && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_DF_CLI Directed Forwarding Configuration Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Directed Forwarding Configuration Client model. CONFIG_BLE_MESH_DF_SRV Directed Forwarding Configuration Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models Enable support for Directed Forwarding Configuration Server model. CONFIG_BLE_MESH_MAX_DISC_TABLE_ENTRY_COUNT Maximum number of discovery table entries in a given subnet Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_DF_SRV Maximum number of Discovery Table entries supported by the node in a given subnet. - Range: - - from 2 to 255 if CONFIG_BLE_MESH_DF_SRV && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_MAX_FORWARD_TABLE_ENTRY_COUNT Maximum number of forward table entries in a given subnet Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_DF_SRV Maximum number of Forward Table entries supported by the node in a given subnet. - Range: - - from 2 to 64 if CONFIG_BLE_MESH_DF_SRV && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_MAX_DEPS_NODES_PER_PATH Maximum number of dependent nodes per path Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_DF_SRV Maximum size of dependent nodes list supported by each forward table entry. - Range: - - from 2 to 64 if CONFIG_BLE_MESH_DF_SRV && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_PATH_MONITOR_TEST Enable Path Monitoring test mode Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_DF_SRV The option only removes the Path Use timer; all other behavior of the device is not changed. If Path Monitoring test mode is going to be used, this option should be enabled. - Default value: - - No (disabled) if CONFIG_BLE_MESH_DF_SRV && CONFIG_BLE_MESH CONFIG_BLE_MESH_SUPPORT_DIRECTED_PROXY Enable Directed Proxy functionality Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models > CONFIG_BLE_MESH_DF_SRV Support Directed Proxy functionality. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH_GATT_PROXY_SERVER && CONFIG_BLE_MESH_DF_SRV && CONFIG_BLE_MESH Support for BLE Mesh Client/Server models Contains: CONFIG_BLE_MESH_GENERIC_ONOFF_CLI Generic OnOff Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic OnOff Client model. CONFIG_BLE_MESH_GENERIC_LEVEL_CLI Generic Level Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic Level Client model. CONFIG_BLE_MESH_GENERIC_DEF_TRANS_TIME_CLI Generic Default Transition Time Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic Default Transition Time Client model. CONFIG_BLE_MESH_GENERIC_POWER_ONOFF_CLI Generic Power OnOff Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic Power OnOff Client model. CONFIG_BLE_MESH_GENERIC_POWER_LEVEL_CLI Generic Power Level Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic Power Level Client model. CONFIG_BLE_MESH_GENERIC_BATTERY_CLI Generic Battery Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic Battery Client model. CONFIG_BLE_MESH_GENERIC_LOCATION_CLI Generic Location Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic Location Client model. CONFIG_BLE_MESH_GENERIC_PROPERTY_CLI Generic Property Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic Property Client model. CONFIG_BLE_MESH_SENSOR_CLI Sensor Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Sensor Client model. CONFIG_BLE_MESH_TIME_CLI Time Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Time Client model. CONFIG_BLE_MESH_SCENE_CLI Scene Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Scene Client model. CONFIG_BLE_MESH_SCHEDULER_CLI Scheduler Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Scheduler Client model. CONFIG_BLE_MESH_LIGHT_LIGHTNESS_CLI Light Lightness Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Light Lightness Client model. CONFIG_BLE_MESH_LIGHT_CTL_CLI Light CTL Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Light CTL Client model. CONFIG_BLE_MESH_LIGHT_HSL_CLI Light HSL Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Light HSL Client model. CONFIG_BLE_MESH_LIGHT_XYL_CLI Light XYL Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Light XYL Client model. CONFIG_BLE_MESH_LIGHT_LC_CLI Light LC Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Light LC Client model. CONFIG_BLE_MESH_GENERIC_SERVER Generic server models Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Generic server models. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_SENSOR_SERVER Sensor server models Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Sensor server models. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_TIME_SCENE_SERVER Time and Scenes server models Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Time and Scenes server models. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_LIGHTING_SERVER Lighting server models Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for Lighting server models. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_MBT_CLI BLOB Transfer Client model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for BLOB Transfer Client model. - Default value: - - No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_MAX_BLOB_RECEIVERS Maximum number of simultaneous blob receivers Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models > CONFIG_BLE_MESH_MBT_CLI Maximum number of BLOB Transfer Server models that can participating in the BLOB transfer with a BLOB Transfer Client model. - Range: - - from 1 to 255 if CONFIG_BLE_MESH_MBT_CLI && CONFIG_BLE_MESH - Default value: - CONFIG_BLE_MESH_MBT_SRV BLOB Transfer Server model Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models Enable support for BLOB Transfer Server model. - Default value: - - No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_IV_UPDATE_TEST Test the IV Update Procedure Found in: Component config > CONFIG_BLE_MESH This option removes the 96 hour limit of the IV Update Procedure and lets the state to be changed at any time. If IV Update test mode is going to be used, this option should be enabled. - Default value: - - No (disabled) if CONFIG_BLE_MESH BLE Mesh specific test option Contains: CONFIG_BLE_MESH_SELF_TEST Perform BLE Mesh self-tests Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option This option adds extra self-tests which are run every time BLE Mesh networking is initialized. - Default value: - - No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_BQB_TEST Enable BLE Mesh specific internal test Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option This option is used to enable some internal functions for auto-pts test. - Default value: - - No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_TEST_AUTO_ENTER_NETWORK Unprovisioned device enters mesh network automatically Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option With this option enabled, an unprovisioned device can automatically enters mesh network using a specific test function without the pro- visioning procedure. And on the Provisioner side, a test function needs to be invoked to add the node information into the mesh stack. - Default value: - - Yes (enabled) if CONFIG_BLE_MESH_SELF_TEST && CONFIG_BLE_MESH CONFIG_BLE_MESH_TEST_USE_WHITE_LIST Use white list to filter mesh advertising packets Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option With this option enabled, users can use white list to filter mesh advertising packets while scanning. - Default value: - - No (disabled) if CONFIG_BLE_MESH_SELF_TEST && CONFIG_BLE_MESH CONFIG_BLE_MESH_SHELL Enable BLE Mesh shell Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option Activate shell module that provides BLE Mesh commands to the console. - Default value: - - No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_DEBUG Enable BLE Mesh debug logs Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option Enable debug logs for the BLE Mesh functionality. - Default value: - - No (disabled) if CONFIG_BLE_MESH CONFIG_BLE_MESH_DEBUG_NET Network layer debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Network layer debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_TRANS Transport layer debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Transport layer debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_BEACON Beacon debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Beacon-related debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_CRYPTO Crypto debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable cryptographic debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_PROV Provisioning debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Provisioning debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_ACCESS Access layer debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Access layer debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_MODEL Foundation model debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Foundation Models debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_ADV Advertising debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable advertising debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_LOW_POWER Low Power debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Low Power debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_FRIEND Friend debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Friend debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_DEBUG_PROXY Proxy debug Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CONFIG_BLE_MESH_DEBUG Enable Proxy protocol debug logs for the BLE Mesh functionality. CONFIG_BLE_MESH_EXPERIMENTAL Make BLE Mesh experimental features visible Found in: Component config > CONFIG_BLE_MESH Make BLE Mesh Experimental features visible. Experimental features list: - CONFIG_BLE_MESH_NOT_RELAY_REPLAY_MSG - Default value: - - No (disabled) if CONFIG_BLE_MESH Driver Configurations Contains: Legacy ADC Configuration Contains: CONFIG_ADC_DISABLE_DAC Disable DAC when ADC2 is used on GPIO 25 and 26 Found in: Component config > Driver Configurations > Legacy ADC Configuration If this is set, the ADC2 driver will disable the output of the DAC corresponding to the specified channel. This is the default value. For testing, disable this option so that we can measure the output of DAC by internal ADC. - Default value: - - Yes (enabled) CONFIG_ADC_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > Legacy ADC Configuration Wether to suppress the deprecation warnings when using legacy adc driver (driver/adc.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. - Default value: - - No (disabled) Legacy ADC Calibration Configuration Contains: CONFIG_ADC_CAL_EFUSE_TP_ENABLE Use Two Point Values Found in: Component config > Driver Configurations > Legacy ADC Configuration > Legacy ADC Calibration Configuration Some ESP32s have Two Point calibration values burned into eFuse BLOCK3. This option will allow the ADC calibration component to characterize the ADC-Voltage curve using Two Point values if they are available. - Default value: - - Yes (enabled) CONFIG_ADC_CAL_EFUSE_VREF_ENABLE Use eFuse Vref Found in: Component config > Driver Configurations > Legacy ADC Configuration > Legacy ADC Calibration Configuration Some ESP32s have Vref burned into eFuse BLOCK0. This option will allow the ADC calibration component to characterize the ADC-Voltage curve using eFuse Vref if it is available. - Default value: - - Yes (enabled) CONFIG_ADC_CAL_LUT_ENABLE Use Lookup Tables Found in: Component config > Driver Configurations > Legacy ADC Configuration > Legacy ADC Calibration Configuration This option will allow the ADC calibration component to use Lookup Tables to correct for non-linear behavior in 11db attenuation. Other attenuations do not exhibit non-linear behavior hence will not be affected by this option. - Default value: - - Yes (enabled) CONFIG_ADC_CALI_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > Legacy ADC Configuration > Legacy ADC Calibration Configuration Wether to suppress the deprecation warnings when using legacy adc calibration driver (esp_adc_cal.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. - Default value: - - No (disabled) SPI Configuration Contains: CONFIG_SPI_MASTER_IN_IRAM Place transmitting functions of SPI master into IRAM Found in: Component config > Driver Configurations > SPI Configuration Normally only the ISR of SPI master is placed in the IRAM, so that it can work without the flash when interrupt is triggered. For other functions, there's some possibility that the flash cache miss when running inside and out of SPI functions, which may increase the interval of SPI transactions. Enable this to put queue\_trans, get\_trans\_resultand transmitfunctions into the IRAM to avoid possible cache miss. This configuration won't be available if CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH is enabled. During unit test, this is enabled to measure the ideal case of api. CONFIG_SPI_MASTER_ISR_IN_IRAM Place SPI master ISR function into IRAM Found in: Component config > Driver Configurations > SPI Configuration Place the SPI master ISR in to IRAM to avoid possible cache miss. Enabling this configuration is possible only when HEAP_PLACE_FUNCTION_INTO_FLASH is disabled since the spi master uses can allocate transactions buffers into DMA memory section using the heap component API that ipso facto has to be placed in IRAM. Also you can forbid the ISR being disabled during flash writing access, by add ESP_INTR_FLAG_IRAM when initializing the driver. CONFIG_SPI_SLAVE_IN_IRAM Place transmitting functions of SPI slave into IRAM Found in: Component config > Driver Configurations > SPI Configuration Normally only the ISR of SPI slave is placed in the IRAM, so that it can work without the flash when interrupt is triggered. For other functions, there's some possibility that the flash cache miss when running inside and out of SPI functions, which may increase the interval of SPI transactions. Enable this to put queue\_trans, get\_trans\_resultand transmitfunctions into the IRAM to avoid possible cache miss. - Default value: - - No (disabled) CONFIG_SPI_SLAVE_ISR_IN_IRAM Place SPI slave ISR function into IRAM Found in: Component config > Driver Configurations > SPI Configuration Place the SPI slave ISR in to IRAM to avoid possible cache miss. Also you can forbid the ISR being disabled during flash writing access, by add ESP_INTR_FLAG_IRAM when initializing the driver. - Default value: - - Yes (enabled) TWAI Configuration Contains: CONFIG_TWAI_ISR_IN_IRAM Place TWAI ISR function into IRAM Found in: Component config > Driver Configurations > TWAI Configuration Place the TWAI ISR in to IRAM. This will allow the ISR to avoid cache misses, and also be able to run whilst the cache is disabled (such as when writing to SPI Flash). Note that if this option is enabled: - Users should also set the ESP_INTR_FLAG_IRAM in the driver configuration structure when installing the driver (see docs for specifics). - Alert logging (i.e., setting of the TWAI_ALERT_AND_LOG flag) will have no effect. - Default value: - - No (disabled) CONFIG_TWAI_ERRATA_FIX_BUS_OFF_REC Add SW workaround for REC change during bus-off Found in: Component config > Driver Configurations > TWAI Configuration When the bus-off condition is reached, the REC should be reset to 0 and frozen (via LOM) by the driver's ISR. However on the ESP32, there is an edge case where the REC will increase before the driver's ISR can respond in time (e.g., due to the rapid occurrence of bus errors), thus causing the REC to be non-zero after bus-off. A non-zero REC can prevent bus-off recovery as the bus-off recovery condition is that both TEC and REC become 0. Enabling this option will add a workaround in the driver to forcibly reset REC to zero on reaching bus-off. - Default value: - - Yes (enabled) CONFIG_TWAI_ERRATA_FIX_TX_INTR_LOST Add SW workaround for TX interrupt lost errata Found in: Component config > Driver Configurations > TWAI Configuration On the ESP32, when a transmit interrupt occurs, and interrupt register is read on the same APB clock cycle, the transmit interrupt could be lost. Enabling this option will add a workaround that checks the transmit buffer status bit to recover any lost transmit interrupt. - Default value: - - Yes (enabled) CONFIG_TWAI_ERRATA_FIX_RX_FRAME_INVALID Add SW workaround for invalid RX frame errata Found in: Component config > Driver Configurations > TWAI Configuration On the ESP32, when receiving a data or remote frame, if a bus error occurs in the data or CRC field, the data of the next received frame could be invalid. Enabling this option will add a workaround that will reset the peripheral on detection of this errata condition. Note that if a frame is transmitted on the bus whilst the reset is ongoing, the message will not be receive by the peripheral sent on the bus during the reset, the message will be lost. - Default value: - - Yes (enabled) CONFIG_TWAI_ERRATA_FIX_RX_FIFO_CORRUPT Add SW workaround for RX FIFO corruption errata Found in: Component config > Driver Configurations > TWAI Configuration On the ESP32, when the RX FIFO overruns and the RX message counter maxes out at 64 messages, the entire RX FIFO is no longer recoverable. Enabling this option will add a workaround that resets the peripheral on detection of this errata condition. Note that if a frame is being sent on the bus during the reset bus during the reset, the message will be lost. - Default value: - - Yes (enabled) CONFIG_TWAI_ERRATA_FIX_LISTEN_ONLY_DOM Add SW workaround for listen only transmits dominant bit errata Found in: Component config > Driver Configurations > TWAI Configuration When in the listen only mode, the TWAI controller must not influence the TWAI bus (i.e., must not send any dominant bits). However, while in listen only mode on the ESP32/ESP32-S2/ESP32-S3/ESP32-C3, the TWAI controller will still transmit dominant bits when it detects an error (i.e., as part of an active error frame). Enabling this option will add a workaround that forces the TWAI controller into an error passive state on initialization, thus preventing any dominant bits from being sent. - Default value: - - Yes (enabled) Temperature sensor Configuration Contains: CONFIG_TEMP_SENSOR_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > Temperature sensor Configuration Wether to suppress the deprecation warnings when using legacy temperature sensor driver (driver/temp_sensor.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. - Default value: - - No (disabled) if SOC_TEMP_SENSOR_SUPPORTED CONFIG_TEMP_SENSOR_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > Temperature sensor Configuration Wether to enable the debug log message for temperature sensor driver. Note that, this option only controls the temperature sensor driver log, won't affect other drivers. - Default value: - - No (disabled) if SOC_TEMP_SENSOR_SUPPORTED CONFIG_TEMP_SENSOR_ISR_IRAM_SAFE Temperature sensor ISR IRAM-Safe Found in: Component config > Driver Configurations > Temperature sensor Configuration Ensure the Temperature Sensor interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). - Default value: - - No (disabled) if SOC_TEMPERATURE_SENSOR_INTR_SUPPORT && SOC_TEMP_SENSOR_SUPPORTED UART Configuration Contains: CONFIG_UART_ISR_IN_IRAM Place UART ISR function into IRAM Found in: Component config > Driver Configurations > UART Configuration If this option is not selected, UART interrupt will be disabled for a long time and may cause data lost when doing spi flash operation. GPIO Configuration Contains: CONFIG_GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL Support light sleep GPIO pullup/pulldown configuration for ESP32 Found in: Component config > Driver Configurations > GPIO Configuration This option is intended to fix the bug that ESP32 is not able to switch to configured pullup/pulldown mode in sleep. If this option is selected, chip will automatically emulate the behaviour of switching, and about 450B of source codes would be placed into IRAM. CONFIG_GPIO_CTRL_FUNC_IN_IRAM Place GPIO control functions into IRAM Found in: Component config > Driver Configurations > GPIO Configuration Place GPIO control functions (like intr_disable/set_level) into IRAM, so that these functions can be IRAM-safe and able to be called in the other IRAM interrupt context. - Default value: - - No (disabled) Sigma Delta Modulator Configuration Contains: CONFIG_SDM_CTRL_FUNC_IN_IRAM Place SDM control functions into IRAM Found in: Component config > Driver Configurations > Sigma Delta Modulator Configuration Place SDM control functions (like set_duty) into IRAM, so that these functions can be IRAM-safe and able to be called in the other IRAM interrupt context. Enabling this option can improve driver performance as well. - Default value: - - No (disabled) CONFIG_SDM_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > Sigma Delta Modulator Configuration Wether to suppress the deprecation warnings when using legacy sigma delta driver. If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. - Default value: - - No (disabled) CONFIG_SDM_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > Sigma Delta Modulator Configuration Wether to enable the debug log message for SDM driver. Note that, this option only controls the SDM driver log, won't affect other drivers. - Default value: - - No (disabled) Analog Comparator Configuration Contains: CONFIG_ANA_CMPR_ISR_IRAM_SAFE Analog comparator ISR IRAM-Safe Found in: Component config > Driver Configurations > Analog Comparator Configuration Ensure the Analog Comparator interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). - Default value: - - No (disabled) if SOC_ANA_CMPR_SUPPORTED CONFIG_ANA_CMPR_CTRL_FUNC_IN_IRAM Place Analog Comparator control functions into IRAM Found in: Component config > Driver Configurations > Analog Comparator Configuration Place Analog Comparator control functions (like ana_cmpr_set_internal_reference) into IRAM, so that these functions can be IRAM-safe and able to be called in an IRAM interrupt context. Enabling this option can improve driver performance as well. - Default value: - - No (disabled) if SOC_ANA_CMPR_SUPPORTED CONFIG_ANA_CMPR_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > Analog Comparator Configuration Wether to enable the debug log message for Analog Comparator driver. Note that, this option only controls the Analog Comparator driver log, won't affect other drivers. - Default value: - - No (disabled) if SOC_ANA_CMPR_SUPPORTED GPTimer Configuration Contains: CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM Place GPTimer ISR handler into IRAM Found in: Component config > Driver Configurations > GPTimer Configuration Place GPTimer ISR handler into IRAM for better performance and fewer cache misses. - Default value: - - Yes (enabled) CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM Place GPTimer control functions into IRAM Found in: Component config > Driver Configurations > GPTimer Configuration Place GPTimer control functions (like start/stop) into IRAM, so that these functions can be IRAM-safe and able to be called in the other IRAM interrupt context. Enabling this option can improve driver performance as well. - Default value: - - No (disabled) CONFIG_GPTIMER_ISR_IRAM_SAFE GPTimer ISR IRAM-Safe Found in: Component config > Driver Configurations > GPTimer Configuration Ensure the GPTimer interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). - Default value: - - No (disabled) CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > GPTimer Configuration Wether to suppress the deprecation warnings when using legacy timer group driver (driver/timer.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. - Default value: - - No (disabled) CONFIG_GPTIMER_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > GPTimer Configuration Wether to enable the debug log message for GPTimer driver. Note that, this option only controls the GPTimer driver log, won't affect other drivers. - Default value: - - No (disabled) PCNT Configuration Contains: CONFIG_PCNT_CTRL_FUNC_IN_IRAM Place PCNT control functions into IRAM Found in: Component config > Driver Configurations > PCNT Configuration Place PCNT control functions (like start/stop) into IRAM, so that these functions can be IRAM-safe and able to be called in the other IRAM interrupt context. Enabling this option can improve driver performance as well. - Default value: - - No (disabled) CONFIG_PCNT_ISR_IRAM_SAFE PCNT ISR IRAM-Safe Found in: Component config > Driver Configurations > PCNT Configuration Ensure the PCNT interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). - Default value: - - No (disabled) CONFIG_PCNT_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > PCNT Configuration Wether to suppress the deprecation warnings when using legacy PCNT driver (driver/pcnt.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. - Default value: - - No (disabled) CONFIG_PCNT_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > PCNT Configuration Wether to enable the debug log message for PCNT driver. Note that, this option only controls the PCNT driver log, won't affect other drivers. - Default value: - - No (disabled) RMT Configuration Contains: CONFIG_RMT_ISR_IRAM_SAFE RMT ISR IRAM-Safe Found in: Component config > Driver Configurations > RMT Configuration Ensure the RMT interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). - Default value: - - No (disabled) CONFIG_RMT_RECV_FUNC_IN_IRAM Place RMT receive function into IRAM Found in: Component config > Driver Configurations > RMT Configuration Place RMT receive function into IRAM, so that the receive function can be IRAM-safe and able to be called when the flash cache is disabled. Enabling this option can improve driver performance as well. - Default value: - - No (disabled) CONFIG_RMT_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > RMT Configuration Wether to suppress the deprecation warnings when using legacy rmt driver (driver/rmt.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. - Default value: - - No (disabled) CONFIG_RMT_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > RMT Configuration Wether to enable the debug log message for RMT driver. Note that, this option only controls the RMT driver log, won't affect other drivers. - Default value: - - No (disabled) MCPWM Configuration Contains: CONFIG_MCPWM_ISR_IRAM_SAFE Place MCPWM ISR function into IRAM Found in: Component config > Driver Configurations > MCPWM Configuration This will ensure the MCPWM interrupt handle is IRAM-Safe, allow to avoid flash cache misses, and also be able to run whilst the cache is disabled. (e.g. SPI Flash write) - Default value: - - No (disabled) CONFIG_MCPWM_CTRL_FUNC_IN_IRAM Place MCPWM control functions into IRAM Found in: Component config > Driver Configurations > MCPWM Configuration Place MCPWM control functions (like set_compare_value) into IRAM, so that these functions can be IRAM-safe and able to be called in the other IRAM interrupt context. Enabling this option can improve driver performance as well. - Default value: - - No (disabled) CONFIG_MCPWM_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > MCPWM Configuration Wether to suppress the deprecation warnings when using legacy MCPWM driver (driver/mcpwm.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. - Default value: - - No (disabled) CONFIG_MCPWM_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > MCPWM Configuration Wether to enable the debug log message for MCPWM driver. Note that, this option only controls the MCPWM driver log, won't affect other drivers. - Default value: - - No (disabled) I2S Configuration Contains: CONFIG_I2S_ISR_IRAM_SAFE I2S ISR IRAM-Safe Found in: Component config > Driver Configurations > I2S Configuration Ensure the I2S interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). - Default value: - - No (disabled) CONFIG_I2S_SUPPRESS_DEPRECATE_WARN Suppress leagcy driver deprecated warning Found in: Component config > Driver Configurations > I2S Configuration Enable this option will suppress the deprecation warnings of using APIs in legacy I2S driver. - Default value: - - No (disabled) CONFIG_I2S_ENABLE_DEBUG_LOG Enable I2S debug log Found in: Component config > Driver Configurations > I2S Configuration Wether to enable the debug log message for I2S driver. Note that, this option only controls the I2S driver log, will not affect other drivers. - Default value: - - No (disabled) DAC Configuration Contains: CONFIG_DAC_CTRL_FUNC_IN_IRAM Place DAC control functions into IRAM Found in: Component config > Driver Configurations > DAC Configuration Place DAC control functions (e.g. 'dac_oneshot_output_voltage') into IRAM, so that this function can be IRAM-safe and able to be called in the other IRAM interrupt context. Enabling this option can improve driver performance as well. - Default value: - - No (disabled) CONFIG_DAC_ISR_IRAM_SAFE DAC ISR IRAM-Safe Found in: Component config > Driver Configurations > DAC Configuration Ensure the DAC interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). - Default value: - - No (disabled) CONFIG_DAC_SUPPRESS_DEPRECATE_WARN Suppress legacy driver deprecated warning Found in: Component config > Driver Configurations > DAC Configuration Wether to suppress the deprecation warnings when using legacy DAC driver (driver/dac.h). If you want to continue using the legacy driver, and don't want to see related deprecation warnings, you can enable this option. - Default value: - - No (disabled) CONFIG_DAC_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > DAC Configuration Wether to enable the debug log message for DAC driver. Note that, this option only controls the DAC driver log, won't affect other drivers. - Default value: - - No (disabled) CONFIG_DAC_DMA_AUTO_16BIT_ALIGN Align the continuous data to 16 bit automatically Found in: Component config > Driver Configurations > DAC Configuration Whether to left shift the continuous data to align every bytes to 16 bits in the driver. On ESP32, although the DAC resolution is only 8 bits, the hardware requires 16 bits data in continuous mode. By enabling this option, the driver will left shift 8 bits for the input data automatically. Only disable this option when you decide to do this step by yourself. Note that the driver will allocate a new piece of memory to save the converted data. - Default value: - - Yes (enabled) USB Serial/JTAG Configuration Contains: CONFIG_USJ_NO_AUTO_LS_ON_CONNECTION Don't enter the automatic light sleep when USB Serial/JTAG port is connected Found in: Component config > Driver Configurations > USB Serial/JTAG Configuration If enabled, the chip will constantly monitor the connection status of the USB Serial/JTAG port. As long as the USB Serial/JTAG is connected, a ESP_PM_NO_LIGHT_SLEEP power management lock will be acquired to prevent the system from entering light sleep. This option can be useful if serial monitoring is needed via USB Serial/JTAG while power management is enabled, as the USB Serial/JTAG cannot work under light sleep and after waking up from light sleep. Note. This option can only control the automatic Light-Sleep behavior. If esp_light_sleep_start() is called manually from the program, enabling this option will not prevent light sleep entry even if the USB Serial/JTAG is in use. Parallel IO Configuration Contains: CONFIG_PARLIO_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Driver Configurations > Parallel IO Configuration Wether to enable the debug log message for parallel IO driver. Note that, this option only controls the parallel IO driver log, won't affect other drivers. - Default value: - - No (disabled) if SOC_PARLIO_SUPPORTED CONFIG_PARLIO_ISR_IRAM_SAFE Parallel IO ISR IRAM-Safe Found in: Component config > Driver Configurations > Parallel IO Configuration Ensure the Parallel IO interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). - Default value: - - No (disabled) if SOC_PARLIO_SUPPORTED LEDC Configuration Contains: CONFIG_LEDC_CTRL_FUNC_IN_IRAM Place LEDC control functions into IRAM Found in: Component config > Driver Configurations > LEDC Configuration Place LEDC control functions (ledc_update_duty and ledc_stop) into IRAM, so that these functions can be IRAM-safe and able to be called in an IRAM context. Enabling this option can improve driver performance as well. - Default value: - - No (disabled) I2C Configuration Contains: CONFIG_I2C_ISR_IRAM_SAFE I2C ISR IRAM-Safe Found in: Component config > Driver Configurations > I2C Configuration Ensure the I2C interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). note: This cannot be used in the I2C legacy driver. - Default value: - - No (disabled) CONFIG_I2C_ENABLE_DEBUG_LOG Enable I2C debug log Found in: Component config > Driver Configurations > I2C Configuration Wether to enable the debug log message for I2C driver. Note that this option only controls the I2C driver log, will not affect other drivers. note: This cannot be used in the I2C legacy driver. - Default value: - - No (disabled) eFuse Bit Manager Contains: CONFIG_EFUSE_CUSTOM_TABLE Use custom eFuse table Found in: Component config > eFuse Bit Manager Allows to generate a structure for eFuse from the CSV file. - Default value: - - No (disabled) CONFIG_EFUSE_CUSTOM_TABLE_FILENAME Custom eFuse CSV file Found in: Component config > eFuse Bit Manager > CONFIG_EFUSE_CUSTOM_TABLE Name of the custom eFuse CSV filename. This path is evaluated relative to the project root directory. - Default value: - - "main/esp_efuse_custom_table.csv" if CONFIG_EFUSE_CUSTOM_TABLE CONFIG_EFUSE_VIRTUAL Simulate eFuse operations in RAM Found in: Component config > eFuse Bit Manager If "n" - No virtual mode. All eFuse operations are real and use eFuse registers. If "y" - The virtual mode is enabled and all eFuse operations (read and write) are redirected to RAM instead of eFuse registers, all permanent changes (via eFuse) are disabled. Log output will state changes that would be applied, but they will not be. If it is "y", then SECURE_FLASH_ENCRYPTION_MODE_RELEASE cannot be used. Because the EFUSE VIRT mode is for testing only. During startup, the eFuses are copied into RAM. This mode is useful for fast tests. - Default value: - - No (disabled) CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH Keep eFuses in flash Found in: Component config > eFuse Bit Manager > CONFIG_EFUSE_VIRTUAL In addition to the "Simulate eFuse operations in RAM" option, this option just adds a feature to keep eFuses after reboots in flash memory. To use this mode the partition_table should have the efuse partition. partition.csv: "efuse_em, data, efuse, , 0x2000," During startup, the eFuses are copied from flash or, in case if flash is empty, from real eFuse to RAM and then update flash. This mode is useful when need to keep changes after reboot (testing secure_boot and flash_encryption). CONFIG_EFUSE_VIRTUAL_LOG_ALL_WRITES Log all virtual writes Found in: Component config > eFuse Bit Manager > CONFIG_EFUSE_VIRTUAL If enabled, log efuse burns. This shows changes that would be made. CONFIG_EFUSE_CODE_SCHEME_SELECTOR Coding Scheme Compatibility Found in: Component config > eFuse Bit Manager Selector eFuse code scheme. Available options: - None Only (CONFIG_EFUSE_CODE_SCHEME_COMPAT_NONE) - 3/4 and None (CONFIG_EFUSE_CODE_SCHEME_COMPAT_3_4) - Repeat, 3/4 and None (common table does not support it) (CONFIG_EFUSE_CODE_SCHEME_COMPAT_REPEAT) ESP-TLS Contains: CONFIG_ESP_TLS_LIBRARY_CHOOSE Choose SSL/TLS library for ESP-TLS (See help for more Info) Found in: Component config > ESP-TLS The ESP-TLS APIs support multiple backend TLS libraries. Currently mbedTLS and WolfSSL are supported. Different TLS libraries may support different features and have different resource usage. Consult the ESP-TLS documentation in ESP-IDF Programming guide for more details. Available options: - mbedTLS (CONFIG_ESP_TLS_USING_MBEDTLS) - wolfSSL (License info in wolfSSL directory README) (CONFIG_ESP_TLS_USING_WOLFSSL) CONFIG_ESP_TLS_USE_SECURE_ELEMENT Use Secure Element (ATECC608A) with ESP-TLS Found in: Component config > ESP-TLS Enable use of Secure Element for ESP-TLS, this enables internal support for ATECC608A peripheral on ESPWROOM32SE, which can be used for TLS connection. CONFIG_ESP_TLS_USE_DS_PERIPHERAL Use Digital Signature (DS) Peripheral with ESP-TLS Found in: Component config > ESP-TLS Enable use of the Digital Signature Peripheral for ESP-TLS.The DS peripheral can only be used when it is appropriately configured for TLS. Consult the ESP-TLS documentation in ESP-IDF Programming Guide for more details. - Default value: - - Yes (enabled) if CONFIG_ESP_TLS_USING_MBEDTLS && SOC_DIG_SIGN_SUPPORTED CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS Enable client session tickets Found in: Component config > ESP-TLS Enable session ticket support as specified in RFC5077. CONFIG_ESP_TLS_SERVER Enable ESP-TLS Server Found in: Component config > ESP-TLS Enable support for creating server side SSL/TLS session, available for mbedTLS as well as wolfSSL TLS library. CONFIG_ESP_TLS_SERVER_SESSION_TICKETS Enable server session tickets Found in: Component config > ESP-TLS > CONFIG_ESP_TLS_SERVER Enable session ticket support as specified in RFC5077 CONFIG_ESP_TLS_SERVER_SESSION_TICKET_TIMEOUT Server session ticket timeout in seconds Found in: Component config > ESP-TLS > CONFIG_ESP_TLS_SERVER > CONFIG_ESP_TLS_SERVER_SESSION_TICKETS Sets the session ticket timeout used in the tls server. - Default value: - CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK Certificate selection hook Found in: Component config > ESP-TLS > CONFIG_ESP_TLS_SERVER Ability to configure and use a certificate selection callback during server handshake, to select a certificate to present to the client based on the TLS extensions supplied in the client hello (alpn, sni, etc). CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL ESP-TLS Server: Set minimum Certificate Verification mode to Optional Found in: Component config > ESP-TLS > CONFIG_ESP_TLS_SERVER When this option is enabled, the peer (here, the client) certificate is checked by the server, however the handshake continues even if verification failed. By default, the peer certificate is not checked and ignored by the server. mbedtls_ssl_get_verify_result() can be called after the handshake is complete to retrieve status of verification. CONFIG_ESP_TLS_PSK_VERIFICATION Enable PSK verification Found in: Component config > ESP-TLS Enable support for pre shared key ciphers, supported for both mbedTLS as well as wolfSSL TLS library. CONFIG_ESP_TLS_INSECURE Allow potentially insecure options Found in: Component config > ESP-TLS You can enable some potentially insecure options. These options should only be used for testing pusposes. Only enable these options if you are very sure. CONFIG_ESP_TLS_SKIP_SERVER_CERT_VERIFY Skip server certificate verification by default (WARNING: ONLY FOR TESTING PURPOSE, READ HELP) Found in: Component config > ESP-TLS > CONFIG_ESP_TLS_INSECURE After enabling this option the esp-tls client will skip the server certificate verification by default. Note that this option will only modify the default behaviour of esp-tls client regarding server cert verification. The default behaviour should only be applicable when no other option regarding the server cert verification is opted in the esp-tls config (e.g. crt_bundle_attach, use_global_ca_store etc.). WARNING : Enabling this option comes with a potential risk of establishing a TLS connection with a server which has a fake identity, provided that the server certificate is not provided either through API or other mechanism like ca_store etc. CONFIG_ESP_WOLFSSL_SMALL_CERT_VERIFY Enable SMALL_CERT_VERIFY Found in: Component config > ESP-TLS Enables server verification with Intermediate CA cert, does not authenticate full chain of trust upto the root CA cert (After Enabling this option client only needs to have Intermediate CA certificate of the server to authenticate server, root CA cert is not necessary). - Default value: - - Yes (enabled) if CONFIG_ESP_TLS_USING_WOLFSSL CONFIG_ESP_DEBUG_WOLFSSL Enable debug logs for wolfSSL Found in: Component config > ESP-TLS Enable detailed debug prints for wolfSSL SSL library. ADC and ADC Calibration Contains: CONFIG_ADC_ONESHOT_CTRL_FUNC_IN_IRAM Place ISR version ADC oneshot mode read function into IRAM Found in: Component config > ADC and ADC Calibration Place ISR version ADC oneshot mode read function into IRAM. - Default value: - - No (disabled) CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE ADC continuous mode driver ISR IRAM-Safe Found in: Component config > ADC and ADC Calibration Ensure the ADC continuous mode ISR is IRAM-Safe. When enabled, the ISR handler will be available when the cache is disabled. - Default value: - - No (disabled) ADC Calibration Configurations Contains: CONFIG_ADC_CALI_EFUSE_TP_ENABLE Use Two Point Values Found in: Component config > ADC and ADC Calibration > ADC Calibration Configurations Some ESP32s have Two Point calibration values burned into eFuse BLOCK3. This option will allow the ADC calibration component to characterize the ADC-Voltage curve using Two Point values if they are available. - Default value: - - Yes (enabled) CONFIG_ADC_CALI_EFUSE_VREF_ENABLE Use eFuse Vref Found in: Component config > ADC and ADC Calibration > ADC Calibration Configurations Some ESP32s have Vref burned into eFuse BLOCK0. This option will allow the ADC calibration component to characterize the ADC-Voltage curve using eFuse Vref if it is available. - Default value: - - Yes (enabled) CONFIG_ADC_CALI_LUT_ENABLE Use Lookup Tables Found in: Component config > ADC and ADC Calibration > ADC Calibration Configurations This option will allow the ADC calibration component to use Lookup Tables to correct for non-linear behavior in 11db attenuation. Other attenuations do not exhibit non-linear behavior hence will not be affected by this option. - Default value: - - Yes (enabled) CONFIG_ADC_DISABLE_DAC_OUTPUT Disable DAC when ADC2 is in use Found in: Component config > ADC and ADC Calibration By default, this is set. The ADC oneshot driver will disable the output of the corresponding DAC channels: ESP32: IO25 and IO26 ESP32S2: IO17 and IO18 Disable this option so as to measure the output of DAC by internal ADC, for test usage. - Default value: - - Yes (enabled) Wireless Coexistence Contains: CONFIG_ESP_COEX_SW_COEXIST_ENABLE Software controls WiFi/Bluetooth coexistence Found in: Component config > Wireless Coexistence If enabled, WiFi & Bluetooth coexistence is controlled by software rather than hardware. Recommended for heavy traffic scenarios. Both coexistence configuration options are automatically managed, no user intervention is required. If only Bluetooth is used, it is recommended to disable this option to reduce binary file size. - Default value: - - Yes (enabled) if CONFIG_BT_ENABLED || CONFIG_IEEE802154_ENABLED || (CONFIG_IEEE802154_ENABLED && CONFIG_BT_ENABLED) Ethernet Contains: CONFIG_ETH_USE_ESP32_EMAC Support ESP32 internal EMAC controller Found in: Component config > Ethernet ESP32 integrates a 10/100M Ethernet MAC controller. - Default value: - - Yes (enabled) Contains: CONFIG_ETH_PHY_INTERFACE PHY interface Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC Select the communication interface between MAC and PHY chip. Available options: - Reduced Media Independent Interface (RMII) (CONFIG_ETH_PHY_INTERFACE_RMII) CONFIG_ETH_RMII_CLK_MODE RMII clock mode Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC Select external or internal RMII clock. Available options: - Input RMII clock from external (CONFIG_ETH_RMII_CLK_INPUT) MAC will get RMII clock from outside. Note that ESP32 only supports GPIO0 to input the RMII clock. - Output RMII clock from internal (CONFIG_ETH_RMII_CLK_OUTPUT) ESP32 can generate RMII clock by internal APLL. This clock can be routed to the external PHY device. ESP32 supports to route the RMII clock to GPIO0/16/17. CONFIG_ETH_RMII_CLK_OUTPUT_GPIO0 Output RMII clock from GPIO0 (Experimental!) Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC GPIO0 can be set to output a pre-divided PLL clock (test only!). Enabling this option will configure GPIO0 to output a 50MHz clock. In fact this clock doesn't have directly relationship with EMAC peripheral. Sometimes this clock won't work well with your PHY chip. You might need to add some extra devices after GPIO0 (e.g. inverter). Note that outputting RMII clock on GPIO0 is an experimental practice. If you want the Ethernet to work with WiFi, don't select GPIO0 output mode for stability. - Default value: - - No (disabled) if CONFIG_ETH_RMII_CLK_OUTPUT && CONFIG_ETH_USE_ESP32_EMAC CONFIG_ETH_RMII_CLK_OUT_GPIO RMII clock GPIO number Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC Set the GPIO number to output RMII Clock. CONFIG_ETH_DMA_BUFFER_SIZE Ethernet DMA buffer size (Byte) Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC Set the size of each buffer used by Ethernet MAC DMA. - Range: - - from 256 to 1600 - Default value: - - 512 CONFIG_ETH_DMA_RX_BUFFER_NUM Amount of Ethernet DMA Rx buffers Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC Number of DMA receive buffers. Each buffer's size is ETH_DMA_BUFFER_SIZE. Larger number of buffers could increase throughput somehow. - Range: - - from 3 to 30 - Default value: - - 10 CONFIG_ETH_DMA_TX_BUFFER_NUM Amount of Ethernet DMA Tx buffers Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC Number of DMA transmit buffers. Each buffer's size is ETH_DMA_BUFFER_SIZE. Larger number of buffers could increase throughput somehow. - Range: - - from 3 to 30 - Default value: - - 10 CONFIG_ETH_SOFT_FLOW_CONTROL Enable software flow control Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC Ethernet MAC engine on ESP32 doesn't feature a flow control logic. The MAC driver can perform a software flow control if you enable this option. Note that, if the RX buffer number is small, enabling software flow control will cause obvious performance loss. - Default value: - - No (disabled) if CONFIG_ETH_DMA_RX_BUFFER_NUM > 15 && CONFIG_ETH_USE_ESP32_EMAC CONFIG_ETH_IRAM_OPTIMIZATION Enable IRAM optimization Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC If enabled, functions related to RX/TX are placed into IRAM. It can improve Ethernet throughput. If disabled, all functions are placed into FLASH. - Default value: - - No (disabled) CONFIG_ETH_USE_SPI_ETHERNET Support SPI to Ethernet Module Found in: Component config > Ethernet ESP-IDF can also support some SPI-Ethernet modules. - Default value: - - Yes (enabled) Contains: CONFIG_ETH_SPI_ETHERNET_DM9051 Use DM9051 Found in: Component config > Ethernet > CONFIG_ETH_USE_SPI_ETHERNET DM9051 is a fast Ethernet controller with an SPI interface. It's also integrated with a 10/100M PHY and MAC. Select this to enable DM9051 driver. CONFIG_ETH_SPI_ETHERNET_W5500 Use W5500 (MAC RAW) Found in: Component config > Ethernet > CONFIG_ETH_USE_SPI_ETHERNET W5500 is a HW TCP/IP embedded Ethernet controller. TCP/IP stack, 10/100 Ethernet MAC and PHY are embedded in a single chip. However the driver in ESP-IDF only enables the RAW MAC mode, making it compatible with the software TCP/IP stack. Say yes to enable W5500 driver. CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL Use KSZ8851SNL Found in: Component config > Ethernet > CONFIG_ETH_USE_SPI_ETHERNET The KSZ8851SNL is a single-chip Fast Ethernet controller consisting of a 10/100 physical layer transceiver (PHY), a MAC, and a Serial Peripheral Interface (SPI). Select this to enable KSZ8851SNL driver. CONFIG_ETH_USE_OPENETH Support OpenCores Ethernet MAC (for use with QEMU) Found in: Component config > Ethernet OpenCores Ethernet MAC driver can be used when an ESP-IDF application is executed in QEMU. This driver is not supported when running on a real chip. - Default value: - - No (disabled) Contains: CONFIG_ETH_OPENETH_DMA_RX_BUFFER_NUM Number of Ethernet DMA Rx buffers Found in: Component config > Ethernet > CONFIG_ETH_USE_OPENETH Number of DMA receive buffers, each buffer is 1600 bytes. - Range: - - from 1 to 64 if CONFIG_ETH_USE_OPENETH - Default value: - CONFIG_ETH_OPENETH_DMA_TX_BUFFER_NUM Number of Ethernet DMA Tx buffers Found in: Component config > Ethernet > CONFIG_ETH_USE_OPENETH Number of DMA transmit buffers, each buffer is 1600 bytes. - Range: - - from 1 to 64 if CONFIG_ETH_USE_OPENETH - Default value: - CONFIG_ETH_TRANSMIT_MUTEX Enable Transmit Mutex Found in: Component config > Ethernet Prevents multiple accesses when Ethernet interface is used as shared resource and multiple functionalities might try to access it at a time. - Default value: - - No (disabled) Event Loop Library Contains: CONFIG_ESP_EVENT_LOOP_PROFILING Enable event loop profiling Found in: Component config > Event Loop Library Enables collections of statistics in the event loop library such as the number of events posted to/recieved by an event loop, number of callbacks involved, number of events dropped to to a full event loop queue, run time of event handlers, and number of times/run time of each event handler. - Default value: - - No (disabled) CONFIG_ESP_EVENT_POST_FROM_ISR Support posting events from ISRs Found in: Component config > Event Loop Library Enable posting events from interrupt handlers. - Default value: - - Yes (enabled) CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR Support posting events from ISRs placed in IRAM Found in: Component config > Event Loop Library > CONFIG_ESP_EVENT_POST_FROM_ISR Enable posting events from interrupt handlers placed in IRAM. Enabling this option places API functions esp_event_post and esp_event_post_to in IRAM. - Default value: - - Yes (enabled) GDB Stub Contains: CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME GDBStub at runtime Found in: Component config > GDB Stub Enable builtin GDBStub. This allows to debug the target device using serial port: - Run 'idf.py monitor'. - Wait for the device to initialize. - Press Ctrl+C to interrupt the execution and enter GDB attached to your device for debugging. NOTE: all UART input will be handled by GDBStub. CONFIG_ESP_GDBSTUB_SUPPORT_TASKS Enable listing FreeRTOS tasks through GDB Stub Found in: Component config > GDB Stub If enabled, GDBStub can supply the list of FreeRTOS tasks to GDB. Thread list can be queried from GDB using 'info threads' command. Note that if GDB task lists were corrupted, this feature may not work. If GDBStub fails, try disabling this feature. CONFIG_ESP_GDBSTUB_MAX_TASKS Maximum number of tasks supported by GDB Stub Found in: Component config > GDB Stub > CONFIG_ESP_GDBSTUB_SUPPORT_TASKS Set the number of tasks which GDB Stub will support. - Default value: - ESP HTTP client Contains: CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS Enable https Found in: Component config > ESP HTTP client This option will enable https protocol by linking esp-tls library and initializing SSL transport - Default value: - - Yes (enabled) CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH Enable HTTP Basic Authentication Found in: Component config > ESP HTTP client This option will enable HTTP Basic Authentication. It is disabled by default as Basic auth uses unencrypted encoding, so it introduces a vulnerability when not using TLS - Default value: - - No (disabled) CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH Enable HTTP Digest Authentication Found in: Component config > ESP HTTP client This option will enable HTTP Digest Authentication. It is enabled by default, but use of this configuration is not recommended as the password can be derived from the exchange, so it introduces a vulnerability when not using TLS - Default value: - - No (disabled) HTTP Server Contains: CONFIG_HTTPD_MAX_REQ_HDR_LEN Max HTTP Request Header Length Found in: Component config > HTTP Server This sets the maximum supported size of headers section in HTTP request packet to be processed by the server - Default value: - - 512 CONFIG_HTTPD_MAX_URI_LEN Max HTTP URI Length Found in: Component config > HTTP Server This sets the maximum supported size of HTTP request URI to be processed by the server - Default value: - - 512 CONFIG_HTTPD_ERR_RESP_NO_DELAY Use TCP_NODELAY socket option when sending HTTP error responses Found in: Component config > HTTP Server Using TCP_NODEALY socket option ensures that HTTP error response reaches the client before the underlying socket is closed. Please note that turning this off may cause multiple test failures - Default value: - - Yes (enabled) CONFIG_HTTPD_PURGE_BUF_LEN Length of temporary buffer for purging data Found in: Component config > HTTP Server This sets the size of the temporary buffer used to receive and discard any remaining data that is received from the HTTP client in the request, but not processed as part of the server HTTP request handler. If the remaining data is larger than the available buffer size, the buffer will be filled in multiple iterations. The buffer should be small enough to fit on the stack, but large enough to avoid excessive iterations. - Default value: - - 32 CONFIG_HTTPD_LOG_PURGE_DATA Log purged content data at Debug level Found in: Component config > HTTP Server Enabling this will log discarded binary HTTP request data at Debug level. For large content data this may not be desirable as it will clutter the log. - Default value: - - No (disabled) CONFIG_HTTPD_WS_SUPPORT WebSocket server support Found in: Component config > HTTP Server This sets the WebSocket server support. - Default value: - - No (disabled) CONFIG_HTTPD_QUEUE_WORK_BLOCKING httpd_queue_work as blocking API Found in: Component config > HTTP Server This makes httpd_queue_work() API to wait until a message space is available on UDP control socket. It internally uses a counting semaphore with count set to LWIP_UDP_RECVMBOX_SIZE to achieve this. This config will slightly change API behavior to block until message gets delivered on control socket. ESP HTTPS OTA Contains: CONFIG_ESP_HTTPS_OTA_DECRYPT_CB Provide decryption callback Found in: Component config > ESP HTTPS OTA Exposes an additional callback whereby firmware data could be decrypted before being processed by OTA update component. This can help to integrate external encryption related format and removal of such encapsulation layer from firmware image. - Default value: - - No (disabled) CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP Allow HTTP for OTA (WARNING: ONLY FOR TESTING PURPOSE, READ HELP) Found in: Component config > ESP HTTPS OTA It is highly recommended to keep HTTPS (along with server certificate validation) enabled. Enabling this option comes with potential risk of: - Non-encrypted communication channel with server - Accepting firmware upgrade image from server with fake identity - Default value: - - No (disabled) ESP HTTPS server Contains: CONFIG_ESP_HTTPS_SERVER_ENABLE Enable ESP_HTTPS_SERVER component Found in: Component config > ESP HTTPS server Enable ESP HTTPS server component Hardware Settings Contains: Chip revision Contains: CONFIG_ESP32_REV_MIN Minimum Supported ESP32 Revision Found in: Component config > Hardware Settings > Chip revision Required minimum chip revision. ESP-IDF will check for it and reject to boot if the chip revision fails the check. This ensures the chip used will have some modifications (features, or bugfixes). The complied binary will only support chips above this revision, this will also help to reduce binary size. Available options: - Rev v0.0 (ECO0) (CONFIG_ESP32_REV_MIN_0) - Rev v1.0 (ECO1) (CONFIG_ESP32_REV_MIN_1) - Rev v1.1 (ECO1.1) (CONFIG_ESP32_REV_MIN_1_1) - Rev v2.0 (ECO2) (CONFIG_ESP32_REV_MIN_2) - Rev v3.0 (ECO3) (CONFIG_ESP32_REV_MIN_3) - Rev v3.1 (ECO4) (CONFIG_ESP32_REV_MIN_3_1) CONFIG_ESP_REV_NEW_CHIP_TEST Internal test mode Found in: Component config > Hardware Settings > Chip revision For internal chip testing, a small number of new versions chips didn't update the version field in eFuse, you can enable this option to force the software recognize the chip version based on the rev selected in menuconfig. - Default value: - - No (disabled) MAC Config Contains: CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES Number of universally administered (by IEEE) MAC address Found in: Component config > Hardware Settings > MAC Config Configure the number of universally administered (by IEEE) MAC addresses. During initialization, MAC addresses for each network interface are generated or derived from a single base MAC address. If the number of universal MAC addresses is four, all four interfaces (WiFi station, WiFi softap, Bluetooth and Ethernet) receive a universally administered MAC address. These are generated sequentially by adding 0, 1, 2 and 3 (respectively) to the final octet of the base MAC address. If the number of universal MAC addresses is two, only two interfaces (WiFi station and Bluetooth) receive a universally administered MAC address. These are generated sequentially by adding 0 and 1 (respectively) to the base MAC address. The remaining two interfaces (WiFi softap and Ethernet) receive local MAC addresses. These are derived from the universal WiFi station and Bluetooth MAC addresses, respectively. When using the default (Espressif-assigned) base MAC address, either setting can be used. When using a custom universal MAC address range, the correct setting will depend on the allocation of MAC addresses in this range (either 2 or 4 per device.) Available options: - Two (CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES_TWO) - Four (CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES_FOUR) CONFIG_ESP_MAC_IGNORE_MAC_CRC_ERROR Ignore MAC CRC error (not recommended) Found in: Component config > Hardware Settings > MAC Config If you have an invalid MAC CRC (ESP_ERR_INVALID_CRC) problem and you still want to use this chip, you can enable this option to bypass such an error. This applies to both MAC_FACTORY and CUSTOM_MAC efuses. - Default value: - - No (disabled) CONFIG_ESP_MAC_USE_CUSTOM_MAC_AS_BASE_MAC Enable using custom mac as base mac Found in: Component config > Hardware Settings > MAC Config When this configuration is enabled, the user can invoke esp_read_mac to obtain the desired type of MAC using a custom MAC as the base MAC. - Default value: - - No (disabled) Sleep Config Contains: CONFIG_ESP_SLEEP_POWER_DOWN_FLASH Power down flash in light sleep when there is no SPIRAM Found in: Component config > Hardware Settings > Sleep Config If enabled, chip will try to power down flash as part of esp_light_sleep_start(), which costs more time when chip wakes up. Can only be enabled if there is no SPIRAM configured. This option will power down flash under a strict but relatively safe condition. Also, it is possible to power down flash under a relaxed condition by using esp_sleep_pd_config() to set ESP_PD_DOMAIN_VDDSDIO to ESP_PD_OPTION_OFF. It should be noted that there is a risk in powering down flash, you can refer ESP-IDF Programming Guide/API Reference/System API/Sleep Modes/Power-down of Flash for more details. CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND Pull-up Flash CS pin in light sleep Found in: Component config > Hardware Settings > Sleep Config All IOs will be set to isolate(floating) state by default during sleep. Since the power supply of SPI Flash is not lost during lightsleep, if its CS pin is recognized as low level(selected state) in the floating state, there will be a large current leakage, and the data in Flash may be corrupted by random signals on other SPI pins. Select this option will set the CS pin of Flash to PULL-UP state during sleep, but this will increase the sleep current about 10 uA. If you are developing with esp32xx modules, you must select this option, but if you are developing with chips, you can also pull up the CS pin of SPI Flash in the external circuit to save power consumption caused by internal pull-up during sleep. (!!! Don't deselect this option if you don't have external SPI Flash CS pin pullups.) CONFIG_ESP_SLEEP_PSRAM_LEAKAGE_WORKAROUND Pull-up PSRAM CS pin in light sleep Found in: Component config > Hardware Settings > Sleep Config All IOs will be set to isolate(floating) state by default during sleep. Since the power supply of PSRAM is not lost during lightsleep, if its CS pin is recognized as low level(selected state) in the floating state, there will be a large current leakage, and the data in PSRAM may be corrupted by random signals on other SPI pins. Select this option will set the CS pin of PSRAM to PULL-UP state during sleep, but this will increase the sleep current about 10 uA. If you are developing with esp32xx modules, you must select this option, but if you are developing with chips, you can also pull up the CS pin of PSRAM in the external circuit to save power consumption caused by internal pull-up during sleep. (!!! Don't deselect this option if you don't have external PSRAM CS pin pullups.) - Default value: - - Yes (enabled) if CONFIG_SPIRAM CONFIG_ESP_SLEEP_MSPI_NEED_ALL_IO_PU Pull-up all SPI pins in light sleep Found in: Component config > Hardware Settings > Sleep Config To reduce leakage current, some types of SPI Flash/RAM only need to pull up the CS pin during light sleep. But there are also some kinds of SPI Flash/RAM that need to pull up all pins. It depends on the SPI Flash/RAM chip used. CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND light sleep GPIO reset workaround Found in: Component config > Hardware Settings > Sleep Config esp32c2, esp32c3, esp32s3, esp32c6 and esp32h2 will reset at wake-up if GPIO is received a small electrostatic pulse during light sleep, with specific condition - GPIO needs to be configured as input-mode only - The pin receives a small electrostatic pulse, and reset occurs when the pulse voltage is higher than 6 V For GPIO set to input mode only, it is not a good practice to leave it open/floating, The hardware design needs to controlled it with determined supply or ground voltage is necessary. This option provides a software workaround for this issue. Configure to isolate all GPIO pins in sleep state. CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY Extra delay (in us) after flash powerdown sleep wakeup to wait flash ready Found in: Component config > Hardware Settings > Sleep Config When the chip exits sleep, the CPU and the flash chip are powered on at the same time. CPU will run rom code (deepsleep) or ram code (lightsleep) first, and then load or execute code from flash. Some flash chips need sufficient time to pass between power on and first read operation. By default, without any extra delay, this time is approximately 900us, although some flash chip types need more than that. (!!! Please adjust this value according to the Data Sheet of SPI Flash used in your project.) In Flash Data Sheet, the parameters that define the Flash ready timing after power-up (minimum time from Vcc(min) to CS activeare) usually named tVSL in ELECTRICAL CHARACTERISTICS chapter, and the configuration value here should be: ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY = tVSL - 900 For esp32 and esp32s3, the default extra delay is set to 2000us. When optimizing startup time for applications which require it, this value may be reduced. If you are seeing "flash read err, 1000" message printed to the console after deep sleep reset on esp32, or triggered RTC_WDT/LP_WDT after lightsleep wakeup, try increasing this value. (For esp32, the delay will be executed in both deep sleep and light sleep wake up flow. For chips after esp32, the delay will be executed only in light sleep flow, the delay controlled by the EFUSE_FLASH_TPUW in ROM will be executed in deepsleep wake up flow.) - Range: - - from 0 to 5000 - Default value: - - 2000 - 0 CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION Check the cache safety of the sleep wakeup code in sleep process Found in: Component config > Hardware Settings > Sleep Config Enabling it will check the cache safety of the code before the flash power is ready after light sleep wakeup, and check PM_SLP_IRAM_OPT related code cache safety. This option is only for code quality inspection. Enabling it will increase the time overhead of entering and exiting sleep. It is not recommended to enable it in the release version. - Default value: - - No (disabled) CONFIG_ESP_SLEEP_DEBUG esp sleep debug Found in: Component config > Hardware Settings > Sleep Config Enable esp sleep debug. - Default value: - - No (disabled) CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS Allow to enable internal pull-up/downs for the Deep-Sleep wakeup IOs Found in: Component config > Hardware Settings > Sleep Config When using rtc gpio wakeup source during deepsleep without external pull-up/downs, you may want to make use of the internal ones. - Default value: - - Yes (enabled) CONFIG_ESP_SLEEP_EVENT_CALLBACKS Enable registration of sleep event callbacks Found in: Component config > Hardware Settings > Sleep Config If enabled, it allows user to register sleep event callbacks. It is primarily designed for internal developers and customers can use PM_LIGHT_SLEEP_CALLBACKS as an alternative. NOTE: These callbacks are executed from the IDLE task context hence you cannot have any blocking calls in your callbacks. NOTE: Enabling these callbacks may change sleep duration calculations based on time spent in callback and hence it is highly recommended to keep them as short as possible. - Default value: - - No (disabled) if CONFIG_FREERTOS_USE_TICKLESS_IDLE ESP_SLEEP_WORKAROUND RTC Clock Config Contains: CONFIG_RTC_CLK_SRC RTC clock source Found in: Component config > Hardware Settings > RTC Clock Config Choose which clock is used as RTC clock source. - - "Internal 150kHz oscillator" option provides lowest deep sleep current - consumption, and does not require extra external components. However frequency stability with respect to temperature is poor, so time may drift in deep/light sleep modes. - - "External 32kHz crystal" provides better frequency stability, at the - expense of slightly higher (1uA) deep sleep current consumption. - - "External 32kHz oscillator" allows using 32kHz clock generated by an - external circuit. In this case, external clock signal must be connected to 32K_XN pin. Amplitude should be <1.2V in case of sine wave signal, and <1V in case of square wave signal. Common mode voltage should be 0.1 < Vcm < 0.5Vamp, where Vamp is the signal amplitude. Additionally, 1nF capacitor must be connected between 32K_XP pin and ground. 32K_XP pin can not be used as a GPIO in this case. - - "Internal 8.5MHz oscillator divided by 256" option results in higher - deep sleep current (by 5uA) but has better frequency stability than the internal 150kHz oscillator. It does not require external components. Available options: - Internal 150 kHz RC oscillator (CONFIG_RTC_CLK_SRC_INT_RC) - External 32kHz crystal (CONFIG_RTC_CLK_SRC_EXT_CRYS) - External 32kHz oscillator at 32K_XN pin (CONFIG_RTC_CLK_SRC_EXT_OSC) - Internal 8.5MHz oscillator, divided by 256 (~33kHz) (CONFIG_RTC_CLK_SRC_INT_8MD256) CONFIG_RTC_EXT_CRYST_ADDIT_CURRENT_METHOD Additional current for external 32kHz crystal Found in: Component config > Hardware Settings > RTC Clock Config With some 32kHz crystal configurations, the X32N and X32P pins may not have enough drive strength to keep the crystal oscillating. Choose the method to provide additional current from touchpad 9 to the external 32kHz crystal. Note that the deep sleep current is slightly high (4-5uA) and the touchpad and the wakeup sources of both touchpad and ULP are not available in method 1 and method 2. This problem is fixed in ESP32 ECO 3, so this workaround is not needed. Setting the project configuration to minimum revision ECO3 will disable this option, , allow all wakeup sources, and save some code size. - "None" option will not provide additional current to external crystal - - "Method 1" option can't ensure 100% to solve the external 32k crystal start failed - issue, but the touchpad can work in this method. - - "Method 2" option can solve the external 32k issue, but the touchpad can't work - in this method. Available options: - None (CONFIG_RTC_EXT_CRYST_ADDIT_CURRENT_NONE) - Method 1 (CONFIG_RTC_EXT_CRYST_ADDIT_CURRENT) - Method 2 (CONFIG_RTC_EXT_CRYST_ADDIT_CURRENT_V2) CONFIG_RTC_CLK_CAL_CYCLES Number of cycles for RTC_SLOW_CLK calibration Found in: Component config > Hardware Settings > RTC Clock Config When the startup code initializes RTC_SLOW_CLK, it can perform calibration by comparing the RTC_SLOW_CLK frequency with main XTAL frequency. This option sets the number of RTC_SLOW_CLK cycles measured by the calibration routine. Higher numbers increase calibration precision, which may be important for applications which spend a lot of time in deep sleep. Lower numbers reduce startup time. When this option is set to 0, clock calibration will not be performed at startup, and approximate clock frequencies will be assumed: - 150000 Hz if internal RC oscillator is used as clock source. For this use value 1024. - - 32768 Hz if the 32k crystal oscillator is used. For this use value 3000 or more. - In case more value will help improve the definition of the launch of the crystal. If the crystal could not start, it will be switched to internal RC. - Range: - - from 0 to 27000 if CONFIG_RTC_CLK_SRC_EXT_CRYS || CONFIG_RTC_CLK_SRC_EXT_OSC || CONFIG_RTC_CLK_SRC_INT_8MD256 - from 0 to 32766 - Default value: - - 3000 if CONFIG_RTC_CLK_SRC_EXT_CRYS || CONFIG_RTC_CLK_SRC_EXT_OSC || CONFIG_RTC_CLK_SRC_INT_8MD256 - 1024 CONFIG_RTC_XTAL_CAL_RETRY Number of attempts to repeat 32k XTAL calibration Found in: Component config > Hardware Settings > RTC Clock Config Number of attempts to repeat 32k XTAL calibration before giving up and switching to the internal RC. Increase this option if the 32k crystal oscillator does not start and switches to internal RC. - Default value: - Peripheral Control Contains: CONFIG_PERIPH_CTRL_FUNC_IN_IRAM Place peripheral control functions into IRAM Found in: Component config > Hardware Settings > Peripheral Control Place peripheral control functions (e.g. periph_module_reset) into IRAM, so that these functions can be IRAM-safe and able to be called in the other IRAM interrupt context. - Default value: - - No (disabled) ETM Configuration Contains: CONFIG_ETM_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Hardware Settings > ETM Configuration Wether to enable the debug log message for ETM core driver. Note that, this option only controls the ETM related driver log, won't affect other drivers. - Default value: - - No (disabled) if SOC_ETM_SUPPORTED GDMA Configuration Contains: CONFIG_GDMA_CTRL_FUNC_IN_IRAM Place GDMA control functions into IRAM Found in: Component config > Hardware Settings > GDMA Configuration Place GDMA control functions (like start/stop/append/reset) into IRAM, so that these functions can be IRAM-safe and able to be called in the other IRAM interrupt context. Enabling this option can improve driver performance as well. - Default value: - - No (disabled) if SOC_GDMA_SUPPORTED CONFIG_GDMA_ISR_IRAM_SAFE GDMA ISR IRAM-Safe Found in: Component config > Hardware Settings > GDMA Configuration This will ensure the GDMA interrupt handler is IRAM-Safe, allow to avoid flash cache misses, and also be able to run whilst the cache is disabled. (e.g. SPI Flash write). - Default value: - - No (disabled) if SOC_GDMA_SUPPORTED CONFIG_GDMA_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > Hardware Settings > GDMA Configuration Wether to enable the debug log message for GDMA driver. Note that, this option only controls the GDMA driver log, won't affect other drivers. - Default value: - - No (disabled) if SOC_GDMA_SUPPORTED Main XTAL Config Contains: CONFIG_XTAL_FREQ_SEL Main XTAL frequency Found in: Component config > Hardware Settings > Main XTAL Config This option selects the operating frequency of the XTAL (crystal) clock used to drive the ESP target. The selected value MUST reflect the frequency of the given hardware. Note: The XTAL_FREQ_AUTO option allows the ESP target to automatically estimating XTAL clock's operating frequency. However, this feature is only supported on the ESP32. The ESP32 uses the internal 8MHZ as a reference when estimating. Due to the internal oscillator's frequency being temperature dependent, usage of the XTAL_FREQ_AUTO is not recommended in applications that operate in high ambient temperatures or use high-temperature qualified chips and modules. Available options: - 24 MHz (CONFIG_XTAL_FREQ_24) - 26 MHz (CONFIG_XTAL_FREQ_26) - 32 MHz (CONFIG_XTAL_FREQ_32) - 40 MHz (CONFIG_XTAL_FREQ_40) - Autodetect (CONFIG_XTAL_FREQ_AUTO) Crypto DPA Protection Contains: CONFIG_ESP_CRYPTO_DPA_PROTECTION_AT_STARTUP Enable crypto DPA protection at startup Found in: Component config > Hardware Settings > Crypto DPA Protection This config controls the DPA (Differential Power Analysis) protection knob for the crypto peripherals. DPA protection dynamically adjusts the clock frequency of the crypto peripheral. DPA protection helps to make it difficult to perform SCA attacks on the crypto peripherals. However, there is also associated performance impact based on the security level set. Please refer to the TRM for more details. - Default value: - - Yes (enabled) if SOC_CRYPTO_DPA_PROTECTION_SUPPORTED CONFIG_ESP_CRYPTO_DPA_PROTECTION_LEVEL DPA protection level Found in: Component config > Hardware Settings > Crypto DPA Protection > CONFIG_ESP_CRYPTO_DPA_PROTECTION_AT_STARTUP Configure the DPA protection security level Available options: - Security level low (CONFIG_ESP_CRYPTO_DPA_PROTECTION_LEVEL_LOW) - Security level medium (CONFIG_ESP_CRYPTO_DPA_PROTECTION_LEVEL_MEDIUM) - Security level high (CONFIG_ESP_CRYPTO_DPA_PROTECTION_LEVEL_HIGH) LCD and Touch Panel Contains: LCD Peripheral Configuration Contains: CONFIG_LCD_PANEL_IO_FORMAT_BUF_SIZE LCD panel io format buffer size Found in: Component config > LCD and Touch Panel > LCD Peripheral Configuration LCD driver allocates an internal buffer to transform the data into a proper format, because of the endian order mismatch. This option is to set the size of the buffer, in bytes. - Default value: - - 32 CONFIG_LCD_ENABLE_DEBUG_LOG Enable debug log Found in: Component config > LCD and Touch Panel > LCD Peripheral Configuration Wether to enable the debug log message for LCD driver. Note that, this option only controls the LCD driver log, won't affect other drivers. - Default value: - - No (disabled) CONFIG_LCD_RGB_ISR_IRAM_SAFE RGB LCD ISR IRAM-Safe Found in: Component config > LCD and Touch Panel > LCD Peripheral Configuration Ensure the LCD interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache is disabled (e.g. SPI Flash write). If you want the LCD driver to keep flushing the screen even when cache ops disabled, you can enable this option. Note, this will also increase the IRAM usage. - Default value: - - No (disabled) if SOC_LCD_RGB_SUPPORTED CONFIG_LCD_RGB_RESTART_IN_VSYNC Restart transmission in VSYNC Found in: Component config > LCD and Touch Panel > LCD Peripheral Configuration Reset the GDMA channel every VBlank to stop permanent desyncs from happening. Only need to enable it when in your application, the DMA can't deliver data as fast as the LCD consumes it. - Default value: - - No (disabled) if SOC_LCD_RGB_SUPPORTED ESP NETIF Adapter Contains: CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL IP Address lost timer interval (seconds) Found in: Component config > ESP NETIF Adapter The value of 0 indicates the IP lost timer is disabled, otherwise the timer is enabled. The IP address may be lost because of some reasons, e.g. when the station disconnects from soft-AP, or when DHCP IP renew fails etc. If the IP lost timer is enabled, it will be started everytime the IP is lost. Event SYSTEM_EVENT_STA_LOST_IP will be raised if the timer expires. The IP lost timer is stopped if the station get the IP again before the timer expires. - Range: - - from 0 to 65535 - Default value: - - 120 CONFIG_ESP_NETIF_USE_TCPIP_STACK_LIB TCP/IP Stack Library Found in: Component config > ESP NETIF Adapter Choose the TCP/IP Stack to work, for example, LwIP, uIP, etc. Available options: - LwIP (CONFIG_ESP_NETIF_TCPIP_LWIP) lwIP is a small independent implementation of the TCP/IP protocol suite. - Loopback (CONFIG_ESP_NETIF_LOOPBACK) Dummy implementation of esp-netif functionality which connects driver transmit to receive function. This option is for testing purpose only CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS Use esp_err_t to report errors from esp_netif_receive Found in: Component config > ESP NETIF Adapter Enable if esp_netif_receive() should return error code. This is useful to inform upper layers that packet input to TCP/IP stack failed, so the upper layers could implement flow control. This option is disabled by default due to backward compatibility and will be enabled in v6.0 (IDF-7194) - Default value: - - No (disabled) CONFIG_ESP_NETIF_L2_TAP Enable netif L2 TAP support Found in: Component config > ESP NETIF Adapter A user program can read/write link layer (L2) frames from/to ESP TAP device. The ESP TAP device can be currently associated only with Ethernet physical interfaces. CONFIG_ESP_NETIF_L2_TAP_MAX_FDS Maximum number of opened L2 TAP File descriptors Found in: Component config > ESP NETIF Adapter > CONFIG_ESP_NETIF_L2_TAP Maximum number of opened File descriptors (FD's) associated with ESP TAP device. ESP TAP FD's take up a certain amount of memory, and allowing fewer FD's to be opened at the same time conserves memory. - Range: - - from 1 to 10 if CONFIG_ESP_NETIF_L2_TAP - Default value: - CONFIG_ESP_NETIF_L2_TAP_RX_QUEUE_SIZE Size of L2 TAP Rx queue Found in: Component config > ESP NETIF Adapter > CONFIG_ESP_NETIF_L2_TAP Maximum number of frames queued in opened File descriptor. Once the queue is full, the newly arriving frames are dropped until the queue has enough room to accept incoming traffic (Tail Drop queue management). - Range: - - from 1 to 100 if CONFIG_ESP_NETIF_L2_TAP - Default value: - - 20 if CONFIG_ESP_NETIF_L2_TAP CONFIG_ESP_NETIF_BRIDGE_EN Enable LwIP IEEE 802.1D bridge Found in: Component config > ESP NETIF Adapter Enable LwIP IEEE 802.1D bridge support in ESP-NETIF. Note that "Number of clients store data in netif" (LWIP_NUM_NETIF_CLIENT_DATA) option needs to be properly configured to be LwIP bridge avaiable! - Default value: - - No (disabled) Partition API Configuration PHY Contains: CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE Store phy calibration data in NVS Found in: Component config > PHY If this option is enabled, NVS will be initialized and calibration data will be loaded from there. PHY calibration will be skipped on deep sleep wakeup. If calibration data is not found, full calibration will be performed and stored in NVS. Normally, only partial calibration will be performed. If this option is disabled, full calibration will be performed. If it's easy that your board calibrate bad data, choose 'n'. Two cases for example, you should choose 'n': 1.If your board is easy to be booted up with antenna disconnected. 2.Because of your board design, each time when you do calibration, the result are too unstable. If unsure, choose 'y'. - Default value: - - Yes (enabled) CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION Use a partition to store PHY init data Found in: Component config > PHY If enabled, PHY init data will be loaded from a partition. When using a custom partition table, make sure that PHY data partition is included (type: 'data', subtype: 'phy'). With default partition tables, this is done automatically. If PHY init data is stored in a partition, it has to be flashed there, otherwise runtime error will occur. If this option is not enabled, PHY init data will be embedded into the application binary. If unsure, choose 'n'. - Default value: - - No (disabled) Contains: CONFIG_ESP_PHY_DEFAULT_INIT_IF_INVALID Reset default PHY init data if invalid Found in: Component config > PHY > CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION If enabled, PHY init data will be restored to default if it cannot be verified successfully to avoid endless bootloops. If unsure, choose 'n'. - Default value: - - No (disabled) if CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN Support multiple PHY init data bin Found in: Component config > PHY > CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION If enabled, the corresponding PHY init data type can be automatically switched according to the country code. China's PHY init data bin is used by default. Can be modified by country information in API esp_wifi_set_country(). The priority of switching the PHY init data type is: 1. Country configured by API esp_wifi_set_country() and the parameter policy is WIFI_COUNTRY_POLICY_MANUAL. 2. Country notified by the connected AP. 3. Country configured by API esp_wifi_set_country() and the parameter policy is WIFI_COUNTRY_POLICY_AUTO. - Default value: - - No (disabled) if CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION && CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN_EMBED Support embedded multiple phy init data bin to app bin Found in: Component config > PHY > CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION > CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN If enabled, multiple phy init data bin will embedded into app bin If not enabled, multiple phy init data bin will still leave alone, and need to be flashed by users. - Default value: - - No (disabled) if CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN && CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION CONFIG_ESP_PHY_INIT_DATA_ERROR Terminate operation when PHY init data error Found in: Component config > PHY > CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION > CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN If enabled, when an error occurs while the PHY init data is updated, the program will terminate and restart. If not enabled, the PHY init data will not be updated when an error occurs. - Default value: - - No (disabled) if CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN && CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION CONFIG_ESP_PHY_MAX_WIFI_TX_POWER Max WiFi TX power (dBm) Found in: Component config > PHY Set maximum transmit power for WiFi radio. Actual transmit power for high data rates may be lower than this setting. - Range: - - from 10 to 20 - Default value: - - 20 CONFIG_ESP_PHY_MAC_BB_PD Power down MAC and baseband of Wi-Fi and Bluetooth when PHY is disabled Found in: Component config > PHY If enabled, the MAC and baseband of Wi-Fi and Bluetooth will be powered down when PHY is disabled. Enabling this setting reduces power consumption by a small amount but increases RAM use by approximately 4 KB(Wi-Fi only), 2 KB(Bluetooth only) or 5.3 KB(Wi-Fi + Bluetooth). - Default value: - - No (disabled) if SOC_PM_SUPPORT_MAC_BB_PD && CONFIG_FREERTOS_USE_TICKLESS_IDLE CONFIG_ESP_PHY_REDUCE_TX_POWER Reduce PHY TX power when brownout reset Found in: Component config > PHY When brownout reset occurs, reduce PHY TX power to keep the code running. - Default value: - - No (disabled) CONFIG_ESP_PHY_ENABLE_USB Enable USB when phy init Found in: Component config > PHY When using USB Serial/JTAG/OTG/CDC, PHY should enable USB, otherwise USB module can not work properly. Notice: Enabling this configuration option will slightly impact wifi performance. - Default value: - - No (disabled) if SOC_USB_OTG_SUPPORTED || CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG || CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG CONFIG_ESP_PHY_CALIBRATION_MODE Calibration mode Found in: Component config > PHY Select PHY calibration mode. During RF initialization, the partial calibration method is used by default for RF calibration. Full calibration takes about 100ms more than partial calibration. If boot duration is not critical, it is suggested to use the full calibration method. No calibration method is only used when the device wakes up from deep sleep. Available options: - Calibration partial (CONFIG_ESP_PHY_RF_CAL_PARTIAL) - Calibration none (CONFIG_ESP_PHY_RF_CAL_NONE) - Calibration full (CONFIG_ESP_PHY_RF_CAL_FULL) CONFIG_ESP_PHY_IMPROVE_RX_11B Improve Wi-Fi receive 11b pkts Found in: Component config > PHY This is a workaround to improve Wi-Fi receive 11b pkts for some modules using AC-DC power supply with high interference, enable this option will sacrifice Wi-Fi OFDM receive performance. But to guarantee 11b receive performance serves as a bottom line in this case. - Default value: - - No (disabled) if SOC_PHY_IMPROVE_RX_11B Power Management Contains: CONFIG_PM_ENABLE Support for power management Found in: Component config > Power Management If enabled, application is compiled with support for power management. This option has run-time overhead (increased interrupt latency, longer time to enter idle state), and it also reduces accuracy of RTOS ticks and timers used for timekeeping. Enable this option if application uses power management APIs. - Default value: - - No (disabled) if __DOXYGEN__ CONFIG_PM_DFS_INIT_AUTO Enable dynamic frequency scaling (DFS) at startup Found in: Component config > Power Management > CONFIG_PM_ENABLE If enabled, startup code configures dynamic frequency scaling. Max CPU frequency is set to DEFAULT_CPU_FREQ_MHZ setting, min frequency is set to XTAL frequency. If disabled, DFS will not be active until the application configures it using esp_pm_configure function. - Default value: - - No (disabled) if CONFIG_PM_ENABLE CONFIG_PM_PROFILING Enable profiling counters for PM locks Found in: Component config > Power Management > CONFIG_PM_ENABLE If enabled, esp_pm_* functions will keep track of the amount of time each of the power management locks has been held, and esp_pm_dump_locks function will print this information. This feature can be used to analyze which locks are preventing the chip from going into a lower power state, and see what time the chip spends in each power saving mode. This feature does incur some run-time overhead, so should typically be disabled in production builds. - Default value: - - No (disabled) if CONFIG_PM_ENABLE CONFIG_PM_TRACE Enable debug tracing of PM using GPIOs Found in: Component config > Power Management > CONFIG_PM_ENABLE If enabled, some GPIOs will be used to signal events such as RTOS ticks, frequency switching, entry/exit from idle state. Refer to pm_trace.c file for the list of GPIOs. This feature is intended to be used when analyzing/debugging behavior of power management implementation, and should be kept disabled in applications. - Default value: - - No (disabled) if CONFIG_PM_ENABLE CONFIG_PM_SLP_IRAM_OPT Put lightsleep related codes in internal RAM Found in: Component config > Power Management If enabled, about 2.1KB of lightsleep related source code would be in IRAM and chip would sleep longer for 310us at 160MHz CPU frequency most each time. This feature is intended to be used when lower power consumption is needed while there is enough place in IRAM to place source code. CONFIG_PM_RTOS_IDLE_OPT Put RTOS IDLE related codes in internal RAM Found in: Component config > Power Management If enabled, about 180Bytes of RTOS_IDLE related source code would be in IRAM and chip would sleep longer for 20us at 160MHz CPU frequency most each time. This feature is intended to be used when lower power consumption is needed while there is enough place in IRAM to place source code. CONFIG_PM_SLP_DISABLE_GPIO Disable all GPIO when chip at sleep Found in: Component config > Power Management This feature is intended to disable all GPIO pins at automantic sleep to get a lower power mode. If enabled, chips will disable all GPIO pins at automantic sleep to reduce about 200~300 uA current. If you want to specifically use some pins normally as chip wakes when chip sleeps, you can call 'gpio_sleep_sel_dis' to disable this feature on those pins. You can also keep this feature on and call 'gpio_sleep_set_direction' and 'gpio_sleep_set_pull_mode' to have a different GPIO configuration at sleep. Waring: If you want to enable this option on ESP32, you should enable GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL at first, otherwise you will not be able to switch pullup/pulldown mode. CONFIG_PM_LIGHTSLEEP_RTC_OSC_CAL_INTERVAL Calibrate the RTC_FAST/SLOW clock every N times of light sleep Found in: Component config > Power Management The value of this option determines the calibration interval of the RTC_FAST/SLOW clock during sleep when power management is enabled. When it is configured as N, the RTC_FAST/SLOW clock will be calibrated every N times of lightsleep. Decreasing this value will increase the time the chip is in the active state, thereby increasing the average power consumption of the chip. Increasing this value can reduce the average power consumption, but when the external environment changes drastically and the chip RTC_FAST/SLOW oscillator frequency drifts, it may cause system instability. - Range: - - from 1 to 128 if CONFIG_PM_ENABLE - Default value: - - 1 if CONFIG_PM_ENABLE CONFIG_PM_POWER_DOWN_CPU_IN_LIGHT_SLEEP Power down CPU in light sleep Found in: Component config > Power Management If enabled, the CPU will be powered down in light sleep, ESP chips supports saving and restoring CPU's running context before and after light sleep, the feature provides applications with seamless CPU powerdowned lightsleep without user awareness. But this will takes up some internal memory. On esp32c3 soc, enabling this option will consume 1.68 KB of internal RAM and will reduce sleep current consumption by about 100 uA. On esp32s3 soc, enabling this option will consume 8.58 KB of internal RAM and will reduce sleep current consumption by about 650 uA. - Default value: - - Yes (enabled) if SOC_PM_SUPPORT_CPU_PD CONFIG_PM_POWER_DOWN_PERIPHERAL_IN_LIGHT_SLEEP Power down Digital Peripheral in light sleep (EXPERIMENTAL) Found in: Component config > Power Management If enabled, digital peripherals will be powered down in light sleep, it will reduce sleep current consumption by about 100 uA. Chip will save/restore register context at sleep/wake time to keep the system running. Enabling this option will increase static RAM and heap usage, the actual cost depends on the peripherals you have initialized. In order to save/restore the context of the necessary hardware for FreeRTOS to run, it will need at least 4.55 KB free heap at sleep time. Otherwise sleep will not power down the peripherals. Note1: Please use this option with caution, the current IDF does not support the retention of all peripherals. When the digital peripherals are powered off and a sleep and wake-up is completed, the peripherals that have not saved the running context are equivalent to performing a reset. !!! Please confirm the peripherals used in your application and their sleep retention support status before enabling this option, peripherals sleep retention driver support status is tracked in power_management.rst Note2: When this option is enabled simultaneously with FREERTOS_USE_TICKLESS_IDLE, since the UART will be powered down, the uart FIFO will be flushed before sleep to avoid data loss, however, this has the potential to block the sleep process and cause the wakeup time to be skipped, which will cause the tick of freertos to not be compensated correctly when returning from sleep and cause the system to crash. To avoid this, you can increase FREERTOS_IDLE_TIME_BEFORE_SLEEP threshold in menuconfig. - Default value: - - No (disabled) if SOC_PAU_SUPPORTED CONFIG_PM_LIGHT_SLEEP_CALLBACKS Enable registration of pm light sleep callbacks Found in: Component config > Power Management If enabled, it allows user to register entry and exit callbacks which are called before and after entering auto light sleep. NOTE: These callbacks are executed from the IDLE task context hence you cannot have any blocking calls in your callbacks. NOTE: Enabling these callbacks may change sleep duration calculations based on time spent in callback and hence it is highly recommended to keep them as short as possible - Default value: - - No (disabled) if CONFIG_FREERTOS_USE_TICKLESS_IDLE ESP PSRAM Contains: CONFIG_SPIRAM Support for external, SPI-connected RAM Found in: Component config > ESP PSRAM This enables support for an external SPI RAM chip, connected in parallel with the main SPI flash chip. SPI RAM config Contains: CONFIG_SPIRAM_TYPE Type of SPI RAM chip in use Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Available options: - Auto-detect (CONFIG_SPIRAM_TYPE_AUTO) - ESP-PSRAM16 or APS1604 (CONFIG_SPIRAM_TYPE_ESPPSRAM16) - ESP-PSRAM32 (CONFIG_SPIRAM_TYPE_ESPPSRAM32) - ESP-PSRAM64 or LY68L6400 (CONFIG_SPIRAM_TYPE_ESPPSRAM64) CONFIG_SPIRAM_SPEED Set RAM clock speed Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Select the speed for the SPI RAM chip. If SPI RAM is enabled, we only support three combinations of SPI speed mode we supported now: - Flash SPI running at 40Mhz and RAM SPI running at 40Mhz - Flash SPI running at 80Mhz and RAM SPI running at 40Mhz - Flash SPI running at 80Mhz and RAM SPI running at 80Mhz Note: If the third mode(80Mhz+80Mhz) is enabled for SPI RAM of type 32MBit, one of the HSPI/VSPI host will be occupied by the system. Which SPI host to use can be selected by the config item SPIRAM_OCCUPY_SPI_HOST. Application code should never touch HSPI/VSPI hardware in this case. The option to select 80MHz will only be visible if the flash SPI speed is also 80MHz. (ESPTOOLPY_FLASHFREQ_80M is true) Available options: - 40MHz clock speed (CONFIG_SPIRAM_SPEED_40M) - 80MHz clock speed (CONFIG_SPIRAM_SPEED_80M) CONFIG_SPIRAM_BOOT_INIT Initialize SPI RAM during startup Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config If this is enabled, the SPI RAM will be enabled during initial boot. Unless you have specific requirements, you'll want to leave this enabled so memory allocated during boot-up can also be placed in SPI RAM. CONFIG_SPIRAM_IGNORE_NOTFOUND Ignore PSRAM when not found Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > CONFIG_SPIRAM_BOOT_INIT Normally, if psram initialization is enabled during compile time but not found at runtime, it is seen as an error making the CPU panic. If this is enabled, booting will complete but no PSRAM will be available. If PSRAM failed to initialize, the following configs may be affected and may need to be corrected manually. SPIRAM_TRY_ALLOCATE_WIFI_LWIP will affect some LWIP and WiFi buffer default values and range values. Enable SPIRAM_TRY_ALLOCATE_WIFI_LWIP, ESP_WIFI_AMSDU_TX_ENABLED, ESP_WIFI_CACHE_TX_BUFFER_NUM and use static WiFi Tx buffer may cause potential memory exhaustion issues. Suggest disable SPIRAM_TRY_ALLOCATE_WIFI_LWIP. Suggest disable ESP_WIFI_AMSDU_TX_ENABLED. Suggest disable ESP_WIFI_CACHE_TX_BUFFER_NUM, need clear CONFIG_FEATURE_CACHE_TX_BUF_BIT of config->feature_caps. Suggest change ESP_WIFI_TX_BUFFER from static to dynamic. Also suggest to adjust some buffer numbers to the values used without PSRAM case. Such as, ESP_WIFI_STATIC_TX_BUFFER_NUM, ESP_WIFI_DYNAMIC_TX_BUFFER_NUM. CONFIG_SPIRAM_USE SPI RAM access method Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config The SPI RAM can be accessed in multiple methods: by just having it available as an unmanaged memory region in the CPU's memory map, by integrating it in the heap as 'special' memory needing heap_caps_malloc to allocate, or by fully integrating it making malloc() also able to return SPI RAM pointers. Available options: - Integrate RAM into memory map (CONFIG_SPIRAM_USE_MEMMAP) - Make RAM allocatable using heap_caps_malloc(..., MALLOC_CAP_SPIRAM) (CONFIG_SPIRAM_USE_CAPS_ALLOC) - Make RAM allocatable using malloc() as well (CONFIG_SPIRAM_USE_MALLOC) CONFIG_SPIRAM_MEMTEST Run memory test on SPI RAM initialization Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Runs a rudimentary memory test on initialization. Aborts when memory test fails. Disable this for slightly faster startup. CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL Maximum malloc() size, in bytes, to always put in internal memory Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config If malloc() is capable of also allocating SPI-connected ram, its allocation strategy will prefer to allocate chunks less than this size in internal memory, while allocations larger than this will be done from external RAM. If allocation from the preferred region fails, an attempt is made to allocate from the non-preferred region instead, so malloc() will not suddenly fail when either internal or external memory is full. CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP Try to allocate memories of WiFi and LWIP in SPIRAM firstly. If failed, allocate internal memory Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Try to allocate memories of WiFi and LWIP in SPIRAM firstly. If failed, try to allocate internal memory then. CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL Reserve this amount of bytes for data that specifically needs to be in DMA or internal memory Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Because the external/internal RAM allocation strategy is not always perfect, it sometimes may happen that the internal memory is entirely filled up. This causes allocations that are specifically done in internal memory, for example the stack for new tasks or memory to service DMA or have memory that's also available when SPI cache is down, to fail. This option reserves a pool specifically for requests like that; the memory in this pool is not given out when a normal malloc() is called. Set this to 0 to disable this feature. Note that because FreeRTOS stacks are forced to internal memory, they will also use this memory pool; be sure to keep this in mind when adjusting this value. Note also that the DMA reserved pool may not be one single contiguous memory region, depending on the configured size and the static memory usage of the app. CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY Allow .bss segment placed in external memory Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config If enabled, variables with EXT_RAM_BSS_ATTR attribute will be placed in SPIRAM instead of internal DRAM. BSS section of lwip, net80211, pp, bt libraries will be automatically placed in SPIRAM. BSS sections from other object files and libraries can also be placed in SPIRAM through linker fragment scheme extram_bss. Note that the variables placed in SPIRAM using EXT_RAM_BSS_ATTR will be zero initialized. CONFIG_SPIRAM_ALLOW_NOINIT_SEG_EXTERNAL_MEMORY Allow .noinit segment placed in external memory Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config If enabled, noinit variables can be placed in PSRAM using EXT_RAM_NOINIT_ATTR. Note the values placed into this section will not be initialized at startup and should keep its value after software restart. CONFIG_SPIRAM_CACHE_WORKAROUND Enable workaround for bug in SPI RAM cache for Rev1 ESP32s Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Revision 1 of the ESP32 has a bug that can cause a write to PSRAM not to take place in some situations when the cache line needs to be fetched from external RAM and an interrupt occurs. This enables a fix in the compiler (-mfix-esp32-psram-cache-issue) that makes sure the specific code that is vulnerable to this will not be emitted. This will also not use any bits of newlib that are located in ROM, opting for a version that is compiled with the workaround and located in flash instead. The workaround is not required for ESP32 revision 3 and above. SPIRAM cache workaround debugging Contains: CONFIG_SPIRAM_CACHE_WORKAROUND_STRATEGY Workaround strategy Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM cache workaround debugging Select the workaround strategy. Note that the strategy for precompiled libraries (libgcc, newlib, bt, wifi) is not affected by this selection. Unless you know you need a different strategy, it's suggested you stay with the default MEMW strategy. Note that DUPLDST can interfere with hardware encryption and this will be automatically disabled if this workaround is selected. 'Insert nops' is the workaround that was used in older esp-idf versions. This workaround still can cause faulty data transfers from/to SPI RAM in some situation. Available options: - Insert memw after vulnerable instructions (default) (CONFIG_SPIRAM_CACHE_WORKAROUND_STRATEGY_MEMW) - Duplicate LD/ST for 32-bit, memw for 8/16 bit (CONFIG_SPIRAM_CACHE_WORKAROUND_STRATEGY_DUPLDST) - Insert nops between vulnerable loads/stores (old strategy, obsolete) (CONFIG_SPIRAM_CACHE_WORKAROUND_STRATEGY_NOPS) SPIRAM workaround libraries placement Contains: CONFIG_SPIRAM_CACHE_LIBJMP_IN_IRAM Put libc's jump related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: longjmp and setjmp. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBMATH_IN_IRAM Put libc's math related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: abs, div, labs, ldiv, quorem, fpclassify, and nan. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBNUMPARSER_IN_IRAM Put libc's number parsing related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: utoa, itoa, atoi, atol, strtol, and strtoul. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBIO_IN_IRAM Put libc's I/O related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: wcrtomb, fvwrite, wbuf, wsetup, fputwc, wctomb_r, ungetc, makebuf, fflush, refill, and sccl. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBTIME_IN_IRAM Put libc's time related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: asctime, asctime_r, ctime, ctime_r, lcltime, lcltime_r, gmtime, gmtime_r, strftime, mktime, tzset_r, tzset, time, gettzinfo, systimes, month_lengths, timelocal, tzvars, tzlock, tzcalc_limits, and strptime. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBCHAR_IN_IRAM Put libc's characters related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: ctype_, toupper, tolower, toascii, strupr, bzero, isalnum, isalpha, isascii, isblank, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, and isupper. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBMEM_IN_IRAM Put libc's memory related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: memccpy, memchr memmove, and memrchr. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBSTR_IN_IRAM Put libc's string related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: strcasecmp, strcasestr, strchr, strcoll, strcpy, strcspn, strdup, strdup_r, strlcat, strlcpy, strlen, strlwr, strncasecmp, strncat, strncmp, strncpy, strndup, strndup_r, strrchr, strsep, strspn, strstr, strtok_r, and strupr. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBRAND_IN_IRAM Put libc's random related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: srand, rand, and rand_r. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBENV_IN_IRAM Put libc's environment related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: environ, envlock, and getenv_r. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBFILE_IN_IRAM Put libc's file related functions in IRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: lock, isatty, fclose, open, close, creat, read, rshift, sbrk, stdio, syssbrk, sysclose, sysopen, creat, sysread, syswrite, impure, fwalk, and findfp. Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_CACHE_LIBMISC_IN_IRAM Put libc's miscellaneous functions in IRAM, see help Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM workaround libraries placement The functions affected by this option are: raise and system Putting these function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for the user application. CONFIG_SPIRAM_BANKSWITCH_ENABLE Enable bank switching for >4MiB external RAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config The ESP32 only supports 4MiB of external RAM in its address space. The hardware does support larger memories, but these have to be bank-switched in and out of this address space. Enabling this allows you to reserve some MMU pages for this, which allows the use of the esp_himem api to manage these banks. #Note that this is limited to 62 banks, as esp_psram_extram_writeback_cache needs some kind of mapping of #some banks below that mark to work. We cannot at this moment guarantee this to exist when himem is #enabled. If spiram 2T mode is enabled, the size of 64Mbit psram will be changed as 32Mbit, so himem will be unusable. CONFIG_SPIRAM_BANKSWITCH_RESERVE Amount of 32K pages to reserve for bank switching Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > CONFIG_SPIRAM_BANKSWITCH_ENABLE Select the amount of banks reserved for bank switching. Note that the amount of RAM allocatable with malloc/esp_heap_alloc_caps will decrease by 32K for each page reserved here. Note that this reservation is only actually done if your program actually uses the himem API. Without any himem calls, the reservation is not done and the original amount of memory will be available to malloc/esp_heap_alloc_caps. CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY Allow external memory as an argument to xTaskCreateStatic Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Because some bits of the ESP32 code environment cannot be recompiled with the cache workaround, normally tasks cannot be safely run with their stack residing in external memory; for this reason xTaskCreate (and related task creaton functions) always allocate stack in internal memory and xTaskCreateStatic will check if the memory passed to it is in internal memory. If you have a task that needs a large amount of stack and does not call on ROM code in any way (no direct calls, but also no Bluetooth/WiFi), you can try enable this to cause xTaskCreateStatic to allow tasks stack in external memory. CONFIG_SPIRAM_OCCUPY_SPI_HOST SPI host to use for 32MBit PSRAM Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config When both flash and PSRAM is working under 80MHz, and the PSRAM is of type 32MBit, one of the HSPI/VSPI host will be used to output the clock. Select which one to use here. Available options: - HSPI host (SPI2) (CONFIG_SPIRAM_OCCUPY_HSPI_HOST) - VSPI host (SPI3) (CONFIG_SPIRAM_OCCUPY_VSPI_HOST) - Will not try to use any host, will abort if not able to use the PSRAM (CONFIG_SPIRAM_OCCUPY_NO_HOST) PSRAM clock and cs IO for ESP32-DOWD Contains: CONFIG_D0WD_PSRAM_CLK_IO PSRAM CLK IO number Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > PSRAM clock and cs IO for ESP32-DOWD The PSRAM CLOCK IO can be any unused GPIO, user can config it based on hardware design. If user use 1.8V flash and 1.8V psram, this value can only be one of 6, 7, 8, 9, 10, 11, 16, 17. If configured to the same pin as Flash, PSRAM shouldn't be rev0. Contact Espressif for more information. CONFIG_D0WD_PSRAM_CS_IO PSRAM CS IO number Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > PSRAM clock and cs IO for ESP32-DOWD The PSRAM CS IO can be any unused GPIO, user can config it based on hardware design. If user use 1.8V flash and 1.8V psram, this value can only be one of 6, 7, 8, 9, 10, 11, 16, 17. PSRAM clock and cs IO for ESP32-D2WD Contains: CONFIG_D2WD_PSRAM_CLK_IO PSRAM CLK IO number Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > PSRAM clock and cs IO for ESP32-D2WD User can config it based on hardware design. For ESP32-D2WD chip, the psram can only be 1.8V psram, so this value can only be one of 6, 7, 8, 9, 10, 11, 16, 17. If configured to the same pin (GPIO6) as Flash, PSRAM shouldn't be rev0. Contact Espressif for more information. CONFIG_D2WD_PSRAM_CS_IO PSRAM CS IO number Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > PSRAM clock and cs IO for ESP32-D2WD User can config it based on hardware design. For ESP32-D2WD chip, the psram can only be 1.8V psram, so this value can only be one of 6, 7, 8, 9, 10, 11, 16, 17. PSRAM clock and cs IO for ESP32-PICO-D4 Contains: CONFIG_PICO_PSRAM_CS_IO PSRAM CS IO number Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > PSRAM clock and cs IO for ESP32-PICO-D4 The PSRAM CS IO can be any unused GPIO, user can config it based on hardware design. For ESP32-PICO chip, the psram share clock with flash, so user do not need to configure the clock IO. For the reference hardware design, please refer to https://www.espressif.com/sites/default/files/documentation/esp32-pico-d4_datasheet_en.pdf CONFIG_SPIRAM_CUSTOM_SPIWP_SD3_PIN Use custom SPI PSRAM WP(SD3) Pin when flash pins set in eFuse (read help) Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config This setting is only used if the SPI flash pins have been overridden by setting the eFuses SPI_PAD_CONFIG_xxx, and the SPI flash mode is DIO or DOUT. When this is the case, the eFuse config only defines 3 of the 4 Quad I/O data pins. The WP pin (aka ESP32 pin "SD_DATA_3" or SPI flash pin "IO2") is not specified in eFuse. The psram only has QPI mode, so a WP pin setting is necessary. If this config item is set to N (default), the correct WP pin will be automatically used for any Espressif chip or module with integrated flash. If a custom setting is needed, set this config item to Y and specify the GPIO number connected to the WP pin. When flash mode is set to QIO or QOUT, the PSRAM WP pin will be set the same as the SPI Flash WP pin configured in the bootloader. CONFIG_SPIRAM_SPIWP_SD3_PIN Custom SPI PSRAM WP(SD3) Pin Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config The option "Use custom SPI PSRAM WP(SD3) pin" must be set or this value is ignored If burning a customized set of SPI flash pins in eFuse and using DIO or DOUT mode for flash, set this value to the GPIO number of the SPIRAM WP pin. CONFIG_SPIRAM_2T_MODE Enable SPI PSRAM 2T mode Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config Enable this option to fix single bit errors inside 64Mbit PSRAM. Some 64Mbit PSRAM chips have a hardware issue in the RAM which causes bit errors at multiple fixed bit positions. Note: If this option is enabled, the 64Mbit PSRAM chip will appear to be 32Mbit in size. Applications will not be affected unless the use the esp_himem APIs, which are not supported in 2T mode. ESP Ringbuf Contains: CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH Place non-ISR ringbuf functions into flash Found in: Component config > ESP Ringbuf Place non-ISR ringbuf functions (like xRingbufferCreate/xRingbufferSend) into flash. This frees up IRAM, but the functions can no longer be called when the cache is disabled. - Default value: - - No (disabled) CONFIG_RINGBUF_PLACE_ISR_FUNCTIONS_INTO_FLASH Place ISR ringbuf functions into flash Found in: Component config > ESP Ringbuf > CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH Place ISR ringbuf functions (like xRingbufferSendFromISR/xRingbufferReceiveFromISR) into flash. This frees up IRAM, but the functions can no longer be called when the cache is disabled or from an IRAM interrupt context. This option is not compatible with ESP-IDF drivers which are configured to run the ISR from an IRAM context, e.g. CONFIG_UART_ISR_IN_IRAM. - Default value: - - No (disabled) if CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH ESP System Settings Contains: CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ CPU frequency Found in: Component config > ESP System Settings CPU frequency to be set on application startup. Available options: - 40 MHz (CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_40) - 80 MHz (CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_80) - 160 MHz (CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160) - 240 MHz (CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240) Memory Contains: CONFIG_ESP32_RTCDATA_IN_FAST_MEM Place RTC_DATA_ATTR and RTC_RODATA_ATTR variables into RTC fast memory segment Found in: Component config > ESP System Settings > Memory This option allows to place .rtc_data and .rtc_rodata sections into RTC fast memory segment to free the slow memory region for ULP programs. This option depends on the CONFIG_FREERTOS_UNICORE option because RTC fast memory can be accessed only by PRO_CPU core. - Default value: - - No (disabled) if CONFIG_FREERTOS_UNICORE CONFIG_ESP32_USE_FIXED_STATIC_RAM_SIZE Use fixed static RAM size Found in: Component config > ESP System Settings > Memory If this option is disabled, the DRAM part of the heap starts right after the .bss section, within the dram0_0 region. As a result, adding or removing some static variables will change the available heap size. If this option is enabled, the DRAM part of the heap starts right after the dram0_0 region, where its length is set with ESP32_FIXED_STATIC_RAM_SIZE - Default value: - - No (disabled) CONFIG_ESP32_FIXED_STATIC_RAM_SIZE Fixed Static RAM size Found in: Component config > ESP System Settings > Memory > CONFIG_ESP32_USE_FIXED_STATIC_RAM_SIZE RAM size dedicated for static variables (.data & .bss sections). Please note that the actual length will be reduced by BTDM_RESERVE_DRAM if Bluetooth controller is enabled. - Range: - - from 0 to 0x2c200 if CONFIG_ESP32_USE_FIXED_STATIC_RAM_SIZE - Default value: - - "0x1E000" if CONFIG_ESP32_USE_FIXED_STATIC_RAM_SIZE CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY Enable IRAM as 8 bit accessible memory Found in: Component config > ESP System Settings > Memory If enabled, application can use IRAM as byte accessible region for storing data (Note: IRAM region cannot be used as task stack) This is possible due to handling of exceptions LoadStoreError (3) and LoadStoreAlignmentError (9) Each unaligned read/write access will incur a penalty of maximum of 167 CPU cycles. Non-backward compatible options Contains: CONFIG_ESP_SYSTEM_ESP32_SRAM1_REGION_AS_IRAM Reserve parts of SRAM1 for app IRAM (WARNING, read help before enabling) Found in: Component config > ESP System Settings > Memory > Non-backward compatible options Reserve parts of SRAM1 for app IRAM which was previously reserved for bootloader DRAM. If booting an app on an older bootloader from before this option was introduced, the app will fail to boot due to not recognizing the new IRAM memory area. If this is the case please test carefully before pushing out any OTA updates. Trace memory Contains: CONFIG_ESP32_TRAX Use TRAX tracing feature Found in: Component config > ESP System Settings > Trace memory The ESP32 contains a feature which allows you to trace the execution path the processor has taken through the program. This is stored in a chunk of 32K (16K for single-processor) of memory that can't be used for general purposes anymore. Disable this if you do not know what this is. - Default value: - - No (disabled) CONFIG_ESP32_TRAX_TWOBANKS Reserve memory for tracing both pro as well as app cpu execution Found in: Component config > ESP System Settings > Trace memory > CONFIG_ESP32_TRAX The ESP32 contains a feature which allows you to trace the execution path the processor has taken through the program. This is stored in a chunk of 32K (16K for single-processor) of memory that can't be used for general purposes anymore. Disable this if you do not know what this is. # Memory to reverse for trace, used in linker script CONFIG_ESP_SYSTEM_PANIC Panic handler behaviour Found in: Component config > ESP System Settings If FreeRTOS detects unexpected behaviour or an unhandled exception, the panic handler is invoked. Configure the panic handler's action here. Available options: - Print registers and halt (CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT) Outputs the relevant registers over the serial port and halt the processor. Needs a manual reset to restart. - Print registers and reboot (CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT) Outputs the relevant registers over the serial port and immediately reset the processor. - Silent reboot (CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT) Just resets the processor without outputting anything - GDBStub on panic (CONFIG_ESP_SYSTEM_PANIC_GDBSTUB) Invoke gdbstub on the serial port, allowing for gdb to attach to it to do a postmortem of the crash. CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS Panic reboot delay (Seconds) Found in: Component config > ESP System Settings After the panic handler executes, you can specify a number of seconds to wait before the device reboots. - Range: - - from 0 to 99 - Default value: - - 0 CONFIG_ESP_SYSTEM_RTC_EXT_XTAL_BOOTSTRAP_CYCLES Bootstrap cycles for external 32kHz crystal Found in: Component config > ESP System Settings To reduce the startup time of an external RTC crystal, we bootstrap it with a 32kHz square wave for a fixed number of cycles. Setting 0 will disable bootstrapping (if disabled, the crystal may take longer to start up or fail to oscillate under some conditions). If this value is too high, a faulty crystal may initially start and then fail. If this value is too low, an otherwise good crystal may not start. To accurately determine if the crystal has started, set a larger "Number of cycles for RTC_SLOW_CLK calibration" (about 3000). CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP Enable RTC fast memory for dynamic allocations Found in: Component config > ESP System Settings This config option allows to add RTC fast memory region to system heap with capability similar to that of DRAM region but without DMA. This memory will be consumed first per heap initialization order by early startup services and scheduler related code. Speed wise RTC fast memory operates on APB clock and hence does not have much performance impact. Memory protection Contains: CONFIG_ESP_SYSTEM_PMP_IDRAM_SPLIT Enable IRAM/DRAM split protection Found in: Component config > ESP System Settings > Memory protection If enabled, the CPU watches all the memory access and raises an exception in case of any memory violation. This feature automatically splits the SRAM memory, using PMP, into data and instruction segments and sets Read/Execute permissions for the instruction part (below given splitting address) and Read/Write permissions for the data part (above the splitting address). The memory protection is effective on all access through the IRAM0 and DRAM0 buses. - Default value: - - Yes (enabled) if SOC_CPU_IDRAM_SPLIT_USING_PMP CONFIG_ESP_SYSTEM_MEMPROT_FEATURE Enable memory protection Found in: Component config > ESP System Settings > Memory protection If enabled, the permission control module watches all the memory access and fires the panic handler if a permission violation is detected. This feature automatically splits the SRAM memory into data and instruction segments and sets Read/Execute permissions for the instruction part (below given splitting address) and Read/Write permissions for the data part (above the splitting address). The memory protection is effective on all access through the IRAM0 and DRAM0 buses. - Default value: - - Yes (enabled) if SOC_MEMPROT_SUPPORTED CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_LOCK Lock memory protection settings Found in: Component config > ESP System Settings > Memory protection > CONFIG_ESP_SYSTEM_MEMPROT_FEATURE Once locked, memory protection settings cannot be changed anymore. The lock is reset only on the chip startup. - Default value: - - Yes (enabled) if CONFIG_ESP_SYSTEM_MEMPROT_FEATURE CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE System event queue size Found in: Component config > ESP System Settings Config system event queue size in different application. - Default value: - - 32 CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE Event loop task stack size Found in: Component config > ESP System Settings Config system event task stack size in different application. - Default value: - - 2304 CONFIG_ESP_MAIN_TASK_STACK_SIZE Main task stack size Found in: Component config > ESP System Settings Configure the "main task" stack size. This is the stack of the task which calls app_main(). If app_main() returns then this task is deleted and its stack memory is freed. - Default value: - - 3584 CONFIG_ESP_MAIN_TASK_AFFINITY Main task core affinity Found in: Component config > ESP System Settings Configure the "main task" core affinity. This is the used core of the task which calls app_main(). If app_main() returns then this task is deleted. Available options: - CPU0 (CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0) - CPU1 (CONFIG_ESP_MAIN_TASK_AFFINITY_CPU1) - No affinity (CONFIG_ESP_MAIN_TASK_AFFINITY_NO_AFFINITY) CONFIG_ESP_CONSOLE_UART Channel for console output Found in: Component config > ESP System Settings Select where to send console output (through stdout and stderr). - Default is to use UART0 on pre-defined GPIOs. - If "Custom" is selected, UART0 or UART1 can be chosen, and any pins can be selected. - If "None" is selected, there will be no console output on any UART, except for initial output from ROM bootloader. This ROM output can be suppressed by GPIO strapping or EFUSE, refer to chip datasheet for details. - On chips with USB OTG peripheral, "USB CDC" option redirects output to the CDC port. This option uses the CDC driver in the chip ROM. This option is incompatible with TinyUSB stack. - On chips with an USB serial/JTAG debug controller, selecting the option for that redirects output to the CDC/ACM (serial port emulation) component of that device. Available options: - Default: UART0 (CONFIG_ESP_CONSOLE_UART_DEFAULT) - USB CDC (CONFIG_ESP_CONSOLE_USB_CDC) - USB Serial/JTAG Controller (CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG) - Custom UART (CONFIG_ESP_CONSOLE_UART_CUSTOM) - None (CONFIG_ESP_CONSOLE_NONE) CONFIG_ESP_CONSOLE_SECONDARY Channel for console secondary output Found in: Component config > ESP System Settings This secondary option supports output through other specific port like USB_SERIAL_JTAG when UART0 port as a primary is selected but not connected. This secondary output currently only supports non-blocking mode without using REPL. If you want to output in blocking mode with REPL or input through this secondary port, please change the primary config to this port in Channel for console output menu. Available options: - No secondary console (CONFIG_ESP_CONSOLE_SECONDARY_NONE) - USB_SERIAL_JTAG PORT (CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG) This option supports output through USB_SERIAL_JTAG port when the UART0 port is not connected. The output currently only supports non-blocking mode without using the console. If you want to output in blocking mode with REPL or input through USB_SERIAL_JTAG port, please change the primary config to ESP_CONSOLE_USB_SERIAL_JTAG above. CONFIG_ESP_CONSOLE_UART_NUM UART peripheral to use for console output (0-1) Found in: Component config > ESP System Settings This UART peripheral is used for console output from the ESP-IDF Bootloader and the app. If the configuration is different in the Bootloader binary compared to the app binary, UART is reconfigured after the bootloader exits and the app starts. Due to an ESP32 ROM bug, UART2 is not supported for console output via esp_rom_printf. Available options: - UART0 (CONFIG_ESP_CONSOLE_UART_CUSTOM_NUM_0) - UART1 (CONFIG_ESP_CONSOLE_UART_CUSTOM_NUM_1) CONFIG_ESP_CONSOLE_UART_TX_GPIO UART TX on GPIO# Found in: Component config > ESP System Settings This GPIO is used for console UART TX output in the ESP-IDF Bootloader and the app (including boot log output and default standard output and standard error of the app). If the configuration is different in the Bootloader binary compared to the app binary, UART is reconfigured after the bootloader exits and the app starts. - Range: - - from 0 to 33 if CONFIG_ESP_CONSOLE_UART_CUSTOM - Default value: - CONFIG_ESP_CONSOLE_UART_RX_GPIO UART RX on GPIO# Found in: Component config > ESP System Settings This GPIO is used for UART RX input in the ESP-IDF Bootloader and the app (including default default standard input of the app). Note: The default ESP-IDF Bootloader configures this pin but doesn't read anything from the UART. If the configuration is different in the Bootloader binary compared to the app binary, UART is reconfigured after the bootloader exits and the app starts. - Range: - - from 0 to 39 if CONFIG_ESP_CONSOLE_UART_CUSTOM - Default value: - CONFIG_ESP_CONSOLE_UART_BAUDRATE UART console baud rate Found in: Component config > ESP System Settings This baud rate is used by both the ESP-IDF Bootloader and the app (including boot log output and default standard input/output/error of the app). The app's maximum baud rate depends on the UART clock source. If Power Management is disabled, the UART clock source is the APB clock and all baud rates in the available range will be sufficiently accurate. If Power Management is enabled, REF_TICK clock source is used so the baud rate is divided from 1MHz. Baud rates above 1Mbps are not possible and values between 500Kbps and 1Mbps may not be accurate. If the configuration is different in the Bootloader binary compared to the app binary, UART is reconfigured after the bootloader exits and the app starts. - Range: - - from 1200 to 1000000 if CONFIG_PM_ENABLE - Default value: - - 115200 CONFIG_ESP_INT_WDT Interrupt watchdog Found in: Component config > ESP System Settings This watchdog timer can detect if the FreeRTOS tick interrupt has not been called for a certain time, either because a task turned off interrupts and did not turn them on for a long time, or because an interrupt handler did not return. It will try to invoke the panic handler first and failing that reset the SoC. - Default value: - - Yes (enabled) CONFIG_ESP_INT_WDT_TIMEOUT_MS Interrupt watchdog timeout (ms) Found in: Component config > ESP System Settings > CONFIG_ESP_INT_WDT The timeout of the watchdog, in miliseconds. Make this higher than the FreeRTOS tick rate. - Range: - - from 10 to 10000 - Default value: - - 800 if CONFIG_SPIRAM && CONFIG_ESP_INT_WDT CONFIG_ESP_INT_WDT_CHECK_CPU1 Also watch CPU1 tick interrupt Found in: Component config > ESP System Settings > CONFIG_ESP_INT_WDT Also detect if interrupts on CPU 1 are disabled for too long. CONFIG_ESP_TASK_WDT_EN Enable Task Watchdog Timer Found in: Component config > ESP System Settings The Task Watchdog Timer can be used to make sure individual tasks are still running. Enabling this option will enable the Task Watchdog Timer. It can be either initialized automatically at startup or initialized after startup (see Task Watchdog Timer API Reference) - Default value: - - Yes (enabled) CONFIG_ESP_TASK_WDT_INIT Initialize Task Watchdog Timer on startup Found in: Component config > ESP System Settings > CONFIG_ESP_TASK_WDT_EN Enabling this option will cause the Task Watchdog Timer to be initialized automatically at startup. - Default value: - - Yes (enabled) CONFIG_ESP_TASK_WDT_PANIC Invoke panic handler on Task Watchdog timeout Found in: Component config > ESP System Settings > CONFIG_ESP_TASK_WDT_EN > CONFIG_ESP_TASK_WDT_INIT If this option is enabled, the Task Watchdog Timer will be configured to trigger the panic handler when it times out. This can also be configured at run time (see Task Watchdog Timer API Reference) - Default value: - - No (disabled) CONFIG_ESP_TASK_WDT_TIMEOUT_S Task Watchdog timeout period (seconds) Found in: Component config > ESP System Settings > CONFIG_ESP_TASK_WDT_EN > CONFIG_ESP_TASK_WDT_INIT Timeout period configuration for the Task Watchdog Timer in seconds. This is also configurable at run time (see Task Watchdog Timer API Reference) - Range: - - from 1 to 60 - Default value: - - 5 CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0 Watch CPU0 Idle Task Found in: Component config > ESP System Settings > CONFIG_ESP_TASK_WDT_EN > CONFIG_ESP_TASK_WDT_INIT If this option is enabled, the Task Watchdog Timer will watch the CPU0 Idle Task. Having the Task Watchdog watch the Idle Task allows for detection of CPU starvation as the Idle Task not being called is usually a symptom of CPU starvation. Starvation of the Idle Task is detrimental as FreeRTOS household tasks depend on the Idle Task getting some runtime every now and then. - Default value: - - Yes (enabled) CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1 Watch CPU1 Idle Task Found in: Component config > ESP System Settings > CONFIG_ESP_TASK_WDT_EN > CONFIG_ESP_TASK_WDT_INIT If this option is enabled, the Task Watchdog Timer will wach the CPU1 Idle Task. CONFIG_ESP_PANIC_HANDLER_IRAM Place panic handler code in IRAM Found in: Component config > ESP System Settings If this option is disabled (default), the panic handler code is placed in flash not IRAM. This means that if ESP-IDF crashes while flash cache is disabled, the panic handler will automatically re-enable flash cache before running GDB Stub or Core Dump. This adds some minor risk, if the flash cache status is also corrupted during the crash. If this option is enabled, the panic handler code (including required UART functions) is placed in IRAM. This may be necessary to debug some complex issues with crashes while flash cache is disabled (for example, when writing to SPI flash) or when flash cache is corrupted when an exception is triggered. - Default value: - - No (disabled) CONFIG_ESP_DEBUG_STUBS_ENABLE OpenOCD debug stubs Found in: Component config > ESP System Settings Debug stubs are used by OpenOCD to execute pre-compiled onboard code which does some useful debugging stuff, e.g. GCOV data dump. CONFIG_ESP_DEBUG_OCDAWARE Make exception and panic handlers JTAG/OCD aware Found in: Component config > ESP System Settings The FreeRTOS panic and unhandled exception handers can detect a JTAG OCD debugger and instead of panicking, have the debugger stop on the offending instruction. - Default value: - - Yes (enabled) CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL Interrupt level to use for Interrupt Watchdog and other system checks Found in: Component config > ESP System Settings Interrupt level to use for Interrupt Watchdog, IPC_ISR and other system checks. Available options: - Level 5 interrupt (CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_5) Using level 5 interrupt for Interrupt Watchdog, IPC_ISR and other system checks. - Level 4 interrupt (CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4) Using level 4 interrupt for Interrupt Watchdog, IPC_ISR and other system checks. Brownout Detector Contains: CONFIG_ESP_BROWNOUT_DET Hardware brownout detect & reset Found in: Component config > ESP System Settings > Brownout Detector The ESP has a built-in brownout detector which can detect if the voltage is lower than a specific value. If this happens, it will reset the chip in order to prevent unintended behaviour. - Default value: - - Yes (enabled) CONFIG_ESP_BROWNOUT_DET_LVL_SEL Brownout voltage level Found in: Component config > ESP System Settings > Brownout Detector > CONFIG_ESP_BROWNOUT_DET The brownout detector will reset the chip when the supply voltage is approximately below this level. Note that there may be some variation of brownout voltage level between each ESP chip. #The voltage levels here are estimates, more work needs to be done to figure out the exact voltages #of the brownout threshold levels. Available options: - 2.43V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_0) - 2.48V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_1) - 2.58V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_2) - 2.62V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_3) - 2.67V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_4) - 2.70V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5) - 2.77V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6) - 2.80V +/- 0.05 (CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7) CONFIG_ESP32_DISABLE_BASIC_ROM_CONSOLE Permanently disable BASIC ROM Console Found in: Component config > ESP System Settings If set, the first time the app boots it will disable the BASIC ROM Console permanently (by burning an eFuse). Otherwise, the BASIC ROM Console starts on reset if no valid bootloader is read from the flash. (Enabling secure boot also disables the BASIC ROM Console by default.) - Default value: - - No (disabled) CONFIG_ESP_SYSTEM_HW_STACK_GUARD Hardware stack guard Found in: Component config > ESP System Settings This config allows to trigger a panic interrupt when Stack Pointer register goes out of allocated stack memory bounds. - Default value: - - Yes (enabled) if SOC_ASSIST_DEBUG_SUPPORTED IPC (Inter-Processor Call) Contains: CONFIG_ESP_IPC_TASK_STACK_SIZE Inter-Processor Call (IPC) task stack size Found in: Component config > IPC (Inter-Processor Call) Configure the IPC tasks stack size. An IPC task runs on each core (in dual core mode), and allows for cross-core function calls. See IPC documentation for more details. The default IPC stack size should be enough for most common simple use cases. However, users can increase/decrease the stack size to their needs. - Range: - - from 512 to 65536 - Default value: - - 1024 CONFIG_ESP_IPC_USES_CALLERS_PRIORITY IPC runs at caller's priority Found in: Component config > IPC (Inter-Processor Call) If this option is not enabled then the IPC task will keep behavior same as prior to that of ESP-IDF v4.0, hence IPC task will run at (configMAX_PRIORITIES - 1) priority. High resolution timer (esp_timer) Contains: CONFIG_ESP_TIMER_PROFILING Enable esp_timer profiling features Found in: Component config > High resolution timer (esp_timer) If enabled, esp_timer_dump will dump information such as number of times the timer was started, number of times the timer has triggered, and the total time it took for the callback to run. This option has some effect on timer performance and the amount of memory used for timer storage, and should only be used for debugging/testing purposes. - Default value: - - No (disabled) CONFIG_ESP_TIMER_TASK_STACK_SIZE High-resolution timer task stack size Found in: Component config > High resolution timer (esp_timer) Configure the stack size of "timer_task" task. This task is used to dispatch callbacks of timers created using ets_timer and esp_timer APIs. If you are seing stack overflow errors in timer task, increase this value. Note that this is not the same as FreeRTOS timer task. To configure FreeRTOS timer task size, see "FreeRTOS timer task stack size" option in "FreeRTOS". - Range: - - from 2048 to 65536 - Default value: - - 3584 CONFIG_ESP_TIMER_INTERRUPT_LEVEL Interrupt level Found in: Component config > High resolution timer (esp_timer) It sets the interrupt level for esp_timer ISR in range 1..3. A higher level (3) helps to decrease the ISR esp_timer latency. - Range: - - from 1 to 3 - Default value: - - 1 CONFIG_ESP_TIMER_SHOW_EXPERIMENTAL show esp_timer's experimental features Found in: Component config > High resolution timer (esp_timer) This shows some hidden features of esp_timer. Note that they may break other features, use them with care. CONFIG_ESP_TIMER_TASK_AFFINITY esp_timer task core affinity Found in: Component config > High resolution timer (esp_timer) The default settings: timer TASK on CPU0 and timer ISR on CPU0. Other settings may help in certain cases, but note that they may break other features, use them with care. - "CPU0": (default) esp_timer task is processed by CPU0. - "CPU1": esp_timer task is processed by CPU1. - "No affinity": esp_timer task can be processed by any CPU. Available options: - CPU0 (CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0) - CPU1 (CONFIG_ESP_TIMER_TASK_AFFINITY_CPU1) - No affinity (CONFIG_ESP_TIMER_TASK_AFFINITY_NO_AFFINITY) CONFIG_ESP_TIMER_ISR_AFFINITY timer interrupt core affinity Found in: Component config > High resolution timer (esp_timer) The default settings: timer TASK on CPU0 and timer ISR on CPU0. Other settings may help in certain cases, but note that they may break other features, use them with care. - "CPU0": (default) timer interrupt is processed by CPU0. - "CPU1": timer interrupt is processed by CPU1. - "No affinity": timer interrupt can be processed by any CPU. It helps to reduce latency but there is a disadvantage it leads to the timer ISR running on every core. It increases the CPU time usage for timer ISRs by N on an N-core system. Available options: - CPU0 (CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0) - CPU1 (CONFIG_ESP_TIMER_ISR_AFFINITY_CPU1) - No affinity (CONFIG_ESP_TIMER_ISR_AFFINITY_NO_AFFINITY) CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD Support ISR dispatch method Found in: Component config > High resolution timer (esp_timer) Allows using ESP_TIMER_ISR dispatch method (ESP_TIMER_TASK dispatch method is also avalible). - ESP_TIMER_TASK - Timer callbacks are dispatched from a high-priority esp_timer task. - ESP_TIMER_ISR - Timer callbacks are dispatched directly from the timer interrupt handler. The ISR dispatch can be used, in some cases, when a callback is very simple or need a lower-latency. - Default value: - - No (disabled) Wi-Fi Contains: CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM Max number of WiFi static RX buffers Found in: Component config > Wi-Fi Set the number of WiFi static RX buffers. Each buffer takes approximately 1.6KB of RAM. The static rx buffers are allocated when esp_wifi_init is called, they are not freed until esp_wifi_deinit is called. WiFi hardware use these buffers to receive all 802.11 frames. A higher number may allow higher throughput but increases memory use. If ESP_WIFI_AMPDU_RX_ENABLED is enabled, this value is recommended to set equal or bigger than ESP_WIFI_RX_BA_WIN in order to achieve better throughput and compatibility with both stations and APs. - Range: - - from 2 to 128 if SOC_WIFI_HE_SUPPORT - Default value: - CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM Max number of WiFi dynamic RX buffers Found in: Component config > Wi-Fi Set the number of WiFi dynamic RX buffers, 0 means unlimited RX buffers will be allocated (provided sufficient free RAM). The size of each dynamic RX buffer depends on the size of the received data frame. For each received data frame, the WiFi driver makes a copy to an RX buffer and then delivers it to the high layer TCP/IP stack. The dynamic RX buffer is freed after the higher layer has successfully received the data frame. For some applications, WiFi data frames may be received faster than the application can process them. In these cases we may run out of memory if RX buffer number is unlimited (0). If a dynamic RX buffer limit is set, it should be at least the number of static RX buffers. - Range: - - from 0 to 1024 if CONFIG_LWIP_WND_SCALE - Default value: - - 32 CONFIG_ESP_WIFI_TX_BUFFER Type of WiFi TX buffers Found in: Component config > Wi-Fi Select type of WiFi TX buffers: If "Static" is selected, WiFi TX buffers are allocated when WiFi is initialized and released when WiFi is de-initialized. The size of each static TX buffer is fixed to about 1.6KB. If "Dynamic" is selected, each WiFi TX buffer is allocated as needed when a data frame is delivered to the Wifi driver from the TCP/IP stack. The buffer is freed after the data frame has been sent by the WiFi driver. The size of each dynamic TX buffer depends on the length of each data frame sent by the TCP/IP layer. If PSRAM is enabled, "Static" should be selected to guarantee enough WiFi TX buffers. If PSRAM is disabled, "Dynamic" should be selected to improve the utilization of RAM. Available options: - Static (CONFIG_ESP_WIFI_STATIC_TX_BUFFER) - Dynamic (CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER) CONFIG_ESP_WIFI_STATIC_TX_BUFFER_NUM Max number of WiFi static TX buffers Found in: Component config > Wi-Fi Set the number of WiFi static TX buffers. Each buffer takes approximately 1.6KB of RAM. The static RX buffers are allocated when esp_wifi_init() is called, they are not released until esp_wifi_deinit() is called. For each transmitted data frame from the higher layer TCP/IP stack, the WiFi driver makes a copy of it in a TX buffer. For some applications especially UDP applications, the upper layer can deliver frames faster than WiFi layer can transmit. In these cases, we may run out of TX buffers. - Range: - - from 1 to 64 if CONFIG_ESP_WIFI_STATIC_TX_BUFFER - Default value: - CONFIG_ESP_WIFI_CACHE_TX_BUFFER_NUM Max number of WiFi cache TX buffers Found in: Component config > Wi-Fi Set the number of WiFi cache TX buffer number. For each TX packet from uplayer, such as LWIP etc, WiFi driver needs to allocate a static TX buffer and makes a copy of uplayer packet. If WiFi driver fails to allocate the static TX buffer, it caches the uplayer packets to a dedicated buffer queue, this option is used to configure the size of the cached TX queue. - Range: - - from 16 to 128 if CONFIG_SPIRAM - Default value: - - 32 if CONFIG_SPIRAM CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM Max number of WiFi dynamic TX buffers Found in: Component config > Wi-Fi Set the number of WiFi dynamic TX buffers. The size of each dynamic TX buffer is not fixed, it depends on the size of each transmitted data frame. For each transmitted frame from the higher layer TCP/IP stack, the WiFi driver makes a copy of it in a TX buffer. For some applications, especially UDP applications, the upper layer can deliver frames faster than WiFi layer can transmit. In these cases, we may run out of TX buffers. - Range: - - from 1 to 128 - Default value: - - 32 CONFIG_ESP_WIFI_MGMT_RX_BUFFER Type of WiFi RX MGMT buffers Found in: Component config > Wi-Fi Select type of WiFi RX MGMT buffers: If "Static" is selected, WiFi RX MGMT buffers are allocated when WiFi is initialized and released when WiFi is de-initialized. The size of each static RX MGMT buffer is fixed to about 500 Bytes. If "Dynamic" is selected, each WiFi RX MGMT buffer is allocated as needed when a MGMT data frame is received. The MGMT buffer is freed after the MGMT data frame has been processed by the WiFi driver. Available options: - Static (CONFIG_ESP_WIFI_STATIC_RX_MGMT_BUFFER) - Dynamic (CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUFFER) CONFIG_ESP_WIFI_RX_MGMT_BUF_NUM_DEF Max number of WiFi RX MGMT buffers Found in: Component config > Wi-Fi Set the number of WiFi RX_MGMT buffers. For Management buffers, the number of dynamic and static management buffers is the same. In order to prevent memory fragmentation, the management buffer type should be set to static first. - Range: - - from 1 to 10 - Default value: - - 5 CONFIG_ESP_WIFI_CSI_ENABLED WiFi CSI(Channel State Information) Found in: Component config > Wi-Fi Select this option to enable CSI(Channel State Information) feature. CSI takes about CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM KB of RAM. If CSI is not used, it is better to disable this feature in order to save memory. - Default value: - - No (disabled) CONFIG_ESP_WIFI_AMPDU_TX_ENABLED WiFi AMPDU TX Found in: Component config > Wi-Fi Select this option to enable AMPDU TX feature - Default value: - - Yes (enabled) CONFIG_ESP_WIFI_TX_BA_WIN WiFi AMPDU TX BA window size Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_AMPDU_TX_ENABLED Set the size of WiFi Block Ack TX window. Generally a bigger value means higher throughput but more memory. Most of time we should NOT change the default value unless special reason, e.g. test the maximum UDP TX throughput with iperf etc. For iperf test in shieldbox, the recommended value is 9~12. - Range: - - from 2 to 64 if SOC_WIFI_HE_SUPPORT && CONFIG_ESP_WIFI_AMPDU_TX_ENABLED - Default value: - - 6 CONFIG_ESP_WIFI_AMPDU_RX_ENABLED WiFi AMPDU RX Found in: Component config > Wi-Fi Select this option to enable AMPDU RX feature - Default value: - - Yes (enabled) CONFIG_ESP_WIFI_RX_BA_WIN WiFi AMPDU RX BA window size Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_AMPDU_RX_ENABLED Set the size of WiFi Block Ack RX window. Generally a bigger value means higher throughput and better compatibility but more memory. Most of time we should NOT change the default value unless special reason, e.g. test the maximum UDP RX throughput with iperf etc. For iperf test in shieldbox, the recommended value is 9~12. If PSRAM is used and WiFi memory is prefered to allocat in PSRAM first, the default and minimum value should be 16 to achieve better throughput and compatibility with both stations and APs. - Range: - - from 2 to 64 if SOC_WIFI_HE_SUPPORT && CONFIG_ESP_WIFI_AMPDU_RX_ENABLED - Default value: - CONFIG_ESP_WIFI_AMSDU_TX_ENABLED WiFi AMSDU TX Found in: Component config > Wi-Fi Select this option to enable AMSDU TX feature - Default value: - - No (disabled) if CONFIG_SPIRAM CONFIG_ESP_WIFI_NVS_ENABLED WiFi NVS flash Found in: Component config > Wi-Fi Select this option to enable WiFi NVS flash - Default value: - - Yes (enabled) CONFIG_ESP_WIFI_TASK_CORE_ID WiFi Task Core ID Found in: Component config > Wi-Fi Pinned WiFi task to core 0 or core 1. Available options: - Core 0 (CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0) - Core 1 (CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_1) CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN Max length of WiFi SoftAP Beacon Found in: Component config > Wi-Fi ESP-MESH utilizes beacon frames to detect and resolve root node conflicts (see documentation). However the default length of a beacon frame can simultaneously hold only five root node identifier structures, meaning that a root node conflict of up to five nodes can be detected at one time. In the occurence of more root nodes conflict involving more than five root nodes, the conflict resolution process will detect five of the root nodes, resolve the conflict, and re-detect more root nodes. This process will repeat until all root node conflicts are resolved. However this process can generally take a very long time. To counter this situation, the beacon frame length can be increased such that more root nodes can be detected simultaneously. Each additional root node will require 36 bytes and should be added ontop of the default beacon frame length of 752 bytes. For example, if you want to detect 10 root nodes simultaneously, you need to set the beacon frame length as 932 (752+36*5). Setting a longer beacon length also assists with debugging as the conflicting root nodes can be identified more quickly. - Range: - - from 752 to 1256 - Default value: - - 752 CONFIG_ESP_WIFI_MGMT_SBUF_NUM WiFi mgmt short buffer number Found in: Component config > Wi-Fi Set the number of WiFi management short buffer. - Range: - - from 6 to 32 - Default value: - - 32 CONFIG_ESP_WIFI_IRAM_OPT WiFi IRAM speed optimization Found in: Component config > Wi-Fi Select this option to place frequently called Wi-Fi library functions in IRAM. When this option is disabled, more than 10Kbytes of IRAM memory will be saved but Wi-Fi throughput will be reduced. - Default value: - - No (disabled) if CONFIG_BT_ENABLED && CONFIG_SPIRAM - Yes (enabled) CONFIG_ESP_WIFI_EXTRA_IRAM_OPT WiFi EXTRA IRAM speed optimization Found in: Component config > Wi-Fi Select this option to place additional frequently called Wi-Fi library functions in IRAM. When this option is disabled, more than 5Kbytes of IRAM memory will be saved but Wi-Fi throughput will be reduced. - Default value: - - No (disabled) CONFIG_ESP_WIFI_RX_IRAM_OPT WiFi RX IRAM speed optimization Found in: Component config > Wi-Fi Select this option to place frequently called Wi-Fi library RX functions in IRAM. When this option is disabled, more than 17Kbytes of IRAM memory will be saved but Wi-Fi performance will be reduced. - Default value: - - No (disabled) if CONFIG_BT_ENABLED && CONFIG_SPIRAM - Yes (enabled) CONFIG_ESP_WIFI_ENABLE_WPA3_SAE Enable WPA3-Personal Found in: Component config > Wi-Fi Select this option to allow the device to establish a WPA3-Personal connection with eligible AP's. PMF (Protected Management Frames) is a prerequisite feature for a WPA3 connection, it needs to be explicitly configured before attempting connection. Please refer to the Wi-Fi Driver API Guide for details. - Default value: - - Yes (enabled) CONFIG_ESP_WIFI_ENABLE_SAE_PK Enable SAE-PK Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_ENABLE_WPA3_SAE Select this option to enable SAE-PK - Default value: - - Yes (enabled) CONFIG_ESP_WIFI_SOFTAP_SAE_SUPPORT Enable WPA3 Personal(SAE) SoftAP Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_ENABLE_WPA3_SAE Select this option to enable SAE support in softAP mode. - Default value: - - Yes (enabled) CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA Enable OWE STA Found in: Component config > Wi-Fi Select this option to allow the device to establish OWE connection with eligible AP's. PMF (Protected Management Frames) is a prerequisite feature for a WPA3 connection, it needs to be explicitly configured before attempting connection. Please refer to the Wi-Fi Driver API Guide for details. - Default value: - - Yes (enabled) CONFIG_ESP_WIFI_SLP_IRAM_OPT WiFi SLP IRAM speed optimization Found in: Component config > Wi-Fi Select this option to place called Wi-Fi library TBTT process and receive beacon functions in IRAM. Some functions can be put in IRAM either by ESP_WIFI_IRAM_OPT and ESP_WIFI_RX_IRAM_OPT, or this one. If already enabled ESP_WIFI_IRAM_OPT, the other 7.3KB IRAM memory would be taken by this option. If already enabled ESP_WIFI_RX_IRAM_OPT, the other 1.3KB IRAM memory would be taken by this option. If neither of them are enabled, the other 7.4KB IRAM memory would be taken by this option. Wi-Fi power-save mode average current would be reduced if this option is enabled. CONFIG_ESP_WIFI_SLP_DEFAULT_MIN_ACTIVE_TIME Minimum active time Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_IRAM_OPT The minimum timeout for waiting to receive data, unit: milliseconds. - Range: - - from 8 to 60 if CONFIG_ESP_WIFI_SLP_IRAM_OPT - Default value: - CONFIG_ESP_WIFI_SLP_DEFAULT_MAX_ACTIVE_TIME Maximum keep alive time Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_IRAM_OPT The maximum time that wifi keep alive, unit: seconds. - Range: - - from 10 to 60 if CONFIG_ESP_WIFI_SLP_IRAM_OPT - Default value: - CONFIG_ESP_WIFI_FTM_ENABLE WiFi FTM Found in: Component config > Wi-Fi Enable feature Fine Timing Measurement for calculating WiFi Round-Trip-Time (RTT). - Default value: - - No (disabled) if SOC_WIFI_FTM_SUPPORT CONFIG_ESP_WIFI_FTM_INITIATOR_SUPPORT FTM Initiator support Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_FTM_ENABLE - Default value: - - Yes (enabled) if CONFIG_ESP_WIFI_FTM_ENABLE CONFIG_ESP_WIFI_FTM_RESPONDER_SUPPORT FTM Responder support Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_FTM_ENABLE - Default value: - - Yes (enabled) if CONFIG_ESP_WIFI_FTM_ENABLE CONFIG_ESP_WIFI_STA_DISCONNECTED_PM_ENABLE Power Management for station at disconnected Found in: Component config > Wi-Fi Select this option to enable power_management for station when disconnected. Chip will do modem-sleep when rf module is not in use any more. - Default value: - - Yes (enabled) CONFIG_ESP_WIFI_GCMP_SUPPORT WiFi GCMP Support(GCMP128 and GCMP256) Found in: Component config > Wi-Fi Select this option to enable GCMP support. GCMP support is compulsory for WiFi Suite-B support. - Default value: - - No (disabled) if SOC_WIFI_GCMP_SUPPORT CONFIG_ESP_WIFI_GMAC_SUPPORT WiFi GMAC Support(GMAC128 and GMAC256) Found in: Component config > Wi-Fi Select this option to enable GMAC support. GMAC support is compulsory for WiFi 192 bit certification. - Default value: - - No (disabled) CONFIG_ESP_WIFI_SOFTAP_SUPPORT WiFi SoftAP Support Found in: Component config > Wi-Fi WiFi module can be compiled without SoftAP to save code size. - Default value: - - Yes (enabled) CONFIG_ESP_WIFI_ENHANCED_LIGHT_SLEEP WiFi modem automatically receives the beacon Found in: Component config > Wi-Fi The wifi modem automatically receives the beacon frame during light sleep. - Default value: - - No (disabled) if CONFIG_ESP_PHY_MAC_BB_PD && SOC_PM_SUPPORT_BEACON_WAKEUP CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT Wifi sleep optimize when beacon lost Found in: Component config > Wi-Fi Enable wifi sleep optimization when beacon loss occurs and immediately enter sleep mode when the WiFi module detects beacon loss. CONFIG_ESP_WIFI_SLP_BEACON_LOST_TIMEOUT Beacon loss timeout Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT Timeout time for close rf phy when beacon loss occurs, Unit: 1024 microsecond. - Range: - - from 5 to 100 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT - Default value: - CONFIG_ESP_WIFI_SLP_BEACON_LOST_THRESHOLD Maximum number of consecutive lost beacons allowed Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT Maximum number of consecutive lost beacons allowed, WiFi keeps Rx state when the number of consecutive beacons lost is greater than the given threshold. - Range: - - from 0 to 8 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT - Default value: - CONFIG_ESP_WIFI_SLP_PHY_ON_DELTA_EARLY_TIME Delta early time for RF PHY on Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT Delta early time for rf phy on, When the beacon is lost, the next rf phy on will be earlier the time specified by the configuration item, Unit: 32 microsecond. - Range: - - from 0 to 100 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT - Default value: - CONFIG_ESP_WIFI_SLP_PHY_OFF_DELTA_TIMEOUT_TIME Delta timeout time for RF PHY off Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT Delta timeout time for rf phy off, When the beacon is lost, the next rf phy off will be delayed for the time specified by the configuration item. Unit: 1024 microsecond. - Range: - - from 0 to 8 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT - Default value: - CONFIG_ESP_WIFI_ESPNOW_MAX_ENCRYPT_NUM Maximum espnow encrypt peers number Found in: Component config > Wi-Fi Maximum number of encrypted peers supported by espnow. The number of hardware keys for encryption is fixed. And the espnow and SoftAP share the same hardware keys. So this configuration will affect the maximum connection number of SoftAP. Maximum espnow encrypted peers number + maximum number of connections of SoftAP = Max hardware keys number. When using ESP mesh, this value should be set to a maximum of 6. - Range: - - from 0 to 17 - Default value: - - 7 CONFIG_ESP_WIFI_NAN_ENABLE WiFi Aware Found in: Component config > Wi-Fi Enable WiFi Aware (NAN) feature. - Default value: - - No (disabled) CONFIG_ESP_WIFI_ENABLE_WIFI_TX_STATS Enable Wi-Fi transmission statistics Found in: Component config > Wi-Fi Enable Wi-Fi transmission statistics. Total support 4 access category. Each access category will use 346 bytes memory. - Default value: - - Yes (enabled) if SOC_WIFI_HE_SUPPORT CONFIG_ESP_WIFI_MBEDTLS_CRYPTO Use MbedTLS crypto APIs Found in: Component config > Wi-Fi Select this option to enable the use of MbedTLS crypto APIs. The internal crypto support within the supplicant is limited and may not suffice for all new security features, including WPA3. It is recommended to always keep this option enabled. Additionally, note that MbedTLS can leverage hardware acceleration if available, resulting in significantly faster cryptographic operations. - Default value: - - Yes (enabled) CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT Use MbedTLS TLS client for WiFi Enterprise connection Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_MBEDTLS_CRYPTO Select this option to use MbedTLS TLS client for WPA2 enterprise connection. Please note that from MbedTLS-3.0 onwards, MbedTLS does not support SSL-3.0 TLS-v1.0, TLS-v1.1 versions. Incase your server is using one of these version, it is advisable to update your server. Please disable this option for compatibilty with older TLS versions. - Default value: - - Yes (enabled) CONFIG_ESP_WIFI_WAPI_PSK Enable WAPI PSK support Found in: Component config > Wi-Fi Select this option to enable WAPI-PSK which is a Chinese National Standard Encryption for Wireless LANs (GB 15629.11-2003). - Default value: - - No (disabled) CONFIG_ESP_WIFI_SUITE_B_192 Enable NSA suite B support with 192 bit key Found in: Component config > Wi-Fi Select this option to enable 192 bit NSA suite-B. This is necessary to support WPA3 192 bit security. - Default value: - - No (disabled) if SOC_WIFI_GCMP_SUPPORT CONFIG_ESP_WIFI_11KV_SUPPORT Enable 802.11k, 802.11v APIs Support Found in: Component config > Wi-Fi Select this option to enable 802.11k 802.11v APIs(RRM and BTM support). Only APIs which are helpful for network assisted roaming are supported for now. Enable this option with BTM and RRM enabled in sta config to make device ready for network assisted roaming. BTM: BSS transition management enables an AP to request a station to transition to a specific AP, or to indicate to a station a set of preferred APs. RRM: Radio measurements enable STAs to understand the radio environment, it enables STAs to observe and gather data on radio link performance and on the radio environment. Current implementation adds beacon report, link measurement, neighbor report. - Default value: - - No (disabled) CONFIG_ESP_WIFI_SCAN_CACHE Keep scan results in cache Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_11KV_SUPPORT Keep scan results in cache, if not enabled, those will be flushed immediately. - Default value: - - No (disabled) if CONFIG_ESP_WIFI_11KV_SUPPORT CONFIG_ESP_WIFI_MBO_SUPPORT Enable Multi Band Operation Certification Support Found in: Component config > Wi-Fi Select this option to enable WiFi Multiband operation certification support. - Default value: - - No (disabled) CONFIG_ESP_WIFI_DPP_SUPPORT Enable DPP support Found in: Component config > Wi-Fi Select this option to enable WiFi Easy Connect Support. - Default value: - - No (disabled) CONFIG_ESP_WIFI_11R_SUPPORT Enable 802.11R (Fast Transition) Support Found in: Component config > Wi-Fi Select this option to enable WiFi Fast Transition Support. - Default value: - - No (disabled) CONFIG_ESP_WIFI_WPS_SOFTAP_REGISTRAR Add WPS Registrar support in SoftAP mode Found in: Component config > Wi-Fi Select this option to enable WPS registrar support in softAP mode. - Default value: - - No (disabled) CONFIG_ESP_WIFI_ENABLE_WIFI_RX_STATS Enable Wi-Fi reception statistics Found in: Component config > Wi-Fi Enable Wi-Fi reception statistics. Total support 2 access category. Each access category will use 190 bytes memory. - Default value: - - Yes (enabled) if SOC_WIFI_HE_SUPPORT CONFIG_ESP_WIFI_ENABLE_WIFI_RX_MU_STATS Enable Wi-Fi DL MU-MIMO and DL OFDMA reception statistics Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_ENABLE_WIFI_RX_STATS Enable Wi-Fi DL MU-MIMO and DL OFDMA reception statistics. Will use 10932 bytes memory. - Default value: - - Yes (enabled) if CONFIG_ESP_WIFI_ENABLE_WIFI_RX_STATS WPS Configuration Options Contains: CONFIG_ESP_WIFI_WPS_STRICT Strictly validate all WPS attributes Found in: Component config > Wi-Fi > WPS Configuration Options Select this option to enable validate each WPS attribute rigorously. Disabling this add the workaorunds with various APs. Enabling this may cause inter operability issues with some APs. - Default value: - - No (disabled) CONFIG_ESP_WIFI_WPS_PASSPHRASE Get WPA2 passphrase in WPS config Found in: Component config > Wi-Fi > WPS Configuration Options Select this option to get passphrase during WPS configuration. This option fakes the virtual display capabilites to get the configuration in passphrase mode. Not recommanded to be used since WPS credentials should not be shared to other devices, making it in readable format increases that risk, also passphrase requires pbkdf2 to convert in psk. - Default value: - - No (disabled) CONFIG_ESP_WIFI_DEBUG_PRINT Print debug messages from WPA Supplicant Found in: Component config > Wi-Fi Select this option to print logging information from WPA supplicant, this includes handshake information and key hex dumps depending on the project logging level. Enabling this could increase the build size ~60kb depending on the project logging level. - Default value: - - No (disabled) CONFIG_ESP_WIFI_TESTING_OPTIONS Add DPP testing code Found in: Component config > Wi-Fi Select this to enable unity test for DPP. - Default value: - - No (disabled) CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT Enable enterprise option Found in: Component config > Wi-Fi Select this to enable/disable enterprise connection support. disabling this will reduce binary size. disabling this will disable the use of any esp_wifi_sta_wpa2_ent_* (as APIs will be meaningless) - Default value: - - Yes (enabled) CONFIG_ESP_WIFI_ENT_FREE_DYNAMIC_BUFFER Free dynamic buffers during WiFi enterprise connection Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT Select this configuration to free dynamic buffers during WiFi enterprise connection. This will enable chip to reduce heap consumption during WiFi enterprise connection. - Default value: - - No (disabled) Core dump Contains: CONFIG_ESP_COREDUMP_TO_FLASH_OR_UART Data destination Found in: Component config > Core dump Select place to store core dump: flash, uart or none (to disable core dumps generation). Core dumps to Flash are not available if PSRAM is used for task stacks. If core dump is configured to be stored in flash and custom partition table is used add corresponding entry to your CSV. For examples, please see predefined partition table CSV descriptions in the components/partition_table directory. Available options: - Flash (CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH) - UART (CONFIG_ESP_COREDUMP_ENABLE_TO_UART) - None (CONFIG_ESP_COREDUMP_ENABLE_TO_NONE) CONFIG_ESP_COREDUMP_DATA_FORMAT Core dump data format Found in: Component config > Core dump Select the data format for core dump. Available options: - Binary format (CONFIG_ESP_COREDUMP_DATA_FORMAT_BIN) - ELF format (CONFIG_ESP_COREDUMP_DATA_FORMAT_ELF) CONFIG_ESP_COREDUMP_CHECKSUM Core dump data integrity check Found in: Component config > Core dump Select the integrity check for the core dump. Available options: - Use CRC32 for integrity verification (CONFIG_ESP_COREDUMP_CHECKSUM_CRC32) - Use SHA256 for integrity verification (CONFIG_ESP_COREDUMP_CHECKSUM_SHA256) CONFIG_ESP_COREDUMP_CHECK_BOOT Check core dump data integrity on boot Found in: Component config > Core dump When enabled, if any data are found on the flash core dump partition, they will be checked by calculating their checksum. - Default value: - - Yes (enabled) if CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH CONFIG_ESP_COREDUMP_LOGS Enable coredump logs for debugging Found in: Component config > Core dump Enable/disable coredump logs. Logs strings from espcoredump component are placed in DRAM. Disabling these helps to save ~5KB of internal memory. CONFIG_ESP_COREDUMP_MAX_TASKS_NUM Maximum number of tasks Found in: Component config > Core dump Maximum number of tasks snapshots in core dump. CONFIG_ESP_COREDUMP_UART_DELAY Delay before print to UART Found in: Component config > Core dump Config delay (in ms) before printing core dump to UART. Delay can be interrupted by pressing Enter key. - Default value: - CONFIG_ESP_COREDUMP_STACK_SIZE Reserved stack size Found in: Component config > Core dump Size of the memory to be reserved for core dump stack. If 0 core dump process will run on the stack of crashed task/ISR, otherwise special stack will be allocated. To ensure that core dump itself will not overflow task/ISR stack set this to the value above 800. NOTE: It eats DRAM. CONFIG_ESP_COREDUMP_DECODE Handling of UART core dumps in IDF Monitor Found in: Component config > Core dump Available options: - Decode and show summary (info_corefile) (CONFIG_ESP_COREDUMP_DECODE_INFO) - Don't decode (CONFIG_ESP_COREDUMP_DECODE_DISABLE) FAT Filesystem support Contains: CONFIG_FATFS_VOLUME_COUNT Number of volumes Found in: Component config > FAT Filesystem support Number of volumes (logical drives) to use. - Range: - - from 1 to 10 - Default value: - - 2 CONFIG_FATFS_LONG_FILENAMES Long filename support Found in: Component config > FAT Filesystem support Support long filenames in FAT. Long filename data increases memory usage. FATFS can be configured to store the buffer for long filename data in stack or heap. Available options: - No long filenames (CONFIG_FATFS_LFN_NONE) - Long filename buffer in heap (CONFIG_FATFS_LFN_HEAP) - Long filename buffer on stack (CONFIG_FATFS_LFN_STACK) CONFIG_FATFS_SECTOR_SIZE Sector size Found in: Component config > FAT Filesystem support Specify the size of the sector in bytes for FATFS partition generator. Available options: - 512 (CONFIG_FATFS_SECTOR_512) - 4096 (CONFIG_FATFS_SECTOR_4096) CONFIG_FATFS_CHOOSE_CODEPAGE OEM Code Page Found in: Component config > FAT Filesystem support OEM code page used for file name encodings. If "Dynamic" is selected, code page can be chosen at runtime using f_setcp function. Note that choosing this option will increase application size by ~480kB. Available options: - Dynamic (all code pages supported) (CONFIG_FATFS_CODEPAGE_DYNAMIC) - US (CP437) (CONFIG_FATFS_CODEPAGE_437) - Arabic (CP720) (CONFIG_FATFS_CODEPAGE_720) - Greek (CP737) (CONFIG_FATFS_CODEPAGE_737) - KBL (CP771) (CONFIG_FATFS_CODEPAGE_771) - Baltic (CP775) (CONFIG_FATFS_CODEPAGE_775) - Latin 1 (CP850) (CONFIG_FATFS_CODEPAGE_850) - Latin 2 (CP852) (CONFIG_FATFS_CODEPAGE_852) - Cyrillic (CP855) (CONFIG_FATFS_CODEPAGE_855) - Turkish (CP857) (CONFIG_FATFS_CODEPAGE_857) - Portugese (CP860) (CONFIG_FATFS_CODEPAGE_860) - Icelandic (CP861) (CONFIG_FATFS_CODEPAGE_861) - Hebrew (CP862) (CONFIG_FATFS_CODEPAGE_862) - Canadian French (CP863) (CONFIG_FATFS_CODEPAGE_863) - Arabic (CP864) (CONFIG_FATFS_CODEPAGE_864) - Nordic (CP865) (CONFIG_FATFS_CODEPAGE_865) - Russian (CP866) (CONFIG_FATFS_CODEPAGE_866) - Greek 2 (CP869) (CONFIG_FATFS_CODEPAGE_869) - Japanese (DBCS) (CP932) (CONFIG_FATFS_CODEPAGE_932) - Simplified Chinese (DBCS) (CP936) (CONFIG_FATFS_CODEPAGE_936) - Korean (DBCS) (CP949) (CONFIG_FATFS_CODEPAGE_949) - Traditional Chinese (DBCS) (CP950) (CONFIG_FATFS_CODEPAGE_950) CONFIG_FATFS_MAX_LFN Max long filename length Found in: Component config > FAT Filesystem support Maximum long filename length. Can be reduced to save RAM. CONFIG_FATFS_API_ENCODING API character encoding Found in: Component config > FAT Filesystem support Choose encoding for character and string arguments/returns when using FATFS APIs. The encoding of arguments will usually depend on text editor settings. Available options: - API uses ANSI/OEM encoding (CONFIG_FATFS_API_ENCODING_ANSI_OEM) - API uses UTF-8 encoding (CONFIG_FATFS_API_ENCODING_UTF_8) CONFIG_FATFS_FS_LOCK Number of simultaneously open files protected by lock function Found in: Component config > FAT Filesystem support This option sets the FATFS configuration value _FS_LOCK. The option _FS_LOCK switches file lock function to control duplicated file open and illegal operation to open objects. * 0: Disable file lock function. To avoid volume corruption, application should avoid illegal open, remove and rename to the open objects. * >0: Enable file lock function. The value defines how many files/sub-directories can be opened simultaneously under file lock control. Note that the file lock control is independent of re-entrancy. - Range: - - from 0 to 65535 - Default value: - - 0 CONFIG_FATFS_TIMEOUT_MS Timeout for acquiring a file lock, ms Found in: Component config > FAT Filesystem support This option sets FATFS configuration value _FS_TIMEOUT, scaled to milliseconds. Sets the number of milliseconds FATFS will wait to acquire a mutex when operating on an open file. For example, if one task is performing a lenghty operation, another task will wait for the first task to release the lock, and time out after amount of time set by this option. - Default value: - - 10000 CONFIG_FATFS_PER_FILE_CACHE Use separate cache for each file Found in: Component config > FAT Filesystem support This option affects FATFS configuration value _FS_TINY. If this option is set, _FS_TINY is 0, and each open file has its own cache, size of the cache is equal to the _MAX_SS variable (512 or 4096 bytes). This option uses more RAM if more than 1 file is open, but needs less reads and writes to the storage for some operations. If this option is not set, _FS_TINY is 1, and single cache is used for all open files, size is also equal to _MAX_SS variable. This reduces the amount of heap used when multiple files are open, but increases the number of read and write operations which FATFS needs to make. - Default value: - - Yes (enabled) CONFIG_FATFS_ALLOC_PREFER_EXTRAM Perfer external RAM when allocating FATFS buffers Found in: Component config > FAT Filesystem support When the option is enabled, internal buffers used by FATFS will be allocated from external RAM. If the allocation from external RAM fails, the buffer will be allocated from the internal RAM. Disable this option if optimizing for performance. Enable this option if optimizing for internal memory size. - Default value: - - Yes (enabled) if CONFIG_SPIRAM_USE_CAPS_ALLOC || CONFIG_SPIRAM_USE_MALLOC CONFIG_FATFS_USE_FASTSEEK Enable fast seek algorithm when using lseek function through VFS FAT Found in: Component config > FAT Filesystem support The fast seek feature enables fast backward/long seek operations without FAT access by using an in-memory CLMT (cluster link map table). Please note, fast-seek is only allowed for read-mode files, if a file is opened in write-mode, the seek mechanism will automatically fallback to the default implementation. - Default value: - - No (disabled) CONFIG_FATFS_FAST_SEEK_BUFFER_SIZE Fast seek CLMT buffer size Found in: Component config > FAT Filesystem support > CONFIG_FATFS_USE_FASTSEEK If fast seek algorithm is enabled, this defines the size of CLMT buffer used by this algorithm in 32-bit word units. This value should be chosen based on prior knowledge of maximum elements of each file entry would store. - Default value: - CONFIG_FATFS_VFS_FSTAT_BLKSIZE Default block size Found in: Component config > FAT Filesystem support If set to 0, the 'newlib' library's default size (BLKSIZ) is used (128 B). If set to a non-zero value, the value is used as the block size. Default file buffer size is set to this value and the buffer is allocated when first attempt of reading/writing to a file is made. Increasing this value improves fread() speed, however the heap usage is increased as well. NOTE: The block size value is shared by all the filesystem functions accessing target media for given file descriptor! See 'Improving I/O performance' section of 'Maximizing Execution Speed' documentation page for more details. - Default value: - - 0 CONFIG_FATFS_IMMEDIATE_FSYNC Enable automatic f_sync Found in: Component config > FAT Filesystem support Enables automatic calling of f_sync() to flush recent file changes after each call of vfs_fat_write(), vfs_fat_pwrite(), vfs_fat_link(), vfs_fat_truncate() and vfs_fat_ftruncate() functions. This feature improves file-consistency and size reporting accuracy for the FatFS, at a price on decreased performance due to frequent disk operations - Default value: - - No (disabled) FreeRTOS Contains: Kernel Contains: CONFIG_FREERTOS_SMP Run the Amazon SMP FreeRTOS kernel instead (FEATURE UNDER DEVELOPMENT) Found in: Component config > FreeRTOS > Kernel Amazon has released an SMP version of the FreeRTOS Kernel which can be found via the following link: https://github.com/FreeRTOS/FreeRTOS-Kernel/tree/smp IDF has added an experimental port of this SMP kernel located in components/freertos/FreeRTOS-Kernel-SMP. Enabling this option will cause IDF to use the Amazon SMP kernel. Note that THIS FEATURE IS UNDER ACTIVE DEVELOPMENT, users use this at their own risk. Leaving this option disabled will mean the IDF FreeRTOS kernel is used instead, which is located in: components/freertos/FreeRTOS-Kernel. Both kernel versions are SMP capable, but differ in their implementation and features. - Default value: - - No (disabled) CONFIG_FREERTOS_UNICORE Run FreeRTOS only on first core Found in: Component config > FreeRTOS > Kernel This version of FreeRTOS normally takes control of all cores of the CPU. Select this if you only want to start it on the first core. This is needed when e.g. another process needs complete control over the second core. CONFIG_FREERTOS_HZ configTICK_RATE_HZ Found in: Component config > FreeRTOS > Kernel Sets the FreeRTOS tick interrupt frequency in Hz (see configTICK_RATE_HZ documentation for more details). - Range: - - from 1 to 1000 - Default value: - - 100 CONFIG_FREERTOS_OPTIMIZED_SCHEDULER configUSE_PORT_OPTIMISED_TASK_SELECTION Found in: Component config > FreeRTOS > Kernel Enables port specific task selection method. This option can speed up the search of ready tasks when scheduling (see configUSE_PORT_OPTIMISED_TASK_SELECTION documentation for more details). CONFIG_FREERTOS_CHECK_STACKOVERFLOW configCHECK_FOR_STACK_OVERFLOW Found in: Component config > FreeRTOS > Kernel Enables FreeRTOS to check for stack overflows (see configCHECK_FOR_STACK_OVERFLOW documentation for more details). Note: If users do not provide their own vApplicationStackOverflowHook()function, a default function will be provided by ESP-IDF. Available options: - No checking (CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE) Do not check for stack overflows (configCHECK_FOR_STACK_OVERFLOW = 0) - Check by stack pointer value (Method 1) (CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL) Check for stack overflows on each context switch by checking if the stack pointer is in a valid range. Quick but does not detect stack overflows that happened between context switches (configCHECK_FOR_STACK_OVERFLOW = 1) - Check using canary bytes (Method 2) (CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY) Places some magic bytes at the end of the stack area and on each context switch, check if these bytes are still intact. More thorough than just checking the pointer, but also slightly slower. (configCHECK_FOR_STACK_OVERFLOW = 2) CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS configNUM_THREAD_LOCAL_STORAGE_POINTERS Found in: Component config > FreeRTOS > Kernel Set the number of thread local storage pointers in each task (see configNUM_THREAD_LOCAL_STORAGE_POINTERS documentation for more details). Note: In ESP-IDF, this value must be at least 1. Index 0 is reserved for use by the pthreads API thread-local-storage. Other indexes can be used for any desired purpose. - Range: - - from 1 to 256 - Default value: - - 1 CONFIG_FREERTOS_IDLE_TASK_STACKSIZE configMINIMAL_STACK_SIZE (Idle task stack size) Found in: Component config > FreeRTOS > Kernel Sets the idle task stack size in bytes (see configMINIMAL_STACK_SIZE documentation for more details). Note: - ESP-IDF specifies stack sizes in bytes instead of words. - The default size is enough for most use cases. - The stack size may need to be increased above the default if the app installs idle or thread local storage cleanup hooks that use a lot of stack memory. - Conversely, the stack size can be reduced to the minimum if non of the idle features are used. - Range: - - from 768 to 32768 - Default value: - - 1536 CONFIG_FREERTOS_USE_IDLE_HOOK configUSE_IDLE_HOOK Found in: Component config > FreeRTOS > Kernel Enables the idle task application hook (see configUSE_IDLE_HOOK documentation for more details). Note: - The application must provide the hook function void vApplicationIdleHook( void ); - vApplicationIdleHook()is called from FreeRTOS idle task(s) - The FreeRTOS idle hook is NOT the same as the ESP-IDF Idle Hook, but both can be enabled simultaneously. - Default value: - - No (disabled) CONFIG_FREERTOS_USE_MINIMAL_IDLE_HOOK Use FreeRTOS minimal idle hook Found in: Component config > FreeRTOS > Kernel Enables the minimal idle task application hook (see configUSE_IDLE_HOOK documentation for more details). Note: - The application must provide the hook function void vApplicationMinimalIdleHook( void ); - vApplicationMinimalIdleHook()is called from FreeRTOS minimal idle task(s) - Default value: - - No (disabled) if CONFIG_FREERTOS_SMP CONFIG_FREERTOS_USE_TICK_HOOK configUSE_TICK_HOOK Found in: Component config > FreeRTOS > Kernel Enables the tick hook (see configUSE_TICK_HOOK documentation for more details). Note: - The application must provide the hook function void vApplicationTickHook( void ); - vApplicationTickHook()is called from FreeRTOS's tick handling function xTaskIncrementTick() - The FreeRTOS tick hook is NOT the same as the ESP-IDF Tick Interrupt Hook, but both can be enabled simultaneously. - Default value: - - No (disabled) CONFIG_FREERTOS_MAX_TASK_NAME_LEN configMAX_TASK_NAME_LEN Found in: Component config > FreeRTOS > Kernel Sets the maximum number of characters for task names (see configMAX_TASK_NAME_LEN documentation for more details). Note: For most uses, the default of 16 characters is sufficient. - Range: - - from 1 to 256 - Default value: - - 16 CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY configENABLE_BACKWARD_COMPATIBILITY Found in: Component config > FreeRTOS > Kernel Enable backward compatibility with APIs prior to FreeRTOS v8.0.0. (see configENABLE_BACKWARD_COMPATIBILITY documentation for more details). - Default value: - - No (disabled) CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME configTIMER_SERVICE_TASK_NAME Found in: Component config > FreeRTOS > Kernel Sets the timer task's name (see configTIMER_SERVICE_TASK_NAME documentation for more details). - Default value: - - "Tmr Svc" CONFIG_FREERTOS_TIMER_TASK_PRIORITY configTIMER_TASK_PRIORITY Found in: Component config > FreeRTOS > Kernel Sets the timer task's priority (see configTIMER_TASK_PRIORITY documentation for more details). - Range: - - from 1 to 25 - Default value: - - 1 CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH configTIMER_TASK_STACK_DEPTH Found in: Component config > FreeRTOS > Kernel Set the timer task's stack size (see configTIMER_TASK_STACK_DEPTH documentation for more details). - Range: - - from 1536 to 32768 - Default value: - - 2048 CONFIG_FREERTOS_TIMER_QUEUE_LENGTH configTIMER_QUEUE_LENGTH Found in: Component config > FreeRTOS > Kernel Set the timer task's command queue length (see configTIMER_QUEUE_LENGTH documentation for more details). - Range: - - from 5 to 20 - Default value: - - 10 CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE configQUEUE_REGISTRY_SIZE Found in: Component config > FreeRTOS > Kernel Set the size of the queue registry (see configQUEUE_REGISTRY_SIZE documentation for more details). Note: A value of 0 will disable queue registry functionality - Range: - - from 0 to 20 - Default value: - - 0 CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES configTASK_NOTIFICATION_ARRAY_ENTRIES Found in: Component config > FreeRTOS > Kernel Set the size of the task notification array of each task. When increasing this value, keep in mind that this means additional memory for each and every task on the system. However, task notifications in general are more light weight compared to alternatives such as semaphores. - Range: - - from 1 to 32 - Default value: - - 1 CONFIG_FREERTOS_USE_TRACE_FACILITY configUSE_TRACE_FACILITY Found in: Component config > FreeRTOS > Kernel Enables additional structure members and functions to assist with execution visualization and tracing (see configUSE_TRACE_FACILITY documentation for more details). - Default value: - - No (disabled) CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS configUSE_STATS_FORMATTING_FUNCTIONS Found in: Component config > FreeRTOS > Kernel > CONFIG_FREERTOS_USE_TRACE_FACILITY Set configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS to 1 to include the vTaskList()and vTaskGetRunTimeStats()functions in the build (see configUSE_STATS_FORMATTING_FUNCTIONS documentation for more details). - Default value: - - No (disabled) if CONFIG_FREERTOS_USE_TRACE_FACILITY CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID Enable display of xCoreID in vTaskList Found in: Component config > FreeRTOS > Kernel > CONFIG_FREERTOS_USE_TRACE_FACILITY > CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS If enabled, this will include an extra column when vTaskList is called to display the CoreID the task is pinned to (0,1) or -1 if not pinned. CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS configGENERATE_RUN_TIME_STATS Found in: Component config > FreeRTOS > Kernel Enables collection of run time statistics for each task (see configGENERATE_RUN_TIME_STATS documentation for more details). Note: The clock used for run time statistics can be configured in FREERTOS_RUN_TIME_STATS_CLK. - Default value: - - No (disabled) CONFIG_FREERTOS_RUN_TIME_COUNTER_TYPE configRUN_TIME_COUNTER_TYPE Found in: Component config > FreeRTOS > Kernel > CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS Sets the data type used for the FreeRTOS run time stats. A larger data type can be used to reduce the frequency of the counter overflowing. Available options: - uint32_t (CONFIG_FREERTOS_RUN_TIME_COUNTER_TYPE_U32) configRUN_TIME_COUNTER_TYPE is set to uint32_t - uint64_t (CONFIG_FREERTOS_RUN_TIME_COUNTER_TYPE_U64) configRUN_TIME_COUNTER_TYPE is set to uint64_t CONFIG_FREERTOS_USE_TICKLESS_IDLE configUSE_TICKLESS_IDLE Found in: Component config > FreeRTOS > Kernel If power management support is enabled, FreeRTOS will be able to put the system into light sleep mode when no tasks need to run for a number of ticks. This number can be set using FREERTOS_IDLE_TIME_BEFORE_SLEEP option. This feature is also known as "automatic light sleep". Note that timers created using esp_timer APIs may prevent the system from entering sleep mode, even when no tasks need to run. To skip unnecessary wake-up initialize a timer with the "skip_unhandled_events" option as true. If disabled, automatic light sleep support will be disabled. - Default value: - - No (disabled) if CONFIG_PM_ENABLE CONFIG_FREERTOS_IDLE_TIME_BEFORE_SLEEP configEXPECTED_IDLE_TIME_BEFORE_SLEEP Found in: Component config > FreeRTOS > Kernel > CONFIG_FREERTOS_USE_TICKLESS_IDLE FreeRTOS will enter light sleep mode if no tasks need to run for this number of ticks. You can enable PM_PROFILING feature in esp_pm components and dump the sleep status with esp_pm_dump_locks, if the proportion of rejected sleeps is too high, please increase this value to improve scheduling efficiency - Range: - - from 2 to 4294967295 if CONFIG_FREERTOS_USE_TICKLESS_IDLE - Default value: - Port Contains: CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER Wrap task functions Found in: Component config > FreeRTOS > Port If enabled, all FreeRTOS task functions will be enclosed in a wrapper function. If a task function mistakenly returns (i.e. does not delete), the call flow will return to the wrapper function. The wrapper function will then log an error and abort the application. This option is also required for GDB backtraces and C++ exceptions to work correctly inside top-level task functions. - Default value: - - Yes (enabled) CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK Enable stack overflow debug watchpoint Found in: Component config > FreeRTOS > Port FreeRTOS can check if a stack has overflown its bounds by checking either the value of the stack pointer or by checking the integrity of canary bytes. (See FREERTOS_CHECK_STACKOVERFLOW for more information.) These checks only happen on a context switch, and the situation that caused the stack overflow may already be long gone by then. This option will use the last debug memory watchpoint to allow breaking into the debugger (or panic'ing) as soon as any of the last 32 bytes on the stack of a task are overwritten. The side effect is that using gdb, you effectively have one hardware watchpoint less because the last one is overwritten as soon as a task switch happens. Another consequence is that due to alignment requirements of the watchpoint, the usable stack size decreases by up to 60 bytes. This is because the watchpoint region has to be aligned to its size and the size for the stack watchpoint in IDF is 32 bytes. This check only triggers if the stack overflow writes within 32 bytes near the end of the stack, rather than overshooting further, so it is worth combining this approach with one of the other stack overflow check methods. When this watchpoint is hit, gdb will stop with a SIGTRAP message. When no JTAG OCD is attached, esp-idf will panic on an unhandled debug exception. - Default value: - - No (disabled) CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS Enable thread local storage pointers deletion callbacks Found in: Component config > FreeRTOS > Port ESP-IDF provides users with the ability to free TLSP memory by registering TLSP deletion callbacks. These callbacks are automatically called by FreeRTOS when a task is deleted. When this option is turned on, the memory reserved for TLSPs in the TCB is doubled to make space for storing the deletion callbacks. If the user does not wish to use TLSP deletion callbacks then this option could be turned off to save space in the TCB memory. - Default value: - - Yes (enabled) CONFIG_FREERTOS_TASK_PRE_DELETION_HOOK Enable task pre-deletion hook Found in: Component config > FreeRTOS > Port Enable this option to make FreeRTOS call a user provided hook function right before it deletes a task (i.e., frees/releases a dynamically/statically allocated task's memory). This is useful if users want to know when a task is actually deleted (in case the task's deletion is delegated to the IDLE task). If this config option is enabled, users must define a void vTaskPreDeletionHook( void \* pxTCB )hook function in their application. CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP Enable static task clean up hook (DEPRECATED) Found in: Component config > FreeRTOS > Port THIS OPTION IS DEPRECATED. Use FREERTOS_TASK_PRE_DELETION_HOOK instead. Enable this option to make FreeRTOS call the static task clean up hook when a task is deleted. Note: Users will need to provide a void vPortCleanUpTCB ( void \*pxTCB )callback - Default value: - - No (disabled) CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER Check that mutex semaphore is given by owner task Found in: Component config > FreeRTOS > Port If enabled, assert that when a mutex semaphore is given, the task giving the semaphore is the task which is currently holding the mutex. CONFIG_FREERTOS_ISR_STACKSIZE ISR stack size Found in: Component config > FreeRTOS > Port The interrupt handlers have their own stack. The size of the stack can be defined here. Each processor has its own stack, so the total size occupied will be twice this. - Range: - - from 2096 to 32768 if CONFIG_ESP_COREDUMP_DATA_FORMAT_ELF - from 1536 to 32768 - Default value: - - - 1536 CONFIG_FREERTOS_INTERRUPT_BACKTRACE Enable backtrace from interrupt to task context Found in: Component config > FreeRTOS > Port If this option is enabled, interrupt stack frame will be modified to point to the code of the interrupted task as its return address. This helps the debugger (or the panic handler) show a backtrace from the interrupt to the task which was interrupted. This also works for nested interrupts: higher level interrupt stack can be traced back to the lower level interrupt. This option adds 4 instructions to the interrupt dispatching code. - Default value: - - Yes (enabled) CONFIG_FREERTOS_FPU_IN_ISR Use float in Level 1 ISR Found in: Component config > FreeRTOS > Port When enabled, the usage of float type is allowed inside Level 1 ISRs. Note that usage of float types in higher level interrupts is still not permitted. - Default value: - - No (disabled) CONFIG_FREERTOS_CORETIMER Tick timer source (Xtensa Only) Found in: Component config > FreeRTOS > Port FreeRTOS needs a timer with an associated interrupt to use as the main tick source to increase counters, run timers and do pre-emptive multitasking with. There are multiple timers available to do this, with different interrupt priorities. Available options: - Timer 0 (int 6, level 1) (CONFIG_FREERTOS_CORETIMER_0) Select this to use timer 0 - Timer 1 (int 15, level 3) (CONFIG_FREERTOS_CORETIMER_1) Select this to use timer 1 - SYSTIMER 0 (level 1) (CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL1) Select this to use systimer with the 1 interrupt priority. - SYSTIMER 0 (level 3) (CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL3) Select this to use systimer with the 3 interrupt priority. CONFIG_FREERTOS_RUN_TIME_STATS_CLK Choose the clock source for run time stats Found in: Component config > FreeRTOS > Port Choose the clock source for FreeRTOS run time stats. Options are CPU0's CPU Clock or the ESP Timer. Both clock sources are 32 bits. The CPU Clock can run at a higher frequency hence provide a finer resolution but will overflow much quicker. Note that run time stats are only valid until the clock source overflows. Available options: - Use ESP TIMER for run time stats (CONFIG_FREERTOS_RUN_TIME_STATS_USING_ESP_TIMER) ESP Timer will be used as the clock source for FreeRTOS run time stats. The ESP Timer runs at a frequency of 1MHz regardless of Dynamic Frequency Scaling. Therefore the ESP Timer will overflow in approximately 4290 seconds. - Use CPU Clock for run time stats (CONFIG_FREERTOS_RUN_TIME_STATS_USING_CPU_CLK) CPU Clock will be used as the clock source for the generation of run time stats. The CPU Clock has a frequency dependent on ESP_DEFAULT_CPU_FREQ_MHZ and Dynamic Frequency Scaling (DFS). Therefore the CPU Clock frequency can fluctuate between 80 to 240MHz. Run time stats generated using the CPU Clock represents the number of CPU cycles each task is allocated and DOES NOT reflect the amount of time each task runs for (as CPU clock frequency can change). If the CPU clock consistently runs at the maximum frequency of 240MHz, it will overflow in approximately 17 seconds. CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH Place FreeRTOS functions into Flash Found in: Component config > FreeRTOS > Port When enabled the selected Non-ISR FreeRTOS functions will be placed into Flash memory instead of IRAM. This saves up to 8KB of IRAM depending on which functions are used. - Default value: - - No (disabled) CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE Tests compliance with Vanilla FreeRTOS port*_CRITICAL calls Found in: Component config > FreeRTOS > Port If enabled, context of port*_CRITICAL calls (ISR or Non-ISR) would be checked to be in compliance with Vanilla FreeRTOS. e.g Calling port*_CRITICAL from ISR context would cause assert failure - Default value: - - No (disabled) Hardware Abstraction Layer (HAL) and Low Level (LL) Contains: CONFIG_HAL_DEFAULT_ASSERTION_LEVEL Default HAL assertion level Found in: Component config > Hardware Abstraction Layer (HAL) and Low Level (LL) Set the assert behavior / level for HAL component. HAL component assert level can be set separately, but the level can't exceed the system assertion level. e.g. If the system assertion is disabled, then the HAL assertion can't be enabled either. If the system assertion is enable, then the HAL assertion can still be disabled by this Kconfig option. Available options: - Same as system assertion level (CONFIG_HAL_ASSERTION_EQUALS_SYSTEM) - Disabled (CONFIG_HAL_ASSERTION_DISABLE) - Silent (CONFIG_HAL_ASSERTION_SILENT) - Enabled (CONFIG_HAL_ASSERTION_ENABLE) CONFIG_HAL_LOG_LEVEL HAL layer log verbosity Found in: Component config > Hardware Abstraction Layer (HAL) and Low Level (LL) Specify how much output to see in HAL logs. Available options: - No output (CONFIG_HAL_LOG_LEVEL_NONE) - Error (CONFIG_HAL_LOG_LEVEL_ERROR) - Warning (CONFIG_HAL_LOG_LEVEL_WARN) - Info (CONFIG_HAL_LOG_LEVEL_INFO) - Debug (CONFIG_HAL_LOG_LEVEL_DEBUG) - Verbose (CONFIG_HAL_LOG_LEVEL_VERBOSE) CONFIG_HAL_SYSTIMER_USE_ROM_IMPL Use ROM implementation of SysTimer HAL driver Found in: Component config > Hardware Abstraction Layer (HAL) and Low Level (LL) Enable this flag to use HAL functions from ROM instead of ESP-IDF. If keeping this as "n" in your project, you will have less free IRAM. If making this as "y" in your project, you will increase free IRAM, but you will lose the possibility to debug this module, and some new features will be added and bugs will be fixed in the IDF source but cannot be synced to ROM. - Default value: - - Yes (enabled) if ESP_ROM_HAS_HAL_SYSTIMER CONFIG_HAL_WDT_USE_ROM_IMPL Use ROM implementation of WDT HAL driver Found in: Component config > Hardware Abstraction Layer (HAL) and Low Level (LL) Enable this flag to use HAL functions from ROM instead of ESP-IDF. If keeping this as "n" in your project, you will have less free IRAM. If making this as "y" in your project, you will increase free IRAM, but you will lose the possibility to debug this module, and some new features will be added and bugs will be fixed in the IDF source but cannot be synced to ROM. - Default value: - - Yes (enabled) if ESP_ROM_HAS_HAL_WDT Heap memory debugging Contains: CONFIG_HEAP_CORRUPTION_DETECTION Heap corruption detection Found in: Component config > Heap memory debugging Enable heap poisoning features to detect heap corruption caused by out-of-bounds access to heap memory. See the "Heap Memory Debugging" page of the IDF documentation for a description of each level of heap corruption detection. Available options: - Basic (no poisoning) (CONFIG_HEAP_POISONING_DISABLED) - Light impact (CONFIG_HEAP_POISONING_LIGHT) - Comprehensive (CONFIG_HEAP_POISONING_COMPREHENSIVE) CONFIG_HEAP_TRACING_DEST Heap tracing Found in: Component config > Heap memory debugging Enables the heap tracing API defined in esp_heap_trace.h. This function causes a moderate increase in IRAM code side and a minor increase in heap function (malloc/free/realloc) CPU overhead, even when the tracing feature is not used. So it's best to keep it disabled unless tracing is being used. Available options: - Disabled (CONFIG_HEAP_TRACING_OFF) - Standalone (CONFIG_HEAP_TRACING_STANDALONE) - Host-based (CONFIG_HEAP_TRACING_TOHOST) CONFIG_HEAP_TRACING_STACK_DEPTH Heap tracing stack depth Found in: Component config > Heap memory debugging Number of stack frames to save when tracing heap operation callers. More stack frames uses more memory in the heap trace buffer (and slows down allocation), but can provide useful information. CONFIG_HEAP_USE_HOOKS Use allocation and free hooks Found in: Component config > Heap memory debugging Enable the user to implement function hooks triggered for each successful allocation and free. CONFIG_HEAP_TASK_TRACKING Enable heap task tracking Found in: Component config > Heap memory debugging Enables tracking the task responsible for each heap allocation. This function depends on heap poisoning being enabled and adds four more bytes of overhead for each block allocated. CONFIG_HEAP_TRACE_HASH_MAP Use hash map mechanism to access heap trace records Found in: Component config > Heap memory debugging Enable this flag to use a hash map to increase performance in handling heap trace records. Heap trace standalone supports storing records as a list, or a list + hash map. Using only a list takes less memory, but calls to 'free' will get slower as the list grows. This is particularly affected when using HEAP_TRACE_ALL mode. By using a list + hash map, calls to 'free' remain fast, at the cost of additional memory to store the hash map. - Default value: - - No (disabled) if CONFIG_HEAP_TRACING_STANDALONE CONFIG_HEAP_TRACE_HASH_MAP_IN_EXT_RAM Place hash map in external RAM Found in: Component config > Heap memory debugging > CONFIG_HEAP_TRACE_HASH_MAP When enabled this configuration forces the hash map to be placed in external RAM. - Default value: - - No (disabled) if CONFIG_HEAP_TRACE_HASH_MAP CONFIG_HEAP_TRACE_HASH_MAP_SIZE The number of entries in the hash map Found in: Component config > Heap memory debugging > CONFIG_HEAP_TRACE_HASH_MAP Defines the number of entries in the heap trace hashmap. Each entry takes 8 bytes. The bigger this number is, the better the performance. Recommended range: 200 - 2000. - Default value: - - 512 if CONFIG_HEAP_TRACE_HASH_MAP CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS Abort if memory allocation fails Found in: Component config > Heap memory debugging When enabled, if a memory allocation operation fails it will cause a system abort. - Default value: - - No (disabled) CONFIG_HEAP_TLSF_USE_ROM_IMPL Use ROM implementation of heap tlsf library Found in: Component config > Heap memory debugging Enable this flag to use heap functions from ROM instead of ESP-IDF. If keeping this as "n" in your project, you will have less free IRAM. If making this as "y" in your project, you will increase free IRAM, but you will lose the possibility to debug this module, and some new features will be added and bugs will be fixed in the IDF source but cannot be synced to ROM. - Default value: - - Yes (enabled) if ESP_ROM_HAS_HEAP_TLSF CONFIG_HEAP_PLACE_FUNCTION_INTO_FLASH Force the entire heap component to be placed in flash memory Found in: Component config > Heap memory debugging Enable this flag to save up RAM space by placing the heap component in the flash memory Note that it is only safe to enable this configuration if no functions from esp_heap_caps.h or esp_heap_trace.h are called from ISR. IEEE 802.15.4 Contains: CONFIG_IEEE802154_ENABLED IEEE802154 Enable Found in: Component config > IEEE 802.15.4 - Default value: - - Yes (enabled) if SOC_IEEE802154_SUPPORTED CONFIG_IEEE802154_RX_BUFFER_SIZE The number of 802.15.4 receive buffers Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED The number of 802.15.4 receive buffers - Range: - - from 2 to 100 if CONFIG_IEEE802154_ENABLED - Default value: - CONFIG_IEEE802154_CCA_MODE Clear Channel Assessment (CCA) mode Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED configure the CCA mode Available options: - Carrier sense only (CONFIG_IEEE802154_CCA_CARRIER) configure the CCA mode to Energy above threshold - Energy above threshold (CONFIG_IEEE802154_CCA_ED) configure the CCA mode to Energy above threshold - Carrier sense OR energy above threshold (CONFIG_IEEE802154_CCA_CARRIER_OR_ED) configure the CCA mode to Carrier sense OR energy above threshold - Carrier sense AND energy above threshold (CONFIG_IEEE802154_CCA_CARRIER_AND_ED) configure the CCA mode to Carrier sense AND energy above threshold CONFIG_IEEE802154_CCA_THRESHOLD CCA detection threshold Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED set the CCA threshold, in dB - Range: - - from -120 to 0 if CONFIG_IEEE802154_ENABLED - Default value: - - "-60" if CONFIG_IEEE802154_ENABLED CONFIG_IEEE802154_PENDING_TABLE_SIZE Pending table size Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED set the pending table size - Range: - - from 1 to 100 if CONFIG_IEEE802154_ENABLED - Default value: - CONFIG_IEEE802154_MULTI_PAN_ENABLE Enable multi-pan feature for frame filter Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED Enable IEEE802154 multi-pan - Default value: - - No (disabled) if CONFIG_IEEE802154_ENABLED CONFIG_IEEE802154_TIMING_OPTIMIZATION Enable throughput optimization Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED Enabling this option increases throughput by ~5% at the expense of ~2.1k IRAM code size increase. - Default value: - - No (disabled) if CONFIG_IEEE802154_ENABLED CONFIG_IEEE802154_SLEEP_ENABLE Enable IEEE802154 light sleep Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED Enabling this option allows the IEEE802.15.4 module to be powered down during automatic light sleep, which reduces current consumption. - Default value: - - No (disabled) if CONFIG_PM_ENABLE && CONFIG_IEEE802154_ENABLED CONFIG_IEEE802154_DEBUG Enable IEEE802154 Debug Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED Enabling this option allows different kinds of IEEE802154 debug output. All IEEE802154 debug features increase the size of the final binary. - Default value: - - No (disabled) if CONFIG_IEEE802154_ENABLED Contains: CONFIG_IEEE802154_ASSERT Enrich the assert information with IEEE802154 state and event Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG Enabling this option to add some probe codes in the driver, and these informations will be printed when assert. - Default value: - - No (disabled) if CONFIG_IEEE802154_DEBUG CONFIG_IEEE802154_RECORD_EVENT Enable record event information for debugging Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG Enabling this option to record event, when assert, the recorded event will be printed. - Default value: - - No (disabled) if CONFIG_IEEE802154_DEBUG CONFIG_IEEE802154_RECORD_EVENT_SIZE Record event table size Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG > CONFIG_IEEE802154_RECORD_EVENT set the record event table size - Range: - - from 1 to 50 if CONFIG_IEEE802154_RECORD_EVENT - Default value: - CONFIG_IEEE802154_RECORD_STATE Enable record state information for debugging Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG Enabling this option to record state, when assert, the recorded state will be printed. - Default value: - - No (disabled) if CONFIG_IEEE802154_DEBUG CONFIG_IEEE802154_RECORD_STATE_SIZE Record state table size Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG > CONFIG_IEEE802154_RECORD_STATE set the record state table size - Range: - - from 1 to 50 if CONFIG_IEEE802154_RECORD_STATE - Default value: - CONFIG_IEEE802154_RECORD_CMD Enable record command information for debugging Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG Enabling this option to record the command, when assert, the recorded command will be printed. - Default value: - - No (disabled) if CONFIG_IEEE802154_DEBUG CONFIG_IEEE802154_RECORD_CMD_SIZE Record command table size Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG > CONFIG_IEEE802154_RECORD_CMD set the record command table size - Range: - - from 1 to 50 if CONFIG_IEEE802154_RECORD_CMD - Default value: - CONFIG_IEEE802154_RECORD_ABORT Enable record abort information for debugging Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG Enabling this option to record the abort, when assert, the recorded abort will be printed. - Default value: - - No (disabled) if CONFIG_IEEE802154_DEBUG CONFIG_IEEE802154_RECORD_ABORT_SIZE Record abort table size Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG > CONFIG_IEEE802154_RECORD_ABORT set the record abort table size - Range: - - from 1 to 50 if CONFIG_IEEE802154_RECORD_ABORT - Default value: - CONFIG_IEEE802154_TXRX_STATISTIC Enable record tx/rx packets information for debugging Found in: Component config > IEEE 802.15.4 > CONFIG_IEEE802154_ENABLED > CONFIG_IEEE802154_DEBUG Enabling this option to record the tx and rx - Default value: - - No (disabled) if CONFIG_IEEE802154_DEBUG Log output Contains: CONFIG_LOG_DEFAULT_LEVEL Default log verbosity Found in: Component config > Log output Specify how much output to see in logs by default. You can set lower verbosity level at runtime using esp_log_level_set function. By default, this setting limits which log statements are compiled into the program. For example, selecting "Warning" would mean that changing log level to "Debug" at runtime will not be possible. To allow increasing log level above the default at runtime, see the next option. Available options: - No output (CONFIG_LOG_DEFAULT_LEVEL_NONE) - Error (CONFIG_LOG_DEFAULT_LEVEL_ERROR) - Warning (CONFIG_LOG_DEFAULT_LEVEL_WARN) - Info (CONFIG_LOG_DEFAULT_LEVEL_INFO) - Debug (CONFIG_LOG_DEFAULT_LEVEL_DEBUG) - Verbose (CONFIG_LOG_DEFAULT_LEVEL_VERBOSE) CONFIG_LOG_MAXIMUM_LEVEL Maximum log verbosity Found in: Component config > Log output This config option sets the highest log verbosity that it's possible to select at runtime by calling esp_log_level_set(). This level may be higher than the default verbosity level which is set when the app starts up. This can be used enable debugging output only at a critical point, for a particular tag, or to minimize startup time but then enable more logs once the firmware has loaded. Note that increasing the maximum available log level will increase the firmware binary size. This option only applies to logging from the app, the bootloader log level is fixed at compile time to the separate "Bootloader log verbosity" setting. Available options: - Same as default (CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT) - Error (CONFIG_LOG_MAXIMUM_LEVEL_ERROR) - Warning (CONFIG_LOG_MAXIMUM_LEVEL_WARN) - Info (CONFIG_LOG_MAXIMUM_LEVEL_INFO) - Debug (CONFIG_LOG_MAXIMUM_LEVEL_DEBUG) - Verbose (CONFIG_LOG_MAXIMUM_LEVEL_VERBOSE) CONFIG_LOG_MASTER_LEVEL Enable global master log level Found in: Component config > Log output Enables an additional global "master" log level check that occurs before a log tag cache lookup. This is useful if you want to compile in a lot of logs that are selectable at runtime, but avoid the performance hit during periods where you don't want log output. Examples include remote log forwarding, or disabling logs during a time-critical or CPU-intensive section and re-enabling them later. Results in larger program size depending on number of logs compiled in. If enabled, defaults to LOG_DEFAULT_LEVEL and can be set using esp_log_set_level_master(). This check takes precedence over ESP_LOG_LEVEL_LOCAL. - Default value: - - No (disabled) CONFIG_LOG_COLORS Use ANSI terminal colors in log output Found in: Component config > Log output Enable ANSI terminal color codes in bootloader output. In order to view these, your terminal program must support ANSI color codes. - Default value: - - Yes (enabled) CONFIG_LOG_TIMESTAMP_SOURCE Log Timestamps Found in: Component config > Log output Choose what sort of timestamp is displayed in the log output: - Milliseconds since boot is calulated from the RTOS tick count multiplied by the tick period. This time will reset after a software reboot. e.g. (90000) - System time is taken from POSIX time functions which use the chip's RTC and high resoultion timers to maintain an accurate time. The system time is initialized to 0 on startup, it can be set with an SNTP sync, or with POSIX time functions. This time will not reset after a software reboot. e.g. (00:01:30.000) - NOTE: Currently this will not get used in logging from binary blobs (i.e WiFi & Bluetooth libraries), these will always print milliseconds since boot. Available options: - Milliseconds Since Boot (CONFIG_LOG_TIMESTAMP_SOURCE_RTOS) - System Time (CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM) LWIP Contains: CONFIG_LWIP_ENABLE Enable LwIP stack Found in: Component config > LWIP Builds normally if selected. Excludes LwIP from build if unselected, even if it is a dependency of a component or application. Some applications can switch their IP stacks, e.g., when switching between chip and Linux targets (LwIP stack vs. Linux IP stack). Since the LwIP dependency cannot easily be excluded based on a Kconfig option, it has to be a dependency in all cases. This switch allows the LwIP stack to be built selectively, even if it is a dependency. - Default value: - - Yes (enabled) CONFIG_LWIP_LOCAL_HOSTNAME Local netif hostname Found in: Component config > LWIP The default name this device will report to other devices on the network. Could be updated at runtime with esp_netif_set_hostname() - Default value: - - "espressif" CONFIG_LWIP_NETIF_API Enable usage of standard POSIX APIs in LWIP Found in: Component config > LWIP If this feature is enabled, standard POSIX APIs: if_indextoname(), if_nametoindex() could be used to convert network interface index to name instead of IDF specific esp-netif APIs (such as esp_netif_get_netif_impl_name()) - Default value: - - No (disabled) CONFIG_LWIP_TCPIP_TASK_PRIO LWIP TCP/IP Task Priority Found in: Component config > LWIP LWIP tcpip task priority. In case of high throughput, this parameter could be changed up to (configMAX_PRIORITIES-1). - Range: - - from 1 to 24 - Default value: - - 18 CONFIG_LWIP_TCPIP_CORE_LOCKING Enable tcpip core locking Found in: Component config > LWIP If Enable tcpip core locking,Creates a global mutex that is held during TCPIP thread operations.Can be locked by client code to perform lwIP operations without changing into TCPIP thread using callbacks. See LOCK_TCPIP_CORE() and UNLOCK_TCPIP_CORE(). If disable tcpip core locking,TCP IP will perform tasks through context switching - Default value: - - No (disabled) CONFIG_LWIP_TCPIP_CORE_LOCKING_INPUT Enable tcpip core locking input Found in: Component config > LWIP > CONFIG_LWIP_TCPIP_CORE_LOCKING when LWIP_TCPIP_CORE_LOCKING is enabled, this lets tcpip_input() grab the mutex for input packets as well, instead of allocating a message and passing it to tcpip_thread. - Default value: - - No (disabled) if CONFIG_LWIP_TCPIP_CORE_LOCKING CONFIG_LWIP_CHECK_THREAD_SAFETY Checks that lwip API runs in expected context Found in: Component config > LWIP Enable to check that the project does not violate lwip thread safety. If enabled, all lwip functions that require thread awareness run an assertion to verify that the TCP/IP core functionality is either locked or accessed from the correct thread. - Default value: - - No (disabled) CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES Enable mDNS queries in resolving host name Found in: Component config > LWIP If this feature is enabled, standard API such as gethostbyname support .local addresses by sending one shot multicast mDNS query - Default value: - - Yes (enabled) CONFIG_LWIP_L2_TO_L3_COPY Enable copy between Layer2 and Layer3 packets Found in: Component config > LWIP If this feature is enabled, all traffic from layer2(WIFI Driver) will be copied to a new buffer before sending it to layer3(LWIP stack), freeing the layer2 buffer. Please be notified that the total layer2 receiving buffer is fixed and ESP32 currently supports 25 layer2 receiving buffer, when layer2 buffer runs out of memory, then the incoming packets will be dropped in hardware. The layer3 buffer is allocated from the heap, so the total layer3 receiving buffer depends on the available heap size, when heap runs out of memory, no copy will be sent to layer3 and packet will be dropped in layer2. Please make sure you fully understand the impact of this feature before enabling it. - Default value: - - No (disabled) CONFIG_LWIP_IRAM_OPTIMIZATION Enable LWIP IRAM optimization Found in: Component config > LWIP If this feature is enabled, some functions relating to RX/TX in LWIP will be put into IRAM, it can improve UDP/TCP throughput by >10% for single core mode, it doesn't help too much for dual core mode. On the other hand, it needs about 10KB IRAM for these optimizations. If this feature is disabled, all lwip functions will be put into FLASH. - Default value: - - No (disabled) CONFIG_LWIP_EXTRA_IRAM_OPTIMIZATION Enable LWIP IRAM optimization for TCP part Found in: Component config > LWIP If this feature is enabled, some tcp part functions relating to RX/TX in LWIP will be put into IRAM, it can improve TCP throughput. On the other hand, it needs about 17KB IRAM for these optimizations. - Default value: - - No (disabled) CONFIG_LWIP_TIMERS_ONDEMAND Enable LWIP Timers on demand Found in: Component config > LWIP If this feature is enabled, IGMP and MLD6 timers will be activated only when joining groups or receiving QUERY packets. This feature will reduce the power consumption for applications which do not use IGMP and MLD6. - Default value: - - Yes (enabled) CONFIG_LWIP_ND6 LWIP NDP6 Enable/Disable Found in: Component config > LWIP This option is used to disable the Network Discovery Protocol (NDP) if it is not required. Please use this option with caution, as the NDP is essential for IPv6 functionality within a local network. - Default value: - - Yes (enabled) CONFIG_LWIP_FORCE_ROUTER_FORWARDING LWIP Force Router Forwarding Enable/Disable Found in: Component config > LWIP > CONFIG_LWIP_ND6 This option is used to set the the router flag for the NA packets. When enabled, the router flag in NA packet will always set to 1, otherwise, never set router flag for NA packets. - Default value: - - No (disabled) CONFIG_LWIP_MAX_SOCKETS Max number of open sockets Found in: Component config > LWIP Sockets take up a certain amount of memory, and allowing fewer sockets to be open at the same time conserves memory. Specify the maximum amount of sockets here. The valid value is from 1 to 16. - Range: - - from 1 to 16 - Default value: - - 10 CONFIG_LWIP_USE_ONLY_LWIP_SELECT Support LWIP socket select() only (DEPRECATED) Found in: Component config > LWIP This option is deprecated. Do not use this option, use VFS_SUPPORT_SELECT instead. - Default value: - - No (disabled) CONFIG_LWIP_SO_LINGER Enable SO_LINGER processing Found in: Component config > LWIP Enabling this option allows SO_LINGER processing. l_onoff = 1,l_linger can set the timeout. If l_linger=0, When a connection is closed, TCP will terminate the connection. This means that TCP will discard any data packets stored in the socket send buffer and send an RST to the peer. If l_linger!=0,Then closesocket() calls to block the process until the remaining data packets has been sent or timed out. - Default value: - - No (disabled) CONFIG_LWIP_SO_REUSE Enable SO_REUSEADDR option Found in: Component config > LWIP Enabling this option allows binding to a port which remains in TIME_WAIT. - Default value: - - Yes (enabled) CONFIG_LWIP_SO_REUSE_RXTOALL SO_REUSEADDR copies broadcast/multicast to all matches Found in: Component config > LWIP > CONFIG_LWIP_SO_REUSE Enabling this option means that any incoming broadcast or multicast packet will be copied to all of the local sockets that it matches (may be more than one if SO_REUSEADDR is set on the socket.) This increases memory overhead as the packets need to be copied, however they are only copied per matching socket. You can safely disable it if you don't plan to receive broadcast or multicast traffic on more than one socket at a time. - Default value: - - Yes (enabled) CONFIG_LWIP_SO_RCVBUF Enable SO_RCVBUF option Found in: Component config > LWIP Enabling this option allows checking for available data on a netconn. - Default value: - - No (disabled) CONFIG_LWIP_NETBUF_RECVINFO Enable IP_PKTINFO option Found in: Component config > LWIP Enabling this option allows checking for the destination address of a received IPv4 Packet. - Default value: - - No (disabled) CONFIG_LWIP_IP_DEFAULT_TTL The value for Time-To-Live used by transport layers Found in: Component config > LWIP Set value for Time-To-Live used by transport layers. - Range: - - from 1 to 255 - Default value: - - 64 CONFIG_LWIP_IP4_FRAG Enable fragment outgoing IP4 packets Found in: Component config > LWIP Enabling this option allows fragmenting outgoing IP4 packets if their size exceeds MTU. - Default value: - - Yes (enabled) CONFIG_LWIP_IP6_FRAG Enable fragment outgoing IP6 packets Found in: Component config > LWIP Enabling this option allows fragmenting outgoing IP6 packets if their size exceeds MTU. - Default value: - - Yes (enabled) CONFIG_LWIP_IP4_REASSEMBLY Enable reassembly incoming fragmented IP4 packets Found in: Component config > LWIP Enabling this option allows reassemblying incoming fragmented IP4 packets. - Default value: - - No (disabled) CONFIG_LWIP_IP6_REASSEMBLY Enable reassembly incoming fragmented IP6 packets Found in: Component config > LWIP Enabling this option allows reassemblying incoming fragmented IP6 packets. - Default value: - - No (disabled) CONFIG_LWIP_IP_REASS_MAX_PBUFS The maximum amount of pbufs waiting to be reassembled Found in: Component config > LWIP Set the maximum amount of pbufs waiting to be reassembled. - Range: - - from 10 to 100 - Default value: - - 10 CONFIG_LWIP_IP_FORWARD Enable IP forwarding Found in: Component config > LWIP Enabling this option allows packets forwarding across multiple interfaces. - Default value: - - No (disabled) CONFIG_LWIP_IPV4_NAPT Enable NAT (new/experimental) Found in: Component config > LWIP > CONFIG_LWIP_IP_FORWARD Enabling this option allows Network Address and Port Translation. - Default value: - - No (disabled) if CONFIG_LWIP_IP_FORWARD CONFIG_LWIP_IPV4_NAPT_PORTMAP Enable NAT Port Mapping (new/experimental) Found in: Component config > LWIP > CONFIG_LWIP_IP_FORWARD > CONFIG_LWIP_IPV4_NAPT Enabling this option allows Port Forwarding or Port mapping. - Default value: - - Yes (enabled) if CONFIG_LWIP_IPV4_NAPT CONFIG_LWIP_STATS Enable LWIP statistics Found in: Component config > LWIP Enabling this option allows LWIP statistics - Default value: - - No (disabled) CONFIG_LWIP_ESP_GRATUITOUS_ARP Send gratuitous ARP periodically Found in: Component config > LWIP Enable this option allows to send gratuitous ARP periodically. This option solve the compatibility issues.If the ARP table of the AP is old, and the AP doesn't send ARP request to update it's ARP table, this will lead to the STA sending IP packet fail. Thus we send gratuitous ARP periodically to let AP update it's ARP table. - Default value: - - Yes (enabled) CONFIG_LWIP_GARP_TMR_INTERVAL GARP timer interval(seconds) Found in: Component config > LWIP > CONFIG_LWIP_ESP_GRATUITOUS_ARP Set the timer interval for gratuitous ARP. The default value is 60s - Default value: - - 60 CONFIG_LWIP_ESP_MLDV6_REPORT Send mldv6 report periodically Found in: Component config > LWIP Enable this option allows to send mldv6 report periodically. This option solve the issue that failed to receive multicast data. Some routers fail to forward multicast packets. To solve this problem, send multicast mdlv6 report to routers regularly. - Default value: - - Yes (enabled) CONFIG_LWIP_MLDV6_TMR_INTERVAL mldv6 report timer interval(seconds) Found in: Component config > LWIP > CONFIG_LWIP_ESP_MLDV6_REPORT Set the timer interval for mldv6 report. The default value is 30s - Default value: - - 40 CONFIG_LWIP_TCPIP_RECVMBOX_SIZE TCPIP task receive mail box size Found in: Component config > LWIP Set TCPIP task receive mail box size. Generally bigger value means higher throughput but more memory. The value should be bigger than UDP/TCP mail box size. - Range: - - from 6 to 1024 if CONFIG_LWIP_WND_SCALE - Default value: - - 32 CONFIG_LWIP_DHCP_DOES_ARP_CHECK DHCP: Perform ARP check on any offered address Found in: Component config > LWIP Enabling this option performs a check (via ARP request) if the offered IP address is not already in use by another host on the network. - Default value: - - Yes (enabled) CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID DHCP: Disable Use of HW address as client identification Found in: Component config > LWIP This option could be used to disable DHCP client identification with its MAC address. (Client id is used by DHCP servers to uniquely identify clients and are included in the DHCP packets as an option 61) Set this option to "y" in order to exclude option 61 from DHCP packets. - Default value: - - No (disabled) CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID DHCP: Disable Use of vendor class identification Found in: Component config > LWIP This option could be used to disable DHCP client vendor class identification. Set this option to "y" in order to exclude option 60 from DHCP packets. - Default value: - - Yes (enabled) CONFIG_LWIP_DHCP_RESTORE_LAST_IP DHCP: Restore last IP obtained from DHCP server Found in: Component config > LWIP When this option is enabled, DHCP client tries to re-obtain last valid IP address obtained from DHCP server. Last valid DHCP configuration is stored in nvs and restored after reset/power-up. If IP is still available, there is no need for sending discovery message to DHCP server and save some time. - Default value: - - No (disabled) CONFIG_LWIP_DHCP_OPTIONS_LEN DHCP total option length Found in: Component config > LWIP Set total length of outgoing DHCP option msg. Generally bigger value means it can carry more options and values. If your code meets LWIP_ASSERT due to option value is too long. Please increase the LWIP_DHCP_OPTIONS_LEN value. - Range: - - from 68 to 255 - Default value: - - 68 CONFIG_LWIP_NUM_NETIF_CLIENT_DATA Number of clients store data in netif Found in: Component config > LWIP Number of clients that may store data in client_data member array of struct netif. - Range: - - from 0 to 256 - Default value: - - 0 CONFIG_LWIP_DHCP_COARSE_TIMER_SECS DHCP coarse timer interval(s) Found in: Component config > LWIP Set DHCP coarse interval in seconds. A higher value will be less precise but cost less power consumption. - Range: - - from 1 to 10 - Default value: - - 1 DHCP server Contains: CONFIG_LWIP_DHCPS DHCPS: Enable IPv4 Dynamic Host Configuration Protocol Server (DHCPS) Found in: Component config > LWIP > DHCP server Enabling this option allows the device to run the DHCP server (to dynamically assign IPv4 addresses to clients). - Default value: - - Yes (enabled) CONFIG_LWIP_DHCPS_LEASE_UNIT Multiplier for lease time, in seconds Found in: Component config > LWIP > DHCP server > CONFIG_LWIP_DHCPS The DHCP server is calculating lease time multiplying the sent and received times by this number of seconds per unit. The default is 60, that equals one minute. - Range: - - from 1 to 3600 - Default value: - - 60 CONFIG_LWIP_DHCPS_MAX_STATION_NUM Maximum number of stations Found in: Component config > LWIP > DHCP server > CONFIG_LWIP_DHCPS The maximum number of DHCP clients that are connected to the server. After this number is exceeded, DHCP server removes of the oldest device from it's address pool, without notification. - Range: - - from 1 to 64 - Default value: - - 8 CONFIG_LWIP_DHCPS_STATIC_ENTRIES Enable ARP static entries Found in: Component config > LWIP > DHCP server > CONFIG_LWIP_DHCPS Enabling this option allows DHCP server to support temporary static ARP entries for DHCP Client. This will help the DHCP server to send the DHCP OFFER and DHCP ACK using IP unicast. - Default value: - - Yes (enabled) CONFIG_LWIP_AUTOIP Enable IPV4 Link-Local Addressing (AUTOIP) Found in: Component config > LWIP Enabling this option allows the device to self-assign an address in the 169.256/16 range if none is assigned statically or via DHCP. See RFC 3927. - Default value: - - No (disabled) Contains: CONFIG_LWIP_AUTOIP_TRIES DHCP Probes before self-assigning IPv4 LL address Found in: Component config > LWIP > CONFIG_LWIP_AUTOIP DHCP client will send this many probes before self-assigning a link local address. From LWIP help: "This can be set as low as 1 to get an AutoIP address very quickly, but you should be prepared to handle a changing IP address when DHCP overrides AutoIP." (In the case of ESP-IDF, this means multiple SYSTEM_EVENT_STA_GOT_IP events.) - Range: - - from 1 to 100 if CONFIG_LWIP_AUTOIP - Default value: - - 2 if CONFIG_LWIP_AUTOIP CONFIG_LWIP_AUTOIP_MAX_CONFLICTS Max IP conflicts before rate limiting Found in: Component config > LWIP > CONFIG_LWIP_AUTOIP If the AUTOIP functionality detects this many IP conflicts while self-assigning an address, it will go into a rate limited mode. - Range: - - from 1 to 100 if CONFIG_LWIP_AUTOIP - Default value: - - 9 if CONFIG_LWIP_AUTOIP CONFIG_LWIP_AUTOIP_RATE_LIMIT_INTERVAL Rate limited interval (seconds) Found in: Component config > LWIP > CONFIG_LWIP_AUTOIP If rate limiting self-assignment requests, wait this long between each request. - Range: - - from 5 to 120 if CONFIG_LWIP_AUTOIP - Default value: - - 20 if CONFIG_LWIP_AUTOIP CONFIG_LWIP_IPV4 Enable IPv4 Found in: Component config > LWIP Enable IPv4 stack. If you want to use IPv6 only TCP/IP stack, disable this. - Default value: - - Yes (enabled) CONFIG_LWIP_IPV6 Enable IPv6 Found in: Component config > LWIP Enable IPv6 function. If not use IPv6 function, set this option to n. If disabling LWIP_IPV6 then some other components (coap and asio) will no longer be available. - Default value: - - Yes (enabled) CONFIG_LWIP_IPV6_AUTOCONFIG Enable IPV6 stateless address autoconfiguration (SLAAC) Found in: Component config > LWIP > CONFIG_LWIP_IPV6 Enabling this option allows the devices to IPV6 stateless address autoconfiguration (SLAAC). See RFC 4862. - Default value: - - No (disabled) CONFIG_LWIP_IPV6_NUM_ADDRESSES Number of IPv6 addresses on each network interface Found in: Component config > LWIP > CONFIG_LWIP_IPV6 The maximum number of IPv6 addresses on each interface. Any additional addresses will be discarded. - Default value: - - 3 CONFIG_LWIP_IPV6_FORWARD Enable IPv6 forwarding between interfaces Found in: Component config > LWIP > CONFIG_LWIP_IPV6 Forwarding IPv6 packets between interfaces is only required when acting as a router. - Default value: - - No (disabled) CONFIG_LWIP_IPV6_RDNSS_MAX_DNS_SERVERS Use IPv6 Router Advertisement Recursive DNS Server Option Found in: Component config > LWIP Use IPv6 Router Advertisement Recursive DNS Server Option (as per RFC 6106) to copy a defined maximum number of DNS servers to the DNS module. Set this option to a number of desired DNS servers advertised in the RA protocol. This feature is disabled when set to 0. - Default value: - CONFIG_LWIP_IPV6_DHCP6 Enable DHCPv6 stateless address autoconfiguration Found in: Component config > LWIP Enable DHCPv6 for IPv6 stateless address autoconfiguration. Note that the dhcpv6 client has to be started using dhcp6_enable_stateless(netif); Note that the stateful address autoconfiguration is not supported. - Default value: - - No (disabled) if CONFIG_LWIP_IPV6_AUTOCONFIG CONFIG_LWIP_NETIF_STATUS_CALLBACK Enable status callback for network interfaces Found in: Component config > LWIP Enable callbacks when the network interface is up/down and addresses are changed. - Default value: - - No (disabled) CONFIG_LWIP_NETIF_LOOPBACK Support per-interface loopback Found in: Component config > LWIP Enabling this option means that if a packet is sent with a destination address equal to the interface's own IP address, it will "loop back" and be received by this interface. Disabling this option disables support of loopback interface in lwIP - Default value: - - Yes (enabled) Contains: CONFIG_LWIP_LOOPBACK_MAX_PBUFS Max queued loopback packets per interface Found in: Component config > LWIP > CONFIG_LWIP_NETIF_LOOPBACK Configure the maximum number of packets which can be queued for loopback on a given interface. Reducing this number may cause packets to be dropped, but will avoid filling memory with queued packet data. - Range: - - from 0 to 16 - Default value: - - 8 TCP Contains: CONFIG_LWIP_MAX_ACTIVE_TCP Maximum active TCP Connections Found in: Component config > LWIP > TCP The maximum number of simultaneously active TCP connections. The practical maximum limit is determined by available heap memory at runtime. Changing this value by itself does not substantially change the memory usage of LWIP, except for preventing new TCP connections after the limit is reached. - Range: - - from 1 to 1024 - Default value: - - 16 CONFIG_LWIP_MAX_LISTENING_TCP Maximum listening TCP Connections Found in: Component config > LWIP > TCP The maximum number of simultaneously listening TCP connections. The practical maximum limit is determined by available heap memory at runtime. Changing this value by itself does not substantially change the memory usage of LWIP, except for preventing new listening TCP connections after the limit is reached. - Range: - - from 1 to 1024 - Default value: - - 16 CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION TCP high speed retransmissions Found in: Component config > LWIP > TCP Speed up the TCP retransmission interval. If disabled, it is recommended to change the number of SYN retransmissions to 6, and TCP initial rto time to 3000. - Default value: - - Yes (enabled) CONFIG_LWIP_TCP_MAXRTX Maximum number of retransmissions of data segments Found in: Component config > LWIP > TCP Set maximum number of retransmissions of data segments. - Range: - - from 3 to 12 - Default value: - - 12 CONFIG_LWIP_TCP_SYNMAXRTX Maximum number of retransmissions of SYN segments Found in: Component config > LWIP > TCP Set maximum number of retransmissions of SYN segments. - Range: - - from 3 to 12 - Default value: - - 12 CONFIG_LWIP_TCP_MSS Maximum Segment Size (MSS) Found in: Component config > LWIP > TCP Set maximum segment size for TCP transmission. Can be set lower to save RAM, the default value 1460(ipv4)/1440(ipv6) will give best throughput. IPv4 TCP_MSS Range: 576 <= TCP_MSS <= 1460 IPv6 TCP_MSS Range: 1220<= TCP_MSS <= 1440 - Range: - - from 536 to 1460 - Default value: - - 1440 CONFIG_LWIP_TCP_TMR_INTERVAL TCP timer interval(ms) Found in: Component config > LWIP > TCP Set TCP timer interval in milliseconds. Can be used to speed connections on bad networks. A lower value will redeliver unacked packets faster. - Default value: - - 250 CONFIG_LWIP_TCP_MSL Maximum segment lifetime (MSL) Found in: Component config > LWIP > TCP Set maximum segment lifetime in milliseconds. - Default value: - - 60000 CONFIG_LWIP_TCP_FIN_WAIT_TIMEOUT Maximum FIN segment lifetime Found in: Component config > LWIP > TCP Set maximum segment lifetime in milliseconds. - Default value: - - 20000 CONFIG_LWIP_TCP_SND_BUF_DEFAULT Default send buffer size Found in: Component config > LWIP > TCP Set default send buffer size for new TCP sockets. Per-socket send buffer size can be changed at runtime with lwip_setsockopt(s, TCP_SNDBUF, ...). This value must be at least 2x the MSS size, and the default is 4x the default MSS size. Setting a smaller default SNDBUF size can save some RAM, but will decrease performance. - Range: - - from 2440 to 1024000 if CONFIG_LWIP_WND_SCALE - Default value: - - 5760 CONFIG_LWIP_TCP_WND_DEFAULT Default receive window size Found in: Component config > LWIP > TCP Set default TCP receive window size for new TCP sockets. Per-socket receive window size can be changed at runtime with lwip_setsockopt(s, TCP_WINDOW, ...). Setting a smaller default receive window size can save some RAM, but will significantly decrease performance. - Range: - - from 2440 to 1024000 if CONFIG_LWIP_WND_SCALE - Default value: - - 5760 CONFIG_LWIP_TCP_RECVMBOX_SIZE Default TCP receive mail box size Found in: Component config > LWIP > TCP Set TCP receive mail box size. Generally bigger value means higher throughput but more memory. The recommended value is: LWIP_TCP_WND_DEFAULT/TCP_MSS + 2, e.g. if LWIP_TCP_WND_DEFAULT=14360, TCP_MSS=1436, then the recommended receive mail box size is (14360/1436 + 2) = 12. TCP receive mail box is a per socket mail box, when the application receives packets from TCP socket, LWIP core firstly posts the packets to TCP receive mail box and the application then fetches the packets from mail box. It means LWIP can caches maximum LWIP_TCP_RECCVMBOX_SIZE packets for each TCP socket, so the maximum possible cached TCP packets for all TCP sockets is LWIP_TCP_RECCVMBOX_SIZE multiples the maximum TCP socket number. In other words, the bigger LWIP_TCP_RECVMBOX_SIZE means more memory. On the other hand, if the receiv mail box is too small, the mail box may be full. If the mail box is full, the LWIP drops the packets. So generally we need to make sure the TCP receive mail box is big enough to avoid packet drop between LWIP core and application. - Range: - - from 6 to 1024 if CONFIG_LWIP_WND_SCALE - Default value: - - 6 CONFIG_LWIP_TCP_QUEUE_OOSEQ Queue incoming out-of-order segments Found in: Component config > LWIP > TCP Queue incoming out-of-order segments for later use. Disable this option to save some RAM during TCP sessions, at the expense of increased retransmissions if segments arrive out of order. - Default value: - - Yes (enabled) CONFIG_LWIP_TCP_OOSEQ_TIMEOUT Timeout for each pbuf queued in TCP OOSEQ, in RTOs. Found in: Component config > LWIP > TCP > CONFIG_LWIP_TCP_QUEUE_OOSEQ The timeout value is TCP_OOSEQ_TIMEOUT * RTO. - Range: - - from 1 to 30 - Default value: - - 6 CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS The maximum number of pbufs queued on OOSEQ per pcb Found in: Component config > LWIP > TCP > CONFIG_LWIP_TCP_QUEUE_OOSEQ If LWIP_TCP_OOSEQ_MAX_PBUFS = 0, TCP will not control the number of OOSEQ pbufs. In a poor network environment, many out-of-order tcp pbufs will be received. These out-of-order pbufs will be cached in the TCP out-of-order queue which will cause Wi-Fi/Ethernet fail to release RX buffer in time. It is possible that all RX buffers for MAC layer are used by OOSEQ. Control the number of out-of-order pbufs to ensure that the MAC layer has enough RX buffer to receive packets. In the Wi-Fi scenario, recommended OOSEQ PBUFS Range: 0 <= TCP_OOSEQ_MAX_PBUFS <= CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM/(MAX_TCP_NUMBER + 1) In the Ethernet scenario,recommended Ethernet OOSEQ PBUFS Range: 0 <= TCP_OOSEQ_MAX_PBUFS <= CONFIG_ETH_DMA_RX_BUFFER_NUM/(MAX_TCP_NUMBER + 1) Within the recommended value range, the larger the value, the better the performance. MAX_TCP_NUMBER represent Maximum number of TCP connections in Wi-Fi(STA+SoftAP) and Ethernet scenario. - Range: - - from 0 to 12 - Default value: - CONFIG_LWIP_TCP_SACK_OUT Support sending selective acknowledgements Found in: Component config > LWIP > TCP > CONFIG_LWIP_TCP_QUEUE_OOSEQ TCP will support sending selective acknowledgements (SACKs). - Default value: - - No (disabled) CONFIG_LWIP_TCP_OVERSIZE Pre-allocate transmit PBUF size Found in: Component config > LWIP > TCP Allows enabling "oversize" allocation of TCP transmission pbufs ahead of time, which can reduce the length of pbuf chains used for transmission. This will not make a difference to sockets where Nagle's algorithm is disabled. Default value of MSS is fine for most applications, 25% MSS may save some RAM when only transmitting small amounts of data. Disabled will have worst performance and fragmentation characteristics, but uses least RAM overall. Available options: - MSS (CONFIG_LWIP_TCP_OVERSIZE_MSS) - 25% MSS (CONFIG_LWIP_TCP_OVERSIZE_QUARTER_MSS) - Disabled (CONFIG_LWIP_TCP_OVERSIZE_DISABLE) CONFIG_LWIP_WND_SCALE Support TCP window scale Found in: Component config > LWIP > TCP Enable this feature to support TCP window scaling. - Default value: - - No (disabled) if CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP CONFIG_LWIP_TCP_RCV_SCALE Set TCP receiving window scaling factor Found in: Component config > LWIP > TCP > CONFIG_LWIP_WND_SCALE Enable this feature to support TCP window scaling. - Range: - - from 0 to 14 if CONFIG_LWIP_WND_SCALE - Default value: - CONFIG_LWIP_TCP_RTO_TIME Default TCP rto time Found in: Component config > LWIP > TCP Set default TCP rto time for a reasonable initial rto. In bad network environment, recommend set value of rto time to 1500. - Default value: - - 1500 UDP Contains: CONFIG_LWIP_MAX_UDP_PCBS Maximum active UDP control blocks Found in: Component config > LWIP > UDP The maximum number of active UDP "connections" (ie UDP sockets sending/receiving data). The practical maximum limit is determined by available heap memory at runtime. - Range: - - from 1 to 1024 - Default value: - - 16 CONFIG_LWIP_UDP_RECVMBOX_SIZE Default UDP receive mail box size Found in: Component config > LWIP > UDP Set UDP receive mail box size. The recommended value is 6. UDP receive mail box is a per socket mail box, when the application receives packets from UDP socket, LWIP core firstly posts the packets to UDP receive mail box and the application then fetches the packets from mail box. It means LWIP can caches maximum UDP_RECCVMBOX_SIZE packets for each UDP socket, so the maximum possible cached UDP packets for all UDP sockets is UDP_RECCVMBOX_SIZE multiples the maximum UDP socket number. In other words, the bigger UDP_RECVMBOX_SIZE means more memory. On the other hand, if the receiv mail box is too small, the mail box may be full. If the mail box is full, the LWIP drops the packets. So generally we need to make sure the UDP receive mail box is big enough to avoid packet drop between LWIP core and application. - Range: - - from 6 to 64 - Default value: - - 6 Checksums Contains: CONFIG_LWIP_CHECKSUM_CHECK_IP Enable LWIP IP checksums Found in: Component config > LWIP > Checksums Enable checksum checking for received IP messages - Default value: - - No (disabled) CONFIG_LWIP_CHECKSUM_CHECK_UDP Enable LWIP UDP checksums Found in: Component config > LWIP > Checksums Enable checksum checking for received UDP messages - Default value: - - No (disabled) CONFIG_LWIP_CHECKSUM_CHECK_ICMP Enable LWIP ICMP checksums Found in: Component config > LWIP > Checksums Enable checksum checking for received ICMP messages - Default value: - - Yes (enabled) CONFIG_LWIP_TCPIP_TASK_STACK_SIZE TCP/IP Task Stack Size Found in: Component config > LWIP Configure TCP/IP task stack size, used by LWIP to process multi-threaded TCP/IP operations. Setting this stack too small will result in stack overflow crashes. - Range: - - from 2048 to 65536 - Default value: - - 3072 CONFIG_LWIP_TCPIP_TASK_AFFINITY TCP/IP task affinity Found in: Component config > LWIP Allows setting LwIP tasks affinity, i.e. whether the task is pinned to CPU0, pinned to CPU1, or allowed to run on any CPU. Currently this applies to "TCP/IP" task and "Ping" task. Available options: - No affinity (CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY) - CPU0 (CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0) - CPU1 (CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU1) CONFIG_LWIP_PPP_SUPPORT Enable PPP support Found in: Component config > LWIP Enable PPP stack. Now only PPP over serial is possible. - Default value: - - No (disabled) Contains: CONFIG_LWIP_PPP_ENABLE_IPV6 Enable IPV6 support for PPP connections (IPV6CP) Found in: Component config > LWIP > CONFIG_LWIP_PPP_SUPPORT Enable IPV6 support in PPP for the local link between the DTE (processor) and DCE (modem). There are some modems which do not support the IPV6 addressing in the local link. If they are requested for IPV6CP negotiation, they may time out. This would in turn fail the configuration for the whole link. If your modem is not responding correctly to PPP Phase Network, try to disable IPV6 support. - Default value: - - Yes (enabled) if CONFIG_LWIP_PPP_SUPPORT && CONFIG_LWIP_IPV6 CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE Max number of IPv6 packets to queue during MAC resolution Found in: Component config > LWIP Config max number of IPv6 packets to queue during MAC resolution. - Range: - - from 3 to 20 - Default value: - - 3 CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS Max number of entries in IPv6 neighbor cache Found in: Component config > LWIP Config max number of entries in IPv6 neighbor cache - Range: - - from 3 to 10 - Default value: - - 5 CONFIG_LWIP_PPP_NOTIFY_PHASE_SUPPORT Enable Notify Phase Callback Found in: Component config > LWIP Enable to set a callback which is called on change of the internal PPP state machine. - Default value: - - No (disabled) if CONFIG_LWIP_PPP_SUPPORT CONFIG_LWIP_PPP_PAP_SUPPORT Enable PAP support Found in: Component config > LWIP Enable Password Authentication Protocol (PAP) support - Default value: - - No (disabled) if CONFIG_LWIP_PPP_SUPPORT CONFIG_LWIP_PPP_CHAP_SUPPORT Enable CHAP support Found in: Component config > LWIP Enable Challenge Handshake Authentication Protocol (CHAP) support - Default value: - - No (disabled) if CONFIG_LWIP_PPP_SUPPORT CONFIG_LWIP_PPP_MSCHAP_SUPPORT Enable MSCHAP support Found in: Component config > LWIP Enable Microsoft version of the Challenge-Handshake Authentication Protocol (MSCHAP) support - Default value: - - No (disabled) if CONFIG_LWIP_PPP_SUPPORT CONFIG_LWIP_PPP_MPPE_SUPPORT Enable MPPE support Found in: Component config > LWIP Enable Microsoft Point-to-Point Encryption (MPPE) support - Default value: - - No (disabled) if CONFIG_LWIP_PPP_SUPPORT CONFIG_LWIP_ENABLE_LCP_ECHO Enable LCP ECHO Found in: Component config > LWIP Enable LCP echo keepalive requests - Default value: - - No (disabled) if CONFIG_LWIP_PPP_SUPPORT CONFIG_LWIP_LCP_ECHOINTERVAL Echo interval (s) Found in: Component config > LWIP > CONFIG_LWIP_ENABLE_LCP_ECHO Interval in seconds between keepalive LCP echo requests, 0 to disable. - Range: - - from 0 to 1000000 if CONFIG_LWIP_ENABLE_LCP_ECHO - Default value: - CONFIG_LWIP_LCP_MAXECHOFAILS Maximum echo failures Found in: Component config > LWIP > CONFIG_LWIP_ENABLE_LCP_ECHO Number of consecutive unanswered echo requests before failure is indicated. - Range: - - from 0 to 100000 if CONFIG_LWIP_ENABLE_LCP_ECHO - Default value: - CONFIG_LWIP_PPP_DEBUG_ON Enable PPP debug log output Found in: Component config > LWIP Enable PPP debug log output - Default value: - - No (disabled) if CONFIG_LWIP_PPP_SUPPORT CONFIG_LWIP_SLIP_SUPPORT Enable SLIP support (new/experimental) Found in: Component config > LWIP Enable SLIP stack. Now only SLIP over serial is possible. SLIP over serial support is experimental and unsupported. - Default value: - - No (disabled) Contains: CONFIG_LWIP_SLIP_DEBUG_ON Enable SLIP debug log output Found in: Component config > LWIP > CONFIG_LWIP_SLIP_SUPPORT Enable SLIP debug log output - Default value: - - No (disabled) if CONFIG_LWIP_SLIP_SUPPORT ICMP Contains: CONFIG_LWIP_ICMP ICMP: Enable ICMP Found in: Component config > LWIP > ICMP Enable ICMP module for check network stability - Default value: - - Yes (enabled) CONFIG_LWIP_MULTICAST_PING Respond to multicast pings Found in: Component config > LWIP > ICMP - Default value: - - No (disabled) CONFIG_LWIP_BROADCAST_PING Respond to broadcast pings Found in: Component config > LWIP > ICMP - Default value: - - No (disabled) LWIP RAW API Contains: CONFIG_LWIP_MAX_RAW_PCBS Maximum LWIP RAW PCBs Found in: Component config > LWIP > LWIP RAW API The maximum number of simultaneously active LWIP RAW protocol control blocks. The practical maximum limit is determined by available heap memory at runtime. - Range: - - from 1 to 1024 - Default value: - - 16 SNTP Contains: CONFIG_LWIP_SNTP_MAX_SERVERS Maximum number of NTP servers Found in: Component config > LWIP > SNTP Set maximum number of NTP servers used by LwIP SNTP module. First argument of sntp_setserver/sntp_setservername functions is limited to this value. - Range: - - from 1 to 16 - Default value: - - 1 CONFIG_LWIP_DHCP_GET_NTP_SRV Request NTP servers from DHCP Found in: Component config > LWIP > SNTP If enabled, LWIP will add 'NTP' to Parameter-Request Option sent via DHCP-request. DHCP server might reply with an NTP server address in option 42. SNTP callback for such replies should be set accordingly (see sntp_servermode_dhcp() func.) - Default value: - - No (disabled) CONFIG_LWIP_DHCP_MAX_NTP_SERVERS Maximum number of NTP servers aquired via DHCP Found in: Component config > LWIP > SNTP > CONFIG_LWIP_DHCP_GET_NTP_SRV Set maximum number of NTP servers aquired via DHCP-offer. Should be less or equal to "Maximum number of NTP servers", any extra servers would be just ignored. - Range: - - from 1 to 16 if CONFIG_LWIP_DHCP_GET_NTP_SRV - Default value: - CONFIG_LWIP_SNTP_UPDATE_DELAY Request interval to update time (ms) Found in: Component config > LWIP > SNTP This option allows you to set the time update period via SNTP. Default is 1 hour. Must not be below 15 seconds by specification. (SNTPv4 RFC 4330 enforces a minimum update time of 15 seconds). - Range: - - from 15000 to 4294967295 - Default value: - - 3600000 DNS Contains: CONFIG_LWIP_DNS_MAX_SERVERS Maximum number of DNS servers Found in: Component config > LWIP > DNS Set maximum number of DNS servers. If fallback DNS servers are supported, the number of DNS servers needs to be greater than or equal to 3. - Range: - - from 1 to 4 - Default value: - - 3 CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT Enable DNS fallback server support Found in: Component config > LWIP > DNS Enable this feature to support DNS fallback server. - Default value: - - No (disabled) CONFIG_LWIP_FALLBACK_DNS_SERVER_ADDRESS DNS fallback server address Found in: Component config > LWIP > DNS > CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT This option allows you to config dns fallback server address. - Default value: - - "114.114.114.114" if CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT CONFIG_LWIP_BRIDGEIF_MAX_PORTS Maximum number of bridge ports Found in: Component config > LWIP Set maximum number of ports a bridge can consists of. - Range: - - from 1 to 63 - Default value: - - 7 CONFIG_LWIP_ESP_LWIP_ASSERT Enable LWIP ASSERT checks Found in: Component config > LWIP Enable this option keeps LWIP assertion checks enabled. It is recommended to keep this option enabled. If asserts are disabled for the entire project, they are also disabled for LWIP and this option is ignored. Hooks Contains: CONFIG_LWIP_HOOK_TCP_ISN TCP ISN Hook Found in: Component config > LWIP > Hooks Enables to define a TCP ISN hook to randomize initial sequence number in TCP connection. The default TCP ISN algorithm used in IDF (standardized in RFC 6528) produces ISN by combining an MD5 of the new TCP id and a stable secret with the current time. This is because the lwIP implementation (tcp_next_iss) is not very strong, as it does not take into consideration any platform specific entropy source. Set to LWIP_HOOK_TCP_ISN_CUSTOM to provide custom implementation. Set to LWIP_HOOK_TCP_ISN_NONE to use lwIP implementation. Available options: - No hook declared (CONFIG_LWIP_HOOK_TCP_ISN_NONE) - Default implementation (CONFIG_LWIP_HOOK_TCP_ISN_DEFAULT) - Custom implementation (CONFIG_LWIP_HOOK_TCP_ISN_CUSTOM) CONFIG_LWIP_HOOK_IP6_ROUTE IPv6 route Hook Found in: Component config > LWIP > Hooks Enables custom IPv6 route hook. Setting this to "default" provides weak implementation stub that could be overwritten in application code. Setting this to "custom" provides hook's declaration only and expects the application to implement it. Available options: - No hook declared (CONFIG_LWIP_HOOK_IP6_ROUTE_NONE) - Default (weak) implementation (CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT) - Custom implementation (CONFIG_LWIP_HOOK_IP6_ROUTE_CUSTOM) CONFIG_LWIP_HOOK_ND6_GET_GW IPv6 get gateway Hook Found in: Component config > LWIP > Hooks Enables custom IPv6 route hook. Setting this to "default" provides weak implementation stub that could be overwritten in application code. Setting this to "custom" provides hook's declaration only and expects the application to implement it. Available options: - No hook declared (CONFIG_LWIP_HOOK_ND6_GET_GW_NONE) - Default (weak) implementation (CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT) - Custom implementation (CONFIG_LWIP_HOOK_ND6_GET_GW_CUSTOM) CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR IPv6 source address selection Hook Found in: Component config > LWIP > Hooks Enables custom IPv6 source address selection. Setting this to "default" provides weak implementation stub that could be overwritten in application code. Setting this to "custom" provides hook's declaration only and expects the application to implement it. Available options: - No hook declared (CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE) - Default (weak) implementation (CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_DEFAULT) - Custom implementation (CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_CUSTOM) CONFIG_LWIP_HOOK_NETCONN_EXTERNAL_RESOLVE Netconn external resolve Hook Found in: Component config > LWIP > Hooks Enables custom DNS resolve hook. Setting this to "default" provides weak implementation stub that could be overwritten in application code. Setting this to "custom" provides hook's declaration only and expects the application to implement it. Available options: - No hook declared (CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE) - Default (weak) implementation (CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_DEFAULT) - Custom implementation (CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM) CONFIG_LWIP_HOOK_IP6_INPUT IPv6 packet input Found in: Component config > LWIP > Hooks Enables custom IPv6 packet input. Setting this to "default" provides weak implementation stub that could be overwritten in application code. Setting this to "custom" provides hook's declaration only and expects the application to implement it. Available options: - No hook declared (CONFIG_LWIP_HOOK_IP6_INPUT_NONE) - Default (weak) implementation (CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT) - Custom implementation (CONFIG_LWIP_HOOK_IP6_INPUT_CUSTOM) CONFIG_LWIP_DEBUG Enable LWIP Debug Found in: Component config > LWIP Enabling this option allows different kinds of lwIP debug output. All lwIP debug features increase the size of the final binary. - Default value: - - No (disabled) Contains: CONFIG_LWIP_DEBUG_ESP_LOG Route LWIP debugs through ESP_LOG interface Found in: Component config > LWIP > CONFIG_LWIP_DEBUG Enabling this option routes all enabled LWIP debugs through ESP_LOGD. - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_NETIF_DEBUG Enable netif debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_PBUF_DEBUG Enable pbuf debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_ETHARP_DEBUG Enable etharp debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_API_LIB_DEBUG Enable api lib debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_SOCKETS_DEBUG Enable socket debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_IP_DEBUG Enable IP debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_ICMP_DEBUG Enable ICMP debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG && CONFIG_LWIP_ICMP CONFIG_LWIP_DHCP_STATE_DEBUG Enable DHCP state tracking Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_DHCP_DEBUG Enable DHCP debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_IP6_DEBUG Enable IP6 debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_ICMP6_DEBUG Enable ICMP6 debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_TCP_DEBUG Enable TCP debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_UDP_DEBUG Enable UDP debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_SNTP_DEBUG Enable SNTP debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_DNS_DEBUG Enable DNS debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_NAPT_DEBUG Enable NAPT debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG && CONFIG_LWIP_IPV4_NAPT CONFIG_LWIP_BRIDGEIF_DEBUG Enable bridge generic debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_BRIDGEIF_FDB_DEBUG Enable bridge FDB debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG CONFIG_LWIP_BRIDGEIF_FW_DEBUG Enable bridge forwarding debug messages Found in: Component config > LWIP > CONFIG_LWIP_DEBUG - Default value: - - No (disabled) if CONFIG_LWIP_DEBUG mbedTLS Contains: CONFIG_MBEDTLS_MEM_ALLOC_MODE Memory allocation strategy Found in: Component config > mbedTLS Allocation strategy for mbedTLS, essentially provides ability to allocate all required dynamic allocations from, - Internal DRAM memory only - External SPIRAM memory only - Either internal or external memory based on default malloc() behavior in ESP-IDF - Custom allocation mode, by overwriting calloc()/free() using mbedtls_platform_set_calloc_free() function - Internal IRAM memory wherever applicable else internal DRAM Recommended mode here is always internal (*), since that is most preferred from security perspective. But if application requirement does not allow sufficient free internal memory then alternate mode can be selected. (*) In case of ESP32-S2/ESP32-S3, hardware allows encryption of external SPIRAM contents provided hardware flash encryption feature is enabled. In that case, using external SPIRAM allocation strategy is also safe choice from security perspective. Available options: - Internal memory (CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC) - External SPIRAM (CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC) - Default alloc mode (CONFIG_MBEDTLS_DEFAULT_MEM_ALLOC) - Custom alloc mode (CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC) - Internal IRAM (CONFIG_MBEDTLS_IRAM_8BIT_MEM_ALLOC) Allows to use IRAM memory region as 8bit accessible region. TLS input and output buffers will be allocated in IRAM section which is 32bit aligned memory. Every unaligned (8bit or 16bit) access will result in an exception and incur penalty of certain clock cycles per unaligned read/write. CONFIG_MBEDTLS_SSL_MAX_CONTENT_LEN TLS maximum message content length Found in: Component config > mbedTLS Maximum TLS message length (in bytes) supported by mbedTLS. 16384 is the default and this value is required to comply fully with TLS standards. However you can set a lower value in order to save RAM. This is safe if the other end of the connection supports Maximum Fragment Length Negotiation Extension (max_fragment_length, see RFC6066) or you know for certain that it will never send a message longer than a certain number of bytes. If the value is set too low, symptoms are a failed TLS handshake or a return value of MBEDTLS_ERR_SSL_INVALID_RECORD (-0x7200). CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN Asymmetric in/out fragment length Found in: Component config > mbedTLS If enabled, this option allows customizing TLS in/out fragment length in asymmetric way. Please note that enabling this with default values saves 12KB of dynamic memory per TLS connection. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN TLS maximum incoming fragment length Found in: Component config > mbedTLS > CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN This defines maximum incoming fragment length, overriding default maximum content length (MBEDTLS_SSL_MAX_CONTENT_LEN). - Range: - - from 512 to 16384 - Default value: - - 16384 CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN TLS maximum outgoing fragment length Found in: Component config > mbedTLS > CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN This defines maximum outgoing fragment length, overriding default maximum content length (MBEDTLS_SSL_MAX_CONTENT_LEN). - Range: - - from 512 to 16384 - Default value: - - 4096 CONFIG_MBEDTLS_DYNAMIC_BUFFER Using dynamic TX/RX buffer Found in: Component config > mbedTLS Using dynamic TX/RX buffer. After enabling this option, mbedTLS will allocate TX buffer when need to send data and then free it if all data is sent, allocate RX buffer when need to receive data and then free it when all data is used or read by upper layer. By default, when SSL is initialized, mbedTLS also allocate TX and RX buffer with the default value of "MBEDTLS_SSL_OUT_CONTENT_LEN" or "MBEDTLS_SSL_IN_CONTENT_LEN", so to save more heap, users can set the options to be an appropriate value. CONFIG_MBEDTLS_DYNAMIC_FREE_CONFIG_DATA Free private key and DHM data after its usage Found in: Component config > mbedTLS > CONFIG_MBEDTLS_DYNAMIC_BUFFER Free private key and DHM data after its usage in handshake process. The option will decrease heap cost when handshake, but also lead to problem: Becasue all certificate, private key and DHM data are freed so users should register certificate and private key to ssl config object again. - Default value: - - No (disabled) if CONFIG_MBEDTLS_DYNAMIC_BUFFER CONFIG_MBEDTLS_DYNAMIC_FREE_CA_CERT Free SSL CA certificate after its usage Found in: Component config > mbedTLS > CONFIG_MBEDTLS_DYNAMIC_BUFFER > CONFIG_MBEDTLS_DYNAMIC_FREE_CONFIG_DATA Free CA certificate after its usage in the handshake process. This option will decrease the heap footprint for the TLS handshake, but may lead to a problem: If the respective ssl object needs to perform the TLS handshake again, the CA certificate should once again be registered to the ssl object. - Default value: - - Yes (enabled) if CONFIG_MBEDTLS_DYNAMIC_FREE_CONFIG_DATA CONFIG_MBEDTLS_DEBUG Enable mbedTLS debugging Found in: Component config > mbedTLS Enable mbedTLS debugging functions at compile time. If this option is enabled, you can include "mbedtls/esp_debug.h" and call mbedtls_esp_enable_debug_log() at runtime in order to enable mbedTLS debug output via the ESP log mechanism. - Default value: - - No (disabled) CONFIG_MBEDTLS_DEBUG_LEVEL Set mbedTLS debugging level Found in: Component config > mbedTLS > CONFIG_MBEDTLS_DEBUG Set mbedTLS debugging level Available options: - Warning (CONFIG_MBEDTLS_DEBUG_LEVEL_WARN) - Info (CONFIG_MBEDTLS_DEBUG_LEVEL_INFO) - Debug (CONFIG_MBEDTLS_DEBUG_LEVEL_DEBUG) - Verbose (CONFIG_MBEDTLS_DEBUG_LEVEL_VERBOSE) Certificate Bundle Contains: CONFIG_MBEDTLS_CERTIFICATE_BUNDLE Enable trusted root certificate bundle Found in: Component config > mbedTLS > Certificate Bundle Enable support for large number of default root certificates When enabled this option allows user to store default as well as customer specific root certificates in compressed format rather than storing full certificate. For the root certificates the public key and the subject name will be stored. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_DEFAULT_CERTIFICATE_BUNDLE Default certificate bundle options Found in: Component config > mbedTLS > Certificate Bundle > CONFIG_MBEDTLS_CERTIFICATE_BUNDLE Available options: - Use the full default certificate bundle (CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL) - Use only the most common certificates from the default bundles (CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN) Use only the most common certificates from the default bundles, reducing the size with 50%, while still having around 99% coverage. - Do not use the default certificate bundle (CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE) CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE Add custom certificates to the default bundle Found in: Component config > mbedTLS > Certificate Bundle > CONFIG_MBEDTLS_CERTIFICATE_BUNDLE - Default value: - - No (disabled) CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE_PATH Custom certificate bundle path Found in: Component config > mbedTLS > Certificate Bundle > CONFIG_MBEDTLS_CERTIFICATE_BUNDLE > CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE Name of the custom certificate directory or file. This path is evaluated relative to the project root directory. CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS Maximum no of certificates allowed in certificate bundle Found in: Component config > mbedTLS > Certificate Bundle > CONFIG_MBEDTLS_CERTIFICATE_BUNDLE - Default value: - - 200 CONFIG_MBEDTLS_ECP_RESTARTABLE Enable mbedTLS ecp restartable Found in: Component config > mbedTLS Enable "non-blocking" ECC operations that can return early and be resumed. - Default value: - - No (disabled) CONFIG_MBEDTLS_CMAC_C Enable CMAC mode for block ciphers Found in: Component config > mbedTLS Enable the CMAC (Cipher-based Message Authentication Code) mode for block ciphers. - Default value: - - No (disabled) CONFIG_MBEDTLS_HARDWARE_AES Enable hardware AES acceleration Found in: Component config > mbedTLS Enable hardware accelerated AES encryption & decryption. Note that if the ESP32 CPU is running at 240MHz, hardware AES does not offer any speed boost over software AES. CONFIG_MBEDTLS_HARDWARE_GCM Enable partially hardware accelerated GCM Found in: Component config > mbedTLS > CONFIG_MBEDTLS_HARDWARE_AES Enable partially hardware accelerated GCM. GHASH calculation is still done in software. If MBEDTLS_HARDWARE_GCM is disabled and MBEDTLS_HARDWARE_AES is enabled then mbedTLS will still use the hardware accelerated AES block operation, but on a single block at a time. - Default value: - - Yes (enabled) if SOC_AES_SUPPORT_GCM && CONFIG_MBEDTLS_HARDWARE_AES CONFIG_MBEDTLS_HARDWARE_MPI Enable hardware MPI (bignum) acceleration Found in: Component config > mbedTLS Enable hardware accelerated multiple precision integer operations. Hardware accelerated multiplication, modulo multiplication, and modular exponentiation for up to SOC_RSA_MAX_BIT_LEN bit results. These operations are used by RSA. CONFIG_MBEDTLS_HARDWARE_SHA Enable hardware SHA acceleration Found in: Component config > mbedTLS Enable hardware accelerated SHA1, SHA256, SHA384 & SHA512 in mbedTLS. Due to a hardware limitation, on the ESP32 hardware acceleration is only guaranteed if SHA digests are calculated one at a time. If more than one SHA digest is calculated at the same time, one will be calculated fully in hardware and the rest will be calculated (at least partially calculated) in software. This happens automatically. SHA hardware acceleration is faster than software in some situations but slower in others. You should benchmark to find the best setting for you. CONFIG_MBEDTLS_HARDWARE_ECC Enable hardware ECC acceleration Found in: Component config > mbedTLS Enable hardware accelerated ECC point multiplication and point verification for points on curve SECP192R1 and SECP256R1 in mbedTLS - Default value: - - Yes (enabled) if SOC_ECC_SUPPORTED CONFIG_MBEDTLS_ECC_OTHER_CURVES_SOFT_FALLBACK Fallback to software implementation for curves not supported in hardware Found in: Component config > mbedTLS > CONFIG_MBEDTLS_HARDWARE_ECC Fallback to software implementation of ECC point multiplication and point verification for curves not supported in hardware. - Default value: - - Yes (enabled) if CONFIG_MBEDTLS_HARDWARE_ECC CONFIG_MBEDTLS_ROM_MD5 Use MD5 implementation in ROM Found in: Component config > mbedTLS Use ROM MD5 in mbedTLS. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_HARDWARE_ECDSA_SIGN Enable ECDSA signing using on-chip ECDSA peripheral Found in: Component config > mbedTLS Enable hardware accelerated ECDSA peripheral to sign data on curve SECP192R1 and SECP256R1 in mbedTLS. Note that for signing, the private key has to be burnt in an efuse key block with key purpose set to ECDSA_KEY. If no key is burnt, it will report an error The key should be burnt in little endian format. espefuse.py utility handles it internally but care needs to be taken while burning using esp_efuse APIs - Default value: - - No (disabled) if SOC_ECDSA_SUPPORTED CONFIG_MBEDTLS_HARDWARE_ECDSA_VERIFY Enable ECDSA signature verification using on-chip ECDSA peripheral Found in: Component config > mbedTLS Enable hardware accelerated ECDSA peripheral to verify signature on curve SECP192R1 and SECP256R1 in mbedTLS. - Default value: - - Yes (enabled) if SOC_ECDSA_SUPPORTED CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN Enable hardware ECDSA sign acceleration when using ATECC608A Found in: Component config > mbedTLS This option enables hardware acceleration for ECDSA sign function, only when using ATECC608A cryptoauth chip (integrated with ESP32-WROOM-32SE) - Default value: - - No (disabled) CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY Enable hardware ECDSA verify acceleration when using ATECC608A Found in: Component config > mbedTLS This option enables hardware acceleration for ECDSA sign function, only when using ATECC608A cryptoauth chip (integrated with ESP32-WROOM-32SE) - Default value: - - No (disabled) CONFIG_MBEDTLS_HAVE_TIME Enable mbedtls time support Found in: Component config > mbedTLS Enable use of time.h functions (time() and gmtime()) by mbedTLS. This option doesn't require the system time to be correct, but enables functionality that requires relative timekeeping - for example periodic expiry of TLS session tickets or session cache entries. Disabling this option will save some firmware size, particularly if the rest of the firmware doesn't call any standard timekeeeping functions. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_PLATFORM_TIME_ALT Enable mbedtls time support: platform-specific Found in: Component config > mbedTLS > CONFIG_MBEDTLS_HAVE_TIME Enabling this config will provide users with a function "mbedtls_platform_set_time()" that allows to set an alternative time function pointer. - Default value: - - No (disabled) CONFIG_MBEDTLS_HAVE_TIME_DATE Enable mbedtls certificate expiry check Found in: Component config > mbedTLS > CONFIG_MBEDTLS_HAVE_TIME Enables X.509 certificate expiry checks in mbedTLS. If this option is disabled (default) then X.509 certificate "valid from" and "valid to" timestamp fields are ignored. If this option is enabled, these fields are compared with the current system date and time. The time is retrieved using the standard time() and gmtime() functions. If the certificate is not valid for the current system time then verification will fail with code MBEDTLS_X509_BADCERT_FUTURE or MBEDTLS_X509_BADCERT_EXPIRED. Enabling this option requires adding functionality in the firmware to set the system clock to a valid timestamp before using TLS. The recommended way to do this is via ESP-IDF's SNTP functionality, but any method can be used. In the case where only a small number of certificates are trusted by the device, please carefully consider the tradeoffs of enabling this option. There may be undesired consequences, for example if all trusted certificates expire while the device is offline and a TLS connection is required to update. Or if an issue with the SNTP server means that the system time is invalid for an extended period after a reset. - Default value: - - No (disabled) CONFIG_MBEDTLS_ECDSA_DETERMINISTIC Enable deterministic ECDSA Found in: Component config > mbedTLS Standard ECDSA is "fragile" in the sense that lack of entropy when signing may result in a compromise of the long-term signing key. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_SHA512_C Enable the SHA-384 and SHA-512 cryptographic hash algorithms Found in: Component config > mbedTLS Enable MBEDTLS_SHA512_C adds support for SHA-384 and SHA-512. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_TLS_MODE TLS Protocol Role Found in: Component config > mbedTLS mbedTLS can be compiled with protocol support for the TLS server, TLS client, or both server and client. Reducing the number of TLS roles supported saves code size. Available options: - Server & Client (CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT) - Server (CONFIG_MBEDTLS_TLS_SERVER_ONLY) - Client (CONFIG_MBEDTLS_TLS_CLIENT_ONLY) - None (CONFIG_MBEDTLS_TLS_DISABLED) TLS Key Exchange Methods Contains: CONFIG_MBEDTLS_PSK_MODES Enable pre-shared-key ciphersuites Found in: Component config > mbedTLS > TLS Key Exchange Methods Enable to show configuration for different types of pre-shared-key TLS authentatication methods. Leaving this options disabled will save code size if they are not used. - Default value: - - No (disabled) CONFIG_MBEDTLS_KEY_EXCHANGE_PSK Enable PSK based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_PSK_MODES Enable to support symmetric key PSK (pre-shared-key) TLS key exchange modes. - Default value: - - No (disabled) if CONFIG_MBEDTLS_PSK_MODES CONFIG_MBEDTLS_KEY_EXCHANGE_DHE_PSK Enable DHE-PSK based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_PSK_MODES Enable to support Diffie-Hellman PSK (pre-shared-key) TLS authentication modes. - Default value: - - Yes (enabled) if CONFIG_MBEDTLS_PSK_MODES && CONFIG_MBEDTLS_DHM_C CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_PSK Enable ECDHE-PSK based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_PSK_MODES Enable to support Elliptic-Curve-Diffie-Hellman PSK (pre-shared-key) TLS authentication modes. - Default value: - - Yes (enabled) if CONFIG_MBEDTLS_PSK_MODES && CONFIG_MBEDTLS_ECDH_C CONFIG_MBEDTLS_KEY_EXCHANGE_RSA_PSK Enable RSA-PSK based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_PSK_MODES Enable to support RSA PSK (pre-shared-key) TLS authentication modes. - Default value: - - Yes (enabled) if CONFIG_MBEDTLS_PSK_MODES CONFIG_MBEDTLS_KEY_EXCHANGE_RSA Enable RSA-only based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods Enable to support ciphersuites with prefix TLS-RSA-WITH- - Default value: - - Yes (enabled) CONFIG_MBEDTLS_KEY_EXCHANGE_DHE_RSA Enable DHE-RSA based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods Enable to support ciphersuites with prefix TLS-DHE-RSA-WITH- - Default value: - - Yes (enabled) if CONFIG_MBEDTLS_DHM_C CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE Support Elliptic Curve based ciphersuites Found in: Component config > mbedTLS > TLS Key Exchange Methods Enable to show Elliptic Curve based ciphersuite mode options. Disabling all Elliptic Curve ciphersuites saves code size and can give slightly faster TLS handshakes, provided the server supports RSA-only ciphersuite modes. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA Enable ECDHE-RSA based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE Enable to support ciphersuites with prefix TLS-ECDHE-RSA-WITH- - Default value: - - Yes (enabled) CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA Enable ECDHE-ECDSA based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE Enable to support ciphersuites with prefix TLS-ECDHE-RSA-WITH- - Default value: - - Yes (enabled) CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA Enable ECDH-ECDSA based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE Enable to support ciphersuites with prefix TLS-ECDHE-RSA-WITH- - Default value: - - Yes (enabled) CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA Enable ECDH-RSA based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods > CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE Enable to support ciphersuites with prefix TLS-ECDHE-RSA-WITH- - Default value: - - Yes (enabled) CONFIG_MBEDTLS_KEY_EXCHANGE_ECJPAKE Enable ECJPAKE based ciphersuite modes Found in: Component config > mbedTLS > TLS Key Exchange Methods Enable to support ciphersuites with prefix TLS-ECJPAKE-WITH- - Default value: - - No (disabled) if CONFIG_MBEDTLS_ECJPAKE_C && CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED CONFIG_MBEDTLS_SSL_RENEGOTIATION Support TLS renegotiation Found in: Component config > mbedTLS The two main uses of renegotiation are (1) refresh keys on long-lived connections and (2) client authentication after the initial handshake. If you don't need renegotiation, disabling it will save code size and reduce the possibility of abuse/vulnerability. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_SSL_PROTO_TLS1_2 Support TLS 1.2 protocol Found in: Component config > mbedTLS - Default value: - - Yes (enabled) CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 Support GM/T SSL 1.1 protocol Found in: Component config > mbedTLS Provisions for GM/T SSL 1.1 support - Default value: - - No (disabled) CONFIG_MBEDTLS_SSL_PROTO_DTLS Support DTLS protocol (all versions) Found in: Component config > mbedTLS Requires TLS 1.2 to be enabled for DTLS 1.2 - Default value: - - No (disabled) CONFIG_MBEDTLS_SSL_ALPN Support ALPN (Application Layer Protocol Negotiation) Found in: Component config > mbedTLS Disabling this option will save some code size if it is not needed. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS TLS: Client Support for RFC 5077 SSL session tickets Found in: Component config > mbedTLS Client support for RFC 5077 session tickets. See mbedTLS documentation for more details. Disabling this option will save some code size. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS TLS: Server Support for RFC 5077 SSL session tickets Found in: Component config > mbedTLS Server support for RFC 5077 session tickets. See mbedTLS documentation for more details. Disabling this option will save some code size. - Default value: - - Yes (enabled) Symmetric Ciphers Contains: CONFIG_MBEDTLS_AES_C AES block cipher Found in: Component config > mbedTLS > Symmetric Ciphers - Default value: - - Yes (enabled) CONFIG_MBEDTLS_CAMELLIA_C Camellia block cipher Found in: Component config > mbedTLS > Symmetric Ciphers - Default value: - - No (disabled) CONFIG_MBEDTLS_DES_C DES block cipher (legacy, insecure) Found in: Component config > mbedTLS > Symmetric Ciphers Enables the DES block cipher to support 3DES-based TLS ciphersuites. 3DES is vulnerable to the Sweet32 attack and should only be enabled if absolutely necessary. - Default value: - - No (disabled) CONFIG_MBEDTLS_BLOWFISH_C Blowfish block cipher (read help) Found in: Component config > mbedTLS > Symmetric Ciphers Enables the Blowfish block cipher (not used for TLS sessions.) The Blowfish cipher is not used for mbedTLS TLS sessions but can be used for other purposes. Read up on the limitations of Blowfish (including Sweet32) before enabling. - Default value: - - No (disabled) CONFIG_MBEDTLS_XTEA_C XTEA block cipher Found in: Component config > mbedTLS > Symmetric Ciphers Enables the XTEA block cipher. - Default value: - - No (disabled) CONFIG_MBEDTLS_CCM_C CCM (Counter with CBC-MAC) block cipher modes Found in: Component config > mbedTLS > Symmetric Ciphers Enable Counter with CBC-MAC (CCM) modes for AES and/or Camellia ciphers. Disabling this option saves some code size. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_GCM_C GCM (Galois/Counter) block cipher modes Found in: Component config > mbedTLS > Symmetric Ciphers Enable Galois/Counter Mode for AES and/or Camellia ciphers. This option is generally faster than CCM. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_NIST_KW_C NIST key wrapping (KW) and KW padding (KWP) Found in: Component config > mbedTLS > Symmetric Ciphers Enable NIST key wrapping and key wrapping padding. - Default value: - - No (disabled) CONFIG_MBEDTLS_RIPEMD160_C Enable RIPEMD-160 hash algorithm Found in: Component config > mbedTLS Enable the RIPEMD-160 hash algorithm. - Default value: - - No (disabled) Certificates Contains: CONFIG_MBEDTLS_PEM_PARSE_C Read & Parse PEM formatted certificates Found in: Component config > mbedTLS > Certificates Enable decoding/parsing of PEM formatted certificates. If your certificates are all in the simpler DER format, disabling this option will save some code size. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_PEM_WRITE_C Write PEM formatted certificates Found in: Component config > mbedTLS > Certificates Enable writing of PEM formatted certificates. If writing certificate data only in DER format, disabling this option will save some code size. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_X509_CRL_PARSE_C X.509 CRL parsing Found in: Component config > mbedTLS > Certificates Support for parsing X.509 Certifificate Revocation Lists. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_X509_CSR_PARSE_C X.509 CSR parsing Found in: Component config > mbedTLS > Certificates Support for parsing X.509 Certifificate Signing Requests - Default value: - - Yes (enabled) CONFIG_MBEDTLS_ECP_C Elliptic Curve Ciphers Found in: Component config > mbedTLS - Default value: - - Yes (enabled) CONFIG_MBEDTLS_DHM_C Diffie-Hellman-Merkle key exchange (DHM) Found in: Component config > mbedTLS Enable DHM. Needed to use DHE-xxx TLS ciphersuites. Note that the security of Diffie-Hellman key exchanges depends on a suitable prime being used for the exchange. Please see detailed warning text about this in file mbedtls/dhm.h file. - Default value: - - No (disabled) CONFIG_MBEDTLS_ECDH_C Elliptic Curve Diffie-Hellman (ECDH) Found in: Component config > mbedTLS Enable ECDH. Needed to use ECDHE-xxx TLS ciphersuites. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_ECDSA_C Elliptic Curve DSA Found in: Component config > mbedTLS > CONFIG_MBEDTLS_ECDH_C Enable ECDSA. Needed to use ECDSA-xxx TLS ciphersuites. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_ECJPAKE_C Elliptic curve J-PAKE Found in: Component config > mbedTLS Enable ECJPAKE. Needed to use ECJPAKE-xxx TLS ciphersuites. - Default value: - - No (disabled) CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED Enable SECP192R1 curve Found in: Component config > mbedTLS Enable support for SECP192R1 Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED Enable SECP224R1 curve Found in: Component config > mbedTLS Enable support for SECP224R1 Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED Enable SECP256R1 curve Found in: Component config > mbedTLS Enable support for SECP256R1 Elliptic Curve. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED Enable SECP384R1 curve Found in: Component config > mbedTLS Enable support for SECP384R1 Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED Enable SECP521R1 curve Found in: Component config > mbedTLS Enable support for SECP521R1 Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED Enable SECP192K1 curve Found in: Component config > mbedTLS Enable support for SECP192K1 Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED Enable SECP224K1 curve Found in: Component config > mbedTLS Enable support for SECP224K1 Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED Enable SECP256K1 curve Found in: Component config > mbedTLS Enable support for SECP256K1 Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED Enable BP256R1 curve Found in: Component config > mbedTLS support for DP Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED Enable BP384R1 curve Found in: Component config > mbedTLS support for DP Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED Enable BP512R1 curve Found in: Component config > mbedTLS support for DP Elliptic Curve. CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED Enable CURVE25519 curve Found in: Component config > mbedTLS Enable support for CURVE25519 Elliptic Curve. CONFIG_MBEDTLS_ECP_NIST_OPTIM NIST 'modulo p' optimisations Found in: Component config > mbedTLS NIST 'modulo p' optimisations increase Elliptic Curve operation performance. Disabling this option saves some code size. - Default value: - - Yes (enabled) CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM Enable fixed-point multiplication optimisations Found in: Component config > mbedTLS This configuration option enables optimizations to speedup (about 3 ~ 4 times) the ECP fixed point multiplication using pre-computed tables in the flash memory. Disabling this configuration option saves flash footprint (about 29KB if all Elliptic Curve selected) in the application binary. # end of Elliptic Curve options - Default value: - - Yes (enabled) CONFIG_MBEDTLS_POLY1305_C Poly1305 MAC algorithm Found in: Component config > mbedTLS Enable support for Poly1305 MAC algorithm. - Default value: - - No (disabled) CONFIG_MBEDTLS_CHACHA20_C Chacha20 stream cipher Found in: Component config > mbedTLS Enable support for Chacha20 stream cipher. - Default value: - - No (disabled) CONFIG_MBEDTLS_CHACHAPOLY_C ChaCha20-Poly1305 AEAD algorithm Found in: Component config > mbedTLS > CONFIG_MBEDTLS_CHACHA20_C Enable support for ChaCha20-Poly1305 AEAD algorithm. - Default value: - - No (disabled) if CONFIG_MBEDTLS_CHACHA20_C && CONFIG_MBEDTLS_POLY1305_C CONFIG_MBEDTLS_HKDF_C HKDF algorithm (RFC 5869) Found in: Component config > mbedTLS Enable support for the Hashed Message Authentication Code (HMAC)-based key derivation function (HKDF). - Default value: - - No (disabled) CONFIG_MBEDTLS_THREADING_C Enable the threading abstraction layer Found in: Component config > mbedTLS If you do intend to use contexts between threads, you will need to enable this layer to prevent race conditions. - Default value: - - No (disabled) CONFIG_MBEDTLS_THREADING_ALT Enable threading alternate implementation Found in: Component config > mbedTLS > CONFIG_MBEDTLS_THREADING_C Enable threading alt to allow your own alternate threading implementation. - Default value: - - Yes (enabled) if CONFIG_MBEDTLS_THREADING_C CONFIG_MBEDTLS_THREADING_PTHREAD Enable threading pthread implementation Found in: Component config > mbedTLS > CONFIG_MBEDTLS_THREADING_C Enable the pthread wrapper layer for the threading layer. - Default value: - - No (disabled) if CONFIG_MBEDTLS_THREADING_C CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI Fallback to software implementation for larger MPI values Found in: Component config > mbedTLS Fallback to software implementation for RSA key lengths larger than SOC_RSA_MAX_BIT_LEN. If this is not active then the ESP will be unable to process keys greater than SOC_RSA_MAX_BIT_LEN. - Default value: - - No (disabled) CONFIG_MBEDTLS_USE_CRYPTO_ROM_IMPL Use ROM implementation of the crypto algorithm Found in: Component config > mbedTLS Enable this flag to use mbedtls crypto algorithm from ROM instead of ESP-IDF. This configuration option saves flash footprint in the application binary. Note that the version of mbedtls crypto algorithm library in ROM is v2.16.12. We have done the security analysis of the mbedtls revision in ROM (v2.16.12) and ensured that affected symbols have been patched (removed). If in the future mbedtls revisions there are security issues that also affects the version in ROM (v2.16.12) then we shall patch the relevant symbols. This would increase the flash footprint and hence care must be taken to keep some reserved space for the application binary in flash layout. - Default value: - - No (disabled) if ESP_ROM_HAS_MBEDTLS_CRYPTO_LIB && CONFIG_IDF_EXPERIMENTAL_FEATURES ESP-MQTT Configurations Contains: CONFIG_MQTT_PROTOCOL_311 Enable MQTT protocol 3.1.1 Found in: Component config > ESP-MQTT Configurations If not, this library will use MQTT protocol 3.1 - Default value: - - Yes (enabled) CONFIG_MQTT_PROTOCOL_5 Enable MQTT protocol 5.0 Found in: Component config > ESP-MQTT Configurations If not, this library will not support MQTT 5.0 - Default value: - - No (disabled) CONFIG_MQTT_TRANSPORT_SSL Enable MQTT over SSL Found in: Component config > ESP-MQTT Configurations Enable MQTT transport over SSL with mbedtls - Default value: - - Yes (enabled) CONFIG_MQTT_TRANSPORT_WEBSOCKET Enable MQTT over Websocket Found in: Component config > ESP-MQTT Configurations Enable MQTT transport over Websocket. - Default value: - - Yes (enabled) CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE Enable MQTT over Websocket Secure Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_TRANSPORT_WEBSOCKET Enable MQTT transport over Websocket Secure. - Default value: - - Yes (enabled) CONFIG_MQTT_MSG_ID_INCREMENTAL Use Incremental Message Id Found in: Component config > ESP-MQTT Configurations Set this to true for the message id (2.3.1 Packet Identifier) to be generated as an incremental number rather then a random value (used by default) - Default value: - - No (disabled) CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED Skip publish if disconnected Found in: Component config > ESP-MQTT Configurations Set this to true to avoid publishing (enqueueing messages) if the client is disconnected. The MQTT client tries to publish all messages by default, even in the disconnected state (where the qos1 and qos2 packets are stored in the internal outbox to be published later) The MQTT_SKIP_PUBLISH_IF_DISCONNECTED option allows applications to override this behaviour and not enqueue publish packets in the disconnected state. - Default value: - - No (disabled) CONFIG_MQTT_REPORT_DELETED_MESSAGES Report deleted messages Found in: Component config > ESP-MQTT Configurations Set this to true to post events for all messages which were deleted from the outbox before being correctly sent and confirmed. - Default value: - - No (disabled) CONFIG_MQTT_USE_CUSTOM_CONFIG MQTT Using custom configurations Found in: Component config > ESP-MQTT Configurations Custom MQTT configurations. - Default value: - - No (disabled) CONFIG_MQTT_TCP_DEFAULT_PORT Default MQTT over TCP port Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG Default MQTT over TCP port - Default value: - - 1883 if CONFIG_MQTT_USE_CUSTOM_CONFIG CONFIG_MQTT_SSL_DEFAULT_PORT Default MQTT over SSL port Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG Default MQTT over SSL port - Default value: - CONFIG_MQTT_WS_DEFAULT_PORT Default MQTT over Websocket port Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG Default MQTT over Websocket port - Default value: - CONFIG_MQTT_WSS_DEFAULT_PORT Default MQTT over Websocket Secure port Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG Default MQTT over Websocket Secure port - Default value: - CONFIG_MQTT_BUFFER_SIZE Default MQTT Buffer Size Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG This buffer size using for both transmit and receive - Default value: - - 1024 if CONFIG_MQTT_USE_CUSTOM_CONFIG CONFIG_MQTT_TASK_STACK_SIZE MQTT task stack size Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG MQTT task stack size - Default value: - - 6144 if CONFIG_MQTT_USE_CUSTOM_CONFIG CONFIG_MQTT_DISABLE_API_LOCKS Disable API locks Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG Default config employs API locks to protect internal structures. It is possible to disable these locks if the user code doesn't access MQTT API from multiple concurrent tasks - Default value: - - No (disabled) if CONFIG_MQTT_USE_CUSTOM_CONFIG CONFIG_MQTT_TASK_PRIORITY MQTT task priority Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG MQTT task priority. Higher number denotes higher priority. - Default value: - CONFIG_MQTT_POLL_READ_TIMEOUT_MS MQTT transport poll read timeut Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG Timeout when polling underlying transport for read. - Default value: - - 1000 if CONFIG_MQTT_USE_CUSTOM_CONFIG CONFIG_MQTT_EVENT_QUEUE_SIZE Number of queued events. Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG A value higher than 1 enables multiple queued events. - Default value: - CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED Enable MQTT task core selection Found in: Component config > ESP-MQTT Configurations This will enable core selection CONFIG_MQTT_TASK_CORE_SELECTION Core to use ? Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED Available options: - Core 0 (CONFIG_MQTT_USE_CORE_0) - Core 1 (CONFIG_MQTT_USE_CORE_1) CONFIG_MQTT_OUTBOX_DATA_ON_EXTERNAL_MEMORY Use external memory for outbox data Found in: Component config > ESP-MQTT Configurations Set to true to use external memory for outbox data. - Default value: - - No (disabled) if CONFIG_MQTT_USE_CUSTOM_CONFIG CONFIG_MQTT_CUSTOM_OUTBOX Enable custom outbox implementation Found in: Component config > ESP-MQTT Configurations Set to true if a specific implementation of message outbox is needed (e.g. persistent outbox in NVM or similar). Note: Implementation of the custom outbox must be added to the mqtt component. These CMake commands could be used to append the custom implementation to lib-mqtt sources: idf_component_get_property(mqtt mqtt COMPONENT_LIB) set_property(TARGET ${mqtt} PROPERTY SOURCES ${PROJECT_DIR}/custom_outbox.c APPEND) - Default value: - - No (disabled) CONFIG_MQTT_OUTBOX_EXPIRED_TIMEOUT_MS Outbox message expired timeout[ms] Found in: Component config > ESP-MQTT Configurations Messages which stays in the outbox longer than this value before being published will be discarded. - Default value: - - 30000 if CONFIG_MQTT_USE_CUSTOM_CONFIG Newlib Contains: CONFIG_NEWLIB_STDOUT_LINE_ENDING Line ending for UART output Found in: Component config > Newlib This option allows configuring the desired line endings sent to UART when a newline ('n', LF) appears on stdout. Three options are possible: CRLF: whenever LF is encountered, prepend it with CR LF: no modification is applied, stdout is sent as is CR: each occurence of LF is replaced with CR This option doesn't affect behavior of the UART driver (drivers/uart.h). Available options: - CRLF (CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF) - LF (CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF) - CR (CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR) CONFIG_NEWLIB_STDIN_LINE_ENDING Line ending for UART input Found in: Component config > Newlib This option allows configuring which input sequence on UART produces a newline ('n', LF) on stdin. Three options are possible: CRLF: CRLF is converted to LF LF: no modification is applied, input is sent to stdin as is CR: each occurence of CR is replaced with LF This option doesn't affect behavior of the UART driver (drivers/uart.h). Available options: - CRLF (CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF) - LF (CONFIG_NEWLIB_STDIN_LINE_ENDING_LF) - CR (CONFIG_NEWLIB_STDIN_LINE_ENDING_CR) CONFIG_NEWLIB_NANO_FORMAT Enable 'nano' formatting options for printf/scanf family Found in: Component config > Newlib In most chips the ROM contains parts of newlib C library, including printf/scanf family of functions. These functions have been compiled with so-called "nano" formatting option. This option doesn't support 64-bit integer formats and C99 features, such as positional arguments. For more details about "nano" formatting option, please see newlib readme file, search for '--enable-newlib-nano-formatted-io': https://sourceware.org/newlib/README If this option is enabled and the ROM contains functions from newlib-nano, the build system will use functions available in ROM, reducing the application binary size. Functions available in ROM run faster than functions which run from flash. Functions available in ROM can also run when flash instruction cache is disabled. Some chips (e.g. ESP32-C6) has the full formatting versions of printf/scanf in ROM instead of the nano versions and in this building with newlib nano might actually increase the size of the binary. Which functions are present in ROM can be seen from ROM caps: ESP_ROM_HAS_NEWLIB_NANO_FORMAT and ESP_ROM_HAS_NEWLIB_NORMAL_FORMAT. If you need 64-bit integer formatting support or C99 features, keep this option disabled. CONFIG_NEWLIB_TIME_SYSCALL Timers used for gettimeofday function Found in: Component config > Newlib This setting defines which hardware timers are used to implement 'gettimeofday' and 'time' functions in C library. - - If both high-resolution (systimer for all targets except ESP32) - and RTC timers are used, timekeeping will continue in deep sleep. Time will be reported at 1 microsecond resolution. This is the default, and the recommended option. - - If only high-resolution timer (systimer) is used, gettimeofday will - provide time at microsecond resolution. Time will not be preserved when going into deep sleep mode. - - If only RTC timer is used, timekeeping will continue in - deep sleep, but time will be measured at 6.(6) microsecond resolution. Also the gettimeofday function itself may take longer to run. - - If no timers are used, gettimeofday and time functions - return -1 and set errno to ENOSYS. - - When RTC is used for timekeeping, two RTC_STORE registers are - used to keep time in deep sleep mode. Available options: - RTC and high-resolution timer (CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT) - RTC (CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC) - High-resolution timer (CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT) - None (CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE) NVS Contains: CONFIG_NVS_ENCRYPTION Enable NVS encryption Found in: Component config > NVS This option enables encryption for NVS. When enabled, XTS-AES is used to encrypt the complete NVS data, except the page headers. It requires XTS encryption keys to be stored in an encrypted partition (enabling flash encryption is mandatory here) or to be derived from an HMAC key burnt in eFuse. - Default value: - - Yes (enabled) if CONFIG_SECURE_FLASH_ENC_ENABLED && (CONFIG_SECURE_FLASH_ENC_ENABLED || SOC_HMAC_SUPPORTED) CONFIG_NVS_COMPATIBLE_PRE_V4_3_ENCRYPTION_FLAG NVS partition encrypted flag compatible with ESP-IDF before v4.3 Found in: Component config > NVS Enabling this will ignore "encrypted" flag for NVS partitions. NVS encryption scheme is different than hardware flash encryption and hence it is not recommended to have "encrypted" flag for NVS partitions. This was not being checked in pre v4.3 IDF. Hence, if you have any devices where this flag is kept enabled in partition table then enabling this config will allow to have same behavior as pre v4.3 IDF. CONFIG_NVS_ASSERT_ERROR_CHECK Use assertions for error checking Found in: Component config > NVS This option switches error checking type between assertions (y) or return codes (n). - Default value: - - No (disabled) CONFIG_NVS_LEGACY_DUP_KEYS_COMPATIBILITY Enable legacy nvs_set function behavior when same key is reused with different data types Found in: Component config > NVS Enabling this option will switch the nvs_set() family of functions to the legacy mode: when called repeatedly with the same key but different data type, the existing value in the NVS remains active and the new value is just stored, actually not accessible through corresponding nvs_get() call for the key given. Use this option only when your application relies on such NVS API behaviour. - Default value: - - No (disabled) NVS Security Provider Contains: CONFIG_NVS_SEC_KEY_PROTECTION_SCHEME NVS Encryption: Key Protection Scheme Found in: Component config > NVS Security Provider This choice defines the default NVS encryption keys protection scheme; which will be used for the default NVS partition. Users can use the corresponding scheme registration APIs to register other schemes for the default as well as other NVS partitions. Available options: - Using Flash Encryption (CONFIG_NVS_SEC_KEY_PROTECT_USING_FLASH_ENC) Protect the NVS Encryption Keys using Flash Encryption Requires a separate 'nvs_keys' partition (which will be encrypted by flash encryption) for storing the NVS encryption keys - Using HMAC peripheral (CONFIG_NVS_SEC_KEY_PROTECT_USING_HMAC) Derive and protect the NVS Encryption Keys using the HMAC peripheral Requires the specified eFuse block (NVS_SEC_HMAC_EFUSE_KEY_ID or the v2 API argument) to be empty or pre-written with a key with the purpose ESP_EFUSE_KEY_PURPOSE_HMAC_UP CONFIG_NVS_SEC_HMAC_EFUSE_KEY_ID eFuse key ID storing the HMAC key Found in: Component config > NVS Security Provider eFuse block key ID storing the HMAC key for deriving the NVS encryption keys Note: The eFuse block key ID required by the HMAC scheme (CONFIG_NVS_SEC_KEY_PROTECT_USING_HMAC) is set using this config when the default NVS partition is initialized with nvs_flash_init(). The eFuse block key ID can also be set at runtime by passing the appropriate value to the NVS security scheme registration APIs. - Range: - - from 0 to 6 if CONFIG_NVS_SEC_KEY_PROTECT_USING_HMAC - Default value: - OpenThread Contains: CONFIG_OPENTHREAD_ENABLED OpenThread Found in: Component config > OpenThread Select this option to enable OpenThread and show the submenu with OpenThread configuration choices. - Default value: - - No (disabled) CONFIG_OPENTHREAD_LOG_LEVEL_DYNAMIC Enable dynamic log level control Found in: Component config > OpenThread > CONFIG_OPENTHREAD_ENABLED Select this option to enable dynamic log level control for OpenThread - Default value: - - Yes (enabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_CONSOLE_TYPE OpenThread console type Found in: Component config > OpenThread > CONFIG_OPENTHREAD_ENABLED Select OpenThread console type Available options: - OpenThread console type UART (CONFIG_OPENTHREAD_CONSOLE_TYPE_UART) - OpenThread console type USB Serial/JTAG Controller (CONFIG_OPENTHREAD_CONSOLE_TYPE_USB_SERIAL_JTAG) CONFIG_OPENTHREAD_LOG_LEVEL OpenThread log verbosity Found in: Component config > OpenThread > CONFIG_OPENTHREAD_ENABLED Select OpenThread log level. Available options: - No logs (CONFIG_OPENTHREAD_LOG_LEVEL_NONE) - Error logs (CONFIG_OPENTHREAD_LOG_LEVEL_CRIT) - Warning logs (CONFIG_OPENTHREAD_LOG_LEVEL_WARN) - Notice logs (CONFIG_OPENTHREAD_LOG_LEVEL_NOTE) - Info logs (CONFIG_OPENTHREAD_LOG_LEVEL_INFO) - Debug logs (CONFIG_OPENTHREAD_LOG_LEVEL_DEBG) Thread Operational Dataset Contains: CONFIG_OPENTHREAD_NETWORK_NAME OpenThread network name Found in: Component config > OpenThread > Thread Operational Dataset - Default value: - - "OpenThread-ESP" CONFIG_OPENTHREAD_MESH_LOCAL_PREFIX OpenThread mesh local prefix, format <address>/<plen> Found in: Component config > OpenThread > Thread Operational Dataset A string in the format "<address>/<plen>", where <address> is an IPv6 address and <plen> is a prefix length. For example "fd00:db8:a0:0::/64" - Default value: - - "fd00:db8:a0:0::/64" CONFIG_OPENTHREAD_NETWORK_CHANNEL OpenThread network channel Found in: Component config > OpenThread > Thread Operational Dataset - Range: - - from 11 to 26 - Default value: - - 15 CONFIG_OPENTHREAD_NETWORK_PANID OpenThread network pan id Found in: Component config > OpenThread > Thread Operational Dataset - Range: - - from 0 to 0xFFFE - Default value: - - "0x1234" CONFIG_OPENTHREAD_NETWORK_EXTPANID OpenThread extended pan id Found in: Component config > OpenThread > Thread Operational Dataset The OpenThread network extended pan id in hex string format - Default value: - - dead00beef00cafe CONFIG_OPENTHREAD_NETWORK_MASTERKEY OpenThread network key Found in: Component config > OpenThread > Thread Operational Dataset The OpenThread network network key in hex string format - Default value: - - 00112233445566778899aabbccddeeff CONFIG_OPENTHREAD_NETWORK_PSKC OpenThread pre-shared commissioner key Found in: Component config > OpenThread > Thread Operational Dataset The OpenThread pre-shared commissioner key in hex string format - Default value: - - 104810e2315100afd6bc9215a6bfac53 CONFIG_OPENTHREAD_RADIO_TYPE Config the Thread radio type Found in: Component config > OpenThread Configure how OpenThread connects to the 15.4 radio Available options: - Native 15.4 radio (CONFIG_OPENTHREAD_RADIO_NATIVE) Select this to use the native 15.4 radio. - Connect via UART (CONFIG_OPENTHREAD_RADIO_SPINEL_UART) Select this to connect to a Radio Co-Processor via UART. - Connect via SPI (CONFIG_OPENTHREAD_RADIO_SPINEL_SPI) Select this to connect to a Radio Co-Processor via SPI. CONFIG_OPENTHREAD_DEVICE_TYPE Config the Thread device type Found in: Component config > OpenThread OpenThread can be configured to different device types (FTD, MTD, Radio) Available options: - Full Thread Device (CONFIG_OPENTHREAD_FTD) Select this to enable Full Thread Device which can act as router and leader in a Thread network. - Minimal Thread Device (CONFIG_OPENTHREAD_MTD) Select this to enable Minimal Thread Device which can only act as end device in a Thread network. This will reduce the code size of the OpenThread stack. - Radio Only Device (CONFIG_OPENTHREAD_RADIO) Select this to enable Radio Only Device which can only forward 15.4 packets to the host. The OpenThread stack will be run on the host and OpenThread will have minimal footprint on the radio only device. CONFIG_OPENTHREAD_RCP_TRANSPORT The RCP transport type Found in: Component config > OpenThread Available options: - UART RCP (CONFIG_OPENTHREAD_RCP_UART) Select this to enable UART connection to host. - SPI RCP (CONFIG_OPENTHREAD_RCP_SPI) Select this to enable SPI connection to host. CONFIG_OPENTHREAD_NCP_VENDOR_HOOK Enable vendor command for RCP Found in: Component config > OpenThread Select this to enable OpenThread NCP vendor commands. - Default value: - - No (disabled) if CONFIG_OPENTHREAD_RADIO CONFIG_OPENTHREAD_CLI Enable Openthread Command-Line Interface Found in: Component config > OpenThread Select this option to enable Command-Line Interface in OpenThread. - Default value: - - Yes (enabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_DIAG Enable diag Found in: Component config > OpenThread Select this option to enable Diag in OpenThread. This will enable diag mode and a series of diag commands in the OpenThread command line. These commands allow users to manipulate low-level features of the storage and 15.4 radio. - Default value: - - Yes (enabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_COMMISSIONER Enable Commissioner Found in: Component config > OpenThread Select this option to enable commissioner in OpenThread. This will enable the device to act as a commissioner in the Thread network. A commissioner checks the pre-shared key from a joining device with the Thread commissioning protocol and shares the network parameter with the joining device upon success. - Default value: - - No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_COMM_MAX_JOINER_ENTRIES The size of max commissioning joiner entries Found in: Component config > OpenThread > CONFIG_OPENTHREAD_COMMISSIONER - Range: - - from 2 to 50 if CONFIG_OPENTHREAD_COMMISSIONER - Default value: - CONFIG_OPENTHREAD_JOINER Enable Joiner Found in: Component config > OpenThread Select this option to enable Joiner in OpenThread. This allows a device to join the Thread network with a pre-shared key using the Thread commissioning protocol. - Default value: - - No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_SRP_CLIENT Enable SRP Client Found in: Component config > OpenThread Select this option to enable SRP Client in OpenThread. This allows a device to register SRP services to SRP Server. - Default value: - - Yes (enabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_SRP_CLIENT_MAX_SERVICES Specifies number of service entries in the SRP client service pool Found in: Component config > OpenThread > CONFIG_OPENTHREAD_SRP_CLIENT Set the max buffer size of service entries in the SRP client service pool. - Range: - - from 2 to 20 if CONFIG_OPENTHREAD_SRP_CLIENT - Default value: - CONFIG_OPENTHREAD_DNS_CLIENT Enable DNS Client Found in: Component config > OpenThread Select this option to enable DNS Client in OpenThread. - Default value: - - Yes (enabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_BORDER_ROUTER Enable Border Router Found in: Component config > OpenThread Select this option to enable border router features in OpenThread. - Default value: - - No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_PLATFORM_MSGPOOL_MANAGEMENT Allocate message pool buffer from PSRAM Found in: Component config > OpenThread If enabled, the message pool is managed by platform defined logic. - Default value: - - No (disabled) if CONFIG_OPENTHREAD_ENABLED && (CONFIG_SPIRAM_USE_CAPS_ALLOC || CONFIG_SPIRAM_USE_MALLOC) CONFIG_OPENTHREAD_NUM_MESSAGE_BUFFERS The number of openthread message buffers Found in: Component config > OpenThread - Range: - - from 10 to 8191 if CONFIG_OPENTHREAD_PLATFORM_MSGPOOL_MANAGEMENT && CONFIG_OPENTHREAD_ENABLED - Default value: - CONFIG_OPENTHREAD_SPINEL_RX_FRAME_BUFFER_SIZE The size of openthread spinel rx frame buffer Found in: Component config > OpenThread - Range: - - from 512 to 8192 if CONFIG_OPENTHREAD_ENABLED || CONFIG_OPENTHREAD_SPINEL_ONLY - Default value: - CONFIG_OPENTHREAD_MLE_MAX_CHILDREN The size of max MLE children entries Found in: Component config > OpenThread - Range: - - from 5 to 50 if CONFIG_OPENTHREAD_ENABLED - Default value: - CONFIG_OPENTHREAD_TMF_ADDR_CACHE_ENTRIES The size of max TMF address cache entries Found in: Component config > OpenThread - Range: - - from 5 to 50 if CONFIG_OPENTHREAD_ENABLED - Default value: - CONFIG_OPENTHREAD_DNS64_CLIENT Use dns64 client Found in: Component config > OpenThread Select this option to acquire NAT64 address from dns servers. - Default value: - - No (disabled) if CONFIG_OPENTHREAD_ENABLED && CONFIG_LWIP_IPV4 CONFIG_OPENTHREAD_DNS_SERVER_ADDR DNS server address (IPv4) Found in: Component config > OpenThread > CONFIG_OPENTHREAD_DNS64_CLIENT Set the DNS server IPv4 address. - Default value: - - "8.8.8.8" if CONFIG_OPENTHREAD_DNS64_CLIENT CONFIG_OPENTHREAD_UART_BUFFER_SIZE The uart received buffer size of openthread Found in: Component config > OpenThread Set the OpenThread UART buffer size. - Range: - - from 128 to 1024 if CONFIG_OPENTHREAD_ENABLED - Default value: - - 768 if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_LINK_METRICS Enable link metrics feature Found in: Component config > OpenThread Select this option to enable link metrics feature - Default value: - - No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_MACFILTER_ENABLE Enable mac filter feature Found in: Component config > OpenThread Select this option to enable mac filter feature - Default value: - - No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_CSL_ENABLE Enable CSL feature Found in: Component config > OpenThread Select this option to enable CSL feature - Default value: - - No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_XTAL_ACCURACY The accuracy of the XTAL Found in: Component config > OpenThread The device's XTAL accuracy, in ppm. - Default value: - - 130 CONFIG_OPENTHREAD_CSL_ACCURACY The current CSL rx/tx scheduling drift, in units of ± ppm Found in: Component config > OpenThread The current accuracy of the clock used for scheduling CSL operations - Default value: - CONFIG_OPENTHREAD_CSL_UNCERTAIN The CSL Uncertainty in units of 10 us. Found in: Component config > OpenThread The fixed uncertainty of the Device for scheduling CSL Transmissions in units of 10 microseconds. - Default value: - CONFIG_OPENTHREAD_CSL_DEBUG_ENABLE Enable CSL debug Found in: Component config > OpenThread Select this option to set rx on when sleep in CSL feature, only for debug - Default value: - - No (disabled) if CONFIG_OPENTHREAD_CSL_ENABLE CONFIG_OPENTHREAD_DUA_ENABLE Enable Domain Unicast Address feature Found in: Component config > OpenThread Only used for Thread1.2 certification - Default value: - - No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_TIME_SYNC Enable the time synchronization service feature Found in: Component config > OpenThread Select this option to enable time synchronization feature, the devices in the same Thread network could sync to the same network time. - Default value: - - No (disabled) if CONFIG_OPENTHREAD_ENABLED CONFIG_OPENTHREAD_RADIO_STATS_ENABLE Enable Radio Statistics feature Found in: Component config > OpenThread Select this option to enable the radio statistics feature, you can use radio command to print some radio Statistics informations. - Default value: - - No (disabled) if CONFIG_OPENTHREAD_FTD || CONFIG_OPENTHREAD_MTD CONFIG_OPENTHREAD_SPINEL_ONLY Enable OpenThread External Radio Spinel feature Found in: Component config > OpenThread Select this option to enable the OpenThread Radio Spinel for external protocol stack, such as Zigbee. - Default value: - - No (disabled) CONFIG_OPENTHREAD_RX_ON_WHEN_IDLE Enable OpenThread radio capibility rx on when idle Found in: Component config > OpenThread Select this option to enable OpenThread radio capibility rx on when idle. Do not support this feature when SW coexistence is enabled. - Default value: - - No (disabled) if CONFIG_ESP_COEX_SW_COEXIST_ENABLE Thread Address Query Config Contains: CONFIG_OPENTHREAD_ADDRESS_QUERY_TIMEOUT Timeout value (in seconds) for a address notification response after sending an address query. Found in: Component config > OpenThread > Thread Address Query Config - Range: - - from 1 to 10 if CONFIG_OPENTHREAD_FTD || CONFIG_OPENTHREAD_MTD - Default value: - CONFIG_OPENTHREAD_ADDRESS_QUERY_RETRY_DELAY Initial retry delay for address query (in seconds). Found in: Component config > OpenThread > Thread Address Query Config - Range: - - from 1 to 120 if CONFIG_OPENTHREAD_FTD || CONFIG_OPENTHREAD_MTD - Default value: - CONFIG_OPENTHREAD_ADDRESS_QUERY_MAX_RETRY_DELAY Maximum retry delay for address query (in seconds). Found in: Component config > OpenThread > Thread Address Query Config - Range: - - from to 960 if CONFIG_OPENTHREAD_FTD || CONFIG_OPENTHREAD_MTD - Default value: - - 120 if CONFIG_OPENTHREAD_FTD || CONFIG_OPENTHREAD_MTD Protocomm Contains: CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0 Support protocomm security version 0 (no security) Found in: Component config > Protocomm Enable support of security version 0. Disabling this option saves some code size. Consult the Enabling protocomm security version section of the Protocomm documentation in ESP-IDF Programming guide for more details. - Default value: - - Yes (enabled) CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1 Support protocomm security version 1 (Curve25519 key exchange + AES-CTR encryption/decryption) Found in: Component config > Protocomm Enable support of security version 1. Disabling this option saves some code size. Consult the Enabling protocomm security version section of the Protocomm documentation in ESP-IDF Programming guide for more details. - Default value: - - Yes (enabled) CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2 Support protocomm security version 2 (SRP6a-based key exchange + AES-GCM encryption/decryption) Found in: Component config > Protocomm Enable support of security version 2. Disabling this option saves some code size. Consult the Enabling protocomm security version section of the Protocomm documentation in ESP-IDF Programming guide for more details. - Default value: - - Yes (enabled) PThreads Contains: CONFIG_PTHREAD_TASK_PRIO_DEFAULT Default task priority Found in: Component config > PThreads Priority used to create new tasks with default pthread parameters. - Range: - - from 0 to 255 - Default value: - - 5 CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT Default task stack size Found in: Component config > PThreads Stack size used to create new tasks with default pthread parameters. - Default value: - - 3072 CONFIG_PTHREAD_STACK_MIN Minimum allowed pthread stack size Found in: Component config > PThreads Minimum allowed pthread stack size set in attributes passed to pthread_create - Default value: - - 768 CONFIG_PTHREAD_TASK_CORE_DEFAULT Default pthread core affinity Found in: Component config > PThreads The default core to which pthreads are pinned. Available options: - No affinity (CONFIG_PTHREAD_DEFAULT_CORE_NO_AFFINITY) - Core 0 (CONFIG_PTHREAD_DEFAULT_CORE_0) - Core 1 (CONFIG_PTHREAD_DEFAULT_CORE_1) CONFIG_PTHREAD_TASK_NAME_DEFAULT Default name of pthreads Found in: Component config > PThreads The default name of pthreads. - Default value: - - "pthread" SoC Settings Contains: MMU Config Main Flash configuration Contains: SPI Flash behavior when brownout Contains: CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC Enable sending reset when brownout for XMC flash chips Found in: Component config > Main Flash configuration > SPI Flash behavior when brownout When this option is selected, the patch will be enabled for XMC. Follow the recommended flow by XMC for better stability. DO NOT DISABLE UNLESS YOU KNOW WHAT YOU ARE DOING. Optional and Experimental Features (READ DOCS FIRST) Contains: CONFIG_SPI_FLASH_HPM_DC Support HPM using DC (READ DOCS FIRST) Found in: Component config > Main Flash configuration > Optional and Experimental Features (READ DOCS FIRST) This feature needs your bootloader to be compiled DC-aware (BOOTLOADER_FLASH_DC_AWARE=y). Otherwise the chip will not be able to boot after a reset. Available options: - Auto (Enable when bootloader support enabled (BOOTLOADER_FLASH_DC_AWARE)) (CONFIG_SPI_FLASH_HPM_DC_AUTO) - Disable (READ DOCS FIRST) (CONFIG_SPI_FLASH_HPM_DC_DISABLE) CONFIG_SPI_FLASH_AUTO_SUSPEND Auto suspend long erase/write operations (READ DOCS FIRST) Found in: Component config > Main Flash configuration > Optional and Experimental Features (READ DOCS FIRST) This option is disabled by default because it is supported only for specific flash chips and for specific Espressif chips. To evaluate if you can use this feature refer to Optional Features for Flash > Auto Suspend & Resume of the ESP-IDF Programming Guide. CAUTION: If you want to OTA to an app with this feature turned on, please make sure the bootloader has the support for it. (later than IDF v4.3) If you are using an official Espressif module, please contact Espressif Business support to check if the module has the flash that support this feature installed. Also refer to Concurrency Constraints for Flash on SPI1 > Flash Auto Suspend Feature before enabling this option. SPI Flash driver Contains: CONFIG_SPI_FLASH_VERIFY_WRITE Verify SPI flash writes Found in: Component config > SPI Flash driver If this option is enabled, any time SPI flash is written then the data will be read back and verified. This can catch hardware problems with SPI flash, or flash which was not erased before verification. CONFIG_SPI_FLASH_LOG_FAILED_WRITE Log errors if verification fails Found in: Component config > SPI Flash driver > CONFIG_SPI_FLASH_VERIFY_WRITE If this option is enabled, if SPI flash write verification fails then a log error line will be written with the address, expected & actual values. This can be useful when debugging hardware SPI flash problems. CONFIG_SPI_FLASH_WARN_SETTING_ZERO_TO_ONE Log warning if writing zero bits to ones Found in: Component config > SPI Flash driver > CONFIG_SPI_FLASH_VERIFY_WRITE If this option is enabled, any SPI flash write which tries to set zero bits in the flash to ones will log a warning. Such writes will not result in the requested data appearing identically in flash once written, as SPI NOR flash can only set bits to one when an entire sector is erased. After erasing, individual bits can only be written from one to zero. Note that some software (such as SPIFFS) which is aware of SPI NOR flash may write one bits as an optimisation, relying on the data in flash becoming a bitwise AND of the new data and any existing data. Such software will log spurious warnings if this option is enabled. CONFIG_SPI_FLASH_ENABLE_COUNTERS Enable operation counters Found in: Component config > SPI Flash driver This option enables the following APIs: - esp_flash_reset_counters - esp_flash_dump_counters - esp_flash_get_counters These APIs may be used to collect performance data for spi_flash APIs and to help understand behaviour of libraries which use SPI flash. CONFIG_SPI_FLASH_ROM_DRIVER_PATCH Enable SPI flash ROM driver patched functions Found in: Component config > SPI Flash driver Enable this flag to use patched versions of SPI flash ROM driver functions. This option should be enabled, if any one of the following is true: (1) need to write to flash on ESP32-D2WD; (2) main SPI flash is connected to non-default pins; (3) main SPI flash chip is manufactured by ISSI. CONFIG_SPI_FLASH_ROM_IMPL Use esp_flash implementation in ROM Found in: Component config > SPI Flash driver Enable this flag to use new SPI flash driver functions from ROM instead of ESP-IDF. If keeping this as "n" in your project, you will have less free IRAM. But you can use all of our flash features. If making this as "y" in your project, you will increase free IRAM. But you may miss out on some flash features and support for new flash chips. Currently the ROM cannot support the following features: - SPI_FLASH_AUTO_SUSPEND (C3, S3) CONFIG_SPI_FLASH_DANGEROUS_WRITE Writing to dangerous flash regions Found in: Component config > SPI Flash driver SPI flash APIs can optionally abort or return a failure code if erasing or writing addresses that fall at the beginning of flash (covering the bootloader and partition table) or that overlap the app partition that contains the running app. It is not recommended to ever write to these regions from an IDF app, and this check prevents logic errors or corrupted firmware memory from damaging these regions. Note that this feature *does not* check calls to the esp_rom_xxx SPI flash ROM functions. These functions should not be called directly from IDF applications. Available options: - Aborts (CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS) - Fails (CONFIG_SPI_FLASH_DANGEROUS_WRITE_FAILS) - Allowed (CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED) CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE Bypass a block erase and always do sector erase Found in: Component config > SPI Flash driver Some flash chips can have very high "max" erase times, especially for block erase (32KB or 64KB). This option allows to bypass "block erase" and always do sector erase commands. This will be much slower overall in most cases, but improves latency for other code to run. CONFIG_SPI_FLASH_YIELD_DURING_ERASE Enables yield operation during flash erase Found in: Component config > SPI Flash driver This allows to yield the CPUs between erase commands. Prevents starvation of other tasks. Please use this configuration together with SPI\_FLASH\_ERASE\_YIELD\_DURATION\_MSand SPI\_FLASH\_ERASE\_YIELD\_TICKSafter carefully checking flash datasheet to avoid a watchdog timeout. For more information, please check SPI Flash API reference documenation under section OS Function. CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS Duration of erasing to yield CPUs (ms) Found in: Component config > SPI Flash driver > CONFIG_SPI_FLASH_YIELD_DURING_ERASE If a duration of one erase command is large then it will yield CPUs after finishing a current command. CONFIG_SPI_FLASH_ERASE_YIELD_TICKS CPU release time (tick) for an erase operation Found in: Component config > SPI Flash driver > CONFIG_SPI_FLASH_YIELD_DURING_ERASE Defines how many ticks will be before returning to continue a erasing. CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE Flash write chunk size Found in: Component config > SPI Flash driver Flash write is broken down in terms of multiple (smaller) write operations. This configuration options helps to set individual write chunk size, smaller value here ensures that cache (and non-IRAM resident interrupts) remains disabled for shorter duration. CONFIG_SPI_FLASH_SIZE_OVERRIDE Override flash size in bootloader header by ESPTOOLPY_FLASHSIZE Found in: Component config > SPI Flash driver SPI Flash driver uses the flash size configured in bootloader header by default. Enable this option to override flash size with latest ESPTOOLPY_FLASHSIZE value from the app header if the size in the bootloader header is incorrect. CONFIG_SPI_FLASH_CHECK_ERASE_TIMEOUT_DISABLED Flash timeout checkout disabled Found in: Component config > SPI Flash driver This option is helpful if you are using a flash chip whose timeout is quite large or unpredictable. CONFIG_SPI_FLASH_OVERRIDE_CHIP_DRIVER_LIST Override default chip driver list Found in: Component config > SPI Flash driver This option allows the chip driver list to be customized, instead of using the default list provided by ESP-IDF. When this option is enabled, the default list is no longer compiled or linked. Instead, the default_registered_chips structure must be provided by the user. See example: custom_chip_driver under examples/storage for more details. Auto-detect flash chips Contains: CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP ISSI Found in: Component config > SPI Flash driver > Auto-detect flash chips Enable this to support auto detection of ISSI chips if chip vendor not directly given by chip\_drvmember of the chip struct. This adds support for variant chips, however will extend detecting time. CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP MXIC Found in: Component config > SPI Flash driver > Auto-detect flash chips Enable this to support auto detection of MXIC chips if chip vendor not directly given by chip\_drvmember of the chip struct. This adds support for variant chips, however will extend detecting time. CONFIG_SPI_FLASH_SUPPORT_GD_CHIP GigaDevice Found in: Component config > SPI Flash driver > Auto-detect flash chips Enable this to support auto detection of GD (GigaDevice) chips if chip vendor not directly given by chip\_drvmember of the chip struct. If you are using Wrover modules, please don't disable this, otherwise your flash may not work in 4-bit mode. This adds support for variant chips, however will extend detecting time and image size. Note that the default chip driver supports the GD chips with product ID 60H. CONFIG_SPI_FLASH_SUPPORT_WINBOND_CHIP Winbond Found in: Component config > SPI Flash driver > Auto-detect flash chips Enable this to support auto detection of Winbond chips if chip vendor not directly given by chip\_drvmember of the chip struct. This adds support for variant chips, however will extend detecting time. CONFIG_SPI_FLASH_SUPPORT_BOYA_CHIP BOYA Found in: Component config > SPI Flash driver > Auto-detect flash chips Enable this to support auto detection of BOYA chips if chip vendor not directly given by chip\_drvmember of the chip struct. This adds support for variant chips, however will extend detecting time. CONFIG_SPI_FLASH_SUPPORT_TH_CHIP TH Found in: Component config > SPI Flash driver > Auto-detect flash chips Enable this to support auto detection of TH chips if chip vendor not directly given by chip\_drvmember of the chip struct. This adds support for variant chips, however will extend detecting time. CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE Enable encrypted partition read/write operations Found in: Component config > SPI Flash driver This option enables flash read/write operations to encrypted partition/s. This option is kept enabled irrespective of state of flash encryption feature. However, in case application is not using flash encryption feature and is in need of some additional memory from IRAM region (~1KB) then this config can be disabled. SPIFFS Configuration Contains: CONFIG_SPIFFS_MAX_PARTITIONS Maximum Number of Partitions Found in: Component config > SPIFFS Configuration Define maximum number of partitions that can be mounted. - Range: - - from 1 to 10 - Default value: - - 3 SPIFFS Cache Configuration Contains: CONFIG_SPIFFS_CACHE Enable SPIFFS Cache Found in: Component config > SPIFFS Configuration > SPIFFS Cache Configuration Enables/disable memory read caching of nucleus file system operations. - Default value: - - Yes (enabled) CONFIG_SPIFFS_CACHE_WR Enable SPIFFS Write Caching Found in: Component config > SPIFFS Configuration > SPIFFS Cache Configuration > CONFIG_SPIFFS_CACHE Enables memory write caching for file descriptors in hydrogen. - Default value: - - Yes (enabled) CONFIG_SPIFFS_CACHE_STATS Enable SPIFFS Cache Statistics Found in: Component config > SPIFFS Configuration > SPIFFS Cache Configuration > CONFIG_SPIFFS_CACHE Enable/disable statistics on caching. Debug/test purpose only. - Default value: - - No (disabled) CONFIG_SPIFFS_PAGE_CHECK Enable SPIFFS Page Check Found in: Component config > SPIFFS Configuration Always check header of each accessed page to ensure consistent state. If enabled it will increase number of reads from flash, especially if cache is disabled. - Default value: - - Yes (enabled) CONFIG_SPIFFS_GC_MAX_RUNS Set Maximum GC Runs Found in: Component config > SPIFFS Configuration Define maximum number of GC runs to perform to reach desired free pages. - Range: - - from 1 to 10000 - Default value: - - 10 CONFIG_SPIFFS_GC_STATS Enable SPIFFS GC Statistics Found in: Component config > SPIFFS Configuration Enable/disable statistics on gc. Debug/test purpose only. - Default value: - - No (disabled) CONFIG_SPIFFS_PAGE_SIZE SPIFFS logical page size Found in: Component config > SPIFFS Configuration Logical page size of SPIFFS partition, in bytes. Must be multiple of flash page size (which is usually 256 bytes). Larger page sizes reduce overhead when storing large files, and improve filesystem performance when reading large files. Smaller page sizes reduce overhead when storing small (< page size) files. - Range: - - from 256 to 1024 - Default value: - - 256 CONFIG_SPIFFS_OBJ_NAME_LEN Set SPIFFS Maximum Name Length Found in: Component config > SPIFFS Configuration Object name maximum length. Note that this length include the zero-termination character, meaning maximum string of characters can at most be SPIFFS_OBJ_NAME_LEN - 1. SPIFFS_OBJ_NAME_LEN + SPIFFS_META_LENGTH should not exceed SPIFFS_PAGE_SIZE - 64. - Range: - - from 1 to 256 - Default value: - - 32 CONFIG_SPIFFS_FOLLOW_SYMLINKS Enable symbolic links for image creation Found in: Component config > SPIFFS Configuration If this option is enabled, symbolic links are taken into account during partition image creation. - Default value: - - No (disabled) CONFIG_SPIFFS_USE_MAGIC Enable SPIFFS Filesystem Magic Found in: Component config > SPIFFS Configuration Enable this to have an identifiable spiffs filesystem. This will look for a magic in all sectors to determine if this is a valid spiffs system or not at mount time. - Default value: - - Yes (enabled) CONFIG_SPIFFS_USE_MAGIC_LENGTH Enable SPIFFS Filesystem Length Magic Found in: Component config > SPIFFS Configuration > CONFIG_SPIFFS_USE_MAGIC If this option is enabled, the magic will also be dependent on the length of the filesystem. For example, a filesystem configured and formatted for 4 megabytes will not be accepted for mounting with a configuration defining the filesystem as 2 megabytes. - Default value: - - Yes (enabled) CONFIG_SPIFFS_META_LENGTH Size of per-file metadata field Found in: Component config > SPIFFS Configuration This option sets the number of extra bytes stored in the file header. These bytes can be used in an application-specific manner. Set this to at least 4 bytes to enable support for saving file modification time. SPIFFS_OBJ_NAME_LEN + SPIFFS_META_LENGTH should not exceed SPIFFS_PAGE_SIZE - 64. - Default value: - - 4 CONFIG_SPIFFS_USE_MTIME Save file modification time Found in: Component config > SPIFFS Configuration If enabled, then the first 4 bytes of per-file metadata will be used to store file modification time (mtime), accessible through stat/fstat functions. Modification time is updated when the file is opened. - Default value: - - Yes (enabled) CONFIG_SPIFFS_MTIME_WIDE_64_BITS The time field occupies 64 bits in the image instead of 32 bits Found in: Component config > SPIFFS Configuration If this option is not set, the time field is 32 bits (up to 2106 year), otherwise it is 64 bits and make sure it matches SPIFFS_META_LENGTH. If the chip already has the spiffs image with the time field = 32 bits then this option cannot be applied in this case. Erase it first before using this option. To resolve the Y2K38 problem for the spiffs, use a toolchain with 64-bit time_t support. - Default value: - - No (disabled) if CONFIG_SPIFFS_META_LENGTH >= 8 Debug Configuration Contains: CONFIG_SPIFFS_DBG Enable general SPIFFS debug Found in: Component config > SPIFFS Configuration > Debug Configuration Enabling this option will print general debug mesages to the console. - Default value: - - No (disabled) CONFIG_SPIFFS_API_DBG Enable SPIFFS API debug Found in: Component config > SPIFFS Configuration > Debug Configuration Enabling this option will print API debug mesages to the console. - Default value: - - No (disabled) CONFIG_SPIFFS_GC_DBG Enable SPIFFS Garbage Cleaner debug Found in: Component config > SPIFFS Configuration > Debug Configuration Enabling this option will print GC debug mesages to the console. - Default value: - - No (disabled) CONFIG_SPIFFS_CACHE_DBG Enable SPIFFS Cache debug Found in: Component config > SPIFFS Configuration > Debug Configuration Enabling this option will print cache debug mesages to the console. - Default value: - - No (disabled) CONFIG_SPIFFS_CHECK_DBG Enable SPIFFS Filesystem Check debug Found in: Component config > SPIFFS Configuration > Debug Configuration Enabling this option will print Filesystem Check debug mesages to the console. - Default value: - - No (disabled) CONFIG_SPIFFS_TEST_VISUALISATION Enable SPIFFS Filesystem Visualization Found in: Component config > SPIFFS Configuration > Debug Configuration Enable this option to enable SPIFFS_vis function in the API. - Default value: - - No (disabled) TCP Transport Contains: Websocket Contains: CONFIG_WS_TRANSPORT Enable Websocket Transport Found in: Component config > TCP Transport > Websocket Enable support for creating websocket transport. - Default value: - - Yes (enabled) CONFIG_WS_BUFFER_SIZE Websocket transport buffer size Found in: Component config > TCP Transport > Websocket > CONFIG_WS_TRANSPORT Size of the buffer used for constructing the HTTP Upgrade request during connect - Default value: - - 1024 CONFIG_WS_DYNAMIC_BUFFER Using dynamic websocket transport buffer Found in: Component config > TCP Transport > Websocket > CONFIG_WS_TRANSPORT If enable this option, websocket transport buffer will be freed after connection succeed to save more heap. - Default value: - - No (disabled) Ultra Low Power (ULP) Co-processor Contains: CONFIG_ULP_COPROC_ENABLED Enable Ultra Low Power (ULP) Co-processor Found in: Component config > Ultra Low Power (ULP) Co-processor Enable this feature if you plan to use the ULP Co-processor. Once this option is enabled, further ULP co-processor configuration will appear in the menu. - Default value: - - No (disabled) CONFIG_ULP_COPROC_TYPE ULP Co-processor type Found in: Component config > Ultra Low Power (ULP) Co-processor > CONFIG_ULP_COPROC_ENABLED Choose the ULP Coprocessor type: ULP FSM (Finite State Machine) or ULP RISC-V. Available options: - ULP FSM (Finite State Machine) (CONFIG_ULP_COPROC_TYPE_FSM) - ULP RISC-V (CONFIG_ULP_COPROC_TYPE_RISCV) - LP core RISC-V (CONFIG_ULP_COPROC_TYPE_LP_CORE) CONFIG_ULP_COPROC_RESERVE_MEM RTC slow memory reserved for coprocessor Found in: Component config > Ultra Low Power (ULP) Co-processor > CONFIG_ULP_COPROC_ENABLED Bytes of memory to reserve for ULP Co-processor firmware & data. Data is reserved at the beginning of RTC slow memory. - Range: - - from 32 to 8176 if CONFIG_ULP_COPROC_ENABLED - Default value: - - 512 if CONFIG_ULP_COPROC_ENABLED ULP RISC-V Settings Contains: CONFIG_ULP_RISCV_UART_BAUDRATE Baudrate used by the bitbanged ULP RISC-V UART driver Found in: Component config > Ultra Low Power (ULP) Co-processor > ULP RISC-V Settings The accuracy of the bitbanged UART driver is limited, it is not recommend to increase the value above 19200. - Default value: - - 9600 if CONFIG_ULP_COPROC_TYPE_RISCV CONFIG_ULP_RISCV_I2C_RW_TIMEOUT Set timeout for ULP RISC-V I2C transaction timeout in ticks. Found in: Component config > Ultra Low Power (ULP) Co-processor > ULP RISC-V Settings Set the ULP RISC-V I2C read/write timeout. Set this value to -1 if the ULP RISC-V I2C read and write APIs should wait forever. Please note that the tick rate of the ULP co-processor would be different than the OS tick rate of the main core and therefore can have different timeout value depending on which core the API is invoked on. - Range: - - from -1 to 4294967295 if CONFIG_ULP_COPROC_TYPE_RISCV - Default value: - - 500 if CONFIG_ULP_COPROC_TYPE_RISCV Unity unit testing library Contains: CONFIG_UNITY_ENABLE_FLOAT Support for float type Found in: Component config > Unity unit testing library If not set, assertions on float arguments will not be available. - Default value: - - Yes (enabled) CONFIG_UNITY_ENABLE_DOUBLE Support for double type Found in: Component config > Unity unit testing library If not set, assertions on double arguments will not be available. - Default value: - - Yes (enabled) CONFIG_UNITY_ENABLE_64BIT Support for 64-bit integer types Found in: Component config > Unity unit testing library If not set, assertions on 64-bit integer types will always fail. If this feature is enabled, take care not to pass pointers (which are 32 bit) to UNITY_ASSERT_EQUAL, as that will cause pointer-to-int-cast warnings. - Default value: - - No (disabled) CONFIG_UNITY_ENABLE_COLOR Colorize test output Found in: Component config > Unity unit testing library If set, Unity will colorize test results using console escape sequences. - Default value: - - No (disabled) CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER Include ESP-IDF test registration/running helpers Found in: Component config > Unity unit testing library If set, then the following features will be available: - TEST_CASE macro which performs automatic registration of test functions - Functions to run registered test functions: unity_run_all_tests, unity_run_tests_with_filter, unity_run_single_test_by_name. - Interactive menu which lists test cases and allows choosing the tests to be run, available via unity_run_menu function. Disable if a different test registration mechanism is used. - Default value: - - Yes (enabled) CONFIG_UNITY_ENABLE_FIXTURE Include Unity test fixture Found in: Component config > Unity unit testing library If set, unity_fixture.h header file and associated source files are part of the build. These provide an optional set of macros and functions to implement test groups. - Default value: - - No (disabled) CONFIG_UNITY_ENABLE_BACKTRACE_ON_FAIL Print a backtrace when a unit test fails Found in: Component config > Unity unit testing library If set, the unity framework will print the backtrace information before jumping back to the test menu. The jumping is usually occurs in assert functions such as TEST_ASSERT, TEST_FAIL etc. - Default value: - - No (disabled) USB-OTG Contains: CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE Largest size (in bytes) of transfers to/from default endpoints Found in: Component config > USB-OTG Each USB device attached is allocated a dedicated buffer for its OUT/IN transfers to/from the device's control endpoint. The maximum size of that buffer is determined by this option. The limited size of the transfer buffer have the following implications: - The maximum length of control transfers is limited - Device's with configuration descriptors larger than this limit cannot be supported - Default value: - - 256 if SOC_USB_OTG_SUPPORTED CONFIG_USB_HOST_HW_BUFFER_BIAS Hardware FIFO size biasing Found in: Component config > USB-OTG The underlying hardware has size adjustable FIFOs to cache USB packets on reception (IN) or for transmission (OUT). The size of these FIFOs will affect the largest MPS (maximum packet size) and the maximum number of packets that can be cached at any one time. The hardware contains the following FIFOS: RX (for all IN packets), Non-periodic TX (for Bulk and Control OUT packets), and Periodic TX (for Interrupt and Isochronous OUT packets). This configuration option allows biasing the FIFO sizes towards a particular use case, which may be necessary for devices that have endpoints with large MPS. The MPS limits for each biasing are listed below: Balanced: - IN (all transfer types), 408 bytes - OUT non-periodic (Bulk/Control), 192 bytes (i.e., 3 x 64 byte packets) - OUT periodic (Interrupt/Isochronous), 192 bytes Bias IN: - IN (all transfer types), 600 bytes - OUT non-periodic (Bulk/Control), 64 bytes (i.e., 1 x 64 byte packets) - OUT periodic (Interrupt/Isochronous), 128 bytes Bias Periodic OUT: - IN (all transfer types), 128 bytes - OUT non-periodic (Bulk/Control), 64 bytes (i.e., 1 x 64 byte packets) - OUT periodic (Interrupt/Isochronous), 600 bytes Available options: - Balanced (CONFIG_USB_HOST_HW_BUFFER_BIAS_BALANCED) - Bias IN (CONFIG_USB_HOST_HW_BUFFER_BIAS_IN) - Periodic OUT (CONFIG_USB_HOST_HW_BUFFER_BIAS_PERIODIC_OUT) Root Hub configuration Contains: CONFIG_USB_HOST_DEBOUNCE_DELAY_MS Debounce delay in ms Found in: Component config > USB-OTG > Root Hub configuration On connection of a USB device, the USB 2.0 specification requires a "debounce interval with a minimum duration of 100ms" to allow the connection to stabilize (see USB 2.0 chapter 7.1.7.3 for more details). During the debounce interval, no new connection/disconnection events are registered. The default value is set to 250 ms to be safe. - Default value: - - 250 if SOC_USB_OTG_SUPPORTED CONFIG_USB_HOST_RESET_HOLD_MS Reset hold in ms Found in: Component config > USB-OTG > Root Hub configuration The reset signaling can be generated on any Hub or Host Controller port by request from the USB System Software. The USB 2.0 specification requires that "the reset signaling must be driven for a minimum of 10ms" (see USB 2.0 chapter 7.1.7.5 for more details). After the reset, the hub port will transition to the Enabled state (refer to Section 11.5). The default value is set to 30 ms to be safe. - Default value: - - 30 if SOC_USB_OTG_SUPPORTED CONFIG_USB_HOST_RESET_RECOVERY_MS Reset recovery delay in ms Found in: Component config > USB-OTG > Root Hub configuration After a port stops driving the reset signal, the USB 2.0 specification requires that the "USB System Software guarantees a minimum of 10 ms for reset recovery" before the attached device is expected to respond to data transfers (see USB 2.0 chapter 7.1.7.3 for more details). The device may ignore any data transfers during the recovery interval. The default value is set to 30 ms to be safe. - Default value: - - 30 if SOC_USB_OTG_SUPPORTED CONFIG_USB_HOST_SET_ADDR_RECOVERY_MS SetAddress() recovery time in ms Found in: Component config > USB-OTG > Root Hub configuration "After successful completion of the Status stage, the device is allowed a SetAddress() recovery interval of 2 ms. At the end of this interval, the device must be able to accept Setup packets addressed to the new address. Also, at the end of the recovery interval, the device must not respond to tokens sent to the old address (unless, of course, the old and new address is the same)." See USB 2.0 chapter 9.2.6.3 for more details. The default value is set to 10 ms to be safe. - Default value: - - 10 if SOC_USB_OTG_SUPPORTED CONFIG_USB_HOST_ENABLE_ENUM_FILTER_CALLBACK Enable enumeration filter callback Found in: Component config > USB-OTG The enumeration filter callback is called before enumeration of each newly attached device. This callback allows users to control whether a device should be enumerated, and what configuration number to use when enumerating a device. If enabled, the enumeration filter callback can be set via 'usb_host_config_t' when calling 'usb_host_install()'. - Default value: - - No (disabled) if SOC_USB_OTG_SUPPORTED Virtual file system Contains: CONFIG_VFS_SUPPORT_IO Provide basic I/O functions Found in: Component config > Virtual file system If enabled, the following functions are provided by the VFS component. open, close, read, write, pread, pwrite, lseek, fstat, fsync, ioctl, fcntl Filesystem drivers can then be registered to handle these functions for specific paths. Disabling this option can save memory when the support for these functions is not required. Note that the following functions can still be used with socket file descriptors when this option is disabled: close, read, write, ioctl, fcntl. - Default value: - - Yes (enabled) CONFIG_VFS_SUPPORT_DIR Provide directory related functions Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO If enabled, the following functions are provided by the VFS component. stat, link, unlink, rename, utime, access, truncate, rmdir, mkdir, opendir, closedir, readdir, readdir_r, seekdir, telldir, rewinddir Filesystem drivers can then be registered to handle these functions for specific paths. Disabling this option can save memory when the support for these functions is not required. - Default value: - - Yes (enabled) CONFIG_VFS_SUPPORT_SELECT Provide select function Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO If enabled, select function is provided by the VFS component, and can be used on peripheral file descriptors (such as UART) and sockets at the same time. If disabled, the default select implementation will be provided by LWIP for sockets only. Disabling this option can reduce code size if support for "select" on UART file descriptors is not required. CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT Suppress select() related debug outputs Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO > CONFIG_VFS_SUPPORT_SELECT Select() related functions might produce an unconveniently lot of debug outputs when one sets the default log level to DEBUG or higher. It is possible to suppress these debug outputs by enabling this option. - Default value: - - Yes (enabled) CONFIG_VFS_SELECT_IN_RAM Make VFS driver select() callbacks IRAM-safe Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO > CONFIG_VFS_SUPPORT_SELECT If enabled, VFS driver select() callback function will be placed in IRAM. - Default value: - - No (disabled) CONFIG_VFS_SUPPORT_TERMIOS Provide termios.h functions Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO Disabling this option can save memory when the support for termios.h is not required. - Default value: - - Yes (enabled) CONFIG_VFS_MAX_COUNT Maximum Number of Virtual Filesystems Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO Define maximum number of virtual filesystems that can be registered. - Range: - - from 1 to 20 - Default value: - - 8 Host File System I/O (Semihosting) Contains: CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS Host FS: Maximum number of the host filesystem mount points Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO > Host File System I/O (Semihosting) Define maximum number of host filesystem mount points. - Default value: - - 1 Wear Levelling Contains: CONFIG_WL_SECTOR_SIZE Wear Levelling library sector size Found in: Component config > Wear Levelling Sector size used by wear levelling library. You can set default sector size or size that will fit to the flash device sector size. With sector size set to 4096 bytes, wear levelling library is more efficient. However if FAT filesystem is used on top of wear levelling library, it will need more temporary storage: 4096 bytes for each mounted filesystem and 4096 bytes for each opened file. With sector size set to 512 bytes, wear levelling library will perform more operations with flash memory, but less RAM will be used by FAT filesystem library (512 bytes for the filesystem and 512 bytes for each file opened). Available options: - 512 (CONFIG_WL_SECTOR_SIZE_512) - 4096 (CONFIG_WL_SECTOR_SIZE_4096) CONFIG_WL_SECTOR_MODE Sector store mode Found in: Component config > Wear Levelling Specify the mode to store data into flash: - In Performance mode a data will be stored to the RAM and then stored back to the flash. Compared to the Safety mode, this operation is faster, but if power will be lost when erase sector operation is in progress, then the data from complete flash device sector will be lost. - In Safety mode data from complete flash device sector will be read from flash, modified, and then stored back to flash. Compared to the Performance mode, this operation is slower, but if power is lost during erase sector operation, then the data from full flash device sector will not be lost. Available options: - Perfomance (CONFIG_WL_SECTOR_MODE_PERF) - Safety (CONFIG_WL_SECTOR_MODE_SAFE) Wi-Fi Provisioning Manager Contains: CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES Max Wi-Fi Scan Result Entries Found in: Component config > Wi-Fi Provisioning Manager This sets the maximum number of entries of Wi-Fi scan results that will be kept by the provisioning manager - Range: - - from 1 to 255 - Default value: - - 16 CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT Provisioning auto-stop timeout Found in: Component config > Wi-Fi Provisioning Manager Time (in seconds) after which the Wi-Fi provisioning manager will auto-stop after connecting to a Wi-Fi network successfully. - Range: - - from 5 to 600 - Default value: - - 30 CONFIG_WIFI_PROV_BLE_BONDING Enable BLE bonding Found in: Component config > Wi-Fi Provisioning Manager This option is applicable only when provisioning transport is BLE. CONFIG_WIFI_PROV_BLE_SEC_CONN Enable BLE Secure connection flag Found in: Component config > Wi-Fi Provisioning Manager Used to enable Secure connection support when provisioning transport is BLE. - Default value: - - Yes (enabled) if CONFIG_BT_NIMBLE_ENABLED CONFIG_WIFI_PROV_BLE_FORCE_ENCRYPTION Force Link Encryption during characteristic Read / Write Found in: Component config > Wi-Fi Provisioning Manager Used to enforce link encryption when attempting to read / write characteristic CONFIG_WIFI_PROV_KEEP_BLE_ON_AFTER_PROV Keep BT on after provisioning is done Found in: Component config > Wi-Fi Provisioning Manager CONFIG_WIFI_PROV_DISCONNECT_AFTER_PROV Terminate connection after provisioning is done Found in: Component config > Wi-Fi Provisioning Manager > CONFIG_WIFI_PROV_KEEP_BLE_ON_AFTER_PROV - Default value: - - Yes (enabled) if CONFIG_WIFI_PROV_KEEP_BLE_ON_AFTER_PROV CONFIG_WIFI_PROV_STA_SCAN_METHOD Wifi Provisioning Scan Method Found in: Component config > Wi-Fi Provisioning Manager Available options: - All Channel Scan (CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN) Scan will end after scanning the entire channel. This option is useful in Mesh WiFi Systems. - Fast Scan (CONFIG_WIFI_PROV_STA_FAST_SCAN) Scan will end after an AP matching with the SSID has been detected. CONFIG_IDF_EXPERIMENTAL_FEATURES Make experimental features visible Found in: By enabling this option, ESP-IDF experimental feature options will be visible. Note you should still enable a certain experimental feature option to use it, and you should read the corresponding risk warning and known issue list carefully. Current experimental feature list: - CONFIG_ESPTOOLPY_FLASHFREQ_120M && CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_DTR - CONFIG_SPIRAM_SPEED_120M && CONFIG_SPIRAM_MODE_OCT - CONFIG_BOOTLOADER_CACHE_32BIT_ADDR_QUAD_FLASH - CONFIG_MBEDTLS_USE_CRYPTO_ROM_IMPL - Default value: - - No (disabled) Deprecated options and their replacements CONFIG_A2DP_ENABLE (CONFIG_BT_A2DP_ENABLE) - CONFIG_A2D_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_A2D_TRACE_LEVEL) CONFIG_A2D_TRACE_LEVEL_NONE CONFIG_A2D_TRACE_LEVEL_ERROR CONFIG_A2D_TRACE_LEVEL_WARNING CONFIG_A2D_TRACE_LEVEL_API CONFIG_A2D_TRACE_LEVEL_EVENT CONFIG_A2D_TRACE_LEVEL_DEBUG CONFIG_A2D_TRACE_LEVEL_VERBOSE - CONFIG_ADC2_DISABLE_DAC (CONFIG_ADC_DISABLE_DAC) - CONFIG_APPL_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_APPL_TRACE_LEVEL) CONFIG_APPL_TRACE_LEVEL_NONE CONFIG_APPL_TRACE_LEVEL_ERROR CONFIG_APPL_TRACE_LEVEL_WARNING CONFIG_APPL_TRACE_LEVEL_API CONFIG_APPL_TRACE_LEVEL_EVENT CONFIG_APPL_TRACE_LEVEL_DEBUG CONFIG_APPL_TRACE_LEVEL_VERBOSE - CONFIG_APP_ANTI_ROLLBACK (CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK) CONFIG_APP_ROLLBACK_ENABLE (CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE) CONFIG_APP_SECURE_VERSION (CONFIG_BOOTLOADER_APP_SECURE_VERSION) CONFIG_APP_SECURE_VERSION_SIZE_EFUSE_FIELD (CONFIG_BOOTLOADER_APP_SEC_VER_SIZE_EFUSE_FIELD) - CONFIG_AVCT_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_AVCT_TRACE_LEVEL) CONFIG_AVCT_TRACE_LEVEL_NONE CONFIG_AVCT_TRACE_LEVEL_ERROR CONFIG_AVCT_TRACE_LEVEL_WARNING CONFIG_AVCT_TRACE_LEVEL_API CONFIG_AVCT_TRACE_LEVEL_EVENT CONFIG_AVCT_TRACE_LEVEL_DEBUG CONFIG_AVCT_TRACE_LEVEL_VERBOSE - - CONFIG_AVDT_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_AVDT_TRACE_LEVEL) CONFIG_AVDT_TRACE_LEVEL_NONE CONFIG_AVDT_TRACE_LEVEL_ERROR CONFIG_AVDT_TRACE_LEVEL_WARNING CONFIG_AVDT_TRACE_LEVEL_API CONFIG_AVDT_TRACE_LEVEL_EVENT CONFIG_AVDT_TRACE_LEVEL_DEBUG CONFIG_AVDT_TRACE_LEVEL_VERBOSE - - CONFIG_AVRC_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_AVRC_TRACE_LEVEL) CONFIG_AVRC_TRACE_LEVEL_NONE CONFIG_AVRC_TRACE_LEVEL_ERROR CONFIG_AVRC_TRACE_LEVEL_WARNING CONFIG_AVRC_TRACE_LEVEL_API CONFIG_AVRC_TRACE_LEVEL_EVENT CONFIG_AVRC_TRACE_LEVEL_DEBUG CONFIG_AVRC_TRACE_LEVEL_VERBOSE - CONFIG_BLE_ACTIVE_SCAN_REPORT_ADV_SCAN_RSP_INDIVIDUALLY (CONFIG_BT_BLE_ACT_SCAN_REP_ADV_SCAN) CONFIG_BLE_ADV_REPORT_DISCARD_THRSHOLD (CONFIG_BTDM_BLE_ADV_REPORT_DISCARD_THRSHOLD) CONFIG_BLE_ADV_REPORT_FLOW_CONTROL_NUM (CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_NUM) CONFIG_BLE_ADV_REPORT_FLOW_CONTROL_SUPPORTED (CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP) CONFIG_BLE_ESTABLISH_LINK_CONNECTION_TIMEOUT (CONFIG_BT_BLE_ESTAB_LINK_CONN_TOUT) CONFIG_BLE_HOST_QUEUE_CONGESTION_CHECK (CONFIG_BT_BLE_HOST_QUEUE_CONG_CHECK) CONFIG_BLE_MESH_GATT_PROXY (CONFIG_BLE_MESH_GATT_PROXY_SERVER) CONFIG_BLE_MESH_SCAN_DUPLICATE_EN (CONFIG_BTDM_BLE_MESH_SCAN_DUPL_EN) CONFIG_BLE_SCAN_DUPLICATE (CONFIG_BTDM_BLE_SCAN_DUPL) CONFIG_BLE_SMP_ENABLE (CONFIG_BT_BLE_SMP_ENABLE) CONFIG_BLUEDROID_MEM_DEBUG (CONFIG_BT_BLUEDROID_MEM_DEBUG) - CONFIG_BLUEDROID_PINNED_TO_CORE_CHOICE (CONFIG_BT_BLUEDROID_PINNED_TO_CORE_CHOICE) CONFIG_BLUEDROID_PINNED_TO_CORE_0 CONFIG_BLUEDROID_PINNED_TO_CORE_1 - - CONFIG_BLUFI_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL) CONFIG_BLUFI_TRACE_LEVEL_NONE CONFIG_BLUFI_TRACE_LEVEL_ERROR CONFIG_BLUFI_TRACE_LEVEL_WARNING CONFIG_BLUFI_TRACE_LEVEL_API CONFIG_BLUFI_TRACE_LEVEL_EVENT CONFIG_BLUFI_TRACE_LEVEL_DEBUG CONFIG_BLUFI_TRACE_LEVEL_VERBOSE - CONFIG_BNEP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BNEP_TRACE_LEVEL) CONFIG_BROWNOUT_DET (CONFIG_ESP_BROWNOUT_DET) - CONFIG_BROWNOUT_DET_LVL_SEL (CONFIG_ESP_BROWNOUT_DET_LVL_SEL) CONFIG_BROWNOUT_DET_LVL_SEL_0 CONFIG_BROWNOUT_DET_LVL_SEL_1 CONFIG_BROWNOUT_DET_LVL_SEL_2 CONFIG_BROWNOUT_DET_LVL_SEL_3 CONFIG_BROWNOUT_DET_LVL_SEL_4 CONFIG_BROWNOUT_DET_LVL_SEL_5 CONFIG_BROWNOUT_DET_LVL_SEL_6 CONFIG_BROWNOUT_DET_LVL_SEL_7 - - CONFIG_BTC_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BTC_TRACE_LEVEL) CONFIG_BTC_TRACE_LEVEL_NONE CONFIG_BTC_TRACE_LEVEL_ERROR CONFIG_BTC_TRACE_LEVEL_WARNING CONFIG_BTC_TRACE_LEVEL_API CONFIG_BTC_TRACE_LEVEL_EVENT CONFIG_BTC_TRACE_LEVEL_DEBUG CONFIG_BTC_TRACE_LEVEL_VERBOSE - CONFIG_BTC_TASK_STACK_SIZE (CONFIG_BT_BTC_TASK_STACK_SIZE) CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN (CONFIG_BTDM_CTRL_BLE_MAX_CONN) CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN (CONFIG_BTDM_CTRL_BR_EDR_MAX_ACL_CONN) CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN (CONFIG_BTDM_CTRL_BR_EDR_MAX_SYNC_CONN) CONFIG_BTDM_CONTROLLER_FULL_SCAN_SUPPORTED (CONFIG_BTDM_CTRL_FULL_SCAN_SUPPORTED) - CONFIG_BTDM_CONTROLLER_HCI_MODE_CHOICE (CONFIG_BTDM_CTRL_HCI_MODE_CHOICE) CONFIG_BTDM_CONTROLLER_HCI_MODE_VHCI CONFIG_BTDM_CONTROLLER_HCI_MODE_UART_H4 - - CONFIG_BTDM_CONTROLLER_MODE (CONFIG_BTDM_CTRL_MODE) CONFIG_BTDM_CONTROLLER_MODE_BLE_ONLY CONFIG_BTDM_CONTROLLER_MODE_BR_EDR_ONLY CONFIG_BTDM_CONTROLLER_MODE_BTDM - CONFIG_BTDM_CONTROLLER_MODEM_SLEEP (CONFIG_BTDM_CTRL_MODEM_SLEEP) CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE_CHOICE (CONFIG_BTDM_CTRL_PINNED_TO_CORE_CHOICE) - CONFIG_BTH_LOG_SDP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_SDP_TRACE_LEVEL) CONFIG_SDP_TRACE_LEVEL_NONE CONFIG_SDP_TRACE_LEVEL_ERROR CONFIG_SDP_TRACE_LEVEL_WARNING CONFIG_SDP_TRACE_LEVEL_API CONFIG_SDP_TRACE_LEVEL_EVENT CONFIG_SDP_TRACE_LEVEL_DEBUG CONFIG_SDP_TRACE_LEVEL_VERBOSE - - CONFIG_BTIF_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BTIF_TRACE_LEVEL) CONFIG_BTIF_TRACE_LEVEL_NONE CONFIG_BTIF_TRACE_LEVEL_ERROR CONFIG_BTIF_TRACE_LEVEL_WARNING CONFIG_BTIF_TRACE_LEVEL_API CONFIG_BTIF_TRACE_LEVEL_EVENT CONFIG_BTIF_TRACE_LEVEL_DEBUG CONFIG_BTIF_TRACE_LEVEL_VERBOSE - - CONFIG_BTM_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BTM_TRACE_LEVEL) CONFIG_BTM_TRACE_LEVEL_NONE CONFIG_BTM_TRACE_LEVEL_ERROR CONFIG_BTM_TRACE_LEVEL_WARNING CONFIG_BTM_TRACE_LEVEL_API CONFIG_BTM_TRACE_LEVEL_EVENT CONFIG_BTM_TRACE_LEVEL_DEBUG CONFIG_BTM_TRACE_LEVEL_VERBOSE - CONFIG_BTU_TASK_STACK_SIZE (CONFIG_BT_BTU_TASK_STACK_SIZE) CONFIG_BT_NIMBLE_ACL_BUF_COUNT (CONFIG_BT_NIMBLE_TRANSPORT_ACL_FROM_LL_COUNT) CONFIG_BT_NIMBLE_ACL_BUF_SIZE (CONFIG_BT_NIMBLE_TRANSPORT_ACL_SIZE) CONFIG_BT_NIMBLE_HCI_EVT_BUF_SIZE (CONFIG_BT_NIMBLE_TRANSPORT_EVT_SIZE) CONFIG_BT_NIMBLE_HCI_EVT_HI_BUF_COUNT (CONFIG_BT_NIMBLE_TRANSPORT_EVT_COUNT) CONFIG_BT_NIMBLE_HCI_EVT_LO_BUF_COUNT (CONFIG_BT_NIMBLE_TRANSPORT_EVT_DISCARD_COUNT) CONFIG_BT_NIMBLE_MSYS1_BLOCK_COUNT (CONFIG_BT_NIMBLE_MSYS_1_BLOCK_COUNT) CONFIG_BT_NIMBLE_TASK_STACK_SIZE (CONFIG_BT_NIMBLE_HOST_TASK_STACK_SIZE) CONFIG_CLASSIC_BT_ENABLED (CONFIG_BT_CLASSIC_ENABLED) - CONFIG_CONSOLE_UART (CONFIG_ESP_CONSOLE_UART) CONFIG_CONSOLE_UART_DEFAULT CONFIG_CONSOLE_UART_CUSTOM CONFIG_CONSOLE_UART_NONE, CONFIG_ESP_CONSOLE_UART_NONE - CONFIG_CONSOLE_UART_BAUDRATE (CONFIG_ESP_CONSOLE_UART_BAUDRATE) - CONFIG_CONSOLE_UART_NUM (CONFIG_ESP_CONSOLE_UART_NUM) CONFIG_CONSOLE_UART_CUSTOM_NUM_0 CONFIG_CONSOLE_UART_CUSTOM_NUM_1 - CONFIG_CONSOLE_UART_RX_GPIO (CONFIG_ESP_CONSOLE_UART_RX_GPIO) CONFIG_CONSOLE_UART_TX_GPIO (CONFIG_ESP_CONSOLE_UART_TX_GPIO) CONFIG_CXX_EXCEPTIONS (CONFIG_COMPILER_CXX_EXCEPTIONS) CONFIG_CXX_EXCEPTIONS_EMG_POOL_SIZE (CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE) CONFIG_DUPLICATE_SCAN_CACHE_SIZE (CONFIG_BTDM_SCAN_DUPL_CACHE_SIZE) CONFIG_EFUSE_SECURE_VERSION_EMULATE (CONFIG_BOOTLOADER_EFUSE_SECURE_VERSION_EMULATE) CONFIG_ENABLE_STATIC_TASK_CLEAN_UP_HOOK (CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP) CONFIG_ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TMO (CONFIG_APPTRACE_ONPANIC_HOST_FLUSH_TMO) CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX (CONFIG_APPTRACE_PENDING_DATA_SIZE_MAX) CONFIG_ESP32_APPTRACE_POSTMORTEM_FLUSH_TRAX_THRESH (CONFIG_APPTRACE_POSTMORTEM_FLUSH_THRESH) CONFIG_ESP32_COMPATIBLE_PRE_V2_1_BOOTLOADERS (CONFIG_APP_COMPATIBLE_PRE_V2_1_BOOTLOADERS) CONFIG_ESP32_COMPATIBLE_PRE_V3_1_BOOTLOADERS (CONFIG_APP_COMPATIBLE_PRE_V3_1_BOOTLOADERS) - CONFIG_ESP32_CORE_DUMP_DECODE (CONFIG_ESP_COREDUMP_DECODE) CONFIG_ESP32_CORE_DUMP_DECODE_INFO CONFIG_ESP32_CORE_DUMP_DECODE_DISABLE - CONFIG_ESP32_CORE_DUMP_MAX_TASKS_NUM (CONFIG_ESP_COREDUMP_MAX_TASKS_NUM) CONFIG_ESP32_CORE_DUMP_STACK_SIZE (CONFIG_ESP_COREDUMP_STACK_SIZE) CONFIG_ESP32_CORE_DUMP_UART_DELAY (CONFIG_ESP_COREDUMP_UART_DELAY) CONFIG_ESP32_DEBUG_STUBS_ENABLE (CONFIG_ESP_DEBUG_STUBS_ENABLE) CONFIG_ESP32_GCOV_ENABLE (CONFIG_APPTRACE_GCOV_ENABLE) CONFIG_ESP32_PHY_CALIBRATION_AND_DATA_STORAGE (CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE) CONFIG_ESP32_PHY_DEFAULT_INIT_IF_INVALID (CONFIG_ESP_PHY_DEFAULT_INIT_IF_INVALID) CONFIG_ESP32_PHY_INIT_DATA_ERROR (CONFIG_ESP_PHY_INIT_DATA_ERROR) CONFIG_ESP32_PHY_INIT_DATA_IN_PARTITION (CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION) CONFIG_ESP32_PHY_MAC_BB_PD (CONFIG_ESP_PHY_MAC_BB_PD) CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER (CONFIG_ESP_PHY_MAX_WIFI_TX_POWER) CONFIG_ESP32_PTHREAD_STACK_MIN (CONFIG_PTHREAD_STACK_MIN) - CONFIG_ESP32_PTHREAD_TASK_CORE_DEFAULT (CONFIG_PTHREAD_TASK_CORE_DEFAULT) CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY CONFIG_ESP32_DEFAULT_PTHREAD_CORE_0 CONFIG_ESP32_DEFAULT_PTHREAD_CORE_1 - CONFIG_ESP32_PTHREAD_TASK_NAME_DEFAULT (CONFIG_PTHREAD_TASK_NAME_DEFAULT) CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT (CONFIG_PTHREAD_TASK_PRIO_DEFAULT) CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT (CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT) CONFIG_ESP32_REDUCE_PHY_TX_POWER (CONFIG_ESP_PHY_REDUCE_TX_POWER) CONFIG_ESP32_RTC_XTAL_BOOTSTRAP_CYCLES (CONFIG_ESP_SYSTEM_RTC_EXT_XTAL_BOOTSTRAP_CYCLES) CONFIG_ESP32_SUPPORT_MULTIPLE_PHY_INIT_DATA_BIN (CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN) CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED (CONFIG_ESP_WIFI_AMPDU_RX_ENABLED) CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED (CONFIG_ESP_WIFI_AMPDU_TX_ENABLED) CONFIG_ESP32_WIFI_AMSDU_TX_ENABLED (CONFIG_ESP_WIFI_AMSDU_TX_ENABLED) CONFIG_ESP32_WIFI_CACHE_TX_BUFFER_NUM (CONFIG_ESP_WIFI_CACHE_TX_BUFFER_NUM) CONFIG_ESP32_WIFI_CSI_ENABLED (CONFIG_ESP_WIFI_CSI_ENABLED) CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM (CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM) CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM (CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM) CONFIG_ESP32_WIFI_ENABLE_WPA3_OWE_STA (CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA) CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE (CONFIG_ESP_WIFI_ENABLE_WPA3_SAE) CONFIG_ESP32_WIFI_IRAM_OPT (CONFIG_ESP_WIFI_IRAM_OPT) CONFIG_ESP32_WIFI_MGMT_SBUF_NUM (CONFIG_ESP_WIFI_MGMT_SBUF_NUM) CONFIG_ESP32_WIFI_NVS_ENABLED (CONFIG_ESP_WIFI_NVS_ENABLED) CONFIG_ESP32_WIFI_RX_BA_WIN (CONFIG_ESP_WIFI_RX_BA_WIN) CONFIG_ESP32_WIFI_RX_IRAM_OPT (CONFIG_ESP_WIFI_RX_IRAM_OPT) CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN (CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN) CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM (CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM) CONFIG_ESP32_WIFI_STATIC_TX_BUFFER_NUM (CONFIG_ESP_WIFI_STATIC_TX_BUFFER_NUM) CONFIG_ESP32_WIFI_SW_COEXIST_ENABLE (CONFIG_ESP_COEX_SW_COEXIST_ENABLE) - CONFIG_ESP32_WIFI_TASK_CORE_ID (CONFIG_ESP_WIFI_TASK_CORE_ID) CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0 CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1 - CONFIG_ESP32_WIFI_TX_BA_WIN (CONFIG_ESP_WIFI_TX_BA_WIN) - CONFIG_ESP32_WIFI_TX_BUFFER (CONFIG_ESP_WIFI_TX_BUFFER) CONFIG_ESP32_WIFI_STATIC_TX_BUFFER CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER - CONFIG_ESP_GRATUITOUS_ARP (CONFIG_LWIP_ESP_GRATUITOUS_ARP) CONFIG_ESP_SYSTEM_PD_FLASH (CONFIG_ESP_SLEEP_POWER_DOWN_FLASH) CONFIG_ESP_SYSTEM_PM_POWER_DOWN_CPU (CONFIG_PM_POWER_DOWN_CPU_IN_LIGHT_SLEEP) CONFIG_ESP_TASK_WDT (CONFIG_ESP_TASK_WDT_INIT) CONFIG_ESP_WIFI_SW_COEXIST_ENABLE (CONFIG_ESP_COEX_SW_COEXIST_ENABLE) CONFIG_EVENT_LOOP_PROFILING (CONFIG_ESP_EVENT_LOOP_PROFILING) CONFIG_FLASH_ENCRYPTION_ENABLED (CONFIG_SECURE_FLASH_ENC_ENABLED) CONFIG_FLASH_ENCRYPTION_UART_BOOTLOADER_ALLOW_CACHE (CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_CACHE) CONFIG_FLASH_ENCRYPTION_UART_BOOTLOADER_ALLOW_DECRYPT (CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_DEC) CONFIG_FLASH_ENCRYPTION_UART_BOOTLOADER_ALLOW_ENCRYPT (CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_ENC) - CONFIG_GAP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_GAP_TRACE_LEVEL) CONFIG_GAP_TRACE_LEVEL_NONE CONFIG_GAP_TRACE_LEVEL_ERROR CONFIG_GAP_TRACE_LEVEL_WARNING CONFIG_GAP_TRACE_LEVEL_API CONFIG_GAP_TRACE_LEVEL_EVENT CONFIG_GAP_TRACE_LEVEL_DEBUG CONFIG_GAP_TRACE_LEVEL_VERBOSE - CONFIG_GARP_TMR_INTERVAL (CONFIG_LWIP_GARP_TMR_INTERVAL) CONFIG_GATTC_CACHE_NVS_FLASH (CONFIG_BT_GATTC_CACHE_NVS_FLASH) CONFIG_GATTC_ENABLE (CONFIG_BT_GATTC_ENABLE) CONFIG_GATTS_ENABLE (CONFIG_BT_GATTS_ENABLE) - CONFIG_GATTS_SEND_SERVICE_CHANGE_MODE (CONFIG_BT_GATTS_SEND_SERVICE_CHANGE_MODE) CONFIG_GATTS_SEND_SERVICE_CHANGE_MANUAL CONFIG_GATTS_SEND_SERVICE_CHANGE_AUTO - - CONFIG_GATT_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_GATT_TRACE_LEVEL) CONFIG_GATT_TRACE_LEVEL_NONE CONFIG_GATT_TRACE_LEVEL_ERROR CONFIG_GATT_TRACE_LEVEL_WARNING CONFIG_GATT_TRACE_LEVEL_API CONFIG_GATT_TRACE_LEVEL_EVENT CONFIG_GATT_TRACE_LEVEL_DEBUG CONFIG_GATT_TRACE_LEVEL_VERBOSE - CONFIG_GDBSTUB_MAX_TASKS (CONFIG_ESP_GDBSTUB_MAX_TASKS) CONFIG_GDBSTUB_SUPPORT_TASKS (CONFIG_ESP_GDBSTUB_SUPPORT_TASKS) - CONFIG_HCI_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_HCI_TRACE_LEVEL) CONFIG_HCI_TRACE_LEVEL_NONE CONFIG_HCI_TRACE_LEVEL_ERROR CONFIG_HCI_TRACE_LEVEL_WARNING CONFIG_HCI_TRACE_LEVEL_API CONFIG_HCI_TRACE_LEVEL_EVENT CONFIG_HCI_TRACE_LEVEL_DEBUG CONFIG_HCI_TRACE_LEVEL_VERBOSE - CONFIG_HFP_AG_ENABLE (CONFIG_BT_HFP_AG_ENABLE) - CONFIG_HFP_AUDIO_DATA_PATH (CONFIG_BT_HFP_AUDIO_DATA_PATH) CONFIG_HFP_AUDIO_DATA_PATH_PCM CONFIG_HFP_AUDIO_DATA_PATH_HCI - CONFIG_HFP_CLIENT_ENABLE (CONFIG_BT_HFP_CLIENT_ENABLE) CONFIG_HFP_ENABLE (CONFIG_BT_HFP_ENABLE) - CONFIG_HID_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_HID_TRACE_LEVEL) CONFIG_HID_TRACE_LEVEL_NONE CONFIG_HID_TRACE_LEVEL_ERROR CONFIG_HID_TRACE_LEVEL_WARNING CONFIG_HID_TRACE_LEVEL_API CONFIG_HID_TRACE_LEVEL_EVENT CONFIG_HID_TRACE_LEVEL_DEBUG CONFIG_HID_TRACE_LEVEL_VERBOSE - CONFIG_INT_WDT (CONFIG_ESP_INT_WDT) CONFIG_INT_WDT_CHECK_CPU1 (CONFIG_ESP_INT_WDT_CHECK_CPU1) CONFIG_INT_WDT_TIMEOUT_MS (CONFIG_ESP_INT_WDT_TIMEOUT_MS) CONFIG_IPC_TASK_STACK_SIZE (CONFIG_ESP_IPC_TASK_STACK_SIZE) - CONFIG_L2CAP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL) CONFIG_L2CAP_TRACE_LEVEL_NONE CONFIG_L2CAP_TRACE_LEVEL_ERROR CONFIG_L2CAP_TRACE_LEVEL_WARNING CONFIG_L2CAP_TRACE_LEVEL_API CONFIG_L2CAP_TRACE_LEVEL_EVENT CONFIG_L2CAP_TRACE_LEVEL_DEBUG CONFIG_L2CAP_TRACE_LEVEL_VERBOSE - CONFIG_L2_TO_L3_COPY (CONFIG_LWIP_L2_TO_L3_COPY) - CONFIG_LOG_BOOTLOADER_LEVEL (CONFIG_BOOTLOADER_LOG_LEVEL) CONFIG_LOG_BOOTLOADER_LEVEL_NONE CONFIG_LOG_BOOTLOADER_LEVEL_ERROR CONFIG_LOG_BOOTLOADER_LEVEL_WARN CONFIG_LOG_BOOTLOADER_LEVEL_INFO CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE - CONFIG_MAC_BB_PD (CONFIG_ESP_PHY_MAC_BB_PD) CONFIG_MAIN_TASK_STACK_SIZE (CONFIG_ESP_MAIN_TASK_STACK_SIZE) - CONFIG_MCA_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_MCA_TRACE_LEVEL) CONFIG_MCA_TRACE_LEVEL_NONE CONFIG_MCA_TRACE_LEVEL_ERROR CONFIG_MCA_TRACE_LEVEL_WARNING CONFIG_MCA_TRACE_LEVEL_API CONFIG_MCA_TRACE_LEVEL_EVENT CONFIG_MCA_TRACE_LEVEL_DEBUG CONFIG_MCA_TRACE_LEVEL_VERBOSE - CONFIG_MCPWM_ISR_IN_IRAM (CONFIG_MCPWM_ISR_IRAM_SAFE) CONFIG_MESH_DUPLICATE_SCAN_CACHE_SIZE (CONFIG_BTDM_MESH_DUPL_SCAN_CACHE_SIZE) CONFIG_NIMBLE_ATT_PREFERRED_MTU (CONFIG_BT_NIMBLE_ATT_PREFERRED_MTU) CONFIG_NIMBLE_CRYPTO_STACK_MBEDTLS (CONFIG_BT_NIMBLE_CRYPTO_STACK_MBEDTLS) CONFIG_NIMBLE_DEBUG (CONFIG_BT_NIMBLE_DEBUG) CONFIG_NIMBLE_GAP_DEVICE_NAME_MAX_LEN (CONFIG_BT_NIMBLE_GAP_DEVICE_NAME_MAX_LEN) CONFIG_NIMBLE_HS_FLOW_CTRL (CONFIG_BT_NIMBLE_HS_FLOW_CTRL) CONFIG_NIMBLE_HS_FLOW_CTRL_ITVL (CONFIG_BT_NIMBLE_HS_FLOW_CTRL_ITVL) CONFIG_NIMBLE_HS_FLOW_CTRL_THRESH (CONFIG_BT_NIMBLE_HS_FLOW_CTRL_THRESH) CONFIG_NIMBLE_HS_FLOW_CTRL_TX_ON_DISCONNECT (CONFIG_BT_NIMBLE_HS_FLOW_CTRL_TX_ON_DISCONNECT) CONFIG_NIMBLE_L2CAP_COC_MAX_NUM (CONFIG_BT_NIMBLE_L2CAP_COC_MAX_NUM) CONFIG_NIMBLE_MAX_BONDS (CONFIG_BT_NIMBLE_MAX_BONDS) CONFIG_NIMBLE_MAX_CCCDS (CONFIG_BT_NIMBLE_MAX_CCCDS) CONFIG_NIMBLE_MAX_CONNECTIONS (CONFIG_BT_NIMBLE_MAX_CONNECTIONS) - CONFIG_NIMBLE_MEM_ALLOC_MODE (CONFIG_BT_NIMBLE_MEM_ALLOC_MODE) CONFIG_NIMBLE_MEM_ALLOC_MODE_INTERNAL CONFIG_NIMBLE_MEM_ALLOC_MODE_EXTERNAL CONFIG_NIMBLE_MEM_ALLOC_MODE_DEFAULT - CONFIG_NIMBLE_MESH (CONFIG_BT_NIMBLE_MESH) CONFIG_NIMBLE_MESH_DEVICE_NAME (CONFIG_BT_NIMBLE_MESH_DEVICE_NAME) CONFIG_NIMBLE_MESH_FRIEND (CONFIG_BT_NIMBLE_MESH_FRIEND) CONFIG_NIMBLE_MESH_GATT_PROXY (CONFIG_BT_NIMBLE_MESH_GATT_PROXY) CONFIG_NIMBLE_MESH_LOW_POWER (CONFIG_BT_NIMBLE_MESH_LOW_POWER) CONFIG_NIMBLE_MESH_PB_ADV (CONFIG_BT_NIMBLE_MESH_PB_ADV) CONFIG_NIMBLE_MESH_PB_GATT (CONFIG_BT_NIMBLE_MESH_PB_GATT) CONFIG_NIMBLE_MESH_PROV (CONFIG_BT_NIMBLE_MESH_PROV) CONFIG_NIMBLE_MESH_PROXY (CONFIG_BT_NIMBLE_MESH_PROXY) CONFIG_NIMBLE_MESH_RELAY (CONFIG_BT_NIMBLE_MESH_RELAY) CONFIG_NIMBLE_NVS_PERSIST (CONFIG_BT_NIMBLE_NVS_PERSIST) - CONFIG_NIMBLE_PINNED_TO_CORE_CHOICE (CONFIG_BT_NIMBLE_PINNED_TO_CORE_CHOICE) CONFIG_NIMBLE_PINNED_TO_CORE_0 CONFIG_NIMBLE_PINNED_TO_CORE_1 - CONFIG_NIMBLE_ROLE_BROADCASTER (CONFIG_BT_NIMBLE_ROLE_BROADCASTER) CONFIG_NIMBLE_ROLE_CENTRAL (CONFIG_BT_NIMBLE_ROLE_CENTRAL) CONFIG_NIMBLE_ROLE_OBSERVER (CONFIG_BT_NIMBLE_ROLE_OBSERVER) CONFIG_NIMBLE_ROLE_PERIPHERAL (CONFIG_BT_NIMBLE_ROLE_PERIPHERAL) CONFIG_NIMBLE_RPA_TIMEOUT (CONFIG_BT_NIMBLE_RPA_TIMEOUT) CONFIG_NIMBLE_SM_LEGACY (CONFIG_BT_NIMBLE_SM_LEGACY) CONFIG_NIMBLE_SM_SC (CONFIG_BT_NIMBLE_SM_SC) CONFIG_NIMBLE_SM_SC_DEBUG_KEYS (CONFIG_BT_NIMBLE_SM_SC_DEBUG_KEYS) CONFIG_NIMBLE_SVC_GAP_APPEARANCE (CONFIG_BT_NIMBLE_SVC_GAP_APPEARANCE) CONFIG_NIMBLE_SVC_GAP_DEVICE_NAME (CONFIG_BT_NIMBLE_SVC_GAP_DEVICE_NAME) CONFIG_NIMBLE_TASK_STACK_SIZE (CONFIG_BT_NIMBLE_HOST_TASK_STACK_SIZE) CONFIG_NO_BLOBS (CONFIG_APP_NO_BLOBS) - CONFIG_NUMBER_OF_UNIVERSAL_MAC_ADDRESS (CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES) CONFIG_TWO_UNIVERSAL_MAC_ADDRESS CONFIG_FOUR_UNIVERSAL_MAC_ADDRESS - - CONFIG_OPTIMIZATION_ASSERTION_LEVEL (CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL) CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED CONFIG_OPTIMIZATION_ASSERTIONS_SILENT CONFIG_OPTIMIZATION_ASSERTIONS_DISABLED - - CONFIG_OPTIMIZATION_COMPILER (CONFIG_COMPILER_OPTIMIZATION) CONFIG_OPTIMIZATION_LEVEL_DEBUG, CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG, CONFIG_COMPILER_OPTIMIZATION_DEFAULT CONFIG_OPTIMIZATION_LEVEL_RELEASE, CONFIG_COMPILER_OPTIMIZATION_LEVEL_RELEASE - - CONFIG_OSI_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_OSI_TRACE_LEVEL) CONFIG_OSI_TRACE_LEVEL_NONE CONFIG_OSI_TRACE_LEVEL_ERROR CONFIG_OSI_TRACE_LEVEL_WARNING CONFIG_OSI_TRACE_LEVEL_API CONFIG_OSI_TRACE_LEVEL_EVENT CONFIG_OSI_TRACE_LEVEL_DEBUG CONFIG_OSI_TRACE_LEVEL_VERBOSE - CONFIG_OTA_ALLOW_HTTP (CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP) - CONFIG_PAN_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_PAN_TRACE_LEVEL) CONFIG_PAN_TRACE_LEVEL_NONE CONFIG_PAN_TRACE_LEVEL_ERROR CONFIG_PAN_TRACE_LEVEL_WARNING CONFIG_PAN_TRACE_LEVEL_API CONFIG_PAN_TRACE_LEVEL_EVENT CONFIG_PAN_TRACE_LEVEL_DEBUG CONFIG_PAN_TRACE_LEVEL_VERBOSE - CONFIG_POST_EVENTS_FROM_IRAM_ISR (CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR) CONFIG_POST_EVENTS_FROM_ISR (CONFIG_ESP_EVENT_POST_FROM_ISR) CONFIG_PPP_CHAP_SUPPORT (CONFIG_LWIP_PPP_CHAP_SUPPORT) CONFIG_PPP_DEBUG_ON (CONFIG_LWIP_PPP_DEBUG_ON) CONFIG_PPP_MPPE_SUPPORT (CONFIG_LWIP_PPP_MPPE_SUPPORT) CONFIG_PPP_MSCHAP_SUPPORT (CONFIG_LWIP_PPP_MSCHAP_SUPPORT) CONFIG_PPP_NOTIFY_PHASE_SUPPORT (CONFIG_LWIP_PPP_NOTIFY_PHASE_SUPPORT) CONFIG_PPP_PAP_SUPPORT (CONFIG_LWIP_PPP_PAP_SUPPORT) CONFIG_PPP_SUPPORT (CONFIG_LWIP_PPP_SUPPORT) CONFIG_REDUCE_PHY_TX_POWER (CONFIG_ESP_PHY_REDUCE_TX_POWER) - CONFIG_RFCOMM_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL) CONFIG_RFCOMM_TRACE_LEVEL_NONE CONFIG_RFCOMM_TRACE_LEVEL_ERROR CONFIG_RFCOMM_TRACE_LEVEL_WARNING CONFIG_RFCOMM_TRACE_LEVEL_API CONFIG_RFCOMM_TRACE_LEVEL_EVENT CONFIG_RFCOMM_TRACE_LEVEL_DEBUG CONFIG_RFCOMM_TRACE_LEVEL_VERBOSE - - CONFIG_SCAN_DUPLICATE_TYPE (CONFIG_BTDM_SCAN_DUPL_TYPE) CONFIG_SCAN_DUPLICATE_BY_DEVICE_ADDR CONFIG_SCAN_DUPLICATE_BY_ADV_DATA CONFIG_SCAN_DUPLICATE_BY_ADV_DATA_AND_DEVICE_ADDR - CONFIG_SEMIHOSTFS_MAX_MOUNT_POINTS (CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS) - CONFIG_SMP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_SMP_TRACE_LEVEL) CONFIG_SMP_TRACE_LEVEL_NONE CONFIG_SMP_TRACE_LEVEL_ERROR CONFIG_SMP_TRACE_LEVEL_WARNING CONFIG_SMP_TRACE_LEVEL_API CONFIG_SMP_TRACE_LEVEL_EVENT CONFIG_SMP_TRACE_LEVEL_DEBUG CONFIG_SMP_TRACE_LEVEL_VERBOSE - CONFIG_SMP_SLAVE_CON_PARAMS_UPD_ENABLE (CONFIG_BT_SMP_SLAVE_CON_PARAMS_UPD_ENABLE) - CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS (CONFIG_SPI_FLASH_DANGEROUS_WRITE) CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_FAILS CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED - - CONFIG_STACK_CHECK_MODE (CONFIG_COMPILER_STACK_CHECK_MODE) CONFIG_STACK_CHECK_NONE CONFIG_STACK_CHECK_NORM CONFIG_STACK_CHECK_STRONG CONFIG_STACK_CHECK_ALL - CONFIG_SUPPORT_TERMIOS (CONFIG_VFS_SUPPORT_TERMIOS) CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT (CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT) CONFIG_SW_COEXIST_ENABLE (CONFIG_ESP_COEX_SW_COEXIST_ENABLE) CONFIG_SYSTEM_EVENT_QUEUE_SIZE (CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE) CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE (CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE) CONFIG_SYSVIEW_BUF_WAIT_TMO (CONFIG_APPTRACE_SV_BUF_WAIT_TMO) CONFIG_SYSVIEW_ENABLE (CONFIG_APPTRACE_SV_ENABLE) CONFIG_SYSVIEW_EVT_IDLE_ENABLE (CONFIG_APPTRACE_SV_EVT_IDLE_ENABLE) CONFIG_SYSVIEW_EVT_ISR_ENTER_ENABLE (CONFIG_APPTRACE_SV_EVT_ISR_ENTER_ENABLE) CONFIG_SYSVIEW_EVT_ISR_EXIT_ENABLE (CONFIG_APPTRACE_SV_EVT_ISR_EXIT_ENABLE) CONFIG_SYSVIEW_EVT_ISR_TO_SCHEDULER_ENABLE (CONFIG_APPTRACE_SV_EVT_ISR_TO_SCHED_ENABLE) CONFIG_SYSVIEW_EVT_OVERFLOW_ENABLE (CONFIG_APPTRACE_SV_EVT_OVERFLOW_ENABLE) CONFIG_SYSVIEW_EVT_TASK_CREATE_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_CREATE_ENABLE) CONFIG_SYSVIEW_EVT_TASK_START_EXEC_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_START_EXEC_ENABLE) CONFIG_SYSVIEW_EVT_TASK_START_READY_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_START_READY_ENABLE) CONFIG_SYSVIEW_EVT_TASK_STOP_EXEC_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_STOP_EXEC_ENABLE) CONFIG_SYSVIEW_EVT_TASK_STOP_READY_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_STOP_READY_ENABLE) CONFIG_SYSVIEW_EVT_TASK_TERMINATE_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_TERMINATE_ENABLE) CONFIG_SYSVIEW_EVT_TIMER_ENTER_ENABLE (CONFIG_APPTRACE_SV_EVT_TIMER_ENTER_ENABLE) CONFIG_SYSVIEW_EVT_TIMER_EXIT_ENABLE (CONFIG_APPTRACE_SV_EVT_TIMER_EXIT_ENABLE) CONFIG_SYSVIEW_MAX_TASKS (CONFIG_APPTRACE_SV_MAX_TASKS) - CONFIG_SYSVIEW_TS_SOURCE (CONFIG_APPTRACE_SV_TS_SOURCE) CONFIG_SYSVIEW_TS_SOURCE_CCOUNT CONFIG_SYSVIEW_TS_SOURCE_ESP_TIMER - CONFIG_TASK_WDT (CONFIG_ESP_TASK_WDT_INIT) CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0 (CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0) CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1 (CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1) CONFIG_TASK_WDT_PANIC (CONFIG_ESP_TASK_WDT_PANIC) CONFIG_TASK_WDT_TIMEOUT_S (CONFIG_ESP_TASK_WDT_TIMEOUT_S) CONFIG_TCPIP_RECVMBOX_SIZE (CONFIG_LWIP_TCPIP_RECVMBOX_SIZE) - CONFIG_TCPIP_TASK_AFFINITY (CONFIG_LWIP_TCPIP_TASK_AFFINITY) CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY CONFIG_TCPIP_TASK_AFFINITY_CPU0 CONFIG_TCPIP_TASK_AFFINITY_CPU1 - CONFIG_TCPIP_TASK_STACK_SIZE (CONFIG_LWIP_TCPIP_TASK_STACK_SIZE) CONFIG_TCP_MAXRTX (CONFIG_LWIP_TCP_MAXRTX) CONFIG_TCP_MSL (CONFIG_LWIP_TCP_MSL) CONFIG_TCP_MSS (CONFIG_LWIP_TCP_MSS) - CONFIG_TCP_OVERSIZE (CONFIG_LWIP_TCP_OVERSIZE) CONFIG_TCP_OVERSIZE_MSS CONFIG_TCP_OVERSIZE_QUARTER_MSS CONFIG_TCP_OVERSIZE_DISABLE - CONFIG_TCP_QUEUE_OOSEQ (CONFIG_LWIP_TCP_QUEUE_OOSEQ) CONFIG_TCP_RECVMBOX_SIZE (CONFIG_LWIP_TCP_RECVMBOX_SIZE) CONFIG_TCP_SND_BUF_DEFAULT (CONFIG_LWIP_TCP_SND_BUF_DEFAULT) CONFIG_TCP_SYNMAXRTX (CONFIG_LWIP_TCP_SYNMAXRTX) CONFIG_TCP_WND_DEFAULT (CONFIG_LWIP_TCP_WND_DEFAULT) CONFIG_TIMER_QUEUE_LENGTH (CONFIG_FREERTOS_TIMER_QUEUE_LENGTH) CONFIG_TIMER_TASK_PRIORITY (CONFIG_FREERTOS_TIMER_TASK_PRIORITY) CONFIG_TIMER_TASK_STACK_DEPTH (CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH) CONFIG_TIMER_TASK_STACK_SIZE (CONFIG_ESP_TIMER_TASK_STACK_SIZE) CONFIG_UDP_RECVMBOX_SIZE (CONFIG_LWIP_UDP_RECVMBOX_SIZE) CONFIG_WARN_WRITE_STRINGS (CONFIG_COMPILER_WARN_WRITE_STRINGS) CONFIG_WPA_11KV_SUPPORT (CONFIG_ESP_WIFI_11KV_SUPPORT) CONFIG_WPA_11R_SUPPORT (CONFIG_ESP_WIFI_11R_SUPPORT) CONFIG_WPA_DEBUG_PRINT (CONFIG_ESP_WIFI_DEBUG_PRINT) CONFIG_WPA_DPP_SUPPORT (CONFIG_ESP_WIFI_DPP_SUPPORT) CONFIG_WPA_MBEDTLS_CRYPTO (CONFIG_ESP_WIFI_MBEDTLS_CRYPTO) CONFIG_WPA_MBEDTLS_TLS_CLIENT (CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT) CONFIG_WPA_MBO_SUPPORT (CONFIG_ESP_WIFI_MBO_SUPPORT) CONFIG_WPA_SCAN_CACHE (CONFIG_ESP_WIFI_SCAN_CACHE) CONFIG_WPA_SUITE_B_192 (CONFIG_ESP_WIFI_SUITE_B_192) CONFIG_WPA_TESTING_OPTIONS (CONFIG_ESP_WIFI_TESTING_OPTIONS) CONFIG_WPA_WAPI_PSK (CONFIG_ESP_WIFI_WAPI_PSK) CONFIG_WPA_WPS_SOFTAP_REGISTRAR (CONFIG_ESP_WIFI_WPS_SOFTAP_REGISTRAR) CONFIG_WPA_WPS_STRICT (CONFIG_ESP_WIFI_WPS_STRICT)
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/kconfig.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Protocol Communication
null
espressif.com
2016-01-01
b700bd5bc237f49c
null
null
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: Communication security at the application level protocomm_security0 (no security) protocomm_security1 (Curve25519 key exchange + AES-CTR encryption/decryption) protocomm_security2 (SRP6a-based key exchange + AES-GCM encryption/decryption) Proof-of-possession (support with protocomm_security1 only) Salt and Verifier (support with protocomm_security2 only) 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: Bluetooth LE 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. See Unified Provisioning for more details about the secure handshake logic. 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: Support protocomm_security0 , with no security: CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0, this option is enabled by default. Support protocomm_security1 with Curve25519 key exchange + AES-CTR encryption/decryption: CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1, this option is enabled by default. Support protocomm_security2 with SRP6a-based key exchange + AES-GCM encryption/decryption: CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2. Note Enabling multiple security versions at once offers the ability to control them dynamically but also increases the firmware size. SoftAP + HTTP Transport Example with Security 2 For sample usage, see wifi_provisioning/src/scheme_softap.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. */ 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. */ 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. 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. */ 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 wifi_provisioning/src/scheme_softap.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. */ 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. */ 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. 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. */ protocomm_httpd_stop(pc); /* Delete, namely deallocate the protocomm instance. */ protocomm_delete(pc); } Bluetooth LE Transport Example with Security 0 For sample usage, see wifi_provisioning/src/scheme_ble.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, }, .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 Header File This header file can be included with: #include "protocomm.h" This header file is a part of the API provided by the protocomm component. To declare that your component depends on protocomm , add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Functions protocomm_t *protocomm_new(void) Create a new protocomm instance. This API will return a new dynamically allocated protocomm instance with all elements of the protocomm_t structure initialized to NULL. Returns protocomm_t* : On success NULL : No memory for allocating new instance protocomm_t* : On success NULL : No memory for allocating new instance protocomm_t* : On success Returns protocomm_t* : On success NULL : No memory for allocating new instance void protocomm_delete(protocomm_t *pc) Delete a protocomm instance. This API will deallocate a protocomm instance that was created using protocomm_new() . Parameters pc -- [in] Pointer to the protocomm instance to be deleted Parameters pc -- [in] Pointer to the protocomm instance to be deleted esp_err_t protocomm_add_endpoint(protocomm_t *pc, const char *ep_name, protocomm_req_handler_t h, void *priv_data) Add endpoint request handler for a protocomm instance. This API will bind an endpoint handler function to the specified endpoint name, along with any private data that needs to be pass to the handler at the time of call. Note An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . This function internally calls the registered add_endpoint() function of the selected transport which is a member of the protocomm_t instance structure. An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . This function internally calls the registered add_endpoint() function of the selected transport which is a member of the protocomm_t instance structure. Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string h -- [in] Endpoint handler function priv_data -- [in] Pointer to private data to be passed as a parameter to the handler function on call. Pass NULL if not needed. pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string h -- [in] Endpoint handler function priv_data -- [in] Pointer to private data to be passed as a parameter to the handler function on call. Pass NULL if not needed. pc -- [in] Pointer to the protocomm instance Returns ESP_OK : Success ESP_FAIL : Error adding endpoint / Endpoint with this name already exists ESP_ERR_NO_MEM : Error allocating endpoint resource ESP_ERR_INVALID_ARG : Null instance/name/handler arguments ESP_OK : Success ESP_FAIL : Error adding endpoint / Endpoint with this name already exists ESP_ERR_NO_MEM : Error allocating endpoint resource ESP_ERR_INVALID_ARG : Null instance/name/handler arguments ESP_OK : Success Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string h -- [in] Endpoint handler function priv_data -- [in] Pointer to private data to be passed as a parameter to the handler function on call. Pass NULL if not needed. Returns ESP_OK : Success ESP_FAIL : Error adding endpoint / Endpoint with this name already exists ESP_ERR_NO_MEM : Error allocating endpoint resource ESP_ERR_INVALID_ARG : Null instance/name/handler arguments An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . esp_err_t protocomm_remove_endpoint(protocomm_t *pc, const char *ep_name) Remove endpoint request handler for a protocomm instance. This API will remove a registered endpoint handler identified by an endpoint name. Note This function internally calls the registered remove_endpoint() function which is a member of the protocomm_t instance structure. This function internally calls the registered remove_endpoint() function which is a member of the protocomm_t instance structure. Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string pc -- [in] Pointer to the protocomm instance Returns ESP_OK : Success ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments ESP_OK : Success ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments ESP_OK : Success Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string Returns ESP_OK : Success ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments This function internally calls the registered remove_endpoint() function which is a member of the protocomm_t instance structure. esp_err_t protocomm_open_session(protocomm_t *pc, uint32_t session_id) Allocates internal resources for new transport session. Note An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . Parameters pc -- [in] Pointer to the protocomm instance session_id -- [in] Unique ID for a communication session pc -- [in] Pointer to the protocomm instance session_id -- [in] Unique ID for a communication session pc -- [in] Pointer to the protocomm instance Returns ESP_OK : Request handled successfully ESP_ERR_NO_MEM : Error allocating internal resource ESP_ERR_INVALID_ARG : Null instance/name arguments ESP_OK : Request handled successfully ESP_ERR_NO_MEM : Error allocating internal resource ESP_ERR_INVALID_ARG : Null instance/name arguments ESP_OK : Request handled successfully Parameters pc -- [in] Pointer to the protocomm instance session_id -- [in] Unique ID for a communication session Returns ESP_OK : Request handled successfully ESP_ERR_NO_MEM : Error allocating internal resource ESP_ERR_INVALID_ARG : Null instance/name arguments An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . esp_err_t protocomm_close_session(protocomm_t *pc, uint32_t session_id) Frees internal resources used by a transport session. Note An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . Parameters pc -- [in] Pointer to the protocomm instance session_id -- [in] Unique ID for a communication session pc -- [in] Pointer to the protocomm instance session_id -- [in] Unique ID for a communication session pc -- [in] Pointer to the protocomm instance Returns ESP_OK : Request handled successfully ESP_ERR_INVALID_ARG : Null instance/name arguments ESP_OK : Request handled successfully ESP_ERR_INVALID_ARG : Null instance/name arguments ESP_OK : Request handled successfully Parameters pc -- [in] Pointer to the protocomm instance session_id -- [in] Unique ID for a communication session Returns ESP_OK : Request handled successfully ESP_ERR_INVALID_ARG : Null instance/name arguments An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . esp_err_t protocomm_req_handle(protocomm_t *pc, const char *ep_name, uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen) Calls the registered handler of an endpoint session for processing incoming data and generating the response. Note An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . Resulting output buffer must be deallocated by the caller. An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . Resulting output buffer must be deallocated by the caller. Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string session_id -- [in] Unique ID for a communication session inbuf -- [in] Input buffer contains input request data which is to be processed by the registered handler inlen -- [in] Length of the input buffer outbuf -- [out] Pointer to internally allocated output buffer, where the resulting response data output from the registered handler is to be stored outlen -- [out] Buffer length of the allocated output buffer pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string session_id -- [in] Unique ID for a communication session inbuf -- [in] Input buffer contains input request data which is to be processed by the registered handler inlen -- [in] Length of the input buffer outbuf -- [out] Pointer to internally allocated output buffer, where the resulting response data output from the registered handler is to be stored outlen -- [out] Buffer length of the allocated output buffer pc -- [in] Pointer to the protocomm instance Returns ESP_OK : Request handled successfully ESP_FAIL : Internal error in execution of registered handler ESP_ERR_NO_MEM : Error allocating internal resource ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments ESP_OK : Request handled successfully ESP_FAIL : Internal error in execution of registered handler ESP_ERR_NO_MEM : Error allocating internal resource ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments ESP_OK : Request handled successfully Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string session_id -- [in] Unique ID for a communication session inbuf -- [in] Input buffer contains input request data which is to be processed by the registered handler inlen -- [in] Length of the input buffer outbuf -- [out] Pointer to internally allocated output buffer, where the resulting response data output from the registered handler is to be stored outlen -- [out] Buffer length of the allocated output buffer Returns ESP_OK : Request handled successfully ESP_FAIL : Internal error in execution of registered handler ESP_ERR_NO_MEM : Error allocating internal resource ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . esp_err_t protocomm_set_security(protocomm_t *pc, const char *ep_name, const protocomm_security_t *sec, const void *sec_params) Add endpoint security for a protocomm instance. This API will bind a security session establisher to the specified endpoint name, along with any proof of possession that may be required for authenticating a session client. Note An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . The choice of security can be any protocomm_security_t instance. Choices protocomm_security0 and protocomm_security1 and protocomm_security2 are readily available. An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . The choice of security can be any protocomm_security_t instance. Choices protocomm_security0 and protocomm_security1 and protocomm_security2 are readily available. Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string sec -- [in] Pointer to endpoint security instance sec_params -- [in] Pointer to security params (NULL if not needed) The pointer should contain the security params struct of appropriate security version. For protocomm security version 1 and 2 sec_params should contain pointer to struct of type protocomm_security1_params_t and protocmm_security2_params_t respectively. The contents of this pointer must be valid till the security session has been running and is not closed. pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string sec -- [in] Pointer to endpoint security instance sec_params -- [in] Pointer to security params (NULL if not needed) The pointer should contain the security params struct of appropriate security version. For protocomm security version 1 and 2 sec_params should contain pointer to struct of type protocomm_security1_params_t and protocmm_security2_params_t respectively. The contents of this pointer must be valid till the security session has been running and is not closed. pc -- [in] Pointer to the protocomm instance Returns ESP_OK : Success ESP_FAIL : Error adding endpoint / Endpoint with this name already exists ESP_ERR_INVALID_STATE : Security endpoint already set ESP_ERR_NO_MEM : Error allocating endpoint resource ESP_ERR_INVALID_ARG : Null instance/name/handler arguments ESP_OK : Success ESP_FAIL : Error adding endpoint / Endpoint with this name already exists ESP_ERR_INVALID_STATE : Security endpoint already set ESP_ERR_NO_MEM : Error allocating endpoint resource ESP_ERR_INVALID_ARG : Null instance/name/handler arguments ESP_OK : Success Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string sec -- [in] Pointer to endpoint security instance sec_params -- [in] Pointer to security params (NULL if not needed) The pointer should contain the security params struct of appropriate security version. For protocomm security version 1 and 2 sec_params should contain pointer to struct of type protocomm_security1_params_t and protocmm_security2_params_t respectively. The contents of this pointer must be valid till the security session has been running and is not closed. Returns ESP_OK : Success ESP_FAIL : Error adding endpoint / Endpoint with this name already exists ESP_ERR_INVALID_STATE : Security endpoint already set ESP_ERR_NO_MEM : Error allocating endpoint resource ESP_ERR_INVALID_ARG : Null instance/name/handler arguments An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . esp_err_t protocomm_unset_security(protocomm_t *pc, const char *ep_name) Remove endpoint security for a protocomm instance. This API will remove a registered security endpoint identified by an endpoint name. Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string pc -- [in] Pointer to the protocomm instance Returns ESP_OK : Success ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments ESP_OK : Success ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments ESP_OK : Success Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string Returns ESP_OK : Success ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments esp_err_t protocomm_set_version(protocomm_t *pc, const char *ep_name, const char *version) Set endpoint for version verification. This API can be used for setting an application specific protocol version which can be verified by clients through the endpoint. Note An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string version -- [in] Version identifier(name) string pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string version -- [in] Version identifier(name) string pc -- [in] Pointer to the protocomm instance Returns ESP_OK : Success ESP_FAIL : Error adding endpoint / Endpoint with this name already exists ESP_ERR_INVALID_STATE : Version endpoint already set ESP_ERR_NO_MEM : Error allocating endpoint resource ESP_ERR_INVALID_ARG : Null instance/name/handler arguments ESP_OK : Success ESP_FAIL : Error adding endpoint / Endpoint with this name already exists ESP_ERR_INVALID_STATE : Version endpoint already set ESP_ERR_NO_MEM : Error allocating endpoint resource ESP_ERR_INVALID_ARG : Null instance/name/handler arguments ESP_OK : Success Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string version -- [in] Version identifier(name) string Returns ESP_OK : Success ESP_FAIL : Error adding endpoint / Endpoint with this name already exists ESP_ERR_INVALID_STATE : Version endpoint already set ESP_ERR_NO_MEM : Error allocating endpoint resource ESP_ERR_INVALID_ARG : Null instance/name/handler arguments An endpoint must be bound to a valid protocomm instance, created using protocomm_new() . esp_err_t protocomm_unset_version(protocomm_t *pc, const char *ep_name) Remove version verification endpoint from a protocomm instance. This API will remove a registered version endpoint identified by an endpoint name. Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string pc -- [in] Pointer to the protocomm instance Returns ESP_OK : Success ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments ESP_OK : Success ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments ESP_OK : Success Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string Returns ESP_OK : Success ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments Type Definitions typedef esp_err_t (*protocomm_req_handler_t)(uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen, void *priv_data) Function prototype for protocomm endpoint handler. typedef struct protocomm protocomm_t This structure corresponds to a unique instance of protocomm returned when the API protocomm_new() is called. The remaining Protocomm APIs require this object as the first parameter. Note Structure of the protocomm object is kept private Header File This header file can be included with: #include "protocomm_security.h" This header file is a part of the API provided by the protocomm component. To declare that your component depends on protocomm , add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Structures struct protocomm_security1_params Protocomm Security 1 parameters: Proof Of Possession. struct protocomm_security2_params Protocomm Security 2 parameters: Salt and Verifier. struct protocomm_security Protocomm security object structure. The member functions are used for implementing secure protocomm sessions. Note This structure should not have any dynamic members to allow re-entrancy Public Members int ver Unique version number of security implementation int ver Unique version number of security implementation esp_err_t (*init)(protocomm_security_handle_t *handle) Function for initializing/allocating security infrastructure esp_err_t (*init)(protocomm_security_handle_t *handle) Function for initializing/allocating security infrastructure esp_err_t (*cleanup)(protocomm_security_handle_t handle) Function for deallocating security infrastructure esp_err_t (*cleanup)(protocomm_security_handle_t handle) Function for deallocating security infrastructure esp_err_t (*new_transport_session)(protocomm_security_handle_t handle, uint32_t session_id) Starts new secure transport session with specified ID esp_err_t (*new_transport_session)(protocomm_security_handle_t handle, uint32_t session_id) Starts new secure transport session with specified ID esp_err_t (*close_transport_session)(protocomm_security_handle_t handle, uint32_t session_id) Closes a secure transport session with specified ID esp_err_t (*close_transport_session)(protocomm_security_handle_t handle, uint32_t session_id) Closes a secure transport session with specified ID esp_err_t (*security_req_handler)(protocomm_security_handle_t handle, const void *sec_params, uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen, void *priv_data) Handler function for authenticating connection request and establishing secure session esp_err_t (*security_req_handler)(protocomm_security_handle_t handle, const void *sec_params, uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen, void *priv_data) Handler function for authenticating connection request and establishing secure session esp_err_t (*encrypt)(protocomm_security_handle_t handle, uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen) Function which implements the encryption algorithm esp_err_t (*encrypt)(protocomm_security_handle_t handle, uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen) Function which implements the encryption algorithm esp_err_t (*decrypt)(protocomm_security_handle_t handle, uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen) Function which implements the decryption algorithm esp_err_t (*decrypt)(protocomm_security_handle_t handle, uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen) Function which implements the decryption algorithm int ver Type Definitions typedef struct protocomm_security1_params protocomm_security1_params_t Protocomm Security 1 parameters: Proof Of Possession. typedef protocomm_security1_params_t protocomm_security_pop_t typedef struct protocomm_security2_params protocomm_security2_params_t Protocomm Security 2 parameters: Salt and Verifier. typedef void *protocomm_security_handle_t typedef struct protocomm_security protocomm_security_t Protocomm security object structure. The member functions are used for implementing secure protocomm sessions. Note This structure should not have any dynamic members to allow re-entrancy Enumerations enum protocomm_security_session_event_t Events generated by the protocomm security layer. These events are generated while establishing secured session. Values: enumerator PROTOCOMM_SECURITY_SESSION_SETUP_OK Secured session established successfully enumerator PROTOCOMM_SECURITY_SESSION_SETUP_OK Secured session established successfully enumerator PROTOCOMM_SECURITY_SESSION_INVALID_SECURITY_PARAMS Received invalid (NULL) security parameters (username / client public-key) enumerator PROTOCOMM_SECURITY_SESSION_INVALID_SECURITY_PARAMS Received invalid (NULL) security parameters (username / client public-key) enumerator PROTOCOMM_SECURITY_SESSION_CREDENTIALS_MISMATCH Received incorrect credentials (username / PoP) enumerator PROTOCOMM_SECURITY_SESSION_CREDENTIALS_MISMATCH Received incorrect credentials (username / PoP) enumerator PROTOCOMM_SECURITY_SESSION_SETUP_OK Header File This header file can be included with: #include "protocomm_security0.h" This header file is a part of the API provided by the protocomm component. To declare that your component depends on protocomm , add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Header File This header file can be included with: #include "protocomm_security1.h" This header file is a part of the API provided by the protocomm component. To declare that your component depends on protocomm , add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Header File This header file can be included with: #include "protocomm_security2.h" This header file is a part of the API provided by the protocomm component. To declare that your component depends on protocomm , add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Header File This header file can be included with: #include "esp_srp.h" This header file is a part of the API provided by the protocomm component. To declare that your component depends on protocomm , add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Functions esp_srp_handle_t *esp_srp_init(esp_ng_type_t ng) Initialize srp context for given NG type. Note the handle gets freed with esp_srp_free Parameters ng -- NG type given by esp_ng_type_t Returns esp_srp_handle_t* srp handle Parameters ng -- NG type given by esp_ng_type_t Returns esp_srp_handle_t* srp handle void esp_srp_free(esp_srp_handle_t *hd) free esp_srp_context Parameters hd -- handle to be free Parameters hd -- handle to be free esp_err_t esp_srp_srv_pubkey(esp_srp_handle_t *hd, const char *username, int username_len, const char *pass, int pass_len, int salt_len, char **bytes_B, int *len_B, char **bytes_salt) Returns B (pub key) and salt. [Step2.b]. Note *bytes_B MUST NOT BE FREED BY THE CALLER Note *bytes_salt MUST NOT BE FREE BY THE CALLER Parameters hd -- esp_srp handle username -- Username not expected NULL terminated username_len -- Username length pass -- Password not expected to be NULL terminated pass_len -- Pasword length salt_len -- Salt length bytes_B -- Public Key returned len_B -- Length of the public key bytes_salt -- Salt bytes generated hd -- esp_srp handle username -- Username not expected NULL terminated username_len -- Username length pass -- Password not expected to be NULL terminated pass_len -- Pasword length salt_len -- Salt length bytes_B -- Public Key returned len_B -- Length of the public key bytes_salt -- Salt bytes generated hd -- esp_srp handle Returns esp_err_t ESP_OK on success, appropriate error otherwise Parameters hd -- esp_srp handle username -- Username not expected NULL terminated username_len -- Username length pass -- Password not expected to be NULL terminated pass_len -- Pasword length salt_len -- Salt length bytes_B -- Public Key returned len_B -- Length of the public key bytes_salt -- Salt bytes generated Returns esp_err_t ESP_OK on success, appropriate error otherwise esp_err_t esp_srp_gen_salt_verifier(const char *username, int username_len, const char *pass, int pass_len, char **bytes_salt, int salt_len, char **verifier, int *verifier_len) Generate salt-verifier pair, given username, password and salt length. Note if API has returned ESP_OK, salt and verifier generated need to be freed by caller Note Usually, username and password are not saved on the device. Rather salt and verifier are generated outside the device and are embedded. this covenience API can be used to generate salt and verifier on the fly for development use case. OR for devices which intentionally want to generate different password each time and can send it to the client securely. e.g., a device has a display and it shows the pin Parameters username -- [in] username username_len -- [in] length of the username pass -- [in] password pass_len -- [in] length of the password bytes_salt -- [out] generated salt on successful generation, or NULL salt_len -- [in] salt length verifier -- [out] generated verifier on successful generation, or NULL verifier_len -- [out] length of the generated verifier username -- [in] username username_len -- [in] length of the username pass -- [in] password pass_len -- [in] length of the password bytes_salt -- [out] generated salt on successful generation, or NULL salt_len -- [in] salt length verifier -- [out] generated verifier on successful generation, or NULL verifier_len -- [out] length of the generated verifier username -- [in] username Returns esp_err_t ESP_OK on success, appropriate error otherwise Parameters username -- [in] username username_len -- [in] length of the username pass -- [in] password pass_len -- [in] length of the password bytes_salt -- [out] generated salt on successful generation, or NULL salt_len -- [in] salt length verifier -- [out] generated verifier on successful generation, or NULL verifier_len -- [out] length of the generated verifier Returns esp_err_t ESP_OK on success, appropriate error otherwise esp_err_t esp_srp_set_salt_verifier(esp_srp_handle_t *hd, const char *salt, int salt_len, const char *verifier, int verifier_len) Set the Salt and Verifier pre-generated for a given password. This should be used only if the actual password is not available. The public key can then be generated using esp_srp_srv_pubkey_from_salt_verifier() and not esp_srp_srv_pubkey() Parameters hd -- esp_srp_handle salt -- pre-generated salt bytes salt_len -- length of the salt bytes verifier -- pre-generated verifier verifier_len -- length of the verifier bytes hd -- esp_srp_handle salt -- pre-generated salt bytes salt_len -- length of the salt bytes verifier -- pre-generated verifier verifier_len -- length of the verifier bytes hd -- esp_srp_handle Returns esp_err_t ESP_OK on success, appropriate error otherwise Parameters hd -- esp_srp_handle salt -- pre-generated salt bytes salt_len -- length of the salt bytes verifier -- pre-generated verifier verifier_len -- length of the verifier bytes Returns esp_err_t ESP_OK on success, appropriate error otherwise esp_err_t esp_srp_srv_pubkey_from_salt_verifier(esp_srp_handle_t *hd, char **bytes_B, int *len_B) Returns B (pub key)[Step2.b] when the salt and verifier are set using esp_srp_set_salt_verifier() Note *bytes_B MUST NOT BE FREED BY THE CALLER Parameters hd -- esp_srp handle bytes_B -- Key returned to the called len_B -- Length of the key returned hd -- esp_srp handle bytes_B -- Key returned to the called len_B -- Length of the key returned hd -- esp_srp handle Returns esp_err_t ESP_OK on success, appropriate error otherwise Parameters hd -- esp_srp handle bytes_B -- Key returned to the called len_B -- Length of the key returned Returns esp_err_t ESP_OK on success, appropriate error otherwise esp_err_t esp_srp_get_session_key(esp_srp_handle_t *hd, char *bytes_A, int len_A, char **bytes_key, uint16_t *len_key) Get session key in *bytes_key given by len in *len_key . [Step2.c]. This calculated session key is used for further communication given the proofs are exchanged/authenticated with esp_srp_exchange_proofs Note *bytes_key MUST NOT BE FREED BY THE CALLER Parameters hd -- esp_srp handle bytes_A -- Private Key len_A -- Private Key length bytes_key -- Key returned to the caller len_key -- length of the key in *bytes_key hd -- esp_srp handle bytes_A -- Private Key len_A -- Private Key length bytes_key -- Key returned to the caller len_key -- length of the key in *bytes_key hd -- esp_srp handle Returns esp_err_t ESP_OK on success, appropriate error otherwise Parameters hd -- esp_srp handle bytes_A -- Private Key len_A -- Private Key length bytes_key -- Key returned to the caller len_key -- length of the key in *bytes_key Returns esp_err_t ESP_OK on success, appropriate error otherwise esp_err_t esp_srp_exchange_proofs(esp_srp_handle_t *hd, char *username, uint16_t username_len, char *bytes_user_proof, char *bytes_host_proof) Complete the authentication. If this step fails, the session_key exchanged should not be used. This is the final authentication step in SRP algorithm [Step4.1, Step4.b, Step4.c] Parameters hd -- esp_srp handle username -- Username not expected NULL terminated username_len -- Username length bytes_user_proof -- param in bytes_host_proof -- parameter out (should be SHA512_DIGEST_LENGTH) bytes in size hd -- esp_srp handle username -- Username not expected NULL terminated username_len -- Username length bytes_user_proof -- param in bytes_host_proof -- parameter out (should be SHA512_DIGEST_LENGTH) bytes in size hd -- esp_srp handle Returns esp_err_t ESP_OK if user's proof is ok and subsequently bytes_host_proof is populated with our own proof. Parameters hd -- esp_srp handle username -- Username not expected NULL terminated username_len -- Username length bytes_user_proof -- param in bytes_host_proof -- parameter out (should be SHA512_DIGEST_LENGTH) bytes in size Returns esp_err_t ESP_OK if user's proof is ok and subsequently bytes_host_proof is populated with our own proof. Type Definitions typedef struct esp_srp_handle esp_srp_handle_t esp_srp handle as the result of esp_srp_init The handle is returned by esp_srp_init on successful init. It is then passed for subsequent API calls as an argument. esp_srp_free can be used to clean up the handle. After esp_srp_free the handle becomes invalid. Enumerations Header File This header file can be included with: #include "protocomm_httpd.h" This header file is a part of the API provided by the protocomm component. To declare that your component depends on protocomm , add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Functions esp_err_t protocomm_httpd_start(protocomm_t *pc, const protocomm_httpd_config_t *config) Start HTTPD protocomm transport. This API internally creates a framework to allow endpoint registration and security configuration for the protocomm. Note This is a singleton. ie. Protocomm can have multiple instances, but only one instance can be bound to an HTTP transport layer. Parameters pc -- [in] Protocomm instance pointer obtained from protocomm_new() config -- [in] Pointer to config structure for initializing HTTP server pc -- [in] Protocomm instance pointer obtained from protocomm_new() config -- [in] Pointer to config structure for initializing HTTP server pc -- [in] Protocomm instance pointer obtained from protocomm_new() Returns ESP_OK : Success ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_NOT_SUPPORTED : Transport layer bound to another protocomm instance ESP_ERR_INVALID_STATE : Transport layer already bound to this protocomm instance ESP_ERR_NO_MEM : Memory allocation for server resource failed ESP_ERR_HTTPD_* : HTTP server error on start ESP_OK : Success ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_NOT_SUPPORTED : Transport layer bound to another protocomm instance ESP_ERR_INVALID_STATE : Transport layer already bound to this protocomm instance ESP_ERR_NO_MEM : Memory allocation for server resource failed ESP_ERR_HTTPD_* : HTTP server error on start ESP_OK : Success Parameters pc -- [in] Protocomm instance pointer obtained from protocomm_new() config -- [in] Pointer to config structure for initializing HTTP server Returns ESP_OK : Success ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_NOT_SUPPORTED : Transport layer bound to another protocomm instance ESP_ERR_INVALID_STATE : Transport layer already bound to this protocomm instance ESP_ERR_NO_MEM : Memory allocation for server resource failed ESP_ERR_HTTPD_* : HTTP server error on start esp_err_t protocomm_httpd_stop(protocomm_t *pc) Stop HTTPD protocomm transport. This API cleans up the HTTPD transport protocomm and frees all the handlers registered with the protocomm. Parameters pc -- [in] Same protocomm instance that was passed to protocomm_httpd_start() Returns ESP_OK : Success ESP_ERR_INVALID_ARG : Null / incorrect protocomm instance pointer ESP_OK : Success ESP_ERR_INVALID_ARG : Null / incorrect protocomm instance pointer ESP_OK : Success Parameters pc -- [in] Same protocomm instance that was passed to protocomm_httpd_start() Returns ESP_OK : Success ESP_ERR_INVALID_ARG : Null / incorrect protocomm instance pointer Unions union protocomm_httpd_config_data_t #include <protocomm_httpd.h> Protocomm HTTPD Configuration Data Public Members void *handle HTTP Server Handle, if ext_handle_provided is set to true void *handle HTTP Server Handle, if ext_handle_provided is set to true protocomm_http_server_config_t config HTTP Server Configuration, if a server is not already active protocomm_http_server_config_t config HTTP Server Configuration, if a server is not already active void *handle Structures struct protocomm_http_server_config_t Config parameters for protocomm HTTP server. struct protocomm_httpd_config_t Config parameters for protocomm HTTP server. Public Members bool ext_handle_provided Flag to indicate of an external HTTP Server Handle has been provided. In such as case, protocomm will use the same HTTP Server and not start a new one internally. bool ext_handle_provided Flag to indicate of an external HTTP Server Handle has been provided. In such as case, protocomm will use the same HTTP Server and not start a new one internally. protocomm_httpd_config_data_t data Protocomm HTTPD Configuration Data protocomm_httpd_config_data_t data Protocomm HTTPD Configuration Data bool ext_handle_provided Macros PROTOCOMM_HTTPD_DEFAULT_CONFIG() Header File This header file can be included with: #include "protocomm_ble.h" This header file is a part of the API provided by the protocomm component. To declare that your component depends on protocomm , add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Functions esp_err_t protocomm_ble_start(protocomm_t *pc, const protocomm_ble_config_t *config) Start Bluetooth Low Energy based transport layer for provisioning. Initialize and start required BLE service for provisioning. This includes the initialization for characteristics/service for BLE. Parameters pc -- [in] Protocomm instance pointer obtained from protocomm_new() config -- [in] Pointer to config structure for initializing BLE pc -- [in] Protocomm instance pointer obtained from protocomm_new() config -- [in] Pointer to config structure for initializing BLE pc -- [in] Protocomm instance pointer obtained from protocomm_new() Returns ESP_OK : Success ESP_FAIL : Simple BLE start error ESP_ERR_NO_MEM : Error allocating memory for internal resources ESP_ERR_INVALID_STATE : Error in ble config ESP_ERR_INVALID_ARG : Null arguments ESP_OK : Success ESP_FAIL : Simple BLE start error ESP_ERR_NO_MEM : Error allocating memory for internal resources ESP_ERR_INVALID_STATE : Error in ble config ESP_ERR_INVALID_ARG : Null arguments ESP_OK : Success Parameters pc -- [in] Protocomm instance pointer obtained from protocomm_new() config -- [in] Pointer to config structure for initializing BLE Returns ESP_OK : Success ESP_FAIL : Simple BLE start error ESP_ERR_NO_MEM : Error allocating memory for internal resources ESP_ERR_INVALID_STATE : Error in ble config ESP_ERR_INVALID_ARG : Null arguments esp_err_t protocomm_ble_stop(protocomm_t *pc) Stop Bluetooth Low Energy based transport layer for provisioning. Stops service/task responsible for BLE based interactions for provisioning Note You might want to optionally reclaim memory from Bluetooth. Refer to the documentation of esp_bt_mem_release in that case. Parameters pc -- [in] Same protocomm instance that was passed to protocomm_ble_start() Returns ESP_OK : Success ESP_FAIL : Simple BLE stop error ESP_ERR_INVALID_ARG : Null / incorrect protocomm instance ESP_OK : Success ESP_FAIL : Simple BLE stop error ESP_ERR_INVALID_ARG : Null / incorrect protocomm instance ESP_OK : Success Parameters pc -- [in] Same protocomm instance that was passed to protocomm_ble_start() Returns ESP_OK : Success ESP_FAIL : Simple BLE stop error ESP_ERR_INVALID_ARG : Null / incorrect protocomm instance Structures struct name_uuid This structure maps handler required by protocomm layer to UUIDs which are used to uniquely identify BLE characteristics from a smartphone or a similar client device. struct protocomm_ble_event_t Structure for BLE events in Protocomm. Public Members uint16_t evt_type This field indicates the type of BLE event that occurred. uint16_t evt_type This field indicates the type of BLE event that occurred. uint16_t conn_handle The handle of the relevant connection. uint16_t conn_handle The handle of the relevant connection. uint16_t conn_status The status of the connection attempt; o 0: the connection was successfully established. o BLE host error code: the connection attempt failed for the specified reason. uint16_t conn_status The status of the connection attempt; o 0: the connection was successfully established. o BLE host error code: the connection attempt failed for the specified reason. uint16_t disconnect_reason Return code indicating the reason for the disconnect. uint16_t disconnect_reason Return code indicating the reason for the disconnect. uint16_t evt_type struct protocomm_ble_config Config parameters for protocomm BLE service. Public Members char device_name[MAX_BLE_DEVNAME_LEN + 1] BLE device name being broadcast at the time of provisioning char device_name[MAX_BLE_DEVNAME_LEN + 1] BLE device name being broadcast at the time of provisioning uint8_t service_uuid[BLE_UUID128_VAL_LENGTH] 128 bit UUID of the provisioning service uint8_t service_uuid[BLE_UUID128_VAL_LENGTH] 128 bit UUID of the provisioning service uint8_t *manufacturer_data BLE device manufacturer data pointer in advertisement uint8_t *manufacturer_data BLE device manufacturer data pointer in advertisement ssize_t manufacturer_data_len BLE device manufacturer data length in advertisement ssize_t manufacturer_data_len BLE device manufacturer data length in advertisement ssize_t nu_lookup_count Number of entries in the Name-UUID lookup table ssize_t nu_lookup_count Number of entries in the Name-UUID lookup table protocomm_ble_name_uuid_t *nu_lookup Pointer to the Name-UUID lookup table protocomm_ble_name_uuid_t *nu_lookup Pointer to the Name-UUID lookup table unsigned ble_bonding BLE bonding unsigned ble_bonding BLE bonding unsigned ble_sm_sc BLE security flag unsigned ble_sm_sc BLE security flag unsigned ble_link_encryption BLE security flag unsigned ble_link_encryption BLE security flag char device_name[MAX_BLE_DEVNAME_LEN + 1] Macros MAX_BLE_DEVNAME_LEN BLE device name cannot be larger than this value 31 bytes (max scan response size) - 1 byte (length) - 1 byte (type) = 29 bytes BLE_UUID128_VAL_LENGTH MAX_BLE_MANUFACTURER_DATA_LEN Theoretically, the limit for max manufacturer length remains same as BLE device name i.e. 31 bytes (max scan response size) - 1 byte (length) - 1 byte (type) = 29 bytes However, manufacturer data goes along with BLE device name in scan response. So, it is important to understand the actual length should be smaller than (29 - (BLE device name length) - 2). Type Definitions typedef struct name_uuid protocomm_ble_name_uuid_t This structure maps handler required by protocomm layer to UUIDs which are used to uniquely identify BLE characteristics from a smartphone or a similar client device. typedef struct protocomm_ble_config protocomm_ble_config_t Config parameters for protocomm BLE service.
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: - Communication security at the application level - protocomm_security0(no security) - protocomm_security1(Curve25519 key exchange + AES-CTR encryption/decryption) - protocomm_security2(SRP6a-based key exchange + AES-GCM encryption/decryption) - Proof-of-possession (support with protocomm_security1 only) - Salt and Verifier (support with protocomm_security2 only) 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: Bluetooth LE 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. See Unified Provisioning for more details about the secure handshake logic. 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: - Support protocomm_security0, with no security: CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0, this option is enabled by default. - Support protocomm_security1with Curve25519 key exchange + AES-CTR encryption/decryption: CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1, this option is enabled by default. - Support protocomm_security2with SRP6a-based key exchange + AES-GCM encryption/decryption: CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2. Note Enabling multiple security versions at once offers the ability to control them dynamically but also increases the firmware size. SoftAP + HTTP Transport Example with Security 2 For sample usage, see wifi_provisioning/src/scheme_softap.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. */ 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. */ 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. 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. */ 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 wifi_provisioning/src/scheme_softap.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. */ 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. */ 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. 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. */ protocomm_httpd_stop(pc); /* Delete, namely deallocate the protocomm instance. */ protocomm_delete(pc); } Bluetooth LE Transport Example with Security 0 For sample usage, see wifi_provisioning/src/scheme_ble.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, }, .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 Header File This header file can be included with: #include "protocomm.h" This header file is a part of the API provided by the protocommcomponent. To declare that your component depends on protocomm, add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Functions - protocomm_t *protocomm_new(void) Create a new protocomm instance. This API will return a new dynamically allocated protocomm instance with all elements of the protocomm_t structure initialized to NULL. - Returns protocomm_t* : On success NULL : No memory for allocating new instance - - void protocomm_delete(protocomm_t *pc) Delete a protocomm instance. This API will deallocate a protocomm instance that was created using protocomm_new(). - Parameters pc -- [in] Pointer to the protocomm instance to be deleted - esp_err_t protocomm_add_endpoint(protocomm_t *pc, const char *ep_name, protocomm_req_handler_t h, void *priv_data) Add endpoint request handler for a protocomm instance. This API will bind an endpoint handler function to the specified endpoint name, along with any private data that needs to be pass to the handler at the time of call. Note An endpoint must be bound to a valid protocomm instance, created using protocomm_new(). This function internally calls the registered add_endpoint()function of the selected transport which is a member of the protocomm_t instance structure. - Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string h -- [in] Endpoint handler function priv_data -- [in] Pointer to private data to be passed as a parameter to the handler function on call. Pass NULL if not needed. - - Returns ESP_OK : Success ESP_FAIL : Error adding endpoint / Endpoint with this name already exists ESP_ERR_NO_MEM : Error allocating endpoint resource ESP_ERR_INVALID_ARG : Null instance/name/handler arguments - - - esp_err_t protocomm_remove_endpoint(protocomm_t *pc, const char *ep_name) Remove endpoint request handler for a protocomm instance. This API will remove a registered endpoint handler identified by an endpoint name. Note This function internally calls the registered remove_endpoint()function which is a member of the protocomm_t instance structure. - Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string - - Returns ESP_OK : Success ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments - - - esp_err_t protocomm_open_session(protocomm_t *pc, uint32_t session_id) Allocates internal resources for new transport session. Note An endpoint must be bound to a valid protocomm instance, created using protocomm_new(). - Parameters pc -- [in] Pointer to the protocomm instance session_id -- [in] Unique ID for a communication session - - Returns ESP_OK : Request handled successfully ESP_ERR_NO_MEM : Error allocating internal resource ESP_ERR_INVALID_ARG : Null instance/name arguments - - - esp_err_t protocomm_close_session(protocomm_t *pc, uint32_t session_id) Frees internal resources used by a transport session. Note An endpoint must be bound to a valid protocomm instance, created using protocomm_new(). - Parameters pc -- [in] Pointer to the protocomm instance session_id -- [in] Unique ID for a communication session - - Returns ESP_OK : Request handled successfully ESP_ERR_INVALID_ARG : Null instance/name arguments - - - esp_err_t protocomm_req_handle(protocomm_t *pc, const char *ep_name, uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen) Calls the registered handler of an endpoint session for processing incoming data and generating the response. Note An endpoint must be bound to a valid protocomm instance, created using protocomm_new(). Resulting output buffer must be deallocated by the caller. - Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string session_id -- [in] Unique ID for a communication session inbuf -- [in] Input buffer contains input request data which is to be processed by the registered handler inlen -- [in] Length of the input buffer outbuf -- [out] Pointer to internally allocated output buffer, where the resulting response data output from the registered handler is to be stored outlen -- [out] Buffer length of the allocated output buffer - - Returns ESP_OK : Request handled successfully ESP_FAIL : Internal error in execution of registered handler ESP_ERR_NO_MEM : Error allocating internal resource ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments - - - esp_err_t protocomm_set_security(protocomm_t *pc, const char *ep_name, const protocomm_security_t *sec, const void *sec_params) Add endpoint security for a protocomm instance. This API will bind a security session establisher to the specified endpoint name, along with any proof of possession that may be required for authenticating a session client. Note An endpoint must be bound to a valid protocomm instance, created using protocomm_new(). The choice of security can be any protocomm_security_tinstance. Choices protocomm_security0and protocomm_security1and protocomm_security2are readily available. - Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string sec -- [in] Pointer to endpoint security instance sec_params -- [in] Pointer to security params (NULL if not needed) The pointer should contain the security params struct of appropriate security version. For protocomm security version 1 and 2 sec_params should contain pointer to struct of type protocomm_security1_params_t and protocmm_security2_params_t respectively. The contents of this pointer must be valid till the security session has been running and is not closed. - - Returns ESP_OK : Success ESP_FAIL : Error adding endpoint / Endpoint with this name already exists ESP_ERR_INVALID_STATE : Security endpoint already set ESP_ERR_NO_MEM : Error allocating endpoint resource ESP_ERR_INVALID_ARG : Null instance/name/handler arguments - - - esp_err_t protocomm_unset_security(protocomm_t *pc, const char *ep_name) Remove endpoint security for a protocomm instance. This API will remove a registered security endpoint identified by an endpoint name. - Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string - - Returns ESP_OK : Success ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments - - esp_err_t protocomm_set_version(protocomm_t *pc, const char *ep_name, const char *version) Set endpoint for version verification. This API can be used for setting an application specific protocol version which can be verified by clients through the endpoint. Note An endpoint must be bound to a valid protocomm instance, created using protocomm_new(). - Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string version -- [in] Version identifier(name) string - - Returns ESP_OK : Success ESP_FAIL : Error adding endpoint / Endpoint with this name already exists ESP_ERR_INVALID_STATE : Version endpoint already set ESP_ERR_NO_MEM : Error allocating endpoint resource ESP_ERR_INVALID_ARG : Null instance/name/handler arguments - - - esp_err_t protocomm_unset_version(protocomm_t *pc, const char *ep_name) Remove version verification endpoint from a protocomm instance. This API will remove a registered version endpoint identified by an endpoint name. - Parameters pc -- [in] Pointer to the protocomm instance ep_name -- [in] Endpoint identifier(name) string - - Returns ESP_OK : Success ESP_ERR_NOT_FOUND : Endpoint with specified name doesn't exist ESP_ERR_INVALID_ARG : Null instance/name arguments - Type Definitions - typedef esp_err_t (*protocomm_req_handler_t)(uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen, void *priv_data) Function prototype for protocomm endpoint handler. - typedef struct protocomm protocomm_t This structure corresponds to a unique instance of protocomm returned when the API protocomm_new()is called. The remaining Protocomm APIs require this object as the first parameter. Note Structure of the protocomm object is kept private Header File This header file can be included with: #include "protocomm_security.h" This header file is a part of the API provided by the protocommcomponent. To declare that your component depends on protocomm, add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Structures - struct protocomm_security1_params Protocomm Security 1 parameters: Proof Of Possession. - struct protocomm_security2_params Protocomm Security 2 parameters: Salt and Verifier. - struct protocomm_security Protocomm security object structure. The member functions are used for implementing secure protocomm sessions. Note This structure should not have any dynamic members to allow re-entrancy Public Members - int ver Unique version number of security implementation - esp_err_t (*init)(protocomm_security_handle_t *handle) Function for initializing/allocating security infrastructure - esp_err_t (*cleanup)(protocomm_security_handle_t handle) Function for deallocating security infrastructure - esp_err_t (*new_transport_session)(protocomm_security_handle_t handle, uint32_t session_id) Starts new secure transport session with specified ID - esp_err_t (*close_transport_session)(protocomm_security_handle_t handle, uint32_t session_id) Closes a secure transport session with specified ID - esp_err_t (*security_req_handler)(protocomm_security_handle_t handle, const void *sec_params, uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen, void *priv_data) Handler function for authenticating connection request and establishing secure session - esp_err_t (*encrypt)(protocomm_security_handle_t handle, uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen) Function which implements the encryption algorithm - esp_err_t (*decrypt)(protocomm_security_handle_t handle, uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen) Function which implements the decryption algorithm - int ver Type Definitions - typedef struct protocomm_security1_params protocomm_security1_params_t Protocomm Security 1 parameters: Proof Of Possession. - typedef protocomm_security1_params_t protocomm_security_pop_t - typedef struct protocomm_security2_params protocomm_security2_params_t Protocomm Security 2 parameters: Salt and Verifier. - typedef void *protocomm_security_handle_t - typedef struct protocomm_security protocomm_security_t Protocomm security object structure. The member functions are used for implementing secure protocomm sessions. Note This structure should not have any dynamic members to allow re-entrancy Enumerations - enum protocomm_security_session_event_t Events generated by the protocomm security layer. These events are generated while establishing secured session. Values: - enumerator PROTOCOMM_SECURITY_SESSION_SETUP_OK Secured session established successfully - enumerator PROTOCOMM_SECURITY_SESSION_INVALID_SECURITY_PARAMS Received invalid (NULL) security parameters (username / client public-key) - enumerator PROTOCOMM_SECURITY_SESSION_CREDENTIALS_MISMATCH Received incorrect credentials (username / PoP) - enumerator PROTOCOMM_SECURITY_SESSION_SETUP_OK Header File This header file can be included with: #include "protocomm_security0.h" This header file is a part of the API provided by the protocommcomponent. To declare that your component depends on protocomm, add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Header File This header file can be included with: #include "protocomm_security1.h" This header file is a part of the API provided by the protocommcomponent. To declare that your component depends on protocomm, add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Header File This header file can be included with: #include "protocomm_security2.h" This header file is a part of the API provided by the protocommcomponent. To declare that your component depends on protocomm, add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Header File This header file can be included with: #include "esp_srp.h" This header file is a part of the API provided by the protocommcomponent. To declare that your component depends on protocomm, add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Functions - esp_srp_handle_t *esp_srp_init(esp_ng_type_t ng) Initialize srp context for given NG type. Note the handle gets freed with esp_srp_free - Parameters ng -- NG type given by esp_ng_type_t - Returns esp_srp_handle_t* srp handle - void esp_srp_free(esp_srp_handle_t *hd) free esp_srp_context - Parameters hd -- handle to be free - esp_err_t esp_srp_srv_pubkey(esp_srp_handle_t *hd, const char *username, int username_len, const char *pass, int pass_len, int salt_len, char **bytes_B, int *len_B, char **bytes_salt) Returns B (pub key) and salt. [Step2.b]. Note *bytes_B MUST NOT BE FREED BY THE CALLER Note *bytes_salt MUST NOT BE FREE BY THE CALLER - Parameters hd -- esp_srp handle username -- Username not expected NULL terminated username_len -- Username length pass -- Password not expected to be NULL terminated pass_len -- Pasword length salt_len -- Salt length bytes_B -- Public Key returned len_B -- Length of the public key bytes_salt -- Salt bytes generated - - Returns esp_err_t ESP_OK on success, appropriate error otherwise - esp_err_t esp_srp_gen_salt_verifier(const char *username, int username_len, const char *pass, int pass_len, char **bytes_salt, int salt_len, char **verifier, int *verifier_len) Generate salt-verifier pair, given username, password and salt length. Note if API has returned ESP_OK, salt and verifier generated need to be freed by caller Note Usually, username and password are not saved on the device. Rather salt and verifier are generated outside the device and are embedded. this covenience API can be used to generate salt and verifier on the fly for development use case. OR for devices which intentionally want to generate different password each time and can send it to the client securely. e.g., a device has a display and it shows the pin - Parameters username -- [in] username username_len -- [in] length of the username pass -- [in] password pass_len -- [in] length of the password bytes_salt -- [out] generated salt on successful generation, or NULL salt_len -- [in] salt length verifier -- [out] generated verifier on successful generation, or NULL verifier_len -- [out] length of the generated verifier - - Returns esp_err_t ESP_OK on success, appropriate error otherwise - esp_err_t esp_srp_set_salt_verifier(esp_srp_handle_t *hd, const char *salt, int salt_len, const char *verifier, int verifier_len) Set the Salt and Verifier pre-generated for a given password. This should be used only if the actual password is not available. The public key can then be generated using esp_srp_srv_pubkey_from_salt_verifier() and not esp_srp_srv_pubkey() - Parameters hd -- esp_srp_handle salt -- pre-generated salt bytes salt_len -- length of the salt bytes verifier -- pre-generated verifier verifier_len -- length of the verifier bytes - - Returns esp_err_t ESP_OK on success, appropriate error otherwise - esp_err_t esp_srp_srv_pubkey_from_salt_verifier(esp_srp_handle_t *hd, char **bytes_B, int *len_B) Returns B (pub key)[Step2.b] when the salt and verifier are set using esp_srp_set_salt_verifier() Note *bytes_B MUST NOT BE FREED BY THE CALLER - Parameters hd -- esp_srp handle bytes_B -- Key returned to the called len_B -- Length of the key returned - - Returns esp_err_t ESP_OK on success, appropriate error otherwise - esp_err_t esp_srp_get_session_key(esp_srp_handle_t *hd, char *bytes_A, int len_A, char **bytes_key, uint16_t *len_key) Get session key in *bytes_keygiven by len in *len_key. [Step2.c]. This calculated session key is used for further communication given the proofs are exchanged/authenticated with esp_srp_exchange_proofs Note *bytes_key MUST NOT BE FREED BY THE CALLER - Parameters hd -- esp_srp handle bytes_A -- Private Key len_A -- Private Key length bytes_key -- Key returned to the caller len_key -- length of the key in *bytes_key - - Returns esp_err_t ESP_OK on success, appropriate error otherwise - esp_err_t esp_srp_exchange_proofs(esp_srp_handle_t *hd, char *username, uint16_t username_len, char *bytes_user_proof, char *bytes_host_proof) Complete the authentication. If this step fails, the session_key exchanged should not be used. This is the final authentication step in SRP algorithm [Step4.1, Step4.b, Step4.c] - Parameters hd -- esp_srp handle username -- Username not expected NULL terminated username_len -- Username length bytes_user_proof -- param in bytes_host_proof -- parameter out (should be SHA512_DIGEST_LENGTH) bytes in size - - Returns esp_err_t ESP_OK if user's proof is ok and subsequently bytes_host_proof is populated with our own proof. Type Definitions - typedef struct esp_srp_handle esp_srp_handle_t esp_srp handle as the result of esp_srp_init The handle is returned by esp_srp_initon successful init. It is then passed for subsequent API calls as an argument. esp_srp_freecan be used to clean up the handle. After esp_srp_freethe handle becomes invalid. Enumerations Header File This header file can be included with: #include "protocomm_httpd.h" This header file is a part of the API provided by the protocommcomponent. To declare that your component depends on protocomm, add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Functions - esp_err_t protocomm_httpd_start(protocomm_t *pc, const protocomm_httpd_config_t *config) Start HTTPD protocomm transport. This API internally creates a framework to allow endpoint registration and security configuration for the protocomm. Note This is a singleton. ie. Protocomm can have multiple instances, but only one instance can be bound to an HTTP transport layer. - Parameters pc -- [in] Protocomm instance pointer obtained from protocomm_new() config -- [in] Pointer to config structure for initializing HTTP server - - Returns ESP_OK : Success ESP_ERR_INVALID_ARG : Null arguments ESP_ERR_NOT_SUPPORTED : Transport layer bound to another protocomm instance ESP_ERR_INVALID_STATE : Transport layer already bound to this protocomm instance ESP_ERR_NO_MEM : Memory allocation for server resource failed ESP_ERR_HTTPD_* : HTTP server error on start - - esp_err_t protocomm_httpd_stop(protocomm_t *pc) Stop HTTPD protocomm transport. This API cleans up the HTTPD transport protocomm and frees all the handlers registered with the protocomm. - Parameters pc -- [in] Same protocomm instance that was passed to protocomm_httpd_start() - Returns ESP_OK : Success ESP_ERR_INVALID_ARG : Null / incorrect protocomm instance pointer - Unions - union protocomm_httpd_config_data_t - #include <protocomm_httpd.h> Protocomm HTTPD Configuration Data Public Members - void *handle HTTP Server Handle, if ext_handle_provided is set to true - protocomm_http_server_config_t config HTTP Server Configuration, if a server is not already active - void *handle Structures - struct protocomm_http_server_config_t Config parameters for protocomm HTTP server. - struct protocomm_httpd_config_t Config parameters for protocomm HTTP server. Public Members - bool ext_handle_provided Flag to indicate of an external HTTP Server Handle has been provided. In such as case, protocomm will use the same HTTP Server and not start a new one internally. - protocomm_httpd_config_data_t data Protocomm HTTPD Configuration Data - bool ext_handle_provided Macros - PROTOCOMM_HTTPD_DEFAULT_CONFIG() Header File This header file can be included with: #include "protocomm_ble.h" This header file is a part of the API provided by the protocommcomponent. To declare that your component depends on protocomm, add the following to your CMakeLists.txt: REQUIRES protocomm or PRIV_REQUIRES protocomm Functions - esp_err_t protocomm_ble_start(protocomm_t *pc, const protocomm_ble_config_t *config) Start Bluetooth Low Energy based transport layer for provisioning. Initialize and start required BLE service for provisioning. This includes the initialization for characteristics/service for BLE. - Parameters pc -- [in] Protocomm instance pointer obtained from protocomm_new() config -- [in] Pointer to config structure for initializing BLE - - Returns ESP_OK : Success ESP_FAIL : Simple BLE start error ESP_ERR_NO_MEM : Error allocating memory for internal resources ESP_ERR_INVALID_STATE : Error in ble config ESP_ERR_INVALID_ARG : Null arguments - - esp_err_t protocomm_ble_stop(protocomm_t *pc) Stop Bluetooth Low Energy based transport layer for provisioning. Stops service/task responsible for BLE based interactions for provisioning Note You might want to optionally reclaim memory from Bluetooth. Refer to the documentation of esp_bt_mem_releasein that case. - Parameters pc -- [in] Same protocomm instance that was passed to protocomm_ble_start() - Returns ESP_OK : Success ESP_FAIL : Simple BLE stop error ESP_ERR_INVALID_ARG : Null / incorrect protocomm instance - Structures - struct name_uuid This structure maps handler required by protocomm layer to UUIDs which are used to uniquely identify BLE characteristics from a smartphone or a similar client device. - struct protocomm_ble_event_t Structure for BLE events in Protocomm. Public Members - uint16_t evt_type This field indicates the type of BLE event that occurred. - uint16_t conn_handle The handle of the relevant connection. - uint16_t conn_status The status of the connection attempt; o 0: the connection was successfully established. o BLE host error code: the connection attempt failed for the specified reason. - uint16_t disconnect_reason Return code indicating the reason for the disconnect. - uint16_t evt_type - struct protocomm_ble_config Config parameters for protocomm BLE service. Public Members - char device_name[MAX_BLE_DEVNAME_LEN + 1] BLE device name being broadcast at the time of provisioning - uint8_t service_uuid[BLE_UUID128_VAL_LENGTH] 128 bit UUID of the provisioning service - uint8_t *manufacturer_data BLE device manufacturer data pointer in advertisement - ssize_t manufacturer_data_len BLE device manufacturer data length in advertisement - ssize_t nu_lookup_count Number of entries in the Name-UUID lookup table - protocomm_ble_name_uuid_t *nu_lookup Pointer to the Name-UUID lookup table - unsigned ble_bonding BLE bonding - unsigned ble_sm_sc BLE security flag - unsigned ble_link_encryption BLE security flag - char device_name[MAX_BLE_DEVNAME_LEN + 1] Macros - MAX_BLE_DEVNAME_LEN BLE device name cannot be larger than this value 31 bytes (max scan response size) - 1 byte (length) - 1 byte (type) = 29 bytes - BLE_UUID128_VAL_LENGTH - MAX_BLE_MANUFACTURER_DATA_LEN Theoretically, the limit for max manufacturer length remains same as BLE device name i.e. 31 bytes (max scan response size) - 1 byte (length) - 1 byte (type) = 29 bytes However, manufacturer data goes along with BLE device name in scan response. So, it is important to understand the actual length should be smaller than (29 - (BLE device name length) - 2). Type Definitions - typedef struct name_uuid protocomm_ble_name_uuid_t This structure maps handler required by protocomm layer to UUIDs which are used to uniquely identify BLE characteristics from a smartphone or a similar client device. - typedef struct protocomm_ble_config protocomm_ble_config_t Config parameters for protocomm BLE service.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/provisioning/protocomm.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Unified Provisioning
null
espressif.com
2016-01-01
f730dc1f48a283cd
null
null
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: Extensible Protocol 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. Transport Flexibility 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. Security Scheme Flexibility 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. Compact Data Representation 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 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 Bluetooth LE-based transport has the advantage of maintaining an intact communication channel between the device and the client during the provisioning, which ensures reliable provisioning feedback. The Bluetooth LE-based provisioning implementation makes the user experience better from the phone apps as on Android and iOS both, the phone app can discover and connect to the device without requiring the user to go out of the phone app. However, the Bluetooth LE transport consumes about 110 KB memory at runtime. If the product does not use the Bluetooth LE or Bluetooth functionality after provisioning is done, almost all the memory can be reclaimed and added into the heap. The SoftAP-based transport is highly interoperable. However, there are a few considerations: 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. 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. 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 SoftAP transport does not require much additional memory for the Wi-Fi use cases. The SoftAP-based provisioning requires the phone-app user to go to System Settings to connect to the Wi-Fi network hosted by the device in the iOS system. The discovery (scanning) as well as connection APIs are not available for the iOS applications. 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: The configuration data sent from the client to the device and the response have to be secured. The client should authenticate the device that it is connected to. The device manufacturer may choose proof-of-possession (PoP), a unique per-device secret to be entered on the provisioning client as a security measure to make sure that only the user can provision the device in their possession. There are two levels of security schemes, of which the developer may select one or a combination, depending on requirements. Transport Security 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. Application 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. Architecture The below diagram shows the architecture of unified provisioning: It relies on the base layer called Protocol Communication (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. 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. Security Schemes At present, the unified provisioning supports the following security schemes: Security 0 No security (No encryption). Security 1 Curve25519-based key exchange, shared key derivation and AES256-CTR mode encryption of the data. It supports two modes : Authorized - Proof of Possession (PoP) string used to authorize session and derive shared key. No Auth (Null PoP) - Shared key derived through key exchange only. Security 2 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. Please refer to Enabling Protocomm Security Version for more details. Security 1 Scheme The Security 1 scheme details are shown in the below sequence diagram: 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 ESP32. 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: Sample Code Please refer to Protocol Communication and Wi-Fi Provisioning for API guides and code snippets on example usage. Application implementation can be found as an example under provisioning. Provisioning Tools Provisioning applications are available for various platforms, along with source code: Android: Source code on GitHub: esp-idf-provisioning-android. Source code on GitHub: esp-idf-provisioning-android. Android: Source code on GitHub: esp-idf-provisioning-android. iOS: Source code on GitHub: esp-idf-provisioning-ios. Source code on GitHub: esp-idf-provisioning-ios. iOS: Source code on GitHub: esp-idf-provisioning-ios. Linux/macOS/Windows: tools/esp_prov, a Python-based command line tool for provisioning. 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.
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: Extensible Protocol 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. Transport Flexibility 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. Security Scheme Flexibility 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. Compact Data Representation 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 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 Bluetooth LE-based transport has the advantage of maintaining an intact communication channel between the device and the client during the provisioning, which ensures reliable provisioning feedback. The Bluetooth LE-based provisioning implementation makes the user experience better from the phone apps as on Android and iOS both, the phone app can discover and connect to the device without requiring the user to go out of the phone app. However, the Bluetooth LE transport consumes about 110 KB memory at runtime. If the product does not use the Bluetooth LE or Bluetooth functionality after provisioning is done, almost all the memory can be reclaimed and added into the heap. The SoftAP-based transport is highly interoperable. However, there are a few considerations: 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. - The SoftAP transport does not require much additional memory for the Wi-Fi use cases. The SoftAP-based provisioning requires the phone-app user to go to System Settingsto connect to the Wi-Fi network hosted by the device in the iOS system. The discovery (scanning) as well as connection APIs are not available for the iOS applications. 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: The configuration data sent from the client to the device and the response have to be secured. The client should authenticate the device that it is connected to. The device manufacturer may choose proof-of-possession (PoP), a unique per-device secret to be entered on the provisioning client as a security measure to make sure that only the user can provision the device in their possession. There are two levels of security schemes, of which the developer may select one or a combination, depending on requirements. Transport Security 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. Application 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. Architecture The below diagram shows the architecture of unified provisioning: It relies on the base layer called Protocol Communication (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. 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. Security Schemes At present, the unified provisioning supports the following security schemes: Security 0 No security (No encryption). Security 1 Curve25519-based key exchange, shared key derivation and AES256-CTR mode encryption of the data. It supports two modes : - Authorized - Proof of Possession (PoP) string used to authorize session and derive shared key. - No Auth (Null PoP) - Shared key derived through key exchange only. Security 2 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. Please refer to Enabling Protocomm Security Version for more details. Security 1 Scheme The Security 1 scheme details are shown in the below sequence diagram: 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 ESP32. The password pand the username Iare 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: Sample Code Please refer to Protocol Communication and Wi-Fi Provisioning for API guides and code snippets on example usage. Application implementation can be found as an example under provisioning. Provisioning Tools Provisioning applications are available for various platforms, along with source code: - Android: Source code on GitHub: esp-idf-provisioning-android. - iOS: Source code on GitHub: esp-idf-provisioning-ios. Linux/macOS/Windows: tools/esp_prov, a Python-based command line tool for provisioning. 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.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/provisioning/provisioning.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Wi-Fi Provisioning
null
espressif.com
2016-01-01
365df5db0022e80c
null
null
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 Protocol Communication 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. Initialization 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 wifi_prov_mgr_deinit() . wifi_prov_mgr_config_t config = { .scheme = wifi_prov_scheme_ble, .scheme_event_handler = WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM }; ESP_ERROR_CHECK( wifi_prov_mgr_init(config) ); The configuration structure wifi_prov_mgr_config_t has a few fields to specify the desired behavior of the manager: wifi_prov_mgr_config_t::scheme - This is used to specify the provisioning scheme. Each scheme corresponds to one of the modes of transport supported by protocomm. Hence, support the following options: wifi_prov_scheme_ble - Bluetooth LE transport and GATT Server for handling the provisioning commands. wifi_prov_scheme_softap - Wi-Fi SoftAP transport and HTTP Server for handling the provisioning commands. wifi_prov_scheme_console - Serial transport and console for handling the provisioning commands. wifi_prov_mgr_config_t::scheme_event_handler : An event handler defined along with the scheme. Choosing the appropriate scheme-specific event handler allows the manager to take care of certain matters automatically. Presently, this option is not used for either the SoftAP or Console-based provisioning, but is very convenient for Bluetooth LE. To understand how, we must recall that Bluetooth requires a substantial amount of memory to function, and once the provisioning is finished, the main application may want to reclaim back this memory (or part of it) if it needs to use either Bluetooth LE or classic Bluetooth. Also, upon every future reboot of a provisioned device, this reclamation of memory needs to be performed again. To reduce this complication in using wifi_prov_scheme_ble , the scheme-specific handlers have been defined, and depending upon the chosen handler, the Bluetooth LE/classic Bluetooth/BTDM memory is freed automatically when the provisioning manager is de-initialized. The available options are: WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM - Free both classic Bluetooth and Bluetooth LE/BTDM memory. Used when the main application does not require Bluetooth at all. WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BLE - Free only Bluetooth LE memory. Used when main application requires classic Bluetooth. WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BT - Free only classic Bluetooth. Used when main application requires Bluetooth LE. In this case freeing happens right when the manager is initialized. WIFI_PROV_EVENT_HANDLER_NONE - Do not use any scheme specific handler. Used when the provisioning scheme is not Bluetooth LE, i.e., using SoftAP or Console, or when main application wants to handle the memory reclaiming on its own, or needs both Bluetooth LE and classic Bluetooth to function. wifi_prov_mgr_config_t::app_event_handler (Deprecated) - It is now recommended to catch WIFI_PROV_EVENT that is emitted to the default event loop handler. See definition of wifi_prov_cb_event_t for the list of events that are generated by the provisioning service. Here is an excerpt showing some of the provisioning events: 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!\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 wifi_prov_mgr_deinit() . Check the Provisioning State Whether the device is provisioned or not can be checked at runtime by calling wifi_prov_mgr_is_provisioned() . 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: The associated part of NVS partition has to be erased manually The main application must implement some logic to call esp_wifi_ APIs for erasing the credentials at runtime The main application must implement some logic to force start the provisioning irrespective of the provisioning state 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: A Wi-Fi SoftAP SSID and a passphrase, respectively, when the scheme is wifi_prov_scheme_softap . Bluetooth LE device name with the service key ignored when the scheme is wifi_prov_scheme_ble . Also, since internally the manager uses protocomm , we have the option of choosing one of the security features provided by it: Security 1 is secure communication which consists of a prior handshake involving X25519 key exchange along with authentication using a proof of possession pop , followed by AES-CTR for encryption or decryption of subsequent messages. Security 0 is simply plain text communication. In this case the pop is simply ignored. See Unified Provisioning for details about the security features. 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. Regardless of that, the provisioning service can be stopped at any moment by making a call to 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 Check the Provisioning 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. The simpler way is to use a blocking call to wifi_prov_mgr_wait() . // 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 wifi_prov_mgr_deinit() when event ID is WIFI_PROV_END : 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. 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 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. 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: Endpoint Name URI, i.e., SoftAP Description prov-session http://<mdns-hostname>.local/prov-session Security endpoint used for session establishment prov-scan the endpoint used for starting Wi-Fi scan and receiving scan results prov-ctrl the endpoint used for controlling Wi-Fi provisioning state prov-config http://<mdns-hostname>.local/prov-config the endpoint used for configuring Wi-Fi credentials on device proto-ver http://<mdns-hostname>.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. 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 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. See Unified Provisioning for more details about the secure handshake and encryption used. Applications must use the .proto files found under 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 wifi_provisioning/proto: get_status - For querying the Wi-Fi connection status. The device responds with a status which is one of connecting, connected or disconnected. If the status is disconnected, a disconnection reason is also to be included in the status response. set_config - For setting the Wi-Fi connection credentials. apply_config - For applying the credentials saved during set_config and starting the Wi-Fi station. 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 : scan_start - For starting Wi-Fi scan with various options: blocking (input) - If true, the command returns only when the scanning is finished. passive (input) - If true, the scan is started in passive mode, which may be slower, instead of active mode. group_channels (input) - This specifies whether to scan all channels in one go when zero, or perform scanning of channels in groups, with 120 ms delay between scanning of consecutive groups, and the value of this parameter sets the number of channels in each group. This is useful when transport mode is SoftAP, where scanning all channels in one go may not give the Wi-Fi driver enough time to send out beacons, and hence may cause disconnection with any connected stations. When scanning in groups, the manager waits for at least 120 ms after completing the scan on a group of channels, and thus allows the driver to send out the beacons. For example, given that the total number of Wi-Fi channels is 14, then setting group_channels to 3 creates 5 groups, with each group having 3 channels, except the last one which has 14 % 3 = 2 channels. So, when the scan is started, the first 3 channels will be scanned, followed by a 120 ms delay, and then the next 3 channels, and so on, until all the 14 channels have been scanned.One may need to adjust this parameter as having only a few channels in a group may increase the overall scan time, while having too many may again cause disconnection. Usually, a value of 4 should work for most cases. Note that for any other mode of transport, e.g., Bluetooth LE, this can be safely set to 0, and hence achieve the shortest overall scanning time. period_ms (input) - The scan parameter specifying how long to wait on each channel. scan_status - It gives the status of scanning process: scan_finished (output) - When the scan has finished, this returns true. result_count (output) - This gives the total number of results obtained till now. If the scan is yet happening, this number keeps on updating. scan_result - For fetching the scan results. This can be called even if the scan is still on going. start_index (input) - Where the index starts from to fetch the entries from the results list. count (input) - The number of entries to fetch from the starting index. entries (output) - The list of entries returned. Each entry consists of ssid , channel and rssi information. The client can also control the provisioning state of the device using wifi_ctrl endpoint. The wifi_ctrl endpoint supports the following protobuf commands: ctrl_reset - Resets internal state machine of the device and clears provisioned credentials only in case of provisioning failures. ctrl_reprov - Resets internal state machine of the device and clears provisioned credentials only in case the device is to be provisioned again for new credentials after a previous successful provisioning. 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 Protocol Communication 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. 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. One can also choose to call 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. If this default behavior is not desired, it can be disabled by calling wifi_prov_mgr_disable_auto_stop() . Now the provisioning service stops only after an explicit call to 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 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 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. Application Examples For complete example implementation see provisioning/wifi_prov_mgr. Provisioning Tools Provisioning applications are available for various platforms, along with source code: Android: Source code on GitHub: esp-idf-provisioning-android. Source code on GitHub: esp-idf-provisioning-android. Android: Source code on GitHub: esp-idf-provisioning-android. iOS: Source code on GitHub: esp-idf-provisioning-ios. Source code on GitHub: esp-idf-provisioning-ios. iOS: Source code on GitHub: esp-idf-provisioning-ios. Linux/MacOS/Windows: tools/esp_prov, a Python-based command-line tool for provisioning. 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 Header File components/wifi_provisioning/include/wifi_provisioning/manager.h This header file can be included with: #include "wifi_provisioning/manager.h" This header file is a part of the API provided by the wifi_provisioning component. To declare that your component depends on wifi_provisioning , add the following to your CMakeLists.txt: REQUIRES wifi_provisioning or PRIV_REQUIRES wifi_provisioning Functions esp_err_t wifi_prov_mgr_init(wifi_prov_mgr_config_t config) Initialize provisioning manager instance. Configures the manager and allocates internal resources Configuration specifies the provisioning scheme (transport) and event handlers Event WIFI_PROV_INIT is emitted right after initialization is complete Parameters config -- [in] Configuration structure Returns ESP_OK : Success ESP_FAIL : Fail ESP_OK : Success ESP_FAIL : Fail ESP_OK : Success Parameters config -- [in] Configuration structure Returns ESP_OK : Success ESP_FAIL : Fail void wifi_prov_mgr_deinit(void) Stop provisioning (if running) and release resource used by the manager. Event WIFI_PROV_DEINIT is emitted right after de-initialization is finished If provisioning service is still active when this API is called, it first stops the service, hence emitting WIFI_PROV_END, and then performs the de-initialization esp_err_t wifi_prov_mgr_is_provisioned(bool *provisioned) Checks if device is provisioned. This checks if Wi-Fi credentials are present on the NVS The Wi-Fi credentials are assumed to be kept in the same NVS namespace as used by esp_wifi component If one were to call esp_wifi_set_config() directly instead of going through the provisioning process, this function will still yield true (i.e. device will be found to be provisioned) Note Calling wifi_prov_mgr_start_provisioning() automatically resets the provision state, irrespective of what the state was prior to making the call. Parameters provisioned -- [out] True if provisioned, else false Returns ESP_OK : Retrieved provision state successfully ESP_FAIL : Wi-Fi not initialized ESP_ERR_INVALID_ARG : Null argument supplied ESP_OK : Retrieved provision state successfully ESP_FAIL : Wi-Fi not initialized ESP_ERR_INVALID_ARG : Null argument supplied ESP_OK : Retrieved provision state successfully Parameters provisioned -- [out] True if provisioned, else false Returns ESP_OK : Retrieved provision state successfully ESP_FAIL : Wi-Fi not initialized ESP_ERR_INVALID_ARG : Null argument supplied esp_err_t wifi_prov_mgr_start_provisioning(wifi_prov_security_t security, const void *wifi_prov_sec_params, const char *service_name, const char *service_key) Start provisioning service. This starts the provisioning service according to the scheme configured at the time of initialization. For scheme : wifi_prov_scheme_ble : This starts protocomm_ble, which internally initializes BLE transport and starts GATT server for handling provisioning requests wifi_prov_scheme_softap : This activates SoftAP mode of Wi-Fi and starts protocomm_httpd, which internally starts an HTTP server for handling provisioning requests (If mDNS is active it also starts advertising service with type _esp_wifi_prov._tcp) wifi_prov_scheme_ble : This starts protocomm_ble, which internally initializes BLE transport and starts GATT server for handling provisioning requests wifi_prov_scheme_softap : This activates SoftAP mode of Wi-Fi and starts protocomm_httpd, which internally starts an HTTP server for handling provisioning requests (If mDNS is active it also starts advertising service with type _esp_wifi_prov._tcp) Event WIFI_PROV_START is emitted right after provisioning starts without failure Note This API will start provisioning service even if device is found to be already provisioned, i.e. wifi_prov_mgr_is_provisioned() yields true Parameters security -- [in] Specify which protocomm security scheme to use : WIFI_PROV_SECURITY_0 : For no security WIFI_PROV_SECURITY_1 : x25519 secure handshake for session establishment followed by AES-CTR encryption of provisioning messages WIFI_PROV_SECURITY_2: SRP6a based authentication and key exchange followed by AES-GCM encryption/decryption of provisioning messages WIFI_PROV_SECURITY_0 : For no security WIFI_PROV_SECURITY_1 : x25519 secure handshake for session establishment followed by AES-CTR encryption of provisioning messages WIFI_PROV_SECURITY_2: SRP6a based authentication and key exchange followed by AES-GCM encryption/decryption of provisioning messages WIFI_PROV_SECURITY_0 : For no security wifi_prov_sec_params -- [in] Pointer to security params (NULL if not needed). This is not needed for protocomm security 0 This pointer should hold the struct of type wifi_prov_security1_params_t for protocomm security 1 and wifi_prov_security2_params_t for protocomm security 2 respectively. This pointer and its contents should be valid till the provisioning service is running and has not been stopped or de-inited. service_name -- [in] Unique name of the service. This translates to: Wi-Fi SSID when provisioning mode is softAP Device name when provisioning mode is BLE Wi-Fi SSID when provisioning mode is softAP Device name when provisioning mode is BLE Wi-Fi SSID when provisioning mode is softAP service_key -- [in] Key required by client to access the service (NULL if not needed). This translates to: Wi-Fi password when provisioning mode is softAP ignored when provisioning mode is BLE Wi-Fi password when provisioning mode is softAP ignored when provisioning mode is BLE Wi-Fi password when provisioning mode is softAP security -- [in] Specify which protocomm security scheme to use : WIFI_PROV_SECURITY_0 : For no security WIFI_PROV_SECURITY_1 : x25519 secure handshake for session establishment followed by AES-CTR encryption of provisioning messages WIFI_PROV_SECURITY_2: SRP6a based authentication and key exchange followed by AES-GCM encryption/decryption of provisioning messages wifi_prov_sec_params -- [in] Pointer to security params (NULL if not needed). This is not needed for protocomm security 0 This pointer should hold the struct of type wifi_prov_security1_params_t for protocomm security 1 and wifi_prov_security2_params_t for protocomm security 2 respectively. This pointer and its contents should be valid till the provisioning service is running and has not been stopped or de-inited. service_name -- [in] Unique name of the service. This translates to: Wi-Fi SSID when provisioning mode is softAP Device name when provisioning mode is BLE service_key -- [in] Key required by client to access the service (NULL if not needed). This translates to: Wi-Fi password when provisioning mode is softAP ignored when provisioning mode is BLE security -- [in] Specify which protocomm security scheme to use : WIFI_PROV_SECURITY_0 : For no security WIFI_PROV_SECURITY_1 : x25519 secure handshake for session establishment followed by AES-CTR encryption of provisioning messages WIFI_PROV_SECURITY_2: SRP6a based authentication and key exchange followed by AES-GCM encryption/decryption of provisioning messages Returns ESP_OK : Provisioning started successfully ESP_FAIL : Failed to start provisioning service ESP_ERR_INVALID_STATE : Provisioning manager not initialized or already started ESP_OK : Provisioning started successfully ESP_FAIL : Failed to start provisioning service ESP_ERR_INVALID_STATE : Provisioning manager not initialized or already started ESP_OK : Provisioning started successfully Parameters security -- [in] Specify which protocomm security scheme to use : WIFI_PROV_SECURITY_0 : For no security WIFI_PROV_SECURITY_1 : x25519 secure handshake for session establishment followed by AES-CTR encryption of provisioning messages WIFI_PROV_SECURITY_2: SRP6a based authentication and key exchange followed by AES-GCM encryption/decryption of provisioning messages wifi_prov_sec_params -- [in] Pointer to security params (NULL if not needed). This is not needed for protocomm security 0 This pointer should hold the struct of type wifi_prov_security1_params_t for protocomm security 1 and wifi_prov_security2_params_t for protocomm security 2 respectively. This pointer and its contents should be valid till the provisioning service is running and has not been stopped or de-inited. service_name -- [in] Unique name of the service. This translates to: Wi-Fi SSID when provisioning mode is softAP Device name when provisioning mode is BLE service_key -- [in] Key required by client to access the service (NULL if not needed). This translates to: Wi-Fi password when provisioning mode is softAP ignored when provisioning mode is BLE Returns ESP_OK : Provisioning started successfully ESP_FAIL : Failed to start provisioning service ESP_ERR_INVALID_STATE : Provisioning manager not initialized or already started wifi_prov_scheme_ble : This starts protocomm_ble, which internally initializes BLE transport and starts GATT server for handling provisioning requests void wifi_prov_mgr_stop_provisioning(void) Stop provisioning service. If provisioning service is active, this API will initiate a process to stop the service and return. Once the service actually stops, the event WIFI_PROV_END will be emitted. If wifi_prov_mgr_deinit() is called without calling this API first, it will automatically stop the provisioning service and emit the WIFI_PROV_END, followed by WIFI_PROV_DEINIT, before returning. This API will generally be used along with wifi_prov_mgr_disable_auto_stop() in the scenario when the main application has registered its own endpoints, and wishes that the provisioning service is stopped only when some protocomm command from the client side application is received. Calling this API inside an endpoint handler, with sufficient cleanup_delay, will allow the response / acknowledgment to be sent successfully before the underlying protocomm service is stopped. Cleaup_delay is set when calling wifi_prov_mgr_disable_auto_stop(). If not specified, it defaults to 1000ms. For straightforward cases, using this API is usually not necessary as provisioning is stopped automatically once WIFI_PROV_CRED_SUCCESS is emitted. Stopping is delayed (maximum 30 seconds) thus allowing the client side application to query for Wi-Fi state, i.e. after receiving the first query and sending Wi-Fi state connected response the service is stopped immediately. void wifi_prov_mgr_wait(void) Wait for provisioning service to finish. Calling this API will block until provisioning service is stopped i.e. till event WIFI_PROV_END is emitted. This will not block if provisioning is not started or not initialized. esp_err_t wifi_prov_mgr_disable_auto_stop(uint32_t cleanup_delay) Disable auto stopping of provisioning service upon completion. By default, once provisioning is complete, the provisioning service is automatically stopped, and all endpoints (along with those registered by main application) are deactivated. This API is useful in the case when main application wishes to close provisioning service only after it receives some protocomm command from the client side app. For example, after connecting to Wi-Fi, the device may want to connect to the cloud, and only once that is successfully, the device is said to be fully configured. But, then it is upto the main application to explicitly call wifi_prov_mgr_stop_provisioning() later when the device is fully configured and the provisioning service is no longer required. Note This must be called before executing wifi_prov_mgr_start_provisioning() Parameters cleanup_delay -- [in] Sets the delay after which the actual cleanup of transport related resources is done after a call to wifi_prov_mgr_stop_provisioning() returns. Minimum allowed value is 100ms. If not specified, this will default to 1000ms. Returns ESP_OK : Success ESP_ERR_INVALID_STATE : Manager not initialized or provisioning service already started ESP_OK : Success ESP_ERR_INVALID_STATE : Manager not initialized or provisioning service already started ESP_OK : Success Parameters cleanup_delay -- [in] Sets the delay after which the actual cleanup of transport related resources is done after a call to wifi_prov_mgr_stop_provisioning() returns. Minimum allowed value is 100ms. If not specified, this will default to 1000ms. Returns ESP_OK : Success ESP_ERR_INVALID_STATE : Manager not initialized or provisioning service already started esp_err_t wifi_prov_mgr_set_app_info(const char *label, const char *version, const char **capabilities, size_t total_capabilities) Set application version and capabilities in the JSON data returned by proto-ver endpoint. This function can be called multiple times, to specify information about the various application specific services running on the device, identified by unique labels. The provisioning service itself registers an entry in the JSON data, by the label "prov", containing only provisioning service version and capabilities. Application services should use a label other than "prov" so as not to overwrite this. Note This must be called before executing wifi_prov_mgr_start_provisioning() Parameters label -- [in] String indicating the application name. version -- [in] String indicating the application version. There is no constraint on format. capabilities -- [in] Array of strings with capabilities. These could be used by the client side app to know the application registered endpoint capabilities total_capabilities -- [in] Size of capabilities array label -- [in] String indicating the application name. version -- [in] String indicating the application version. There is no constraint on format. capabilities -- [in] Array of strings with capabilities. These could be used by the client side app to know the application registered endpoint capabilities total_capabilities -- [in] Size of capabilities array label -- [in] String indicating the application name. Returns ESP_OK : Success ESP_ERR_INVALID_STATE : Manager not initialized or provisioning service already started ESP_ERR_NO_MEM : Failed to allocate memory for version string ESP_ERR_INVALID_ARG : Null argument ESP_OK : Success ESP_ERR_INVALID_STATE : Manager not initialized or provisioning service already started ESP_ERR_NO_MEM : Failed to allocate memory for version string ESP_ERR_INVALID_ARG : Null argument ESP_OK : Success Parameters label -- [in] String indicating the application name. version -- [in] String indicating the application version. There is no constraint on format. capabilities -- [in] Array of strings with capabilities. These could be used by the client side app to know the application registered endpoint capabilities total_capabilities -- [in] Size of capabilities array Returns ESP_OK : Success ESP_ERR_INVALID_STATE : Manager not initialized or provisioning service already started ESP_ERR_NO_MEM : Failed to allocate memory for version string ESP_ERR_INVALID_ARG : Null argument esp_err_t wifi_prov_mgr_endpoint_create(const char *ep_name) Create an additional endpoint and allocate internal resources for it. This API is to be called by the application if it wants to create an additional endpoint. All additional endpoints will be assigned UUIDs starting from 0xFF54 and so on in the order of execution. protocomm handler for the created endpoint is to be registered later using wifi_prov_mgr_endpoint_register() after provisioning has started. Note This API can only be called BEFORE provisioning is started Note Additional endpoints can be used for configuring client provided parameters other than Wi-Fi credentials, that are necessary for the main application and hence must be set prior to starting the application Note After session establishment, the additional endpoints must be targeted first by the client side application before sending Wi-Fi configuration, because once Wi-Fi configuration finishes the provisioning service is stopped and hence all endpoints are unregistered Parameters ep_name -- [in] unique name of the endpoint Returns ESP_OK : Success ESP_FAIL : Failure ESP_OK : Success ESP_FAIL : Failure ESP_OK : Success Parameters ep_name -- [in] unique name of the endpoint Returns ESP_OK : Success ESP_FAIL : Failure esp_err_t wifi_prov_mgr_endpoint_register(const char *ep_name, protocomm_req_handler_t handler, void *user_ctx) Register a handler for the previously created endpoint. This API can be called by the application to register a protocomm handler to any endpoint that was created using wifi_prov_mgr_endpoint_create(). Note This API can only be called AFTER provisioning has started Note Additional endpoints can be used for configuring client provided parameters other than Wi-Fi credentials, that are necessary for the main application and hence must be set prior to starting the application Note After session establishment, the additional endpoints must be targeted first by the client side application before sending Wi-Fi configuration, because once Wi-Fi configuration finishes the provisioning service is stopped and hence all endpoints are unregistered Parameters ep_name -- [in] Name of the endpoint handler -- [in] Endpoint handler function user_ctx -- [in] User data ep_name -- [in] Name of the endpoint handler -- [in] Endpoint handler function user_ctx -- [in] User data ep_name -- [in] Name of the endpoint Returns ESP_OK : Success ESP_FAIL : Failure ESP_OK : Success ESP_FAIL : Failure ESP_OK : Success Parameters ep_name -- [in] Name of the endpoint handler -- [in] Endpoint handler function user_ctx -- [in] User data Returns ESP_OK : Success ESP_FAIL : Failure void wifi_prov_mgr_endpoint_unregister(const char *ep_name) Unregister the handler for an endpoint. This API can be called if the application wants to selectively unregister the handler of an endpoint while the provisioning is still in progress. All the endpoint handlers are unregistered automatically when the provisioning stops. Parameters ep_name -- [in] Name of the endpoint Parameters ep_name -- [in] Name of the endpoint esp_err_t wifi_prov_mgr_get_wifi_state(wifi_prov_sta_state_t *state) Get state of Wi-Fi Station during provisioning. Parameters state -- [out] Pointer to wifi_prov_sta_state_t variable to be filled Returns ESP_OK : Successfully retrieved Wi-Fi state ESP_FAIL : Provisioning app not running ESP_OK : Successfully retrieved Wi-Fi state ESP_FAIL : Provisioning app not running ESP_OK : Successfully retrieved Wi-Fi state Parameters state -- [out] Pointer to wifi_prov_sta_state_t variable to be filled Returns ESP_OK : Successfully retrieved Wi-Fi state ESP_FAIL : Provisioning app not running esp_err_t wifi_prov_mgr_get_wifi_disconnect_reason(wifi_prov_sta_fail_reason_t *reason) Get reason code in case of Wi-Fi station disconnection during provisioning. Parameters reason -- [out] Pointer to wifi_prov_sta_fail_reason_t variable to be filled Returns ESP_OK : Successfully retrieved Wi-Fi disconnect reason ESP_FAIL : Provisioning app not running ESP_OK : Successfully retrieved Wi-Fi disconnect reason ESP_FAIL : Provisioning app not running ESP_OK : Successfully retrieved Wi-Fi disconnect reason Parameters reason -- [out] Pointer to wifi_prov_sta_fail_reason_t variable to be filled Returns ESP_OK : Successfully retrieved Wi-Fi disconnect reason ESP_FAIL : Provisioning app not running esp_err_t wifi_prov_mgr_configure_sta(wifi_config_t *wifi_cfg) Runs Wi-Fi as Station with the supplied configuration. Configures the Wi-Fi station mode to connect to the AP with SSID and password specified in config structure and sets Wi-Fi to run as station. This is automatically called by provisioning service upon receiving new credentials. If credentials are to be supplied to the manager via a different mode other than through protocomm, then this API needs to be called. Event WIFI_PROV_CRED_RECV is emitted after credentials have been applied and Wi-Fi station started Parameters wifi_cfg -- [in] Pointer to Wi-Fi configuration structure Returns ESP_OK : Wi-Fi configured and started successfully ESP_FAIL : Failed to set configuration ESP_OK : Wi-Fi configured and started successfully ESP_FAIL : Failed to set configuration ESP_OK : Wi-Fi configured and started successfully Parameters wifi_cfg -- [in] Pointer to Wi-Fi configuration structure Returns ESP_OK : Wi-Fi configured and started successfully ESP_FAIL : Failed to set configuration esp_err_t wifi_prov_mgr_reset_provisioning(void) Reset Wi-Fi provisioning config. Calling this API will restore WiFi stack persistent settings to default values. Returns ESP_OK : Reset provisioning config successfully ESP_FAIL : Failed to reset provisioning config ESP_OK : Reset provisioning config successfully ESP_FAIL : Failed to reset provisioning config ESP_OK : Reset provisioning config successfully Returns ESP_OK : Reset provisioning config successfully ESP_FAIL : Failed to reset provisioning config esp_err_t wifi_prov_mgr_reset_sm_state_on_failure(void) Reset internal state machine and clear provisioned credentials. This API should be used to restart provisioning ONLY in the case of provisioning failures without rebooting the device. Returns ESP_OK : Reset provisioning state machine successfully ESP_FAIL : Failed to reset provisioning state machine ESP_ERR_INVALID_STATE : Manager not initialized ESP_OK : Reset provisioning state machine successfully ESP_FAIL : Failed to reset provisioning state machine ESP_ERR_INVALID_STATE : Manager not initialized ESP_OK : Reset provisioning state machine successfully Returns ESP_OK : Reset provisioning state machine successfully ESP_FAIL : Failed to reset provisioning state machine ESP_ERR_INVALID_STATE : Manager not initialized esp_err_t wifi_prov_mgr_reset_sm_state_for_reprovision(void) Reset internal state machine and clear provisioned credentials. This API can be used to restart provisioning ONLY in case the device is to be provisioned again for new credentials after a previous successful provisioning without rebooting the device. Note This API can be used only if provisioning auto-stop has been disabled using wifi_prov_mgr_disable_auto_stop() Returns ESP_OK : Reset provisioning state machine successfully ESP_FAIL : Failed to reset provisioning state machine ESP_ERR_INVALID_STATE : Manager not initialized ESP_OK : Reset provisioning state machine successfully ESP_FAIL : Failed to reset provisioning state machine ESP_ERR_INVALID_STATE : Manager not initialized ESP_OK : Reset provisioning state machine successfully Returns ESP_OK : Reset provisioning state machine successfully ESP_FAIL : Failed to reset provisioning state machine ESP_ERR_INVALID_STATE : Manager not initialized Structures struct wifi_prov_event_handler_t Event handler that is used by the manager while provisioning service is active. Public Members wifi_prov_cb_func_t event_cb Callback function to be executed on provisioning events wifi_prov_cb_func_t event_cb Callback function to be executed on provisioning events void *user_data User context data to pass as parameter to callback function void *user_data User context data to pass as parameter to callback function wifi_prov_cb_func_t event_cb struct wifi_prov_scheme Structure for specifying the provisioning scheme to be followed by the manager. Note Ready to use schemes are available: wifi_prov_scheme_ble : for provisioning over BLE transport + GATT server wifi_prov_scheme_softap : for provisioning over SoftAP transport + HTTP server wifi_prov_scheme_console : for provisioning over Serial UART transport + Console (for debugging) wifi_prov_scheme_ble : for provisioning over BLE transport + GATT server wifi_prov_scheme_softap : for provisioning over SoftAP transport + HTTP server wifi_prov_scheme_console : for provisioning over Serial UART transport + Console (for debugging) Public Members esp_err_t (*prov_start)(protocomm_t *pc, void *config) Function which is to be called by the manager when it is to start the provisioning service associated with a protocomm instance and a scheme specific configuration esp_err_t (*prov_start)(protocomm_t *pc, void *config) Function which is to be called by the manager when it is to start the provisioning service associated with a protocomm instance and a scheme specific configuration esp_err_t (*prov_stop)(protocomm_t *pc) Function which is to be called by the manager to stop the provisioning service previously associated with a protocomm instance esp_err_t (*prov_stop)(protocomm_t *pc) Function which is to be called by the manager to stop the provisioning service previously associated with a protocomm instance void *(*new_config)(void) Function which is to be called by the manager to generate a new configuration for the provisioning service, that is to be passed to prov_start() void *(*new_config)(void) Function which is to be called by the manager to generate a new configuration for the provisioning service, that is to be passed to prov_start() void (*delete_config)(void *config) Function which is to be called by the manager to delete a configuration generated using new_config() void (*delete_config)(void *config) Function which is to be called by the manager to delete a configuration generated using new_config() esp_err_t (*set_config_service)(void *config, const char *service_name, const char *service_key) Function which is to be called by the manager to set the service name and key values in the configuration structure esp_err_t (*set_config_service)(void *config, const char *service_name, const char *service_key) Function which is to be called by the manager to set the service name and key values in the configuration structure esp_err_t (*set_config_endpoint)(void *config, const char *endpoint_name, uint16_t uuid) Function which is to be called by the manager to set a protocomm endpoint with an identifying name and UUID in the configuration structure esp_err_t (*set_config_endpoint)(void *config, const char *endpoint_name, uint16_t uuid) Function which is to be called by the manager to set a protocomm endpoint with an identifying name and UUID in the configuration structure wifi_mode_t wifi_mode Sets mode of operation of Wi-Fi during provisioning This is set to : WIFI_MODE_APSTA for SoftAP transport WIFI_MODE_STA for BLE transport WIFI_MODE_APSTA for SoftAP transport WIFI_MODE_STA for BLE transport WIFI_MODE_APSTA for SoftAP transport wifi_mode_t wifi_mode Sets mode of operation of Wi-Fi during provisioning This is set to : WIFI_MODE_APSTA for SoftAP transport WIFI_MODE_STA for BLE transport wifi_prov_scheme_ble : for provisioning over BLE transport + GATT server struct wifi_prov_mgr_config_t Structure for specifying the manager configuration. Public Members wifi_prov_scheme_t scheme Provisioning scheme to use. Following schemes are already available: wifi_prov_scheme_ble : for provisioning over BLE transport + GATT server wifi_prov_scheme_softap : for provisioning over SoftAP transport + HTTP server + mDNS (optional) wifi_prov_scheme_console : for provisioning over Serial UART transport + Console (for debugging) wifi_prov_scheme_ble : for provisioning over BLE transport + GATT server wifi_prov_scheme_softap : for provisioning over SoftAP transport + HTTP server + mDNS (optional) wifi_prov_scheme_console : for provisioning over Serial UART transport + Console (for debugging) wifi_prov_scheme_ble : for provisioning over BLE transport + GATT server wifi_prov_scheme_t scheme Provisioning scheme to use. Following schemes are already available: wifi_prov_scheme_ble : for provisioning over BLE transport + GATT server wifi_prov_scheme_softap : for provisioning over SoftAP transport + HTTP server + mDNS (optional) wifi_prov_scheme_console : for provisioning over Serial UART transport + Console (for debugging) wifi_prov_event_handler_t scheme_event_handler Event handler required by the scheme for incorporating scheme specific behavior while provisioning manager is running. Various options may be provided by the scheme for setting this field. Use WIFI_PROV_EVENT_HANDLER_NONE when not used. When using scheme wifi_prov_scheme_ble, the following options are available: WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BLE WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BT WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BLE WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BT WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM wifi_prov_event_handler_t scheme_event_handler Event handler required by the scheme for incorporating scheme specific behavior while provisioning manager is running. Various options may be provided by the scheme for setting this field. Use WIFI_PROV_EVENT_HANDLER_NONE when not used. When using scheme wifi_prov_scheme_ble, the following options are available: WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BLE WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BT wifi_prov_event_handler_t app_event_handler Event handler that can be set for the purpose of incorporating application specific behavior. Use WIFI_PROV_EVENT_HANDLER_NONE when not used. wifi_prov_event_handler_t app_event_handler Event handler that can be set for the purpose of incorporating application specific behavior. Use WIFI_PROV_EVENT_HANDLER_NONE when not used. wifi_prov_scheme_t scheme Macros WIFI_PROV_EVENT_HANDLER_NONE Event handler can be set to none if not used. Type Definitions typedef void (*wifi_prov_cb_func_t)(void *user_data, wifi_prov_cb_event_t event, void *event_data) typedef struct wifi_prov_scheme wifi_prov_scheme_t Structure for specifying the provisioning scheme to be followed by the manager. Note Ready to use schemes are available: wifi_prov_scheme_ble : for provisioning over BLE transport + GATT server wifi_prov_scheme_softap : for provisioning over SoftAP transport + HTTP server wifi_prov_scheme_console : for provisioning over Serial UART transport + Console (for debugging) wifi_prov_scheme_ble : for provisioning over BLE transport + GATT server wifi_prov_scheme_softap : for provisioning over SoftAP transport + HTTP server wifi_prov_scheme_console : for provisioning over Serial UART transport + Console (for debugging) wifi_prov_scheme_ble : for provisioning over BLE transport + GATT server typedef enum wifi_prov_security wifi_prov_security_t Security modes supported by the Provisioning Manager. These are same as the security modes provided by protocomm typedef protocomm_security2_params_t wifi_prov_security2_params_t Security 2 params structure This needs to be passed when using WIFI_PROV_SECURITY_2. Enumerations enum wifi_prov_cb_event_t Events generated by manager. These events are generated in order of declaration and, for the stretch of time between initialization and de-initialization of the manager, each event is signaled only once Values: enumerator WIFI_PROV_INIT Emitted when the manager is initialized enumerator WIFI_PROV_INIT Emitted when the manager is initialized enumerator WIFI_PROV_START Indicates that provisioning has started enumerator WIFI_PROV_START Indicates that provisioning has started enumerator WIFI_PROV_CRED_RECV Emitted when Wi-Fi AP credentials are received via protocomm endpoint wifi_config . The event data in this case is a pointer to the corresponding wifi_sta_config_t structure enumerator WIFI_PROV_CRED_RECV Emitted when Wi-Fi AP credentials are received via protocomm endpoint wifi_config . The event data in this case is a pointer to the corresponding wifi_sta_config_t structure enumerator WIFI_PROV_CRED_FAIL Emitted when device fails to connect to the AP of which the credentials were received earlier on event WIFI_PROV_CRED_RECV . The event data in this case is a pointer to the disconnection reason code with type wifi_prov_sta_fail_reason_t enumerator WIFI_PROV_CRED_FAIL Emitted when device fails to connect to the AP of which the credentials were received earlier on event WIFI_PROV_CRED_RECV . The event data in this case is a pointer to the disconnection reason code with type wifi_prov_sta_fail_reason_t enumerator WIFI_PROV_CRED_SUCCESS Emitted when device successfully connects to the AP of which the credentials were received earlier on event WIFI_PROV_CRED_RECV enumerator WIFI_PROV_CRED_SUCCESS Emitted when device successfully connects to the AP of which the credentials were received earlier on event WIFI_PROV_CRED_RECV enumerator WIFI_PROV_END Signals that provisioning service has stopped enumerator WIFI_PROV_END Signals that provisioning service has stopped enumerator WIFI_PROV_DEINIT Signals that manager has been de-initialized enumerator WIFI_PROV_DEINIT Signals that manager has been de-initialized enumerator WIFI_PROV_INIT enum wifi_prov_security Security modes supported by the Provisioning Manager. These are same as the security modes provided by protocomm Values: enumerator WIFI_PROV_SECURITY_0 No security (plain-text communication) enumerator WIFI_PROV_SECURITY_0 No security (plain-text communication) enumerator WIFI_PROV_SECURITY_1 This secure communication mode consists of X25519 key exchange proof of possession (pop) based authentication AES-CTR encryption proof of possession (pop) based authentication AES-CTR encryption proof of possession (pop) based authentication enumerator WIFI_PROV_SECURITY_1 This secure communication mode consists of X25519 key exchange proof of possession (pop) based authentication AES-CTR encryption enumerator WIFI_PROV_SECURITY_2 This secure communication mode consists of SRP6a based authentication and key exchange AES-GCM encryption/decryption AES-GCM encryption/decryption AES-GCM encryption/decryption enumerator WIFI_PROV_SECURITY_2 This secure communication mode consists of SRP6a based authentication and key exchange AES-GCM encryption/decryption enumerator WIFI_PROV_SECURITY_0 Header File components/wifi_provisioning/include/wifi_provisioning/scheme_ble.h This header file can be included with: #include "wifi_provisioning/scheme_ble.h" This header file is a part of the API provided by the wifi_provisioning component. To declare that your component depends on wifi_provisioning , add the following to your CMakeLists.txt: REQUIRES wifi_provisioning or PRIV_REQUIRES wifi_provisioning Functions void wifi_prov_scheme_ble_event_cb_free_btdm(void *user_data, wifi_prov_cb_event_t event, void *event_data) void wifi_prov_scheme_ble_event_cb_free_ble(void *user_data, wifi_prov_cb_event_t event, void *event_data) void wifi_prov_scheme_ble_event_cb_free_bt(void *user_data, wifi_prov_cb_event_t event, void *event_data) esp_err_t wifi_prov_scheme_ble_set_service_uuid(uint8_t *uuid128) Set the 128 bit GATT service UUID used for provisioning. This API is used to override the default 128 bit provisioning service UUID, which is 0000ffff-0000-1000-8000-00805f9b34fb. This must be called before starting provisioning, i.e. before making a call to wifi_prov_mgr_start_provisioning(), otherwise the default UUID will be used. Note The data being pointed to by the argument must be valid atleast till provisioning is started. Upon start, the manager will store an internal copy of this UUID, and this data can be freed or invalidated afterwords. Parameters uuid128 -- [in] A custom 128 bit UUID Returns ESP_OK : Success ESP_ERR_INVALID_ARG : Null argument ESP_OK : Success ESP_ERR_INVALID_ARG : Null argument ESP_OK : Success Parameters uuid128 -- [in] A custom 128 bit UUID Returns ESP_OK : Success ESP_ERR_INVALID_ARG : Null argument esp_err_t wifi_prov_scheme_ble_set_mfg_data(uint8_t *mfg_data, ssize_t mfg_data_len) Set manufacturer specific data in scan response. This must be called before starting provisioning, i.e. before making a call to wifi_prov_mgr_start_provisioning(). Note It is important to understand that length of custom manufacturer data should be within limits. The manufacturer data goes into scan response along with BLE device name. By default, BLE device name length is of 11 Bytes, however it can vary as per application use case. So, one has to honour the scan response data size limits i.e. (mfg_data_len + 2) < 31 - (device_name_length + 2 ). If the mfg_data length exceeds this limit, the length will be truncated. Parameters mfg_data -- [in] Custom manufacturer data mfg_data_len -- [in] Manufacturer data length mfg_data -- [in] Custom manufacturer data mfg_data_len -- [in] Manufacturer data length mfg_data -- [in] Custom manufacturer data Returns ESP_OK : Success ESP_ERR_INVALID_ARG : Null argument ESP_OK : Success ESP_ERR_INVALID_ARG : Null argument ESP_OK : Success Parameters mfg_data -- [in] Custom manufacturer data mfg_data_len -- [in] Manufacturer data length Returns ESP_OK : Success ESP_ERR_INVALID_ARG : Null argument Macros WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BLE WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BT Header File components/wifi_provisioning/include/wifi_provisioning/scheme_softap.h This header file can be included with: #include "wifi_provisioning/scheme_softap.h" This header file is a part of the API provided by the wifi_provisioning component. To declare that your component depends on wifi_provisioning , add the following to your CMakeLists.txt: REQUIRES wifi_provisioning or PRIV_REQUIRES wifi_provisioning Functions void wifi_prov_scheme_softap_set_httpd_handle(void *handle) Provide HTTPD Server handle externally. Useful in cases wherein applications need the webserver for some different operations, and do not want the wifi provisioning component to start/stop a new instance. Note This API should be called before wifi_prov_mgr_start_provisioning() Parameters handle -- [in] Handle to HTTPD server instance Parameters handle -- [in] Handle to HTTPD server instance Header File components/wifi_provisioning/include/wifi_provisioning/scheme_console.h This header file can be included with: #include "wifi_provisioning/scheme_console.h" This header file is a part of the API provided by the wifi_provisioning component. To declare that your component depends on wifi_provisioning , add the following to your CMakeLists.txt: REQUIRES wifi_provisioning or PRIV_REQUIRES wifi_provisioning Header File components/wifi_provisioning/include/wifi_provisioning/wifi_config.h This header file can be included with: #include "wifi_provisioning/wifi_config.h" This header file is a part of the API provided by the wifi_provisioning component. To declare that your component depends on wifi_provisioning , add the following to your CMakeLists.txt: REQUIRES wifi_provisioning or PRIV_REQUIRES wifi_provisioning Functions esp_err_t wifi_prov_config_data_handler(uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen, void *priv_data) Handler for receiving and responding to requests from master. This is to be registered as the wifi_config endpoint handler (protocomm protocomm_req_handler_t ) using protocomm_add_endpoint() Structures struct wifi_prov_sta_conn_info_t WiFi STA connected status information. struct wifi_prov_config_get_data_t WiFi status data to be sent in response to get_status request from master. Public Members wifi_prov_sta_state_t wifi_state WiFi state of the station wifi_prov_sta_state_t wifi_state WiFi state of the station wifi_prov_sta_fail_reason_t fail_reason Reason for disconnection (valid only when wifi_state is WIFI_STATION_DISCONNECTED ) wifi_prov_sta_fail_reason_t fail_reason Reason for disconnection (valid only when wifi_state is WIFI_STATION_DISCONNECTED ) wifi_prov_sta_conn_info_t conn_info Connection information (valid only when wifi_state is WIFI_STATION_CONNECTED ) wifi_prov_sta_conn_info_t conn_info Connection information (valid only when wifi_state is WIFI_STATION_CONNECTED ) wifi_prov_sta_state_t wifi_state struct wifi_prov_config_set_data_t WiFi config data received by slave during set_config request from master. struct wifi_prov_config_handlers Internal handlers for receiving and responding to protocomm requests from master. This is to be passed as priv_data for protocomm request handler (refer to wifi_prov_config_data_handler() ) when calling protocomm_add_endpoint() . Public Members esp_err_t (*get_status_handler)(wifi_prov_config_get_data_t *resp_data, wifi_prov_ctx_t **ctx) Handler function called when connection status of the slave (in WiFi station mode) is requested esp_err_t (*get_status_handler)(wifi_prov_config_get_data_t *resp_data, wifi_prov_ctx_t **ctx) Handler function called when connection status of the slave (in WiFi station mode) is requested esp_err_t (*set_config_handler)(const wifi_prov_config_set_data_t *req_data, wifi_prov_ctx_t **ctx) Handler function called when WiFi connection configuration (eg. AP SSID, password, etc.) of the slave (in WiFi station mode) is to be set to user provided values esp_err_t (*set_config_handler)(const wifi_prov_config_set_data_t *req_data, wifi_prov_ctx_t **ctx) Handler function called when WiFi connection configuration (eg. AP SSID, password, etc.) of the slave (in WiFi station mode) is to be set to user provided values esp_err_t (*apply_config_handler)(wifi_prov_ctx_t **ctx) Handler function for applying the configuration that was set in set_config_handler . After applying the station may get connected to the AP or may fail to connect. The slave must be ready to convey the updated connection status information when get_status_handler is invoked again by the master. esp_err_t (*apply_config_handler)(wifi_prov_ctx_t **ctx) Handler function for applying the configuration that was set in set_config_handler . After applying the station may get connected to the AP or may fail to connect. The slave must be ready to convey the updated connection status information when get_status_handler is invoked again by the master. wifi_prov_ctx_t *ctx Context pointer to be passed to above handler functions upon invocation wifi_prov_ctx_t *ctx Context pointer to be passed to above handler functions upon invocation esp_err_t (*get_status_handler)(wifi_prov_config_get_data_t *resp_data, wifi_prov_ctx_t **ctx) Type Definitions typedef struct wifi_prov_ctx wifi_prov_ctx_t Type of context data passed to each get/set/apply handler function set in wifi_prov_config_handlers structure. This is passed as an opaque pointer, thereby allowing it be defined later in application code as per requirements. typedef struct wifi_prov_config_handlers wifi_prov_config_handlers_t Internal handlers for receiving and responding to protocomm requests from master. This is to be passed as priv_data for protocomm request handler (refer to wifi_prov_config_data_handler() ) when calling protocomm_add_endpoint() . Enumerations enum wifi_prov_sta_state_t WiFi STA status for conveying back to the provisioning master. Values: enumerator WIFI_PROV_STA_CONNECTING enumerator WIFI_PROV_STA_CONNECTING enumerator WIFI_PROV_STA_CONNECTED enumerator WIFI_PROV_STA_CONNECTED enumerator WIFI_PROV_STA_DISCONNECTED enumerator WIFI_PROV_STA_DISCONNECTED enumerator WIFI_PROV_STA_CONNECTING
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 Protocol Communication 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. Initialization 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 wifi_prov_mgr_deinit(). wifi_prov_mgr_config_t config = { .scheme = wifi_prov_scheme_ble, .scheme_event_handler = WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM }; ESP_ERROR_CHECK( wifi_prov_mgr_init(config) ); The configuration structure wifi_prov_mgr_config_t has a few fields to specify the desired behavior of the manager: - wifi_prov_mgr_config_t::scheme- This is used to specify the provisioning scheme. Each scheme corresponds to one of the modes of transport supported by protocomm. Hence, support the following options: - wifi_prov_scheme_ble- Bluetooth LE transport and GATT Server for handling the provisioning commands. - wifi_prov_scheme_softap- Wi-Fi SoftAP transport and HTTP Server for handling the provisioning commands. - wifi_prov_scheme_console- Serial transport and console for handling the provisioning commands. - wifi_prov_mgr_config_t::scheme_event_handler: An event handler defined along with the scheme. Choosing the appropriate scheme-specific event handler allows the manager to take care of certain matters automatically. Presently, this option is not used for either the SoftAP or Console-based provisioning, but is very convenient for Bluetooth LE. To understand how, we must recall that Bluetooth requires a substantial amount of memory to function, and once the provisioning is finished, the main application may want to reclaim back this memory (or part of it) if it needs to use either Bluetooth LE or classic Bluetooth. Also, upon every future reboot of a provisioned device, this reclamation of memory needs to be performed again. To reduce this complication in using wifi_prov_scheme_ble, the scheme-specific handlers have been defined, and depending upon the chosen handler, the Bluetooth LE/classic Bluetooth/BTDM memory is freed automatically when the provisioning manager is de-initialized. The available options are: - WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM- Free both classic Bluetooth and Bluetooth LE/BTDM memory. Used when the main application does not require Bluetooth at all. - WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BLE- Free only Bluetooth LE memory. Used when main application requires classic Bluetooth. - WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BT- Free only classic Bluetooth. Used when main application requires Bluetooth LE. In this case freeing happens right when the manager is initialized. - WIFI_PROV_EVENT_HANDLER_NONE- Do not use any scheme specific handler. Used when the provisioning scheme is not Bluetooth LE, i.e., using SoftAP or Console, or when main application wants to handle the memory reclaiming on its own, or needs both Bluetooth LE and classic Bluetooth to function. - wifi_prov_mgr_config_t::app_event_handler(Deprecated) - It is now recommended to catch WIFI_PROV_EVENTthat is emitted to the default event loop handler. See definition of wifi_prov_cb_event_tfor the list of events that are generated by the provisioning service. Here is an excerpt showing some of the provisioning events: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!\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 wifi_prov_mgr_deinit(). Check the Provisioning State Whether the device is provisioned or not can be checked at runtime by calling wifi_prov_mgr_is_provisioned(). 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: - The associated part of NVS partition has to be erased manually - The main application must implement some logic to call esp_wifi_APIs for erasing the credentials at runtime - The main application must implement some logic to force start the provisioning irrespective of the provisioning statebool 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: - A Wi-Fi SoftAP SSID and a passphrase, respectively, when the scheme is wifi_prov_scheme_softap. - Bluetooth LE device name with the service key ignored when the scheme is wifi_prov_scheme_ble. Also, since internally the manager uses protocomm, we have the option of choosing one of the security features provided by it: - Security 1 is secure communication which consists of a prior handshake involving X25519 key exchange along with authentication using a proof of possession pop, followed by AES-CTR for encryption or decryption of subsequent messages. - Security 0 is simply plain text communication. In this case the popis simply ignored. See Unified Provisioning for details about the security features. 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. Regardless of that, the provisioning service can be stopped at any moment by making a call to 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 Check the Provisioning 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. The simpler way is to use a blocking call to wifi_prov_mgr_wait(). // 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 wifi_prov_mgr_deinit() when event ID is WIFI_PROV_END: 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. 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 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. 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: | Endpoint Name | URI, i.e., SoftAP | Description | prov-session | http://<mdns-hostname>.local/prov-session | Security endpoint used for session establishment | prov-scan | the endpoint used for starting Wi-Fi scan and receiving scan results | prov-ctrl | the endpoint used for controlling Wi-Fi provisioning state | prov-config | http://<mdns-hostname>.local/prov-config | the endpoint used for configuring Wi-Fi credentials on device | proto-ver | http://<mdns-hostname>.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. 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 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. See Unified Provisioning for more details about the secure handshake and encryption used. Applications must use the .proto files found under 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 wifi_provisioning/proto: - get_status- For querying the Wi-Fi connection status. The device responds with a status which is one of connecting, connected or disconnected. If the status is disconnected, a disconnection reason is also to be included in the status response. - set_config- For setting the Wi-Fi connection credentials. - apply_config- For applying the credentials saved during set_configand starting the Wi-Fi station. 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 : - scan_start- For starting Wi-Fi scan with various options: - blocking(input) - If true, the command returns only when the scanning is finished. - passive(input) - If true, the scan is started in passive mode, which may be slower, instead of active mode. - group_channels(input) - This specifies whether to scan all channels in one go when zero, or perform scanning of channels in groups, with 120 ms delay between scanning of consecutive groups, and the value of this parameter sets the number of channels in each group. This is useful when transport mode is SoftAP, where scanning all channels in one go may not give the Wi-Fi driver enough time to send out beacons, and hence may cause disconnection with any connected stations. When scanning in groups, the manager waits for at least 120 ms after completing the scan on a group of channels, and thus allows the driver to send out the beacons. For example, given that the total number of Wi-Fi channels is 14, then setting group_channelsto 3 creates 5 groups, with each group having 3 channels, except the last one which has 14 % 3 = 2 channels. So, when the scan is started, the first 3 channels will be scanned, followed by a 120 ms delay, and then the next 3 channels, and so on, until all the 14 channels have been scanned.One may need to adjust this parameter as having only a few channels in a group may increase the overall scan time, while having too many may again cause disconnection. Usually, a value of 4 should work for most cases. Note that for any other mode of transport, e.g., Bluetooth LE, this can be safely set to 0, and hence achieve the shortest overall scanning time. - period_ms(input) - The scan parameter specifying how long to wait on each channel. - scan_status- It gives the status of scanning process: - scan_finished(output) - When the scan has finished, this returns true. - result_count(output) - This gives the total number of results obtained till now. If the scan is yet happening, this number keeps on updating. - scan_result- For fetching the scan results. This can be called even if the scan is still on going. - start_index(input) - Where the index starts from to fetch the entries from the results list. - count(input) - The number of entries to fetch from the starting index. - entries(output) - The list of entries returned. Each entry consists of ssid, channeland rssiinformation. The client can also control the provisioning state of the device using wifi_ctrl endpoint. The wifi_ctrl endpoint supports the following protobuf commands: - ctrl_reset- Resets internal state machine of the device and clears provisioned credentials only in case of provisioning failures. - ctrl_reprov- Resets internal state machine of the device and clears provisioned credentials only in case the device is to be provisioned again for new credentials after a previous successful provisioning. 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 Protocol Communication 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. 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. One can also choose to call 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. If this default behavior is not desired, it can be disabled by calling wifi_prov_mgr_disable_auto_stop(). Now the provisioning service stops only after an explicit call to 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 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 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. Application Examples For complete example implementation see provisioning/wifi_prov_mgr. Provisioning Tools Provisioning applications are available for various platforms, along with source code: - Android: Source code on GitHub: esp-idf-provisioning-android. - iOS: Source code on GitHub: esp-idf-provisioning-ios. Linux/MacOS/Windows: tools/esp_prov, a Python-based command-line tool for provisioning. 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 Header File components/wifi_provisioning/include/wifi_provisioning/manager.h This header file can be included with: #include "wifi_provisioning/manager.h" This header file is a part of the API provided by the wifi_provisioningcomponent. To declare that your component depends on wifi_provisioning, add the following to your CMakeLists.txt: REQUIRES wifi_provisioning or PRIV_REQUIRES wifi_provisioning Functions - esp_err_t wifi_prov_mgr_init(wifi_prov_mgr_config_t config) Initialize provisioning manager instance. Configures the manager and allocates internal resources Configuration specifies the provisioning scheme (transport) and event handlers Event WIFI_PROV_INIT is emitted right after initialization is complete - Parameters config -- [in] Configuration structure - Returns ESP_OK : Success ESP_FAIL : Fail - - void wifi_prov_mgr_deinit(void) Stop provisioning (if running) and release resource used by the manager. Event WIFI_PROV_DEINIT is emitted right after de-initialization is finished If provisioning service is still active when this API is called, it first stops the service, hence emitting WIFI_PROV_END, and then performs the de-initialization - esp_err_t wifi_prov_mgr_is_provisioned(bool *provisioned) Checks if device is provisioned. This checks if Wi-Fi credentials are present on the NVS The Wi-Fi credentials are assumed to be kept in the same NVS namespace as used by esp_wifi component If one were to call esp_wifi_set_config() directly instead of going through the provisioning process, this function will still yield true (i.e. device will be found to be provisioned) Note Calling wifi_prov_mgr_start_provisioning() automatically resets the provision state, irrespective of what the state was prior to making the call. - Parameters provisioned -- [out] True if provisioned, else false - Returns ESP_OK : Retrieved provision state successfully ESP_FAIL : Wi-Fi not initialized ESP_ERR_INVALID_ARG : Null argument supplied - - esp_err_t wifi_prov_mgr_start_provisioning(wifi_prov_security_t security, const void *wifi_prov_sec_params, const char *service_name, const char *service_key) Start provisioning service. This starts the provisioning service according to the scheme configured at the time of initialization. For scheme : wifi_prov_scheme_ble : This starts protocomm_ble, which internally initializes BLE transport and starts GATT server for handling provisioning requests wifi_prov_scheme_softap : This activates SoftAP mode of Wi-Fi and starts protocomm_httpd, which internally starts an HTTP server for handling provisioning requests (If mDNS is active it also starts advertising service with type _esp_wifi_prov._tcp) Event WIFI_PROV_START is emitted right after provisioning starts without failure Note This API will start provisioning service even if device is found to be already provisioned, i.e. wifi_prov_mgr_is_provisioned() yields true - Parameters security -- [in] Specify which protocomm security scheme to use : WIFI_PROV_SECURITY_0 : For no security WIFI_PROV_SECURITY_1 : x25519 secure handshake for session establishment followed by AES-CTR encryption of provisioning messages WIFI_PROV_SECURITY_2: SRP6a based authentication and key exchange followed by AES-GCM encryption/decryption of provisioning messages - wifi_prov_sec_params -- [in] Pointer to security params (NULL if not needed). This is not needed for protocomm security 0 This pointer should hold the struct of type wifi_prov_security1_params_t for protocomm security 1 and wifi_prov_security2_params_t for protocomm security 2 respectively. This pointer and its contents should be valid till the provisioning service is running and has not been stopped or de-inited. service_name -- [in] Unique name of the service. This translates to: Wi-Fi SSID when provisioning mode is softAP Device name when provisioning mode is BLE - service_key -- [in] Key required by client to access the service (NULL if not needed). This translates to: Wi-Fi password when provisioning mode is softAP ignored when provisioning mode is BLE - - - Returns ESP_OK : Provisioning started successfully ESP_FAIL : Failed to start provisioning service ESP_ERR_INVALID_STATE : Provisioning manager not initialized or already started - - - void wifi_prov_mgr_stop_provisioning(void) Stop provisioning service. If provisioning service is active, this API will initiate a process to stop the service and return. Once the service actually stops, the event WIFI_PROV_END will be emitted. If wifi_prov_mgr_deinit() is called without calling this API first, it will automatically stop the provisioning service and emit the WIFI_PROV_END, followed by WIFI_PROV_DEINIT, before returning. This API will generally be used along with wifi_prov_mgr_disable_auto_stop() in the scenario when the main application has registered its own endpoints, and wishes that the provisioning service is stopped only when some protocomm command from the client side application is received. Calling this API inside an endpoint handler, with sufficient cleanup_delay, will allow the response / acknowledgment to be sent successfully before the underlying protocomm service is stopped. Cleaup_delay is set when calling wifi_prov_mgr_disable_auto_stop(). If not specified, it defaults to 1000ms. For straightforward cases, using this API is usually not necessary as provisioning is stopped automatically once WIFI_PROV_CRED_SUCCESS is emitted. Stopping is delayed (maximum 30 seconds) thus allowing the client side application to query for Wi-Fi state, i.e. after receiving the first query and sending Wi-Fi state connectedresponse the service is stopped immediately. - void wifi_prov_mgr_wait(void) Wait for provisioning service to finish. Calling this API will block until provisioning service is stopped i.e. till event WIFI_PROV_END is emitted. This will not block if provisioning is not started or not initialized. - esp_err_t wifi_prov_mgr_disable_auto_stop(uint32_t cleanup_delay) Disable auto stopping of provisioning service upon completion. By default, once provisioning is complete, the provisioning service is automatically stopped, and all endpoints (along with those registered by main application) are deactivated. This API is useful in the case when main application wishes to close provisioning service only after it receives some protocomm command from the client side app. For example, after connecting to Wi-Fi, the device may want to connect to the cloud, and only once that is successfully, the device is said to be fully configured. But, then it is upto the main application to explicitly call wifi_prov_mgr_stop_provisioning() later when the device is fully configured and the provisioning service is no longer required. Note This must be called before executing wifi_prov_mgr_start_provisioning() - Parameters cleanup_delay -- [in] Sets the delay after which the actual cleanup of transport related resources is done after a call to wifi_prov_mgr_stop_provisioning() returns. Minimum allowed value is 100ms. If not specified, this will default to 1000ms. - Returns ESP_OK : Success ESP_ERR_INVALID_STATE : Manager not initialized or provisioning service already started - - esp_err_t wifi_prov_mgr_set_app_info(const char *label, const char *version, const char **capabilities, size_t total_capabilities) Set application version and capabilities in the JSON data returned by proto-ver endpoint. This function can be called multiple times, to specify information about the various application specific services running on the device, identified by unique labels. The provisioning service itself registers an entry in the JSON data, by the label "prov", containing only provisioning service version and capabilities. Application services should use a label other than "prov" so as not to overwrite this. Note This must be called before executing wifi_prov_mgr_start_provisioning() - Parameters label -- [in] String indicating the application name. version -- [in] String indicating the application version. There is no constraint on format. capabilities -- [in] Array of strings with capabilities. These could be used by the client side app to know the application registered endpoint capabilities total_capabilities -- [in] Size of capabilities array - - Returns ESP_OK : Success ESP_ERR_INVALID_STATE : Manager not initialized or provisioning service already started ESP_ERR_NO_MEM : Failed to allocate memory for version string ESP_ERR_INVALID_ARG : Null argument - - esp_err_t wifi_prov_mgr_endpoint_create(const char *ep_name) Create an additional endpoint and allocate internal resources for it. This API is to be called by the application if it wants to create an additional endpoint. All additional endpoints will be assigned UUIDs starting from 0xFF54 and so on in the order of execution. protocomm handler for the created endpoint is to be registered later using wifi_prov_mgr_endpoint_register() after provisioning has started. Note This API can only be called BEFORE provisioning is started Note Additional endpoints can be used for configuring client provided parameters other than Wi-Fi credentials, that are necessary for the main application and hence must be set prior to starting the application Note After session establishment, the additional endpoints must be targeted first by the client side application before sending Wi-Fi configuration, because once Wi-Fi configuration finishes the provisioning service is stopped and hence all endpoints are unregistered - Parameters ep_name -- [in] unique name of the endpoint - Returns ESP_OK : Success ESP_FAIL : Failure - - esp_err_t wifi_prov_mgr_endpoint_register(const char *ep_name, protocomm_req_handler_t handler, void *user_ctx) Register a handler for the previously created endpoint. This API can be called by the application to register a protocomm handler to any endpoint that was created using wifi_prov_mgr_endpoint_create(). Note This API can only be called AFTER provisioning has started Note Additional endpoints can be used for configuring client provided parameters other than Wi-Fi credentials, that are necessary for the main application and hence must be set prior to starting the application Note After session establishment, the additional endpoints must be targeted first by the client side application before sending Wi-Fi configuration, because once Wi-Fi configuration finishes the provisioning service is stopped and hence all endpoints are unregistered - Parameters ep_name -- [in] Name of the endpoint handler -- [in] Endpoint handler function user_ctx -- [in] User data - - Returns ESP_OK : Success ESP_FAIL : Failure - - void wifi_prov_mgr_endpoint_unregister(const char *ep_name) Unregister the handler for an endpoint. This API can be called if the application wants to selectively unregister the handler of an endpoint while the provisioning is still in progress. All the endpoint handlers are unregistered automatically when the provisioning stops. - Parameters ep_name -- [in] Name of the endpoint - esp_err_t wifi_prov_mgr_get_wifi_state(wifi_prov_sta_state_t *state) Get state of Wi-Fi Station during provisioning. - Parameters state -- [out] Pointer to wifi_prov_sta_state_t variable to be filled - Returns ESP_OK : Successfully retrieved Wi-Fi state ESP_FAIL : Provisioning app not running - - esp_err_t wifi_prov_mgr_get_wifi_disconnect_reason(wifi_prov_sta_fail_reason_t *reason) Get reason code in case of Wi-Fi station disconnection during provisioning. - Parameters reason -- [out] Pointer to wifi_prov_sta_fail_reason_t variable to be filled - Returns ESP_OK : Successfully retrieved Wi-Fi disconnect reason ESP_FAIL : Provisioning app not running - - esp_err_t wifi_prov_mgr_configure_sta(wifi_config_t *wifi_cfg) Runs Wi-Fi as Station with the supplied configuration. Configures the Wi-Fi station mode to connect to the AP with SSID and password specified in config structure and sets Wi-Fi to run as station. This is automatically called by provisioning service upon receiving new credentials. If credentials are to be supplied to the manager via a different mode other than through protocomm, then this API needs to be called. Event WIFI_PROV_CRED_RECV is emitted after credentials have been applied and Wi-Fi station started - Parameters wifi_cfg -- [in] Pointer to Wi-Fi configuration structure - Returns ESP_OK : Wi-Fi configured and started successfully ESP_FAIL : Failed to set configuration - - esp_err_t wifi_prov_mgr_reset_provisioning(void) Reset Wi-Fi provisioning config. Calling this API will restore WiFi stack persistent settings to default values. - Returns ESP_OK : Reset provisioning config successfully ESP_FAIL : Failed to reset provisioning config - - esp_err_t wifi_prov_mgr_reset_sm_state_on_failure(void) Reset internal state machine and clear provisioned credentials. This API should be used to restart provisioning ONLY in the case of provisioning failures without rebooting the device. - Returns ESP_OK : Reset provisioning state machine successfully ESP_FAIL : Failed to reset provisioning state machine ESP_ERR_INVALID_STATE : Manager not initialized - - esp_err_t wifi_prov_mgr_reset_sm_state_for_reprovision(void) Reset internal state machine and clear provisioned credentials. This API can be used to restart provisioning ONLY in case the device is to be provisioned again for new credentials after a previous successful provisioning without rebooting the device. Note This API can be used only if provisioning auto-stop has been disabled using wifi_prov_mgr_disable_auto_stop() - Returns ESP_OK : Reset provisioning state machine successfully ESP_FAIL : Failed to reset provisioning state machine ESP_ERR_INVALID_STATE : Manager not initialized - Structures - struct wifi_prov_event_handler_t Event handler that is used by the manager while provisioning service is active. Public Members - wifi_prov_cb_func_t event_cb Callback function to be executed on provisioning events - void *user_data User context data to pass as parameter to callback function - wifi_prov_cb_func_t event_cb - struct wifi_prov_scheme Structure for specifying the provisioning scheme to be followed by the manager. Note Ready to use schemes are available: wifi_prov_scheme_ble : for provisioning over BLE transport + GATT server wifi_prov_scheme_softap : for provisioning over SoftAP transport + HTTP server wifi_prov_scheme_console : for provisioning over Serial UART transport + Console (for debugging) Public Members - esp_err_t (*prov_start)(protocomm_t *pc, void *config) Function which is to be called by the manager when it is to start the provisioning service associated with a protocomm instance and a scheme specific configuration - esp_err_t (*prov_stop)(protocomm_t *pc) Function which is to be called by the manager to stop the provisioning service previously associated with a protocomm instance - void *(*new_config)(void) Function which is to be called by the manager to generate a new configuration for the provisioning service, that is to be passed to prov_start() - void (*delete_config)(void *config) Function which is to be called by the manager to delete a configuration generated using new_config() - esp_err_t (*set_config_service)(void *config, const char *service_name, const char *service_key) Function which is to be called by the manager to set the service name and key values in the configuration structure - esp_err_t (*set_config_endpoint)(void *config, const char *endpoint_name, uint16_t uuid) Function which is to be called by the manager to set a protocomm endpoint with an identifying name and UUID in the configuration structure - wifi_mode_t wifi_mode Sets mode of operation of Wi-Fi during provisioning This is set to : WIFI_MODE_APSTA for SoftAP transport WIFI_MODE_STA for BLE transport - - - struct wifi_prov_mgr_config_t Structure for specifying the manager configuration. Public Members - wifi_prov_scheme_t scheme Provisioning scheme to use. Following schemes are already available: wifi_prov_scheme_ble : for provisioning over BLE transport + GATT server wifi_prov_scheme_softap : for provisioning over SoftAP transport + HTTP server + mDNS (optional) wifi_prov_scheme_console : for provisioning over Serial UART transport + Console (for debugging) - - wifi_prov_event_handler_t scheme_event_handler Event handler required by the scheme for incorporating scheme specific behavior while provisioning manager is running. Various options may be provided by the scheme for setting this field. Use WIFI_PROV_EVENT_HANDLER_NONE when not used. When using scheme wifi_prov_scheme_ble, the following options are available: WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BLE WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BT - - wifi_prov_event_handler_t app_event_handler Event handler that can be set for the purpose of incorporating application specific behavior. Use WIFI_PROV_EVENT_HANDLER_NONE when not used. - wifi_prov_scheme_t scheme Macros - WIFI_PROV_EVENT_HANDLER_NONE Event handler can be set to none if not used. Type Definitions - typedef void (*wifi_prov_cb_func_t)(void *user_data, wifi_prov_cb_event_t event, void *event_data) - typedef struct wifi_prov_scheme wifi_prov_scheme_t Structure for specifying the provisioning scheme to be followed by the manager. Note Ready to use schemes are available: wifi_prov_scheme_ble : for provisioning over BLE transport + GATT server wifi_prov_scheme_softap : for provisioning over SoftAP transport + HTTP server wifi_prov_scheme_console : for provisioning over Serial UART transport + Console (for debugging) - - typedef enum wifi_prov_security wifi_prov_security_t Security modes supported by the Provisioning Manager. These are same as the security modes provided by protocomm - typedef protocomm_security2_params_t wifi_prov_security2_params_t Security 2 params structure This needs to be passed when using WIFI_PROV_SECURITY_2. Enumerations - enum wifi_prov_cb_event_t Events generated by manager. These events are generated in order of declaration and, for the stretch of time between initialization and de-initialization of the manager, each event is signaled only once Values: - enumerator WIFI_PROV_INIT Emitted when the manager is initialized - enumerator WIFI_PROV_START Indicates that provisioning has started - enumerator WIFI_PROV_CRED_RECV Emitted when Wi-Fi AP credentials are received via protocommendpoint wifi_config. The event data in this case is a pointer to the corresponding wifi_sta_config_tstructure - enumerator WIFI_PROV_CRED_FAIL Emitted when device fails to connect to the AP of which the credentials were received earlier on event WIFI_PROV_CRED_RECV. The event data in this case is a pointer to the disconnection reason code with type wifi_prov_sta_fail_reason_t - enumerator WIFI_PROV_CRED_SUCCESS Emitted when device successfully connects to the AP of which the credentials were received earlier on event WIFI_PROV_CRED_RECV - enumerator WIFI_PROV_END Signals that provisioning service has stopped - enumerator WIFI_PROV_DEINIT Signals that manager has been de-initialized - enumerator WIFI_PROV_INIT - enum wifi_prov_security Security modes supported by the Provisioning Manager. These are same as the security modes provided by protocomm Values: - enumerator WIFI_PROV_SECURITY_0 No security (plain-text communication) - enumerator WIFI_PROV_SECURITY_1 This secure communication mode consists of X25519 key exchange proof of possession (pop) based authentication AES-CTR encryption - - enumerator WIFI_PROV_SECURITY_2 This secure communication mode consists of SRP6a based authentication and key exchange AES-GCM encryption/decryption - - enumerator WIFI_PROV_SECURITY_0 Header File components/wifi_provisioning/include/wifi_provisioning/scheme_ble.h This header file can be included with: #include "wifi_provisioning/scheme_ble.h" This header file is a part of the API provided by the wifi_provisioningcomponent. To declare that your component depends on wifi_provisioning, add the following to your CMakeLists.txt: REQUIRES wifi_provisioning or PRIV_REQUIRES wifi_provisioning Functions - void wifi_prov_scheme_ble_event_cb_free_btdm(void *user_data, wifi_prov_cb_event_t event, void *event_data) - void wifi_prov_scheme_ble_event_cb_free_ble(void *user_data, wifi_prov_cb_event_t event, void *event_data) - void wifi_prov_scheme_ble_event_cb_free_bt(void *user_data, wifi_prov_cb_event_t event, void *event_data) - esp_err_t wifi_prov_scheme_ble_set_service_uuid(uint8_t *uuid128) Set the 128 bit GATT service UUID used for provisioning. This API is used to override the default 128 bit provisioning service UUID, which is 0000ffff-0000-1000-8000-00805f9b34fb. This must be called before starting provisioning, i.e. before making a call to wifi_prov_mgr_start_provisioning(), otherwise the default UUID will be used. Note The data being pointed to by the argument must be valid atleast till provisioning is started. Upon start, the manager will store an internal copy of this UUID, and this data can be freed or invalidated afterwords. - Parameters uuid128 -- [in] A custom 128 bit UUID - Returns ESP_OK : Success ESP_ERR_INVALID_ARG : Null argument - - esp_err_t wifi_prov_scheme_ble_set_mfg_data(uint8_t *mfg_data, ssize_t mfg_data_len) Set manufacturer specific data in scan response. This must be called before starting provisioning, i.e. before making a call to wifi_prov_mgr_start_provisioning(). Note It is important to understand that length of custom manufacturer data should be within limits. The manufacturer data goes into scan response along with BLE device name. By default, BLE device name length is of 11 Bytes, however it can vary as per application use case. So, one has to honour the scan response data size limits i.e. (mfg_data_len + 2) < 31 - (device_name_length + 2 ). If the mfg_data length exceeds this limit, the length will be truncated. - Parameters mfg_data -- [in] Custom manufacturer data mfg_data_len -- [in] Manufacturer data length - - Returns ESP_OK : Success ESP_ERR_INVALID_ARG : Null argument - Macros - WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM - WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BLE - WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BT Header File components/wifi_provisioning/include/wifi_provisioning/scheme_softap.h This header file can be included with: #include "wifi_provisioning/scheme_softap.h" This header file is a part of the API provided by the wifi_provisioningcomponent. To declare that your component depends on wifi_provisioning, add the following to your CMakeLists.txt: REQUIRES wifi_provisioning or PRIV_REQUIRES wifi_provisioning Functions - void wifi_prov_scheme_softap_set_httpd_handle(void *handle) Provide HTTPD Server handle externally. Useful in cases wherein applications need the webserver for some different operations, and do not want the wifi provisioning component to start/stop a new instance. Note This API should be called before wifi_prov_mgr_start_provisioning() - Parameters handle -- [in] Handle to HTTPD server instance Header File components/wifi_provisioning/include/wifi_provisioning/scheme_console.h This header file can be included with: #include "wifi_provisioning/scheme_console.h" This header file is a part of the API provided by the wifi_provisioningcomponent. To declare that your component depends on wifi_provisioning, add the following to your CMakeLists.txt: REQUIRES wifi_provisioning or PRIV_REQUIRES wifi_provisioning Header File components/wifi_provisioning/include/wifi_provisioning/wifi_config.h This header file can be included with: #include "wifi_provisioning/wifi_config.h" This header file is a part of the API provided by the wifi_provisioningcomponent. To declare that your component depends on wifi_provisioning, add the following to your CMakeLists.txt: REQUIRES wifi_provisioning or PRIV_REQUIRES wifi_provisioning Functions - esp_err_t wifi_prov_config_data_handler(uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen, void *priv_data) Handler for receiving and responding to requests from master. This is to be registered as the wifi_configendpoint handler (protocomm protocomm_req_handler_t) using protocomm_add_endpoint() Structures - struct wifi_prov_sta_conn_info_t WiFi STA connected status information. - struct wifi_prov_config_get_data_t WiFi status data to be sent in response to get_statusrequest from master. Public Members - wifi_prov_sta_state_t wifi_state WiFi state of the station - wifi_prov_sta_fail_reason_t fail_reason Reason for disconnection (valid only when wifi_stateis WIFI_STATION_DISCONNECTED) - wifi_prov_sta_conn_info_t conn_info Connection information (valid only when wifi_stateis WIFI_STATION_CONNECTED) - wifi_prov_sta_state_t wifi_state - struct wifi_prov_config_set_data_t WiFi config data received by slave during set_configrequest from master. - struct wifi_prov_config_handlers Internal handlers for receiving and responding to protocomm requests from master. This is to be passed as priv_data for protocomm request handler (refer to wifi_prov_config_data_handler()) when calling protocomm_add_endpoint(). Public Members - esp_err_t (*get_status_handler)(wifi_prov_config_get_data_t *resp_data, wifi_prov_ctx_t **ctx) Handler function called when connection status of the slave (in WiFi station mode) is requested - esp_err_t (*set_config_handler)(const wifi_prov_config_set_data_t *req_data, wifi_prov_ctx_t **ctx) Handler function called when WiFi connection configuration (eg. AP SSID, password, etc.) of the slave (in WiFi station mode) is to be set to user provided values - esp_err_t (*apply_config_handler)(wifi_prov_ctx_t **ctx) Handler function for applying the configuration that was set in set_config_handler. After applying the station may get connected to the AP or may fail to connect. The slave must be ready to convey the updated connection status information when get_status_handleris invoked again by the master. - wifi_prov_ctx_t *ctx Context pointer to be passed to above handler functions upon invocation - esp_err_t (*get_status_handler)(wifi_prov_config_get_data_t *resp_data, wifi_prov_ctx_t **ctx) Type Definitions - typedef struct wifi_prov_ctx wifi_prov_ctx_t Type of context data passed to each get/set/apply handler function set in wifi_prov_config_handlersstructure. This is passed as an opaque pointer, thereby allowing it be defined later in application code as per requirements. - typedef struct wifi_prov_config_handlers wifi_prov_config_handlers_t Internal handlers for receiving and responding to protocomm requests from master. This is to be passed as priv_data for protocomm request handler (refer to wifi_prov_config_data_handler()) when calling protocomm_add_endpoint(). Enumerations - enum wifi_prov_sta_state_t WiFi STA status for conveying back to the provisioning master. Values: - enumerator WIFI_PROV_STA_CONNECTING - enumerator WIFI_PROV_STA_CONNECTED - enumerator WIFI_PROV_STA_DISCONNECTED - enumerator WIFI_PROV_STA_CONNECTING
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/provisioning/wifi_provisioning.html
ESP-IDF Programming Guide v5.2.1 documentation
null
FAT Filesystem Support
null
espressif.com
2016-01-01
8e45da4bb6add0b3
null
null
FAT Filesystem Support ESP-IDF uses the FatFs library to work with FAT filesystems. FatFs resides in the fatfs component. Although the library can be used directly, many of its features can be accessed via VFS using the C standard library and POSIX API functions. Additionally, FatFs has been modified to support the runtime pluggable disk I/O layer. This allows mapping of FatFs drives to physical disks at runtime. Using FatFs with VFS The header file fatfs/vfs/esp_vfs_fat.h defines the functions for connecting FatFs and VFS. The function esp_vfs_fat_register() allocates a FATFS structure and registers a given path prefix in VFS. Subsequent operations on files starting with this prefix are forwarded to FatFs APIs. The function esp_vfs_fat_unregister_path() deletes the registration with VFS, and frees the FATFS structure. Most applications use the following workflow when working with esp_vfs_fat_ functions: Call esp_vfs_fat_register() to specify: Path prefix where to mount the filesystem (e.g., "/sdcard" , "/spiflash" ) FatFs drive number A variable which receives the pointer to the FATFS structure Path prefix where to mount the filesystem (e.g., "/sdcard" , "/spiflash" ) FatFs drive number A variable which receives the pointer to the FATFS structure Path prefix where to mount the filesystem (e.g., "/sdcard" , "/spiflash" ) Call esp_vfs_fat_register() to specify: Path prefix where to mount the filesystem (e.g., "/sdcard" , "/spiflash" ) FatFs drive number A variable which receives the pointer to the FATFS structure Call esp_vfs_fat_register() to specify: Call ff_diskio_register() to register the disk I/O driver for the drive number used in Step 1. Call the FatFs function f_mount() , and optionally f_fdisk() , f_mkfs() , to mount the filesystem using the same drive number which was passed to esp_vfs_fat_register() . For more information, see FatFs documentation. Call the C standard library and POSIX API functions to perform such actions on files as open, read, write, erase, copy, etc. Use paths starting with the path prefix passed to esp_vfs_register() (for example, "/sdcard/hello.txt" ). The filesystem uses 8.3 filenames format (SFN) by default. If you need to use long filenames (LFN), enable the CONFIG_FATFS_LONG_FILENAMES option. More details on the FatFs filenames are available here. Optionally, by enabling the option CONFIG_FATFS_USE_FASTSEEK, you can use the POSIX lseek function to perform it faster. The fast seek does not work for files in write mode, so to take advantage of fast seek, you should open (or close and then reopen) the file in read-only mode. Optionally, by enabling the option CONFIG_FATFS_IMMEDIATE_FSYNC, you can enable automatic calling of f_sync() to flush recent file changes after each call of vfs_fat_write() , vfs_fat_pwrite() , vfs_fat_link() , vfs_fat_truncate() and vfs_fat_ftruncate() functions. This feature improves file-consistency and size reporting accuracy for the FatFs, at a price on decreased performance due to frequent disk operations. Optionally, call the FatFs library functions directly. In this case, use paths without a VFS prefix, for example, "/hello.txt" . Close all open files. Call the FatFs function f_mount() for the same drive number with NULL FATFS* argument to unmount the filesystem. Call the FatFs function ff_diskio_register() with NULL ff_diskio_impl_t* argument and the same drive number to unregister the disk I/O driver. Call esp_vfs_fat_unregister_path() with the path where the file system is mounted to remove FatFs from VFS, and free the FATFS structure allocated in Step 1. The convenience functions esp_vfs_fat_sdmmc_mount() , esp_vfs_fat_sdspi_mount() , and esp_vfs_fat_sdcard_unmount() wrap the steps described above and also handle SD card initialization. These functions are described in the next section. Using FatFs with VFS and SD Cards The header file fatfs/vfs/esp_vfs_fat.h defines convenience functions esp_vfs_fat_sdmmc_mount() , esp_vfs_fat_sdspi_mount() , and esp_vfs_fat_sdcard_unmount() . These functions perform Steps 1–3 and 7–9 respectively and handle SD card initialization, but provide only limited error handling. Developers are encouraged to check its source code and incorporate more advanced features into production applications. The convenience function esp_vfs_fat_sdmmc_unmount() unmounts the filesystem and releases the resources acquired by esp_vfs_fat_sdmmc_mount() . Using FatFs with VFS in Read-Only Mode The header file fatfs/vfs/esp_vfs_fat.h also defines the convenience functions esp_vfs_fat_spiflash_mount_ro() and esp_vfs_fat_spiflash_unmount_ro() . These functions perform Steps 1-3 and 7-9 respectively for read-only FAT partitions. These are particularly helpful for data partitions written only once during factory provisioning, which will not be changed by production application throughout the lifetime of the hardware. FatFS Disk IO Layer FatFs has been extended with API functions that register the disk I/O driver at runtime. These APIs provide implementation of disk I/O functions for SD/MMC cards and can be registered for the given FatFs drive number using the function ff_diskio_register_sdmmc() . void ff_diskio_register(BYTE pdrv, const ff_diskio_impl_t *discio_impl) Register or unregister diskio driver for given drive number. When FATFS library calls one of disk_xxx functions for driver number pdrv, corresponding function in discio_impl for given pdrv will be called. Parameters pdrv -- drive number discio_impl -- pointer to ff_diskio_impl_t structure with diskio functions or NULL to unregister and free previously registered drive pdrv -- drive number discio_impl -- pointer to ff_diskio_impl_t structure with diskio functions or NULL to unregister and free previously registered drive pdrv -- drive number Parameters pdrv -- drive number discio_impl -- pointer to ff_diskio_impl_t structure with diskio functions or NULL to unregister and free previously registered drive struct ff_diskio_impl_t Structure of pointers to disk IO driver functions. See FatFs documentation for details about these functions Public Members DSTATUS (*init)(unsigned char pdrv) disk initialization function DSTATUS (*init)(unsigned char pdrv) disk initialization function DSTATUS (*status)(unsigned char pdrv) disk status check function DSTATUS (*status)(unsigned char pdrv) disk status check function DRESULT (*read)(unsigned char pdrv, unsigned char *buff, uint32_t sector, unsigned count) sector read function DRESULT (*read)(unsigned char pdrv, unsigned char *buff, uint32_t sector, unsigned count) sector read function DRESULT (*write)(unsigned char pdrv, const unsigned char *buff, uint32_t sector, unsigned count) sector write function DRESULT (*write)(unsigned char pdrv, const unsigned char *buff, uint32_t sector, unsigned count) sector write function DRESULT (*ioctl)(unsigned char pdrv, unsigned char cmd, void *buff) function to get info about disk and do some misc operations DRESULT (*ioctl)(unsigned char pdrv, unsigned char cmd, void *buff) function to get info about disk and do some misc operations DSTATUS (*init)(unsigned char pdrv) void ff_diskio_register_sdmmc(unsigned char pdrv, sdmmc_card_t *card) Register SD/MMC diskio driver Parameters pdrv -- drive number card -- pointer to sdmmc_card_t structure describing a card; card should be initialized before calling f_mount. pdrv -- drive number card -- pointer to sdmmc_card_t structure describing a card; card should be initialized before calling f_mount. pdrv -- drive number Parameters pdrv -- drive number card -- pointer to sdmmc_card_t structure describing a card; card should be initialized before calling f_mount. esp_err_t ff_diskio_register_wl_partition(unsigned char pdrv, wl_handle_t flash_handle) Register spi flash partition Parameters pdrv -- drive number flash_handle -- handle of the wear levelling partition. pdrv -- drive number flash_handle -- handle of the wear levelling partition. pdrv -- drive number Parameters pdrv -- drive number flash_handle -- handle of the wear levelling partition. esp_err_t ff_diskio_register_raw_partition(unsigned char pdrv, const esp_partition_t *part_handle) Register spi flash partition Parameters pdrv -- drive number part_handle -- pointer to raw flash partition. pdrv -- drive number part_handle -- pointer to raw flash partition. pdrv -- drive number Parameters pdrv -- drive number part_handle -- pointer to raw flash partition. FatFs Partition Generator We provide a partition generator for FatFs (wl_fatfsgen.py ) which is integrated into the build system and could be easily used in the user project. The tool is used to create filesystem images on a host and populate it with content of the specified host folder. The script is based on the partition generator (fatfsgen.py ). Apart from generating partition, it can also initialize wear levelling. The latest version supports both short and long file names, FAT12 and FAT16. The long file names are limited to 255 characters and can contain multiple periods ( . ) characters within the filename and additional characters + , , , ; , = , [ and ] . An in-depth description of the FatFs partition generator and analyzer can be found at Generating and parsing FAT partition on host. Build System Integration with FatFs Partition Generator It is possible to invoke FatFs generator directly from the CMake build system by calling fatfs_create_spiflash_image : fatfs_create_spiflash_image(<partition> <base_dir> [FLASH_IN_PROJECT]) If you prefer generating partition without wear levelling support, you can use fatfs_create_rawflash_image : fatfs_create_rawflash_image(<partition> <base_dir> [FLASH_IN_PROJECT]) fatfs_create_spiflash_image respectively fatfs_create_rawflash_image must be called from project's CMakeLists.txt. If you decide for any reason to use fatfs_create_rawflash_image (without wear levelling support), beware that it supports mounting only in read-only mode in the device. The arguments of the function are as follows: partition - the name of the partition as defined in the partition table (e.g., storage/fatfsgen/partitions_example.csv). base_dir - the directory that will be encoded to FatFs partition and optionally flashed into the device. Beware that you have to specify the suitable size of the partition in the partition table. flag FLASH_IN_PROJECT - optionally, users can have the image automatically flashed together with the app binaries, partition tables, etc. on idf.py flash -p <PORT> by specifying FLASH_IN_PROJECT . flag PRESERVE_TIME - optionally, users can force preserving the timestamps from the source folder to the target image. Without preserving the time, every timestamp will be set to the FATFS default initial time (1st January 1980). For example: fatfs_create_spiflash_image(my_fatfs_partition my_folder FLASH_IN_PROJECT) If FLASH_IN_PROJECT is not specified, the image will still be generated, but you will have to flash it manually using esptool.py or a custom build system target. For an example, see storage/fatfsgen. FatFs Partition Analyzer (fatfsparse.py ) is a partition analyzing tool for FatFs. It is a reverse tool of (fatfsgen.py ), i.e., it can generate the folder structure on the host based on the FatFs image. Usage: ./fatfsparse.py [-h] [--wl-layer {detect,enabled,disabled}] fatfs_image.img High-level API Reference Header File This header file can be included with: #include "esp_vfs_fat.h" This header file is a part of the API provided by the fatfs component. To declare that your component depends on fatfs , add the following to your CMakeLists.txt: REQUIRES fatfs or PRIV_REQUIRES fatfs Functions esp_err_t esp_vfs_fat_register(const char *base_path, const char *fat_drive, size_t max_files, FATFS **out_fs) Register FATFS with VFS component. This function registers given FAT drive in VFS, at the specified base path. If only one drive is used, fat_drive argument can be an empty string. Refer to FATFS library documentation on how to specify FAT drive. This function also allocates FATFS structure which should be used for f_mount call. Note This function doesn't mount the drive into FATFS, it just connects POSIX and C standard library IO function with FATFS. You need to mount desired drive into FATFS separately. Parameters base_path -- path prefix where FATFS should be registered fat_drive -- FATFS drive specification; if only one drive is used, can be an empty string max_files -- maximum number of files which can be open at the same time out_fs -- [out] pointer to FATFS structure which can be used for FATFS f_mount call is returned via this argument. base_path -- path prefix where FATFS should be registered fat_drive -- FATFS drive specification; if only one drive is used, can be an empty string max_files -- maximum number of files which can be open at the same time out_fs -- [out] pointer to FATFS structure which can be used for FATFS f_mount call is returned via this argument. base_path -- path prefix where FATFS should be registered Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_register was already called ESP_ERR_NO_MEM if not enough memory or too many VFSes already registered ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_register was already called ESP_ERR_NO_MEM if not enough memory or too many VFSes already registered ESP_OK on success Parameters base_path -- path prefix where FATFS should be registered fat_drive -- FATFS drive specification; if only one drive is used, can be an empty string max_files -- maximum number of files which can be open at the same time out_fs -- [out] pointer to FATFS structure which can be used for FATFS f_mount call is returned via this argument. Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_register was already called ESP_ERR_NO_MEM if not enough memory or too many VFSes already registered esp_err_t esp_vfs_fat_unregister_path(const char *base_path) Un-register FATFS from VFS. Note FATFS structure returned by esp_vfs_fat_register is destroyed after this call. Make sure to call f_mount function to unmount it before calling esp_vfs_fat_unregister_ctx. Difference between this function and the one above is that this one will release the correct drive, while the one above will release the last registered one Parameters base_path -- path prefix where FATFS is registered. This is the same used when esp_vfs_fat_register was called Returns ESP_OK on success ESP_ERR_INVALID_STATE if FATFS is not registered in VFS ESP_OK on success ESP_ERR_INVALID_STATE if FATFS is not registered in VFS ESP_OK on success Parameters base_path -- path prefix where FATFS is registered. This is the same used when esp_vfs_fat_register was called Returns ESP_OK on success ESP_ERR_INVALID_STATE if FATFS is not registered in VFS esp_err_t esp_vfs_fat_sdmmc_mount(const char *base_path, const sdmmc_host_t *host_config, const void *slot_config, const esp_vfs_fat_mount_config_t *mount_config, sdmmc_card_t **out_card) Convenience function to get FAT filesystem on SD card registered in VFS. This is an all-in-one function which does the following: initializes SDMMC driver or SPI driver with configuration in host_config initializes SD card with configuration in slot_config mounts FAT partition on SD card using FATFS library, with configuration in mount_config registers FATFS library with VFS, with prefix given by base_prefix variable initializes SDMMC driver or SPI driver with configuration in host_config initializes SD card with configuration in slot_config mounts FAT partition on SD card using FATFS library, with configuration in mount_config registers FATFS library with VFS, with prefix given by base_prefix variable This function is intended to make example code more compact. For real world applications, developers should implement the logic of probing SD card, locating and mounting partition, and registering FATFS in VFS, with proper error checking and handling of exceptional conditions. Note Use this API to mount a card through SDSPI is deprecated. Please call esp_vfs_fat_sdspi_mount() instead for that case. Parameters base_path -- path where partition should be registered (e.g. "/sdcard") host_config -- Pointer to structure describing SDMMC host. When using SDMMC peripheral, this structure can be initialized using SDMMC_HOST_DEFAULT() macro. When using SPI peripheral, this structure can be initialized using SDSPI_HOST_DEFAULT() macro. slot_config -- Pointer to structure with slot configuration. For SDMMC peripheral, pass a pointer to sdmmc_slot_config_t structure initialized using SDMMC_SLOT_CONFIG_DEFAULT. mount_config -- pointer to structure with extra parameters for mounting FATFS out_card -- [out] if not NULL, pointer to the card information structure will be returned via this argument base_path -- path where partition should be registered (e.g. "/sdcard") host_config -- Pointer to structure describing SDMMC host. When using SDMMC peripheral, this structure can be initialized using SDMMC_HOST_DEFAULT() macro. When using SPI peripheral, this structure can be initialized using SDSPI_HOST_DEFAULT() macro. slot_config -- Pointer to structure with slot configuration. For SDMMC peripheral, pass a pointer to sdmmc_slot_config_t structure initialized using SDMMC_SLOT_CONFIG_DEFAULT. mount_config -- pointer to structure with extra parameters for mounting FATFS out_card -- [out] if not NULL, pointer to the card information structure will be returned via this argument base_path -- path where partition should be registered (e.g. "/sdcard") Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers ESP_OK on success Parameters base_path -- path where partition should be registered (e.g. "/sdcard") host_config -- Pointer to structure describing SDMMC host. When using SDMMC peripheral, this structure can be initialized using SDMMC_HOST_DEFAULT() macro. When using SPI peripheral, this structure can be initialized using SDSPI_HOST_DEFAULT() macro. slot_config -- Pointer to structure with slot configuration. For SDMMC peripheral, pass a pointer to sdmmc_slot_config_t structure initialized using SDMMC_SLOT_CONFIG_DEFAULT. mount_config -- pointer to structure with extra parameters for mounting FATFS out_card -- [out] if not NULL, pointer to the card information structure will be returned via this argument Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers initializes SDMMC driver or SPI driver with configuration in host_config esp_err_t esp_vfs_fat_sdspi_mount(const char *base_path, const sdmmc_host_t *host_config_input, const sdspi_device_config_t *slot_config, const esp_vfs_fat_mount_config_t *mount_config, sdmmc_card_t **out_card) Convenience function to get FAT filesystem on SD card registered in VFS. This is an all-in-one function which does the following: initializes an SPI Master device based on the SPI Master driver with configuration in slot_config, and attach it to an initialized SPI bus. initializes SD card with configuration in host_config_input mounts FAT partition on SD card using FATFS library, with configuration in mount_config registers FATFS library with VFS, with prefix given by base_prefix variable initializes an SPI Master device based on the SPI Master driver with configuration in slot_config, and attach it to an initialized SPI bus. initializes SD card with configuration in host_config_input mounts FAT partition on SD card using FATFS library, with configuration in mount_config registers FATFS library with VFS, with prefix given by base_prefix variable This function is intended to make example code more compact. For real world applications, developers should implement the logic of probing SD card, locating and mounting partition, and registering FATFS in VFS, with proper error checking and handling of exceptional conditions. Note This function try to attach the new SD SPI device to the bus specified in host_config. Make sure the SPI bus specified in host_config->slot have been initialized by spi_bus_initialize() before. Parameters base_path -- path where partition should be registered (e.g. "/sdcard") host_config_input -- Pointer to structure describing SDMMC host. This structure can be initialized using SDSPI_HOST_DEFAULT() macro. slot_config -- Pointer to structure with slot configuration. For SPI peripheral, pass a pointer to sdspi_device_config_t structure initialized using SDSPI_DEVICE_CONFIG_DEFAULT(). mount_config -- pointer to structure with extra parameters for mounting FATFS out_card -- [out] If not NULL, pointer to the card information structure will be returned via this argument. It is suggested to hold this handle and use it to unmount the card later if needed. Otherwise it's not suggested to use more than one card at the same time and unmount one of them in your application. base_path -- path where partition should be registered (e.g. "/sdcard") host_config_input -- Pointer to structure describing SDMMC host. This structure can be initialized using SDSPI_HOST_DEFAULT() macro. slot_config -- Pointer to structure with slot configuration. For SPI peripheral, pass a pointer to sdspi_device_config_t structure initialized using SDSPI_DEVICE_CONFIG_DEFAULT(). mount_config -- pointer to structure with extra parameters for mounting FATFS out_card -- [out] If not NULL, pointer to the card information structure will be returned via this argument. It is suggested to hold this handle and use it to unmount the card later if needed. Otherwise it's not suggested to use more than one card at the same time and unmount one of them in your application. base_path -- path where partition should be registered (e.g. "/sdcard") Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers ESP_OK on success Parameters base_path -- path where partition should be registered (e.g. "/sdcard") host_config_input -- Pointer to structure describing SDMMC host. This structure can be initialized using SDSPI_HOST_DEFAULT() macro. slot_config -- Pointer to structure with slot configuration. For SPI peripheral, pass a pointer to sdspi_device_config_t structure initialized using SDSPI_DEVICE_CONFIG_DEFAULT(). mount_config -- pointer to structure with extra parameters for mounting FATFS out_card -- [out] If not NULL, pointer to the card information structure will be returned via this argument. It is suggested to hold this handle and use it to unmount the card later if needed. Otherwise it's not suggested to use more than one card at the same time and unmount one of them in your application. Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers initializes an SPI Master device based on the SPI Master driver with configuration in slot_config, and attach it to an initialized SPI bus. esp_err_t esp_vfs_fat_sdmmc_unmount(void) Unmount FAT filesystem and release resources acquired using esp_vfs_fat_sdmmc_mount. Deprecated: Use esp_vfs_fat_sdcard_unmount() instead. Deprecated: Use esp_vfs_fat_sdcard_unmount() instead. Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount hasn't been called ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount hasn't been called ESP_OK on success Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount hasn't been called esp_err_t esp_vfs_fat_sdcard_unmount(const char *base_path, sdmmc_card_t *card) Unmount an SD card from the FAT filesystem and release resources acquired using esp_vfs_fat_sdmmc_mount() or esp_vfs_fat_sdspi_mount() Returns ESP_OK on success ESP_ERR_INVALID_ARG if the card argument is unregistered ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount hasn't been called ESP_OK on success ESP_ERR_INVALID_ARG if the card argument is unregistered ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount hasn't been called ESP_OK on success Returns ESP_OK on success ESP_ERR_INVALID_ARG if the card argument is unregistered ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount hasn't been called esp_err_t esp_vfs_fat_sdcard_format(const char *base_path, sdmmc_card_t *card) Format FAT filesystem. Note This API should be only called when the FAT is already mounted. Parameters base_path -- Path where partition should be registered (e.g. "/sdcard") card -- Pointer to the card handle, which should be initialised by calling esp_vfs_fat_sdspi_mount first base_path -- Path where partition should be registered (e.g. "/sdcard") card -- Pointer to the card handle, which should be initialised by calling esp_vfs_fat_sdspi_mount first base_path -- Path where partition should be registered (e.g. "/sdcard") Returns ESP_OK ESP_ERR_INVALID_STATE: FAT partition isn't mounted, call esp_vfs_fat_sdmmc_mount or esp_vfs_fat_sdspi_mount first ESP_ERR_NO_MEM: if memory can not be allocated ESP_FAIL: fail to format it, or fail to mount back ESP_OK ESP_ERR_INVALID_STATE: FAT partition isn't mounted, call esp_vfs_fat_sdmmc_mount or esp_vfs_fat_sdspi_mount first ESP_ERR_NO_MEM: if memory can not be allocated ESP_FAIL: fail to format it, or fail to mount back ESP_OK Parameters base_path -- Path where partition should be registered (e.g. "/sdcard") card -- Pointer to the card handle, which should be initialised by calling esp_vfs_fat_sdspi_mount first Returns ESP_OK ESP_ERR_INVALID_STATE: FAT partition isn't mounted, call esp_vfs_fat_sdmmc_mount or esp_vfs_fat_sdspi_mount first ESP_ERR_NO_MEM: if memory can not be allocated ESP_FAIL: fail to format it, or fail to mount back esp_err_t esp_vfs_fat_spiflash_mount_rw_wl(const char *base_path, const char *partition_label, const esp_vfs_fat_mount_config_t *mount_config, wl_handle_t *wl_handle) Convenience function to initialize FAT filesystem in SPI flash and register it in VFS. This is an all-in-one function which does the following: finds the partition with defined partition_label. Partition label should be configured in the partition table. initializes flash wear levelling library on top of the given partition mounts FAT partition using FATFS library on top of flash wear levelling library registers FATFS library with VFS, with prefix given by base_prefix variable finds the partition with defined partition_label. Partition label should be configured in the partition table. initializes flash wear levelling library on top of the given partition mounts FAT partition using FATFS library on top of flash wear levelling library registers FATFS library with VFS, with prefix given by base_prefix variable This function is intended to make example code more compact. Parameters base_path -- path where FATFS partition should be mounted (e.g. "/spiflash") partition_label -- label of the partition which should be used mount_config -- pointer to structure with extra parameters for mounting FATFS wl_handle -- [out] wear levelling driver handle base_path -- path where FATFS partition should be mounted (e.g. "/spiflash") partition_label -- label of the partition which should be used mount_config -- pointer to structure with extra parameters for mounting FATFS wl_handle -- [out] wear levelling driver handle base_path -- path where FATFS partition should be mounted (e.g. "/spiflash") Returns ESP_OK on success ESP_ERR_NOT_FOUND if the partition table does not contain FATFS partition with given label ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_rw_wl was already called ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from wear levelling library, SPI flash driver, or FATFS drivers ESP_OK on success ESP_ERR_NOT_FOUND if the partition table does not contain FATFS partition with given label ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_rw_wl was already called ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from wear levelling library, SPI flash driver, or FATFS drivers ESP_OK on success Parameters base_path -- path where FATFS partition should be mounted (e.g. "/spiflash") partition_label -- label of the partition which should be used mount_config -- pointer to structure with extra parameters for mounting FATFS wl_handle -- [out] wear levelling driver handle Returns ESP_OK on success ESP_ERR_NOT_FOUND if the partition table does not contain FATFS partition with given label ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_rw_wl was already called ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from wear levelling library, SPI flash driver, or FATFS drivers finds the partition with defined partition_label. Partition label should be configured in the partition table. esp_err_t esp_vfs_fat_spiflash_unmount_rw_wl(const char *base_path, wl_handle_t wl_handle) Unmount FAT filesystem and release resources acquired using esp_vfs_fat_spiflash_mount_rw_wl. Parameters base_path -- path where partition should be registered (e.g. "/spiflash") wl_handle -- wear levelling driver handle returned by esp_vfs_fat_spiflash_mount_rw_wl base_path -- path where partition should be registered (e.g. "/spiflash") wl_handle -- wear levelling driver handle returned by esp_vfs_fat_spiflash_mount_rw_wl base_path -- path where partition should be registered (e.g. "/spiflash") Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_rw_wl hasn't been called ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_rw_wl hasn't been called ESP_OK on success Parameters base_path -- path where partition should be registered (e.g. "/spiflash") wl_handle -- wear levelling driver handle returned by esp_vfs_fat_spiflash_mount_rw_wl Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_rw_wl hasn't been called esp_err_t esp_vfs_fat_spiflash_format_rw_wl(const char *base_path, const char *partition_label) Format FAT filesystem. Note This API can be called when the FAT is mounted / not mounted. If this API is called when the FAT isn't mounted (by calling esp_vfs_fat_spiflash_mount_rw_wl), this API will first mount the FAT then format it, then restore back to the original state. Parameters base_path -- Path where partition should be registered (e.g. "/spiflash") partition_label -- Label of the partition which should be used base_path -- Path where partition should be registered (e.g. "/spiflash") partition_label -- Label of the partition which should be used base_path -- Path where partition should be registered (e.g. "/spiflash") Returns ESP_OK ESP_ERR_NO_MEM: if memory can not be allocated Other errors from esp_vfs_fat_spiflash_mount_rw_wl ESP_OK ESP_ERR_NO_MEM: if memory can not be allocated Other errors from esp_vfs_fat_spiflash_mount_rw_wl ESP_OK Parameters base_path -- Path where partition should be registered (e.g. "/spiflash") partition_label -- Label of the partition which should be used Returns ESP_OK ESP_ERR_NO_MEM: if memory can not be allocated Other errors from esp_vfs_fat_spiflash_mount_rw_wl esp_err_t esp_vfs_fat_spiflash_mount_ro(const char *base_path, const char *partition_label, const esp_vfs_fat_mount_config_t *mount_config) Convenience function to initialize read-only FAT filesystem and register it in VFS. This is an all-in-one function which does the following: finds the partition with defined partition_label. Partition label should be configured in the partition table. mounts FAT partition using FATFS library registers FATFS library with VFS, with prefix given by base_prefix variable finds the partition with defined partition_label. Partition label should be configured in the partition table. mounts FAT partition using FATFS library registers FATFS library with VFS, with prefix given by base_prefix variable Note Wear levelling is not used when FAT is mounted in read-only mode using this function. Parameters base_path -- path where FATFS partition should be mounted (e.g. "/spiflash") partition_label -- label of the partition which should be used mount_config -- pointer to structure with extra parameters for mounting FATFS base_path -- path where FATFS partition should be mounted (e.g. "/spiflash") partition_label -- label of the partition which should be used mount_config -- pointer to structure with extra parameters for mounting FATFS base_path -- path where FATFS partition should be mounted (e.g. "/spiflash") Returns ESP_OK on success ESP_ERR_NOT_FOUND if the partition table does not contain FATFS partition with given label ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_ro was already called for the same partition ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from SPI flash driver, or FATFS drivers ESP_OK on success ESP_ERR_NOT_FOUND if the partition table does not contain FATFS partition with given label ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_ro was already called for the same partition ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from SPI flash driver, or FATFS drivers ESP_OK on success Parameters base_path -- path where FATFS partition should be mounted (e.g. "/spiflash") partition_label -- label of the partition which should be used mount_config -- pointer to structure with extra parameters for mounting FATFS Returns ESP_OK on success ESP_ERR_NOT_FOUND if the partition table does not contain FATFS partition with given label ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_ro was already called for the same partition ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from SPI flash driver, or FATFS drivers finds the partition with defined partition_label. Partition label should be configured in the partition table. esp_err_t esp_vfs_fat_spiflash_unmount_ro(const char *base_path, const char *partition_label) Unmount FAT filesystem and release resources acquired using esp_vfs_fat_spiflash_mount_ro. Parameters base_path -- path where partition should be registered (e.g. "/spiflash") partition_label -- label of partition to be unmounted base_path -- path where partition should be registered (e.g. "/spiflash") partition_label -- label of partition to be unmounted base_path -- path where partition should be registered (e.g. "/spiflash") Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_ro hasn't been called ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_ro hasn't been called ESP_OK on success Parameters base_path -- path where partition should be registered (e.g. "/spiflash") partition_label -- label of partition to be unmounted Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_ro hasn't been called esp_err_t esp_vfs_fat_info(const char *base_path, uint64_t *out_total_bytes, uint64_t *out_free_bytes) Get information for FATFS partition. Parameters base_path -- Base path of the partition examined (e.g. "/spiflash") out_total_bytes -- [out] Size of the file system out_free_bytes -- [out] Free bytes available in the file system base_path -- Base path of the partition examined (e.g. "/spiflash") out_total_bytes -- [out] Size of the file system out_free_bytes -- [out] Free bytes available in the file system base_path -- Base path of the partition examined (e.g. "/spiflash") Returns ESP_OK on success ESP_ERR_INVALID_STATE if partition not found ESP_FAIL if another FRESULT error (saved in errno) ESP_OK on success ESP_ERR_INVALID_STATE if partition not found ESP_FAIL if another FRESULT error (saved in errno) ESP_OK on success Parameters base_path -- Base path of the partition examined (e.g. "/spiflash") out_total_bytes -- [out] Size of the file system out_free_bytes -- [out] Free bytes available in the file system Returns ESP_OK on success ESP_ERR_INVALID_STATE if partition not found ESP_FAIL if another FRESULT error (saved in errno) Structures struct esp_vfs_fat_mount_config_t Configuration arguments for esp_vfs_fat_sdmmc_mount and esp_vfs_fat_spiflash_mount_rw_wl functions. Public Members bool format_if_mount_failed If FAT partition can not be mounted, and this parameter is true, create partition table and format the filesystem. bool format_if_mount_failed If FAT partition can not be mounted, and this parameter is true, create partition table and format the filesystem. int max_files Max number of open files. int max_files Max number of open files. size_t allocation_unit_size If format_if_mount_failed is set, and mount fails, format the card with given allocation unit size. Must be a power of 2, between sector size and 128 * sector size. For SD cards, sector size is always 512 bytes. For wear_levelling, sector size is determined by CONFIG_WL_SECTOR_SIZE option. Using larger allocation unit size will result in higher read/write performance and higher overhead when storing small files. Setting this field to 0 will result in allocation unit set to the sector size. size_t allocation_unit_size If format_if_mount_failed is set, and mount fails, format the card with given allocation unit size. Must be a power of 2, between sector size and 128 * sector size. For SD cards, sector size is always 512 bytes. For wear_levelling, sector size is determined by CONFIG_WL_SECTOR_SIZE option. Using larger allocation unit size will result in higher read/write performance and higher overhead when storing small files. Setting this field to 0 will result in allocation unit set to the sector size. bool disk_status_check_enable Enables real ff_disk_status function implementation for SD cards (ff_sdmmc_status). Possibly slows down IO performance. Try to enable if you need to handle situations when SD cards are not unmounted properly before physical removal or you are experiencing issues with SD cards. Doesn't do anything for other memory storage media. bool disk_status_check_enable Enables real ff_disk_status function implementation for SD cards (ff_sdmmc_status). Possibly slows down IO performance. Try to enable if you need to handle situations when SD cards are not unmounted properly before physical removal or you are experiencing issues with SD cards. Doesn't do anything for other memory storage media. bool format_if_mount_failed Type Definitions typedef esp_vfs_fat_mount_config_t esp_vfs_fat_sdmmc_mount_config_t
FAT Filesystem Support ESP-IDF uses the FatFs library to work with FAT filesystems. FatFs resides in the fatfs component. Although the library can be used directly, many of its features can be accessed via VFS using the C standard library and POSIX API functions. Additionally, FatFs has been modified to support the runtime pluggable disk I/O layer. This allows mapping of FatFs drives to physical disks at runtime. Using FatFs with VFS The header file fatfs/vfs/esp_vfs_fat.h defines the functions for connecting FatFs and VFS. The function esp_vfs_fat_register() allocates a FATFS structure and registers a given path prefix in VFS. Subsequent operations on files starting with this prefix are forwarded to FatFs APIs. The function esp_vfs_fat_unregister_path() deletes the registration with VFS, and frees the FATFS structure. Most applications use the following workflow when working with esp_vfs_fat_ functions: - Call esp_vfs_fat_register()to specify: Path prefix where to mount the filesystem (e.g., "/sdcard", "/spiflash") FatFs drive number A variable which receives the pointer to the FATFSstructure - - Call Call ff_diskio_register()to register the disk I/O driver for the drive number used in Step 1. Call the FatFs function f_mount(), and optionally f_fdisk(), f_mkfs(), to mount the filesystem using the same drive number which was passed to esp_vfs_fat_register(). For more information, see FatFs documentation. Call the C standard library and POSIX API functions to perform such actions on files as open, read, write, erase, copy, etc. Use paths starting with the path prefix passed to esp_vfs_register()(for example, "/sdcard/hello.txt"). The filesystem uses 8.3 filenames format (SFN) by default. If you need to use long filenames (LFN), enable the CONFIG_FATFS_LONG_FILENAMES option. More details on the FatFs filenames are available here. Optionally, by enabling the option CONFIG_FATFS_USE_FASTSEEK, you can use the POSIX lseek function to perform it faster. The fast seek does not work for files in write mode, so to take advantage of fast seek, you should open (or close and then reopen) the file in read-only mode. Optionally, by enabling the option CONFIG_FATFS_IMMEDIATE_FSYNC, you can enable automatic calling of f_sync()to flush recent file changes after each call of vfs_fat_write(), vfs_fat_pwrite(), vfs_fat_link(), vfs_fat_truncate()and vfs_fat_ftruncate()functions. This feature improves file-consistency and size reporting accuracy for the FatFs, at a price on decreased performance due to frequent disk operations. Optionally, call the FatFs library functions directly. In this case, use paths without a VFS prefix, for example, "/hello.txt". Close all open files. Call the FatFs function f_mount()for the same drive number with NULL FATFS*argument to unmount the filesystem. Call the FatFs function ff_diskio_register()with NULL ff_diskio_impl_t*argument and the same drive number to unregister the disk I/O driver. Call esp_vfs_fat_unregister_path()with the path where the file system is mounted to remove FatFs from VFS, and free the FATFSstructure allocated in Step 1. The convenience functions esp_vfs_fat_sdmmc_mount(), esp_vfs_fat_sdspi_mount(), and esp_vfs_fat_sdcard_unmount() wrap the steps described above and also handle SD card initialization. These functions are described in the next section. Using FatFs with VFS and SD Cards The header file fatfs/vfs/esp_vfs_fat.h defines convenience functions esp_vfs_fat_sdmmc_mount(), esp_vfs_fat_sdspi_mount(), and esp_vfs_fat_sdcard_unmount(). These functions perform Steps 1–3 and 7–9 respectively and handle SD card initialization, but provide only limited error handling. Developers are encouraged to check its source code and incorporate more advanced features into production applications. The convenience function esp_vfs_fat_sdmmc_unmount() unmounts the filesystem and releases the resources acquired by esp_vfs_fat_sdmmc_mount(). Using FatFs with VFS in Read-Only Mode The header file fatfs/vfs/esp_vfs_fat.h also defines the convenience functions esp_vfs_fat_spiflash_mount_ro() and esp_vfs_fat_spiflash_unmount_ro(). These functions perform Steps 1-3 and 7-9 respectively for read-only FAT partitions. These are particularly helpful for data partitions written only once during factory provisioning, which will not be changed by production application throughout the lifetime of the hardware. FatFS Disk IO Layer FatFs has been extended with API functions that register the disk I/O driver at runtime. These APIs provide implementation of disk I/O functions for SD/MMC cards and can be registered for the given FatFs drive number using the function ff_diskio_register_sdmmc(). - void ff_diskio_register(BYTE pdrv, const ff_diskio_impl_t *discio_impl) Register or unregister diskio driver for given drive number. When FATFS library calls one of disk_xxx functions for driver number pdrv, corresponding function in discio_impl for given pdrv will be called. - Parameters pdrv -- drive number discio_impl -- pointer to ff_diskio_impl_t structure with diskio functions or NULL to unregister and free previously registered drive - - struct ff_diskio_impl_t Structure of pointers to disk IO driver functions. See FatFs documentation for details about these functions Public Members - DSTATUS (*init)(unsigned char pdrv) disk initialization function - DSTATUS (*status)(unsigned char pdrv) disk status check function - DRESULT (*read)(unsigned char pdrv, unsigned char *buff, uint32_t sector, unsigned count) sector read function - DRESULT (*write)(unsigned char pdrv, const unsigned char *buff, uint32_t sector, unsigned count) sector write function - DRESULT (*ioctl)(unsigned char pdrv, unsigned char cmd, void *buff) function to get info about disk and do some misc operations - DSTATUS (*init)(unsigned char pdrv) - void ff_diskio_register_sdmmc(unsigned char pdrv, sdmmc_card_t *card) Register SD/MMC diskio driver - Parameters pdrv -- drive number card -- pointer to sdmmc_card_t structure describing a card; card should be initialized before calling f_mount. - - esp_err_t ff_diskio_register_wl_partition(unsigned char pdrv, wl_handle_t flash_handle) Register spi flash partition - Parameters pdrv -- drive number flash_handle -- handle of the wear levelling partition. - - esp_err_t ff_diskio_register_raw_partition(unsigned char pdrv, const esp_partition_t *part_handle) Register spi flash partition - Parameters pdrv -- drive number part_handle -- pointer to raw flash partition. - FatFs Partition Generator We provide a partition generator for FatFs (wl_fatfsgen.py ) which is integrated into the build system and could be easily used in the user project. The tool is used to create filesystem images on a host and populate it with content of the specified host folder. The script is based on the partition generator (fatfsgen.py ). Apart from generating partition, it can also initialize wear levelling. The latest version supports both short and long file names, FAT12 and FAT16. The long file names are limited to 255 characters and can contain multiple periods ( .) characters within the filename and additional characters +, ,, ;, =, [ and ]. An in-depth description of the FatFs partition generator and analyzer can be found at Generating and parsing FAT partition on host. Build System Integration with FatFs Partition Generator It is possible to invoke FatFs generator directly from the CMake build system by calling fatfs_create_spiflash_image: fatfs_create_spiflash_image(<partition> <base_dir> [FLASH_IN_PROJECT]) If you prefer generating partition without wear levelling support, you can use fatfs_create_rawflash_image: fatfs_create_rawflash_image(<partition> <base_dir> [FLASH_IN_PROJECT]) fatfs_create_spiflash_image respectively fatfs_create_rawflash_image must be called from project's CMakeLists.txt. If you decide for any reason to use fatfs_create_rawflash_image (without wear levelling support), beware that it supports mounting only in read-only mode in the device. The arguments of the function are as follows: partition - the name of the partition as defined in the partition table (e.g., storage/fatfsgen/partitions_example.csv). base_dir - the directory that will be encoded to FatFs partition and optionally flashed into the device. Beware that you have to specify the suitable size of the partition in the partition table. flag FLASH_IN_PROJECT- optionally, users can have the image automatically flashed together with the app binaries, partition tables, etc. on idf.py flash -p <PORT>by specifying FLASH_IN_PROJECT. flag PRESERVE_TIME- optionally, users can force preserving the timestamps from the source folder to the target image. Without preserving the time, every timestamp will be set to the FATFS default initial time (1st January 1980). For example: fatfs_create_spiflash_image(my_fatfs_partition my_folder FLASH_IN_PROJECT) If FLASH_IN_PROJECT is not specified, the image will still be generated, but you will have to flash it manually using esptool.py or a custom build system target. For an example, see storage/fatfsgen. FatFs Partition Analyzer (fatfsparse.py ) is a partition analyzing tool for FatFs. It is a reverse tool of (fatfsgen.py ), i.e., it can generate the folder structure on the host based on the FatFs image. Usage: ./fatfsparse.py [-h] [--wl-layer {detect,enabled,disabled}] fatfs_image.img High-level API Reference Header File This header file can be included with: #include "esp_vfs_fat.h" This header file is a part of the API provided by the fatfscomponent. To declare that your component depends on fatfs, add the following to your CMakeLists.txt: REQUIRES fatfs or PRIV_REQUIRES fatfs Functions - esp_err_t esp_vfs_fat_register(const char *base_path, const char *fat_drive, size_t max_files, FATFS **out_fs) Register FATFS with VFS component. This function registers given FAT drive in VFS, at the specified base path. If only one drive is used, fat_drive argument can be an empty string. Refer to FATFS library documentation on how to specify FAT drive. This function also allocates FATFS structure which should be used for f_mount call. Note This function doesn't mount the drive into FATFS, it just connects POSIX and C standard library IO function with FATFS. You need to mount desired drive into FATFS separately. - Parameters base_path -- path prefix where FATFS should be registered fat_drive -- FATFS drive specification; if only one drive is used, can be an empty string max_files -- maximum number of files which can be open at the same time out_fs -- [out] pointer to FATFS structure which can be used for FATFS f_mount call is returned via this argument. - - Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_register was already called ESP_ERR_NO_MEM if not enough memory or too many VFSes already registered - - esp_err_t esp_vfs_fat_unregister_path(const char *base_path) Un-register FATFS from VFS. Note FATFS structure returned by esp_vfs_fat_register is destroyed after this call. Make sure to call f_mount function to unmount it before calling esp_vfs_fat_unregister_ctx. Difference between this function and the one above is that this one will release the correct drive, while the one above will release the last registered one - Parameters base_path -- path prefix where FATFS is registered. This is the same used when esp_vfs_fat_register was called - Returns ESP_OK on success ESP_ERR_INVALID_STATE if FATFS is not registered in VFS - - esp_err_t esp_vfs_fat_sdmmc_mount(const char *base_path, const sdmmc_host_t *host_config, const void *slot_config, const esp_vfs_fat_mount_config_t *mount_config, sdmmc_card_t **out_card) Convenience function to get FAT filesystem on SD card registered in VFS. This is an all-in-one function which does the following: initializes SDMMC driver or SPI driver with configuration in host_config initializes SD card with configuration in slot_config mounts FAT partition on SD card using FATFS library, with configuration in mount_config registers FATFS library with VFS, with prefix given by base_prefix variable This function is intended to make example code more compact. For real world applications, developers should implement the logic of probing SD card, locating and mounting partition, and registering FATFS in VFS, with proper error checking and handling of exceptional conditions. Note Use this API to mount a card through SDSPI is deprecated. Please call esp_vfs_fat_sdspi_mount()instead for that case. - Parameters base_path -- path where partition should be registered (e.g. "/sdcard") host_config -- Pointer to structure describing SDMMC host. When using SDMMC peripheral, this structure can be initialized using SDMMC_HOST_DEFAULT() macro. When using SPI peripheral, this structure can be initialized using SDSPI_HOST_DEFAULT() macro. slot_config -- Pointer to structure with slot configuration. For SDMMC peripheral, pass a pointer to sdmmc_slot_config_t structure initialized using SDMMC_SLOT_CONFIG_DEFAULT. mount_config -- pointer to structure with extra parameters for mounting FATFS out_card -- [out] if not NULL, pointer to the card information structure will be returned via this argument - - Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers - - - esp_err_t esp_vfs_fat_sdspi_mount(const char *base_path, const sdmmc_host_t *host_config_input, const sdspi_device_config_t *slot_config, const esp_vfs_fat_mount_config_t *mount_config, sdmmc_card_t **out_card) Convenience function to get FAT filesystem on SD card registered in VFS. This is an all-in-one function which does the following: initializes an SPI Master device based on the SPI Master driver with configuration in slot_config, and attach it to an initialized SPI bus. initializes SD card with configuration in host_config_input mounts FAT partition on SD card using FATFS library, with configuration in mount_config registers FATFS library with VFS, with prefix given by base_prefix variable This function is intended to make example code more compact. For real world applications, developers should implement the logic of probing SD card, locating and mounting partition, and registering FATFS in VFS, with proper error checking and handling of exceptional conditions. Note This function try to attach the new SD SPI device to the bus specified in host_config. Make sure the SPI bus specified in host_config->slothave been initialized by spi_bus_initialize()before. - Parameters base_path -- path where partition should be registered (e.g. "/sdcard") host_config_input -- Pointer to structure describing SDMMC host. This structure can be initialized using SDSPI_HOST_DEFAULT() macro. slot_config -- Pointer to structure with slot configuration. For SPI peripheral, pass a pointer to sdspi_device_config_t structure initialized using SDSPI_DEVICE_CONFIG_DEFAULT(). mount_config -- pointer to structure with extra parameters for mounting FATFS out_card -- [out] If not NULL, pointer to the card information structure will be returned via this argument. It is suggested to hold this handle and use it to unmount the card later if needed. Otherwise it's not suggested to use more than one card at the same time and unmount one of them in your application. - - Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers - - - esp_err_t esp_vfs_fat_sdmmc_unmount(void) Unmount FAT filesystem and release resources acquired using esp_vfs_fat_sdmmc_mount. - Deprecated: Use esp_vfs_fat_sdcard_unmount()instead. - Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount hasn't been called - - esp_err_t esp_vfs_fat_sdcard_unmount(const char *base_path, sdmmc_card_t *card) Unmount an SD card from the FAT filesystem and release resources acquired using esp_vfs_fat_sdmmc_mount()or esp_vfs_fat_sdspi_mount() - Returns ESP_OK on success ESP_ERR_INVALID_ARG if the card argument is unregistered ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount hasn't been called - - esp_err_t esp_vfs_fat_sdcard_format(const char *base_path, sdmmc_card_t *card) Format FAT filesystem. Note This API should be only called when the FAT is already mounted. - Parameters base_path -- Path where partition should be registered (e.g. "/sdcard") card -- Pointer to the card handle, which should be initialised by calling esp_vfs_fat_sdspi_mountfirst - - Returns ESP_OK ESP_ERR_INVALID_STATE: FAT partition isn't mounted, call esp_vfs_fat_sdmmc_mount or esp_vfs_fat_sdspi_mount first ESP_ERR_NO_MEM: if memory can not be allocated ESP_FAIL: fail to format it, or fail to mount back - - esp_err_t esp_vfs_fat_spiflash_mount_rw_wl(const char *base_path, const char *partition_label, const esp_vfs_fat_mount_config_t *mount_config, wl_handle_t *wl_handle) Convenience function to initialize FAT filesystem in SPI flash and register it in VFS. This is an all-in-one function which does the following: finds the partition with defined partition_label. Partition label should be configured in the partition table. initializes flash wear levelling library on top of the given partition mounts FAT partition using FATFS library on top of flash wear levelling library registers FATFS library with VFS, with prefix given by base_prefix variable This function is intended to make example code more compact. - Parameters base_path -- path where FATFS partition should be mounted (e.g. "/spiflash") partition_label -- label of the partition which should be used mount_config -- pointer to structure with extra parameters for mounting FATFS wl_handle -- [out] wear levelling driver handle - - Returns ESP_OK on success ESP_ERR_NOT_FOUND if the partition table does not contain FATFS partition with given label ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_rw_wl was already called ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from wear levelling library, SPI flash driver, or FATFS drivers - - - esp_err_t esp_vfs_fat_spiflash_unmount_rw_wl(const char *base_path, wl_handle_t wl_handle) Unmount FAT filesystem and release resources acquired using esp_vfs_fat_spiflash_mount_rw_wl. - Parameters base_path -- path where partition should be registered (e.g. "/spiflash") wl_handle -- wear levelling driver handle returned by esp_vfs_fat_spiflash_mount_rw_wl - - Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_rw_wl hasn't been called - - esp_err_t esp_vfs_fat_spiflash_format_rw_wl(const char *base_path, const char *partition_label) Format FAT filesystem. Note This API can be called when the FAT is mounted / not mounted. If this API is called when the FAT isn't mounted (by calling esp_vfs_fat_spiflash_mount_rw_wl), this API will first mount the FAT then format it, then restore back to the original state. - Parameters base_path -- Path where partition should be registered (e.g. "/spiflash") partition_label -- Label of the partition which should be used - - Returns ESP_OK ESP_ERR_NO_MEM: if memory can not be allocated Other errors from esp_vfs_fat_spiflash_mount_rw_wl - - esp_err_t esp_vfs_fat_spiflash_mount_ro(const char *base_path, const char *partition_label, const esp_vfs_fat_mount_config_t *mount_config) Convenience function to initialize read-only FAT filesystem and register it in VFS. This is an all-in-one function which does the following: finds the partition with defined partition_label. Partition label should be configured in the partition table. mounts FAT partition using FATFS library registers FATFS library with VFS, with prefix given by base_prefix variable Note Wear levelling is not used when FAT is mounted in read-only mode using this function. - Parameters base_path -- path where FATFS partition should be mounted (e.g. "/spiflash") partition_label -- label of the partition which should be used mount_config -- pointer to structure with extra parameters for mounting FATFS - - Returns ESP_OK on success ESP_ERR_NOT_FOUND if the partition table does not contain FATFS partition with given label ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_ro was already called for the same partition ESP_ERR_NO_MEM if memory can not be allocated ESP_FAIL if partition can not be mounted other error codes from SPI flash driver, or FATFS drivers - - - esp_err_t esp_vfs_fat_spiflash_unmount_ro(const char *base_path, const char *partition_label) Unmount FAT filesystem and release resources acquired using esp_vfs_fat_spiflash_mount_ro. - Parameters base_path -- path where partition should be registered (e.g. "/spiflash") partition_label -- label of partition to be unmounted - - Returns ESP_OK on success ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_ro hasn't been called - - esp_err_t esp_vfs_fat_info(const char *base_path, uint64_t *out_total_bytes, uint64_t *out_free_bytes) Get information for FATFS partition. - Parameters base_path -- Base path of the partition examined (e.g. "/spiflash") out_total_bytes -- [out] Size of the file system out_free_bytes -- [out] Free bytes available in the file system - - Returns ESP_OK on success ESP_ERR_INVALID_STATE if partition not found ESP_FAIL if another FRESULT error (saved in errno) - Structures - struct esp_vfs_fat_mount_config_t Configuration arguments for esp_vfs_fat_sdmmc_mount and esp_vfs_fat_spiflash_mount_rw_wl functions. Public Members - bool format_if_mount_failed If FAT partition can not be mounted, and this parameter is true, create partition table and format the filesystem. - int max_files Max number of open files. - size_t allocation_unit_size If format_if_mount_failed is set, and mount fails, format the card with given allocation unit size. Must be a power of 2, between sector size and 128 * sector size. For SD cards, sector size is always 512 bytes. For wear_levelling, sector size is determined by CONFIG_WL_SECTOR_SIZE option. Using larger allocation unit size will result in higher read/write performance and higher overhead when storing small files. Setting this field to 0 will result in allocation unit set to the sector size. - bool disk_status_check_enable Enables real ff_disk_status function implementation for SD cards (ff_sdmmc_status). Possibly slows down IO performance. Try to enable if you need to handle situations when SD cards are not unmounted properly before physical removal or you are experiencing issues with SD cards. Doesn't do anything for other memory storage media. - bool format_if_mount_failed Type Definitions - typedef esp_vfs_fat_mount_config_t esp_vfs_fat_sdmmc_mount_config_t
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/storage/fatfs.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Manufacturing Utility
null
espressif.com
2016-01-01
be97185984470f89
null
null
Manufacturing Utility Introduction This utility is designed to create instances of factory NVS partition images on a per-device basis for mass manufacturing purposes. The NVS partition images are created from CSV files containing user-provided configurations and values. Please note that this utility only creates manufacturing binary images which then need to be flashed onto your devices using: Flash Download tool (available on Windows only) Download and unzip it, and follow the instructions inside the doc folder. Download and unzip it, and follow the instructions inside the doc folder. Download and unzip it, and follow the instructions inside the doc folder. Flash Download tool (available on Windows only) Download and unzip it, and follow the instructions inside the doc folder. Direct flash programming using custom production tools. Prerequisites This utility is dependent on ESP-IDF's NVS Partition Generator Utility. Operating System requirements: Linux / MacOS / Windows (standard distributions) Linux / MacOS / Windows (standard distributions) Linux / MacOS / Windows (standard distributions) Operating System requirements: Linux / MacOS / Windows (standard distributions) The following packages are needed to use this utility: The following packages are needed to use this utility: Note Before using this utility, please make sure that: The path to Python is added to the PATH environment variable. You have installed the packages from requirement.txt, the file in the root of the ESP-IDF directory. The path to Python is added to the PATH environment variable. You have installed the packages from requirement.txt, the file in the root of the ESP-IDF directory. The path to Python is added to the PATH environment variable. Workflow CSV Configuration File This file contains the configuration of the device to be flashed. The data in the configuration file has the following format (the REPEAT tag is optional): name1,namespace, <-- First entry should be of type "namespace" key1,type1,encoding1 key2,type2,encoding2,REPEAT name2,namespace, key3,type3,encoding3 key4,type4,encoding4 Note The first line in this file should always be the namespace entry. Each line should have three parameters: key,type,encoding , separated by a comma. If the REPEAT tag is present, the value corresponding to this key in the master value CSV file will be the same for all devices. Please refer to README of the NVS Partition Generator Utility for detailed description of each parameter. Below is a sample example of such a configuration file: app,namespace, firmware_key,data,hex2bin serial_no,data,string,REPEAT device_no,data,i32 Note Make sure there are no spaces: before and after ',' at the end of each line in a CSV file before and after ',' at the end of each line in a CSV file before and after ',' Master Value CSV File This file contains details of the devices to be flashed. Each line in this file corresponds to a device instance. The data in the master value CSV file has the following format: key1,key2,key3,..... value1,value2,value3,.... Note The first line in the file should always contain the key names. All the keys from the configuration file should be present here in the same order. This file can have additional columns (keys). The additional keys will be treated as metadata and would not be part of the final binary files. Each line should contain the value of the corresponding keys, separated by a comma. If the key has the REPEAT tag, its corresponding value must be entered in the second line only. Keep the entry empty for this value in the following lines. The description of this parameter is as follows: value Data value Data value is the value of data corresponding to the key. Below is a sample example of a master value CSV file: id,firmware_key,serial_no,device_no 1,1a2b3c4d5e6faabb,A1,101 2,1a2b3c4d5e6fccdd,,102 3,1a2b3c4d5e6feeff,,103 Note If the 'REPEAT' tag is present, a new master value CSV file will be created in the same folder as the input Master CSV File with the values inserted at each line for the key with the 'REPEAT' tag. This utility creates intermediate CSV files which are used as input for the NVS partition utility to generate the binary files. The format of this intermediate CSV file is as follows: key,type,encoding,value key,namespace, , key1,type1,encoding1,value1 key2,type2,encoding2,value2 An instance of an intermediate CSV file will be created for each device on an individual basis. Running the utility Usage: python mfg_gen.py [-h] {generate,generate-key} ... Optional Arguments: No. Parameter Description 1 -h / --help Show the help message and exit Commands: Run mfg_gen.py {command} -h for additional help No. Parameter Description 1 generate Generate NVS partition 2 generate-key Generate keys for encryption To generate factory images for each device (Default): Usage: python mfg_gen.py generate [-h] [--fileid FILEID] [--version {1,2}] [--keygen] [--inputkey INPUTKEY] [--outdir OUTDIR] [--key_protect_hmac] [--kp_hmac_keygen] [--kp_hmac_keyfile KP_HMAC_KEYFILE] [--kp_hmac_inputkey KP_HMAC_INPUTKEY] conf values prefix size Positional Arguments: Parameter Description conf Path to configuration csv file to parse values Path to values csv file to parse prefix Unique name for each output filename prefix size Size of NVS partition in bytes (must be multiple of 4096) Optional Arguments: Parameter Description -h / --help Show the help message and exit --fileid FILEID Unique file identifier (any key in values file) for each filename suffix (Default: numeric value(1,2,3...)) --version {1,2} Set multipage blob version. (Default: Version 2) Version 1 - Multipage blob support disabled. Version 2 - Multipage blob support enabled. --keygen Generates key for encrypting NVS partition --inputkey INPUTKEY File having key for encrypting NVS partition --outdir OUTDIR Output directory to store files created (Default: current directory) --key_protect_hmac If set, the NVS encryption key protection scheme based on HMAC peripheral is used; else the default scheme based on Flash Encryption is used --kp_hmac_keygen Generate the HMAC key for HMAC-based encryption scheme --kp_hmac_keyfile KP_HMAC_KEYFILE Path to output HMAC key file --kp_hmac_inputkey KP_HMAC_INPUTKEY File having the HMAC key for generating the NVS encryption keys You can run the utility to generate factory images for each device using the command below. A sample CSV file is provided with the utility: python mfg_gen.py generate samples/sample_config.csv samples/sample_values_singlepage_blob.csv Sample 0x3000 The master value CSV file should have the path in the file type relative to the directory from which you are running the utility. To generate encrypted factory images for each device: You can run the utility to encrypt factory images for each device using the command below. A sample CSV file is provided with the utility: Encrypt by allowing the utility to generate encryption keys: python mfg_gen.py generate samples/sample_config.csv samples/sample_values_singlepage_blob.csv Sample 0x3000 --keygen Note Encryption key of the following format <outdir>/keys/keys-<prefix>-<fileid>.bin is created. This newly created file having encryption keys in keys/ directory is compatible with NVS key-partition structure. Refer to NVS Key Partition for more details. To generate an encrypted image using the HMAC-based scheme, the above command can be used alongwith some additional parameters. Encrypt by allowing the utility to generate encryption keys and the HMAC-key: python mfg_gen.py generate samples/sample_config.csv samples/sample_values_singlepage_blob.csv Sample 0x3000 --keygen --key_protect_hmac --kp_hmac_keygen Encrypt by allowing the utility to generate encryption keys and the HMAC-key: python mfg_gen.py generate samples/sample_config.csv samples/sample_values_singlepage_blob.csv Sample 0x3000 --keygen --key_protect_hmac --kp_hmac_keygen Note Encryption key of the format <outdir>/keys/keys-<timestamp>.bin and HMAC key of the format <outdir>/keys/hmac-keys-<timestamp>.bin are created. Encrypt by allowing the utility to generate encryption keys and the HMAC-key: python mfg_gen.py generate samples/sample_config.csv samples/sample_values_singlepage_blob.csv Sample 0x3000 --keygen --key_protect_hmac --kp_hmac_keygen Encrypt by allowing the utility to generate encryption keys with user-provided HMAC-key: python mfg_gen.py generate samples/sample_config.csv samples/sample_values_singlepage_blob.csv Sample 0x3000 --keygen --key_protect_hmac --kp_hmac_inputkey testdata/sample_hmac_key.bin Note You can provide the custom filename for the HMAC key as well as the encryption key as a parameter. Encrypt by providing the encryption keys as input binary file: python mfg_gen.py generate samples/sample_config.csv samples/sample_values_singlepage_blob.csv Sample 0x3000 --inputkey keys/sample_keys.bin To generate only encryption keys: Usage:: python mfg_gen.py generate-key [-h] [--keyfile KEYFILE] [--outdir OUTDIR] Optional Arguments: Parameter Description -h / --help Show the help message and exit --keyfile KEYFILE Path to output encryption keys file --outdir OUTDIR Output directory to store files created. (Default: current directory) --key_protect_hmac If set, the NVS encryption key protection scheme based on HMAC peripheral is used; else the default scheme based on Flash Encryption is used --kp_hmac_keygen Generate the HMAC key for HMAC-based encryption scheme --kp_hmac_keyfile KP_HMAC_KEYFILE Path to output HMAC key file --kp_hmac_inputkey KP_HMAC_INPUTKEY File having the HMAC key for generating the NVS encryption keys You can run the utility to generate only encryption keys using the command below: python mfg_gen.py generate-key Note Encryption key of the following format <outdir>/keys/keys-<timestamp>.bin is created. Timestamp format is: %m-%d_%H-%M . To provide custom target filename use the --keyfile argument. For generating encryption key for the HMAC-based scheme, the following commands can be used: Generate the HMAC key and the NVS encryption keys: python mfg_gen.py generate-key --key_protect_hmac --kp_hmac_keygen Note Encryption key of the format <outdir>/keys/keys-<timestamp>.bin and HMAC key of the format <outdir>/keys/hmac-keys-<timestamp>.bin are created. Generate the NVS encryption keys, given the HMAC-key: python mfg_gen.py generate-key --key_protect_hmac --kp_hmac_inputkey testdata/sample_hmac_key.bin Note You can provide the custom filename for the HMAC key as well as the encryption key as a parameter. Generated encryption key binary file can further be used to encrypt factory images created on the per device basis. The default numeric value: 1,2,3... of the fileid argument corresponds to each line bearing device instance values in the master value CSV file. While running the manufacturing utility, the following folders will be created in the specified outdir directory: bin/ for storing the generated binary files csv/ for storing the generated intermediate CSV files keys/ for storing encryption keys (when generating encrypted factory images)
Manufacturing Utility Introduction This utility is designed to create instances of factory NVS partition images on a per-device basis for mass manufacturing purposes. The NVS partition images are created from CSV files containing user-provided configurations and values. Please note that this utility only creates manufacturing binary images which then need to be flashed onto your devices using: - Flash Download tool (available on Windows only) Download and unzip it, and follow the instructions inside the doc folder. - Direct flash programming using custom production tools. Prerequisites This utility is dependent on ESP-IDF's NVS Partition Generator Utility. - Operating System requirements: Linux / MacOS / Windows (standard distributions) - - The following packages are needed to use this utility: Note - Before using this utility, please make sure that: The path to Python is added to the PATH environment variable. You have installed the packages from requirement.txt, the file in the root of the ESP-IDF directory. - Workflow CSV Configuration File This file contains the configuration of the device to be flashed. The data in the configuration file has the following format (the REPEAT tag is optional): name1,namespace, <-- First entry should be of type "namespace" key1,type1,encoding1 key2,type2,encoding2,REPEAT name2,namespace, key3,type3,encoding3 key4,type4,encoding4 Note The first line in this file should always be the namespace entry. Each line should have three parameters: key,type,encoding, separated by a comma. If the REPEAT tag is present, the value corresponding to this key in the master value CSV file will be the same for all devices. Please refer to README of the NVS Partition Generator Utility for detailed description of each parameter. Below is a sample example of such a configuration file: app,namespace, firmware_key,data,hex2bin serial_no,data,string,REPEAT device_no,data,i32 Note - Make sure there are no spaces: before and after ',' at the end of each line in a CSV file - Master Value CSV File This file contains details of the devices to be flashed. Each line in this file corresponds to a device instance. The data in the master value CSV file has the following format: key1,key2,key3,..... value1,value2,value3,.... Note The first line in the file should always contain the key names. All the keys from the configuration file should be present here in the same order. This file can have additional columns (keys). The additional keys will be treated as metadata and would not be part of the final binary files. Each line should contain the value of the corresponding keys, separated by a comma. If the key has the REPEAT tag, its corresponding value must be entered in the second line only. Keep the entry empty for this value in the following lines. The description of this parameter is as follows: value Data value Data value is the value of data corresponding to the key. Below is a sample example of a master value CSV file: id,firmware_key,serial_no,device_no 1,1a2b3c4d5e6faabb,A1,101 2,1a2b3c4d5e6fccdd,,102 3,1a2b3c4d5e6feeff,,103 Note If the 'REPEAT' tag is present, a new master value CSV file will be created in the same folder as the input Master CSV File with the values inserted at each line for the key with the 'REPEAT' tag. This utility creates intermediate CSV files which are used as input for the NVS partition utility to generate the binary files. The format of this intermediate CSV file is as follows: key,type,encoding,value key,namespace, , key1,type1,encoding1,value1 key2,type2,encoding2,value2 An instance of an intermediate CSV file will be created for each device on an individual basis. Running the utility Usage: python mfg_gen.py [-h] {generate,generate-key} ... Optional Arguments: No. Parameter Description 1 -h/ --help Show the help message and exit Commands: Run mfg_gen.py {command} -h for additional help No. Parameter Description 1 generate Generate NVS partition 2 generate-key Generate keys for encryption To generate factory images for each device (Default): Usage: python mfg_gen.py generate [-h] [--fileid FILEID] [--version {1,2}] [--keygen] [--inputkey INPUTKEY] [--outdir OUTDIR] [--key_protect_hmac] [--kp_hmac_keygen] [--kp_hmac_keyfile KP_HMAC_KEYFILE] [--kp_hmac_inputkey KP_HMAC_INPUTKEY] conf values prefix size Positional Arguments: Parameter Description conf Path to configuration csv file to parse values Path to values csv file to parse prefix Unique name for each output filename prefix size Size of NVS partition in bytes (must be multiple of 4096) Optional Arguments: Parameter Description -h/ --help Show the help message and exit --fileid FILEID Unique file identifier (any key in values file) for each filename suffix (Default: numeric value(1,2,3...)) --version {1,2} Set multipage blob version. (Default: Version 2) Version 1 - Multipage blob support disabled. Version 2 - Multipage blob support enabled. --keygen Generates key for encrypting NVS partition --inputkey INPUTKEY File having key for encrypting NVS partition --outdir OUTDIR Output directory to store files created (Default: current directory) --key_protect_hmac If set, the NVS encryption key protection scheme based on HMAC peripheral is used; else the default scheme based on Flash Encryption is used --kp_hmac_keygen Generate the HMAC key for HMAC-based encryption scheme --kp_hmac_keyfile KP_HMAC_KEYFILE Path to output HMAC key file --kp_hmac_inputkey KP_HMAC_INPUTKEY File having the HMAC key for generating the NVS encryption keys You can run the utility to generate factory images for each device using the command below. A sample CSV file is provided with the utility: python mfg_gen.py generate samples/sample_config.csv samples/sample_values_singlepage_blob.csv Sample 0x3000 The master value CSV file should have the path in the file type relative to the directory from which you are running the utility. To generate encrypted factory images for each device: You can run the utility to encrypt factory images for each device using the command below. A sample CSV file is provided with the utility: Encrypt by allowing the utility to generate encryption keys: python mfg_gen.py generate samples/sample_config.csv samples/sample_values_singlepage_blob.csv Sample 0x3000 --keygen Note Encryption key of the following format <outdir>/keys/keys-<prefix>-<fileid>.bin is created. This newly created file having encryption keys in keys/ directory is compatible with NVS key-partition structure. Refer to NVS Key Partition for more details. To generate an encrypted image using the HMAC-based scheme, the above command can be used alongwith some additional parameters. Encrypt by allowing the utility to generate encryption keys and the HMAC-key: python mfg_gen.py generate samples/sample_config.csv samples/sample_values_singlepage_blob.csv Sample 0x3000 --keygen --key_protect_hmac --kp_hmac_keygen Note Encryption key of the format <outdir>/keys/keys-<timestamp>.binand HMAC key of the format <outdir>/keys/hmac-keys-<timestamp>.binare created. - Encrypt by allowing the utility to generate encryption keys with user-provided HMAC-key: python mfg_gen.py generate samples/sample_config.csv samples/sample_values_singlepage_blob.csv Sample 0x3000 --keygen --key_protect_hmac --kp_hmac_inputkey testdata/sample_hmac_key.bin Note You can provide the custom filename for the HMAC key as well as the encryption key as a parameter. Encrypt by providing the encryption keys as input binary file: python mfg_gen.py generate samples/sample_config.csv samples/sample_values_singlepage_blob.csv Sample 0x3000 --inputkey keys/sample_keys.bin To generate only encryption keys: - Usage:: python mfg_gen.py generate-key [-h] [--keyfile KEYFILE] [--outdir OUTDIR] - Optional Arguments: Parameter Description -h/ --help Show the help message and exit --keyfile KEYFILE Path to output encryption keys file --outdir OUTDIR Output directory to store files created. (Default: current directory) --key_protect_hmac If set, the NVS encryption key protection scheme based on HMAC peripheral is used; else the default scheme based on Flash Encryption is used --kp_hmac_keygen Generate the HMAC key for HMAC-based encryption scheme --kp_hmac_keyfile KP_HMAC_KEYFILE Path to output HMAC key file --kp_hmac_inputkey KP_HMAC_INPUTKEY File having the HMAC key for generating the NVS encryption keys You can run the utility to generate only encryption keys using the command below: python mfg_gen.py generate-key Note Encryption key of the following format <outdir>/keys/keys-<timestamp>.bin is created. Timestamp format is: %m-%d_%H-%M. To provide custom target filename use the --keyfile argument. For generating encryption key for the HMAC-based scheme, the following commands can be used: Generate the HMAC key and the NVS encryption keys: python mfg_gen.py generate-key --key_protect_hmac --kp_hmac_keygen Note Encryption key of the format <outdir>/keys/keys-<timestamp>.bin and HMAC key of the format <outdir>/keys/hmac-keys-<timestamp>.bin are created. Generate the NVS encryption keys, given the HMAC-key: python mfg_gen.py generate-key --key_protect_hmac --kp_hmac_inputkey testdata/sample_hmac_key.bin Note You can provide the custom filename for the HMAC key as well as the encryption key as a parameter. Generated encryption key binary file can further be used to encrypt factory images created on the per device basis. The default numeric value: 1,2,3... of the fileid argument corresponds to each line bearing device instance values in the master value CSV file. While running the manufacturing utility, the following folders will be created in the specified outdir directory: bin/for storing the generated binary files csv/for storing the generated intermediate CSV files keys/for storing encryption keys (when generating encrypted factory images)
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/storage/mass_mfg.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Non-Volatile Storage Library
null
espressif.com
2016-01-01
dc43b013868cd599
null
null
Non-Volatile Storage Library Introduction Non-volatile storage (NVS) library is designed to store key-value pairs in flash. This section introduces some concepts used by NVS. Underlying Storage Currently, NVS uses a portion of main flash memory through the esp_partition API. The library uses all the partitions with data type and nvs subtype. The application can choose to use the partition with the label nvs through the nvs_open() API function or any other partition by specifying its name using the nvs_open_from_partition() API function. Future versions of this library may have other storage backends to keep data in another flash chip (SPI or I2C), RTC, FRAM, etc. Note if an NVS partition is truncated (for example, when the partition table layout is changed), its contents should be erased. ESP-IDF build system provides a idf.py erase-flash target to erase all contents of the flash chip. Note NVS works best for storing many small values, rather than a few large values of the type 'string' and 'blob'. If you need to store large blobs or strings, consider using the facilities provided by the FAT filesystem on top of the wear levelling library. Keys and Values NVS operates on key-value pairs. Keys are ASCII strings; the maximum key length is currently 15 characters. Values can have one of the following types: integer types: uint8_t , int8_t , uint16_t , int16_t , uint32_t , int32_t , uint64_t , int64_t zero-terminated string variable length binary data (blob) Note String values are currently limited to 4000 bytes. This includes the null terminator. Blob values are limited to 508,000 bytes or 97.6% of the partition size - 4000 bytes, whichever is lower. Additional types, such as float and double might be added later. Keys are required to be unique. Assigning a new value to an existing key replaces the old value and data type with the value and data type specified by a write operation. A data type check is performed when reading a value. An error is returned if the data type expected by read operation does not match the data type of entry found for the key provided. Namespaces To mitigate potential conflicts in key names between different components, NVS assigns each key-value pair to one of namespaces. Namespace names follow the same rules as key names, i.e., the maximum length is 15 characters. Furthermore, there can be no more than 254 different namespaces in one NVS partition. Namespace name is specified in the nvs_open() or nvs_open_from_partition call. This call returns an opaque handle, which is used in subsequent calls to the nvs_get_* , nvs_set_* , and nvs_commit() functions. This way, a handle is associated with a namespace, and key names will not collide with same names in other namespaces. Please note that the namespaces with the same name in different NVS partitions are considered as separate namespaces. NVS Iterators Iterators allow to list key-value pairs stored in NVS, based on specified partition name, namespace, and data type. There are the following functions available: nvs_entry_find() creates an opaque handle, which is used in subsequent calls to the nvs_entry_next() and nvs_entry_info() functions. nvs_entry_next() advances an iterator to the next key-value pair. nvs_entry_info() returns information about each key-value pair In general, all iterators obtained via nvs_entry_find() have to be released using nvs_release_iterator() , which also tolerates NULL iterators. nvs_entry_find() and nvs_entry_next() set the given iterator to NULL or a valid iterator in all cases except a parameter error occured (i.e., return ESP_ERR_NVS_NOT_FOUND ). In case of a parameter error, the given iterator will not be modified. Hence, it is best practice to initialize the iterator to NULL before calling nvs_entry_find() to avoid complicated error checking before releasing the iterator. Security, Tampering, and Robustness NVS is not directly compatible with the ESP32 flash encryption system. However, data can still be stored in encrypted form if NVS encryption is used together with ESP32 flash encryption. Please refer to NVS Encryption for more details. If NVS encryption is not used, it is possible for anyone with physical access to the flash chip to alter, erase, or add key-value pairs. With NVS encryption enabled, it is not possible to alter or add a key-value pair and get recognized as a valid pair without knowing corresponding NVS encryption keys. However, there is no tamper-resistance against the erase operation. The library does try to recover from conditions when flash memory is in an inconsistent state. In particular, one should be able to power off the device at any point and time and then power it back on. This should not result in loss of data, except for the new key-value pair if it was being written at the moment of powering off. The library should also be able to initialize properly with any random data present in flash memory. NVS Encryption Please refer to the NVS Encryption guide for more details. NVS Partition Generator Utility This utility helps generate NVS partition binary files which can be flashed separately on a dedicated partition via a flashing utility. Key-value pairs to be flashed onto the partition can be provided via a CSV file. For more details, please refer to NVS Partition Generator Utility. Instead of calling the nvs_partition_gen.py tool manually, the creation of the partition binary files can also be done directly from CMake using the function nvs_create_partition_image : nvs_create_partition_image(<partition> <csv> [FLASH_IN_PROJECT] [DEPENDS dep dep dep ...]) Positional Arguments: Parameter Description Name of the NVS parition Path to CSV file to parse Optional Arguments: Parameter Description Name of the NVS parition Specify files on which the command depends If FLASH_IN_PROJECT is not specified, the image will still be generated, but you will have to flash it manually using idf.py <partition>-flash (e.g., if your parition name is nvs , then use idf.py nvs-flash ). nvs_create_partition_image must be called from one of the component CMakeLists.txt files. Currently, only non-encrypted partitions are supported. Application Example You can find code examples in the storage directory of ESP-IDF examples: Demonstrates how to read a single integer value from, and write it to NVS. The value checked in this example holds the number of the ESP32 module restarts. The value's function as a counter is only possible due to its storing in NVS. The example also shows how to check if a read/write operation was successful, or if a certain value has not been initialized in NVS. The diagnostic procedure is provided in plain text to help you track the program flow and capture any issues on the way. Demonstrates how to read a single integer value and a blob (binary large object), and write them to NVS to preserve this value between ESP32 module restarts. value - tracks the number of the ESP32 module soft and hard restarts. blob - contains a table with module run times. The table is read from NVS to dynamically allocated RAM. A new run time is added to the table on each manually triggered soft restart, and then the added run time is written to NVS. Triggering is done by pulling down GPIO0. The example also shows how to implement the diagnostic procedure to check if the read/write operation was successful. This example does exactly the same as storage/nvs_rw_value, except that it uses the C++ NVS handle class. Internals Log of Key-Value Pairs NVS stores key-value pairs sequentially, with new key-value pairs being added at the end. When a value of any given key has to be updated, a new key-value pair is added at the end of the log and the old key-value pair is marked as erased. Pages and Entries NVS library uses two main entities in its operation: pages and entries. Page is a logical structure which stores a portion of the overall log. Logical page corresponds to one physical sector of flash memory. Pages which are in use have a sequence number associated with them. Sequence numbers impose an ordering on pages. Higher sequence numbers correspond to pages which were created later. Each page can be in one of the following states: Empty/uninitialized Flash storage for the page is empty (all bytes are 0xff ). Page is not used to store any data at this point and does not have a sequence number. Active Flash storage is initialized, page header has been written to flash, page has a valid sequence number. Page has some empty entries and data can be written there. No more than one page can be in this state at any given moment. Full Flash storage is in a consistent state and is filled with key-value pairs. Writing new key-value pairs into this page is not possible. It is still possible to mark some key-value pairs as erased. Erasing Non-erased key-value pairs are being moved into another page so that the current page can be erased. This is a transient state, i.e., page should never stay in this state at the time when any API call returns. In case of a sudden power off, the move-and-erase process will be completed upon the next power-on. Corrupted Page header contains invalid data, and further parsing of page data was canceled. Any items previously written into this page will not be accessible. The corresponding flash sector will not be erased immediately and will be kept along with sectors in uninitialized state for later use. This may be useful for debugging. Mapping from flash sectors to logical pages does not have any particular order. The library will inspect sequence numbers of pages found in each flash sector and organize pages in a list based on these numbers. +--------+ +--------+ +--------+ +--------+ | Page 1 | | Page 2 | | Page 3 | | Page 4 | | Full +---> | Full +---> | Active | | Empty | <- states | #11 | | #12 | | #14 | | | <- sequence numbers +---+----+ +----+---+ +----+---+ +---+----+ | | | | | | | | | | | | +---v------+ +-----v----+ +------v---+ +------v---+ | Sector 3 | | Sector 0 | | Sector 2 | | Sector 1 | <- physical sectors +----------+ +----------+ +----------+ +----------+ Structure of a Page For now, we assume that flash sector size is 4096 bytes and that ESP32 flash encryption hardware operates on 32-byte blocks. It is possible to introduce some settings configurable at compile-time (e.g., via menuconfig) to accommodate flash chips with different sector sizes (although it is not clear if other components in the system, e.g., SPI flash driver and SPI flash cache can support these other sizes). Page consists of three parts: header, entry state bitmap, and entries themselves. To be compatible with ESP32 flash encryption, the entry size is 32 bytes. For integer types, an entry holds one key-value pair. For strings and blobs, an entry holds part of key-value pair (more on that in the entry structure description). The following diagram illustrates the page structure. Numbers in parentheses indicate the size of each part in bytes. +-----------+--------------+-------------+-------------------------+ | State (4) | Seq. no. (4) | version (1) | Unused (19) | CRC32 (4) | Header (32) +-----------+--------------+-------------+-------------------------+ | Entry state bitmap (32) | +------------------------------------------------------------------+ | Entry 0 (32) | +------------------------------------------------------------------+ | Entry 1 (32) | +------------------------------------------------------------------+ / / / / +------------------------------------------------------------------+ | Entry 125 (32) | +------------------------------------------------------------------+ Page header and entry state bitmap are always written to flash unencrypted. Entries are encrypted if flash encryption feature of ESP32 is used. Page state values are defined in such a way that changing state is possible by writing 0 into some of the bits. Therefore it is not necessary to erase the page to change its state unless that is a change to the erased state. The version field in the header reflects the NVS format version used. For backward compatibility reasons, it is decremented for every version upgrade starting at 0xff (i.e., 0xff for version-1, 0xfe for version-2 and so on). CRC32 value in the header is calculated over the part which does not include a state value (bytes 4 to 28). The unused part is currently filled with 0xff bytes. The following sections describe the structure of entry state bitmap and entry itself. Entry and Entry State Bitmap Each entry can be in one of the following three states represented with two bits in the entry state bitmap. The final four bits in the bitmap (256 - 2 * 126) are not used. Empty (2'b11) Nothing is written into the specific entry yet. It is in an uninitialized state (all bytes are 0xff ). Written (2'b10) A key-value pair (or part of key-value pair which spans multiple entries) has been written into the entry. Erased (2'b00) A key-value pair in this entry has been discarded. Contents of this entry will not be parsed anymore. Structure of Entry For values of primitive types (currently integers from 1 to 8 bytes long), entry holds one key-value pair. For string and blob types, entry holds part of the whole key-value pair. For strings, in case when a key-value pair spans multiple entries, all entries are stored in the same page. Blobs are allowed to span over multiple pages by dividing them into smaller chunks. For tracking these chunks, an additional fixed length metadata entry is stored called "blob index". Earlier formats of blobs are still supported (can be read and modified). However, once the blobs are modified, they are stored using the new format. +--------+----------+----------+----------------+-----------+---------------+----------+ | NS (1) | Type (1) | Span (1) | ChunkIndex (1) | CRC32 (4) | Key (16) | Data (8) | +--------+----------+----------+----------------+-----------+---------------+----------+ Primitive +--------------------------------+ +--------> | Data (8) | | Types +--------------------------------+ +-> Fixed length -- | | +---------+--------------+---------------+-------+ | +--------> | Size(4) | ChunkCount(1)| ChunkStart(1) | Rsv(2)| Data format ---+ Blob Index +---------+--------------+---------------+-------+ | | +----------+---------+-----------+ +-> Variable length --> | Size (2) | Rsv (2) | CRC32 (4) | (Strings, Blob Data) +----------+---------+-----------+ Individual fields in entry structure have the following meanings: NS Namespace index for this entry. For more information on this value, see the section on namespaces implementation. Type One byte indicating the value data type. See the ItemType enumeration in nvs_flash/include/nvs_handle.hpp for possible values. Span Number of entries used by this key-value pair. For integer types, this is equal to 1. For strings and blobs, this depends on value length. ChunkIndex Used to store the index of a blob-data chunk for blob types. For other types, this should be 0xff . CRC32 Checksum calculated over all the bytes in this entry, except for the CRC32 field itself. Key Zero-terminated ASCII string containing a key name. Maximum string length is 15 bytes, excluding a zero terminator. Data For integer types, this field contains the value itself. If the value itself is shorter than 8 bytes, it is padded to the right, with unused bytes filled with 0xff . For "blob index" entry, these 8 bytes hold the following information about data-chunks: Size (Only for blob index.) Size, in bytes, of complete blob data. Size (Only for blob index.) Size, in bytes, of complete blob data. ChunkCount (Only for blob index.) Total number of blob-data chunks into which the blob was divided during storage. ChunkCount (Only for blob index.) Total number of blob-data chunks into which the blob was divided during storage. ChunkStart (Only for blob index.) ChunkIndex of the first blob-data chunk of this blob. Subsequent chunks have chunkIndex incrementally allocated (step of 1). ChunkStart (Only for blob index.) ChunkIndex of the first blob-data chunk of this blob. Subsequent chunks have chunkIndex incrementally allocated (step of 1). Size (Only for blob index.) Size, in bytes, of complete blob data. ChunkCount (Only for blob index.) Total number of blob-data chunks into which the blob was divided during storage. ChunkStart (Only for blob index.) ChunkIndex of the first blob-data chunk of this blob. Subsequent chunks have chunkIndex incrementally allocated (step of 1). For string and blob data chunks, these 8 bytes hold additional data about the value, which are described below: Size (Only for strings and blobs.) Size, in bytes, of actual data. For strings, this includes zero terminators. Size (Only for strings and blobs.) Size, in bytes, of actual data. For strings, this includes zero terminators. CRC32 (Only for strings and blobs.) Checksum calculated over all bytes of data. CRC32 (Only for strings and blobs.) Checksum calculated over all bytes of data. Size (Only for strings and blobs.) Size, in bytes, of actual data. For strings, this includes zero terminators. CRC32 (Only for strings and blobs.) Checksum calculated over all bytes of data. Size (Only for blob index.) Size, in bytes, of complete blob data. Variable length values (strings and blobs) are written into subsequent entries, 32 bytes per entry. The Span field of the first entry indicates how many entries are used. Namespaces As mentioned above, each key-value pair belongs to one of the namespaces. Namespace identifiers (strings) are stored as keys of key-value pairs in namespace with index 0. Values corresponding to these keys are indexes of these namespaces. +-------------------------------------------+ | NS=0 Type=uint8_t Key="wifi" Value=1 | Entry describing namespace "wifi" +-------------------------------------------+ | NS=1 Type=uint32_t Key="channel" Value=6 | Key "channel" in namespace "wifi" +-------------------------------------------+ | NS=0 Type=uint8_t Key="pwm" Value=2 | Entry describing namespace "pwm" +-------------------------------------------+ | NS=2 Type=uint16_t Key="channel" Value=20 | Key "channel" in namespace "pwm" +-------------------------------------------+ Item Hash List To reduce the number of reads from flash memory, each member of the Page class maintains a list of pairs: item index; item hash. This list makes searches much quicker. Instead of iterating over all entries, reading them from flash one at a time, Page::findItem first performs a search for the item hash in the hash list. This gives the item index within the page if such an item exists. Due to a hash collision, it is possible that a different item is found. This is handled by falling back to iteration over items in flash. Each node in the hash list contains a 24-bit hash and 8-bit item index. Hash is calculated based on item namespace, key name, and ChunkIndex. CRC32 is used for calculation; the result is truncated to 24 bits. To reduce the overhead for storing 32-bit entries in a linked list, the list is implemented as a double-linked list of arrays. Each array holds 29 entries, for the total size of 128 bytes, together with linked list pointers and a 32-bit count field. The minimum amount of extra RAM usage per page is therefore 128 bytes; maximum is 640 bytes. API Reference Header File This header file can be included with: #include "nvs_flash.h" This header file is a part of the API provided by the nvs_flash component. To declare that your component depends on nvs_flash , add the following to your CMakeLists.txt: REQUIRES nvs_flash or PRIV_REQUIRES nvs_flash Functions esp_err_t nvs_flash_init(void) Initialize the default NVS partition. This API initialises the default NVS partition. The default NVS partition is the one that is labeled "nvs" in the partition table. When "NVS_ENCRYPTION" is enabled in the menuconfig, this API enables the NVS encryption for the default NVS partition as follows Read security configurations from the first NVS key partition listed in the partition table. (NVS key partition is any "data" type partition which has the subtype value set to "nvs_keys") If the NVS key partiton obtained in the previous step is empty, generate and store new keys in that NVS key partiton. Internally call "nvs_flash_secure_init()" with the security configurations obtained/generated in the previous steps. Read security configurations from the first NVS key partition listed in the partition table. (NVS key partition is any "data" type partition which has the subtype value set to "nvs_keys") If the NVS key partiton obtained in the previous step is empty, generate and store new keys in that NVS key partiton. Internally call "nvs_flash_secure_init()" with the security configurations obtained/generated in the previous steps. Post initialization NVS read/write APIs remain the same irrespective of NVS encryption. Returns ESP_OK if storage was successfully initialized. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if no partition with label "nvs" is found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver error codes from nvs_flash_read_security_cfg API (when "NVS_ENCRYPTION" is enabled). error codes from nvs_flash_generate_keys API (when "NVS_ENCRYPTION" is enabled). error codes from nvs_flash_secure_init_partition API (when "NVS_ENCRYPTION" is enabled) . ESP_OK if storage was successfully initialized. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if no partition with label "nvs" is found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver error codes from nvs_flash_read_security_cfg API (when "NVS_ENCRYPTION" is enabled). error codes from nvs_flash_generate_keys API (when "NVS_ENCRYPTION" is enabled). error codes from nvs_flash_secure_init_partition API (when "NVS_ENCRYPTION" is enabled) . ESP_OK if storage was successfully initialized. Returns ESP_OK if storage was successfully initialized. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if no partition with label "nvs" is found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver error codes from nvs_flash_read_security_cfg API (when "NVS_ENCRYPTION" is enabled). error codes from nvs_flash_generate_keys API (when "NVS_ENCRYPTION" is enabled). error codes from nvs_flash_secure_init_partition API (when "NVS_ENCRYPTION" is enabled) . Read security configurations from the first NVS key partition listed in the partition table. (NVS key partition is any "data" type partition which has the subtype value set to "nvs_keys") esp_err_t nvs_flash_init_partition(const char *partition_label) Initialize NVS flash storage for the specified partition. Parameters partition_label -- [in] Label of the partition. Must be no longer than 16 characters. Returns ESP_OK if storage was successfully initialized. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if specified partition is not found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver ESP_OK if storage was successfully initialized. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if specified partition is not found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver ESP_OK if storage was successfully initialized. Parameters partition_label -- [in] Label of the partition. Must be no longer than 16 characters. Returns ESP_OK if storage was successfully initialized. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if specified partition is not found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver esp_err_t nvs_flash_init_partition_ptr(const esp_partition_t *partition) Initialize NVS flash storage for the partition specified by partition pointer. Parameters partition -- [in] pointer to a partition obtained by the ESP partition API. Returns ESP_OK if storage was successfully initialized ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_INVALID_ARG in case partition is NULL ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver ESP_OK if storage was successfully initialized ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_INVALID_ARG in case partition is NULL ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver ESP_OK if storage was successfully initialized Parameters partition -- [in] pointer to a partition obtained by the ESP partition API. Returns ESP_OK if storage was successfully initialized ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_INVALID_ARG in case partition is NULL ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver esp_err_t nvs_flash_deinit(void) Deinitialize NVS storage for the default NVS partition. Default NVS partition is the partition with "nvs" label in the partition table. Returns ESP_OK on success (storage was deinitialized) ESP_ERR_NVS_NOT_INITIALIZED if the storage was not initialized prior to this call ESP_OK on success (storage was deinitialized) ESP_ERR_NVS_NOT_INITIALIZED if the storage was not initialized prior to this call ESP_OK on success (storage was deinitialized) Returns ESP_OK on success (storage was deinitialized) ESP_ERR_NVS_NOT_INITIALIZED if the storage was not initialized prior to this call esp_err_t nvs_flash_deinit_partition(const char *partition_label) Deinitialize NVS storage for the given NVS partition. Parameters partition_label -- [in] Label of the partition Returns ESP_OK on success ESP_ERR_NVS_NOT_INITIALIZED if the storage for given partition was not initialized prior to this call ESP_OK on success ESP_ERR_NVS_NOT_INITIALIZED if the storage for given partition was not initialized prior to this call ESP_OK on success Parameters partition_label -- [in] Label of the partition Returns ESP_OK on success ESP_ERR_NVS_NOT_INITIALIZED if the storage for given partition was not initialized prior to this call esp_err_t nvs_flash_erase(void) Erase the default NVS partition. Erases all contents of the default NVS partition (one with label "nvs"). Note If the partition is initialized, this function first de-initializes it. Afterwards, the partition has to be initialized again to be used. Returns ESP_OK on success ESP_ERR_NOT_FOUND if there is no NVS partition labeled "nvs" in the partition table different error in case de-initialization fails (shouldn't happen) ESP_OK on success ESP_ERR_NOT_FOUND if there is no NVS partition labeled "nvs" in the partition table different error in case de-initialization fails (shouldn't happen) ESP_OK on success Returns ESP_OK on success ESP_ERR_NOT_FOUND if there is no NVS partition labeled "nvs" in the partition table different error in case de-initialization fails (shouldn't happen) esp_err_t nvs_flash_erase_partition(const char *part_name) Erase specified NVS partition. Erase all content of a specified NVS partition Note If the partition is initialized, this function first de-initializes it. Afterwards, the partition has to be initialized again to be used. Parameters part_name -- [in] Name (label) of the partition which should be erased Returns ESP_OK on success ESP_ERR_NOT_FOUND if there is no NVS partition with the specified name in the partition table different error in case de-initialization fails (shouldn't happen) ESP_OK on success ESP_ERR_NOT_FOUND if there is no NVS partition with the specified name in the partition table different error in case de-initialization fails (shouldn't happen) ESP_OK on success Parameters part_name -- [in] Name (label) of the partition which should be erased Returns ESP_OK on success ESP_ERR_NOT_FOUND if there is no NVS partition with the specified name in the partition table different error in case de-initialization fails (shouldn't happen) esp_err_t nvs_flash_erase_partition_ptr(const esp_partition_t *partition) Erase custom partition. Erase all content of specified custom partition. Note If the partition is initialized, this function first de-initializes it. Afterwards, the partition has to be initialized again to be used. Parameters partition -- [in] pointer to a partition obtained by the ESP partition API. Returns ESP_OK on success ESP_ERR_NOT_FOUND if there is no partition with the specified parameters in the partition table ESP_ERR_INVALID_ARG in case partition is NULL one of the error codes from the underlying flash storage driver ESP_OK on success ESP_ERR_NOT_FOUND if there is no partition with the specified parameters in the partition table ESP_ERR_INVALID_ARG in case partition is NULL one of the error codes from the underlying flash storage driver ESP_OK on success Parameters partition -- [in] pointer to a partition obtained by the ESP partition API. Returns ESP_OK on success ESP_ERR_NOT_FOUND if there is no partition with the specified parameters in the partition table ESP_ERR_INVALID_ARG in case partition is NULL one of the error codes from the underlying flash storage driver esp_err_t nvs_flash_secure_init(nvs_sec_cfg_t *cfg) Initialize the default NVS partition. This API initialises the default NVS partition. The default NVS partition is the one that is labeled "nvs" in the partition table. Parameters cfg -- [in] Security configuration (keys) to be used for NVS encryption/decryption. If cfg is NULL, no encryption is used. Returns ESP_OK if storage has been initialized successfully. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if no partition with label "nvs" is found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver ESP_OK if storage has been initialized successfully. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if no partition with label "nvs" is found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver ESP_OK if storage has been initialized successfully. Parameters cfg -- [in] Security configuration (keys) to be used for NVS encryption/decryption. If cfg is NULL, no encryption is used. Returns ESP_OK if storage has been initialized successfully. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if no partition with label "nvs" is found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver esp_err_t nvs_flash_secure_init_partition(const char *partition_label, nvs_sec_cfg_t *cfg) Initialize NVS flash storage for the specified partition. Parameters partition_label -- [in] Label of the partition. Note that internally, a reference to passed value is kept and it should be accessible for future operations cfg -- [in] Security configuration (keys) to be used for NVS encryption/decryption. If cfg is null, no encryption/decryption is used. partition_label -- [in] Label of the partition. Note that internally, a reference to passed value is kept and it should be accessible for future operations cfg -- [in] Security configuration (keys) to be used for NVS encryption/decryption. If cfg is null, no encryption/decryption is used. partition_label -- [in] Label of the partition. Note that internally, a reference to passed value is kept and it should be accessible for future operations Returns ESP_OK if storage has been initialized successfully. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if specified partition is not found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver ESP_OK if storage has been initialized successfully. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if specified partition is not found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver ESP_OK if storage has been initialized successfully. Parameters partition_label -- [in] Label of the partition. Note that internally, a reference to passed value is kept and it should be accessible for future operations cfg -- [in] Security configuration (keys) to be used for NVS encryption/decryption. If cfg is null, no encryption/decryption is used. Returns ESP_OK if storage has been initialized successfully. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if specified partition is not found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver esp_err_t nvs_flash_generate_keys(const esp_partition_t *partition, nvs_sec_cfg_t *cfg) Generate and store NVS keys in the provided esp partition. Parameters partition -- [in] Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. cfg -- [out] Pointer to nvs security configuration structure. Pointer must be non-NULL. Generated keys will be populated in this structure. partition -- [in] Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. cfg -- [out] Pointer to nvs security configuration structure. Pointer must be non-NULL. Generated keys will be populated in this structure. partition -- [in] Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. Returns ESP_OK, if cfg was read successfully; ESP_ERR_INVALID_ARG, if partition or cfg is NULL; or error codes from esp_partition_write/erase APIs. ESP_OK, if cfg was read successfully; ESP_ERR_INVALID_ARG, if partition or cfg is NULL; or error codes from esp_partition_write/erase APIs. ESP_OK, if cfg was read successfully; Parameters partition -- [in] Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. cfg -- [out] Pointer to nvs security configuration structure. Pointer must be non-NULL. Generated keys will be populated in this structure. Returns ESP_OK, if cfg was read successfully; ESP_ERR_INVALID_ARG, if partition or cfg is NULL; or error codes from esp_partition_write/erase APIs. esp_err_t nvs_flash_read_security_cfg(const esp_partition_t *partition, nvs_sec_cfg_t *cfg) Read NVS security configuration from a partition. Note Provided partition is assumed to be marked 'encrypted'. Parameters partition -- [in] Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. cfg -- [out] Pointer to nvs security configuration structure. Pointer must be non-NULL. partition -- [in] Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. cfg -- [out] Pointer to nvs security configuration structure. Pointer must be non-NULL. partition -- [in] Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. Returns ESP_OK, if cfg was read successfully; ESP_ERR_INVALID_ARG, if partition or cfg is NULL ESP_ERR_NVS_KEYS_NOT_INITIALIZED, if the partition is not yet written with keys. ESP_ERR_NVS_CORRUPT_KEY_PART, if the partition containing keys is found to be corrupt or error codes from esp_partition_read API. ESP_OK, if cfg was read successfully; ESP_ERR_INVALID_ARG, if partition or cfg is NULL ESP_ERR_NVS_KEYS_NOT_INITIALIZED, if the partition is not yet written with keys. ESP_ERR_NVS_CORRUPT_KEY_PART, if the partition containing keys is found to be corrupt or error codes from esp_partition_read API. ESP_OK, if cfg was read successfully; Parameters partition -- [in] Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. cfg -- [out] Pointer to nvs security configuration structure. Pointer must be non-NULL. Returns ESP_OK, if cfg was read successfully; ESP_ERR_INVALID_ARG, if partition or cfg is NULL ESP_ERR_NVS_KEYS_NOT_INITIALIZED, if the partition is not yet written with keys. ESP_ERR_NVS_CORRUPT_KEY_PART, if the partition containing keys is found to be corrupt or error codes from esp_partition_read API. esp_err_t nvs_flash_register_security_scheme(nvs_sec_scheme_t *scheme_cfg) Registers the given security scheme for NVS encryption The scheme registered with sec_scheme_id by this API be used as the default security scheme for the "nvs" partition. Users will have to call this API explicitly in their application. Parameters scheme_cfg -- [in] Pointer to the security scheme configuration structure that the user (or the nvs_key_provider) wants to register. Returns ESP_OK, if security scheme registration succeeds; ESP_ERR_INVALID_ARG, if scheme_cfg is NULL; ESP_FAIL, if security scheme registration fails ESP_OK, if security scheme registration succeeds; ESP_ERR_INVALID_ARG, if scheme_cfg is NULL; ESP_FAIL, if security scheme registration fails ESP_OK, if security scheme registration succeeds; Parameters scheme_cfg -- [in] Pointer to the security scheme configuration structure that the user (or the nvs_key_provider) wants to register. Returns ESP_OK, if security scheme registration succeeds; ESP_ERR_INVALID_ARG, if scheme_cfg is NULL; ESP_FAIL, if security scheme registration fails nvs_sec_scheme_t *nvs_flash_get_default_security_scheme(void) Fetch the configuration structure for the default active security scheme for NVS encryption. Returns Pointer to the default active security scheme configuration (NULL if no scheme is registered yet i.e. active) Returns Pointer to the default active security scheme configuration (NULL if no scheme is registered yet i.e. active) esp_err_t nvs_flash_generate_keys_v2(nvs_sec_scheme_t *scheme_cfg, nvs_sec_cfg_t *cfg) Generate (and store) the NVS keys using the specified key-protection scheme. Parameters scheme_cfg -- [in] Security scheme specific configuration cfg -- [out] Security configuration (encryption keys) scheme_cfg -- [in] Security scheme specific configuration cfg -- [out] Security configuration (encryption keys) scheme_cfg -- [in] Security scheme specific configuration Returns ESP_OK, if cfg was populated successfully with generated encryption keys; ESP_ERR_INVALID_ARG, if scheme_cfg or cfg is NULL; ESP_FAIL, if the key generation process fails ESP_OK, if cfg was populated successfully with generated encryption keys; ESP_ERR_INVALID_ARG, if scheme_cfg or cfg is NULL; ESP_FAIL, if the key generation process fails ESP_OK, if cfg was populated successfully with generated encryption keys; Parameters scheme_cfg -- [in] Security scheme specific configuration cfg -- [out] Security configuration (encryption keys) Returns ESP_OK, if cfg was populated successfully with generated encryption keys; ESP_ERR_INVALID_ARG, if scheme_cfg or cfg is NULL; ESP_FAIL, if the key generation process fails esp_err_t nvs_flash_read_security_cfg_v2(nvs_sec_scheme_t *scheme_cfg, nvs_sec_cfg_t *cfg) Read NVS security configuration set by the specified security scheme. Parameters scheme_cfg -- [in] Security scheme specific configuration cfg -- [out] Security configuration (encryption keys) scheme_cfg -- [in] Security scheme specific configuration cfg -- [out] Security configuration (encryption keys) scheme_cfg -- [in] Security scheme specific configuration Returns ESP_OK, if cfg was read successfully; ESP_ERR_INVALID_ARG, if scheme_cfg or cfg is NULL; ESP_FAIL, if the key reading process fails ESP_OK, if cfg was read successfully; ESP_ERR_INVALID_ARG, if scheme_cfg or cfg is NULL; ESP_FAIL, if the key reading process fails ESP_OK, if cfg was read successfully; Parameters scheme_cfg -- [in] Security scheme specific configuration cfg -- [out] Security configuration (encryption keys) Returns ESP_OK, if cfg was read successfully; ESP_ERR_INVALID_ARG, if scheme_cfg or cfg is NULL; ESP_FAIL, if the key reading process fails Structures struct nvs_sec_cfg_t Key for encryption and decryption. struct nvs_sec_scheme_t NVS encryption: Security scheme configuration structure. Public Members int scheme_id Security Scheme ID (E.g. HMAC) int scheme_id Security Scheme ID (E.g. HMAC) void *scheme_data Scheme-specific data (E.g. eFuse block for HMAC-based key generation) void *scheme_data Scheme-specific data (E.g. eFuse block for HMAC-based key generation) nvs_flash_generate_keys_t nvs_flash_key_gen Callback for the nvs_flash_key_gen implementation nvs_flash_generate_keys_t nvs_flash_key_gen Callback for the nvs_flash_key_gen implementation nvs_flash_read_cfg_t nvs_flash_read_cfg Callback for the nvs_flash_read_keys implementation nvs_flash_read_cfg_t nvs_flash_read_cfg Callback for the nvs_flash_read_keys implementation int scheme_id Macros NVS_KEY_SIZE Type Definitions typedef esp_err_t (*nvs_flash_generate_keys_t)(const void *scheme_data, nvs_sec_cfg_t *cfg) Callback function prototype for generating the NVS encryption keys. typedef esp_err_t (*nvs_flash_read_cfg_t)(const void *scheme_data, nvs_sec_cfg_t *cfg) Callback function prototype for reading the NVS encryption keys. Header File This header file can be included with: #include "nvs.h" This header file is a part of the API provided by the nvs_flash component. To declare that your component depends on nvs_flash , add the following to your CMakeLists.txt: REQUIRES nvs_flash or PRIV_REQUIRES nvs_flash Functions esp_err_t nvs_set_i8(nvs_handle_t handle, const char *key, int8_t value) set int8_t value for given key Set value for the key, given its name. Note that the actual storage will not be updated until nvs_commit is called. Regardless whether key-value pair is created or updated, function always requires at least one nvs available entry. See nvs_get_stats . After create type of operation, the number of available entries is decreased by one. After update type of operation, the number of available entries remains the same. Parameters handle -- [in] Handle obtained from nvs_open function. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. value -- [in] The value to set. handle -- [in] Handle obtained from nvs_open function. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. value -- [in] The value to set. handle -- [in] Handle obtained from nvs_open function. Handles that were opened read only cannot be used. Returns ESP_OK if value was set successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the underlying storage to save the value ESP_ERR_NVS_REMOVE_FAILED if the value wasn't updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn't fail again. ESP_OK if value was set successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the underlying storage to save the value ESP_ERR_NVS_REMOVE_FAILED if the value wasn't updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn't fail again. ESP_OK if value was set successfully Parameters handle -- [in] Handle obtained from nvs_open function. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. value -- [in] The value to set. Returns ESP_OK if value was set successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the underlying storage to save the value ESP_ERR_NVS_REMOVE_FAILED if the value wasn't updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn't fail again. esp_err_t nvs_set_u8(nvs_handle_t handle, const char *key, uint8_t value) set uint8_t value for given key This function is the same as nvs_set_i8 except for the data type. esp_err_t nvs_set_i16(nvs_handle_t handle, const char *key, int16_t value) set int16_t value for given key This function is the same as nvs_set_i8 except for the data type. esp_err_t nvs_set_u16(nvs_handle_t handle, const char *key, uint16_t value) set uint16_t value for given key This function is the same as nvs_set_i8 except for the data type. esp_err_t nvs_set_i32(nvs_handle_t handle, const char *key, int32_t value) set int32_t value for given key This function is the same as nvs_set_i8 except for the data type. esp_err_t nvs_set_u32(nvs_handle_t handle, const char *key, uint32_t value) set uint32_t value for given key This function is the same as nvs_set_i8 except for the data type. esp_err_t nvs_set_i64(nvs_handle_t handle, const char *key, int64_t value) set int64_t value for given key This function is the same as nvs_set_i8 except for the data type. esp_err_t nvs_set_u64(nvs_handle_t handle, const char *key, uint64_t value) set uint64_t value for given key This function is the same as nvs_set_i8 except for the data type. esp_err_t nvs_set_str(nvs_handle_t handle, const char *key, const char *value) set string for given key Sets string value for the key. Function requires whole space for new data to be available as contiguous entries in same nvs page. Operation consumes 1 overhead entry and 1 entry per each 32 characters of new string including zero character to be set. In case of value update for existing key, entries occupied by the previous value and overhead entry are returned to the pool of available entries. Note that storage of long string values can fail due to fragmentation of nvs pages even if available_entries returned by nvs_get_stats suggests enough overall space available. Note that the underlying storage will not be updated until nvs_commit is called. Parameters handle -- [in] Handle obtained from nvs_open function. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. value -- [in] The value to set. For strings, the maximum length (including null character) is 4000 bytes, if there is one complete page free for writing. This decreases, however, if the free space is fragmented. handle -- [in] Handle obtained from nvs_open function. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. value -- [in] The value to set. For strings, the maximum length (including null character) is 4000 bytes, if there is one complete page free for writing. This decreases, however, if the free space is fragmented. handle -- [in] Handle obtained from nvs_open function. Handles that were opened read only cannot be used. Returns ESP_OK if value was set successfully ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the underlying storage to save the value ESP_ERR_NVS_REMOVE_FAILED if the value wasn't updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn't fail again. ESP_ERR_NVS_VALUE_TOO_LONG if the string value is too long ESP_OK if value was set successfully ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the underlying storage to save the value ESP_ERR_NVS_REMOVE_FAILED if the value wasn't updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn't fail again. ESP_ERR_NVS_VALUE_TOO_LONG if the string value is too long ESP_OK if value was set successfully Parameters handle -- [in] Handle obtained from nvs_open function. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. value -- [in] The value to set. For strings, the maximum length (including null character) is 4000 bytes, if there is one complete page free for writing. This decreases, however, if the free space is fragmented. Returns ESP_OK if value was set successfully ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the underlying storage to save the value ESP_ERR_NVS_REMOVE_FAILED if the value wasn't updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn't fail again. ESP_ERR_NVS_VALUE_TOO_LONG if the string value is too long esp_err_t nvs_get_i8(nvs_handle_t handle, const char *key, int8_t *out_value) get int8_t value for given key These functions retrieve value for the key, given its name. If key does not exist, or the requested variable type doesn't match the type which was used when setting a value, an error is returned. In case of any error, out_value is not modified. out_value has to be a pointer to an already allocated variable of the given type. // Example of using nvs_get_i32: int32_t max_buffer_size = 4096; // default value esp_err_t err = nvs_get_i32(my_handle, "max_buffer_size", &max_buffer_size); assert(err == ESP_OK || err == ESP_ERR_NVS_NOT_FOUND); // if ESP_ERR_NVS_NOT_FOUND was returned, max_buffer_size will still // have its default value. Parameters handle -- [in] Handle obtained from nvs_open function. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. out_value -- Pointer to the output value. May be NULL for nvs_get_str and nvs_get_blob, in this case required length will be returned in length argument. handle -- [in] Handle obtained from nvs_open function. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. out_value -- Pointer to the output value. May be NULL for nvs_get_str and nvs_get_blob, in this case required length will be returned in length argument. handle -- [in] Handle obtained from nvs_open function. Returns ESP_OK if the value was retrieved successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_INVALID_LENGTH if length is not sufficient to store data ESP_OK if the value was retrieved successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_INVALID_LENGTH if length is not sufficient to store data ESP_OK if the value was retrieved successfully Parameters handle -- [in] Handle obtained from nvs_open function. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. out_value -- Pointer to the output value. May be NULL for nvs_get_str and nvs_get_blob, in this case required length will be returned in length argument. Returns ESP_OK if the value was retrieved successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_INVALID_LENGTH if length is not sufficient to store data esp_err_t nvs_get_u8(nvs_handle_t handle, const char *key, uint8_t *out_value) get uint8_t value for given key This function is the same as nvs_get_i8 except for the data type. esp_err_t nvs_get_i16(nvs_handle_t handle, const char *key, int16_t *out_value) get int16_t value for given key This function is the same as nvs_get_i8 except for the data type. esp_err_t nvs_get_u16(nvs_handle_t handle, const char *key, uint16_t *out_value) get uint16_t value for given key This function is the same as nvs_get_i8 except for the data type. esp_err_t nvs_get_i32(nvs_handle_t handle, const char *key, int32_t *out_value) get int32_t value for given key This function is the same as nvs_get_i8 except for the data type. esp_err_t nvs_get_u32(nvs_handle_t handle, const char *key, uint32_t *out_value) get uint32_t value for given key This function is the same as nvs_get_i8 except for the data type. esp_err_t nvs_get_i64(nvs_handle_t handle, const char *key, int64_t *out_value) get int64_t value for given key This function is the same as nvs_get_i8 except for the data type. esp_err_t nvs_get_u64(nvs_handle_t handle, const char *key, uint64_t *out_value) get uint64_t value for given key This function is the same as nvs_get_i8 except for the data type. esp_err_t nvs_get_str(nvs_handle_t handle, const char *key, char *out_value, size_t *length) get string value for given key These functions retrieve the data of an entry, given its key. If key does not exist, or the requested variable type doesn't match the type which was used when setting a value, an error is returned. In case of any error, out_value is not modified. All functions expect out_value to be a pointer to an already allocated variable of the given type. nvs_get_str and nvs_get_blob functions support WinAPI-style length queries. To get the size necessary to store the value, call nvs_get_str or nvs_get_blob with zero out_value and non-zero pointer to length. Variable pointed to by length argument will be set to the required length. For nvs_get_str, this length includes the zero terminator. When calling nvs_get_str and nvs_get_blob with non-zero out_value, length has to be non-zero and has to point to the length available in out_value. It is suggested that nvs_get/set_str is used for zero-terminated C strings, and nvs_get/set_blob used for arbitrary data structures. // Example (without error checking) of using nvs_get_str to get a string into dynamic array: size_t required_size; nvs_get_str(my_handle, "server_name", NULL, &required_size); char* server_name = malloc(required_size); nvs_get_str(my_handle, "server_name", server_name, &required_size); // Example (without error checking) of using nvs_get_blob to get a binary data into a static array: uint8_t mac_addr[6]; size_t size = sizeof(mac_addr); nvs_get_blob(my_handle, "dst_mac_addr", mac_addr, &size); Parameters handle -- [in] Handle obtained from nvs_open function. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. out_value -- [out] Pointer to the output value. May be NULL for nvs_get_str and nvs_get_blob, in this case required length will be returned in length argument. length -- [inout] A non-zero pointer to the variable holding the length of out_value. In case out_value a zero, will be set to the length required to hold the value. In case out_value is not zero, will be set to the actual length of the value written. For nvs_get_str this includes zero terminator. handle -- [in] Handle obtained from nvs_open function. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. out_value -- [out] Pointer to the output value. May be NULL for nvs_get_str and nvs_get_blob, in this case required length will be returned in length argument. length -- [inout] A non-zero pointer to the variable holding the length of out_value. In case out_value a zero, will be set to the length required to hold the value. In case out_value is not zero, will be set to the actual length of the value written. For nvs_get_str this includes zero terminator. handle -- [in] Handle obtained from nvs_open function. Returns ESP_OK if the value was retrieved successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_INVALID_LENGTH if length is not sufficient to store data ESP_OK if the value was retrieved successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_INVALID_LENGTH if length is not sufficient to store data ESP_OK if the value was retrieved successfully Parameters handle -- [in] Handle obtained from nvs_open function. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. out_value -- [out] Pointer to the output value. May be NULL for nvs_get_str and nvs_get_blob, in this case required length will be returned in length argument. length -- [inout] A non-zero pointer to the variable holding the length of out_value. In case out_value a zero, will be set to the length required to hold the value. In case out_value is not zero, will be set to the actual length of the value written. For nvs_get_str this includes zero terminator. Returns ESP_OK if the value was retrieved successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_INVALID_LENGTH if length is not sufficient to store data esp_err_t nvs_get_blob(nvs_handle_t handle, const char *key, void *out_value, size_t *length) get blob value for given key This function behaves the same as nvs_get_str , except for the data type. esp_err_t nvs_open(const char *namespace_name, nvs_open_mode_t open_mode, nvs_handle_t *out_handle) Open non-volatile storage with a given namespace from the default NVS partition. Multiple internal ESP-IDF and third party application modules can store their key-value pairs in the NVS module. In order to reduce possible conflicts on key names, each module can use its own namespace. The default NVS partition is the one that is labelled "nvs" in the partition table. Parameters namespace_name -- [in] Namespace name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. open_mode -- [in] NVS_READWRITE or NVS_READONLY. If NVS_READONLY, will open a handle for reading only. All write requests will be rejected for this handle. out_handle -- [out] If successful (return code is zero), handle will be returned in this argument. namespace_name -- [in] Namespace name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. open_mode -- [in] NVS_READWRITE or NVS_READONLY. If NVS_READONLY, will open a handle for reading only. All write requests will be rejected for this handle. out_handle -- [out] If successful (return code is zero), handle will be returned in this argument. namespace_name -- [in] Namespace name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. Returns ESP_OK if storage handle was opened successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized ESP_ERR_NVS_PART_NOT_FOUND if the partition with label "nvs" is not found ESP_ERR_NVS_NOT_FOUND id namespace doesn't exist yet and mode is NVS_READONLY ESP_ERR_NVS_INVALID_NAME if namespace name doesn't satisfy constraints ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is no space for a new entry or there are too many different namespaces (maximum allowed different namespaces: 254) ESP_ERR_NOT_ALLOWED if the NVS partition is read-only and mode is NVS_READWRITE ESP_ERR_INVALID_ARG if out_handle is equal to NULL other error codes from the underlying storage driver ESP_OK if storage handle was opened successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized ESP_ERR_NVS_PART_NOT_FOUND if the partition with label "nvs" is not found ESP_ERR_NVS_NOT_FOUND id namespace doesn't exist yet and mode is NVS_READONLY ESP_ERR_NVS_INVALID_NAME if namespace name doesn't satisfy constraints ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is no space for a new entry or there are too many different namespaces (maximum allowed different namespaces: 254) ESP_ERR_NOT_ALLOWED if the NVS partition is read-only and mode is NVS_READWRITE ESP_ERR_INVALID_ARG if out_handle is equal to NULL other error codes from the underlying storage driver ESP_OK if storage handle was opened successfully Parameters namespace_name -- [in] Namespace name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. open_mode -- [in] NVS_READWRITE or NVS_READONLY. If NVS_READONLY, will open a handle for reading only. All write requests will be rejected for this handle. out_handle -- [out] If successful (return code is zero), handle will be returned in this argument. Returns ESP_OK if storage handle was opened successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized ESP_ERR_NVS_PART_NOT_FOUND if the partition with label "nvs" is not found ESP_ERR_NVS_NOT_FOUND id namespace doesn't exist yet and mode is NVS_READONLY ESP_ERR_NVS_INVALID_NAME if namespace name doesn't satisfy constraints ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is no space for a new entry or there are too many different namespaces (maximum allowed different namespaces: 254) ESP_ERR_NOT_ALLOWED if the NVS partition is read-only and mode is NVS_READWRITE ESP_ERR_INVALID_ARG if out_handle is equal to NULL other error codes from the underlying storage driver esp_err_t nvs_open_from_partition(const char *part_name, const char *namespace_name, nvs_open_mode_t open_mode, nvs_handle_t *out_handle) Open non-volatile storage with a given namespace from specified partition. The behaviour is same as nvs_open() API. However this API can operate on a specified NVS partition instead of default NVS partition. Note that the specified partition must be registered with NVS using nvs_flash_init_partition() API. Parameters part_name -- [in] Label (name) of the partition of interest for object read/write/erase namespace_name -- [in] Namespace name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. open_mode -- [in] NVS_READWRITE or NVS_READONLY. If NVS_READONLY, will open a handle for reading only. All write requests will be rejected for this handle. out_handle -- [out] If successful (return code is zero), handle will be returned in this argument. part_name -- [in] Label (name) of the partition of interest for object read/write/erase namespace_name -- [in] Namespace name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. open_mode -- [in] NVS_READWRITE or NVS_READONLY. If NVS_READONLY, will open a handle for reading only. All write requests will be rejected for this handle. out_handle -- [out] If successful (return code is zero), handle will be returned in this argument. part_name -- [in] Label (name) of the partition of interest for object read/write/erase Returns ESP_OK if storage handle was opened successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized ESP_ERR_NVS_PART_NOT_FOUND if the partition with specified name is not found ESP_ERR_NVS_NOT_FOUND id namespace doesn't exist yet and mode is NVS_READONLY ESP_ERR_NVS_INVALID_NAME if namespace name doesn't satisfy constraints ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is no space for a new entry or there are too many different namespaces (maximum allowed different namespaces: 254) ESP_ERR_NOT_ALLOWED if the NVS partition is read-only and mode is NVS_READWRITE ESP_ERR_INVALID_ARG if out_handle is equal to NULL other error codes from the underlying storage driver ESP_OK if storage handle was opened successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized ESP_ERR_NVS_PART_NOT_FOUND if the partition with specified name is not found ESP_ERR_NVS_NOT_FOUND id namespace doesn't exist yet and mode is NVS_READONLY ESP_ERR_NVS_INVALID_NAME if namespace name doesn't satisfy constraints ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is no space for a new entry or there are too many different namespaces (maximum allowed different namespaces: 254) ESP_ERR_NOT_ALLOWED if the NVS partition is read-only and mode is NVS_READWRITE ESP_ERR_INVALID_ARG if out_handle is equal to NULL other error codes from the underlying storage driver ESP_OK if storage handle was opened successfully Parameters part_name -- [in] Label (name) of the partition of interest for object read/write/erase namespace_name -- [in] Namespace name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. open_mode -- [in] NVS_READWRITE or NVS_READONLY. If NVS_READONLY, will open a handle for reading only. All write requests will be rejected for this handle. out_handle -- [out] If successful (return code is zero), handle will be returned in this argument. Returns ESP_OK if storage handle was opened successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized ESP_ERR_NVS_PART_NOT_FOUND if the partition with specified name is not found ESP_ERR_NVS_NOT_FOUND id namespace doesn't exist yet and mode is NVS_READONLY ESP_ERR_NVS_INVALID_NAME if namespace name doesn't satisfy constraints ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is no space for a new entry or there are too many different namespaces (maximum allowed different namespaces: 254) ESP_ERR_NOT_ALLOWED if the NVS partition is read-only and mode is NVS_READWRITE ESP_ERR_INVALID_ARG if out_handle is equal to NULL other error codes from the underlying storage driver esp_err_t nvs_set_blob(nvs_handle_t handle, const char *key, const void *value, size_t length) set variable length binary value for given key Sets variable length binary value for the key. Function uses 2 overhead and 1 entry per each 32 bytes of new data from the pool of available entries. See nvs_get_stats . In case of value update for existing key, space occupied by the existing value and 2 overhead entries are returned to the pool of available entries. Note that the underlying storage will not be updated until nvs_commit is called. Parameters handle -- [in] Handle obtained from nvs_open function. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. value -- [in] The value to set. length -- [in] length of binary value to set, in bytes; Maximum length is 508000 bytes or (97.6% of the partition size - 4000) bytes whichever is lower. handle -- [in] Handle obtained from nvs_open function. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. value -- [in] The value to set. length -- [in] length of binary value to set, in bytes; Maximum length is 508000 bytes or (97.6% of the partition size - 4000) bytes whichever is lower. handle -- [in] Handle obtained from nvs_open function. Handles that were opened read only cannot be used. Returns ESP_OK if value was set successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the underlying storage to save the value ESP_ERR_NVS_REMOVE_FAILED if the value wasn't updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn't fail again. ESP_ERR_NVS_VALUE_TOO_LONG if the value is too long ESP_OK if value was set successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the underlying storage to save the value ESP_ERR_NVS_REMOVE_FAILED if the value wasn't updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn't fail again. ESP_ERR_NVS_VALUE_TOO_LONG if the value is too long ESP_OK if value was set successfully Parameters handle -- [in] Handle obtained from nvs_open function. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. value -- [in] The value to set. length -- [in] length of binary value to set, in bytes; Maximum length is 508000 bytes or (97.6% of the partition size - 4000) bytes whichever is lower. Returns ESP_OK if value was set successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the underlying storage to save the value ESP_ERR_NVS_REMOVE_FAILED if the value wasn't updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn't fail again. ESP_ERR_NVS_VALUE_TOO_LONG if the value is too long esp_err_t nvs_find_key(nvs_handle_t handle, const char *key, nvs_type_t *out_type) Lookup key-value pair with given key name. Note that function may indicate both existence of the key as well as the data type of NVS entry if it is found. Parameters handle -- [in] Storage handle obtained with nvs_open. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. out_type -- [out] Pointer to the output variable populated with data type of NVS entry in case key was found. May be NULL, respective data type is then not provided. handle -- [in] Storage handle obtained with nvs_open. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. out_type -- [out] Pointer to the output variable populated with data type of NVS entry in case key was found. May be NULL, respective data type is then not provided. handle -- [in] Storage handle obtained with nvs_open. Returns ESP_OK if NVS entry for key provided was found ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) other error codes from the underlying storage driver ESP_OK if NVS entry for key provided was found ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) other error codes from the underlying storage driver ESP_OK if NVS entry for key provided was found Parameters handle -- [in] Storage handle obtained with nvs_open. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. out_type -- [out] Pointer to the output variable populated with data type of NVS entry in case key was found. May be NULL, respective data type is then not provided. Returns ESP_OK if NVS entry for key provided was found ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) other error codes from the underlying storage driver esp_err_t nvs_erase_key(nvs_handle_t handle, const char *key) Erase key-value pair with given key name. Note that actual storage may not be updated until nvs_commit function is called. Parameters handle -- [in] Storage handle obtained with nvs_open. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. handle -- [in] Storage handle obtained with nvs_open. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. handle -- [in] Storage handle obtained with nvs_open. Handles that were opened read only cannot be used. Returns ESP_OK if erase operation was successful ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if handle was opened as read only ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist other error codes from the underlying storage driver ESP_OK if erase operation was successful ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if handle was opened as read only ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist other error codes from the underlying storage driver ESP_OK if erase operation was successful Parameters handle -- [in] Storage handle obtained with nvs_open. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. Returns ESP_OK if erase operation was successful ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if handle was opened as read only ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist other error codes from the underlying storage driver esp_err_t nvs_erase_all(nvs_handle_t handle) Erase all key-value pairs in a namespace. Note that actual storage may not be updated until nvs_commit function is called. Parameters handle -- [in] Storage handle obtained with nvs_open. Handles that were opened read only cannot be used. Returns ESP_OK if erase operation was successful ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if handle was opened as read only other error codes from the underlying storage driver ESP_OK if erase operation was successful ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if handle was opened as read only other error codes from the underlying storage driver ESP_OK if erase operation was successful Parameters handle -- [in] Storage handle obtained with nvs_open. Handles that were opened read only cannot be used. Returns ESP_OK if erase operation was successful ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if handle was opened as read only other error codes from the underlying storage driver esp_err_t nvs_commit(nvs_handle_t handle) Write any pending changes to non-volatile storage. After setting any values, nvs_commit() must be called to ensure changes are written to non-volatile storage. Individual implementations may write to storage at other times, but this is not guaranteed. Parameters handle -- [in] Storage handle obtained with nvs_open. Handles that were opened read only cannot be used. Returns ESP_OK if the changes have been written successfully ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL other error codes from the underlying storage driver ESP_OK if the changes have been written successfully ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL other error codes from the underlying storage driver ESP_OK if the changes have been written successfully Parameters handle -- [in] Storage handle obtained with nvs_open. Handles that were opened read only cannot be used. Returns ESP_OK if the changes have been written successfully ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL other error codes from the underlying storage driver void nvs_close(nvs_handle_t handle) Close the storage handle and free any allocated resources. This function should be called for each handle opened with nvs_open once the handle is not in use any more. Closing the handle may not automatically write the changes to nonvolatile storage. This has to be done explicitly using nvs_commit function. Once this function is called on a handle, the handle should no longer be used. Parameters handle -- [in] Storage handle to close Parameters handle -- [in] Storage handle to close esp_err_t nvs_get_stats(const char *part_name, nvs_stats_t *nvs_stats) Fill structure nvs_stats_t. It provides info about memory used by NVS. This function calculates the number of used entries, free entries, available entries, total entries and number of namespaces in partition. // Example of nvs_get_stats() to get overview of actual statistics of data entries : nvs_stats_t nvs_stats; nvs_get_stats(NULL, &nvs_stats); printf("Count: UsedEntries = (%lu), FreeEntries = (%lu), AvailableEntries = (%lu), AllEntries = (%lu)\n", nvs_stats.used_entries, nvs_stats.free_entries, nvs_stats.available_entries, nvs_stats.total_entries); Parameters part_name -- [in] Partition name NVS in the partition table. If pass a NULL than will use NVS_DEFAULT_PART_NAME ("nvs"). nvs_stats -- [out] Returns filled structure nvs_states_t. It provides info about used memory the partition. part_name -- [in] Partition name NVS in the partition table. If pass a NULL than will use NVS_DEFAULT_PART_NAME ("nvs"). nvs_stats -- [out] Returns filled structure nvs_states_t. It provides info about used memory the partition. part_name -- [in] Partition name NVS in the partition table. If pass a NULL than will use NVS_DEFAULT_PART_NAME ("nvs"). Returns ESP_OK if the changes have been written successfully. Return param nvs_stats will be filled. ESP_ERR_NVS_PART_NOT_FOUND if the partition with label "name" is not found. Return param nvs_stats will be filled 0. ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized. Return param nvs_stats will be filled 0. ESP_ERR_INVALID_ARG if nvs_stats is equal to NULL. ESP_ERR_INVALID_STATE if there is page with the status of INVALID. Return param nvs_stats will be filled not with correct values because not all pages will be counted. Counting will be interrupted at the first INVALID page. ESP_OK if the changes have been written successfully. Return param nvs_stats will be filled. ESP_ERR_NVS_PART_NOT_FOUND if the partition with label "name" is not found. Return param nvs_stats will be filled 0. ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized. Return param nvs_stats will be filled 0. ESP_ERR_INVALID_ARG if nvs_stats is equal to NULL. ESP_ERR_INVALID_STATE if there is page with the status of INVALID. Return param nvs_stats will be filled not with correct values because not all pages will be counted. Counting will be interrupted at the first INVALID page. ESP_OK if the changes have been written successfully. Return param nvs_stats will be filled. Parameters part_name -- [in] Partition name NVS in the partition table. If pass a NULL than will use NVS_DEFAULT_PART_NAME ("nvs"). nvs_stats -- [out] Returns filled structure nvs_states_t. It provides info about used memory the partition. Returns ESP_OK if the changes have been written successfully. Return param nvs_stats will be filled. ESP_ERR_NVS_PART_NOT_FOUND if the partition with label "name" is not found. Return param nvs_stats will be filled 0. ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized. Return param nvs_stats will be filled 0. ESP_ERR_INVALID_ARG if nvs_stats is equal to NULL. ESP_ERR_INVALID_STATE if there is page with the status of INVALID. Return param nvs_stats will be filled not with correct values because not all pages will be counted. Counting will be interrupted at the first INVALID page. esp_err_t nvs_get_used_entry_count(nvs_handle_t handle, size_t *used_entries) Calculate all entries in a namespace. An entry represents the smallest storage unit in NVS. Strings and blobs may occupy more than one entry. Note that to find out the total number of entries occupied by the namespace, add one to the returned value used_entries (if err is equal to ESP_OK). Because the name space entry takes one entry. // Example of nvs_get_used_entry_count() to get amount of all key-value pairs in one namespace: nvs_handle_t handle; nvs_open("namespace1", NVS_READWRITE, &handle); ... size_t used_entries; size_t total_entries_namespace; if(nvs_get_used_entry_count(handle, &used_entries) == ESP_OK){ // the total number of entries occupied by the namespace total_entries_namespace = used_entries + 1; } Parameters handle -- [in] Handle obtained from nvs_open function. used_entries -- [out] Returns amount of used entries from a namespace. handle -- [in] Handle obtained from nvs_open function. used_entries -- [out] Returns amount of used entries from a namespace. handle -- [in] Handle obtained from nvs_open function. Returns ESP_OK if the changes have been written successfully. Return param used_entries will be filled valid value. ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized. Return param used_entries will be filled 0. ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL. Return param used_entries will be filled 0. ESP_ERR_INVALID_ARG if used_entries is equal to NULL. Other error codes from the underlying storage driver. Return param used_entries will be filled 0. ESP_OK if the changes have been written successfully. Return param used_entries will be filled valid value. ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized. Return param used_entries will be filled 0. ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL. Return param used_entries will be filled 0. ESP_ERR_INVALID_ARG if used_entries is equal to NULL. Other error codes from the underlying storage driver. Return param used_entries will be filled 0. ESP_OK if the changes have been written successfully. Return param used_entries will be filled valid value. Parameters handle -- [in] Handle obtained from nvs_open function. used_entries -- [out] Returns amount of used entries from a namespace. Returns ESP_OK if the changes have been written successfully. Return param used_entries will be filled valid value. ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized. Return param used_entries will be filled 0. ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL. Return param used_entries will be filled 0. ESP_ERR_INVALID_ARG if used_entries is equal to NULL. Other error codes from the underlying storage driver. Return param used_entries will be filled 0. esp_err_t nvs_entry_find(const char *part_name, const char *namespace_name, nvs_type_t type, nvs_iterator_t *output_iterator) Create an iterator to enumerate NVS entries based on one or more parameters. // Example of listing all the key-value pairs of any type under specified partition and namespace nvs_iterator_t it = NULL; esp_err_t res = nvs_entry_find(<nvs_partition_name>, <namespace>, NVS_TYPE_ANY, &it); while(res == ESP_OK) { nvs_entry_info_t info; nvs_entry_info(it, &info); // Can omit error check if parameters are guaranteed to be non-NULL printf("key '%s', type '%d' \n", info.key, info.type); res = nvs_entry_next(&it); } nvs_release_iterator(it); Parameters part_name -- [in] Partition name namespace_name -- [in] Set this value if looking for entries with a specific namespace. Pass NULL otherwise. type -- [in] One of nvs_type_t values. output_iterator -- [out] Set to a valid iterator to enumerate all the entries found. Set to NULL if no entry for specified criteria was found. If any other error except ESP_ERR_INVALID_ARG occurs, output_iterator is NULL, too. If ESP_ERR_INVALID_ARG occurs, output_iterator is not changed. If a valid iterator is obtained through this function, it has to be released using nvs_release_iterator when not used any more, unless ESP_ERR_INVALID_ARG is returned. part_name -- [in] Partition name namespace_name -- [in] Set this value if looking for entries with a specific namespace. Pass NULL otherwise. type -- [in] One of nvs_type_t values. output_iterator -- [out] Set to a valid iterator to enumerate all the entries found. Set to NULL if no entry for specified criteria was found. If any other error except ESP_ERR_INVALID_ARG occurs, output_iterator is NULL, too. If ESP_ERR_INVALID_ARG occurs, output_iterator is not changed. If a valid iterator is obtained through this function, it has to be released using nvs_release_iterator when not used any more, unless ESP_ERR_INVALID_ARG is returned. part_name -- [in] Partition name Returns ESP_OK if no internal error or programming error occurred. ESP_ERR_NVS_NOT_FOUND if no element of specified criteria has been found. ESP_ERR_NO_MEM if memory has been exhausted during allocation of internal structures. ESP_ERR_INVALID_ARG if any of the parameters is NULL. Note: don't release output_iterator in case ESP_ERR_INVALID_ARG has been returned ESP_OK if no internal error or programming error occurred. ESP_ERR_NVS_NOT_FOUND if no element of specified criteria has been found. ESP_ERR_NO_MEM if memory has been exhausted during allocation of internal structures. ESP_ERR_INVALID_ARG if any of the parameters is NULL. Note: don't release output_iterator in case ESP_ERR_INVALID_ARG has been returned ESP_OK if no internal error or programming error occurred. Parameters part_name -- [in] Partition name namespace_name -- [in] Set this value if looking for entries with a specific namespace. Pass NULL otherwise. type -- [in] One of nvs_type_t values. output_iterator -- [out] Set to a valid iterator to enumerate all the entries found. Set to NULL if no entry for specified criteria was found. If any other error except ESP_ERR_INVALID_ARG occurs, output_iterator is NULL, too. If ESP_ERR_INVALID_ARG occurs, output_iterator is not changed. If a valid iterator is obtained through this function, it has to be released using nvs_release_iterator when not used any more, unless ESP_ERR_INVALID_ARG is returned. Returns ESP_OK if no internal error or programming error occurred. ESP_ERR_NVS_NOT_FOUND if no element of specified criteria has been found. ESP_ERR_NO_MEM if memory has been exhausted during allocation of internal structures. ESP_ERR_INVALID_ARG if any of the parameters is NULL. Note: don't release output_iterator in case ESP_ERR_INVALID_ARG has been returned esp_err_t nvs_entry_find_in_handle(nvs_handle_t handle, nvs_type_t type, nvs_iterator_t *output_iterator) Create an iterator to enumerate NVS entries based on a handle and type. // Example of listing all the key-value pairs of any type under specified handle (which defines a partition and namespace) nvs_iterator_t it = NULL; esp_err_t res = nvs_entry_find_in_handle(<nvs_handle>, NVS_TYPE_ANY, &it); while(res == ESP_OK) { nvs_entry_info_t info; nvs_entry_info(it, &info); // Can omit error check if parameters are guaranteed to be non-NULL printf("key '%s', type '%d' \n", info.key, info.type); res = nvs_entry_next(&it); } nvs_release_iterator(it); Parameters handle -- [in] Handle obtained from nvs_open function. type -- [in] One of nvs_type_t values. output_iterator -- [out] Set to a valid iterator to enumerate all the entries found. Set to NULL if no entry for specified criteria was found. If any other error except ESP_ERR_INVALID_ARG occurs, output_iterator is NULL, too. If ESP_ERR_INVALID_ARG occurs, output_iterator is not changed. If a valid iterator is obtained through this function, it has to be released using nvs_release_iterator when not used any more, unless ESP_ERR_INVALID_ARG is returned. handle -- [in] Handle obtained from nvs_open function. type -- [in] One of nvs_type_t values. output_iterator -- [out] Set to a valid iterator to enumerate all the entries found. Set to NULL if no entry for specified criteria was found. If any other error except ESP_ERR_INVALID_ARG occurs, output_iterator is NULL, too. If ESP_ERR_INVALID_ARG occurs, output_iterator is not changed. If a valid iterator is obtained through this function, it has to be released using nvs_release_iterator when not used any more, unless ESP_ERR_INVALID_ARG is returned. handle -- [in] Handle obtained from nvs_open function. Returns ESP_OK if no internal error or programming error occurred. ESP_ERR_NVS_NOT_FOUND if no element of specified criteria has been found. ESP_ERR_NO_MEM if memory has been exhausted during allocation of internal structures. ESP_ERR_NVS_INVALID_HANDLE if unknown handle was specified. ESP_ERR_INVALID_ARG if output_iterator parameter is NULL. Note: don't release output_iterator in case ESP_ERR_INVALID_ARG has been returned ESP_OK if no internal error or programming error occurred. ESP_ERR_NVS_NOT_FOUND if no element of specified criteria has been found. ESP_ERR_NO_MEM if memory has been exhausted during allocation of internal structures. ESP_ERR_NVS_INVALID_HANDLE if unknown handle was specified. ESP_ERR_INVALID_ARG if output_iterator parameter is NULL. Note: don't release output_iterator in case ESP_ERR_INVALID_ARG has been returned ESP_OK if no internal error or programming error occurred. Parameters handle -- [in] Handle obtained from nvs_open function. type -- [in] One of nvs_type_t values. output_iterator -- [out] Set to a valid iterator to enumerate all the entries found. Set to NULL if no entry for specified criteria was found. If any other error except ESP_ERR_INVALID_ARG occurs, output_iterator is NULL, too. If ESP_ERR_INVALID_ARG occurs, output_iterator is not changed. If a valid iterator is obtained through this function, it has to be released using nvs_release_iterator when not used any more, unless ESP_ERR_INVALID_ARG is returned. Returns ESP_OK if no internal error or programming error occurred. ESP_ERR_NVS_NOT_FOUND if no element of specified criteria has been found. ESP_ERR_NO_MEM if memory has been exhausted during allocation of internal structures. ESP_ERR_NVS_INVALID_HANDLE if unknown handle was specified. ESP_ERR_INVALID_ARG if output_iterator parameter is NULL. Note: don't release output_iterator in case ESP_ERR_INVALID_ARG has been returned esp_err_t nvs_entry_next(nvs_iterator_t *iterator) Advances the iterator to next item matching the iterator criteria. Note that any copies of the iterator will be invalid after this call. Parameters iterator -- [inout] Iterator obtained from nvs_entry_find or nvs_entry_find_in_handle function. Must be non-NULL. If any error except ESP_ERR_INVALID_ARG occurs, iterator is set to NULL. If ESP_ERR_INVALID_ARG occurs, iterator is not changed. Returns ESP_OK if no internal error or programming error occurred. ESP_ERR_NVS_NOT_FOUND if no next element matching the iterator criteria. ESP_ERR_INVALID_ARG if iterator is NULL. Possibly other errors in the future for internal programming or flash errors. ESP_OK if no internal error or programming error occurred. ESP_ERR_NVS_NOT_FOUND if no next element matching the iterator criteria. ESP_ERR_INVALID_ARG if iterator is NULL. Possibly other errors in the future for internal programming or flash errors. ESP_OK if no internal error or programming error occurred. Parameters iterator -- [inout] Iterator obtained from nvs_entry_find or nvs_entry_find_in_handle function. Must be non-NULL. If any error except ESP_ERR_INVALID_ARG occurs, iterator is set to NULL. If ESP_ERR_INVALID_ARG occurs, iterator is not changed. Returns ESP_OK if no internal error or programming error occurred. ESP_ERR_NVS_NOT_FOUND if no next element matching the iterator criteria. ESP_ERR_INVALID_ARG if iterator is NULL. Possibly other errors in the future for internal programming or flash errors. esp_err_t nvs_entry_info(const nvs_iterator_t iterator, nvs_entry_info_t *out_info) Fills nvs_entry_info_t structure with information about entry pointed to by the iterator. Parameters iterator -- [in] Iterator obtained from nvs_entry_find or nvs_entry_find_in_handle function. Must be non-NULL. out_info -- [out] Structure to which entry information is copied. iterator -- [in] Iterator obtained from nvs_entry_find or nvs_entry_find_in_handle function. Must be non-NULL. out_info -- [out] Structure to which entry information is copied. iterator -- [in] Iterator obtained from nvs_entry_find or nvs_entry_find_in_handle function. Must be non-NULL. Returns ESP_OK if all parameters are valid; current iterator data has been written to out_info ESP_ERR_INVALID_ARG if one of the parameters is NULL. ESP_OK if all parameters are valid; current iterator data has been written to out_info ESP_ERR_INVALID_ARG if one of the parameters is NULL. ESP_OK if all parameters are valid; current iterator data has been written to out_info Parameters iterator -- [in] Iterator obtained from nvs_entry_find or nvs_entry_find_in_handle function. Must be non-NULL. out_info -- [out] Structure to which entry information is copied. Returns ESP_OK if all parameters are valid; current iterator data has been written to out_info ESP_ERR_INVALID_ARG if one of the parameters is NULL. void nvs_release_iterator(nvs_iterator_t iterator) Release iterator. Parameters iterator -- [in] Release iterator obtained from nvs_entry_find or nvs_entry_find_in_handle or nvs_entry_next function. NULL argument is allowed. Parameters iterator -- [in] Release iterator obtained from nvs_entry_find or nvs_entry_find_in_handle or nvs_entry_next function. NULL argument is allowed. Structures struct nvs_entry_info_t information about entry obtained from nvs_entry_info function Public Members char namespace_name[NVS_NS_NAME_MAX_SIZE] Namespace to which key-value belong char namespace_name[NVS_NS_NAME_MAX_SIZE] Namespace to which key-value belong char key[NVS_KEY_NAME_MAX_SIZE] Key of stored key-value pair char key[NVS_KEY_NAME_MAX_SIZE] Key of stored key-value pair nvs_type_t type Type of stored key-value pair nvs_type_t type Type of stored key-value pair char namespace_name[NVS_NS_NAME_MAX_SIZE] struct nvs_stats_t Note Info about storage space NVS. Public Members size_t used_entries Number of used entries. size_t used_entries Number of used entries. size_t free_entries Number of free entries. It includes also reserved entries. size_t free_entries Number of free entries. It includes also reserved entries. size_t available_entries Number of entries available for data storage. size_t available_entries Number of entries available for data storage. size_t total_entries Number of all entries. size_t total_entries Number of all entries. size_t namespace_count Number of namespaces. size_t namespace_count Number of namespaces. size_t used_entries Macros ESP_ERR_NVS_BASE Starting number of error codes ESP_ERR_NVS_NOT_INITIALIZED The storage driver is not initialized ESP_ERR_NVS_NOT_FOUND A requested entry couldn't be found or namespace doesn’t exist yet and mode is NVS_READONLY ESP_ERR_NVS_TYPE_MISMATCH The type of set or get operation doesn't match the type of value stored in NVS ESP_ERR_NVS_READ_ONLY Storage handle was opened as read only ESP_ERR_NVS_NOT_ENOUGH_SPACE There is not enough space in the underlying storage to save the value ESP_ERR_NVS_INVALID_NAME Namespace name doesn’t satisfy constraints ESP_ERR_NVS_INVALID_HANDLE Handle has been closed or is NULL ESP_ERR_NVS_REMOVE_FAILED The value wasn’t updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn’t fail again. ESP_ERR_NVS_KEY_TOO_LONG Key name is too long ESP_ERR_NVS_PAGE_FULL Internal error; never returned by nvs API functions ESP_ERR_NVS_INVALID_STATE NVS is in an inconsistent state due to a previous error. Call nvs_flash_init and nvs_open again, then retry. ESP_ERR_NVS_INVALID_LENGTH String or blob length is not sufficient to store data ESP_ERR_NVS_NO_FREE_PAGES NVS partition doesn't contain any empty pages. This may happen if NVS partition was truncated. Erase the whole partition and call nvs_flash_init again. ESP_ERR_NVS_VALUE_TOO_LONG Value doesn't fit into the entry or string or blob length is longer than supported by the implementation ESP_ERR_NVS_PART_NOT_FOUND Partition with specified name is not found in the partition table ESP_ERR_NVS_NEW_VERSION_FOUND NVS partition contains data in new format and cannot be recognized by this version of code ESP_ERR_NVS_XTS_ENCR_FAILED XTS encryption failed while writing NVS entry ESP_ERR_NVS_XTS_DECR_FAILED XTS decryption failed while reading NVS entry ESP_ERR_NVS_XTS_CFG_FAILED XTS configuration setting failed ESP_ERR_NVS_XTS_CFG_NOT_FOUND XTS configuration not found ESP_ERR_NVS_ENCR_NOT_SUPPORTED NVS encryption is not supported in this version ESP_ERR_NVS_KEYS_NOT_INITIALIZED NVS key partition is uninitialized ESP_ERR_NVS_CORRUPT_KEY_PART NVS key partition is corrupt ESP_ERR_NVS_WRONG_ENCRYPTION NVS partition is marked as encrypted with generic flash encryption. This is forbidden since the NVS encryption works differently. ESP_ERR_NVS_CONTENT_DIFFERS Internal error; never returned by nvs API functions. NVS key is different in comparison NVS_DEFAULT_PART_NAME Default partition name of the NVS partition in the partition table NVS_PART_NAME_MAX_SIZE maximum length of partition name (excluding null terminator) NVS_KEY_NAME_MAX_SIZE Maximum length of NVS key name (including null terminator) NVS_NS_NAME_MAX_SIZE Maximum length of NVS namespace name (including null terminator) Type Definitions typedef uint32_t nvs_handle_t Opaque pointer type representing non-volatile storage handle typedef nvs_handle_t nvs_handle typedef nvs_open_mode_t nvs_open_mode typedef struct nvs_opaque_iterator_t *nvs_iterator_t Opaque pointer type representing iterator to nvs entries Enumerations enum nvs_open_mode_t Mode of opening the non-volatile storage. Values: enumerator NVS_READONLY Read only enumerator NVS_READONLY Read only enumerator NVS_READWRITE Read and write enumerator NVS_READWRITE Read and write enumerator NVS_READONLY enum nvs_type_t Types of variables. Values: enumerator NVS_TYPE_U8 Type uint8_t enumerator NVS_TYPE_U8 Type uint8_t enumerator NVS_TYPE_I8 Type int8_t enumerator NVS_TYPE_I8 Type int8_t enumerator NVS_TYPE_U16 Type uint16_t enumerator NVS_TYPE_U16 Type uint16_t enumerator NVS_TYPE_I16 Type int16_t enumerator NVS_TYPE_I16 Type int16_t enumerator NVS_TYPE_U32 Type uint32_t enumerator NVS_TYPE_U32 Type uint32_t enumerator NVS_TYPE_I32 Type int32_t enumerator NVS_TYPE_I32 Type int32_t enumerator NVS_TYPE_U64 Type uint64_t enumerator NVS_TYPE_U64 Type uint64_t enumerator NVS_TYPE_I64 Type int64_t enumerator NVS_TYPE_I64 Type int64_t enumerator NVS_TYPE_STR Type string enumerator NVS_TYPE_STR Type string enumerator NVS_TYPE_BLOB Type blob enumerator NVS_TYPE_BLOB Type blob enumerator NVS_TYPE_ANY Must be last enumerator NVS_TYPE_ANY Must be last enumerator NVS_TYPE_U8
Non-Volatile Storage Library Introduction Non-volatile storage (NVS) library is designed to store key-value pairs in flash. This section introduces some concepts used by NVS. Underlying Storage Currently, NVS uses a portion of main flash memory through the esp_partition API. The library uses all the partitions with data type and nvs subtype. The application can choose to use the partition with the label nvs through the nvs_open() API function or any other partition by specifying its name using the nvs_open_from_partition() API function. Future versions of this library may have other storage backends to keep data in another flash chip (SPI or I2C), RTC, FRAM, etc. Note if an NVS partition is truncated (for example, when the partition table layout is changed), its contents should be erased. ESP-IDF build system provides a idf.py erase-flash target to erase all contents of the flash chip. Note NVS works best for storing many small values, rather than a few large values of the type 'string' and 'blob'. If you need to store large blobs or strings, consider using the facilities provided by the FAT filesystem on top of the wear levelling library. Keys and Values NVS operates on key-value pairs. Keys are ASCII strings; the maximum key length is currently 15 characters. Values can have one of the following types: integer types: uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t, int64_t zero-terminated string variable length binary data (blob) Note String values are currently limited to 4000 bytes. This includes the null terminator. Blob values are limited to 508,000 bytes or 97.6% of the partition size - 4000 bytes, whichever is lower. Additional types, such as float and double might be added later. Keys are required to be unique. Assigning a new value to an existing key replaces the old value and data type with the value and data type specified by a write operation. A data type check is performed when reading a value. An error is returned if the data type expected by read operation does not match the data type of entry found for the key provided. Namespaces To mitigate potential conflicts in key names between different components, NVS assigns each key-value pair to one of namespaces. Namespace names follow the same rules as key names, i.e., the maximum length is 15 characters. Furthermore, there can be no more than 254 different namespaces in one NVS partition. Namespace name is specified in the nvs_open() or nvs_open_from_partition call. This call returns an opaque handle, which is used in subsequent calls to the nvs_get_*, nvs_set_*, and nvs_commit() functions. This way, a handle is associated with a namespace, and key names will not collide with same names in other namespaces. Please note that the namespaces with the same name in different NVS partitions are considered as separate namespaces. NVS Iterators Iterators allow to list key-value pairs stored in NVS, based on specified partition name, namespace, and data type. There are the following functions available: nvs_entry_find()creates an opaque handle, which is used in subsequent calls to the nvs_entry_next()and nvs_entry_info()functions. nvs_entry_next()advances an iterator to the next key-value pair. nvs_entry_info()returns information about each key-value pair In general, all iterators obtained via nvs_entry_find() have to be released using nvs_release_iterator(), which also tolerates NULL iterators. nvs_entry_find() and nvs_entry_next() set the given iterator to NULL or a valid iterator in all cases except a parameter error occured (i.e., return ESP_ERR_NVS_NOT_FOUND). In case of a parameter error, the given iterator will not be modified. Hence, it is best practice to initialize the iterator to NULL before calling nvs_entry_find() to avoid complicated error checking before releasing the iterator. Security, Tampering, and Robustness NVS is not directly compatible with the ESP32 flash encryption system. However, data can still be stored in encrypted form if NVS encryption is used together with ESP32 flash encryption. Please refer to NVS Encryption for more details. If NVS encryption is not used, it is possible for anyone with physical access to the flash chip to alter, erase, or add key-value pairs. With NVS encryption enabled, it is not possible to alter or add a key-value pair and get recognized as a valid pair without knowing corresponding NVS encryption keys. However, there is no tamper-resistance against the erase operation. The library does try to recover from conditions when flash memory is in an inconsistent state. In particular, one should be able to power off the device at any point and time and then power it back on. This should not result in loss of data, except for the new key-value pair if it was being written at the moment of powering off. The library should also be able to initialize properly with any random data present in flash memory. NVS Encryption Please refer to the NVS Encryption guide for more details. NVS Partition Generator Utility This utility helps generate NVS partition binary files which can be flashed separately on a dedicated partition via a flashing utility. Key-value pairs to be flashed onto the partition can be provided via a CSV file. For more details, please refer to NVS Partition Generator Utility. Instead of calling the nvs_partition_gen.py tool manually, the creation of the partition binary files can also be done directly from CMake using the function nvs_create_partition_image: nvs_create_partition_image(<partition> <csv> [FLASH_IN_PROJECT] [DEPENDS dep dep dep ...]) Positional Arguments: | Parameter | Description | | Name of the NVS parition | | Path to CSV file to parse Optional Arguments: | Parameter | Description | | Name of the NVS parition | | Specify files on which the command depends If FLASH_IN_PROJECT is not specified, the image will still be generated, but you will have to flash it manually using idf.py <partition>-flash (e.g., if your parition name is nvs, then use idf.py nvs-flash). nvs_create_partition_image must be called from one of the component CMakeLists.txt files. Currently, only non-encrypted partitions are supported. Application Example You can find code examples in the storage directory of ESP-IDF examples: Demonstrates how to read a single integer value from, and write it to NVS. The value checked in this example holds the number of the ESP32 module restarts. The value's function as a counter is only possible due to its storing in NVS. The example also shows how to check if a read/write operation was successful, or if a certain value has not been initialized in NVS. The diagnostic procedure is provided in plain text to help you track the program flow and capture any issues on the way. Demonstrates how to read a single integer value and a blob (binary large object), and write them to NVS to preserve this value between ESP32 module restarts. - value - tracks the number of the ESP32 module soft and hard restarts. - blob - contains a table with module run times. The table is read from NVS to dynamically allocated RAM. A new run time is added to the table on each manually triggered soft restart, and then the added run time is written to NVS. Triggering is done by pulling down GPIO0. The example also shows how to implement the diagnostic procedure to check if the read/write operation was successful. This example does exactly the same as storage/nvs_rw_value, except that it uses the C++ NVS handle class. Internals Log of Key-Value Pairs NVS stores key-value pairs sequentially, with new key-value pairs being added at the end. When a value of any given key has to be updated, a new key-value pair is added at the end of the log and the old key-value pair is marked as erased. Pages and Entries NVS library uses two main entities in its operation: pages and entries. Page is a logical structure which stores a portion of the overall log. Logical page corresponds to one physical sector of flash memory. Pages which are in use have a sequence number associated with them. Sequence numbers impose an ordering on pages. Higher sequence numbers correspond to pages which were created later. Each page can be in one of the following states: - Empty/uninitialized Flash storage for the page is empty (all bytes are 0xff). Page is not used to store any data at this point and does not have a sequence number. - Active Flash storage is initialized, page header has been written to flash, page has a valid sequence number. Page has some empty entries and data can be written there. No more than one page can be in this state at any given moment. - Full Flash storage is in a consistent state and is filled with key-value pairs. Writing new key-value pairs into this page is not possible. It is still possible to mark some key-value pairs as erased. - Erasing Non-erased key-value pairs are being moved into another page so that the current page can be erased. This is a transient state, i.e., page should never stay in this state at the time when any API call returns. In case of a sudden power off, the move-and-erase process will be completed upon the next power-on. - Corrupted Page header contains invalid data, and further parsing of page data was canceled. Any items previously written into this page will not be accessible. The corresponding flash sector will not be erased immediately and will be kept along with sectors in uninitialized state for later use. This may be useful for debugging. Mapping from flash sectors to logical pages does not have any particular order. The library will inspect sequence numbers of pages found in each flash sector and organize pages in a list based on these numbers. +--------+ +--------+ +--------+ +--------+ | Page 1 | | Page 2 | | Page 3 | | Page 4 | | Full +---> | Full +---> | Active | | Empty | <- states | #11 | | #12 | | #14 | | | <- sequence numbers +---+----+ +----+---+ +----+---+ +---+----+ | | | | | | | | | | | | +---v------+ +-----v----+ +------v---+ +------v---+ | Sector 3 | | Sector 0 | | Sector 2 | | Sector 1 | <- physical sectors +----------+ +----------+ +----------+ +----------+ Structure of a Page For now, we assume that flash sector size is 4096 bytes and that ESP32 flash encryption hardware operates on 32-byte blocks. It is possible to introduce some settings configurable at compile-time (e.g., via menuconfig) to accommodate flash chips with different sector sizes (although it is not clear if other components in the system, e.g., SPI flash driver and SPI flash cache can support these other sizes). Page consists of three parts: header, entry state bitmap, and entries themselves. To be compatible with ESP32 flash encryption, the entry size is 32 bytes. For integer types, an entry holds one key-value pair. For strings and blobs, an entry holds part of key-value pair (more on that in the entry structure description). The following diagram illustrates the page structure. Numbers in parentheses indicate the size of each part in bytes. +-----------+--------------+-------------+-------------------------+ | State (4) | Seq. no. (4) | version (1) | Unused (19) | CRC32 (4) | Header (32) +-----------+--------------+-------------+-------------------------+ | Entry state bitmap (32) | +------------------------------------------------------------------+ | Entry 0 (32) | +------------------------------------------------------------------+ | Entry 1 (32) | +------------------------------------------------------------------+ / / / / +------------------------------------------------------------------+ | Entry 125 (32) | +------------------------------------------------------------------+ Page header and entry state bitmap are always written to flash unencrypted. Entries are encrypted if flash encryption feature of ESP32 is used. Page state values are defined in such a way that changing state is possible by writing 0 into some of the bits. Therefore it is not necessary to erase the page to change its state unless that is a change to the erased state. The version field in the header reflects the NVS format version used. For backward compatibility reasons, it is decremented for every version upgrade starting at 0xff (i.e., 0xff for version-1, 0xfe for version-2 and so on). CRC32 value in the header is calculated over the part which does not include a state value (bytes 4 to 28). The unused part is currently filled with 0xff bytes. The following sections describe the structure of entry state bitmap and entry itself. Entry and Entry State Bitmap Each entry can be in one of the following three states represented with two bits in the entry state bitmap. The final four bits in the bitmap (256 - 2 * 126) are not used. - Empty (2'b11) Nothing is written into the specific entry yet. It is in an uninitialized state (all bytes are 0xff). - Written (2'b10) A key-value pair (or part of key-value pair which spans multiple entries) has been written into the entry. - Erased (2'b00) A key-value pair in this entry has been discarded. Contents of this entry will not be parsed anymore. Structure of Entry For values of primitive types (currently integers from 1 to 8 bytes long), entry holds one key-value pair. For string and blob types, entry holds part of the whole key-value pair. For strings, in case when a key-value pair spans multiple entries, all entries are stored in the same page. Blobs are allowed to span over multiple pages by dividing them into smaller chunks. For tracking these chunks, an additional fixed length metadata entry is stored called "blob index". Earlier formats of blobs are still supported (can be read and modified). However, once the blobs are modified, they are stored using the new format. +--------+----------+----------+----------------+-----------+---------------+----------+ | NS (1) | Type (1) | Span (1) | ChunkIndex (1) | CRC32 (4) | Key (16) | Data (8) | +--------+----------+----------+----------------+-----------+---------------+----------+ Primitive +--------------------------------+ +--------> | Data (8) | | Types +--------------------------------+ +-> Fixed length -- | | +---------+--------------+---------------+-------+ | +--------> | Size(4) | ChunkCount(1)| ChunkStart(1) | Rsv(2)| Data format ---+ Blob Index +---------+--------------+---------------+-------+ | | +----------+---------+-----------+ +-> Variable length --> | Size (2) | Rsv (2) | CRC32 (4) | (Strings, Blob Data) +----------+---------+-----------+ Individual fields in entry structure have the following meanings: - NS Namespace index for this entry. For more information on this value, see the section on namespaces implementation. - Type One byte indicating the value data type. See the ItemTypeenumeration in nvs_flash/include/nvs_handle.hpp for possible values. - Span Number of entries used by this key-value pair. For integer types, this is equal to 1. For strings and blobs, this depends on value length. - ChunkIndex Used to store the index of a blob-data chunk for blob types. For other types, this should be 0xff. - CRC32 Checksum calculated over all the bytes in this entry, except for the CRC32 field itself. - Key Zero-terminated ASCII string containing a key name. Maximum string length is 15 bytes, excluding a zero terminator. - Data For integer types, this field contains the value itself. If the value itself is shorter than 8 bytes, it is padded to the right, with unused bytes filled with 0xff. For "blob index" entry, these 8 bytes hold the following information about data-chunks: - Size (Only for blob index.) Size, in bytes, of complete blob data. - ChunkCount (Only for blob index.) Total number of blob-data chunks into which the blob was divided during storage. - ChunkStart (Only for blob index.) ChunkIndex of the first blob-data chunk of this blob. Subsequent chunks have chunkIndex incrementally allocated (step of 1). For string and blob data chunks, these 8 bytes hold additional data about the value, which are described below: - Size (Only for strings and blobs.) Size, in bytes, of actual data. For strings, this includes zero terminators. - CRC32 (Only for strings and blobs.) Checksum calculated over all bytes of data. - Variable length values (strings and blobs) are written into subsequent entries, 32 bytes per entry. The Span field of the first entry indicates how many entries are used. Namespaces As mentioned above, each key-value pair belongs to one of the namespaces. Namespace identifiers (strings) are stored as keys of key-value pairs in namespace with index 0. Values corresponding to these keys are indexes of these namespaces. +-------------------------------------------+ | NS=0 Type=uint8_t Key="wifi" Value=1 | Entry describing namespace "wifi" +-------------------------------------------+ | NS=1 Type=uint32_t Key="channel" Value=6 | Key "channel" in namespace "wifi" +-------------------------------------------+ | NS=0 Type=uint8_t Key="pwm" Value=2 | Entry describing namespace "pwm" +-------------------------------------------+ | NS=2 Type=uint16_t Key="channel" Value=20 | Key "channel" in namespace "pwm" +-------------------------------------------+ Item Hash List To reduce the number of reads from flash memory, each member of the Page class maintains a list of pairs: item index; item hash. This list makes searches much quicker. Instead of iterating over all entries, reading them from flash one at a time, Page::findItem first performs a search for the item hash in the hash list. This gives the item index within the page if such an item exists. Due to a hash collision, it is possible that a different item is found. This is handled by falling back to iteration over items in flash. Each node in the hash list contains a 24-bit hash and 8-bit item index. Hash is calculated based on item namespace, key name, and ChunkIndex. CRC32 is used for calculation; the result is truncated to 24 bits. To reduce the overhead for storing 32-bit entries in a linked list, the list is implemented as a double-linked list of arrays. Each array holds 29 entries, for the total size of 128 bytes, together with linked list pointers and a 32-bit count field. The minimum amount of extra RAM usage per page is therefore 128 bytes; maximum is 640 bytes. API Reference Header File This header file can be included with: #include "nvs_flash.h" This header file is a part of the API provided by the nvs_flashcomponent. To declare that your component depends on nvs_flash, add the following to your CMakeLists.txt: REQUIRES nvs_flash or PRIV_REQUIRES nvs_flash Functions - esp_err_t nvs_flash_init(void) Initialize the default NVS partition. This API initialises the default NVS partition. The default NVS partition is the one that is labeled "nvs" in the partition table. When "NVS_ENCRYPTION" is enabled in the menuconfig, this API enables the NVS encryption for the default NVS partition as follows Read security configurations from the first NVS key partition listed in the partition table. (NVS key partition is any "data" type partition which has the subtype value set to "nvs_keys") If the NVS key partiton obtained in the previous step is empty, generate and store new keys in that NVS key partiton. Internally call "nvs_flash_secure_init()" with the security configurations obtained/generated in the previous steps. Post initialization NVS read/write APIs remain the same irrespective of NVS encryption. - Returns ESP_OK if storage was successfully initialized. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if no partition with label "nvs" is found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver error codes from nvs_flash_read_security_cfg API (when "NVS_ENCRYPTION" is enabled). error codes from nvs_flash_generate_keys API (when "NVS_ENCRYPTION" is enabled). error codes from nvs_flash_secure_init_partition API (when "NVS_ENCRYPTION" is enabled) . - - - esp_err_t nvs_flash_init_partition(const char *partition_label) Initialize NVS flash storage for the specified partition. - Parameters partition_label -- [in] Label of the partition. Must be no longer than 16 characters. - Returns ESP_OK if storage was successfully initialized. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if specified partition is not found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver - - esp_err_t nvs_flash_init_partition_ptr(const esp_partition_t *partition) Initialize NVS flash storage for the partition specified by partition pointer. - Parameters partition -- [in] pointer to a partition obtained by the ESP partition API. - Returns ESP_OK if storage was successfully initialized ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_INVALID_ARG in case partition is NULL ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver - - esp_err_t nvs_flash_deinit(void) Deinitialize NVS storage for the default NVS partition. Default NVS partition is the partition with "nvs" label in the partition table. - Returns ESP_OK on success (storage was deinitialized) ESP_ERR_NVS_NOT_INITIALIZED if the storage was not initialized prior to this call - - esp_err_t nvs_flash_deinit_partition(const char *partition_label) Deinitialize NVS storage for the given NVS partition. - Parameters partition_label -- [in] Label of the partition - Returns ESP_OK on success ESP_ERR_NVS_NOT_INITIALIZED if the storage for given partition was not initialized prior to this call - - esp_err_t nvs_flash_erase(void) Erase the default NVS partition. Erases all contents of the default NVS partition (one with label "nvs"). Note If the partition is initialized, this function first de-initializes it. Afterwards, the partition has to be initialized again to be used. - Returns ESP_OK on success ESP_ERR_NOT_FOUND if there is no NVS partition labeled "nvs" in the partition table different error in case de-initialization fails (shouldn't happen) - - esp_err_t nvs_flash_erase_partition(const char *part_name) Erase specified NVS partition. Erase all content of a specified NVS partition Note If the partition is initialized, this function first de-initializes it. Afterwards, the partition has to be initialized again to be used. - Parameters part_name -- [in] Name (label) of the partition which should be erased - Returns ESP_OK on success ESP_ERR_NOT_FOUND if there is no NVS partition with the specified name in the partition table different error in case de-initialization fails (shouldn't happen) - - esp_err_t nvs_flash_erase_partition_ptr(const esp_partition_t *partition) Erase custom partition. Erase all content of specified custom partition. Note If the partition is initialized, this function first de-initializes it. Afterwards, the partition has to be initialized again to be used. - Parameters partition -- [in] pointer to a partition obtained by the ESP partition API. - Returns ESP_OK on success ESP_ERR_NOT_FOUND if there is no partition with the specified parameters in the partition table ESP_ERR_INVALID_ARG in case partition is NULL one of the error codes from the underlying flash storage driver - - esp_err_t nvs_flash_secure_init(nvs_sec_cfg_t *cfg) Initialize the default NVS partition. This API initialises the default NVS partition. The default NVS partition is the one that is labeled "nvs" in the partition table. - Parameters cfg -- [in] Security configuration (keys) to be used for NVS encryption/decryption. If cfg is NULL, no encryption is used. - Returns ESP_OK if storage has been initialized successfully. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if no partition with label "nvs" is found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver - - esp_err_t nvs_flash_secure_init_partition(const char *partition_label, nvs_sec_cfg_t *cfg) Initialize NVS flash storage for the specified partition. - Parameters partition_label -- [in] Label of the partition. Note that internally, a reference to passed value is kept and it should be accessible for future operations cfg -- [in] Security configuration (keys) to be used for NVS encryption/decryption. If cfg is null, no encryption/decryption is used. - - Returns ESP_OK if storage has been initialized successfully. ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which may happen if NVS partition was truncated) ESP_ERR_NOT_FOUND if specified partition is not found in the partition table ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures one of the error codes from the underlying flash storage driver - - esp_err_t nvs_flash_generate_keys(const esp_partition_t *partition, nvs_sec_cfg_t *cfg) Generate and store NVS keys in the provided esp partition. - Parameters partition -- [in] Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. cfg -- [out] Pointer to nvs security configuration structure. Pointer must be non-NULL. Generated keys will be populated in this structure. - - Returns ESP_OK, if cfg was read successfully; ESP_ERR_INVALID_ARG, if partition or cfg is NULL; or error codes from esp_partition_write/erase APIs. - - esp_err_t nvs_flash_read_security_cfg(const esp_partition_t *partition, nvs_sec_cfg_t *cfg) Read NVS security configuration from a partition. Note Provided partition is assumed to be marked 'encrypted'. - Parameters partition -- [in] Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. cfg -- [out] Pointer to nvs security configuration structure. Pointer must be non-NULL. - - Returns ESP_OK, if cfg was read successfully; ESP_ERR_INVALID_ARG, if partition or cfg is NULL ESP_ERR_NVS_KEYS_NOT_INITIALIZED, if the partition is not yet written with keys. ESP_ERR_NVS_CORRUPT_KEY_PART, if the partition containing keys is found to be corrupt or error codes from esp_partition_read API. - - esp_err_t nvs_flash_register_security_scheme(nvs_sec_scheme_t *scheme_cfg) Registers the given security scheme for NVS encryption The scheme registered with sec_scheme_id by this API be used as the default security scheme for the "nvs" partition. Users will have to call this API explicitly in their application. - Parameters scheme_cfg -- [in] Pointer to the security scheme configuration structure that the user (or the nvs_key_provider) wants to register. - Returns ESP_OK, if security scheme registration succeeds; ESP_ERR_INVALID_ARG, if scheme_cfg is NULL; ESP_FAIL, if security scheme registration fails - - nvs_sec_scheme_t *nvs_flash_get_default_security_scheme(void) Fetch the configuration structure for the default active security scheme for NVS encryption. - Returns Pointer to the default active security scheme configuration (NULL if no scheme is registered yet i.e. active) - esp_err_t nvs_flash_generate_keys_v2(nvs_sec_scheme_t *scheme_cfg, nvs_sec_cfg_t *cfg) Generate (and store) the NVS keys using the specified key-protection scheme. - Parameters scheme_cfg -- [in] Security scheme specific configuration cfg -- [out] Security configuration (encryption keys) - - Returns ESP_OK, if cfg was populated successfully with generated encryption keys; ESP_ERR_INVALID_ARG, if scheme_cfg or cfg is NULL; ESP_FAIL, if the key generation process fails - - esp_err_t nvs_flash_read_security_cfg_v2(nvs_sec_scheme_t *scheme_cfg, nvs_sec_cfg_t *cfg) Read NVS security configuration set by the specified security scheme. - Parameters scheme_cfg -- [in] Security scheme specific configuration cfg -- [out] Security configuration (encryption keys) - - Returns ESP_OK, if cfg was read successfully; ESP_ERR_INVALID_ARG, if scheme_cfg or cfg is NULL; ESP_FAIL, if the key reading process fails - Structures - struct nvs_sec_cfg_t Key for encryption and decryption. - struct nvs_sec_scheme_t NVS encryption: Security scheme configuration structure. Public Members - int scheme_id Security Scheme ID (E.g. HMAC) - void *scheme_data Scheme-specific data (E.g. eFuse block for HMAC-based key generation) - nvs_flash_generate_keys_t nvs_flash_key_gen Callback for the nvs_flash_key_gen implementation - nvs_flash_read_cfg_t nvs_flash_read_cfg Callback for the nvs_flash_read_keys implementation - int scheme_id Macros - NVS_KEY_SIZE Type Definitions - typedef esp_err_t (*nvs_flash_generate_keys_t)(const void *scheme_data, nvs_sec_cfg_t *cfg) Callback function prototype for generating the NVS encryption keys. - typedef esp_err_t (*nvs_flash_read_cfg_t)(const void *scheme_data, nvs_sec_cfg_t *cfg) Callback function prototype for reading the NVS encryption keys. Header File This header file can be included with: #include "nvs.h" This header file is a part of the API provided by the nvs_flashcomponent. To declare that your component depends on nvs_flash, add the following to your CMakeLists.txt: REQUIRES nvs_flash or PRIV_REQUIRES nvs_flash Functions - esp_err_t nvs_set_i8(nvs_handle_t handle, const char *key, int8_t value) set int8_t value for given key Set value for the key, given its name. Note that the actual storage will not be updated until nvs_commitis called. Regardless whether key-value pair is created or updated, function always requires at least one nvs available entry. See nvs_get_stats. After create type of operation, the number of available entries is decreased by one. After update type of operation, the number of available entries remains the same. - Parameters handle -- [in] Handle obtained from nvs_open function. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. value -- [in] The value to set. - - Returns ESP_OK if value was set successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the underlying storage to save the value ESP_ERR_NVS_REMOVE_FAILED if the value wasn't updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn't fail again. - - esp_err_t nvs_set_u8(nvs_handle_t handle, const char *key, uint8_t value) set uint8_t value for given key This function is the same as nvs_set_i8except for the data type. - esp_err_t nvs_set_i16(nvs_handle_t handle, const char *key, int16_t value) set int16_t value for given key This function is the same as nvs_set_i8except for the data type. - esp_err_t nvs_set_u16(nvs_handle_t handle, const char *key, uint16_t value) set uint16_t value for given key This function is the same as nvs_set_i8except for the data type. - esp_err_t nvs_set_i32(nvs_handle_t handle, const char *key, int32_t value) set int32_t value for given key This function is the same as nvs_set_i8except for the data type. - esp_err_t nvs_set_u32(nvs_handle_t handle, const char *key, uint32_t value) set uint32_t value for given key This function is the same as nvs_set_i8except for the data type. - esp_err_t nvs_set_i64(nvs_handle_t handle, const char *key, int64_t value) set int64_t value for given key This function is the same as nvs_set_i8except for the data type. - esp_err_t nvs_set_u64(nvs_handle_t handle, const char *key, uint64_t value) set uint64_t value for given key This function is the same as nvs_set_i8except for the data type. - esp_err_t nvs_set_str(nvs_handle_t handle, const char *key, const char *value) set string for given key Sets string value for the key. Function requires whole space for new data to be available as contiguous entries in same nvs page. Operation consumes 1 overhead entry and 1 entry per each 32 characters of new string including zero character to be set. In case of value update for existing key, entries occupied by the previous value and overhead entry are returned to the pool of available entries. Note that storage of long string values can fail due to fragmentation of nvs pages even if available_entriesreturned by nvs_get_statssuggests enough overall space available. Note that the underlying storage will not be updated until nvs_commitis called. - Parameters handle -- [in] Handle obtained from nvs_open function. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. value -- [in] The value to set. For strings, the maximum length (including null character) is 4000 bytes, if there is one complete page free for writing. This decreases, however, if the free space is fragmented. - - Returns ESP_OK if value was set successfully ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the underlying storage to save the value ESP_ERR_NVS_REMOVE_FAILED if the value wasn't updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn't fail again. ESP_ERR_NVS_VALUE_TOO_LONG if the string value is too long - - esp_err_t nvs_get_i8(nvs_handle_t handle, const char *key, int8_t *out_value) get int8_t value for given key These functions retrieve value for the key, given its name. If keydoes not exist, or the requested variable type doesn't match the type which was used when setting a value, an error is returned. In case of any error, out_value is not modified. out_valuehas to be a pointer to an already allocated variable of the given type. // Example of using nvs_get_i32: int32_t max_buffer_size = 4096; // default value esp_err_t err = nvs_get_i32(my_handle, "max_buffer_size", &max_buffer_size); assert(err == ESP_OK || err == ESP_ERR_NVS_NOT_FOUND); // if ESP_ERR_NVS_NOT_FOUND was returned, max_buffer_size will still // have its default value. - Parameters handle -- [in] Handle obtained from nvs_open function. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. out_value -- Pointer to the output value. May be NULL for nvs_get_str and nvs_get_blob, in this case required length will be returned in length argument. - - Returns ESP_OK if the value was retrieved successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_INVALID_LENGTH if length is not sufficient to store data - - esp_err_t nvs_get_u8(nvs_handle_t handle, const char *key, uint8_t *out_value) get uint8_t value for given key This function is the same as nvs_get_i8except for the data type. - esp_err_t nvs_get_i16(nvs_handle_t handle, const char *key, int16_t *out_value) get int16_t value for given key This function is the same as nvs_get_i8except for the data type. - esp_err_t nvs_get_u16(nvs_handle_t handle, const char *key, uint16_t *out_value) get uint16_t value for given key This function is the same as nvs_get_i8except for the data type. - esp_err_t nvs_get_i32(nvs_handle_t handle, const char *key, int32_t *out_value) get int32_t value for given key This function is the same as nvs_get_i8except for the data type. - esp_err_t nvs_get_u32(nvs_handle_t handle, const char *key, uint32_t *out_value) get uint32_t value for given key This function is the same as nvs_get_i8except for the data type. - esp_err_t nvs_get_i64(nvs_handle_t handle, const char *key, int64_t *out_value) get int64_t value for given key This function is the same as nvs_get_i8except for the data type. - esp_err_t nvs_get_u64(nvs_handle_t handle, const char *key, uint64_t *out_value) get uint64_t value for given key This function is the same as nvs_get_i8except for the data type. - esp_err_t nvs_get_str(nvs_handle_t handle, const char *key, char *out_value, size_t *length) get string value for given key These functions retrieve the data of an entry, given its key. If key does not exist, or the requested variable type doesn't match the type which was used when setting a value, an error is returned. In case of any error, out_value is not modified. All functions expect out_value to be a pointer to an already allocated variable of the given type. nvs_get_str and nvs_get_blob functions support WinAPI-style length queries. To get the size necessary to store the value, call nvs_get_str or nvs_get_blob with zero out_value and non-zero pointer to length. Variable pointed to by length argument will be set to the required length. For nvs_get_str, this length includes the zero terminator. When calling nvs_get_str and nvs_get_blob with non-zero out_value, length has to be non-zero and has to point to the length available in out_value. It is suggested that nvs_get/set_str is used for zero-terminated C strings, and nvs_get/set_blob used for arbitrary data structures. // Example (without error checking) of using nvs_get_str to get a string into dynamic array: size_t required_size; nvs_get_str(my_handle, "server_name", NULL, &required_size); char* server_name = malloc(required_size); nvs_get_str(my_handle, "server_name", server_name, &required_size); // Example (without error checking) of using nvs_get_blob to get a binary data into a static array: uint8_t mac_addr[6]; size_t size = sizeof(mac_addr); nvs_get_blob(my_handle, "dst_mac_addr", mac_addr, &size); - Parameters handle -- [in] Handle obtained from nvs_open function. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. out_value -- [out] Pointer to the output value. May be NULL for nvs_get_str and nvs_get_blob, in this case required length will be returned in length argument. length -- [inout] A non-zero pointer to the variable holding the length of out_value. In case out_value a zero, will be set to the length required to hold the value. In case out_value is not zero, will be set to the actual length of the value written. For nvs_get_str this includes zero terminator. - - Returns ESP_OK if the value was retrieved successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_INVALID_LENGTH if lengthis not sufficient to store data - - esp_err_t nvs_get_blob(nvs_handle_t handle, const char *key, void *out_value, size_t *length) get blob value for given key This function behaves the same as nvs_get_str, except for the data type. - esp_err_t nvs_open(const char *namespace_name, nvs_open_mode_t open_mode, nvs_handle_t *out_handle) Open non-volatile storage with a given namespace from the default NVS partition. Multiple internal ESP-IDF and third party application modules can store their key-value pairs in the NVS module. In order to reduce possible conflicts on key names, each module can use its own namespace. The default NVS partition is the one that is labelled "nvs" in the partition table. - Parameters namespace_name -- [in] Namespace name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. open_mode -- [in] NVS_READWRITE or NVS_READONLY. If NVS_READONLY, will open a handle for reading only. All write requests will be rejected for this handle. out_handle -- [out] If successful (return code is zero), handle will be returned in this argument. - - Returns ESP_OK if storage handle was opened successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized ESP_ERR_NVS_PART_NOT_FOUND if the partition with label "nvs" is not found ESP_ERR_NVS_NOT_FOUND id namespace doesn't exist yet and mode is NVS_READONLY ESP_ERR_NVS_INVALID_NAME if namespace name doesn't satisfy constraints ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is no space for a new entry or there are too many different namespaces (maximum allowed different namespaces: 254) ESP_ERR_NOT_ALLOWED if the NVS partition is read-only and mode is NVS_READWRITE ESP_ERR_INVALID_ARG if out_handle is equal to NULL other error codes from the underlying storage driver - - esp_err_t nvs_open_from_partition(const char *part_name, const char *namespace_name, nvs_open_mode_t open_mode, nvs_handle_t *out_handle) Open non-volatile storage with a given namespace from specified partition. The behaviour is same as nvs_open() API. However this API can operate on a specified NVS partition instead of default NVS partition. Note that the specified partition must be registered with NVS using nvs_flash_init_partition() API. - Parameters part_name -- [in] Label (name) of the partition of interest for object read/write/erase namespace_name -- [in] Namespace name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. open_mode -- [in] NVS_READWRITE or NVS_READONLY. If NVS_READONLY, will open a handle for reading only. All write requests will be rejected for this handle. out_handle -- [out] If successful (return code is zero), handle will be returned in this argument. - - Returns ESP_OK if storage handle was opened successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized ESP_ERR_NVS_PART_NOT_FOUND if the partition with specified name is not found ESP_ERR_NVS_NOT_FOUND id namespace doesn't exist yet and mode is NVS_READONLY ESP_ERR_NVS_INVALID_NAME if namespace name doesn't satisfy constraints ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is no space for a new entry or there are too many different namespaces (maximum allowed different namespaces: 254) ESP_ERR_NOT_ALLOWED if the NVS partition is read-only and mode is NVS_READWRITE ESP_ERR_INVALID_ARG if out_handle is equal to NULL other error codes from the underlying storage driver - - esp_err_t nvs_set_blob(nvs_handle_t handle, const char *key, const void *value, size_t length) set variable length binary value for given key Sets variable length binary value for the key. Function uses 2 overhead and 1 entry per each 32 bytes of new data from the pool of available entries. See nvs_get_stats. In case of value update for existing key, space occupied by the existing value and 2 overhead entries are returned to the pool of available entries. Note that the underlying storage will not be updated until nvs_commitis called. - Parameters handle -- [in] Handle obtained from nvs_open function. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. value -- [in] The value to set. length -- [in] length of binary value to set, in bytes; Maximum length is 508000 bytes or (97.6% of the partition size - 4000) bytes whichever is lower. - - Returns ESP_OK if value was set successfully ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the underlying storage to save the value ESP_ERR_NVS_REMOVE_FAILED if the value wasn't updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn't fail again. ESP_ERR_NVS_VALUE_TOO_LONG if the value is too long - - esp_err_t nvs_find_key(nvs_handle_t handle, const char *key, nvs_type_t *out_type) Lookup key-value pair with given key name. Note that function may indicate both existence of the key as well as the data type of NVS entry if it is found. - Parameters handle -- [in] Storage handle obtained with nvs_open. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. out_type -- [out] Pointer to the output variable populated with data type of NVS entry in case key was found. May be NULL, respective data type is then not provided. - - Returns ESP_OK if NVS entry for key provided was found ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) other error codes from the underlying storage driver - - esp_err_t nvs_erase_key(nvs_handle_t handle, const char *key) Erase key-value pair with given key name. Note that actual storage may not be updated until nvs_commit function is called. - Parameters handle -- [in] Storage handle obtained with nvs_open. Handles that were opened read only cannot be used. key -- [in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty. - - Returns ESP_OK if erase operation was successful ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if handle was opened as read only ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist other error codes from the underlying storage driver - - esp_err_t nvs_erase_all(nvs_handle_t handle) Erase all key-value pairs in a namespace. Note that actual storage may not be updated until nvs_commit function is called. - Parameters handle -- [in] Storage handle obtained with nvs_open. Handles that were opened read only cannot be used. - Returns ESP_OK if erase operation was successful ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only if NVS assertion checks are disabled) ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL ESP_ERR_NVS_READ_ONLY if handle was opened as read only other error codes from the underlying storage driver - - esp_err_t nvs_commit(nvs_handle_t handle) Write any pending changes to non-volatile storage. After setting any values, nvs_commit() must be called to ensure changes are written to non-volatile storage. Individual implementations may write to storage at other times, but this is not guaranteed. - Parameters handle -- [in] Storage handle obtained with nvs_open. Handles that were opened read only cannot be used. - Returns ESP_OK if the changes have been written successfully ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL other error codes from the underlying storage driver - - void nvs_close(nvs_handle_t handle) Close the storage handle and free any allocated resources. This function should be called for each handle opened with nvs_open once the handle is not in use any more. Closing the handle may not automatically write the changes to nonvolatile storage. This has to be done explicitly using nvs_commit function. Once this function is called on a handle, the handle should no longer be used. - Parameters handle -- [in] Storage handle to close - esp_err_t nvs_get_stats(const char *part_name, nvs_stats_t *nvs_stats) Fill structure nvs_stats_t. It provides info about memory used by NVS. This function calculates the number of used entries, free entries, available entries, total entries and number of namespaces in partition. // Example of nvs_get_stats() to get overview of actual statistics of data entries : nvs_stats_t nvs_stats; nvs_get_stats(NULL, &nvs_stats); printf("Count: UsedEntries = (%lu), FreeEntries = (%lu), AvailableEntries = (%lu), AllEntries = (%lu)\n", nvs_stats.used_entries, nvs_stats.free_entries, nvs_stats.available_entries, nvs_stats.total_entries); - Parameters part_name -- [in] Partition name NVS in the partition table. If pass a NULL than will use NVS_DEFAULT_PART_NAME ("nvs"). nvs_stats -- [out] Returns filled structure nvs_states_t. It provides info about used memory the partition. - - Returns ESP_OK if the changes have been written successfully. Return param nvs_stats will be filled. ESP_ERR_NVS_PART_NOT_FOUND if the partition with label "name" is not found. Return param nvs_stats will be filled 0. ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized. Return param nvs_stats will be filled 0. ESP_ERR_INVALID_ARG if nvs_stats is equal to NULL. ESP_ERR_INVALID_STATE if there is page with the status of INVALID. Return param nvs_stats will be filled not with correct values because not all pages will be counted. Counting will be interrupted at the first INVALID page. - - esp_err_t nvs_get_used_entry_count(nvs_handle_t handle, size_t *used_entries) Calculate all entries in a namespace. An entry represents the smallest storage unit in NVS. Strings and blobs may occupy more than one entry. Note that to find out the total number of entries occupied by the namespace, add one to the returned value used_entries (if err is equal to ESP_OK). Because the name space entry takes one entry. // Example of nvs_get_used_entry_count() to get amount of all key-value pairs in one namespace: nvs_handle_t handle; nvs_open("namespace1", NVS_READWRITE, &handle); ... size_t used_entries; size_t total_entries_namespace; if(nvs_get_used_entry_count(handle, &used_entries) == ESP_OK){ // the total number of entries occupied by the namespace total_entries_namespace = used_entries + 1; } - Parameters handle -- [in] Handle obtained from nvs_open function. used_entries -- [out] Returns amount of used entries from a namespace. - - Returns ESP_OK if the changes have been written successfully. Return param used_entries will be filled valid value. ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized. Return param used_entries will be filled 0. ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL. Return param used_entries will be filled 0. ESP_ERR_INVALID_ARG if used_entries is equal to NULL. Other error codes from the underlying storage driver. Return param used_entries will be filled 0. - - esp_err_t nvs_entry_find(const char *part_name, const char *namespace_name, nvs_type_t type, nvs_iterator_t *output_iterator) Create an iterator to enumerate NVS entries based on one or more parameters. // Example of listing all the key-value pairs of any type under specified partition and namespace nvs_iterator_t it = NULL; esp_err_t res = nvs_entry_find(<nvs_partition_name>, <namespace>, NVS_TYPE_ANY, &it); while(res == ESP_OK) { nvs_entry_info_t info; nvs_entry_info(it, &info); // Can omit error check if parameters are guaranteed to be non-NULL printf("key '%s', type '%d' \n", info.key, info.type); res = nvs_entry_next(&it); } nvs_release_iterator(it); - Parameters part_name -- [in] Partition name namespace_name -- [in] Set this value if looking for entries with a specific namespace. Pass NULL otherwise. type -- [in] One of nvs_type_t values. output_iterator -- [out] Set to a valid iterator to enumerate all the entries found. Set to NULL if no entry for specified criteria was found. If any other error except ESP_ERR_INVALID_ARG occurs, output_iteratoris NULL, too. If ESP_ERR_INVALID_ARG occurs, output_iteratoris not changed. If a valid iterator is obtained through this function, it has to be released using nvs_release_iteratorwhen not used any more, unless ESP_ERR_INVALID_ARG is returned. - - Returns ESP_OK if no internal error or programming error occurred. ESP_ERR_NVS_NOT_FOUND if no element of specified criteria has been found. ESP_ERR_NO_MEM if memory has been exhausted during allocation of internal structures. ESP_ERR_INVALID_ARG if any of the parameters is NULL. Note: don't release output_iteratorin case ESP_ERR_INVALID_ARG has been returned - - esp_err_t nvs_entry_find_in_handle(nvs_handle_t handle, nvs_type_t type, nvs_iterator_t *output_iterator) Create an iterator to enumerate NVS entries based on a handle and type. // Example of listing all the key-value pairs of any type under specified handle (which defines a partition and namespace) nvs_iterator_t it = NULL; esp_err_t res = nvs_entry_find_in_handle(<nvs_handle>, NVS_TYPE_ANY, &it); while(res == ESP_OK) { nvs_entry_info_t info; nvs_entry_info(it, &info); // Can omit error check if parameters are guaranteed to be non-NULL printf("key '%s', type '%d' \n", info.key, info.type); res = nvs_entry_next(&it); } nvs_release_iterator(it); - Parameters handle -- [in] Handle obtained from nvs_open function. type -- [in] One of nvs_type_t values. output_iterator -- [out] Set to a valid iterator to enumerate all the entries found. Set to NULL if no entry for specified criteria was found. If any other error except ESP_ERR_INVALID_ARG occurs, output_iteratoris NULL, too. If ESP_ERR_INVALID_ARG occurs, output_iteratoris not changed. If a valid iterator is obtained through this function, it has to be released using nvs_release_iteratorwhen not used any more, unless ESP_ERR_INVALID_ARG is returned. - - Returns ESP_OK if no internal error or programming error occurred. ESP_ERR_NVS_NOT_FOUND if no element of specified criteria has been found. ESP_ERR_NO_MEM if memory has been exhausted during allocation of internal structures. ESP_ERR_NVS_INVALID_HANDLE if unknown handle was specified. ESP_ERR_INVALID_ARG if output_iterator parameter is NULL. Note: don't release output_iteratorin case ESP_ERR_INVALID_ARG has been returned - - esp_err_t nvs_entry_next(nvs_iterator_t *iterator) Advances the iterator to next item matching the iterator criteria. Note that any copies of the iterator will be invalid after this call. - Parameters iterator -- [inout] Iterator obtained from nvs_entry_find or nvs_entry_find_in_handle function. Must be non-NULL. If any error except ESP_ERR_INVALID_ARG occurs, iteratoris set to NULL. If ESP_ERR_INVALID_ARG occurs, iteratoris not changed. - Returns ESP_OK if no internal error or programming error occurred. ESP_ERR_NVS_NOT_FOUND if no next element matching the iterator criteria. ESP_ERR_INVALID_ARG if iteratoris NULL. Possibly other errors in the future for internal programming or flash errors. - - esp_err_t nvs_entry_info(const nvs_iterator_t iterator, nvs_entry_info_t *out_info) Fills nvs_entry_info_t structure with information about entry pointed to by the iterator. - Parameters iterator -- [in] Iterator obtained from nvs_entry_find or nvs_entry_find_in_handle function. Must be non-NULL. out_info -- [out] Structure to which entry information is copied. - - Returns ESP_OK if all parameters are valid; current iterator data has been written to out_info ESP_ERR_INVALID_ARG if one of the parameters is NULL. - - void nvs_release_iterator(nvs_iterator_t iterator) Release iterator. - Parameters iterator -- [in] Release iterator obtained from nvs_entry_find or nvs_entry_find_in_handle or nvs_entry_next function. NULL argument is allowed. Structures - struct nvs_entry_info_t information about entry obtained from nvs_entry_info function Public Members - char namespace_name[NVS_NS_NAME_MAX_SIZE] Namespace to which key-value belong - char key[NVS_KEY_NAME_MAX_SIZE] Key of stored key-value pair - nvs_type_t type Type of stored key-value pair - char namespace_name[NVS_NS_NAME_MAX_SIZE] - struct nvs_stats_t Note Info about storage space NVS. Public Members - size_t used_entries Number of used entries. - size_t free_entries Number of free entries. It includes also reserved entries. - size_t available_entries Number of entries available for data storage. - size_t total_entries Number of all entries. - size_t namespace_count Number of namespaces. - size_t used_entries Macros - ESP_ERR_NVS_BASE Starting number of error codes - ESP_ERR_NVS_NOT_INITIALIZED The storage driver is not initialized - ESP_ERR_NVS_NOT_FOUND A requested entry couldn't be found or namespace doesn’t exist yet and mode is NVS_READONLY - ESP_ERR_NVS_TYPE_MISMATCH The type of set or get operation doesn't match the type of value stored in NVS - ESP_ERR_NVS_READ_ONLY Storage handle was opened as read only - ESP_ERR_NVS_NOT_ENOUGH_SPACE There is not enough space in the underlying storage to save the value - ESP_ERR_NVS_INVALID_NAME Namespace name doesn’t satisfy constraints - ESP_ERR_NVS_INVALID_HANDLE Handle has been closed or is NULL - ESP_ERR_NVS_REMOVE_FAILED The value wasn’t updated because flash write operation has failed. The value was written however, and update will be finished after re-initialization of nvs, provided that flash operation doesn’t fail again. - ESP_ERR_NVS_KEY_TOO_LONG Key name is too long - ESP_ERR_NVS_PAGE_FULL Internal error; never returned by nvs API functions - ESP_ERR_NVS_INVALID_STATE NVS is in an inconsistent state due to a previous error. Call nvs_flash_init and nvs_open again, then retry. - ESP_ERR_NVS_INVALID_LENGTH String or blob length is not sufficient to store data - ESP_ERR_NVS_NO_FREE_PAGES NVS partition doesn't contain any empty pages. This may happen if NVS partition was truncated. Erase the whole partition and call nvs_flash_init again. - ESP_ERR_NVS_VALUE_TOO_LONG Value doesn't fit into the entry or string or blob length is longer than supported by the implementation - ESP_ERR_NVS_PART_NOT_FOUND Partition with specified name is not found in the partition table - ESP_ERR_NVS_NEW_VERSION_FOUND NVS partition contains data in new format and cannot be recognized by this version of code - ESP_ERR_NVS_XTS_ENCR_FAILED XTS encryption failed while writing NVS entry - ESP_ERR_NVS_XTS_DECR_FAILED XTS decryption failed while reading NVS entry - ESP_ERR_NVS_XTS_CFG_FAILED XTS configuration setting failed - ESP_ERR_NVS_XTS_CFG_NOT_FOUND XTS configuration not found - ESP_ERR_NVS_ENCR_NOT_SUPPORTED NVS encryption is not supported in this version - ESP_ERR_NVS_KEYS_NOT_INITIALIZED NVS key partition is uninitialized - ESP_ERR_NVS_CORRUPT_KEY_PART NVS key partition is corrupt - ESP_ERR_NVS_WRONG_ENCRYPTION NVS partition is marked as encrypted with generic flash encryption. This is forbidden since the NVS encryption works differently. - ESP_ERR_NVS_CONTENT_DIFFERS Internal error; never returned by nvs API functions. NVS key is different in comparison - NVS_DEFAULT_PART_NAME Default partition name of the NVS partition in the partition table - NVS_PART_NAME_MAX_SIZE maximum length of partition name (excluding null terminator) - NVS_KEY_NAME_MAX_SIZE Maximum length of NVS key name (including null terminator) - NVS_NS_NAME_MAX_SIZE Maximum length of NVS namespace name (including null terminator) Type Definitions - typedef uint32_t nvs_handle_t Opaque pointer type representing non-volatile storage handle - typedef nvs_handle_t nvs_handle - typedef nvs_open_mode_t nvs_open_mode - typedef struct nvs_opaque_iterator_t *nvs_iterator_t Opaque pointer type representing iterator to nvs entries Enumerations - enum nvs_open_mode_t Mode of opening the non-volatile storage. Values: - enumerator NVS_READONLY Read only - enumerator NVS_READWRITE Read and write - enumerator NVS_READONLY - enum nvs_type_t Types of variables. Values: - enumerator NVS_TYPE_U8 Type uint8_t - enumerator NVS_TYPE_I8 Type int8_t - enumerator NVS_TYPE_U16 Type uint16_t - enumerator NVS_TYPE_I16 Type int16_t - enumerator NVS_TYPE_U32 Type uint32_t - enumerator NVS_TYPE_I32 Type int32_t - enumerator NVS_TYPE_U64 Type uint64_t - enumerator NVS_TYPE_I64 Type int64_t - enumerator NVS_TYPE_STR Type string - enumerator NVS_TYPE_BLOB Type blob - enumerator NVS_TYPE_ANY Must be last - enumerator NVS_TYPE_U8
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/storage/nvs_flash.html
ESP-IDF Programming Guide v5.2.1 documentation
null
NVS Encryption
null
espressif.com
2016-01-01
9e87d40bb27ca9c1
null
null
NVS Encryption Overview This guide provides an overview of the NVS encryption feature. NVS encryption helps to achieve secure storage on the device flash memory. Data stored in NVS partitions can be encrypted using XTS-AES in the manner similar to the one mentioned in disk encryption standard IEEE P1619. For the purpose of encryption, each entry is treated as one sector and relative address of the entry (w.r.t., partition-start) is fed to the encryption algorithm as sector-number . NVS Encryption: Flash Encryption-Based Scheme In this scheme, the keys required for NVS encryption are stored in yet another partition, which is protected using Flash Encryption. Therefore, enabling Flash Encryption becomes a prerequisite for NVS encryption here. NVS encryption is enabled by default when Flash Encryption is enabled. This is done because Wi-Fi driver stores credentials (like SSID and passphrase) in the default NVS partition. It is important to encrypt them as default choice if platform-level encryption is already enabled. For using NVS encryption using this scheme, the partition table must contain the NVS Key Partition. Two partition tables containing the NVS Key Partition are provided for NVS encryption under the partition table option ( menuconfig > Partition Table ). They can be selected with the project configuration menu ( idf.py menuconfig ). Please refer to the example security/flash_encryption for how to configure and use the NVS encryption feature. NVS Key Partition An application requiring NVS encryption support (using the Flash Encryption-based scheme) needs to be compiled with a key-partition of the type data and subtype key . This partition should be marked as encrypted and its size should be the minimum partition size (4 KB). Refer to Partition Tables for more details. Two additional partition tables which contain the NVS Key Partition are provided under the partition table option ( menuconfig > Partition Table ). They can be directly used for NVS encryption. The structure of these partitions is depicted below: +-----------+--------------+-------------+----+ | XTS encryption key (32) | +---------------------------------------------+ | XTS tweak key (32) | +---------------------------------------------+ | CRC32 (4) | +---------------------------------------------+ The XTS encryption keys in the NVS Key Partition can be generated in one of the following two ways. Generate the keys on ESP32 chip itself When NVS encryption is enabled, the nvs_flash_init() API function can be used to initialize the encrypted default NVS partition. The API function internally generates the XTS encryption keys on the ESP chip. The API function finds the first NVS Key Partition. Then the API function automatically generates and stores the NVS keys in that partition by making use of the nvs_flash_generate_keys() API function provided by nvs_flash/include/nvs_flash.h. New keys are generated and stored only when the respective key partition is empty. The same key partition can then be used to read the security configurations for initializing a custom encrypted NVS partition with help of nvs_flash_secure_init_partition() . The API functions nvs_flash_secure_init() and nvs_flash_secure_init_partition() do not generate the keys internally. When these API functions are used for initializing encrypted NVS partitions, the keys can be generated after startup using the nvs_flash_generate_keys() API function provided by nvs_flash.h . The API function then writes those keys onto the key-partition in encrypted form. Note Please note that nvs_keys partition must be completely erased before you start the application in this approach. Otherwise the application may generate the ESP_ERR_NVS_CORRUPT_KEY_PART error code assuming that nvs_keys partition is not empty and contains malformatted data. You can use the following command for this: parttool.py --port PORT --partition-table-file=PARTITION_TABLE_FILE --partition-table-offset PARTITION_TABLE_OFFSET erase_partition --partition-type=data --partition-subtype=nvs_keys Use a pre-generated NVS key partition This option will be required by the user when keys in the NVS Key Partition are not generated by the application. The NVS Key Partition containing the XTS encryption keys can be generated with the help of NVS Partition Generator Utility. Then the user can store the pre-generated key partition on the flash with help of the following two commands: 1. Build and flash the partition table idf.py partition-table partition-table-flash 2. Store the keys in the NVS Key Partition (on the flash) with the help of parttool.py (see Partition Tool section in partition-tables for more details) parttool.py --port PORT --partition-table-offset PARTITION_TABLE_OFFSET write_partition --partition-name="name of nvs_key partition" --input NVS_KEY_PARTITION_FILE Note If the device is encrypted in flash encryption development mode and you want to renew the NVS key partition, you need to tell parttool.py to encrypt the NVS key partition and you also need to give it a pointer to the unencrypted partition table in your build directory (build/partition_table) since the partition table on the device is encrypted, too. You can use the following command: parttool.py --esptool-write-args encrypt --port PORT --partition-table-file=PARTITION_TABLE_FILE --partition-table-offset PARTITION_TABLE_OFFSET write_partition --partition-name="name of nvs_key partition" --input NVS_KEY_PARTITION_FILE Since the key partition is marked as encrypted and Flash Encryption is enabled, the bootloader will encrypt this partition using flash encryption key on the first boot. It is possible for an application to use different keys for different NVS partitions and thereby have multiple key-partitions. However, it is a responsibility of the application to provide the correct key-partition and keys for encryption or decryption. Encrypted Read/Write The same NVS API functions nvs_get_* or nvs_set_* can be used for reading of, and writing to an encrypted NVS partition as well. Encrypt the default NVS partition To enable encryption for the default NVS partition, no additional step is necessary. When CONFIG_NVS_ENCRYPTION is enabled, the nvs_flash_init() API function internally performs some additional steps to enable encryption for the default NVS partition depending on the scheme being used (set by CONFIG_NVS_SEC_KEY_PROTECTION_SCHEME). For the flash encryption-based scheme, the first NVS Key Partition found is used to generate the encryption keys while for the HMAC one, keys are generated using the HMAC key burnt in eFuse at CONFIG_NVS_SEC_HMAC_EFUSE_KEY_ID (refer to the API documentation for more details). Alternatively, nvs_flash_secure_init() API function can also be used to enable encryption for the default NVS partition. Encrypt a custom NVS partition To enable encryption for a custom NVS partition, nvs_flash_secure_init_partition() API function is used instead of nvs_flash_init_partition() . When nvs_flash_secure_init() and nvs_flash_secure_init_partition() API functions are used, the applications are expected to follow the steps below in order to perform NVS read/write operations with encryption enabled: Populate the NVS security configuration structure nvs_sec_cfg_t For the Flash Encryption-based scheme Find key partition and NVS data partition using esp_partition_find* API functions. Populate the nvs_sec_cfg_t struct using the nvs_flash_read_security_cfg() or nvs_flash_generate_keys() API functions. Find key partition and NVS data partition using esp_partition_find* API functions. Populate the nvs_sec_cfg_t struct using the nvs_flash_read_security_cfg() or nvs_flash_generate_keys() API functions. Find key partition and NVS data partition using esp_partition_find* API functions. For the Flash Encryption-based scheme Find key partition and NVS data partition using esp_partition_find* API functions. Populate the nvs_sec_cfg_t struct using the nvs_flash_read_security_cfg() or nvs_flash_generate_keys() API functions. For the Flash Encryption-based scheme Find key partition and NVS data partition using esp_partition_find* API functions. Populate the nvs_sec_cfg_t struct using the nvs_flash_read_security_cfg() or nvs_flash_generate_keys() API functions. Initialise NVS flash partition using the nvs_flash_secure_init() or nvs_flash_secure_init_partition() API functions. Open a namespace using the nvs_open() or nvs_open_from_partition() API functions. Perform NVS read/write operations using nvs_get_* or nvs_set_* . Deinitialise an NVS partition using nvs_flash_deinit() . Populate the NVS security configuration structure nvs_sec_cfg_t For the Flash Encryption-based scheme Find key partition and NVS data partition using esp_partition_find* API functions. Populate the nvs_sec_cfg_t struct using the nvs_flash_read_security_cfg() or nvs_flash_generate_keys() API functions. Initialise NVS flash partition using the nvs_flash_secure_init() or nvs_flash_secure_init_partition() API functions. Open a namespace using the nvs_open() or nvs_open_from_partition() API functions. Perform NVS read/write operations using nvs_get_* or nvs_set_* . Deinitialise an NVS partition using nvs_flash_deinit() . Populate the NVS security configuration structure nvs_sec_cfg_t For the Flash Encryption-based scheme Find key partition and NVS data partition using esp_partition_find* API functions. Populate the nvs_sec_cfg_t struct using the nvs_flash_read_security_cfg() or nvs_flash_generate_keys() API functions. NVS Security Provider The component nvs_sec_provider stores all the implementation-specific code for the NVS encryption schemes and would also accomodate any future schemes. This component acts as an interface to the nvs_flash component for the handling of encryption keys. nvs_sec_provider has a configuration menu of its own, based on which the selected security scheme and the corresponding settings are registered for the nvs_flash component. API Reference Header File This header file can be included with: #include "nvs_sec_provider.h" This header file is a part of the API provided by the nvs_sec_provider component. To declare that your component depends on nvs_sec_provider , add the following to your CMakeLists.txt: REQUIRES nvs_sec_provider or PRIV_REQUIRES nvs_sec_provider Functions esp_err_t nvs_sec_provider_register_flash_enc(const nvs_sec_config_flash_enc_t *sec_scheme_cfg, nvs_sec_scheme_t **sec_scheme_handle_out) Register the Flash-Encryption based scheme for NVS Encryption. Parameters sec_scheme_cfg -- [in] Security scheme specific configuration data sec_scheme_handle_out -- [out] Security scheme specific configuration handle sec_scheme_cfg -- [in] Security scheme specific configuration data sec_scheme_handle_out -- [out] Security scheme specific configuration handle sec_scheme_cfg -- [in] Security scheme specific configuration data Returns ESP_OK, if sec_scheme_handle_out was populated successfully with the scheme configuration; ESP_ERR_INVALID_ARG, if scheme_cfg_hmac is NULL; ESP_ERR_NO_MEM, No memory for the scheme-specific handle sec_scheme_handle_out ESP_ERR_NOT_FOUND, if no nvs_keys partition is found ESP_OK, if sec_scheme_handle_out was populated successfully with the scheme configuration; ESP_ERR_INVALID_ARG, if scheme_cfg_hmac is NULL; ESP_ERR_NO_MEM, No memory for the scheme-specific handle sec_scheme_handle_out ESP_ERR_NOT_FOUND, if no nvs_keys partition is found ESP_OK, if sec_scheme_handle_out was populated successfully with the scheme configuration; Parameters sec_scheme_cfg -- [in] Security scheme specific configuration data sec_scheme_handle_out -- [out] Security scheme specific configuration handle Returns ESP_OK, if sec_scheme_handle_out was populated successfully with the scheme configuration; ESP_ERR_INVALID_ARG, if scheme_cfg_hmac is NULL; ESP_ERR_NO_MEM, No memory for the scheme-specific handle sec_scheme_handle_out ESP_ERR_NOT_FOUND, if no nvs_keys partition is found esp_err_t nvs_sec_provider_deregister(nvs_sec_scheme_t *sec_scheme_handle) Deregister the NVS encryption scheme registered with the given handle. Parameters sec_scheme_handle -- [in] Security scheme specific configuration handle Returns ESP_OK, if the scheme registered with sec_scheme_handle was deregistered successfully ESP_ERR_INVALID_ARG, if sec_scheme_handle is NULL; ESP_OK, if the scheme registered with sec_scheme_handle was deregistered successfully ESP_ERR_INVALID_ARG, if sec_scheme_handle is NULL; ESP_OK, if the scheme registered with sec_scheme_handle was deregistered successfully Parameters sec_scheme_handle -- [in] Security scheme specific configuration handle Returns ESP_OK, if the scheme registered with sec_scheme_handle was deregistered successfully ESP_ERR_INVALID_ARG, if sec_scheme_handle is NULL; Structures struct nvs_sec_config_flash_enc_t Flash encryption-based scheme specific configuration data. Public Members const esp_partition_t *nvs_keys_part Partition of subtype nvs_keys holding the NVS encryption keys const esp_partition_t *nvs_keys_part Partition of subtype nvs_keys holding the NVS encryption keys const esp_partition_t *nvs_keys_part Macros ESP_ERR_NVS_SEC_BASE Starting number of error codes ESP_ERR_NVS_SEC_HMAC_KEY_NOT_FOUND HMAC Key required to generate the NVS encryption keys not found ESP_ERR_NVS_SEC_HMAC_KEY_BLK_ALREADY_USED Provided eFuse block for HMAC key generation is already in use ESP_ERR_NVS_SEC_HMAC_KEY_GENERATION_FAILED Failed to generate/write the HMAC key to eFuse ESP_ERR_NVS_SEC_HMAC_XTS_KEYS_DERIV_FAILED Failed to derive the NVS encryption keys based on the HMAC-based scheme NVS_SEC_PROVIDER_CFG_FLASH_ENC_DEFAULT() Helper for populating the Flash encryption-based scheme specific configuration data.
NVS Encryption Overview This guide provides an overview of the NVS encryption feature. NVS encryption helps to achieve secure storage on the device flash memory. Data stored in NVS partitions can be encrypted using XTS-AES in the manner similar to the one mentioned in disk encryption standard IEEE P1619. For the purpose of encryption, each entry is treated as one sector and relative address of the entry (w.r.t., partition-start) is fed to the encryption algorithm as sector-number. NVS Encryption: Flash Encryption-Based Scheme In this scheme, the keys required for NVS encryption are stored in yet another partition, which is protected using Flash Encryption. Therefore, enabling Flash Encryption becomes a prerequisite for NVS encryption here. NVS encryption is enabled by default when Flash Encryption is enabled. This is done because Wi-Fi driver stores credentials (like SSID and passphrase) in the default NVS partition. It is important to encrypt them as default choice if platform-level encryption is already enabled. For using NVS encryption using this scheme, the partition table must contain the NVS Key Partition. Two partition tables containing the NVS Key Partition are provided for NVS encryption under the partition table option ( menuconfig > Partition Table). They can be selected with the project configuration menu ( idf.py menuconfig). Please refer to the example security/flash_encryption for how to configure and use the NVS encryption feature. NVS Key Partition An application requiring NVS encryption support (using the Flash Encryption-based scheme) needs to be compiled with a key-partition of the type data and subtype key. This partition should be marked as encrypted and its size should be the minimum partition size (4 KB). Refer to Partition Tables for more details. Two additional partition tables which contain the NVS Key Partition are provided under the partition table option ( menuconfig > Partition Table). They can be directly used for NVS encryption. The structure of these partitions is depicted below: +-----------+--------------+-------------+----+ | XTS encryption key (32) | +---------------------------------------------+ | XTS tweak key (32) | +---------------------------------------------+ | CRC32 (4) | +---------------------------------------------+ The XTS encryption keys in the NVS Key Partition can be generated in one of the following two ways. Generate the keys on ESP32 chip itself - When NVS encryption is enabled, the nvs_flash_init()API function can be used to initialize the encrypted default NVS partition. The API function internally generates the XTS encryption keys on the ESP chip. The API function finds the first NVS Key Partition. - Then the API function automatically generates and stores the NVS keys in that partition by making use of the nvs_flash_generate_keys()API function provided by nvs_flash/include/nvs_flash.h. New keys are generated and stored only when the respective key partition is empty. The same key partition can then be used to read the security configurations for initializing a custom encrypted NVS partition with help of nvs_flash_secure_init_partition(). - The API functions nvs_flash_secure_init()and nvs_flash_secure_init_partition()do not generate the keys internally. When these API functions are used for initializing encrypted NVS partitions, the keys can be generated after startup using the nvs_flash_generate_keys()API function provided by nvs_flash.h. The API function then writes those keys onto the key-partition in encrypted form. Note Please note that nvs_keyspartition must be completely erased before you start the application in this approach. Otherwise the application may generate the ESP_ERR_NVS_CORRUPT_KEY_PARTerror code assuming that nvs_keyspartition is not empty and contains malformatted data. You can use the following command for this:parttool.py --port PORT --partition-table-file=PARTITION_TABLE_FILE --partition-table-offset PARTITION_TABLE_OFFSET erase_partition --partition-type=data --partition-subtype=nvs_keys Use a pre-generated NVS key partition This option will be required by the user when keys in the NVS Key Partition are not generated by the application. The NVS Key Partition containing the XTS encryption keys can be generated with the help of NVS Partition Generator Utility. Then the user can store the pre-generated key partition on the flash with help of the following two commands: 1. Build and flash the partition tableidf.py partition-table partition-table-flash 2. Store the keys in the NVS Key Partition (on the flash) with the help of parttool.py (see Partition Tool section in partition-tables for more details)parttool.py --port PORT --partition-table-offset PARTITION_TABLE_OFFSET write_partition --partition-name="name of nvs_key partition" --input NVS_KEY_PARTITION_FILE Note If the device is encrypted in flash encryption development mode and you want to renew the NVS key partition, you need to tell parttool.py to encrypt the NVS key partition and you also need to give it a pointer to the unencrypted partition table in your build directory (build/partition_table) since the partition table on the device is encrypted, too. You can use the following command:parttool.py --esptool-write-args encrypt --port PORT --partition-table-file=PARTITION_TABLE_FILE --partition-table-offset PARTITION_TABLE_OFFSET write_partition --partition-name="name of nvs_key partition" --input NVS_KEY_PARTITION_FILE Since the key partition is marked as encrypted and Flash Encryption is enabled, the bootloader will encrypt this partition using flash encryption key on the first boot. It is possible for an application to use different keys for different NVS partitions and thereby have multiple key-partitions. However, it is a responsibility of the application to provide the correct key-partition and keys for encryption or decryption. Encrypted Read/Write The same NVS API functions nvs_get_* or nvs_set_* can be used for reading of, and writing to an encrypted NVS partition as well. Encrypt the default NVS partition To enable encryption for the default NVS partition, no additional step is necessary. When CONFIG_NVS_ENCRYPTION is enabled, the nvs_flash_init()API function internally performs some additional steps to enable encryption for the default NVS partition depending on the scheme being used (set by CONFIG_NVS_SEC_KEY_PROTECTION_SCHEME). For the flash encryption-based scheme, the first NVS Key Partition found is used to generate the encryption keys while for the HMAC one, keys are generated using the HMAC key burnt in eFuse at CONFIG_NVS_SEC_HMAC_EFUSE_KEY_ID (refer to the API documentation for more details). Alternatively, nvs_flash_secure_init() API function can also be used to enable encryption for the default NVS partition. Encrypt a custom NVS partition To enable encryption for a custom NVS partition, nvs_flash_secure_init_partition()API function is used instead of nvs_flash_init_partition(). When nvs_flash_secure_init()and nvs_flash_secure_init_partition()API functions are used, the applications are expected to follow the steps below in order to perform NVS read/write operations with encryption enabled: Populate the NVS security configuration structure nvs_sec_cfg_t For the Flash Encryption-based scheme Find key partition and NVS data partition using esp_partition_find*API functions. Populate the nvs_sec_cfg_tstruct using the nvs_flash_read_security_cfg()or nvs_flash_generate_keys()API functions. - - Initialise NVS flash partition using the nvs_flash_secure_init()or nvs_flash_secure_init_partition()API functions. Open a namespace using the nvs_open()or nvs_open_from_partition()API functions. Perform NVS read/write operations using nvs_get_*or nvs_set_*. Deinitialise an NVS partition using nvs_flash_deinit(). - NVS Security Provider The component nvs_sec_provider stores all the implementation-specific code for the NVS encryption schemes and would also accomodate any future schemes. This component acts as an interface to the nvs_flash component for the handling of encryption keys. nvs_sec_provider has a configuration menu of its own, based on which the selected security scheme and the corresponding settings are registered for the nvs_flash component. API Reference Header File This header file can be included with: #include "nvs_sec_provider.h" This header file is a part of the API provided by the nvs_sec_providercomponent. To declare that your component depends on nvs_sec_provider, add the following to your CMakeLists.txt: REQUIRES nvs_sec_provider or PRIV_REQUIRES nvs_sec_provider Functions - esp_err_t nvs_sec_provider_register_flash_enc(const nvs_sec_config_flash_enc_t *sec_scheme_cfg, nvs_sec_scheme_t **sec_scheme_handle_out) Register the Flash-Encryption based scheme for NVS Encryption. - Parameters sec_scheme_cfg -- [in] Security scheme specific configuration data sec_scheme_handle_out -- [out] Security scheme specific configuration handle - - Returns ESP_OK, if sec_scheme_handle_outwas populated successfully with the scheme configuration; ESP_ERR_INVALID_ARG, if scheme_cfg_hmacis NULL; ESP_ERR_NO_MEM, No memory for the scheme-specific handle sec_scheme_handle_out ESP_ERR_NOT_FOUND, if no nvs_keyspartition is found - - esp_err_t nvs_sec_provider_deregister(nvs_sec_scheme_t *sec_scheme_handle) Deregister the NVS encryption scheme registered with the given handle. - Parameters sec_scheme_handle -- [in] Security scheme specific configuration handle - Returns ESP_OK, if the scheme registered with sec_scheme_handlewas deregistered successfully ESP_ERR_INVALID_ARG, if sec_scheme_handleis NULL; - Structures - struct nvs_sec_config_flash_enc_t Flash encryption-based scheme specific configuration data. Public Members - const esp_partition_t *nvs_keys_part Partition of subtype nvs_keysholding the NVS encryption keys - const esp_partition_t *nvs_keys_part Macros - ESP_ERR_NVS_SEC_BASE Starting number of error codes - ESP_ERR_NVS_SEC_HMAC_KEY_NOT_FOUND HMAC Key required to generate the NVS encryption keys not found - ESP_ERR_NVS_SEC_HMAC_KEY_BLK_ALREADY_USED Provided eFuse block for HMAC key generation is already in use - ESP_ERR_NVS_SEC_HMAC_KEY_GENERATION_FAILED Failed to generate/write the HMAC key to eFuse - ESP_ERR_NVS_SEC_HMAC_XTS_KEYS_DERIV_FAILED Failed to derive the NVS encryption keys based on the HMAC-based scheme - NVS_SEC_PROVIDER_CFG_FLASH_ENC_DEFAULT() Helper for populating the Flash encryption-based scheme specific configuration data.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/storage/nvs_encryption.html
ESP-IDF Programming Guide v5.2.1 documentation
null
NVS Partition Generator Utility
null
espressif.com
2016-01-01
be9d381b84c71ac0
null
null
NVS Partition Generator Utility Introduction The utility nvs_flash/nvs_partition_generator/nvs_partition_gen.py creates a binary file, compatible with the NVS architecture defined in Non-Volatile Storage Library, based on the key-value pairs provided in a CSV file. This utility is ideally suited for generating a binary blob, containing data specific to ODM/OEM, which can be flashed externally at the time of device manufacturing. This allows manufacturers to generate many instances of the same application firmware with customized parameters for each device, such as a serial number. Prerequisites To use this utility in encryption mode, install the following packages: cryptography cryptography cryptography All the required packages are included in requirements.txt in the root of the ESP-IDF directory. CSV File Format Each line of a CSV file should contain 4 parameters, separated by a comma. The table below describes each of these parameters. No. Parameter Description Notes 1 Key Key of the data. The data can be accessed later from an application using this key. 2 Type Supported values are 3 Encoding Supported values are: As of now, for the 4 Value Data value Note The first line of the CSV file should always be the column header and it is not configurable. Below is an example dump of such a CSV file: key,type,encoding,value <-- column header namespace_name,namespace,, <-- First entry should be of type "namespace" key1,data,u8,1 key2,file,string,/path/to/file Note Make sure there are no spaces: before and after ',' at the end of each line in a CSV file before and after ',' at the end of each line in a CSV file before and after ',' NVS Entry and Namespace Association When a namespace entry is encountered in a CSV file, each following entry will be treated as part of that namespace until the next namespace entry is found. At this point, all the following entries will be treated as part of the new namespace. Note First entry in a CSV file should always be a namespace entry. Multipage Blob Support By default, binary blobs are allowed to span over multiple pages and are written in the format mentioned in Section Structure of Entry. If you intend to use the older format, the utility provides an option to disable this feature. Encryption-Decryption Support The NVS Partition Generator utility also allows you to create an encrypted binary file and decrypt an encrypted one. The utility uses the XTS-AES encryption. Please refer to NVS Encryption for more details. Running the Utility Usage: python nvs_partition_gen.py [-h] {generate,generate-key,encrypt,decrypt} ... Optional Arguments: No. Parameter Description 1 Show the help message and exit Commands: Run nvs_partition_gen.py {command} -h for additional help No. Parameter Description 1 Generate NVS partition 2 Generate keys for encryption 3 Generate NVS encrypted partition 4 Decrypt NVS encrypted partition Generate NVS Partition (Default) Usage: python nvs_partition_gen.py generate [-h] [--version {1,2}] [--outdir OUTDIR] input output size Positional Arguments: Parameter Description Path to CSV file to parse Path to output NVS binary file Size of NVS partition in bytes (must be multiple of 4096) Optional Arguments: Parameter Description Show the help message and exit Set multipage blob version (Default: Version 2) Version 1 - Multipage blob support disabled Version 2 - Multipage blob support enabled Output directory to store file created (Default: current directory) You can run the utility to generate NVS partition using the command below. A sample CSV file is provided with the utility: python nvs_partition_gen.py generate sample_singlepage_blob.csv sample.bin 0x3000 Generate Encryption Keys Partition Usage: python nvs_partition_gen.py generate-key [-h] [--keyfile KEYFILE] [--outdir OUTDIR] Optional Arguments: Parameter Description Show the help message and exit Path to output encryption keys file Output directory to store files created. (Default: current directory) You can run the utility to generate only the encryption key partition using the command below: python nvs_partition_gen.py generate-key Generate Encrypted NVS Partition Usage: python nvs_partition_gen.py encrypt [-h] [--version {1,2}] [--keygen] [--keyfile KEYFILE] [--inputkey INPUTKEY] [--outdir OUTDIR] input output size Positional Arguments: Parameter Description Path to CSV file to parse Path to output NVS binary file Size of NVS partition in bytes (must be multiple of 4096) Optional Arguments: Parameter Description Show the help message and exit Set multipage blob version (Default: Version 2) Version 1 - Multipage blob support disabled Version 2 - Multipage blob support enabled Generates key for encrypting NVS partition Path to output encryption keys file File having key for encrypting NVS partition Output directory to store file created (Default: current directory) You can run the utility to encrypt NVS partition using the command below. A sample CSV file is provided with the utility: Encrypt by allowing the utility to generate encryption keys: python nvs_partition_gen.py encrypt sample_singlepage_blob.csv sample_encr.bin 0x3000 --keygen Note Encryption key of the format <outdir>/keys/keys-<timestamp>.bin is created. Encrypt by allowing the utility to generate encryption keys and store it in provided custom filename: python nvs_partition_gen.py encrypt sample_singlepage_blob.csv sample_encr.bin 0x3000 --keygen --keyfile sample_keys.bin Note Encryption key of the format <outdir>/keys/sample_keys.bin is created. This newly created file having encryption keys in keys/ directory is compatible with NVS key-partition structure. Refer to NVS Key Partition for more details. Encrypt by providing the encryption keys as input binary file: python nvs_partition_gen.py encrypt sample_singlepage_blob.csv sample_encr.bin 0x3000 --inputkey sample_keys.bin Decrypt Encrypted NVS Partition Usage: python nvs_partition_gen.py decrypt [-h] [--outdir OUTDIR] input key output Positional Arguments: Parameter Description Path to encrypted NVS partition file to parse Path to file having keys for decryption Path to output decrypted binary file Optional Arguments: Parameter Description Show the help message and exit Output directory to store files created. (Default: current directory) You can run the utility to decrypt encrypted NVS partition using the command below: python nvs_partition_gen.py decrypt sample_encr.bin sample_keys.bin sample_decr.bin You can also provide the format version number: Multipage blob support disabled (Version 1) Multipage blob support enabled (Version 2) Multipage blob support disabled (Version 1) Multipage blob support enabled (Version 2) Multipage blob support disabled (Version 1) Multipage Blob Support Disabled (Version 1) You can run the utility in this format by setting the version parameter to 1, as shown below. A sample CSV file for the same is provided with the utility: python nvs_partition_gen.py generate sample_singlepage_blob.csv sample.bin 0x3000 --version 1 Multipage Blob Support Enabled (Version 2) You can run the utility in this format by setting the version parameter to 2, as shown below. A sample CSV file for the same is provided with the utility: python nvs_partition_gen.py generate sample_multipage_blob.csv sample.bin 0x4000 --version 2 Note Minimum NVS Partition Size needed is 0x3000 bytes. When flashing the binary onto the device, make sure it is consistent with the application's sdkconfig. Caveats Utility does not check for duplicate keys and will write data pertaining to both keys. You need to make sure that the keys are distinct. Once a new page is created, no data will be written in the space left on the previous page. Fields in the CSV file need to be ordered in such a way as to optimize memory. 64-bit datatype is not yet supported.
NVS Partition Generator Utility Introduction The utility nvs_flash/nvs_partition_generator/nvs_partition_gen.py creates a binary file, compatible with the NVS architecture defined in Non-Volatile Storage Library, based on the key-value pairs provided in a CSV file. This utility is ideally suited for generating a binary blob, containing data specific to ODM/OEM, which can be flashed externally at the time of device manufacturing. This allows manufacturers to generate many instances of the same application firmware with customized parameters for each device, such as a serial number. Prerequisites - To use this utility in encryption mode, install the following packages: cryptography - All the required packages are included in requirements.txt in the root of the ESP-IDF directory. CSV File Format Each line of a CSV file should contain 4 parameters, separated by a comma. The table below describes each of these parameters. | No. | Parameter | Description | Notes | 1 | Key | Key of the data. The data can be accessed later from an application using this key. | 2 | Type | Supported values are | 3 | Encoding | Supported values are: | As of now, for the | 4 | Value | Data value | Note The first line of the CSV file should always be the column header and it is not configurable. Below is an example dump of such a CSV file: key,type,encoding,value <-- column header namespace_name,namespace,, <-- First entry should be of type "namespace" key1,data,u8,1 key2,file,string,/path/to/file Note - Make sure there are no spaces: before and after ',' at the end of each line in a CSV file - NVS Entry and Namespace Association When a namespace entry is encountered in a CSV file, each following entry will be treated as part of that namespace until the next namespace entry is found. At this point, all the following entries will be treated as part of the new namespace. Note First entry in a CSV file should always be a namespace entry. Multipage Blob Support By default, binary blobs are allowed to span over multiple pages and are written in the format mentioned in Section Structure of Entry. If you intend to use the older format, the utility provides an option to disable this feature. Encryption-Decryption Support The NVS Partition Generator utility also allows you to create an encrypted binary file and decrypt an encrypted one. The utility uses the XTS-AES encryption. Please refer to NVS Encryption for more details. Running the Utility Usage: python nvs_partition_gen.py [-h] {generate,generate-key,encrypt,decrypt} ... Optional Arguments: | No. | Parameter | Description | 1 | | Show the help message and exit Commands: Run nvs_partition_gen.py {command} -hfor additional help | No. | Parameter | Description | 1 | | Generate NVS partition | 2 | | Generate keys for encryption | 3 | | Generate NVS encrypted partition | 4 | | Decrypt NVS encrypted partition Generate NVS Partition (Default) Usage: python nvs_partition_gen.py generate [-h] [--version {1,2}] [--outdir OUTDIR] input output size Positional Arguments: | Parameter | Description | | Path to CSV file to parse | | Path to output NVS binary file | | Size of NVS partition in bytes (must be multiple of 4096) Optional Arguments: | Parameter | Description | | Show the help message and exit | | Set multipage blob version (Default: Version 2) Version 1 - Multipage blob support disabled Version 2 - Multipage blob support enabled | | Output directory to store file created (Default: current directory) You can run the utility to generate NVS partition using the command below. A sample CSV file is provided with the utility: python nvs_partition_gen.py generate sample_singlepage_blob.csv sample.bin 0x3000 Generate Encryption Keys Partition Usage: python nvs_partition_gen.py generate-key [-h] [--keyfile KEYFILE] [--outdir OUTDIR] Optional Arguments: | Parameter | Description | | Show the help message and exit | | Path to output encryption keys file | | Output directory to store files created. (Default: current directory) You can run the utility to generate only the encryption key partition using the command below: python nvs_partition_gen.py generate-key Generate Encrypted NVS Partition Usage: python nvs_partition_gen.py encrypt [-h] [--version {1,2}] [--keygen] [--keyfile KEYFILE] [--inputkey INPUTKEY] [--outdir OUTDIR] input output size Positional Arguments: | Parameter | Description | | Path to CSV file to parse | | Path to output NVS binary file | | Size of NVS partition in bytes (must be multiple of 4096) Optional Arguments: | Parameter | Description | | Show the help message and exit | | Set multipage blob version (Default: Version 2) Version 1 - Multipage blob support disabled Version 2 - Multipage blob support enabled | | Generates key for encrypting NVS partition | | Path to output encryption keys file | | File having key for encrypting NVS partition | | Output directory to store file created (Default: current directory) You can run the utility to encrypt NVS partition using the command below. A sample CSV file is provided with the utility: Encrypt by allowing the utility to generate encryption keys: python nvs_partition_gen.py encrypt sample_singlepage_blob.csv sample_encr.bin 0x3000 --keygen Note Encryption key of the format <outdir>/keys/keys-<timestamp>.binis created. Encrypt by allowing the utility to generate encryption keys and store it in provided custom filename: python nvs_partition_gen.py encrypt sample_singlepage_blob.csv sample_encr.bin 0x3000 --keygen --keyfile sample_keys.bin Note Encryption key of the format <outdir>/keys/sample_keys.binis created. This newly created file having encryption keys in keys/directory is compatible with NVS key-partition structure. Refer to NVS Key Partition for more details. Encrypt by providing the encryption keys as input binary file: python nvs_partition_gen.py encrypt sample_singlepage_blob.csv sample_encr.bin 0x3000 --inputkey sample_keys.bin Decrypt Encrypted NVS Partition Usage: python nvs_partition_gen.py decrypt [-h] [--outdir OUTDIR] input key output Positional Arguments: | Parameter | Description | | Path to encrypted NVS partition file to parse | | Path to file having keys for decryption | | Path to output decrypted binary file Optional Arguments: | Parameter | Description | | Show the help message and exit | | Output directory to store files created. (Default: current directory) You can run the utility to decrypt encrypted NVS partition using the command below: python nvs_partition_gen.py decrypt sample_encr.bin sample_keys.bin sample_decr.bin - You can also provide the format version number: Multipage blob support disabled (Version 1) Multipage blob support enabled (Version 2) - Multipage Blob Support Disabled (Version 1) You can run the utility in this format by setting the version parameter to 1, as shown below. A sample CSV file for the same is provided with the utility: python nvs_partition_gen.py generate sample_singlepage_blob.csv sample.bin 0x3000 --version 1 Multipage Blob Support Enabled (Version 2) You can run the utility in this format by setting the version parameter to 2, as shown below. A sample CSV file for the same is provided with the utility: python nvs_partition_gen.py generate sample_multipage_blob.csv sample.bin 0x4000 --version 2 Note Minimum NVS Partition Size needed is 0x3000 bytes. When flashing the binary onto the device, make sure it is consistent with the application's sdkconfig. Caveats Utility does not check for duplicate keys and will write data pertaining to both keys. You need to make sure that the keys are distinct. Once a new page is created, no data will be written in the space left on the previous page. Fields in the CSV file need to be ordered in such a way as to optimize memory. 64-bit datatype is not yet supported.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/storage/nvs_partition_gen.html
ESP-IDF Programming Guide v5.2.1 documentation
null
SD/SDIO/MMC Driver
null
espressif.com
2016-01-01
8e41da12a0123033
null
null
SD/SDIO/MMC Driver Overview The SD/SDIO/MMC driver currently supports SD memory, SDIO cards, and eMMC chips. This is a protocol level driver built on top of SDMMC and SD SPI host drivers. SDMMC and SD SPI host drivers (driver/sdmmc/include/driver/sdmmc_host.h and driver/spi/include/driver/sdspi_host.h) provide API functions for: Sending commands to slave devices Sending and receiving data Handling error conditions within the bus For functions used to initialize and configure: SDMMC host, see SDMMC Host API SD SPI host, see SD SPI Host API The SDMMC protocol layer described in this document handles the specifics of the SD protocol, such as the card initialization and data transfer commands. The protocol layer works with the host via the sdmmc_host_t structure. This structure contains pointers to various functions of the host. Pin Configurations ..only:: SOC_SDMMC_USE_IOMUX and not SOC_SDMMC_USE_GPIO_MATRIX SDMMC pins are dedicated, you don't have to configure the pins. ..only:: SOC_SDMMC_USE_GPIO_MATRIX and not SOC_SDMMC_USE_IOMUX SDMMC pin signals are routed via GPIO Matrix, so you will need to configure the pins in sdmmc_slot_config_t . ..only:: esp32p4 SDMMC have two slots: slot 0 pins are dedicated for UHS-I mode. This is not yet supported in the driver. slot 1 pins are routed via GPIO Matrix, and it's for non UHS-I usage. You will need to configure the pins in sdmmc_slot_config_t to use the slot 1. Application Example An example which combines the SDMMC driver with the FATFS library is provided in the 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. 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 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. Protocol Layer API The protocol layer is given the sdmmc_host_t structure. This structure describes the SD/MMC host driver, lists its capabilities, and provides pointers to functions of the driver. The protocol layer stores card-specific information in the sdmmc_card_t structure. When sending commands to the SD/MMC host driver, the protocol layer uses the sdmmc_command_t structure to describe the command, arguments, expected return values, and data to transfer if there is any. Using API with SD Memory Cards To initialize the host, call the host driver functions, e.g., sdmmc_host_init() , sdmmc_host_init_slot() . To initialize the card, call sdmmc_card_init() and pass to it the parameters host - the host driver information, and card - a pointer to the structure sdmmc_card_t which will be filled with information about the card when the function completes. To read and write sectors of the card, use sdmmc_read_sectors() and sdmmc_write_sectors() respectively and pass to it the parameter card - a pointer to the card information structure. If the card is not used anymore, call the host driver function - e.g., sdmmc_host_deinit() - to disable the host peripheral and free the resources allocated by the driver. 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 sdmmc_card_init() , the driver only configures the following registers of the IO card: The IO portion of the card is reset by setting RES bit in the I/O Abort (0x06) register. If 4-line mode is enabled in host and slot configuration, the driver attempts to set the Bus width field in the Bus Interface Control (0x07) register. If setting the filed is successful, which means that the slave supports 4-line mode, the host is also switched to 4-line mode. If high-speed mode is enabled in the host configuration, the SHS bit is set in the High Speed (0x13) register. In particular, the driver does not set any bits in (1) I/O Enable and Int Enable registers, (2) I/O block sizes, etc. Applications can set them by calling sdmmc_io_write_byte() . For card configuration and data transfer, choose the pair of functions relevant to your case from the table below. Action Read Function Write Function Read and write a single byte using IO_RW_DIRECT (CMD52) Read and write multiple bytes using IO_RW_EXTENDED (CMD53) in byte mode Read and write blocks of data using IO_RW_EXTENDED (CMD53) in block mode SDIO interrupts can be enabled by the application using the function 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 sdmmc_io_wait_int() . There is a component ESSL (ESP Serial Slave Link) to use if you are communicating with an ESP32 SDIO slave. See ESP Serial Slave Link and example peripherals/sdio/host. API Reference Header File This header file can be included with: #include "sdmmc_cmd.h" This header file is a part of the API provided by the sdmmc component. To declare that your component depends on sdmmc , add the following to your CMakeLists.txt: REQUIRES sdmmc or PRIV_REQUIRES sdmmc Functions esp_err_t sdmmc_card_init(const sdmmc_host_t *host, sdmmc_card_t *out_card) Probe and initialize SD/MMC card using given host Note Only SD cards (SDSC and SDHC/SDXC) are supported now. Support for MMC/eMMC cards will be added later. Parameters host -- pointer to structure defining host controller out_card -- pointer to structure which will receive information about the card when the function completes host -- pointer to structure defining host controller out_card -- pointer to structure which will receive information about the card when the function completes host -- pointer to structure defining host controller Returns ESP_OK on success One of the error codes from SDMMC host controller ESP_OK on success One of the error codes from SDMMC host controller ESP_OK on success Parameters host -- pointer to structure defining host controller out_card -- pointer to structure which will receive information about the card when the function completes Returns ESP_OK on success One of the error codes from SDMMC host controller void sdmmc_card_print_info(FILE *stream, const sdmmc_card_t *card) Print information about the card to a stream. Parameters stream -- stream obtained using fopen or fdopen card -- card information structure initialized using sdmmc_card_init stream -- stream obtained using fopen or fdopen card -- card information structure initialized using sdmmc_card_init stream -- stream obtained using fopen or fdopen Parameters stream -- stream obtained using fopen or fdopen card -- card information structure initialized using sdmmc_card_init esp_err_t sdmmc_get_status(sdmmc_card_t *card) Get status of SD/MMC card Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success One of the error codes from SDMMC host controller ESP_OK on success One of the error codes from SDMMC host controller ESP_OK on success Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success One of the error codes from SDMMC host controller esp_err_t sdmmc_write_sectors(sdmmc_card_t *card, const void *src, size_t start_sector, size_t sector_count) Write given number of sectors to SD/MMC card Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init src -- pointer to data buffer to read data from; data size must be equal to sector_count * card->csd.sector_size start_sector -- sector where to start writing sector_count -- number of sectors to write card -- pointer to card information structure previously initialized using sdmmc_card_init src -- pointer to data buffer to read data from; data size must be equal to sector_count * card->csd.sector_size start_sector -- sector where to start writing sector_count -- number of sectors to write card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success or sector_count equal to 0 One of the error codes from SDMMC host controller ESP_OK on success or sector_count equal to 0 One of the error codes from SDMMC host controller ESP_OK on success or sector_count equal to 0 Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init src -- pointer to data buffer to read data from; data size must be equal to sector_count * card->csd.sector_size start_sector -- sector where to start writing sector_count -- number of sectors to write Returns ESP_OK on success or sector_count equal to 0 One of the error codes from SDMMC host controller esp_err_t sdmmc_read_sectors(sdmmc_card_t *card, void *dst, size_t start_sector, size_t sector_count) Read given number of sectors from the SD/MMC card Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init dst -- pointer to data buffer to write into; buffer size must be at least sector_count * card->csd.sector_size start_sector -- sector where to start reading sector_count -- number of sectors to read card -- pointer to card information structure previously initialized using sdmmc_card_init dst -- pointer to data buffer to write into; buffer size must be at least sector_count * card->csd.sector_size start_sector -- sector where to start reading sector_count -- number of sectors to read card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success or sector_count equal to 0 One of the error codes from SDMMC host controller ESP_OK on success or sector_count equal to 0 One of the error codes from SDMMC host controller ESP_OK on success or sector_count equal to 0 Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init dst -- pointer to data buffer to write into; buffer size must be at least sector_count * card->csd.sector_size start_sector -- sector where to start reading sector_count -- number of sectors to read Returns ESP_OK on success or sector_count equal to 0 One of the error codes from SDMMC host controller esp_err_t sdmmc_erase_sectors(sdmmc_card_t *card, size_t start_sector, size_t sector_count, sdmmc_erase_arg_t arg) Erase given number of sectors from the SD/MMC card Note When sdmmc_erase_sectors used with cards in SDSPI mode, it was observed that card requires re-init after erase operation. Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init start_sector -- sector where to start erase sector_count -- number of sectors to erase arg -- erase command (CMD38) argument card -- pointer to card information structure previously initialized using sdmmc_card_init start_sector -- sector where to start erase sector_count -- number of sectors to erase arg -- erase command (CMD38) argument card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success or sector_count equal to 0 One of the error codes from SDMMC host controller ESP_OK on success or sector_count equal to 0 One of the error codes from SDMMC host controller ESP_OK on success or sector_count equal to 0 Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init start_sector -- sector where to start erase sector_count -- number of sectors to erase arg -- erase command (CMD38) argument Returns ESP_OK on success or sector_count equal to 0 One of the error codes from SDMMC host controller esp_err_t sdmmc_can_discard(sdmmc_card_t *card) Check if SD/MMC card supports discard Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK if supported by the card/device ESP_FAIL if not supported by the card/device ESP_OK if supported by the card/device ESP_FAIL if not supported by the card/device ESP_OK if supported by the card/device Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK if supported by the card/device ESP_FAIL if not supported by the card/device esp_err_t sdmmc_can_trim(sdmmc_card_t *card) Check if SD/MMC card supports trim Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK if supported by the card/device ESP_FAIL if not supported by the card/device ESP_OK if supported by the card/device ESP_FAIL if not supported by the card/device ESP_OK if supported by the card/device Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK if supported by the card/device ESP_FAIL if not supported by the card/device esp_err_t sdmmc_mmc_can_sanitize(sdmmc_card_t *card) Check if SD/MMC card supports sanitize Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK if supported by the card/device ESP_FAIL if not supported by the card/device ESP_OK if supported by the card/device ESP_FAIL if not supported by the card/device ESP_OK if supported by the card/device Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK if supported by the card/device ESP_FAIL if not supported by the card/device esp_err_t sdmmc_mmc_sanitize(sdmmc_card_t *card, uint32_t timeout_ms) Sanitize the data that was unmapped by a Discard command Note Discard command has to precede sanitize operation. To discard, use MMC_DICARD_ARG with sdmmc_erase_sectors argument Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init timeout_ms -- timeout value in milliseconds required to sanitize the selected range of sectors. card -- pointer to card information structure previously initialized using sdmmc_card_init timeout_ms -- timeout value in milliseconds required to sanitize the selected range of sectors. card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success One of the error codes from SDMMC host controller ESP_OK on success One of the error codes from SDMMC host controller ESP_OK on success Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init timeout_ms -- timeout value in milliseconds required to sanitize the selected range of sectors. Returns ESP_OK on success One of the error codes from SDMMC host controller esp_err_t sdmmc_full_erase(sdmmc_card_t *card) Erase complete SD/MMC card Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success One of the error codes from SDMMC host controller ESP_OK on success One of the error codes from SDMMC host controller ESP_OK on success Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success One of the error codes from SDMMC host controller esp_err_t sdmmc_io_read_byte(sdmmc_card_t *card, uint32_t function, uint32_t reg, uint8_t *out_byte) Read one byte from an SDIO card using IO_RW_DIRECT (CMD52) Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number reg -- byte address within IO function out_byte -- [out] output, receives the value read from the card card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number reg -- byte address within IO function out_byte -- [out] output, receives the value read from the card card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success One of the error codes from SDMMC host controller ESP_OK on success One of the error codes from SDMMC host controller ESP_OK on success Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number reg -- byte address within IO function out_byte -- [out] output, receives the value read from the card Returns ESP_OK on success One of the error codes from SDMMC host controller esp_err_t sdmmc_io_write_byte(sdmmc_card_t *card, uint32_t function, uint32_t reg, uint8_t in_byte, uint8_t *out_byte) Write one byte to an SDIO card using IO_RW_DIRECT (CMD52) Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number reg -- byte address within IO function in_byte -- value to be written out_byte -- [out] if not NULL, receives new byte value read from the card (read-after-write). card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number reg -- byte address within IO function in_byte -- value to be written out_byte -- [out] if not NULL, receives new byte value read from the card (read-after-write). card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success One of the error codes from SDMMC host controller ESP_OK on success One of the error codes from SDMMC host controller ESP_OK on success Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number reg -- byte address within IO function in_byte -- value to be written out_byte -- [out] if not NULL, receives new byte value read from the card (read-after-write). Returns ESP_OK on success One of the error codes from SDMMC host controller esp_err_t sdmmc_io_read_bytes(sdmmc_card_t *card, uint32_t function, uint32_t addr, void *dst, size_t size) Read multiple bytes from an SDIO card using IO_RW_EXTENDED (CMD53) This function performs read operation using CMD53 in byte mode. For block mode, see sdmmc_io_read_blocks. Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where reading starts dst -- buffer which receives the data read from card size -- number of bytes to read card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where reading starts dst -- buffer which receives the data read from card size -- number of bytes to read card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success ESP_ERR_INVALID_SIZE if size exceeds 512 bytes One of the error codes from SDMMC host controller ESP_OK on success ESP_ERR_INVALID_SIZE if size exceeds 512 bytes One of the error codes from SDMMC host controller ESP_OK on success Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where reading starts dst -- buffer which receives the data read from card size -- number of bytes to read Returns ESP_OK on success ESP_ERR_INVALID_SIZE if size exceeds 512 bytes One of the error codes from SDMMC host controller esp_err_t sdmmc_io_write_bytes(sdmmc_card_t *card, uint32_t function, uint32_t addr, const void *src, size_t size) Write multiple bytes to an SDIO card using IO_RW_EXTENDED (CMD53) This function performs write operation using CMD53 in byte mode. For block mode, see sdmmc_io_write_blocks. Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where writing starts src -- data to be written size -- number of bytes to write card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where writing starts src -- data to be written size -- number of bytes to write card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success ESP_ERR_INVALID_SIZE if size exceeds 512 bytes One of the error codes from SDMMC host controller ESP_OK on success ESP_ERR_INVALID_SIZE if size exceeds 512 bytes One of the error codes from SDMMC host controller ESP_OK on success Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where writing starts src -- data to be written size -- number of bytes to write Returns ESP_OK on success ESP_ERR_INVALID_SIZE if size exceeds 512 bytes One of the error codes from SDMMC host controller esp_err_t sdmmc_io_read_blocks(sdmmc_card_t *card, uint32_t function, uint32_t addr, void *dst, size_t size) Read blocks of data from an SDIO card using IO_RW_EXTENDED (CMD53) This function performs read operation using CMD53 in block mode. For byte mode, see sdmmc_io_read_bytes. Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where writing starts dst -- buffer which receives the data read from card size -- number of bytes to read, must be divisible by the card block size. card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where writing starts dst -- buffer which receives the data read from card size -- number of bytes to read, must be divisible by the card block size. card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success ESP_ERR_INVALID_SIZE if size is not divisible by 512 bytes One of the error codes from SDMMC host controller ESP_OK on success ESP_ERR_INVALID_SIZE if size is not divisible by 512 bytes One of the error codes from SDMMC host controller ESP_OK on success Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where writing starts dst -- buffer which receives the data read from card size -- number of bytes to read, must be divisible by the card block size. Returns ESP_OK on success ESP_ERR_INVALID_SIZE if size is not divisible by 512 bytes One of the error codes from SDMMC host controller esp_err_t sdmmc_io_write_blocks(sdmmc_card_t *card, uint32_t function, uint32_t addr, const void *src, size_t size) Write blocks of data to an SDIO card using IO_RW_EXTENDED (CMD53) This function performs write operation using CMD53 in block mode. For byte mode, see sdmmc_io_write_bytes. Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where writing starts src -- data to be written size -- number of bytes to read, must be divisible by the card block size. card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where writing starts src -- data to be written size -- number of bytes to read, must be divisible by the card block size. card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success ESP_ERR_INVALID_SIZE if size is not divisible by 512 bytes One of the error codes from SDMMC host controller ESP_OK on success ESP_ERR_INVALID_SIZE if size is not divisible by 512 bytes One of the error codes from SDMMC host controller ESP_OK on success Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where writing starts src -- data to be written size -- number of bytes to read, must be divisible by the card block size. Returns ESP_OK on success ESP_ERR_INVALID_SIZE if size is not divisible by 512 bytes One of the error codes from SDMMC host controller esp_err_t sdmmc_io_enable_int(sdmmc_card_t *card) Enable SDIO interrupt in the SDMMC host Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if the host controller does not support IO interrupts ESP_OK on success ESP_ERR_NOT_SUPPORTED if the host controller does not support IO interrupts ESP_OK on success Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if the host controller does not support IO interrupts esp_err_t sdmmc_io_wait_int(sdmmc_card_t *card, TickType_t timeout_ticks) Block until an SDIO interrupt is received Slave uses D1 line to signal interrupt condition to the host. This function can be used to wait for the interrupt. Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init timeout_ticks -- time to wait for the interrupt, in RTOS ticks card -- pointer to card information structure previously initialized using sdmmc_card_init timeout_ticks -- time to wait for the interrupt, in RTOS ticks card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK if the interrupt is received ESP_ERR_NOT_SUPPORTED if the host controller does not support IO interrupts ESP_ERR_TIMEOUT if the interrupt does not happen in timeout_ticks ESP_OK if the interrupt is received ESP_ERR_NOT_SUPPORTED if the host controller does not support IO interrupts ESP_ERR_TIMEOUT if the interrupt does not happen in timeout_ticks ESP_OK if the interrupt is received Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init timeout_ticks -- time to wait for the interrupt, in RTOS ticks Returns ESP_OK if the interrupt is received ESP_ERR_NOT_SUPPORTED if the host controller does not support IO interrupts ESP_ERR_TIMEOUT if the interrupt does not happen in timeout_ticks esp_err_t sdmmc_io_get_cis_data(sdmmc_card_t *card, uint8_t *out_buffer, size_t buffer_size, size_t *inout_cis_size) Get the data of CIS region of an SDIO card. You may provide a buffer not sufficient to store all the CIS data. In this case, this function stores as much data into your buffer as possible. Also, this function will try to get and return the size required for you. Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init out_buffer -- Output buffer of the CIS data buffer_size -- Size of the buffer. inout_cis_size -- Mandatory, pointer to a size, input and output. input: Limitation of maximum searching range, should be 0 or larger than buffer_size. The function searches for CIS_CODE_END until this range. Set to 0 to search infinitely. output: The size required to store all the CIS data, if CIS_CODE_END is found. input: Limitation of maximum searching range, should be 0 or larger than buffer_size. The function searches for CIS_CODE_END until this range. Set to 0 to search infinitely. output: The size required to store all the CIS data, if CIS_CODE_END is found. input: Limitation of maximum searching range, should be 0 or larger than buffer_size. The function searches for CIS_CODE_END until this range. Set to 0 to search infinitely. card -- pointer to card information structure previously initialized using sdmmc_card_init out_buffer -- Output buffer of the CIS data buffer_size -- Size of the buffer. inout_cis_size -- Mandatory, pointer to a size, input and output. input: Limitation of maximum searching range, should be 0 or larger than buffer_size. The function searches for CIS_CODE_END until this range. Set to 0 to search infinitely. output: The size required to store all the CIS data, if CIS_CODE_END is found. card -- pointer to card information structure previously initialized using sdmmc_card_init Returns ESP_OK: on success ESP_ERR_INVALID_RESPONSE: if the card does not (correctly) support CIS. ESP_ERR_INVALID_SIZE: CIS_CODE_END found, but buffer_size is less than required size, which is stored in the inout_cis_size then. ESP_ERR_NOT_FOUND: if the CIS_CODE_END not found. Increase input value of inout_cis_size or set it to 0, if you still want to search for the end; output value of inout_cis_size is invalid in this case. and other error code return from sdmmc_io_read_bytes ESP_OK: on success ESP_ERR_INVALID_RESPONSE: if the card does not (correctly) support CIS. ESP_ERR_INVALID_SIZE: CIS_CODE_END found, but buffer_size is less than required size, which is stored in the inout_cis_size then. ESP_ERR_NOT_FOUND: if the CIS_CODE_END not found. Increase input value of inout_cis_size or set it to 0, if you still want to search for the end; output value of inout_cis_size is invalid in this case. and other error code return from sdmmc_io_read_bytes ESP_OK: on success Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init out_buffer -- Output buffer of the CIS data buffer_size -- Size of the buffer. inout_cis_size -- Mandatory, pointer to a size, input and output. input: Limitation of maximum searching range, should be 0 or larger than buffer_size. The function searches for CIS_CODE_END until this range. Set to 0 to search infinitely. output: The size required to store all the CIS data, if CIS_CODE_END is found. Returns ESP_OK: on success ESP_ERR_INVALID_RESPONSE: if the card does not (correctly) support CIS. ESP_ERR_INVALID_SIZE: CIS_CODE_END found, but buffer_size is less than required size, which is stored in the inout_cis_size then. ESP_ERR_NOT_FOUND: if the CIS_CODE_END not found. Increase input value of inout_cis_size or set it to 0, if you still want to search for the end; output value of inout_cis_size is invalid in this case. and other error code return from sdmmc_io_read_bytes esp_err_t sdmmc_io_print_cis_info(uint8_t *buffer, size_t buffer_size, FILE *fp) Parse and print the CIS information of an SDIO card. Note Not all the CIS codes and all kinds of tuples are supported. If you see some unresolved code, you can add the parsing of these code in sdmmc_io.c and contribute to the IDF through the Github repository. using sdmmc_card_init Parameters buffer -- Buffer to parse buffer_size -- Size of the buffer. fp -- File pointer to print to, set to NULL to print to stdout. buffer -- Buffer to parse buffer_size -- Size of the buffer. fp -- File pointer to print to, set to NULL to print to stdout. buffer -- Buffer to parse Returns ESP_OK: on success ESP_ERR_NOT_SUPPORTED: if the value from the card is not supported to be parsed. ESP_ERR_INVALID_SIZE: if the CIS size fields are not correct. ESP_OK: on success ESP_ERR_NOT_SUPPORTED: if the value from the card is not supported to be parsed. ESP_ERR_INVALID_SIZE: if the CIS size fields are not correct. ESP_OK: on success Parameters buffer -- Buffer to parse buffer_size -- Size of the buffer. fp -- File pointer to print to, set to NULL to print to stdout. Returns ESP_OK: on success ESP_ERR_NOT_SUPPORTED: if the value from the card is not supported to be parsed. ESP_ERR_INVALID_SIZE: if the CIS size fields are not correct. Header File This header file can be included with: #include "driver/sdmmc_types.h" This header file is a part of the API provided by the driver component. To declare that your component depends on driver , add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Structures struct sdmmc_csd_t Decoded values from SD card Card Specific Data register struct sdmmc_cid_t Decoded values from SD card Card IDentification register struct sdmmc_scr_t Decoded values from SD Configuration Register Note: When new member is added, update reserved bits accordingly Public Members uint32_t sd_spec SD Physical layer specification version, reported by card uint32_t sd_spec SD Physical layer specification version, reported by card uint32_t erase_mem_state data state on card after erase whether 0 or 1 (card vendor dependent) uint32_t erase_mem_state data state on card after erase whether 0 or 1 (card vendor dependent) uint32_t bus_width bus widths supported by card: BIT(0) — 1-bit bus, BIT(2) — 4-bit bus uint32_t bus_width bus widths supported by card: BIT(0) — 1-bit bus, BIT(2) — 4-bit bus uint32_t reserved reserved for future expansion uint32_t reserved reserved for future expansion uint32_t rsvd_mnf reserved for manufacturer usage uint32_t rsvd_mnf reserved for manufacturer usage uint32_t sd_spec struct sdmmc_ssr_t Decoded values from SD Status Register Note: When new member is added, update reserved bits accordingly Public Members uint32_t alloc_unit_kb Allocation unit of the card, in multiples of kB (1024 bytes) uint32_t alloc_unit_kb Allocation unit of the card, in multiples of kB (1024 bytes) uint32_t erase_size_au Erase size for the purpose of timeout calculation, in multiples of allocation unit uint32_t erase_size_au Erase size for the purpose of timeout calculation, in multiples of allocation unit uint32_t cur_bus_width SD current bus width uint32_t cur_bus_width SD current bus width uint32_t discard_support SD discard feature support uint32_t discard_support SD discard feature support uint32_t fule_support SD FULE (Full User Area Logical Erase) feature support uint32_t fule_support SD FULE (Full User Area Logical Erase) feature support uint32_t erase_timeout Timeout (in seconds) for erase of a single allocation unit uint32_t erase_timeout Timeout (in seconds) for erase of a single allocation unit uint32_t erase_offset Constant timeout offset (in seconds) for any erase operation uint32_t erase_offset Constant timeout offset (in seconds) for any erase operation uint32_t reserved reserved for future expansion uint32_t reserved reserved for future expansion uint32_t alloc_unit_kb struct sdmmc_ext_csd_t Decoded values of Extended Card Specific Data struct sdmmc_switch_func_rsp_t SD SWITCH_FUNC response buffer Public Members uint32_t data[512 / 8 / sizeof(uint32_t)] response data uint32_t data[512 / 8 / sizeof(uint32_t)] response data uint32_t data[512 / 8 / sizeof(uint32_t)] struct sdmmc_command_t SD/MMC command information Public Members uint32_t opcode SD or MMC command index uint32_t opcode SD or MMC command index uint32_t arg SD/MMC command argument uint32_t arg SD/MMC command argument sdmmc_response_t response response buffer sdmmc_response_t response response buffer void *data buffer to send or read into void *data buffer to send or read into size_t datalen length of data in the buffer size_t datalen length of data in the buffer size_t buflen length of the buffer size_t buflen length of the buffer size_t blklen block length size_t blklen block length int flags see below int flags see below uint32_t timeout_ms response timeout, in milliseconds uint32_t timeout_ms response timeout, in milliseconds uint32_t opcode struct sdmmc_host_t SD/MMC Host description This structure defines properties of SD/MMC host and functions of SD/MMC host which can be used by upper layers. Public Members uint32_t flags flags defining host properties uint32_t flags flags defining host properties int slot slot number, to be passed to host functions int slot slot number, to be passed to host functions int max_freq_khz max frequency supported by the host int max_freq_khz max frequency supported by the host float io_voltage I/O voltage used by the controller (voltage switching is not supported) float io_voltage I/O voltage used by the controller (voltage switching is not supported) size_t (*get_bus_width)(int slot) host function to get bus width size_t (*get_bus_width)(int slot) host function to get bus width esp_err_t (*set_cclk_always_on)(int slot, bool cclk_always_on) host function to set whether the clock is always enabled esp_err_t (*set_cclk_always_on)(int slot, bool cclk_always_on) host function to set whether the clock is always enabled esp_err_t (*do_transaction)(int slot, sdmmc_command_t *cmdinfo) host function to do a transaction esp_err_t (*do_transaction)(int slot, sdmmc_command_t *cmdinfo) host function to do a transaction esp_err_t (*io_int_wait)(int slot, TickType_t timeout_ticks) Host function to wait for SDIO interrupt line to be active esp_err_t (*io_int_wait)(int slot, TickType_t timeout_ticks) Host function to wait for SDIO interrupt line to be active int command_timeout_ms timeout, in milliseconds, of a single command. Set to 0 to use the default value. int command_timeout_ms timeout, in milliseconds, of a single command. Set to 0 to use the default value. esp_err_t (*get_real_freq)(int slot, int *real_freq) Host function to provide real working freq, based on SDMMC controller setup esp_err_t (*get_real_freq)(int slot, int *real_freq) Host function to provide real working freq, based on SDMMC controller setup sdmmc_delay_phase_t input_delay_phase input delay phase, this will only take into effect when the host works in SDMMC_FREQ_HIGHSPEED or SDMMC_FREQ_52M. Driver will print out how long the delay is sdmmc_delay_phase_t input_delay_phase input delay phase, this will only take into effect when the host works in SDMMC_FREQ_HIGHSPEED or SDMMC_FREQ_52M. Driver will print out how long the delay is esp_err_t (*set_input_delay)(int slot, sdmmc_delay_phase_t delay_phase) set input delay phase esp_err_t (*set_input_delay)(int slot, sdmmc_delay_phase_t delay_phase) set input delay phase uint32_t flags struct sdmmc_card_t SD/MMC card information structure Public Members sdmmc_host_t host Host with which the card is associated sdmmc_host_t host Host with which the card is associated uint32_t ocr OCR (Operation Conditions Register) value uint32_t ocr OCR (Operation Conditions Register) value sdmmc_cid_t cid decoded CID (Card IDentification) register value sdmmc_cid_t cid decoded CID (Card IDentification) register value sdmmc_response_t raw_cid raw CID of MMC card to be decoded after the CSD is fetched in the data transfer mode sdmmc_response_t raw_cid raw CID of MMC card to be decoded after the CSD is fetched in the data transfer mode sdmmc_csd_t csd decoded CSD (Card-Specific Data) register value sdmmc_csd_t csd decoded CSD (Card-Specific Data) register value sdmmc_scr_t scr decoded SCR (SD card Configuration Register) value sdmmc_scr_t scr decoded SCR (SD card Configuration Register) value sdmmc_ssr_t ssr decoded SSR (SD Status Register) value sdmmc_ssr_t ssr decoded SSR (SD Status Register) value sdmmc_ext_csd_t ext_csd decoded EXT_CSD (Extended Card Specific Data) register value sdmmc_ext_csd_t ext_csd decoded EXT_CSD (Extended Card Specific Data) register value uint16_t rca RCA (Relative Card Address) uint16_t rca RCA (Relative Card Address) uint16_t max_freq_khz Maximum frequency, in kHz, supported by the card uint16_t max_freq_khz Maximum frequency, in kHz, supported by the card int real_freq_khz Real working frequency, in kHz, configured on the host controller int real_freq_khz Real working frequency, in kHz, configured on the host controller uint32_t is_mem Bit indicates if the card is a memory card uint32_t is_mem Bit indicates if the card is a memory card uint32_t is_sdio Bit indicates if the card is an IO card uint32_t is_sdio Bit indicates if the card is an IO card uint32_t is_mmc Bit indicates if the card is MMC uint32_t is_mmc Bit indicates if the card is MMC uint32_t num_io_functions If is_sdio is 1, contains the number of IO functions on the card uint32_t num_io_functions If is_sdio is 1, contains the number of IO functions on the card uint32_t log_bus_width log2(bus width supported by card) uint32_t log_bus_width log2(bus width supported by card) uint32_t is_ddr Card supports DDR mode uint32_t is_ddr Card supports DDR mode uint32_t reserved Reserved for future expansion uint32_t reserved Reserved for future expansion sdmmc_host_t host Macros SDMMC_HOST_FLAG_1BIT host supports 1-line SD and MMC protocol SDMMC_HOST_FLAG_4BIT host supports 4-line SD and MMC protocol SDMMC_HOST_FLAG_8BIT host supports 8-line MMC protocol SDMMC_HOST_FLAG_SPI host supports SPI protocol SDMMC_HOST_FLAG_DDR host supports DDR mode for SD/MMC SDMMC_HOST_FLAG_DEINIT_ARG host deinit function called with the slot argument SDMMC_FREQ_DEFAULT SD/MMC Default speed (limited by clock divider) SDMMC_FREQ_HIGHSPEED SD High speed (limited by clock divider) SDMMC_FREQ_PROBING SD/MMC probing speed SDMMC_FREQ_52M MMC 52MHz speed SDMMC_FREQ_26M MMC 26MHz speed Type Definitions typedef uint32_t sdmmc_response_t[4] SD/MMC command response buffer Enumerations enum sdmmc_delay_phase_t SD/MMC Host clock timing delay phases This will only take effect when the host works in SDMMC_FREQ_HIGHSPEED or SDMMC_FREQ_52M. Driver will print out how long the delay is, in picosecond (ps). Values: enumerator SDMMC_DELAY_PHASE_0 Delay phase 0 enumerator SDMMC_DELAY_PHASE_0 Delay phase 0 enumerator SDMMC_DELAY_PHASE_1 Delay phase 1 enumerator SDMMC_DELAY_PHASE_1 Delay phase 1 enumerator SDMMC_DELAY_PHASE_2 Delay phase 2 enumerator SDMMC_DELAY_PHASE_2 Delay phase 2 enumerator SDMMC_DELAY_PHASE_3 Delay phase 3 enumerator SDMMC_DELAY_PHASE_3 Delay phase 3 enumerator SDMMC_DELAY_PHASE_0 enum sdmmc_erase_arg_t SD/MMC erase command(38) arguments SD: ERASE: Erase the write blocks, physical/hard erase. DISCARD: Card may deallocate the discarded blocks partially or completely. After discard operation the previously written data may be partially or fully read by the host depending on card implementation. MMC: ERASE: Does TRIM, applies erase operation to write blocks instead of Erase Group. DISCARD: The Discard function allows the host to identify data that is no longer required so that the device can erase the data if necessary during background erase events. Applies to write blocks instead of Erase Group After discard operation, the original data may be remained partially or fully accessible to the host dependent on device. Values: enumerator SDMMC_ERASE_ARG Erase operation on SD, Trim operation on MMC enumerator SDMMC_ERASE_ARG Erase operation on SD, Trim operation on MMC enumerator SDMMC_DISCARD_ARG Discard operation for SD/MMC enumerator SDMMC_DISCARD_ARG Discard operation for SD/MMC enumerator SDMMC_ERASE_ARG
SD/SDIO/MMC Driver Overview The SD/SDIO/MMC driver currently supports SD memory, SDIO cards, and eMMC chips. This is a protocol level driver built on top of SDMMC and SD SPI host drivers. SDMMC and SD SPI host drivers (driver/sdmmc/include/driver/sdmmc_host.h and driver/spi/include/driver/sdspi_host.h) provide API functions for: Sending commands to slave devices Sending and receiving data Handling error conditions within the bus For functions used to initialize and configure: SDMMC host, see SDMMC Host API SD SPI host, see SD SPI Host API The SDMMC protocol layer described in this document handles the specifics of the SD protocol, such as the card initialization and data transfer commands. The protocol layer works with the host via the sdmmc_host_t structure. This structure contains pointers to various functions of the host. Pin Configurations ..only:: SOC_SDMMC_USE_IOMUX and not SOC_SDMMC_USE_GPIO_MATRIX SDMMC pins are dedicated, you don't have to configure the pins. ..only:: SOC_SDMMC_USE_GPIO_MATRIX and not SOC_SDMMC_USE_IOMUX SDMMC pin signals are routed via GPIO Matrix, so you will need to configure the pins in sdmmc_slot_config_t. ..only:: esp32p4 SDMMC have two slots: - slot 0 pins are dedicated for UHS-I mode. This is not yet supported in the driver. - slot 1 pins are routed via GPIO Matrix, and it's for non UHS-I usage. You will need to configure the pins in sdmmc_slot_config_tto use the slot 1. Application Example An example which combines the SDMMC driver with the FATFS library is provided in the 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. 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 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. Protocol Layer API The protocol layer is given the sdmmc_host_t structure. This structure describes the SD/MMC host driver, lists its capabilities, and provides pointers to functions of the driver. The protocol layer stores card-specific information in the sdmmc_card_t structure. When sending commands to the SD/MMC host driver, the protocol layer uses the sdmmc_command_t structure to describe the command, arguments, expected return values, and data to transfer if there is any. Using API with SD Memory Cards To initialize the host, call the host driver functions, e.g., sdmmc_host_init(), sdmmc_host_init_slot(). To initialize the card, call sdmmc_card_init()and pass to it the parameters host- the host driver information, and card- a pointer to the structure sdmmc_card_twhich will be filled with information about the card when the function completes. To read and write sectors of the card, use sdmmc_read_sectors()and sdmmc_write_sectors()respectively and pass to it the parameter card- a pointer to the card information structure. If the card is not used anymore, call the host driver function - e.g., sdmmc_host_deinit()- to disable the host peripheral and free the resources allocated by the driver. 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 sdmmc_card_init(), the driver only configures the following registers of the IO card: The IO portion of the card is reset by setting RES bit in the I/O Abort (0x06) register. If 4-line mode is enabled in host and slot configuration, the driver attempts to set the Bus width field in the Bus Interface Control (0x07) register. If setting the filed is successful, which means that the slave supports 4-line mode, the host is also switched to 4-line mode. If high-speed mode is enabled in the host configuration, the SHS bit is set in the High Speed (0x13) register. In particular, the driver does not set any bits in (1) I/O Enable and Int Enable registers, (2) I/O block sizes, etc. Applications can set them by calling sdmmc_io_write_byte(). For card configuration and data transfer, choose the pair of functions relevant to your case from the table below. | Action | Read Function | Write Function | Read and write a single byte using IO_RW_DIRECT (CMD52) | Read and write multiple bytes using IO_RW_EXTENDED (CMD53) in byte mode | Read and write blocks of data using IO_RW_EXTENDED (CMD53) in block mode SDIO interrupts can be enabled by the application using the function 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 sdmmc_io_wait_int(). There is a component ESSL (ESP Serial Slave Link) to use if you are communicating with an ESP32 SDIO slave. See ESP Serial Slave Link and example peripherals/sdio/host. API Reference Header File This header file can be included with: #include "sdmmc_cmd.h" This header file is a part of the API provided by the sdmmccomponent. To declare that your component depends on sdmmc, add the following to your CMakeLists.txt: REQUIRES sdmmc or PRIV_REQUIRES sdmmc Functions - esp_err_t sdmmc_card_init(const sdmmc_host_t *host, sdmmc_card_t *out_card) Probe and initialize SD/MMC card using given host Note Only SD cards (SDSC and SDHC/SDXC) are supported now. Support for MMC/eMMC cards will be added later. - Parameters host -- pointer to structure defining host controller out_card -- pointer to structure which will receive information about the card when the function completes - - Returns ESP_OK on success One of the error codes from SDMMC host controller - - void sdmmc_card_print_info(FILE *stream, const sdmmc_card_t *card) Print information about the card to a stream. - Parameters stream -- stream obtained using fopen or fdopen card -- card information structure initialized using sdmmc_card_init - - esp_err_t sdmmc_get_status(sdmmc_card_t *card) Get status of SD/MMC card - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init - Returns ESP_OK on success One of the error codes from SDMMC host controller - - esp_err_t sdmmc_write_sectors(sdmmc_card_t *card, const void *src, size_t start_sector, size_t sector_count) Write given number of sectors to SD/MMC card - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init src -- pointer to data buffer to read data from; data size must be equal to sector_count * card->csd.sector_size start_sector -- sector where to start writing sector_count -- number of sectors to write - - Returns ESP_OK on success or sector_count equal to 0 One of the error codes from SDMMC host controller - - esp_err_t sdmmc_read_sectors(sdmmc_card_t *card, void *dst, size_t start_sector, size_t sector_count) Read given number of sectors from the SD/MMC card - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init dst -- pointer to data buffer to write into; buffer size must be at least sector_count * card->csd.sector_size start_sector -- sector where to start reading sector_count -- number of sectors to read - - Returns ESP_OK on success or sector_count equal to 0 One of the error codes from SDMMC host controller - - esp_err_t sdmmc_erase_sectors(sdmmc_card_t *card, size_t start_sector, size_t sector_count, sdmmc_erase_arg_t arg) Erase given number of sectors from the SD/MMC card Note When sdmmc_erase_sectors used with cards in SDSPI mode, it was observed that card requires re-init after erase operation. - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init start_sector -- sector where to start erase sector_count -- number of sectors to erase arg -- erase command (CMD38) argument - - Returns ESP_OK on success or sector_count equal to 0 One of the error codes from SDMMC host controller - - esp_err_t sdmmc_can_discard(sdmmc_card_t *card) Check if SD/MMC card supports discard - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init - Returns ESP_OK if supported by the card/device ESP_FAIL if not supported by the card/device - - esp_err_t sdmmc_can_trim(sdmmc_card_t *card) Check if SD/MMC card supports trim - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init - Returns ESP_OK if supported by the card/device ESP_FAIL if not supported by the card/device - - esp_err_t sdmmc_mmc_can_sanitize(sdmmc_card_t *card) Check if SD/MMC card supports sanitize - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init - Returns ESP_OK if supported by the card/device ESP_FAIL if not supported by the card/device - - esp_err_t sdmmc_mmc_sanitize(sdmmc_card_t *card, uint32_t timeout_ms) Sanitize the data that was unmapped by a Discard command Note Discard command has to precede sanitize operation. To discard, use MMC_DICARD_ARG with sdmmc_erase_sectors argument - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init timeout_ms -- timeout value in milliseconds required to sanitize the selected range of sectors. - - Returns ESP_OK on success One of the error codes from SDMMC host controller - - esp_err_t sdmmc_full_erase(sdmmc_card_t *card) Erase complete SD/MMC card - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init - Returns ESP_OK on success One of the error codes from SDMMC host controller - - esp_err_t sdmmc_io_read_byte(sdmmc_card_t *card, uint32_t function, uint32_t reg, uint8_t *out_byte) Read one byte from an SDIO card using IO_RW_DIRECT (CMD52) - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number reg -- byte address within IO function out_byte -- [out] output, receives the value read from the card - - Returns ESP_OK on success One of the error codes from SDMMC host controller - - esp_err_t sdmmc_io_write_byte(sdmmc_card_t *card, uint32_t function, uint32_t reg, uint8_t in_byte, uint8_t *out_byte) Write one byte to an SDIO card using IO_RW_DIRECT (CMD52) - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number reg -- byte address within IO function in_byte -- value to be written out_byte -- [out] if not NULL, receives new byte value read from the card (read-after-write). - - Returns ESP_OK on success One of the error codes from SDMMC host controller - - esp_err_t sdmmc_io_read_bytes(sdmmc_card_t *card, uint32_t function, uint32_t addr, void *dst, size_t size) Read multiple bytes from an SDIO card using IO_RW_EXTENDED (CMD53) This function performs read operation using CMD53 in byte mode. For block mode, see sdmmc_io_read_blocks. - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where reading starts dst -- buffer which receives the data read from card size -- number of bytes to read - - Returns ESP_OK on success ESP_ERR_INVALID_SIZE if size exceeds 512 bytes One of the error codes from SDMMC host controller - - esp_err_t sdmmc_io_write_bytes(sdmmc_card_t *card, uint32_t function, uint32_t addr, const void *src, size_t size) Write multiple bytes to an SDIO card using IO_RW_EXTENDED (CMD53) This function performs write operation using CMD53 in byte mode. For block mode, see sdmmc_io_write_blocks. - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where writing starts src -- data to be written size -- number of bytes to write - - Returns ESP_OK on success ESP_ERR_INVALID_SIZE if size exceeds 512 bytes One of the error codes from SDMMC host controller - - esp_err_t sdmmc_io_read_blocks(sdmmc_card_t *card, uint32_t function, uint32_t addr, void *dst, size_t size) Read blocks of data from an SDIO card using IO_RW_EXTENDED (CMD53) This function performs read operation using CMD53 in block mode. For byte mode, see sdmmc_io_read_bytes. - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where writing starts dst -- buffer which receives the data read from card size -- number of bytes to read, must be divisible by the card block size. - - Returns ESP_OK on success ESP_ERR_INVALID_SIZE if size is not divisible by 512 bytes One of the error codes from SDMMC host controller - - esp_err_t sdmmc_io_write_blocks(sdmmc_card_t *card, uint32_t function, uint32_t addr, const void *src, size_t size) Write blocks of data to an SDIO card using IO_RW_EXTENDED (CMD53) This function performs write operation using CMD53 in block mode. For byte mode, see sdmmc_io_write_bytes. - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init function -- IO function number addr -- byte address within IO function where writing starts src -- data to be written size -- number of bytes to read, must be divisible by the card block size. - - Returns ESP_OK on success ESP_ERR_INVALID_SIZE if size is not divisible by 512 bytes One of the error codes from SDMMC host controller - - esp_err_t sdmmc_io_enable_int(sdmmc_card_t *card) Enable SDIO interrupt in the SDMMC host - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init - Returns ESP_OK on success ESP_ERR_NOT_SUPPORTED if the host controller does not support IO interrupts - - esp_err_t sdmmc_io_wait_int(sdmmc_card_t *card, TickType_t timeout_ticks) Block until an SDIO interrupt is received Slave uses D1 line to signal interrupt condition to the host. This function can be used to wait for the interrupt. - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init timeout_ticks -- time to wait for the interrupt, in RTOS ticks - - Returns ESP_OK if the interrupt is received ESP_ERR_NOT_SUPPORTED if the host controller does not support IO interrupts ESP_ERR_TIMEOUT if the interrupt does not happen in timeout_ticks - - esp_err_t sdmmc_io_get_cis_data(sdmmc_card_t *card, uint8_t *out_buffer, size_t buffer_size, size_t *inout_cis_size) Get the data of CIS region of an SDIO card. You may provide a buffer not sufficient to store all the CIS data. In this case, this function stores as much data into your buffer as possible. Also, this function will try to get and return the size required for you. - Parameters card -- pointer to card information structure previously initialized using sdmmc_card_init out_buffer -- Output buffer of the CIS data buffer_size -- Size of the buffer. inout_cis_size -- Mandatory, pointer to a size, input and output. input: Limitation of maximum searching range, should be 0 or larger than buffer_size. The function searches for CIS_CODE_END until this range. Set to 0 to search infinitely. output: The size required to store all the CIS data, if CIS_CODE_END is found. - - - Returns ESP_OK: on success ESP_ERR_INVALID_RESPONSE: if the card does not (correctly) support CIS. ESP_ERR_INVALID_SIZE: CIS_CODE_END found, but buffer_size is less than required size, which is stored in the inout_cis_size then. ESP_ERR_NOT_FOUND: if the CIS_CODE_END not found. Increase input value of inout_cis_size or set it to 0, if you still want to search for the end; output value of inout_cis_size is invalid in this case. and other error code return from sdmmc_io_read_bytes - - esp_err_t sdmmc_io_print_cis_info(uint8_t *buffer, size_t buffer_size, FILE *fp) Parse and print the CIS information of an SDIO card. Note Not all the CIS codes and all kinds of tuples are supported. If you see some unresolved code, you can add the parsing of these code in sdmmc_io.c and contribute to the IDF through the Github repository. using sdmmc_card_init - Parameters buffer -- Buffer to parse buffer_size -- Size of the buffer. fp -- File pointer to print to, set to NULL to print to stdout. - - Returns ESP_OK: on success ESP_ERR_NOT_SUPPORTED: if the value from the card is not supported to be parsed. ESP_ERR_INVALID_SIZE: if the CIS size fields are not correct. - Header File This header file can be included with: #include "driver/sdmmc_types.h" This header file is a part of the API provided by the drivercomponent. To declare that your component depends on driver, add the following to your CMakeLists.txt: REQUIRES driver or PRIV_REQUIRES driver Structures - struct sdmmc_csd_t Decoded values from SD card Card Specific Data register - struct sdmmc_cid_t Decoded values from SD card Card IDentification register - struct sdmmc_scr_t Decoded values from SD Configuration Register Note: When new member is added, update reserved bits accordingly Public Members - uint32_t sd_spec SD Physical layer specification version, reported by card - uint32_t erase_mem_state data state on card after erase whether 0 or 1 (card vendor dependent) - uint32_t bus_width bus widths supported by card: BIT(0) — 1-bit bus, BIT(2) — 4-bit bus - uint32_t reserved reserved for future expansion - uint32_t rsvd_mnf reserved for manufacturer usage - uint32_t sd_spec - struct sdmmc_ssr_t Decoded values from SD Status Register Note: When new member is added, update reserved bits accordingly Public Members - uint32_t alloc_unit_kb Allocation unit of the card, in multiples of kB (1024 bytes) - uint32_t erase_size_au Erase size for the purpose of timeout calculation, in multiples of allocation unit - uint32_t cur_bus_width SD current bus width - uint32_t discard_support SD discard feature support - uint32_t fule_support SD FULE (Full User Area Logical Erase) feature support - uint32_t erase_timeout Timeout (in seconds) for erase of a single allocation unit - uint32_t erase_offset Constant timeout offset (in seconds) for any erase operation - uint32_t reserved reserved for future expansion - uint32_t alloc_unit_kb - struct sdmmc_ext_csd_t Decoded values of Extended Card Specific Data - struct sdmmc_switch_func_rsp_t SD SWITCH_FUNC response buffer Public Members - uint32_t data[512 / 8 / sizeof(uint32_t)] response data - uint32_t data[512 / 8 / sizeof(uint32_t)] - struct sdmmc_command_t SD/MMC command information Public Members - uint32_t opcode SD or MMC command index - uint32_t arg SD/MMC command argument - sdmmc_response_t response response buffer - void *data buffer to send or read into - size_t datalen length of data in the buffer - size_t buflen length of the buffer - size_t blklen block length - int flags see below - uint32_t timeout_ms response timeout, in milliseconds - uint32_t opcode - struct sdmmc_host_t SD/MMC Host description This structure defines properties of SD/MMC host and functions of SD/MMC host which can be used by upper layers. Public Members - uint32_t flags flags defining host properties - int slot slot number, to be passed to host functions - int max_freq_khz max frequency supported by the host - float io_voltage I/O voltage used by the controller (voltage switching is not supported) - size_t (*get_bus_width)(int slot) host function to get bus width - esp_err_t (*set_cclk_always_on)(int slot, bool cclk_always_on) host function to set whether the clock is always enabled - esp_err_t (*do_transaction)(int slot, sdmmc_command_t *cmdinfo) host function to do a transaction - esp_err_t (*io_int_wait)(int slot, TickType_t timeout_ticks) Host function to wait for SDIO interrupt line to be active - int command_timeout_ms timeout, in milliseconds, of a single command. Set to 0 to use the default value. - esp_err_t (*get_real_freq)(int slot, int *real_freq) Host function to provide real working freq, based on SDMMC controller setup - sdmmc_delay_phase_t input_delay_phase input delay phase, this will only take into effect when the host works in SDMMC_FREQ_HIGHSPEED or SDMMC_FREQ_52M. Driver will print out how long the delay is - esp_err_t (*set_input_delay)(int slot, sdmmc_delay_phase_t delay_phase) set input delay phase - uint32_t flags - struct sdmmc_card_t SD/MMC card information structure Public Members - sdmmc_host_t host Host with which the card is associated - uint32_t ocr OCR (Operation Conditions Register) value - sdmmc_cid_t cid decoded CID (Card IDentification) register value - sdmmc_response_t raw_cid raw CID of MMC card to be decoded after the CSD is fetched in the data transfer mode - sdmmc_csd_t csd decoded CSD (Card-Specific Data) register value - sdmmc_scr_t scr decoded SCR (SD card Configuration Register) value - sdmmc_ssr_t ssr decoded SSR (SD Status Register) value - sdmmc_ext_csd_t ext_csd decoded EXT_CSD (Extended Card Specific Data) register value - uint16_t rca RCA (Relative Card Address) - uint16_t max_freq_khz Maximum frequency, in kHz, supported by the card - int real_freq_khz Real working frequency, in kHz, configured on the host controller - uint32_t is_mem Bit indicates if the card is a memory card - uint32_t is_sdio Bit indicates if the card is an IO card - uint32_t is_mmc Bit indicates if the card is MMC - uint32_t num_io_functions If is_sdio is 1, contains the number of IO functions on the card - uint32_t log_bus_width log2(bus width supported by card) - uint32_t is_ddr Card supports DDR mode - uint32_t reserved Reserved for future expansion - sdmmc_host_t host Macros - SDMMC_HOST_FLAG_1BIT host supports 1-line SD and MMC protocol - SDMMC_HOST_FLAG_4BIT host supports 4-line SD and MMC protocol - SDMMC_HOST_FLAG_8BIT host supports 8-line MMC protocol - SDMMC_HOST_FLAG_SPI host supports SPI protocol - SDMMC_HOST_FLAG_DDR host supports DDR mode for SD/MMC - SDMMC_HOST_FLAG_DEINIT_ARG host deinitfunction called with the slot argument - SDMMC_FREQ_DEFAULT SD/MMC Default speed (limited by clock divider) - SDMMC_FREQ_HIGHSPEED SD High speed (limited by clock divider) - SDMMC_FREQ_PROBING SD/MMC probing speed - SDMMC_FREQ_52M MMC 52MHz speed - SDMMC_FREQ_26M MMC 26MHz speed Type Definitions - typedef uint32_t sdmmc_response_t[4] SD/MMC command response buffer Enumerations - enum sdmmc_delay_phase_t SD/MMC Host clock timing delay phases This will only take effect when the host works in SDMMC_FREQ_HIGHSPEED or SDMMC_FREQ_52M. Driver will print out how long the delay is, in picosecond (ps). Values: - enumerator SDMMC_DELAY_PHASE_0 Delay phase 0 - enumerator SDMMC_DELAY_PHASE_1 Delay phase 1 - enumerator SDMMC_DELAY_PHASE_2 Delay phase 2 - enumerator SDMMC_DELAY_PHASE_3 Delay phase 3 - enumerator SDMMC_DELAY_PHASE_0 - enum sdmmc_erase_arg_t SD/MMC erase command(38) arguments SD: ERASE: Erase the write blocks, physical/hard erase. DISCARD: Card may deallocate the discarded blocks partially or completely. After discard operation the previously written data may be partially or fully read by the host depending on card implementation. MMC: ERASE: Does TRIM, applies erase operation to write blocks instead of Erase Group. DISCARD: The Discard function allows the host to identify data that is no longer required so that the device can erase the data if necessary during background erase events. Applies to write blocks instead of Erase Group After discard operation, the original data may be remained partially or fully accessible to the host dependent on device. Values: - enumerator SDMMC_ERASE_ARG Erase operation on SD, Trim operation on MMC - enumerator SDMMC_DISCARD_ARG Discard operation for SD/MMC - enumerator SDMMC_ERASE_ARG
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/storage/sdmmc.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Partitions API
null
espressif.com
2016-01-01
8c65c01ba6ace8df
null
null
Partitions API Overview The esp_partition component has higher-level API functions which work with partitions defined in the Partition Tables. These APIs are based on lower level API provided by SPI Flash API. Partition Table API ESP-IDF projects use a partition table to maintain information about various regions of SPI flash memory (bootloader, various application binaries, data, filesystems). More information can be found in Partition Tables. This component provides API functions to enumerate partitions found in the partition table and perform operations on them. These functions are declared in esp_partition.h : esp_partition_find() checks a partition table for entries with specific type, returns an opaque iterator. esp_partition_get() returns a structure describing the partition for a given iterator. esp_partition_next() shifts the iterator to the next found partition. esp_partition_iterator_release() releases iterator returned by esp_partition_find() . esp_partition_find_first() is a convenience function which returns the structure describing the first partition found by esp_partition_find() . esp_partition_read() , esp_partition_write() , esp_partition_erase_range() are equivalent to esp_flash_read() , esp_flash_write() , esp_flash_erase_region() , but operate within partition boundaries. See Also Over The Air Updates (OTA) provides high-level API for updating applications stored in flash. Non-Volatile Storage Library provides a structured API for storing small pieces of data in SPI flash. API Reference - Partition Table Header File This header file can be included with: #include "esp_partition.h" This header file is a part of the API provided by the esp_partition component. To declare that your component depends on esp_partition , add the following to your CMakeLists.txt: REQUIRES esp_partition or PRIV_REQUIRES esp_partition Functions esp_partition_iterator_t esp_partition_find(esp_partition_type_t type, esp_partition_subtype_t subtype, const char *label) Find partition based on one or more parameters. Parameters type -- Partition type, one of esp_partition_type_t values or an 8-bit unsigned integer. To find all partitions, no matter the type, use ESP_PARTITION_TYPE_ANY, and set subtype argument to ESP_PARTITION_SUBTYPE_ANY. subtype -- Partition subtype, one of esp_partition_subtype_t values or an 8-bit unsigned integer. To find all partitions of given type, use ESP_PARTITION_SUBTYPE_ANY. label -- (optional) Partition label. Set this value if looking for partition with a specific name. Pass NULL otherwise. type -- Partition type, one of esp_partition_type_t values or an 8-bit unsigned integer. To find all partitions, no matter the type, use ESP_PARTITION_TYPE_ANY, and set subtype argument to ESP_PARTITION_SUBTYPE_ANY. subtype -- Partition subtype, one of esp_partition_subtype_t values or an 8-bit unsigned integer. To find all partitions of given type, use ESP_PARTITION_SUBTYPE_ANY. label -- (optional) Partition label. Set this value if looking for partition with a specific name. Pass NULL otherwise. type -- Partition type, one of esp_partition_type_t values or an 8-bit unsigned integer. To find all partitions, no matter the type, use ESP_PARTITION_TYPE_ANY, and set subtype argument to ESP_PARTITION_SUBTYPE_ANY. Returns iterator which can be used to enumerate all the partitions found, or NULL if no partitions were found. Iterator obtained through this function has to be released using esp_partition_iterator_release when not used any more. Parameters type -- Partition type, one of esp_partition_type_t values or an 8-bit unsigned integer. To find all partitions, no matter the type, use ESP_PARTITION_TYPE_ANY, and set subtype argument to ESP_PARTITION_SUBTYPE_ANY. subtype -- Partition subtype, one of esp_partition_subtype_t values or an 8-bit unsigned integer. To find all partitions of given type, use ESP_PARTITION_SUBTYPE_ANY. label -- (optional) Partition label. Set this value if looking for partition with a specific name. Pass NULL otherwise. Returns iterator which can be used to enumerate all the partitions found, or NULL if no partitions were found. Iterator obtained through this function has to be released using esp_partition_iterator_release when not used any more. const esp_partition_t *esp_partition_find_first(esp_partition_type_t type, esp_partition_subtype_t subtype, const char *label) Find first partition based on one or more parameters. Parameters type -- Partition type, one of esp_partition_type_t values or an 8-bit unsigned integer. To find all partitions, no matter the type, use ESP_PARTITION_TYPE_ANY, and set subtype argument to ESP_PARTITION_SUBTYPE_ANY. subtype -- Partition subtype, one of esp_partition_subtype_t values or an 8-bit unsigned integer To find all partitions of given type, use ESP_PARTITION_SUBTYPE_ANY. label -- (optional) Partition label. Set this value if looking for partition with a specific name. Pass NULL otherwise. type -- Partition type, one of esp_partition_type_t values or an 8-bit unsigned integer. To find all partitions, no matter the type, use ESP_PARTITION_TYPE_ANY, and set subtype argument to ESP_PARTITION_SUBTYPE_ANY. subtype -- Partition subtype, one of esp_partition_subtype_t values or an 8-bit unsigned integer To find all partitions of given type, use ESP_PARTITION_SUBTYPE_ANY. label -- (optional) Partition label. Set this value if looking for partition with a specific name. Pass NULL otherwise. type -- Partition type, one of esp_partition_type_t values or an 8-bit unsigned integer. To find all partitions, no matter the type, use ESP_PARTITION_TYPE_ANY, and set subtype argument to ESP_PARTITION_SUBTYPE_ANY. Returns pointer to esp_partition_t structure, or NULL if no partition is found. This pointer is valid for the lifetime of the application. Parameters type -- Partition type, one of esp_partition_type_t values or an 8-bit unsigned integer. To find all partitions, no matter the type, use ESP_PARTITION_TYPE_ANY, and set subtype argument to ESP_PARTITION_SUBTYPE_ANY. subtype -- Partition subtype, one of esp_partition_subtype_t values or an 8-bit unsigned integer To find all partitions of given type, use ESP_PARTITION_SUBTYPE_ANY. label -- (optional) Partition label. Set this value if looking for partition with a specific name. Pass NULL otherwise. Returns pointer to esp_partition_t structure, or NULL if no partition is found. This pointer is valid for the lifetime of the application. const esp_partition_t *esp_partition_get(esp_partition_iterator_t iterator) Get esp_partition_t structure for given partition. Parameters iterator -- Iterator obtained using esp_partition_find. Must be non-NULL. Returns pointer to esp_partition_t structure. This pointer is valid for the lifetime of the application. Parameters iterator -- Iterator obtained using esp_partition_find. Must be non-NULL. Returns pointer to esp_partition_t structure. This pointer is valid for the lifetime of the application. esp_partition_iterator_t esp_partition_next(esp_partition_iterator_t iterator) Move partition iterator to the next partition found. Any copies of the iterator will be invalid after this call. Parameters iterator -- Iterator obtained using esp_partition_find. Must be non-NULL. Returns NULL if no partition was found, valid esp_partition_iterator_t otherwise. Parameters iterator -- Iterator obtained using esp_partition_find. Must be non-NULL. Returns NULL if no partition was found, valid esp_partition_iterator_t otherwise. void esp_partition_iterator_release(esp_partition_iterator_t iterator) Release partition iterator. Parameters iterator -- Iterator obtained using esp_partition_find. The iterator is allowed to be NULL, so it is not necessary to check its value before calling this function. Parameters iterator -- Iterator obtained using esp_partition_find. The iterator is allowed to be NULL, so it is not necessary to check its value before calling this function. const esp_partition_t *esp_partition_verify(const esp_partition_t *partition) Verify partition data. Given a pointer to partition data, verify this partition exists in the partition table (all fields match.) This function is also useful to take partition data which may be in a RAM buffer and convert it to a pointer to the permanent partition data stored in flash. Pointers returned from this function can be compared directly to the address of any pointer returned from esp_partition_get(), as a test for equality. Parameters partition -- Pointer to partition data to verify. Must be non-NULL. All fields of this structure must match the partition table entry in flash for this function to return a successful match. Returns If partition not found, returns NULL. If found, returns a pointer to the esp_partition_t structure in flash. This pointer is always valid for the lifetime of the application. If partition not found, returns NULL. If found, returns a pointer to the esp_partition_t structure in flash. This pointer is always valid for the lifetime of the application. If partition not found, returns NULL. Parameters partition -- Pointer to partition data to verify. Must be non-NULL. All fields of this structure must match the partition table entry in flash for this function to return a successful match. Returns If partition not found, returns NULL. If found, returns a pointer to the esp_partition_t structure in flash. This pointer is always valid for the lifetime of the application. esp_err_t esp_partition_read(const esp_partition_t *partition, size_t src_offset, void *dst, size_t size) Read data from the partition. Partitions marked with an encryption flag will automatically be be read and decrypted via a cache mapping. Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst -- Pointer to the buffer where data should be stored. Pointer must be non-NULL and buffer must be at least 'size' bytes long. src_offset -- Address of the data to be read, relative to the beginning of the partition. size -- Size of data to be read, in bytes. partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst -- Pointer to the buffer where data should be stored. Pointer must be non-NULL and buffer must be at least 'size' bytes long. src_offset -- Address of the data to be read, relative to the beginning of the partition. size -- Size of data to be read, in bytes. partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. Returns ESP_OK, if data was read successfully; ESP_ERR_INVALID_ARG, if src_offset exceeds partition size; ESP_ERR_INVALID_SIZE, if read would go out of bounds of the partition; or one of error codes from lower-level flash driver. Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst -- Pointer to the buffer where data should be stored. Pointer must be non-NULL and buffer must be at least 'size' bytes long. src_offset -- Address of the data to be read, relative to the beginning of the partition. size -- Size of data to be read, in bytes. Returns ESP_OK, if data was read successfully; ESP_ERR_INVALID_ARG, if src_offset exceeds partition size; ESP_ERR_INVALID_SIZE, if read would go out of bounds of the partition; or one of error codes from lower-level flash driver. esp_err_t esp_partition_write(const esp_partition_t *partition, size_t dst_offset, const void *src, size_t size) Write data to the partition. Before writing data to flash, corresponding region of flash needs to be erased. This can be done using esp_partition_erase_range function. Partitions marked with an encryption flag will automatically be written via the esp_flash_write_encrypted() function. If writing to an encrypted partition, all write offsets and lengths must be multiples of 16 bytes. See the esp_flash_write_encrypted() function for more details. Unencrypted partitions do not have this restriction. Note Prior to writing to flash memory, make sure it has been erased with esp_partition_erase_range call. Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst_offset -- Address where the data should be written, relative to the beginning of the partition. src -- Pointer to the source buffer. Pointer must be non-NULL and buffer must be at least 'size' bytes long. size -- Size of data to be written, in bytes. partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst_offset -- Address where the data should be written, relative to the beginning of the partition. src -- Pointer to the source buffer. Pointer must be non-NULL and buffer must be at least 'size' bytes long. size -- Size of data to be written, in bytes. partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. Returns ESP_OK, if data was written successfully; ESP_ERR_INVALID_ARG, if dst_offset exceeds partition size; ESP_ERR_INVALID_SIZE, if write would go out of bounds of the partition; ESP_ERR_NOT_ALLOWED, if partition is read-only; or one of error codes from lower-level flash driver. Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst_offset -- Address where the data should be written, relative to the beginning of the partition. src -- Pointer to the source buffer. Pointer must be non-NULL and buffer must be at least 'size' bytes long. size -- Size of data to be written, in bytes. Returns ESP_OK, if data was written successfully; ESP_ERR_INVALID_ARG, if dst_offset exceeds partition size; ESP_ERR_INVALID_SIZE, if write would go out of bounds of the partition; ESP_ERR_NOT_ALLOWED, if partition is read-only; or one of error codes from lower-level flash driver. esp_err_t esp_partition_read_raw(const esp_partition_t *partition, size_t src_offset, void *dst, size_t size) Read data from the partition without any transformation/decryption. Note This function is essentially the same as esp_partition_read() above. It just never decrypts data but returns it as is. Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst -- Pointer to the buffer where data should be stored. Pointer must be non-NULL and buffer must be at least 'size' bytes long. src_offset -- Address of the data to be read, relative to the beginning of the partition. size -- Size of data to be read, in bytes. partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst -- Pointer to the buffer where data should be stored. Pointer must be non-NULL and buffer must be at least 'size' bytes long. src_offset -- Address of the data to be read, relative to the beginning of the partition. size -- Size of data to be read, in bytes. partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. Returns ESP_OK, if data was read successfully; ESP_ERR_INVALID_ARG, if src_offset exceeds partition size; ESP_ERR_INVALID_SIZE, if read would go out of bounds of the partition; or one of error codes from lower-level flash driver. Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst -- Pointer to the buffer where data should be stored. Pointer must be non-NULL and buffer must be at least 'size' bytes long. src_offset -- Address of the data to be read, relative to the beginning of the partition. size -- Size of data to be read, in bytes. Returns ESP_OK, if data was read successfully; ESP_ERR_INVALID_ARG, if src_offset exceeds partition size; ESP_ERR_INVALID_SIZE, if read would go out of bounds of the partition; or one of error codes from lower-level flash driver. esp_err_t esp_partition_write_raw(const esp_partition_t *partition, size_t dst_offset, const void *src, size_t size) Write data to the partition without any transformation/encryption. Before writing data to flash, corresponding region of flash needs to be erased. This can be done using esp_partition_erase_range function. Note This function is essentially the same as esp_partition_write() above. It just never encrypts data but writes it as is. Note Prior to writing to flash memory, make sure it has been erased with esp_partition_erase_range call. Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst_offset -- Address where the data should be written, relative to the beginning of the partition. src -- Pointer to the source buffer. Pointer must be non-NULL and buffer must be at least 'size' bytes long. size -- Size of data to be written, in bytes. partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst_offset -- Address where the data should be written, relative to the beginning of the partition. src -- Pointer to the source buffer. Pointer must be non-NULL and buffer must be at least 'size' bytes long. size -- Size of data to be written, in bytes. partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. Returns ESP_OK, if data was written successfully; ESP_ERR_INVALID_ARG, if dst_offset exceeds partition size; ESP_ERR_INVALID_SIZE, if write would go out of bounds of the partition; ESP_ERR_NOT_ALLOWED, if partition is read-only; or one of the error codes from lower-level flash driver. Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst_offset -- Address where the data should be written, relative to the beginning of the partition. src -- Pointer to the source buffer. Pointer must be non-NULL and buffer must be at least 'size' bytes long. size -- Size of data to be written, in bytes. Returns ESP_OK, if data was written successfully; ESP_ERR_INVALID_ARG, if dst_offset exceeds partition size; ESP_ERR_INVALID_SIZE, if write would go out of bounds of the partition; ESP_ERR_NOT_ALLOWED, if partition is read-only; or one of the error codes from lower-level flash driver. esp_err_t esp_partition_erase_range(const esp_partition_t *partition, size_t offset, size_t size) Erase part of the partition. Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. offset -- Offset from the beginning of partition where erase operation should start. Must be aligned to partition->erase_size. size -- Size of the range which should be erased, in bytes. Must be divisible by partition->erase_size. partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. offset -- Offset from the beginning of partition where erase operation should start. Must be aligned to partition->erase_size. size -- Size of the range which should be erased, in bytes. Must be divisible by partition->erase_size. partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. Returns ESP_OK, if the range was erased successfully; ESP_ERR_INVALID_ARG, if iterator or dst are NULL; ESP_ERR_INVALID_SIZE, if erase would go out of bounds of the partition; ESP_ERR_NOT_ALLOWED, if partition is read-only; or one of error codes from lower-level flash driver. Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. offset -- Offset from the beginning of partition where erase operation should start. Must be aligned to partition->erase_size. size -- Size of the range which should be erased, in bytes. Must be divisible by partition->erase_size. Returns ESP_OK, if the range was erased successfully; ESP_ERR_INVALID_ARG, if iterator or dst are NULL; ESP_ERR_INVALID_SIZE, if erase would go out of bounds of the partition; ESP_ERR_NOT_ALLOWED, if partition is read-only; or one of error codes from lower-level flash driver. esp_err_t esp_partition_mmap(const esp_partition_t *partition, size_t offset, size_t size, esp_partition_mmap_memory_t memory, const void **out_ptr, esp_partition_mmap_handle_t *out_handle) Configure MMU to map partition into data memory. Unlike spi_flash_mmap function, which requires a 64kB aligned base address, this function doesn't impose such a requirement. If offset results in a flash address which is not aligned to 64kB boundary, address will be rounded to the lower 64kB boundary, so that mapped region includes requested range. Pointer returned via out_ptr argument will be adjusted to point to the requested offset (not necessarily to the beginning of mmap-ed region). To release mapped memory, pass handle returned via out_handle argument to esp_partition_munmap function. Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. offset -- Offset from the beginning of partition where mapping should start. size -- Size of the area to be mapped. memory -- Memory space where the region should be mapped out_ptr -- Output, pointer to the mapped memory region out_handle -- Output, handle which should be used for esp_partition_munmap call partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. offset -- Offset from the beginning of partition where mapping should start. size -- Size of the area to be mapped. memory -- Memory space where the region should be mapped out_ptr -- Output, pointer to the mapped memory region out_handle -- Output, handle which should be used for esp_partition_munmap call partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. Returns ESP_OK, if successful Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. offset -- Offset from the beginning of partition where mapping should start. size -- Size of the area to be mapped. memory -- Memory space where the region should be mapped out_ptr -- Output, pointer to the mapped memory region out_handle -- Output, handle which should be used for esp_partition_munmap call Returns ESP_OK, if successful void esp_partition_munmap(esp_partition_mmap_handle_t handle) Release region previously obtained using esp_partition_mmap. Note Calling this function will not necessarily unmap memory region. Region will only be unmapped when there are no other handles which reference this region. In case of partially overlapping regions it is possible that memory will be unmapped partially. Parameters handle -- Handle obtained from spi_flash_mmap Parameters handle -- Handle obtained from spi_flash_mmap esp_err_t esp_partition_get_sha256(const esp_partition_t *partition, uint8_t *sha_256) Get SHA-256 digest for required partition. For apps with SHA-256 appended to the app image, the result is the appended SHA-256 value for the app image content. The hash is verified before returning, if app content is invalid then the function returns ESP_ERR_IMAGE_INVALID. For apps without SHA-256 appended to the image, the result is the SHA-256 of all bytes in the app image. For other partition types, the result is the SHA-256 of the entire partition. Parameters partition -- [in] Pointer to info for partition containing app or data. (fields: address, size and type, are required to be filled). sha_256 -- [out] Returned SHA-256 digest for a given partition. partition -- [in] Pointer to info for partition containing app or data. (fields: address, size and type, are required to be filled). sha_256 -- [out] Returned SHA-256 digest for a given partition. partition -- [in] Pointer to info for partition containing app or data. (fields: address, size and type, are required to be filled). Returns ESP_OK: In case of successful operation. ESP_ERR_INVALID_ARG: The size was 0 or the sha_256 was NULL. ESP_ERR_NO_MEM: Cannot allocate memory for sha256 operation. ESP_ERR_IMAGE_INVALID: App partition doesn't contain a valid app image. ESP_FAIL: An allocation error occurred. ESP_OK: In case of successful operation. ESP_ERR_INVALID_ARG: The size was 0 or the sha_256 was NULL. ESP_ERR_NO_MEM: Cannot allocate memory for sha256 operation. ESP_ERR_IMAGE_INVALID: App partition doesn't contain a valid app image. ESP_FAIL: An allocation error occurred. ESP_OK: In case of successful operation. Parameters partition -- [in] Pointer to info for partition containing app or data. (fields: address, size and type, are required to be filled). sha_256 -- [out] Returned SHA-256 digest for a given partition. Returns ESP_OK: In case of successful operation. ESP_ERR_INVALID_ARG: The size was 0 or the sha_256 was NULL. ESP_ERR_NO_MEM: Cannot allocate memory for sha256 operation. ESP_ERR_IMAGE_INVALID: App partition doesn't contain a valid app image. ESP_FAIL: An allocation error occurred. bool esp_partition_check_identity(const esp_partition_t *partition_1, const esp_partition_t *partition_2) Check for the identity of two partitions by SHA-256 digest. Parameters partition_1 -- [in] Pointer to info for partition 1 containing app or data. (fields: address, size and type, are required to be filled). partition_2 -- [in] Pointer to info for partition 2 containing app or data. (fields: address, size and type, are required to be filled). partition_1 -- [in] Pointer to info for partition 1 containing app or data. (fields: address, size and type, are required to be filled). partition_2 -- [in] Pointer to info for partition 2 containing app or data. (fields: address, size and type, are required to be filled). partition_1 -- [in] Pointer to info for partition 1 containing app or data. (fields: address, size and type, are required to be filled). Returns True: In case of the two firmware is equal. False: Otherwise True: In case of the two firmware is equal. False: Otherwise True: In case of the two firmware is equal. Parameters partition_1 -- [in] Pointer to info for partition 1 containing app or data. (fields: address, size and type, are required to be filled). partition_2 -- [in] Pointer to info for partition 2 containing app or data. (fields: address, size and type, are required to be filled). Returns True: In case of the two firmware is equal. False: Otherwise esp_err_t esp_partition_register_external(esp_flash_t *flash_chip, size_t offset, size_t size, const char *label, esp_partition_type_t type, esp_partition_subtype_t subtype, const esp_partition_t **out_partition) Register a partition on an external flash chip. This API allows designating certain areas of external flash chips (identified by the esp_flash_t structure) as partitions. This allows using them with components which access SPI flash through the esp_partition API. Parameters flash_chip -- Pointer to the structure identifying the flash chip offset -- Address in bytes, where the partition starts size -- Size of the partition in bytes label -- Partition name type -- One of the partition types (ESP_PARTITION_TYPE_*), or an integer. Note that applications can not be booted from external flash chips, so using ESP_PARTITION_TYPE_APP is not supported. subtype -- One of the partition subtypes (ESP_PARTITION_SUBTYPE_*), or an integer. out_partition -- [out] Output, if non-NULL, receives the pointer to the resulting esp_partition_t structure flash_chip -- Pointer to the structure identifying the flash chip offset -- Address in bytes, where the partition starts size -- Size of the partition in bytes label -- Partition name type -- One of the partition types (ESP_PARTITION_TYPE_*), or an integer. Note that applications can not be booted from external flash chips, so using ESP_PARTITION_TYPE_APP is not supported. subtype -- One of the partition subtypes (ESP_PARTITION_SUBTYPE_*), or an integer. out_partition -- [out] Output, if non-NULL, receives the pointer to the resulting esp_partition_t structure flash_chip -- Pointer to the structure identifying the flash chip Returns ESP_OK on success ESP_ERR_NO_MEM if memory allocation has failed ESP_ERR_INVALID_ARG if the new partition overlaps another partition on the same flash chip ESP_ERR_INVALID_SIZE if the partition doesn't fit into the flash chip size ESP_OK on success ESP_ERR_NO_MEM if memory allocation has failed ESP_ERR_INVALID_ARG if the new partition overlaps another partition on the same flash chip ESP_ERR_INVALID_SIZE if the partition doesn't fit into the flash chip size ESP_OK on success Parameters flash_chip -- Pointer to the structure identifying the flash chip offset -- Address in bytes, where the partition starts size -- Size of the partition in bytes label -- Partition name type -- One of the partition types (ESP_PARTITION_TYPE_*), or an integer. Note that applications can not be booted from external flash chips, so using ESP_PARTITION_TYPE_APP is not supported. subtype -- One of the partition subtypes (ESP_PARTITION_SUBTYPE_*), or an integer. out_partition -- [out] Output, if non-NULL, receives the pointer to the resulting esp_partition_t structure Returns ESP_OK on success ESP_ERR_NO_MEM if memory allocation has failed ESP_ERR_INVALID_ARG if the new partition overlaps another partition on the same flash chip ESP_ERR_INVALID_SIZE if the partition doesn't fit into the flash chip size esp_err_t esp_partition_deregister_external(const esp_partition_t *partition) Deregister the partition previously registered using esp_partition_register_external. Parameters partition -- pointer to the partition structure obtained from esp_partition_register_external, Returns ESP_OK on success ESP_ERR_NOT_FOUND if the partition pointer is not found ESP_ERR_INVALID_ARG if the partition comes from the partition table ESP_ERR_INVALID_ARG if the partition was not registered using esp_partition_register_external function. ESP_OK on success ESP_ERR_NOT_FOUND if the partition pointer is not found ESP_ERR_INVALID_ARG if the partition comes from the partition table ESP_ERR_INVALID_ARG if the partition was not registered using esp_partition_register_external function. ESP_OK on success Parameters partition -- pointer to the partition structure obtained from esp_partition_register_external, Returns ESP_OK on success ESP_ERR_NOT_FOUND if the partition pointer is not found ESP_ERR_INVALID_ARG if the partition comes from the partition table ESP_ERR_INVALID_ARG if the partition was not registered using esp_partition_register_external function. void esp_partition_unload_all(void) Unload partitions and free space allocated by them. Structures struct esp_partition_t partition information structure This is not the format in flash, that format is esp_partition_info_t. However, this is the format used by this API. Public Members esp_flash_t *flash_chip SPI flash chip on which the partition resides esp_flash_t *flash_chip SPI flash chip on which the partition resides esp_partition_type_t type partition type (app/data) esp_partition_type_t type partition type (app/data) esp_partition_subtype_t subtype partition subtype esp_partition_subtype_t subtype partition subtype uint32_t address starting address of the partition in flash uint32_t address starting address of the partition in flash uint32_t size size of the partition, in bytes uint32_t size size of the partition, in bytes uint32_t erase_size size the erase operation should be aligned to uint32_t erase_size size the erase operation should be aligned to char label[17] partition label, zero-terminated ASCII string char label[17] partition label, zero-terminated ASCII string bool encrypted flag is set to true if partition is encrypted bool encrypted flag is set to true if partition is encrypted bool readonly flag is set to true if partition is read-only bool readonly flag is set to true if partition is read-only esp_flash_t *flash_chip Macros ESP_PARTITION_SUBTYPE_OTA(i) Convenience macro to get esp_partition_subtype_t value for the i-th OTA partition. Type Definitions typedef uint32_t esp_partition_mmap_handle_t Opaque handle for memory region obtained from esp_partition_mmap. typedef struct esp_partition_iterator_opaque_ *esp_partition_iterator_t Opaque partition iterator type. Enumerations enum esp_partition_mmap_memory_t Enumeration which specifies memory space requested in an mmap call. Values: enumerator ESP_PARTITION_MMAP_DATA map to data memory (Vaddr0), allows byte-aligned access, 4 MB total enumerator ESP_PARTITION_MMAP_DATA map to data memory (Vaddr0), allows byte-aligned access, 4 MB total enumerator ESP_PARTITION_MMAP_INST map to instruction memory (Vaddr1-3), allows only 4-byte-aligned access, 11 MB total enumerator ESP_PARTITION_MMAP_INST map to instruction memory (Vaddr1-3), allows only 4-byte-aligned access, 11 MB total enumerator ESP_PARTITION_MMAP_DATA enum esp_partition_type_t Partition type. Note Partition types with integer value 0x00-0x3F are reserved for partition types defined by ESP-IDF. Any other integer value 0x40-0xFE can be used by individual applications, without restriction. Values: enumerator ESP_PARTITION_TYPE_APP Application partition type. enumerator ESP_PARTITION_TYPE_APP Application partition type. enumerator ESP_PARTITION_TYPE_DATA Data partition type. enumerator ESP_PARTITION_TYPE_DATA Data partition type. enumerator ESP_PARTITION_TYPE_ANY Used to search for partitions with any type. enumerator ESP_PARTITION_TYPE_ANY Used to search for partitions with any type. enumerator ESP_PARTITION_TYPE_APP enum esp_partition_subtype_t Partition subtype. Application-defined partition types (0x40-0xFE) can set any numeric subtype value. Note These ESP-IDF-defined partition subtypes apply to partitions of type ESP_PARTITION_TYPE_APP and ESP_PARTITION_TYPE_DATA. Values: enumerator ESP_PARTITION_SUBTYPE_APP_FACTORY Factory application partition. enumerator ESP_PARTITION_SUBTYPE_APP_FACTORY Factory application partition. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_MIN Base for OTA partition subtypes. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_MIN Base for OTA partition subtypes. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_0 OTA partition 0. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_0 OTA partition 0. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_1 OTA partition 1. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_1 OTA partition 1. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_2 OTA partition 2. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_2 OTA partition 2. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_3 OTA partition 3. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_3 OTA partition 3. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_4 OTA partition 4. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_4 OTA partition 4. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_5 OTA partition 5. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_5 OTA partition 5. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_6 OTA partition 6. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_6 OTA partition 6. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_7 OTA partition 7. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_7 OTA partition 7. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_8 OTA partition 8. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_8 OTA partition 8. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_9 OTA partition 9. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_9 OTA partition 9. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_10 OTA partition 10. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_10 OTA partition 10. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_11 OTA partition 11. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_11 OTA partition 11. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_12 OTA partition 12. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_12 OTA partition 12. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_13 OTA partition 13. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_13 OTA partition 13. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_14 OTA partition 14. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_14 OTA partition 14. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_15 OTA partition 15. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_15 OTA partition 15. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_MAX Max subtype of OTA partition. enumerator ESP_PARTITION_SUBTYPE_APP_OTA_MAX Max subtype of OTA partition. enumerator ESP_PARTITION_SUBTYPE_APP_TEST Test application partition. enumerator ESP_PARTITION_SUBTYPE_APP_TEST Test application partition. enumerator ESP_PARTITION_SUBTYPE_DATA_OTA OTA selection partition. enumerator ESP_PARTITION_SUBTYPE_DATA_OTA OTA selection partition. enumerator ESP_PARTITION_SUBTYPE_DATA_PHY PHY init data partition. enumerator ESP_PARTITION_SUBTYPE_DATA_PHY PHY init data partition. enumerator ESP_PARTITION_SUBTYPE_DATA_NVS NVS partition. enumerator ESP_PARTITION_SUBTYPE_DATA_NVS NVS partition. enumerator ESP_PARTITION_SUBTYPE_DATA_COREDUMP COREDUMP partition. enumerator ESP_PARTITION_SUBTYPE_DATA_COREDUMP COREDUMP partition. enumerator ESP_PARTITION_SUBTYPE_DATA_NVS_KEYS Partition for NVS keys. enumerator ESP_PARTITION_SUBTYPE_DATA_NVS_KEYS Partition for NVS keys. enumerator ESP_PARTITION_SUBTYPE_DATA_EFUSE_EM Partition for emulate eFuse bits. enumerator ESP_PARTITION_SUBTYPE_DATA_EFUSE_EM Partition for emulate eFuse bits. enumerator ESP_PARTITION_SUBTYPE_DATA_UNDEFINED Undefined (or unspecified) data partition. enumerator ESP_PARTITION_SUBTYPE_DATA_UNDEFINED Undefined (or unspecified) data partition. enumerator ESP_PARTITION_SUBTYPE_DATA_ESPHTTPD ESPHTTPD partition. enumerator ESP_PARTITION_SUBTYPE_DATA_ESPHTTPD ESPHTTPD partition. enumerator ESP_PARTITION_SUBTYPE_DATA_FAT FAT partition. enumerator ESP_PARTITION_SUBTYPE_DATA_FAT FAT partition. enumerator ESP_PARTITION_SUBTYPE_DATA_SPIFFS SPIFFS partition. enumerator ESP_PARTITION_SUBTYPE_DATA_SPIFFS SPIFFS partition. enumerator ESP_PARTITION_SUBTYPE_DATA_LITTLEFS LITTLEFS partition. enumerator ESP_PARTITION_SUBTYPE_DATA_LITTLEFS LITTLEFS partition. enumerator ESP_PARTITION_SUBTYPE_ANY Used to search for partitions with any subtype. enumerator ESP_PARTITION_SUBTYPE_ANY Used to search for partitions with any subtype. enumerator ESP_PARTITION_SUBTYPE_APP_FACTORY
Partitions API Overview The esp_partition component has higher-level API functions which work with partitions defined in the Partition Tables. These APIs are based on lower level API provided by SPI Flash API. Partition Table API ESP-IDF projects use a partition table to maintain information about various regions of SPI flash memory (bootloader, various application binaries, data, filesystems). More information can be found in Partition Tables. This component provides API functions to enumerate partitions found in the partition table and perform operations on them. These functions are declared in esp_partition.h: esp_partition_find()checks a partition table for entries with specific type, returns an opaque iterator. esp_partition_get()returns a structure describing the partition for a given iterator. esp_partition_next()shifts the iterator to the next found partition. esp_partition_iterator_release()releases iterator returned by esp_partition_find(). esp_partition_find_first()is a convenience function which returns the structure describing the first partition found by esp_partition_find(). esp_partition_read(), esp_partition_write(), esp_partition_erase_range()are equivalent to esp_flash_read(), esp_flash_write(), esp_flash_erase_region(), but operate within partition boundaries. See Also Over The Air Updates (OTA) provides high-level API for updating applications stored in flash. Non-Volatile Storage Library provides a structured API for storing small pieces of data in SPI flash. API Reference - Partition Table Header File This header file can be included with: #include "esp_partition.h" This header file is a part of the API provided by the esp_partitioncomponent. To declare that your component depends on esp_partition, add the following to your CMakeLists.txt: REQUIRES esp_partition or PRIV_REQUIRES esp_partition Functions - esp_partition_iterator_t esp_partition_find(esp_partition_type_t type, esp_partition_subtype_t subtype, const char *label) Find partition based on one or more parameters. - Parameters type -- Partition type, one of esp_partition_type_t values or an 8-bit unsigned integer. To find all partitions, no matter the type, use ESP_PARTITION_TYPE_ANY, and set subtype argument to ESP_PARTITION_SUBTYPE_ANY. subtype -- Partition subtype, one of esp_partition_subtype_t values or an 8-bit unsigned integer. To find all partitions of given type, use ESP_PARTITION_SUBTYPE_ANY. label -- (optional) Partition label. Set this value if looking for partition with a specific name. Pass NULL otherwise. - - Returns iterator which can be used to enumerate all the partitions found, or NULL if no partitions were found. Iterator obtained through this function has to be released using esp_partition_iterator_release when not used any more. - const esp_partition_t *esp_partition_find_first(esp_partition_type_t type, esp_partition_subtype_t subtype, const char *label) Find first partition based on one or more parameters. - Parameters type -- Partition type, one of esp_partition_type_t values or an 8-bit unsigned integer. To find all partitions, no matter the type, use ESP_PARTITION_TYPE_ANY, and set subtype argument to ESP_PARTITION_SUBTYPE_ANY. subtype -- Partition subtype, one of esp_partition_subtype_t values or an 8-bit unsigned integer To find all partitions of given type, use ESP_PARTITION_SUBTYPE_ANY. label -- (optional) Partition label. Set this value if looking for partition with a specific name. Pass NULL otherwise. - - Returns pointer to esp_partition_t structure, or NULL if no partition is found. This pointer is valid for the lifetime of the application. - const esp_partition_t *esp_partition_get(esp_partition_iterator_t iterator) Get esp_partition_t structure for given partition. - Parameters iterator -- Iterator obtained using esp_partition_find. Must be non-NULL. - Returns pointer to esp_partition_t structure. This pointer is valid for the lifetime of the application. - esp_partition_iterator_t esp_partition_next(esp_partition_iterator_t iterator) Move partition iterator to the next partition found. Any copies of the iterator will be invalid after this call. - Parameters iterator -- Iterator obtained using esp_partition_find. Must be non-NULL. - Returns NULL if no partition was found, valid esp_partition_iterator_t otherwise. - void esp_partition_iterator_release(esp_partition_iterator_t iterator) Release partition iterator. - Parameters iterator -- Iterator obtained using esp_partition_find. The iterator is allowed to be NULL, so it is not necessary to check its value before calling this function. - const esp_partition_t *esp_partition_verify(const esp_partition_t *partition) Verify partition data. Given a pointer to partition data, verify this partition exists in the partition table (all fields match.) This function is also useful to take partition data which may be in a RAM buffer and convert it to a pointer to the permanent partition data stored in flash. Pointers returned from this function can be compared directly to the address of any pointer returned from esp_partition_get(), as a test for equality. - Parameters partition -- Pointer to partition data to verify. Must be non-NULL. All fields of this structure must match the partition table entry in flash for this function to return a successful match. - Returns If partition not found, returns NULL. If found, returns a pointer to the esp_partition_t structure in flash. This pointer is always valid for the lifetime of the application. - - esp_err_t esp_partition_read(const esp_partition_t *partition, size_t src_offset, void *dst, size_t size) Read data from the partition. Partitions marked with an encryption flag will automatically be be read and decrypted via a cache mapping. - Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst -- Pointer to the buffer where data should be stored. Pointer must be non-NULL and buffer must be at least 'size' bytes long. src_offset -- Address of the data to be read, relative to the beginning of the partition. size -- Size of data to be read, in bytes. - - Returns ESP_OK, if data was read successfully; ESP_ERR_INVALID_ARG, if src_offset exceeds partition size; ESP_ERR_INVALID_SIZE, if read would go out of bounds of the partition; or one of error codes from lower-level flash driver. - esp_err_t esp_partition_write(const esp_partition_t *partition, size_t dst_offset, const void *src, size_t size) Write data to the partition. Before writing data to flash, corresponding region of flash needs to be erased. This can be done using esp_partition_erase_range function. Partitions marked with an encryption flag will automatically be written via the esp_flash_write_encrypted() function. If writing to an encrypted partition, all write offsets and lengths must be multiples of 16 bytes. See the esp_flash_write_encrypted() function for more details. Unencrypted partitions do not have this restriction. Note Prior to writing to flash memory, make sure it has been erased with esp_partition_erase_range call. - Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst_offset -- Address where the data should be written, relative to the beginning of the partition. src -- Pointer to the source buffer. Pointer must be non-NULL and buffer must be at least 'size' bytes long. size -- Size of data to be written, in bytes. - - Returns ESP_OK, if data was written successfully; ESP_ERR_INVALID_ARG, if dst_offset exceeds partition size; ESP_ERR_INVALID_SIZE, if write would go out of bounds of the partition; ESP_ERR_NOT_ALLOWED, if partition is read-only; or one of error codes from lower-level flash driver. - esp_err_t esp_partition_read_raw(const esp_partition_t *partition, size_t src_offset, void *dst, size_t size) Read data from the partition without any transformation/decryption. Note This function is essentially the same as esp_partition_read()above. It just never decrypts data but returns it as is. - Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst -- Pointer to the buffer where data should be stored. Pointer must be non-NULL and buffer must be at least 'size' bytes long. src_offset -- Address of the data to be read, relative to the beginning of the partition. size -- Size of data to be read, in bytes. - - Returns ESP_OK, if data was read successfully; ESP_ERR_INVALID_ARG, if src_offset exceeds partition size; ESP_ERR_INVALID_SIZE, if read would go out of bounds of the partition; or one of error codes from lower-level flash driver. - esp_err_t esp_partition_write_raw(const esp_partition_t *partition, size_t dst_offset, const void *src, size_t size) Write data to the partition without any transformation/encryption. Before writing data to flash, corresponding region of flash needs to be erased. This can be done using esp_partition_erase_range function. Note This function is essentially the same as esp_partition_write()above. It just never encrypts data but writes it as is. Note Prior to writing to flash memory, make sure it has been erased with esp_partition_erase_range call. - Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. dst_offset -- Address where the data should be written, relative to the beginning of the partition. src -- Pointer to the source buffer. Pointer must be non-NULL and buffer must be at least 'size' bytes long. size -- Size of data to be written, in bytes. - - Returns ESP_OK, if data was written successfully; ESP_ERR_INVALID_ARG, if dst_offset exceeds partition size; ESP_ERR_INVALID_SIZE, if write would go out of bounds of the partition; ESP_ERR_NOT_ALLOWED, if partition is read-only; or one of the error codes from lower-level flash driver. - esp_err_t esp_partition_erase_range(const esp_partition_t *partition, size_t offset, size_t size) Erase part of the partition. - Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. offset -- Offset from the beginning of partition where erase operation should start. Must be aligned to partition->erase_size. size -- Size of the range which should be erased, in bytes. Must be divisible by partition->erase_size. - - Returns ESP_OK, if the range was erased successfully; ESP_ERR_INVALID_ARG, if iterator or dst are NULL; ESP_ERR_INVALID_SIZE, if erase would go out of bounds of the partition; ESP_ERR_NOT_ALLOWED, if partition is read-only; or one of error codes from lower-level flash driver. - esp_err_t esp_partition_mmap(const esp_partition_t *partition, size_t offset, size_t size, esp_partition_mmap_memory_t memory, const void **out_ptr, esp_partition_mmap_handle_t *out_handle) Configure MMU to map partition into data memory. Unlike spi_flash_mmap function, which requires a 64kB aligned base address, this function doesn't impose such a requirement. If offset results in a flash address which is not aligned to 64kB boundary, address will be rounded to the lower 64kB boundary, so that mapped region includes requested range. Pointer returned via out_ptr argument will be adjusted to point to the requested offset (not necessarily to the beginning of mmap-ed region). To release mapped memory, pass handle returned via out_handle argument to esp_partition_munmap function. - Parameters partition -- Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. offset -- Offset from the beginning of partition where mapping should start. size -- Size of the area to be mapped. memory -- Memory space where the region should be mapped out_ptr -- Output, pointer to the mapped memory region out_handle -- Output, handle which should be used for esp_partition_munmap call - - Returns ESP_OK, if successful - void esp_partition_munmap(esp_partition_mmap_handle_t handle) Release region previously obtained using esp_partition_mmap. Note Calling this function will not necessarily unmap memory region. Region will only be unmapped when there are no other handles which reference this region. In case of partially overlapping regions it is possible that memory will be unmapped partially. - Parameters handle -- Handle obtained from spi_flash_mmap - esp_err_t esp_partition_get_sha256(const esp_partition_t *partition, uint8_t *sha_256) Get SHA-256 digest for required partition. For apps with SHA-256 appended to the app image, the result is the appended SHA-256 value for the app image content. The hash is verified before returning, if app content is invalid then the function returns ESP_ERR_IMAGE_INVALID. For apps without SHA-256 appended to the image, the result is the SHA-256 of all bytes in the app image. For other partition types, the result is the SHA-256 of the entire partition. - Parameters partition -- [in] Pointer to info for partition containing app or data. (fields: address, size and type, are required to be filled). sha_256 -- [out] Returned SHA-256 digest for a given partition. - - Returns ESP_OK: In case of successful operation. ESP_ERR_INVALID_ARG: The size was 0 or the sha_256 was NULL. ESP_ERR_NO_MEM: Cannot allocate memory for sha256 operation. ESP_ERR_IMAGE_INVALID: App partition doesn't contain a valid app image. ESP_FAIL: An allocation error occurred. - - bool esp_partition_check_identity(const esp_partition_t *partition_1, const esp_partition_t *partition_2) Check for the identity of two partitions by SHA-256 digest. - Parameters partition_1 -- [in] Pointer to info for partition 1 containing app or data. (fields: address, size and type, are required to be filled). partition_2 -- [in] Pointer to info for partition 2 containing app or data. (fields: address, size and type, are required to be filled). - - Returns True: In case of the two firmware is equal. False: Otherwise - - esp_err_t esp_partition_register_external(esp_flash_t *flash_chip, size_t offset, size_t size, const char *label, esp_partition_type_t type, esp_partition_subtype_t subtype, const esp_partition_t **out_partition) Register a partition on an external flash chip. This API allows designating certain areas of external flash chips (identified by the esp_flash_t structure) as partitions. This allows using them with components which access SPI flash through the esp_partition API. - Parameters flash_chip -- Pointer to the structure identifying the flash chip offset -- Address in bytes, where the partition starts size -- Size of the partition in bytes label -- Partition name type -- One of the partition types (ESP_PARTITION_TYPE_*), or an integer. Note that applications can not be booted from external flash chips, so using ESP_PARTITION_TYPE_APP is not supported. subtype -- One of the partition subtypes (ESP_PARTITION_SUBTYPE_*), or an integer. out_partition -- [out] Output, if non-NULL, receives the pointer to the resulting esp_partition_t structure - - Returns ESP_OK on success ESP_ERR_NO_MEM if memory allocation has failed ESP_ERR_INVALID_ARG if the new partition overlaps another partition on the same flash chip ESP_ERR_INVALID_SIZE if the partition doesn't fit into the flash chip size - - esp_err_t esp_partition_deregister_external(const esp_partition_t *partition) Deregister the partition previously registered using esp_partition_register_external. - Parameters partition -- pointer to the partition structure obtained from esp_partition_register_external, - Returns ESP_OK on success ESP_ERR_NOT_FOUND if the partition pointer is not found ESP_ERR_INVALID_ARG if the partition comes from the partition table ESP_ERR_INVALID_ARG if the partition was not registered using esp_partition_register_external function. - - void esp_partition_unload_all(void) Unload partitions and free space allocated by them. Structures - struct esp_partition_t partition information structure This is not the format in flash, that format is esp_partition_info_t. However, this is the format used by this API. Public Members - esp_flash_t *flash_chip SPI flash chip on which the partition resides - esp_partition_type_t type partition type (app/data) - esp_partition_subtype_t subtype partition subtype - uint32_t address starting address of the partition in flash - uint32_t size size of the partition, in bytes - uint32_t erase_size size the erase operation should be aligned to - char label[17] partition label, zero-terminated ASCII string - bool encrypted flag is set to true if partition is encrypted - bool readonly flag is set to true if partition is read-only - esp_flash_t *flash_chip Macros - ESP_PARTITION_SUBTYPE_OTA(i) Convenience macro to get esp_partition_subtype_t value for the i-th OTA partition. Type Definitions - typedef uint32_t esp_partition_mmap_handle_t Opaque handle for memory region obtained from esp_partition_mmap. - typedef struct esp_partition_iterator_opaque_ *esp_partition_iterator_t Opaque partition iterator type. Enumerations - enum esp_partition_mmap_memory_t Enumeration which specifies memory space requested in an mmap call. Values: - enumerator ESP_PARTITION_MMAP_DATA map to data memory (Vaddr0), allows byte-aligned access, 4 MB total - enumerator ESP_PARTITION_MMAP_INST map to instruction memory (Vaddr1-3), allows only 4-byte-aligned access, 11 MB total - enumerator ESP_PARTITION_MMAP_DATA - enum esp_partition_type_t Partition type. Note Partition types with integer value 0x00-0x3F are reserved for partition types defined by ESP-IDF. Any other integer value 0x40-0xFE can be used by individual applications, without restriction. Values: - enumerator ESP_PARTITION_TYPE_APP Application partition type. - enumerator ESP_PARTITION_TYPE_DATA Data partition type. - enumerator ESP_PARTITION_TYPE_ANY Used to search for partitions with any type. - enumerator ESP_PARTITION_TYPE_APP - enum esp_partition_subtype_t Partition subtype. Application-defined partition types (0x40-0xFE) can set any numeric subtype value. Note These ESP-IDF-defined partition subtypes apply to partitions of type ESP_PARTITION_TYPE_APP and ESP_PARTITION_TYPE_DATA. Values: - enumerator ESP_PARTITION_SUBTYPE_APP_FACTORY Factory application partition. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_MIN Base for OTA partition subtypes. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_0 OTA partition 0. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_1 OTA partition 1. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_2 OTA partition 2. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_3 OTA partition 3. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_4 OTA partition 4. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_5 OTA partition 5. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_6 OTA partition 6. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_7 OTA partition 7. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_8 OTA partition 8. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_9 OTA partition 9. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_10 OTA partition 10. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_11 OTA partition 11. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_12 OTA partition 12. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_13 OTA partition 13. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_14 OTA partition 14. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_15 OTA partition 15. - enumerator ESP_PARTITION_SUBTYPE_APP_OTA_MAX Max subtype of OTA partition. - enumerator ESP_PARTITION_SUBTYPE_APP_TEST Test application partition. - enumerator ESP_PARTITION_SUBTYPE_DATA_OTA OTA selection partition. - enumerator ESP_PARTITION_SUBTYPE_DATA_PHY PHY init data partition. - enumerator ESP_PARTITION_SUBTYPE_DATA_NVS NVS partition. - enumerator ESP_PARTITION_SUBTYPE_DATA_COREDUMP COREDUMP partition. - enumerator ESP_PARTITION_SUBTYPE_DATA_NVS_KEYS Partition for NVS keys. - enumerator ESP_PARTITION_SUBTYPE_DATA_EFUSE_EM Partition for emulate eFuse bits. - enumerator ESP_PARTITION_SUBTYPE_DATA_UNDEFINED Undefined (or unspecified) data partition. - enumerator ESP_PARTITION_SUBTYPE_DATA_ESPHTTPD ESPHTTPD partition. - enumerator ESP_PARTITION_SUBTYPE_DATA_FAT FAT partition. - enumerator ESP_PARTITION_SUBTYPE_DATA_SPIFFS SPIFFS partition. - enumerator ESP_PARTITION_SUBTYPE_DATA_LITTLEFS LITTLEFS partition. - enumerator ESP_PARTITION_SUBTYPE_ANY Used to search for partitions with any subtype. - enumerator ESP_PARTITION_SUBTYPE_APP_FACTORY
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/storage/partition.html
ESP-IDF Programming Guide v5.2.1 documentation
null
SPIFFS Filesystem
null
espressif.com
2016-01-01
9c05d21386f49cd3
null
null
SPIFFS Filesystem Overview SPIFFS is a file system intended for SPI NOR flash devices on embedded targets. It supports wear levelling, file system consistency checks, and more. Notes Currently, SPIFFS does not support directories, it produces a flat structure. If SPIFFS is mounted under /spiffs , then creating a file with the path /spiffs/tmp/myfile.txt will create a file called /tmp/myfile.txt in SPIFFS, instead of myfile.txt in the directory /spiffs/tmp . It is not a real-time stack. One write operation might take much longer than another. For now, it does not detect or handle bad blocks. SPIFFS is able to reliably utilize only around 75% of assigned partition space. When the filesystem is running out of space, the garbage collector is trying to find free space by scanning the filesystem multiple times, which can take up to several seconds per write function call, depending on required space. This is caused by the SPIFFS design and the issue has been reported multiple times (e.g., here) and in the official SPIFFS github repository. The issue can be partially mitigated by the SPIFFS configuration. Deleting a file does not always remove the whole file, which leaves unusable sections throughout the filesystem. When the chip experiences a power loss during a file system operation it could result in SPIFFS corruption. However the file system still might be recovered via esp_spiffs_check function. More details in the official SPIFFS FAQ. Tools spiffsgen.py  spiffsgen.py  spiffsgen.py is a write-only Python SPIFFS implementation used to create filesystem images from the contents of a host folder. To use spiffsgen.py , open Terminal and run: python spiffsgen.py <image_size> <base_dir> <output_file> The required arguments are as follows: image_size: size of the partition onto which the created SPIFFS image will be flashed. base_dir: directory for which the SPIFFS image needs to be created. output_file: SPIFFS image output file. There are also other arguments that control image generation. Documentation on these arguments can be found in the tool's help: python spiffsgen.py --help These optional arguments correspond to a possible SPIFFS build configuration. To generate the right image, please make sure that you use the same arguments/configuration as were used to build SPIFFS. As a guide, the help output indicates the SPIFFS build configuration to which the argument corresponds. In cases when these arguments are not specified, the default values shown in the help output will be used. When the image is created, it can be flashed using esptool.py or parttool.py . Aside from invoking the spiffsgen.py standalone by manually running it from the command line or a script, it is also possible to invoke spiffsgen.py directly from the build system by calling spiffs_create_partition_image : spiffs_create_partition_image(<partition> <base_dir> [FLASH_IN_PROJECT] [DEPENDS dep dep dep...]) This is more convenient as the build configuration is automatically passed to the tool, ensuring that the generated image is valid for that build. An example of this is while the image_size is required for the standalone invocation, only the partition name is required when using spiffs_create_partition_image -- the image size is automatically obtained from the project's partition table. spiffs_create_partition_image must be called from one of the component CMakeLists.txt files. Optionally, users can opt to have the image automatically flashed together with the app binaries, partition tables, etc. on idf.py flash by specifying FLASH_IN_PROJECT . For example: spiffs_create_partition_image(my_spiffs_partition my_folder FLASH_IN_PROJECT) If FLASH_IN_PROJECT/SPIFFS_IMAGE_FLASH_IN_PROJECT is not specified, the image will still be generated, but you will have to flash it manually using esptool.py , parttool.py , or a custom build system target. There are cases where the contents of the base directory itself is generated at build time. Users can use DEPENDS/SPIFFS_IMAGE_DEPENDS to specify targets that should be executed before generating the image: add_custom_target(dep COMMAND ...) spiffs_create_partition_image(my_spiffs_partition my_folder DEPENDS dep) For an example, see storage/spiffsgen. mkspiffs  mkspiffs  Another tool for creating SPIFFS partition images is mkspiffs. Similar to spiffsgen.py , it can be used to create an image from a given folder and then flash that image using esptool.py For that, you need to obtain the following parameters: Block Size: 4096 (standard for SPI Flash) Page Size: 256 (standard for SPI Flash) Image Size: Size of the partition in bytes (can be obtained from a partition table) Partition Offset: Starting address of the partition (can be obtained from a partition table) To pack a folder into a 1-Megabyte image, run: mkspiffs -c [src_folder] -b 4096 -p 256 -s 0x100000 spiffs.bin To flash the image onto ESP32 at offset 0x110000, run: python esptool.py --chip esp32 --port [port] --baud [baud] write_flash -z 0x110000 spiffs.bin Notes on Which SPIFFS Tool to Use The two tools presented above offer very similar functionality. However, there are reasons to prefer one over the other, depending on the use case. Use spiffsgen.py in the following cases: If you want to simply generate a SPIFFS image during the build. spiffsgen.py makes it very convenient by providing functions/commands from the build system itself. If the host has no C/C++ compiler available, because spiffsgen.py does not require compilation. Use mkspiffs in the following cases: If you need to unpack SPIFFS images in addition to image generation. For now, it is not possible with spiffsgen.py . If you have an environment where a Python interpreter is not available, but a host compiler is available. Otherwise, a pre-compiled mkspiffs binary can do the job. However, there is no build system integration for mkspiffs and the user has to do the corresponding work: compiling mkspiffs during build (if a pre-compiled binary is not used), creating build rules/targets for the output files, passing proper parameters to the tool, etc. See Also Application Example An example of using SPIFFS is provided in the storage/spiffs directory. This example initializes and mounts a SPIFFS partition, then writes and reads data from it using POSIX and C library APIs. See the README.md file in the example directory for more information. High-level API Reference Header File This header file can be included with: #include "esp_spiffs.h" This header file is a part of the API provided by the spiffs component. To declare that your component depends on spiffs , add the following to your CMakeLists.txt: REQUIRES spiffs or PRIV_REQUIRES spiffs Functions esp_err_t esp_vfs_spiffs_register(const esp_vfs_spiffs_conf_t *conf) Register and mount SPIFFS to VFS with given path prefix. Parameters conf -- Pointer to esp_vfs_spiffs_conf_t configuration structure Returns ESP_OK if success ESP_ERR_NO_MEM if objects could not be allocated ESP_ERR_INVALID_STATE if already mounted or partition is encrypted ESP_ERR_NOT_FOUND if partition for SPIFFS was not found ESP_FAIL if mount or format fails ESP_OK if success ESP_ERR_NO_MEM if objects could not be allocated ESP_ERR_INVALID_STATE if already mounted or partition is encrypted ESP_ERR_NOT_FOUND if partition for SPIFFS was not found ESP_FAIL if mount or format fails ESP_OK if success Parameters conf -- Pointer to esp_vfs_spiffs_conf_t configuration structure Returns ESP_OK if success ESP_ERR_NO_MEM if objects could not be allocated ESP_ERR_INVALID_STATE if already mounted or partition is encrypted ESP_ERR_NOT_FOUND if partition for SPIFFS was not found ESP_FAIL if mount or format fails esp_err_t esp_vfs_spiffs_unregister(const char *partition_label) Unregister and unmount SPIFFS from VFS Parameters partition_label -- Same label as passed to esp_vfs_spiffs_register. Returns ESP_OK if successful ESP_ERR_INVALID_STATE already unregistered ESP_OK if successful ESP_ERR_INVALID_STATE already unregistered ESP_OK if successful Parameters partition_label -- Same label as passed to esp_vfs_spiffs_register. Returns ESP_OK if successful ESP_ERR_INVALID_STATE already unregistered bool esp_spiffs_mounted(const char *partition_label) Check if SPIFFS is mounted Parameters partition_label -- Optional, label of the partition to check. If not specified, first partition with subtype=spiffs is used. Returns true if mounted false if not mounted true if mounted false if not mounted true if mounted Parameters partition_label -- Optional, label of the partition to check. If not specified, first partition with subtype=spiffs is used. Returns true if mounted false if not mounted esp_err_t esp_spiffs_format(const char *partition_label) Format the SPIFFS partition Parameters partition_label -- Same label as passed to esp_vfs_spiffs_register. Returns ESP_OK if successful ESP_FAIL on error ESP_OK if successful ESP_FAIL on error ESP_OK if successful Parameters partition_label -- Same label as passed to esp_vfs_spiffs_register. Returns ESP_OK if successful ESP_FAIL on error esp_err_t esp_spiffs_info(const char *partition_label, size_t *total_bytes, size_t *used_bytes) Get information for SPIFFS Parameters partition_label -- Same label as passed to esp_vfs_spiffs_register total_bytes -- [out] Size of the file system used_bytes -- [out] Current used bytes in the file system partition_label -- Same label as passed to esp_vfs_spiffs_register total_bytes -- [out] Size of the file system used_bytes -- [out] Current used bytes in the file system partition_label -- Same label as passed to esp_vfs_spiffs_register Returns ESP_OK if success ESP_ERR_INVALID_STATE if not mounted ESP_OK if success ESP_ERR_INVALID_STATE if not mounted ESP_OK if success Parameters partition_label -- Same label as passed to esp_vfs_spiffs_register total_bytes -- [out] Size of the file system used_bytes -- [out] Current used bytes in the file system Returns ESP_OK if success ESP_ERR_INVALID_STATE if not mounted esp_err_t esp_spiffs_check(const char *partition_label) Check integrity of SPIFFS Parameters partition_label -- Same label as passed to esp_vfs_spiffs_register Returns ESP_OK if successful ESP_ERR_INVALID_STATE if not mounted ESP_FAIL on error ESP_OK if successful ESP_ERR_INVALID_STATE if not mounted ESP_FAIL on error ESP_OK if successful Parameters partition_label -- Same label as passed to esp_vfs_spiffs_register Returns ESP_OK if successful ESP_ERR_INVALID_STATE if not mounted ESP_FAIL on error esp_err_t esp_spiffs_gc(const char *partition_label, size_t size_to_gc) Perform garbage collection in SPIFFS partition. Call this function to run GC and ensure that at least the given amount of space is available in the partition. This function will fail with ESP_ERR_NOT_FINISHED if it is not possible to reclaim the requested space (that is, not enough free or deleted pages in the filesystem). This function will also fail if it fails to reclaim the requested space after CONFIG_SPIFFS_GC_MAX_RUNS number of GC iterations. On one GC iteration, SPIFFS will erase one logical block (4kB). Therefore the value of CONFIG_SPIFFS_GC_MAX_RUNS should be set at least to the maximum expected size_to_gc, divided by 4096. For example, if the application expects to make room for a 1MB file and calls esp_spiffs_gc(label, 1024 * 1024), CONFIG_SPIFFS_GC_MAX_RUNS should be set to at least 256. On the other hand, increasing CONFIG_SPIFFS_GC_MAX_RUNS value increases the maximum amount of time for which any SPIFFS GC or write operation may potentially block. Parameters partition_label -- Label of the partition to be garbage-collected. The partition must be already mounted. size_to_gc -- The number of bytes that the GC process should attempt to make available. partition_label -- Label of the partition to be garbage-collected. The partition must be already mounted. size_to_gc -- The number of bytes that the GC process should attempt to make available. partition_label -- Label of the partition to be garbage-collected. The partition must be already mounted. Returns ESP_OK on success ESP_ERR_NOT_FINISHED if GC fails to reclaim the size given by size_to_gc ESP_ERR_INVALID_STATE if the partition is not mounted ESP_FAIL on all other errors ESP_OK on success ESP_ERR_NOT_FINISHED if GC fails to reclaim the size given by size_to_gc ESP_ERR_INVALID_STATE if the partition is not mounted ESP_FAIL on all other errors ESP_OK on success Parameters partition_label -- Label of the partition to be garbage-collected. The partition must be already mounted. size_to_gc -- The number of bytes that the GC process should attempt to make available. Returns ESP_OK on success ESP_ERR_NOT_FINISHED if GC fails to reclaim the size given by size_to_gc ESP_ERR_INVALID_STATE if the partition is not mounted ESP_FAIL on all other errors Structures struct esp_vfs_spiffs_conf_t Configuration structure for esp_vfs_spiffs_register. Public Members const char *base_path File path prefix associated with the filesystem. const char *base_path File path prefix associated with the filesystem. const char *partition_label Optional, label of SPIFFS partition to use. If set to NULL, first partition with subtype=spiffs will be used. const char *partition_label Optional, label of SPIFFS partition to use. If set to NULL, first partition with subtype=spiffs will be used. size_t max_files Maximum files that could be open at the same time. size_t max_files Maximum files that could be open at the same time. bool format_if_mount_failed If true, it will format the file system if it fails to mount. bool format_if_mount_failed If true, it will format the file system if it fails to mount. const char *base_path
SPIFFS Filesystem Overview SPIFFS is a file system intended for SPI NOR flash devices on embedded targets. It supports wear levelling, file system consistency checks, and more. Notes - Currently, SPIFFS does not support directories, it produces a flat structure. If SPIFFS is mounted under /spiffs, then creating a file with the path /spiffs/tmp/myfile.txtwill create a file called /tmp/myfile.txtin SPIFFS, instead of myfile.txtin the directory /spiffs/tmp. - It is not a real-time stack. One write operation might take much longer than another. - For now, it does not detect or handle bad blocks. - SPIFFS is able to reliably utilize only around 75% of assigned partition space. - When the filesystem is running out of space, the garbage collector is trying to find free space by scanning the filesystem multiple times, which can take up to several seconds per write function call, depending on required space. This is caused by the SPIFFS design and the issue has been reported multiple times (e.g., here) and in the official SPIFFS github repository. The issue can be partially mitigated by the SPIFFS configuration. - Deleting a file does not always remove the whole file, which leaves unusable sections throughout the filesystem. - When the chip experiences a power loss during a file system operation it could result in SPIFFS corruption. However the file system still might be recovered via esp_spiffs_checkfunction. More details in the official SPIFFS FAQ. Tools spiffsgen.py spiffsgen.py is a write-only Python SPIFFS implementation used to create filesystem images from the contents of a host folder. To use spiffsgen.py, open Terminal and run: python spiffsgen.py <image_size> <base_dir> <output_file> The required arguments are as follows: image_size: size of the partition onto which the created SPIFFS image will be flashed. base_dir: directory for which the SPIFFS image needs to be created. output_file: SPIFFS image output file. There are also other arguments that control image generation. Documentation on these arguments can be found in the tool's help: python spiffsgen.py --help These optional arguments correspond to a possible SPIFFS build configuration. To generate the right image, please make sure that you use the same arguments/configuration as were used to build SPIFFS. As a guide, the help output indicates the SPIFFS build configuration to which the argument corresponds. In cases when these arguments are not specified, the default values shown in the help output will be used. When the image is created, it can be flashed using esptool.py or parttool.py. Aside from invoking the spiffsgen.py standalone by manually running it from the command line or a script, it is also possible to invoke spiffsgen.py directly from the build system by calling spiffs_create_partition_image: spiffs_create_partition_image(<partition> <base_dir> [FLASH_IN_PROJECT] [DEPENDS dep dep dep...]) This is more convenient as the build configuration is automatically passed to the tool, ensuring that the generated image is valid for that build. An example of this is while the image_size is required for the standalone invocation, only the partition name is required when using spiffs_create_partition_image -- the image size is automatically obtained from the project's partition table. spiffs_create_partition_image must be called from one of the component CMakeLists.txt files. Optionally, users can opt to have the image automatically flashed together with the app binaries, partition tables, etc. on idf.py flash by specifying FLASH_IN_PROJECT. For example: spiffs_create_partition_image(my_spiffs_partition my_folder FLASH_IN_PROJECT) If FLASH_IN_PROJECT/SPIFFS_IMAGE_FLASH_IN_PROJECT is not specified, the image will still be generated, but you will have to flash it manually using esptool.py, parttool.py, or a custom build system target. There are cases where the contents of the base directory itself is generated at build time. Users can use DEPENDS/SPIFFS_IMAGE_DEPENDS to specify targets that should be executed before generating the image: add_custom_target(dep COMMAND ...) spiffs_create_partition_image(my_spiffs_partition my_folder DEPENDS dep) For an example, see storage/spiffsgen. mkspiffs Another tool for creating SPIFFS partition images is mkspiffs. Similar to spiffsgen.py, it can be used to create an image from a given folder and then flash that image using esptool.py For that, you need to obtain the following parameters: Block Size: 4096 (standard for SPI Flash) Page Size: 256 (standard for SPI Flash) Image Size: Size of the partition in bytes (can be obtained from a partition table) Partition Offset: Starting address of the partition (can be obtained from a partition table) To pack a folder into a 1-Megabyte image, run: mkspiffs -c [src_folder] -b 4096 -p 256 -s 0x100000 spiffs.bin To flash the image onto ESP32 at offset 0x110000, run: python esptool.py --chip esp32 --port [port] --baud [baud] write_flash -z 0x110000 spiffs.bin Notes on Which SPIFFS Tool to Use The two tools presented above offer very similar functionality. However, there are reasons to prefer one over the other, depending on the use case. Use spiffsgen.py in the following cases: If you want to simply generate a SPIFFS image during the build. spiffsgen.pymakes it very convenient by providing functions/commands from the build system itself. If the host has no C/C++ compiler available, because spiffsgen.pydoes not require compilation. Use mkspiffs in the following cases: If you need to unpack SPIFFS images in addition to image generation. For now, it is not possible with spiffsgen.py. If you have an environment where a Python interpreter is not available, but a host compiler is available. Otherwise, a pre-compiled mkspiffsbinary can do the job. However, there is no build system integration for mkspiffsand the user has to do the corresponding work: compiling mkspiffsduring build (if a pre-compiled binary is not used), creating build rules/targets for the output files, passing proper parameters to the tool, etc. See Also Application Example An example of using SPIFFS is provided in the storage/spiffs directory. This example initializes and mounts a SPIFFS partition, then writes and reads data from it using POSIX and C library APIs. See the README.md file in the example directory for more information. High-level API Reference Header File This header file can be included with: #include "esp_spiffs.h" This header file is a part of the API provided by the spiffscomponent. To declare that your component depends on spiffs, add the following to your CMakeLists.txt: REQUIRES spiffs or PRIV_REQUIRES spiffs Functions - esp_err_t esp_vfs_spiffs_register(const esp_vfs_spiffs_conf_t *conf) Register and mount SPIFFS to VFS with given path prefix. - Parameters conf -- Pointer to esp_vfs_spiffs_conf_t configuration structure - Returns ESP_OK if success ESP_ERR_NO_MEM if objects could not be allocated ESP_ERR_INVALID_STATE if already mounted or partition is encrypted ESP_ERR_NOT_FOUND if partition for SPIFFS was not found ESP_FAIL if mount or format fails - - esp_err_t esp_vfs_spiffs_unregister(const char *partition_label) Unregister and unmount SPIFFS from VFS - Parameters partition_label -- Same label as passed to esp_vfs_spiffs_register. - Returns ESP_OK if successful ESP_ERR_INVALID_STATE already unregistered - - bool esp_spiffs_mounted(const char *partition_label) Check if SPIFFS is mounted - Parameters partition_label -- Optional, label of the partition to check. If not specified, first partition with subtype=spiffs is used. - Returns true if mounted false if not mounted - - esp_err_t esp_spiffs_format(const char *partition_label) Format the SPIFFS partition - Parameters partition_label -- Same label as passed to esp_vfs_spiffs_register. - Returns ESP_OK if successful ESP_FAIL on error - - esp_err_t esp_spiffs_info(const char *partition_label, size_t *total_bytes, size_t *used_bytes) Get information for SPIFFS - Parameters partition_label -- Same label as passed to esp_vfs_spiffs_register total_bytes -- [out] Size of the file system used_bytes -- [out] Current used bytes in the file system - - Returns ESP_OK if success ESP_ERR_INVALID_STATE if not mounted - - esp_err_t esp_spiffs_check(const char *partition_label) Check integrity of SPIFFS - Parameters partition_label -- Same label as passed to esp_vfs_spiffs_register - Returns ESP_OK if successful ESP_ERR_INVALID_STATE if not mounted ESP_FAIL on error - - esp_err_t esp_spiffs_gc(const char *partition_label, size_t size_to_gc) Perform garbage collection in SPIFFS partition. Call this function to run GC and ensure that at least the given amount of space is available in the partition. This function will fail with ESP_ERR_NOT_FINISHED if it is not possible to reclaim the requested space (that is, not enough free or deleted pages in the filesystem). This function will also fail if it fails to reclaim the requested space after CONFIG_SPIFFS_GC_MAX_RUNS number of GC iterations. On one GC iteration, SPIFFS will erase one logical block (4kB). Therefore the value of CONFIG_SPIFFS_GC_MAX_RUNS should be set at least to the maximum expected size_to_gc, divided by 4096. For example, if the application expects to make room for a 1MB file and calls esp_spiffs_gc(label, 1024 * 1024), CONFIG_SPIFFS_GC_MAX_RUNS should be set to at least 256. On the other hand, increasing CONFIG_SPIFFS_GC_MAX_RUNS value increases the maximum amount of time for which any SPIFFS GC or write operation may potentially block. - Parameters partition_label -- Label of the partition to be garbage-collected. The partition must be already mounted. size_to_gc -- The number of bytes that the GC process should attempt to make available. - - Returns ESP_OK on success ESP_ERR_NOT_FINISHED if GC fails to reclaim the size given by size_to_gc ESP_ERR_INVALID_STATE if the partition is not mounted ESP_FAIL on all other errors - Structures - struct esp_vfs_spiffs_conf_t Configuration structure for esp_vfs_spiffs_register. Public Members - const char *base_path File path prefix associated with the filesystem. - const char *partition_label Optional, label of SPIFFS partition to use. If set to NULL, first partition with subtype=spiffs will be used. - size_t max_files Maximum files that could be open at the same time. - bool format_if_mount_failed If true, it will format the file system if it fails to mount. - const char *base_path
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/storage/spiffs.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Virtual Filesystem Component
null
espressif.com
2016-01-01
a6479e1770ab9242
null
null
Virtual Filesystem Component Overview Virtual filesystem (VFS) component provides a unified interface for drivers which can perform operations on file-like objects. These can be real filesystems (FAT, SPIFFS, etc.) or device drivers which provide a file-like interface. This component allows C library functions, such as fopen and fprintf, to work with FS drivers. At a high level, each FS driver is associated with some path prefix. When one of C library functions needs to open a file, the VFS component searches for the FS driver associated with the file path and forwards the call to that driver. VFS also forwards read, write, and other calls for the given file to the same FS driver. For example, one can register a FAT filesystem driver with the /fat prefix and call fopen("/fat/file.txt", "w") . Then the VFS component calls the function open of the FAT driver and pass the argument /file.txt to it together with appropriate mode flags. All subsequent calls to C library functions for the returned FILE* stream will also be forwarded to the FAT driver. FS Registration To register an FS driver, an application needs to define an instance of the esp_vfs_t structure and populate it with function pointers to FS APIs: esp_vfs_t myfs = { .flags = ESP_VFS_FLAG_DEFAULT, .write = &myfs_write, .open = &myfs_open, .fstat = &myfs_fstat, .close = &myfs_close, .read = &myfs_read, }; ESP_ERROR_CHECK(esp_vfs_register("/data", &myfs, NULL)); Depending on the way how the FS driver declares its API functions, either read , write , etc., or read_p , write_p , etc., should be used. Case 1: API functions are declared without an extra context pointer (the FS driver is a singleton): ssize_t myfs_write(int fd, const void * data, size_t size); // In definition of esp_vfs_t: .flags = ESP_VFS_FLAG_DEFAULT, .write = &myfs_write, // ... other members initialized // When registering FS, context pointer (third argument) is NULL: ESP_ERROR_CHECK(esp_vfs_register("/data", &myfs, NULL)); Case 2: API functions are declared with an extra context pointer (the FS driver supports multiple instances): ssize_t myfs_write(myfs_t* fs, int fd, const void * data, size_t size); // In definition of esp_vfs_t: .flags = ESP_VFS_FLAG_CONTEXT_PTR, .write_p = &myfs_write, // ... other members initialized // When registering FS, pass the FS context pointer into the third argument // (hypothetical myfs_mount function is used for illustrative purposes) myfs_t* myfs_inst1 = myfs_mount(partition1->offset, partition1->size); ESP_ERROR_CHECK(esp_vfs_register("/data1", &myfs, myfs_inst1)); // Can register another instance: myfs_t* myfs_inst2 = myfs_mount(partition2->offset, partition2->size); ESP_ERROR_CHECK(esp_vfs_register("/data2", &myfs, myfs_inst2)); Synchronous Input/Output Multiplexing Synchronous input/output multiplexing by select() is supported in the VFS component. The implementation works in the following way. select() is called with file descriptors which could belong to various VFS drivers. The file descriptors are divided into groups each belonging to one VFS driver. The file descriptors belonging to non-socket VFS drivers are handed over to the given VFS drivers by start_select() , described later on this page. This function represents the driver-specific implementation of select() for the given driver. This should be a non-blocking call which means the function should immediately return after setting up the environment for checking events related to the given file descriptors. The file descriptors belonging to the socket VFS driver are handed over to the socket driver by socket_select() described later on this page. This is a blocking call which means that it will return only if there is an event related to socket file descriptors or a non-socket driver signals socket_select() to exit. Results are collected from each VFS driver and all drivers are stopped by de-initialization of the environment for checking events. The select() call ends and returns the appropriate results. Non-Socket VFS Drivers If you want to use select() with a file descriptor belonging to a non-socket VFS driver, then you need to register the driver with functions start_select() and end_select() similarly to the following example: // In definition of esp_vfs_t: .start_select = &uart_start_select, .end_select = &uart_end_select, // ... other members initialized start_select() is called for setting up the environment for detection of read/write/error conditions on file descriptors belonging to the given VFS driver. end_select() is called to stop/deinitialize/free the environment which was setup by start_select() . Note end_select() might be called without a previous start_select() call in some rare circumstances. end_select() should fail gracefully if this is the case (i.e., should not crash but return an error instead). Please refer to the reference implementation for the UART peripheral in vfs/vfs_uart.c and most particularly to the functions esp_vfs_dev_uart_register() , uart_start_select() , and uart_end_select() for more information. Please check the following examples that demonstrate the use of select() with VFS file descriptors: Socket VFS Drivers A socket VFS driver is using its own internal implementation of select() and non-socket VFS drivers notify it upon read/write/error conditions. A socket VFS driver needs to be registered with the following functions defined: // In definition of esp_vfs_t: .socket_select = &lwip_select, .get_socket_select_semaphore = &lwip_get_socket_select_semaphore, .stop_socket_select = &lwip_stop_socket_select, .stop_socket_select_isr = &lwip_stop_socket_select_isr, // ... other members initialized socket_select() is the internal implementation of select() for the socket driver. It works only with file descriptors belonging to the socket VFS. get_socket_select_semaphore() returns the signalization object (semaphore) which is used in non-socket drivers to stop the waiting in socket_select() . stop_socket_select() call is used to stop the waiting in socket_select() by passing the object returned by get_socket_select_semaphore() . stop_socket_select_isr() has the same functionality as stop_socket_select() but it can be used from ISR. Please see lwip/port/esp32xx/vfs_lwip.c for a reference socket driver implementation using LWIP. Note If you use select() for socket file descriptors only then you can disable the CONFIG_VFS_SUPPORT_SELECT option to reduce the code size and improve performance. You should not change the socket driver during an active select() call or you might experience some undefined behavior. Paths Each registered FS has a path prefix associated with it. This prefix can be considered as a "mount point" of this partition. In case when mount points are nested, the mount point with the longest matching path prefix is used when opening the file. For instance, suppose that the following filesystems are registered in VFS: FS 1 on /data FS 2 on /data/static Then: FS 1 will be used when opening a file called /data/log.txt FS 2 will be used when opening a file called /data/static/index.html Even if /index.html" does not exist in FS 2, FS 1 will not be searched for /static/index.html . As a general rule, mount point names must start with the path separator ( / ) and must contain at least one character after path separator. However, an empty mount point name is also supported and might be used in cases when an application needs to provide a "fallback" filesystem or to override VFS functionality altogether. Such filesystem will be used if no prefix matches the path given. VFS does not handle dots ( . ) in path names in any special way. VFS does not treat .. as a reference to the parent directory. In the above example, using a path /data/static/../log.txt will not result in a call to FS 1 to open /log.txt . Specific FS drivers (such as FATFS) might handle dots in file names differently. When opening files, the FS driver receives only relative paths to files. For example: The myfs driver is registered with /data as a path prefix. The application calls fopen("/data/config.json", ...) . The VFS component calls myfs_open("/config.json", ...) . The myfs driver opens the /config.json file. VFS does not impose any limit on total file path length, but it does limit the FS path prefix to ESP_VFS_PATH_MAX characters. Individual FS drivers may have their own filename length limitations. File Descriptors File descriptors are small positive integers from 0 to FD_SETSIZE - 1 , where FD_SETSIZE is defined in sys/select.h . The largest file descriptors (configured by CONFIG_LWIP_MAX_SOCKETS ) are reserved for sockets. The VFS component contains a lookup-table called s_fd_table for mapping global file descriptors to VFS driver indexes registered in the s_vfs array. Standard IO Streams ( stdin , stdout , stderr ) stdin , stdout , stderr ) If the menuconfig option UART for console output is not set to None , then stdin , stdout , and stderr are configured to read from, and write to, a UART. It is possible to use UART0 or UART1 for standard IO. By default, UART0 is used with 115200 baud rate; TX pin is GPIO1; RX pin is GPIO3. These parameters can be changed in menuconfig. Writing to stdout or stderr sends characters to the UART transmit FIFO. Reading from stdin retrieves characters from the UART receive FIFO. By default, VFS uses simple functions for reading from and writing to UART. Writes busy-wait until all data is put into UART FIFO, and reads are non-blocking, returning only the data present in the FIFO. Due to this non-blocking read behavior, higher level C library calls, such as fscanf("%d\n", &var); , might not have desired results. Applications which use the UART driver can instruct VFS to use the driver's interrupt driven, blocking read and write functions instead. This can be done using a call to the esp_vfs_dev_uart_use_driver function. It is also possible to revert to the basic non-blocking functions using a call to esp_vfs_dev_uart_use_nonblocking . VFS also provides an optional newline conversion feature for input and output. Internally, most applications send and receive lines terminated by the LF (''n'') character. Different terminal programs may require different line termination, such as CR or CRLF. Applications can configure this separately for input and output either via menuconfig, or by calls to the functions esp_vfs_dev_uart_port_set_rx_line_endings and esp_vfs_dev_uart_port_set_tx_line_endings . Standard Streams and FreeRTOS Tasks FILE objects for stdin , stdout , and stderr are shared between all FreeRTOS tasks, but the pointers to these objects are stored in per-task struct _reent . The following code is transferred to fprintf(__getreent()->_stderr, "42\n"); by the preprocessor: fprintf(stderr, "42\n"); The __getreent() function returns a per-task pointer to struct _reent in newlib libc. This structure is allocated on the TCB of each task. When a task is initialized, _stdin , _stdout , and _stderr members of struct _reent are set to the values of _stdin , _stdout , and _stderr of _GLOBAL_REENT (i.e., the structure which is used before FreeRTOS is started). Such a design has the following consequences: It is possible to set stdin , stdout , and stderr for any given task without affecting other tasks, e.g., by doing stdin = fopen("/dev/uart/1", "r") . Closing default stdin , stdout , or stderr using fclose closes the FILE stream object, which will affect all other tasks. To change the default stdin , stdout , stderr streams for new tasks, modify _GLOBAL_REENT->_stdin ( _stdout , _stderr ) before creating the task. eventfd()  eventfd()  eventfd() call is a powerful tool to notify a select() based loop of custom events. The eventfd() implementation in ESP-IDF is generally the same as described in man(2) eventfd except for: esp_vfs_eventfd_register() has to be called before calling eventfd() Options EFD_CLOEXEC , EFD_NONBLOCK and EFD_SEMAPHORE are not supported in flags. Option EFD_SUPPORT_ISR has been added in flags. This flag is required to read and write the eventfd in an interrupt handler. Note that creating an eventfd with EFD_SUPPORT_ISR will cause interrupts to be temporarily disabled when reading, writing the file and during the beginning and the ending of the select() when this file is set. API Reference Header File This header file can be included with: #include "esp_vfs.h" This header file is a part of the API provided by the vfs component. To declare that your component depends on vfs , add the following to your CMakeLists.txt: REQUIRES vfs or PRIV_REQUIRES vfs Functions ssize_t esp_vfs_write(struct _reent *r, int fd, const void *data, size_t size) These functions are to be used in newlib syscall table. They will be called by newlib when it needs to use any of the syscalls. off_t esp_vfs_lseek(struct _reent *r, int fd, off_t size, int mode) ssize_t esp_vfs_read(struct _reent *r, int fd, void *dst, size_t size) int esp_vfs_open(struct _reent *r, const char *path, int flags, int mode) int esp_vfs_close(struct _reent *r, int fd) int esp_vfs_fstat(struct _reent *r, int fd, struct stat *st) int esp_vfs_stat(struct _reent *r, const char *path, struct stat *st) int esp_vfs_link(struct _reent *r, const char *n1, const char *n2) int esp_vfs_unlink(struct _reent *r, const char *path) int esp_vfs_rename(struct _reent *r, const char *src, const char *dst) int esp_vfs_utime(const char *path, const struct utimbuf *times) esp_err_t esp_vfs_register(const char *base_path, const esp_vfs_t *vfs, void *ctx) Register a virtual filesystem for given path prefix. Parameters base_path -- file path prefix associated with the filesystem. Must be a zero-terminated C string, may be empty. If not empty, must be up to ESP_VFS_PATH_MAX characters long, and at least 2 characters long. Name must start with a "/" and must not end with "/". For example, "/data" or "/dev/spi" are valid. These VFSes would then be called to handle file paths such as "/data/myfile.txt" or "/dev/spi/0". In the special case of an empty base_path, a "fallback" VFS is registered. Such VFS will handle paths which are not matched by any other registered VFS. vfs -- Pointer to esp_vfs_t, a structure which maps syscalls to the filesystem driver functions. VFS component doesn't assume ownership of this pointer. ctx -- If vfs->flags has ESP_VFS_FLAG_CONTEXT_PTR set, a pointer which should be passed to VFS functions. Otherwise, NULL. base_path -- file path prefix associated with the filesystem. Must be a zero-terminated C string, may be empty. If not empty, must be up to ESP_VFS_PATH_MAX characters long, and at least 2 characters long. Name must start with a "/" and must not end with "/". For example, "/data" or "/dev/spi" are valid. These VFSes would then be called to handle file paths such as "/data/myfile.txt" or "/dev/spi/0". In the special case of an empty base_path, a "fallback" VFS is registered. Such VFS will handle paths which are not matched by any other registered VFS. vfs -- Pointer to esp_vfs_t, a structure which maps syscalls to the filesystem driver functions. VFS component doesn't assume ownership of this pointer. ctx -- If vfs->flags has ESP_VFS_FLAG_CONTEXT_PTR set, a pointer which should be passed to VFS functions. Otherwise, NULL. base_path -- file path prefix associated with the filesystem. Must be a zero-terminated C string, may be empty. If not empty, must be up to ESP_VFS_PATH_MAX characters long, and at least 2 characters long. Name must start with a "/" and must not end with "/". For example, "/data" or "/dev/spi" are valid. These VFSes would then be called to handle file paths such as "/data/myfile.txt" or "/dev/spi/0". In the special case of an empty base_path, a "fallback" VFS is registered. Such VFS will handle paths which are not matched by any other registered VFS. Returns ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are registered. Parameters base_path -- file path prefix associated with the filesystem. Must be a zero-terminated C string, may be empty. If not empty, must be up to ESP_VFS_PATH_MAX characters long, and at least 2 characters long. Name must start with a "/" and must not end with "/". For example, "/data" or "/dev/spi" are valid. These VFSes would then be called to handle file paths such as "/data/myfile.txt" or "/dev/spi/0". In the special case of an empty base_path, a "fallback" VFS is registered. Such VFS will handle paths which are not matched by any other registered VFS. vfs -- Pointer to esp_vfs_t, a structure which maps syscalls to the filesystem driver functions. VFS component doesn't assume ownership of this pointer. ctx -- If vfs->flags has ESP_VFS_FLAG_CONTEXT_PTR set, a pointer which should be passed to VFS functions. Otherwise, NULL. Returns ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are registered. esp_err_t esp_vfs_register_fd_range(const esp_vfs_t *vfs, void *ctx, int min_fd, int max_fd) Special case function for registering a VFS that uses a method other than open() to open new file descriptors from the interval <min_fd; max_fd). This is a special-purpose function intended for registering LWIP sockets to VFS. Parameters vfs -- Pointer to esp_vfs_t. Meaning is the same as for esp_vfs_register(). ctx -- Pointer to context structure. Meaning is the same as for esp_vfs_register(). min_fd -- The smallest file descriptor this VFS will use. max_fd -- Upper boundary for file descriptors this VFS will use (the biggest file descriptor plus one). vfs -- Pointer to esp_vfs_t. Meaning is the same as for esp_vfs_register(). ctx -- Pointer to context structure. Meaning is the same as for esp_vfs_register(). min_fd -- The smallest file descriptor this VFS will use. max_fd -- Upper boundary for file descriptors this VFS will use (the biggest file descriptor plus one). vfs -- Pointer to esp_vfs_t. Meaning is the same as for esp_vfs_register(). Returns ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are registered, ESP_ERR_INVALID_ARG if the file descriptor boundaries are incorrect. Parameters vfs -- Pointer to esp_vfs_t. Meaning is the same as for esp_vfs_register(). ctx -- Pointer to context structure. Meaning is the same as for esp_vfs_register(). min_fd -- The smallest file descriptor this VFS will use. max_fd -- Upper boundary for file descriptors this VFS will use (the biggest file descriptor plus one). Returns ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are registered, ESP_ERR_INVALID_ARG if the file descriptor boundaries are incorrect. esp_err_t esp_vfs_register_with_id(const esp_vfs_t *vfs, void *ctx, esp_vfs_id_t *vfs_id) Special case function for registering a VFS that uses a method other than open() to open new file descriptors. In comparison with esp_vfs_register_fd_range, this function doesn't pre-registers an interval of file descriptors. File descriptors can be registered later, by using esp_vfs_register_fd. Parameters vfs -- Pointer to esp_vfs_t. Meaning is the same as for esp_vfs_register(). ctx -- Pointer to context structure. Meaning is the same as for esp_vfs_register(). vfs_id -- Here will be written the VFS ID which can be passed to esp_vfs_register_fd for registering file descriptors. vfs -- Pointer to esp_vfs_t. Meaning is the same as for esp_vfs_register(). ctx -- Pointer to context structure. Meaning is the same as for esp_vfs_register(). vfs_id -- Here will be written the VFS ID which can be passed to esp_vfs_register_fd for registering file descriptors. vfs -- Pointer to esp_vfs_t. Meaning is the same as for esp_vfs_register(). Returns ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are registered, ESP_ERR_INVALID_ARG if the file descriptor boundaries are incorrect. Parameters vfs -- Pointer to esp_vfs_t. Meaning is the same as for esp_vfs_register(). ctx -- Pointer to context structure. Meaning is the same as for esp_vfs_register(). vfs_id -- Here will be written the VFS ID which can be passed to esp_vfs_register_fd for registering file descriptors. Returns ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are registered, ESP_ERR_INVALID_ARG if the file descriptor boundaries are incorrect. esp_err_t esp_vfs_unregister(const char *base_path) Unregister a virtual filesystem for given path prefix Parameters base_path -- file prefix previously used in esp_vfs_register call Returns ESP_OK if successful, ESP_ERR_INVALID_STATE if VFS for given prefix hasn't been registered Parameters base_path -- file prefix previously used in esp_vfs_register call Returns ESP_OK if successful, ESP_ERR_INVALID_STATE if VFS for given prefix hasn't been registered esp_err_t esp_vfs_unregister_with_id(esp_vfs_id_t vfs_id) Unregister a virtual filesystem with the given index Parameters vfs_id -- The VFS ID returned by esp_vfs_register_with_id Returns ESP_OK if successful, ESP_ERR_INVALID_STATE if VFS for the given index hasn't been registered Parameters vfs_id -- The VFS ID returned by esp_vfs_register_with_id Returns ESP_OK if successful, ESP_ERR_INVALID_STATE if VFS for the given index hasn't been registered esp_err_t esp_vfs_register_fd(esp_vfs_id_t vfs_id, int *fd) Special function for registering another file descriptor for a VFS registered by esp_vfs_register_with_id. Parameters vfs_id -- VFS identificator returned by esp_vfs_register_with_id. fd -- The registered file descriptor will be written to this address. vfs_id -- VFS identificator returned by esp_vfs_register_with_id. fd -- The registered file descriptor will be written to this address. vfs_id -- VFS identificator returned by esp_vfs_register_with_id. Returns ESP_OK if the registration is successful, ESP_ERR_NO_MEM if too many file descriptors are registered, ESP_ERR_INVALID_ARG if the arguments are incorrect. Parameters vfs_id -- VFS identificator returned by esp_vfs_register_with_id. fd -- The registered file descriptor will be written to this address. Returns ESP_OK if the registration is successful, ESP_ERR_NO_MEM if too many file descriptors are registered, ESP_ERR_INVALID_ARG if the arguments are incorrect. esp_err_t esp_vfs_register_fd_with_local_fd(esp_vfs_id_t vfs_id, int local_fd, bool permanent, int *fd) Special function for registering another file descriptor with given local_fd for a VFS registered by esp_vfs_register_with_id. Parameters vfs_id -- VFS identificator returned by esp_vfs_register_with_id. local_fd -- The fd in the local vfs. Passing -1 will set the local fd as the (*fd) value. permanent -- Whether the fd should be treated as permannet (not removed after close()) fd -- The registered file descriptor will be written to this address. vfs_id -- VFS identificator returned by esp_vfs_register_with_id. local_fd -- The fd in the local vfs. Passing -1 will set the local fd as the (*fd) value. permanent -- Whether the fd should be treated as permannet (not removed after close()) fd -- The registered file descriptor will be written to this address. vfs_id -- VFS identificator returned by esp_vfs_register_with_id. Returns ESP_OK if the registration is successful, ESP_ERR_NO_MEM if too many file descriptors are registered, ESP_ERR_INVALID_ARG if the arguments are incorrect. Parameters vfs_id -- VFS identificator returned by esp_vfs_register_with_id. local_fd -- The fd in the local vfs. Passing -1 will set the local fd as the (*fd) value. permanent -- Whether the fd should be treated as permannet (not removed after close()) fd -- The registered file descriptor will be written to this address. Returns ESP_OK if the registration is successful, ESP_ERR_NO_MEM if too many file descriptors are registered, ESP_ERR_INVALID_ARG if the arguments are incorrect. esp_err_t esp_vfs_unregister_fd(esp_vfs_id_t vfs_id, int fd) Special function for unregistering a file descriptor belonging to a VFS registered by esp_vfs_register_with_id. Parameters vfs_id -- VFS identificator returned by esp_vfs_register_with_id. fd -- File descriptor which should be unregistered. vfs_id -- VFS identificator returned by esp_vfs_register_with_id. fd -- File descriptor which should be unregistered. vfs_id -- VFS identificator returned by esp_vfs_register_with_id. Returns ESP_OK if the registration is successful, ESP_ERR_INVALID_ARG if the arguments are incorrect. Parameters vfs_id -- VFS identificator returned by esp_vfs_register_with_id. fd -- File descriptor which should be unregistered. Returns ESP_OK if the registration is successful, ESP_ERR_INVALID_ARG if the arguments are incorrect. int esp_vfs_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout) Synchronous I/O multiplexing which implements the functionality of POSIX select() for VFS. Parameters nfds -- Specifies the range of descriptors which should be checked. The first nfds descriptors will be checked in each set. readfds -- If not NULL, then points to a descriptor set that on input specifies which descriptors should be checked for being ready to read, and on output indicates which descriptors are ready to read. writefds -- If not NULL, then points to a descriptor set that on input specifies which descriptors should be checked for being ready to write, and on output indicates which descriptors are ready to write. errorfds -- If not NULL, then points to a descriptor set that on input specifies which descriptors should be checked for error conditions, and on output indicates which descriptors have error conditions. timeout -- If not NULL, then points to timeval structure which specifies the time period after which the functions should time-out and return. If it is NULL, then the function will not time-out. Note that the timeout period is rounded up to the system tick and incremented by one. nfds -- Specifies the range of descriptors which should be checked. The first nfds descriptors will be checked in each set. readfds -- If not NULL, then points to a descriptor set that on input specifies which descriptors should be checked for being ready to read, and on output indicates which descriptors are ready to read. writefds -- If not NULL, then points to a descriptor set that on input specifies which descriptors should be checked for being ready to write, and on output indicates which descriptors are ready to write. errorfds -- If not NULL, then points to a descriptor set that on input specifies which descriptors should be checked for error conditions, and on output indicates which descriptors have error conditions. timeout -- If not NULL, then points to timeval structure which specifies the time period after which the functions should time-out and return. If it is NULL, then the function will not time-out. Note that the timeout period is rounded up to the system tick and incremented by one. nfds -- Specifies the range of descriptors which should be checked. The first nfds descriptors will be checked in each set. Returns The number of descriptors set in the descriptor sets, or -1 when an error (specified by errno) have occurred. Parameters nfds -- Specifies the range of descriptors which should be checked. The first nfds descriptors will be checked in each set. readfds -- If not NULL, then points to a descriptor set that on input specifies which descriptors should be checked for being ready to read, and on output indicates which descriptors are ready to read. writefds -- If not NULL, then points to a descriptor set that on input specifies which descriptors should be checked for being ready to write, and on output indicates which descriptors are ready to write. errorfds -- If not NULL, then points to a descriptor set that on input specifies which descriptors should be checked for error conditions, and on output indicates which descriptors have error conditions. timeout -- If not NULL, then points to timeval structure which specifies the time period after which the functions should time-out and return. If it is NULL, then the function will not time-out. Note that the timeout period is rounded up to the system tick and incremented by one. Returns The number of descriptors set in the descriptor sets, or -1 when an error (specified by errno) have occurred. void esp_vfs_select_triggered(esp_vfs_select_sem_t sem) Notification from a VFS driver about a read/write/error condition. This function is called when the VFS driver detects a read/write/error condition as it was requested by the previous call to start_select. Parameters sem -- semaphore structure which was passed to the driver by the start_select call Parameters sem -- semaphore structure which was passed to the driver by the start_select call void esp_vfs_select_triggered_isr(esp_vfs_select_sem_t sem, BaseType_t *woken) Notification from a VFS driver about a read/write/error condition (ISR version) This function is called when the VFS driver detects a read/write/error condition as it was requested by the previous call to start_select. Parameters sem -- semaphore structure which was passed to the driver by the start_select call woken -- is set to pdTRUE if the function wakes up a task with higher priority sem -- semaphore structure which was passed to the driver by the start_select call woken -- is set to pdTRUE if the function wakes up a task with higher priority sem -- semaphore structure which was passed to the driver by the start_select call Parameters sem -- semaphore structure which was passed to the driver by the start_select call woken -- is set to pdTRUE if the function wakes up a task with higher priority ssize_t esp_vfs_pread(int fd, void *dst, size_t size, off_t offset) Implements the VFS layer of POSIX pread() Parameters fd -- File descriptor used for read dst -- Pointer to the buffer where the output will be written size -- Number of bytes to be read offset -- Starting offset of the read fd -- File descriptor used for read dst -- Pointer to the buffer where the output will be written size -- Number of bytes to be read offset -- Starting offset of the read fd -- File descriptor used for read Returns A positive return value indicates the number of bytes read. -1 is return on failure and errno is set accordingly. Parameters fd -- File descriptor used for read dst -- Pointer to the buffer where the output will be written size -- Number of bytes to be read offset -- Starting offset of the read Returns A positive return value indicates the number of bytes read. -1 is return on failure and errno is set accordingly. ssize_t esp_vfs_pwrite(int fd, const void *src, size_t size, off_t offset) Implements the VFS layer of POSIX pwrite() Parameters fd -- File descriptor used for write src -- Pointer to the buffer from where the output will be read size -- Number of bytes to write offset -- Starting offset of the write fd -- File descriptor used for write src -- Pointer to the buffer from where the output will be read size -- Number of bytes to write offset -- Starting offset of the write fd -- File descriptor used for write Returns A positive return value indicates the number of bytes written. -1 is return on failure and errno is set accordingly. Parameters fd -- File descriptor used for write src -- Pointer to the buffer from where the output will be read size -- Number of bytes to write offset -- Starting offset of the write Returns A positive return value indicates the number of bytes written. -1 is return on failure and errno is set accordingly. Structures struct esp_vfs_select_sem_t VFS semaphore type for select() struct esp_vfs_t VFS definition structure. This structure should be filled with pointers to corresponding FS driver functions. VFS component will translate all FDs so that the filesystem implementation sees them starting at zero. The caller sees a global FD which is prefixed with an pre-filesystem-implementation. Some FS implementations expect some state (e.g. pointer to some structure) to be passed in as a first argument. For these implementations, populate the members of this structure which have _p suffix, set flags member to ESP_VFS_FLAG_CONTEXT_PTR and provide the context pointer to esp_vfs_register function. If the implementation doesn't use this extra argument, populate the members without _p suffix and set flags member to ESP_VFS_FLAG_DEFAULT. If the FS driver doesn't provide some of the functions, set corresponding members to NULL. Public Members int flags ESP_VFS_FLAG_CONTEXT_PTR and/or ESP_VFS_FLAG_READONLY_FS or ESP_VFS_FLAG_DEFAULT int flags ESP_VFS_FLAG_CONTEXT_PTR and/or ESP_VFS_FLAG_READONLY_FS or ESP_VFS_FLAG_DEFAULT ssize_t (*write_p)(void *p, int fd, const void *data, size_t size) Write with context pointer ssize_t (*write_p)(void *p, int fd, const void *data, size_t size) Write with context pointer ssize_t (*write)(int fd, const void *data, size_t size) Write without context pointer ssize_t (*write)(int fd, const void *data, size_t size) Write without context pointer off_t (*lseek_p)(void *p, int fd, off_t size, int mode) Seek with context pointer off_t (*lseek_p)(void *p, int fd, off_t size, int mode) Seek with context pointer off_t (*lseek)(int fd, off_t size, int mode) Seek without context pointer off_t (*lseek)(int fd, off_t size, int mode) Seek without context pointer ssize_t (*read_p)(void *ctx, int fd, void *dst, size_t size) Read with context pointer ssize_t (*read_p)(void *ctx, int fd, void *dst, size_t size) Read with context pointer ssize_t (*read)(int fd, void *dst, size_t size) Read without context pointer ssize_t (*read)(int fd, void *dst, size_t size) Read without context pointer ssize_t (*pread_p)(void *ctx, int fd, void *dst, size_t size, off_t offset) pread with context pointer ssize_t (*pread_p)(void *ctx, int fd, void *dst, size_t size, off_t offset) pread with context pointer ssize_t (*pread)(int fd, void *dst, size_t size, off_t offset) pread without context pointer ssize_t (*pread)(int fd, void *dst, size_t size, off_t offset) pread without context pointer ssize_t (*pwrite_p)(void *ctx, int fd, const void *src, size_t size, off_t offset) pwrite with context pointer ssize_t (*pwrite_p)(void *ctx, int fd, const void *src, size_t size, off_t offset) pwrite with context pointer ssize_t (*pwrite)(int fd, const void *src, size_t size, off_t offset) pwrite without context pointer ssize_t (*pwrite)(int fd, const void *src, size_t size, off_t offset) pwrite without context pointer int (*open_p)(void *ctx, const char *path, int flags, int mode) open with context pointer int (*open_p)(void *ctx, const char *path, int flags, int mode) open with context pointer int (*open)(const char *path, int flags, int mode) open without context pointer int (*open)(const char *path, int flags, int mode) open without context pointer int (*close_p)(void *ctx, int fd) close with context pointer int (*close_p)(void *ctx, int fd) close with context pointer int (*close)(int fd) close without context pointer int (*close)(int fd) close without context pointer int (*link_p)(void *ctx, const char *n1, const char *n2) link with context pointer int (*link_p)(void *ctx, const char *n1, const char *n2) link with context pointer int (*link)(const char *n1, const char *n2) link without context pointer int (*link)(const char *n1, const char *n2) link without context pointer int (*unlink_p)(void *ctx, const char *path) unlink with context pointer int (*unlink_p)(void *ctx, const char *path) unlink with context pointer int (*unlink)(const char *path) unlink without context pointer int (*unlink)(const char *path) unlink without context pointer int (*rename_p)(void *ctx, const char *src, const char *dst) rename with context pointer int (*rename_p)(void *ctx, const char *src, const char *dst) rename with context pointer int (*rename)(const char *src, const char *dst) rename without context pointer int (*rename)(const char *src, const char *dst) rename without context pointer DIR *(*opendir_p)(void *ctx, const char *name) opendir with context pointer DIR *(*opendir_p)(void *ctx, const char *name) opendir with context pointer DIR *(*opendir)(const char *name) opendir without context pointer DIR *(*opendir)(const char *name) opendir without context pointer struct dirent *(*readdir_p)(void *ctx, DIR *pdir) readdir with context pointer struct dirent *(*readdir_p)(void *ctx, DIR *pdir) readdir with context pointer struct dirent *(*readdir)(DIR *pdir) readdir without context pointer struct dirent *(*readdir)(DIR *pdir) readdir without context pointer int (*readdir_r_p)(void *ctx, DIR *pdir, struct dirent *entry, struct dirent **out_dirent) readdir_r with context pointer int (*readdir_r_p)(void *ctx, DIR *pdir, struct dirent *entry, struct dirent **out_dirent) readdir_r with context pointer int (*readdir_r)(DIR *pdir, struct dirent *entry, struct dirent **out_dirent) readdir_r without context pointer int (*readdir_r)(DIR *pdir, struct dirent *entry, struct dirent **out_dirent) readdir_r without context pointer long (*telldir_p)(void *ctx, DIR *pdir) telldir with context pointer long (*telldir_p)(void *ctx, DIR *pdir) telldir with context pointer long (*telldir)(DIR *pdir) telldir without context pointer long (*telldir)(DIR *pdir) telldir without context pointer void (*seekdir_p)(void *ctx, DIR *pdir, long offset) seekdir with context pointer void (*seekdir_p)(void *ctx, DIR *pdir, long offset) seekdir with context pointer void (*seekdir)(DIR *pdir, long offset) seekdir without context pointer void (*seekdir)(DIR *pdir, long offset) seekdir without context pointer int (*closedir_p)(void *ctx, DIR *pdir) closedir with context pointer int (*closedir_p)(void *ctx, DIR *pdir) closedir with context pointer int (*closedir)(DIR *pdir) closedir without context pointer int (*closedir)(DIR *pdir) closedir without context pointer int (*mkdir_p)(void *ctx, const char *name, mode_t mode) mkdir with context pointer int (*mkdir_p)(void *ctx, const char *name, mode_t mode) mkdir with context pointer int (*mkdir)(const char *name, mode_t mode) mkdir without context pointer int (*mkdir)(const char *name, mode_t mode) mkdir without context pointer int (*rmdir_p)(void *ctx, const char *name) rmdir with context pointer int (*rmdir_p)(void *ctx, const char *name) rmdir with context pointer int (*rmdir)(const char *name) rmdir without context pointer int (*rmdir)(const char *name) rmdir without context pointer int (*fcntl_p)(void *ctx, int fd, int cmd, int arg) fcntl with context pointer int (*fcntl_p)(void *ctx, int fd, int cmd, int arg) fcntl with context pointer int (*fcntl)(int fd, int cmd, int arg) fcntl without context pointer int (*fcntl)(int fd, int cmd, int arg) fcntl without context pointer int (*ioctl_p)(void *ctx, int fd, int cmd, va_list args) ioctl with context pointer int (*ioctl_p)(void *ctx, int fd, int cmd, va_list args) ioctl with context pointer int (*ioctl)(int fd, int cmd, va_list args) ioctl without context pointer int (*ioctl)(int fd, int cmd, va_list args) ioctl without context pointer int (*fsync_p)(void *ctx, int fd) fsync with context pointer int (*fsync_p)(void *ctx, int fd) fsync with context pointer int (*fsync)(int fd) fsync without context pointer int (*fsync)(int fd) fsync without context pointer int (*access_p)(void *ctx, const char *path, int amode) access with context pointer int (*access_p)(void *ctx, const char *path, int amode) access with context pointer int (*access)(const char *path, int amode) access without context pointer int (*access)(const char *path, int amode) access without context pointer int (*truncate_p)(void *ctx, const char *path, off_t length) truncate with context pointer int (*truncate_p)(void *ctx, const char *path, off_t length) truncate with context pointer int (*truncate)(const char *path, off_t length) truncate without context pointer int (*truncate)(const char *path, off_t length) truncate without context pointer int (*ftruncate_p)(void *ctx, int fd, off_t length) ftruncate with context pointer int (*ftruncate_p)(void *ctx, int fd, off_t length) ftruncate with context pointer int (*ftruncate)(int fd, off_t length) ftruncate without context pointer int (*ftruncate)(int fd, off_t length) ftruncate without context pointer int (*utime_p)(void *ctx, const char *path, const struct utimbuf *times) utime with context pointer int (*utime_p)(void *ctx, const char *path, const struct utimbuf *times) utime with context pointer int (*utime)(const char *path, const struct utimbuf *times) utime without context pointer int (*utime)(const char *path, const struct utimbuf *times) utime without context pointer int (*tcsetattr_p)(void *ctx, int fd, int optional_actions, const struct termios *p) tcsetattr with context pointer int (*tcsetattr_p)(void *ctx, int fd, int optional_actions, const struct termios *p) tcsetattr with context pointer int (*tcsetattr)(int fd, int optional_actions, const struct termios *p) tcsetattr without context pointer int (*tcsetattr)(int fd, int optional_actions, const struct termios *p) tcsetattr without context pointer int (*tcgetattr_p)(void *ctx, int fd, struct termios *p) tcgetattr with context pointer int (*tcgetattr_p)(void *ctx, int fd, struct termios *p) tcgetattr with context pointer int (*tcgetattr)(int fd, struct termios *p) tcgetattr without context pointer int (*tcgetattr)(int fd, struct termios *p) tcgetattr without context pointer int (*tcdrain_p)(void *ctx, int fd) tcdrain with context pointer int (*tcdrain_p)(void *ctx, int fd) tcdrain with context pointer int (*tcdrain)(int fd) tcdrain without context pointer int (*tcdrain)(int fd) tcdrain without context pointer int (*tcflush_p)(void *ctx, int fd, int select) tcflush with context pointer int (*tcflush_p)(void *ctx, int fd, int select) tcflush with context pointer int (*tcflush)(int fd, int select) tcflush without context pointer int (*tcflush)(int fd, int select) tcflush without context pointer int (*tcflow_p)(void *ctx, int fd, int action) tcflow with context pointer int (*tcflow_p)(void *ctx, int fd, int action) tcflow with context pointer int (*tcflow)(int fd, int action) tcflow without context pointer int (*tcflow)(int fd, int action) tcflow without context pointer pid_t (*tcgetsid_p)(void *ctx, int fd) tcgetsid with context pointer pid_t (*tcgetsid_p)(void *ctx, int fd) tcgetsid with context pointer pid_t (*tcgetsid)(int fd) tcgetsid without context pointer pid_t (*tcgetsid)(int fd) tcgetsid without context pointer int (*tcsendbreak_p)(void *ctx, int fd, int duration) tcsendbreak with context pointer int (*tcsendbreak_p)(void *ctx, int fd, int duration) tcsendbreak with context pointer int (*tcsendbreak)(int fd, int duration) tcsendbreak without context pointer int (*tcsendbreak)(int fd, int duration) tcsendbreak without context pointer esp_err_t (*start_select)(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, esp_vfs_select_sem_t sem, void **end_select_args) start_select is called for setting up synchronous I/O multiplexing of the desired file descriptors in the given VFS esp_err_t (*start_select)(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, esp_vfs_select_sem_t sem, void **end_select_args) start_select is called for setting up synchronous I/O multiplexing of the desired file descriptors in the given VFS int (*socket_select)(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout) socket select function for socket FDs with the functionality of POSIX select(); this should be set only for the socket VFS int (*socket_select)(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout) socket select function for socket FDs with the functionality of POSIX select(); this should be set only for the socket VFS void (*stop_socket_select)(void *sem) called by VFS to interrupt the socket_select call when select is activated from a non-socket VFS driver; set only for the socket driver void (*stop_socket_select)(void *sem) called by VFS to interrupt the socket_select call when select is activated from a non-socket VFS driver; set only for the socket driver void (*stop_socket_select_isr)(void *sem, BaseType_t *woken) stop_socket_select which can be called from ISR; set only for the socket driver void (*stop_socket_select_isr)(void *sem, BaseType_t *woken) stop_socket_select which can be called from ISR; set only for the socket driver void *(*get_socket_select_semaphore)(void) end_select is called to stop the I/O multiplexing and deinitialize the environment created by start_select for the given VFS void *(*get_socket_select_semaphore)(void) end_select is called to stop the I/O multiplexing and deinitialize the environment created by start_select for the given VFS int flags Macros MAX_FDS Maximum number of (global) file descriptors. ESP_VFS_PATH_MAX Maximum length of path prefix (not including zero terminator) ESP_VFS_FLAG_CONTEXT_PTR Flag which indicates that FS needs extra context pointer in syscalls. ESP_VFS_FLAG_READONLY_FS Flag which indicates that FS is located on read-only partition. Type Definitions typedef int esp_vfs_id_t Header File This header file can be included with: #include "esp_vfs_dev.h" This header file is a part of the API provided by the vfs component. To declare that your component depends on vfs , add the following to your CMakeLists.txt: REQUIRES vfs or PRIV_REQUIRES vfs Functions void esp_vfs_dev_uart_register(void) add /dev/uart virtual filesystem driver This function is called from startup code to enable serial output void esp_vfs_dev_uart_set_rx_line_endings(esp_line_endings_t mode) Set the line endings expected to be received on UART. This specifies the conversion between line endings received on UART and newlines (' ', LF) passed into stdin: ESP_LINE_ENDINGS_CRLF: convert CRLF to LF ESP_LINE_ENDINGS_CR: convert CR to LF ESP_LINE_ENDINGS_LF: no modification ESP_LINE_ENDINGS_CRLF: convert CRLF to LF ESP_LINE_ENDINGS_CR: convert CR to LF ESP_LINE_ENDINGS_LF: no modification Note this function is not thread safe w.r.t. reading from UART Parameters mode -- line endings expected on UART Parameters mode -- line endings expected on UART ESP_LINE_ENDINGS_CRLF: convert CRLF to LF void esp_vfs_dev_uart_set_tx_line_endings(esp_line_endings_t mode) Set the line endings to sent to UART. This specifies the conversion between newlines (' ', LF) on stdout and line endings sent over UART: ESP_LINE_ENDINGS_CRLF: convert LF to CRLF ESP_LINE_ENDINGS_CR: convert LF to CR ESP_LINE_ENDINGS_LF: no modification ESP_LINE_ENDINGS_CRLF: convert LF to CRLF ESP_LINE_ENDINGS_CR: convert LF to CR ESP_LINE_ENDINGS_LF: no modification Note this function is not thread safe w.r.t. writing to UART Parameters mode -- line endings to send to UART Parameters mode -- line endings to send to UART ESP_LINE_ENDINGS_CRLF: convert LF to CRLF int esp_vfs_dev_uart_port_set_rx_line_endings(int uart_num, esp_line_endings_t mode) Set the line endings expected to be received on specified UART. This specifies the conversion between line endings received on UART and newlines (' ', LF) passed into stdin: ESP_LINE_ENDINGS_CRLF: convert CRLF to LF ESP_LINE_ENDINGS_CR: convert CR to LF ESP_LINE_ENDINGS_LF: no modification ESP_LINE_ENDINGS_CRLF: convert CRLF to LF ESP_LINE_ENDINGS_CR: convert CR to LF ESP_LINE_ENDINGS_LF: no modification Note this function is not thread safe w.r.t. reading from UART Parameters uart_num -- the UART number mode -- line endings to send to UART uart_num -- the UART number mode -- line endings to send to UART uart_num -- the UART number Returns 0 if successed, or -1 when an error (specified by errno) have occurred. Parameters uart_num -- the UART number mode -- line endings to send to UART Returns 0 if successed, or -1 when an error (specified by errno) have occurred. ESP_LINE_ENDINGS_CRLF: convert CRLF to LF int esp_vfs_dev_uart_port_set_tx_line_endings(int uart_num, esp_line_endings_t mode) Set the line endings to sent to specified UART. This specifies the conversion between newlines (' ', LF) on stdout and line endings sent over UART: ESP_LINE_ENDINGS_CRLF: convert LF to CRLF ESP_LINE_ENDINGS_CR: convert LF to CR ESP_LINE_ENDINGS_LF: no modification ESP_LINE_ENDINGS_CRLF: convert LF to CRLF ESP_LINE_ENDINGS_CR: convert LF to CR ESP_LINE_ENDINGS_LF: no modification Note this function is not thread safe w.r.t. writing to UART Parameters uart_num -- the UART number mode -- line endings to send to UART uart_num -- the UART number mode -- line endings to send to UART uart_num -- the UART number Returns 0 if successed, or -1 when an error (specified by errno) have occurred. Parameters uart_num -- the UART number mode -- line endings to send to UART Returns 0 if successed, or -1 when an error (specified by errno) have occurred. ESP_LINE_ENDINGS_CRLF: convert LF to CRLF void esp_vfs_dev_uart_use_nonblocking(int uart_num) set VFS to use simple functions for reading and writing UART Read is non-blocking, write is busy waiting until TX FIFO has enough space. These functions are used by default. Parameters uart_num -- UART peripheral number Parameters uart_num -- UART peripheral number void esp_vfs_dev_uart_use_driver(int uart_num) set VFS to use UART driver for reading and writing Note application must configure UART driver before calling these functions With these functions, read and write are blocking and interrupt-driven. Parameters uart_num -- UART peripheral number Parameters uart_num -- UART peripheral number void esp_vfs_usb_serial_jtag_use_driver(void) set VFS to use USB-SERIAL-JTAG driver for reading and writing Note application must configure USB-SERIAL-JTAG driver before calling these functions With these functions, read and write are blocking and interrupt-driven. void esp_vfs_usb_serial_jtag_use_nonblocking(void) set VFS to use simple functions for reading and writing UART Read is non-blocking, write is busy waiting until TX FIFO has enough space. These functions are used by default. Header File This header file can be included with: #include "esp_vfs_eventfd.h" This header file is a part of the API provided by the vfs component. To declare that your component depends on vfs , add the following to your CMakeLists.txt: REQUIRES vfs or PRIV_REQUIRES vfs Functions esp_err_t esp_vfs_eventfd_register(const esp_vfs_eventfd_config_t *config) Registers the event vfs. Returns ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are registered. Returns ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are registered. esp_err_t esp_vfs_eventfd_unregister(void) Unregisters the event vfs. Returns ESP_OK if successful, ESP_ERR_INVALID_STATE if VFS for given prefix hasn't been registered Returns ESP_OK if successful, ESP_ERR_INVALID_STATE if VFS for given prefix hasn't been registered int eventfd(unsigned int initval, int flags) Structures Macros EFD_SUPPORT_ISR ESP_VFS_EVENTD_CONFIG_DEFAULT()
Virtual Filesystem Component Overview Virtual filesystem (VFS) component provides a unified interface for drivers which can perform operations on file-like objects. These can be real filesystems (FAT, SPIFFS, etc.) or device drivers which provide a file-like interface. This component allows C library functions, such as fopen and fprintf, to work with FS drivers. At a high level, each FS driver is associated with some path prefix. When one of C library functions needs to open a file, the VFS component searches for the FS driver associated with the file path and forwards the call to that driver. VFS also forwards read, write, and other calls for the given file to the same FS driver. For example, one can register a FAT filesystem driver with the /fat prefix and call fopen("/fat/file.txt", "w"). Then the VFS component calls the function open of the FAT driver and pass the argument /file.txt to it together with appropriate mode flags. All subsequent calls to C library functions for the returned FILE* stream will also be forwarded to the FAT driver. FS Registration To register an FS driver, an application needs to define an instance of the esp_vfs_t structure and populate it with function pointers to FS APIs: esp_vfs_t myfs = { .flags = ESP_VFS_FLAG_DEFAULT, .write = &myfs_write, .open = &myfs_open, .fstat = &myfs_fstat, .close = &myfs_close, .read = &myfs_read, }; ESP_ERROR_CHECK(esp_vfs_register("/data", &myfs, NULL)); Depending on the way how the FS driver declares its API functions, either read, write, etc., or read_p, write_p, etc., should be used. Case 1: API functions are declared without an extra context pointer (the FS driver is a singleton): ssize_t myfs_write(int fd, const void * data, size_t size); // In definition of esp_vfs_t: .flags = ESP_VFS_FLAG_DEFAULT, .write = &myfs_write, // ... other members initialized // When registering FS, context pointer (third argument) is NULL: ESP_ERROR_CHECK(esp_vfs_register("/data", &myfs, NULL)); Case 2: API functions are declared with an extra context pointer (the FS driver supports multiple instances): ssize_t myfs_write(myfs_t* fs, int fd, const void * data, size_t size); // In definition of esp_vfs_t: .flags = ESP_VFS_FLAG_CONTEXT_PTR, .write_p = &myfs_write, // ... other members initialized // When registering FS, pass the FS context pointer into the third argument // (hypothetical myfs_mount function is used for illustrative purposes) myfs_t* myfs_inst1 = myfs_mount(partition1->offset, partition1->size); ESP_ERROR_CHECK(esp_vfs_register("/data1", &myfs, myfs_inst1)); // Can register another instance: myfs_t* myfs_inst2 = myfs_mount(partition2->offset, partition2->size); ESP_ERROR_CHECK(esp_vfs_register("/data2", &myfs, myfs_inst2)); Synchronous Input/Output Multiplexing Synchronous input/output multiplexing by select() is supported in the VFS component. The implementation works in the following way. select()is called with file descriptors which could belong to various VFS drivers. The file descriptors are divided into groups each belonging to one VFS driver. The file descriptors belonging to non-socket VFS drivers are handed over to the given VFS drivers by start_select(), described later on this page. This function represents the driver-specific implementation of select()for the given driver. This should be a non-blocking call which means the function should immediately return after setting up the environment for checking events related to the given file descriptors. The file descriptors belonging to the socket VFS driver are handed over to the socket driver by socket_select()described later on this page. This is a blocking call which means that it will return only if there is an event related to socket file descriptors or a non-socket driver signals socket_select()to exit. Results are collected from each VFS driver and all drivers are stopped by de-initialization of the environment for checking events. The select()call ends and returns the appropriate results. Non-Socket VFS Drivers If you want to use select() with a file descriptor belonging to a non-socket VFS driver, then you need to register the driver with functions start_select() and end_select() similarly to the following example: // In definition of esp_vfs_t: .start_select = &uart_start_select, .end_select = &uart_end_select, // ... other members initialized start_select() is called for setting up the environment for detection of read/write/error conditions on file descriptors belonging to the given VFS driver. end_select() is called to stop/deinitialize/free the environment which was setup by start_select(). Note end_select() might be called without a previous start_select() call in some rare circumstances. end_select() should fail gracefully if this is the case (i.e., should not crash but return an error instead). Please refer to the reference implementation for the UART peripheral in vfs/vfs_uart.c and most particularly to the functions esp_vfs_dev_uart_register(), uart_start_select(), and uart_end_select() for more information. Please check the following examples that demonstrate the use of select() with VFS file descriptors: Socket VFS Drivers A socket VFS driver is using its own internal implementation of select() and non-socket VFS drivers notify it upon read/write/error conditions. A socket VFS driver needs to be registered with the following functions defined: // In definition of esp_vfs_t: .socket_select = &lwip_select, .get_socket_select_semaphore = &lwip_get_socket_select_semaphore, .stop_socket_select = &lwip_stop_socket_select, .stop_socket_select_isr = &lwip_stop_socket_select_isr, // ... other members initialized socket_select() is the internal implementation of select() for the socket driver. It works only with file descriptors belonging to the socket VFS. get_socket_select_semaphore() returns the signalization object (semaphore) which is used in non-socket drivers to stop the waiting in socket_select(). stop_socket_select() call is used to stop the waiting in socket_select() by passing the object returned by get_socket_select_semaphore(). stop_socket_select_isr() has the same functionality as stop_socket_select() but it can be used from ISR. Please see lwip/port/esp32xx/vfs_lwip.c for a reference socket driver implementation using LWIP. Note If you use select() for socket file descriptors only then you can disable the CONFIG_VFS_SUPPORT_SELECT option to reduce the code size and improve performance. You should not change the socket driver during an active select() call or you might experience some undefined behavior. Paths Each registered FS has a path prefix associated with it. This prefix can be considered as a "mount point" of this partition. In case when mount points are nested, the mount point with the longest matching path prefix is used when opening the file. For instance, suppose that the following filesystems are registered in VFS: FS 1 on /data FS 2 on /data/static Then: FS 1 will be used when opening a file called /data/log.txt FS 2 will be used when opening a file called /data/static/index.html Even if /index.html"does not exist in FS 2, FS 1 will not be searched for /static/index.html. As a general rule, mount point names must start with the path separator ( /) and must contain at least one character after path separator. However, an empty mount point name is also supported and might be used in cases when an application needs to provide a "fallback" filesystem or to override VFS functionality altogether. Such filesystem will be used if no prefix matches the path given. VFS does not handle dots ( .) in path names in any special way. VFS does not treat .. as a reference to the parent directory. In the above example, using a path /data/static/../log.txt will not result in a call to FS 1 to open /log.txt. Specific FS drivers (such as FATFS) might handle dots in file names differently. When opening files, the FS driver receives only relative paths to files. For example: The myfsdriver is registered with /dataas a path prefix. The application calls fopen("/data/config.json", ...). The VFS component calls myfs_open("/config.json", ...). The myfsdriver opens the /config.jsonfile. VFS does not impose any limit on total file path length, but it does limit the FS path prefix to ESP_VFS_PATH_MAX characters. Individual FS drivers may have their own filename length limitations. File Descriptors File descriptors are small positive integers from 0 to FD_SETSIZE - 1, where FD_SETSIZE is defined in sys/select.h. The largest file descriptors (configured by CONFIG_LWIP_MAX_SOCKETS) are reserved for sockets. The VFS component contains a lookup-table called s_fd_table for mapping global file descriptors to VFS driver indexes registered in the s_vfs array. Standard IO Streams ( stdin, stdout, stderr) If the menuconfig option UART for console output is not set to None, then stdin, stdout, and stderr are configured to read from, and write to, a UART. It is possible to use UART0 or UART1 for standard IO. By default, UART0 is used with 115200 baud rate; TX pin is GPIO1; RX pin is GPIO3. These parameters can be changed in menuconfig. Writing to stdout or stderr sends characters to the UART transmit FIFO. Reading from stdin retrieves characters from the UART receive FIFO. By default, VFS uses simple functions for reading from and writing to UART. Writes busy-wait until all data is put into UART FIFO, and reads are non-blocking, returning only the data present in the FIFO. Due to this non-blocking read behavior, higher level C library calls, such as fscanf("%d\n", &var);, might not have desired results. Applications which use the UART driver can instruct VFS to use the driver's interrupt driven, blocking read and write functions instead. This can be done using a call to the esp_vfs_dev_uart_use_driver function. It is also possible to revert to the basic non-blocking functions using a call to esp_vfs_dev_uart_use_nonblocking. VFS also provides an optional newline conversion feature for input and output. Internally, most applications send and receive lines terminated by the LF (''n'') character. Different terminal programs may require different line termination, such as CR or CRLF. Applications can configure this separately for input and output either via menuconfig, or by calls to the functions esp_vfs_dev_uart_port_set_rx_line_endings and esp_vfs_dev_uart_port_set_tx_line_endings. Standard Streams and FreeRTOS Tasks FILE objects for stdin, stdout, and stderr are shared between all FreeRTOS tasks, but the pointers to these objects are stored in per-task struct _reent. The following code is transferred to fprintf(__getreent()->_stderr, "42\n"); by the preprocessor: fprintf(stderr, "42\n"); The __getreent() function returns a per-task pointer to struct _reent in newlib libc. This structure is allocated on the TCB of each task. When a task is initialized, _stdin, _stdout, and _stderr members of struct _reent are set to the values of _stdin, _stdout, and _stderr of _GLOBAL_REENT (i.e., the structure which is used before FreeRTOS is started). Such a design has the following consequences: It is possible to set stdin, stdout, and stderrfor any given task without affecting other tasks, e.g., by doing stdin = fopen("/dev/uart/1", "r"). Closing default stdin, stdout, or stderrusing fclosecloses the FILEstream object, which will affect all other tasks. To change the default stdin, stdout, stderrstreams for new tasks, modify _GLOBAL_REENT->_stdin( _stdout, _stderr) before creating the task. eventfd() eventfd() call is a powerful tool to notify a select() based loop of custom events. The eventfd() implementation in ESP-IDF is generally the same as described in man(2) eventfd except for: esp_vfs_eventfd_register()has to be called before calling eventfd() Options EFD_CLOEXEC, EFD_NONBLOCKand EFD_SEMAPHOREare not supported in flags. Option EFD_SUPPORT_ISRhas been added in flags. This flag is required to read and write the eventfd in an interrupt handler. Note that creating an eventfd with EFD_SUPPORT_ISR will cause interrupts to be temporarily disabled when reading, writing the file and during the beginning and the ending of the select() when this file is set. API Reference Header File This header file can be included with: #include "esp_vfs.h" This header file is a part of the API provided by the vfscomponent. To declare that your component depends on vfs, add the following to your CMakeLists.txt: REQUIRES vfs or PRIV_REQUIRES vfs Functions - ssize_t esp_vfs_write(struct _reent *r, int fd, const void *data, size_t size) These functions are to be used in newlib syscall table. They will be called by newlib when it needs to use any of the syscalls. - off_t esp_vfs_lseek(struct _reent *r, int fd, off_t size, int mode) - ssize_t esp_vfs_read(struct _reent *r, int fd, void *dst, size_t size) - int esp_vfs_open(struct _reent *r, const char *path, int flags, int mode) - int esp_vfs_close(struct _reent *r, int fd) - int esp_vfs_fstat(struct _reent *r, int fd, struct stat *st) - int esp_vfs_stat(struct _reent *r, const char *path, struct stat *st) - int esp_vfs_link(struct _reent *r, const char *n1, const char *n2) - int esp_vfs_unlink(struct _reent *r, const char *path) - int esp_vfs_rename(struct _reent *r, const char *src, const char *dst) - int esp_vfs_utime(const char *path, const struct utimbuf *times) - esp_err_t esp_vfs_register(const char *base_path, const esp_vfs_t *vfs, void *ctx) Register a virtual filesystem for given path prefix. - Parameters base_path -- file path prefix associated with the filesystem. Must be a zero-terminated C string, may be empty. If not empty, must be up to ESP_VFS_PATH_MAX characters long, and at least 2 characters long. Name must start with a "/" and must not end with "/". For example, "/data" or "/dev/spi" are valid. These VFSes would then be called to handle file paths such as "/data/myfile.txt" or "/dev/spi/0". In the special case of an empty base_path, a "fallback" VFS is registered. Such VFS will handle paths which are not matched by any other registered VFS. vfs -- Pointer to esp_vfs_t, a structure which maps syscalls to the filesystem driver functions. VFS component doesn't assume ownership of this pointer. ctx -- If vfs->flags has ESP_VFS_FLAG_CONTEXT_PTR set, a pointer which should be passed to VFS functions. Otherwise, NULL. - - Returns ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are registered. - esp_err_t esp_vfs_register_fd_range(const esp_vfs_t *vfs, void *ctx, int min_fd, int max_fd) Special case function for registering a VFS that uses a method other than open() to open new file descriptors from the interval <min_fd; max_fd). This is a special-purpose function intended for registering LWIP sockets to VFS. - Parameters vfs -- Pointer to esp_vfs_t. Meaning is the same as for esp_vfs_register(). ctx -- Pointer to context structure. Meaning is the same as for esp_vfs_register(). min_fd -- The smallest file descriptor this VFS will use. max_fd -- Upper boundary for file descriptors this VFS will use (the biggest file descriptor plus one). - - Returns ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are registered, ESP_ERR_INVALID_ARG if the file descriptor boundaries are incorrect. - esp_err_t esp_vfs_register_with_id(const esp_vfs_t *vfs, void *ctx, esp_vfs_id_t *vfs_id) Special case function for registering a VFS that uses a method other than open() to open new file descriptors. In comparison with esp_vfs_register_fd_range, this function doesn't pre-registers an interval of file descriptors. File descriptors can be registered later, by using esp_vfs_register_fd. - Parameters vfs -- Pointer to esp_vfs_t. Meaning is the same as for esp_vfs_register(). ctx -- Pointer to context structure. Meaning is the same as for esp_vfs_register(). vfs_id -- Here will be written the VFS ID which can be passed to esp_vfs_register_fd for registering file descriptors. - - Returns ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are registered, ESP_ERR_INVALID_ARG if the file descriptor boundaries are incorrect. - esp_err_t esp_vfs_unregister(const char *base_path) Unregister a virtual filesystem for given path prefix - Parameters base_path -- file prefix previously used in esp_vfs_register call - Returns ESP_OK if successful, ESP_ERR_INVALID_STATE if VFS for given prefix hasn't been registered - esp_err_t esp_vfs_unregister_with_id(esp_vfs_id_t vfs_id) Unregister a virtual filesystem with the given index - Parameters vfs_id -- The VFS ID returned by esp_vfs_register_with_id - Returns ESP_OK if successful, ESP_ERR_INVALID_STATE if VFS for the given index hasn't been registered - esp_err_t esp_vfs_register_fd(esp_vfs_id_t vfs_id, int *fd) Special function for registering another file descriptor for a VFS registered by esp_vfs_register_with_id. - Parameters vfs_id -- VFS identificator returned by esp_vfs_register_with_id. fd -- The registered file descriptor will be written to this address. - - Returns ESP_OK if the registration is successful, ESP_ERR_NO_MEM if too many file descriptors are registered, ESP_ERR_INVALID_ARG if the arguments are incorrect. - esp_err_t esp_vfs_register_fd_with_local_fd(esp_vfs_id_t vfs_id, int local_fd, bool permanent, int *fd) Special function for registering another file descriptor with given local_fd for a VFS registered by esp_vfs_register_with_id. - Parameters vfs_id -- VFS identificator returned by esp_vfs_register_with_id. local_fd -- The fd in the local vfs. Passing -1 will set the local fd as the (*fd) value. permanent -- Whether the fd should be treated as permannet (not removed after close()) fd -- The registered file descriptor will be written to this address. - - Returns ESP_OK if the registration is successful, ESP_ERR_NO_MEM if too many file descriptors are registered, ESP_ERR_INVALID_ARG if the arguments are incorrect. - esp_err_t esp_vfs_unregister_fd(esp_vfs_id_t vfs_id, int fd) Special function for unregistering a file descriptor belonging to a VFS registered by esp_vfs_register_with_id. - Parameters vfs_id -- VFS identificator returned by esp_vfs_register_with_id. fd -- File descriptor which should be unregistered. - - Returns ESP_OK if the registration is successful, ESP_ERR_INVALID_ARG if the arguments are incorrect. - int esp_vfs_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout) Synchronous I/O multiplexing which implements the functionality of POSIX select() for VFS. - Parameters nfds -- Specifies the range of descriptors which should be checked. The first nfds descriptors will be checked in each set. readfds -- If not NULL, then points to a descriptor set that on input specifies which descriptors should be checked for being ready to read, and on output indicates which descriptors are ready to read. writefds -- If not NULL, then points to a descriptor set that on input specifies which descriptors should be checked for being ready to write, and on output indicates which descriptors are ready to write. errorfds -- If not NULL, then points to a descriptor set that on input specifies which descriptors should be checked for error conditions, and on output indicates which descriptors have error conditions. timeout -- If not NULL, then points to timeval structure which specifies the time period after which the functions should time-out and return. If it is NULL, then the function will not time-out. Note that the timeout period is rounded up to the system tick and incremented by one. - - Returns The number of descriptors set in the descriptor sets, or -1 when an error (specified by errno) have occurred. - void esp_vfs_select_triggered(esp_vfs_select_sem_t sem) Notification from a VFS driver about a read/write/error condition. This function is called when the VFS driver detects a read/write/error condition as it was requested by the previous call to start_select. - Parameters sem -- semaphore structure which was passed to the driver by the start_select call - void esp_vfs_select_triggered_isr(esp_vfs_select_sem_t sem, BaseType_t *woken) Notification from a VFS driver about a read/write/error condition (ISR version) This function is called when the VFS driver detects a read/write/error condition as it was requested by the previous call to start_select. - Parameters sem -- semaphore structure which was passed to the driver by the start_select call woken -- is set to pdTRUE if the function wakes up a task with higher priority - - ssize_t esp_vfs_pread(int fd, void *dst, size_t size, off_t offset) Implements the VFS layer of POSIX pread() - Parameters fd -- File descriptor used for read dst -- Pointer to the buffer where the output will be written size -- Number of bytes to be read offset -- Starting offset of the read - - Returns A positive return value indicates the number of bytes read. -1 is return on failure and errno is set accordingly. - ssize_t esp_vfs_pwrite(int fd, const void *src, size_t size, off_t offset) Implements the VFS layer of POSIX pwrite() - Parameters fd -- File descriptor used for write src -- Pointer to the buffer from where the output will be read size -- Number of bytes to write offset -- Starting offset of the write - - Returns A positive return value indicates the number of bytes written. -1 is return on failure and errno is set accordingly. Structures - struct esp_vfs_select_sem_t VFS semaphore type for select() - struct esp_vfs_t VFS definition structure. This structure should be filled with pointers to corresponding FS driver functions. VFS component will translate all FDs so that the filesystem implementation sees them starting at zero. The caller sees a global FD which is prefixed with an pre-filesystem-implementation. Some FS implementations expect some state (e.g. pointer to some structure) to be passed in as a first argument. For these implementations, populate the members of this structure which have _p suffix, set flags member to ESP_VFS_FLAG_CONTEXT_PTR and provide the context pointer to esp_vfs_register function. If the implementation doesn't use this extra argument, populate the members without _p suffix and set flags member to ESP_VFS_FLAG_DEFAULT. If the FS driver doesn't provide some of the functions, set corresponding members to NULL. Public Members - int flags ESP_VFS_FLAG_CONTEXT_PTR and/or ESP_VFS_FLAG_READONLY_FS or ESP_VFS_FLAG_DEFAULT - ssize_t (*write_p)(void *p, int fd, const void *data, size_t size) Write with context pointer - ssize_t (*write)(int fd, const void *data, size_t size) Write without context pointer - off_t (*lseek_p)(void *p, int fd, off_t size, int mode) Seek with context pointer - off_t (*lseek)(int fd, off_t size, int mode) Seek without context pointer - ssize_t (*read_p)(void *ctx, int fd, void *dst, size_t size) Read with context pointer - ssize_t (*read)(int fd, void *dst, size_t size) Read without context pointer - ssize_t (*pread_p)(void *ctx, int fd, void *dst, size_t size, off_t offset) pread with context pointer - ssize_t (*pread)(int fd, void *dst, size_t size, off_t offset) pread without context pointer - ssize_t (*pwrite_p)(void *ctx, int fd, const void *src, size_t size, off_t offset) pwrite with context pointer - ssize_t (*pwrite)(int fd, const void *src, size_t size, off_t offset) pwrite without context pointer - int (*open_p)(void *ctx, const char *path, int flags, int mode) open with context pointer - int (*open)(const char *path, int flags, int mode) open without context pointer - int (*close_p)(void *ctx, int fd) close with context pointer - int (*close)(int fd) close without context pointer - int (*link_p)(void *ctx, const char *n1, const char *n2) link with context pointer - int (*link)(const char *n1, const char *n2) link without context pointer - int (*unlink_p)(void *ctx, const char *path) unlink with context pointer - int (*unlink)(const char *path) unlink without context pointer - int (*rename_p)(void *ctx, const char *src, const char *dst) rename with context pointer - int (*rename)(const char *src, const char *dst) rename without context pointer - DIR *(*opendir_p)(void *ctx, const char *name) opendir with context pointer - DIR *(*opendir)(const char *name) opendir without context pointer - struct dirent *(*readdir_p)(void *ctx, DIR *pdir) readdir with context pointer - struct dirent *(*readdir)(DIR *pdir) readdir without context pointer - int (*readdir_r_p)(void *ctx, DIR *pdir, struct dirent *entry, struct dirent **out_dirent) readdir_r with context pointer - int (*readdir_r)(DIR *pdir, struct dirent *entry, struct dirent **out_dirent) readdir_r without context pointer - long (*telldir_p)(void *ctx, DIR *pdir) telldir with context pointer - long (*telldir)(DIR *pdir) telldir without context pointer - void (*seekdir_p)(void *ctx, DIR *pdir, long offset) seekdir with context pointer - void (*seekdir)(DIR *pdir, long offset) seekdir without context pointer - int (*closedir_p)(void *ctx, DIR *pdir) closedir with context pointer - int (*closedir)(DIR *pdir) closedir without context pointer - int (*mkdir_p)(void *ctx, const char *name, mode_t mode) mkdir with context pointer - int (*mkdir)(const char *name, mode_t mode) mkdir without context pointer - int (*rmdir_p)(void *ctx, const char *name) rmdir with context pointer - int (*rmdir)(const char *name) rmdir without context pointer - int (*fcntl_p)(void *ctx, int fd, int cmd, int arg) fcntl with context pointer - int (*fcntl)(int fd, int cmd, int arg) fcntl without context pointer - int (*ioctl_p)(void *ctx, int fd, int cmd, va_list args) ioctl with context pointer - int (*ioctl)(int fd, int cmd, va_list args) ioctl without context pointer - int (*fsync_p)(void *ctx, int fd) fsync with context pointer - int (*fsync)(int fd) fsync without context pointer - int (*access_p)(void *ctx, const char *path, int amode) access with context pointer - int (*access)(const char *path, int amode) access without context pointer - int (*truncate_p)(void *ctx, const char *path, off_t length) truncate with context pointer - int (*truncate)(const char *path, off_t length) truncate without context pointer - int (*ftruncate_p)(void *ctx, int fd, off_t length) ftruncate with context pointer - int (*ftruncate)(int fd, off_t length) ftruncate without context pointer - int (*utime_p)(void *ctx, const char *path, const struct utimbuf *times) utime with context pointer - int (*utime)(const char *path, const struct utimbuf *times) utime without context pointer - int (*tcsetattr_p)(void *ctx, int fd, int optional_actions, const struct termios *p) tcsetattr with context pointer - int (*tcsetattr)(int fd, int optional_actions, const struct termios *p) tcsetattr without context pointer - int (*tcgetattr_p)(void *ctx, int fd, struct termios *p) tcgetattr with context pointer - int (*tcgetattr)(int fd, struct termios *p) tcgetattr without context pointer - int (*tcdrain_p)(void *ctx, int fd) tcdrain with context pointer - int (*tcdrain)(int fd) tcdrain without context pointer - int (*tcflush_p)(void *ctx, int fd, int select) tcflush with context pointer - int (*tcflush)(int fd, int select) tcflush without context pointer - int (*tcflow_p)(void *ctx, int fd, int action) tcflow with context pointer - int (*tcflow)(int fd, int action) tcflow without context pointer - pid_t (*tcgetsid_p)(void *ctx, int fd) tcgetsid with context pointer - pid_t (*tcgetsid)(int fd) tcgetsid without context pointer - int (*tcsendbreak_p)(void *ctx, int fd, int duration) tcsendbreak with context pointer - int (*tcsendbreak)(int fd, int duration) tcsendbreak without context pointer - esp_err_t (*start_select)(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, esp_vfs_select_sem_t sem, void **end_select_args) start_select is called for setting up synchronous I/O multiplexing of the desired file descriptors in the given VFS - int (*socket_select)(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout) socket select function for socket FDs with the functionality of POSIX select(); this should be set only for the socket VFS - void (*stop_socket_select)(void *sem) called by VFS to interrupt the socket_select call when select is activated from a non-socket VFS driver; set only for the socket driver - void (*stop_socket_select_isr)(void *sem, BaseType_t *woken) stop_socket_select which can be called from ISR; set only for the socket driver - void *(*get_socket_select_semaphore)(void) end_select is called to stop the I/O multiplexing and deinitialize the environment created by start_select for the given VFS - int flags Macros - MAX_FDS Maximum number of (global) file descriptors. - ESP_VFS_PATH_MAX Maximum length of path prefix (not including zero terminator) - ESP_VFS_FLAG_CONTEXT_PTR Flag which indicates that FS needs extra context pointer in syscalls. - ESP_VFS_FLAG_READONLY_FS Flag which indicates that FS is located on read-only partition. Type Definitions - typedef int esp_vfs_id_t Header File This header file can be included with: #include "esp_vfs_dev.h" This header file is a part of the API provided by the vfscomponent. To declare that your component depends on vfs, add the following to your CMakeLists.txt: REQUIRES vfs or PRIV_REQUIRES vfs Functions - void esp_vfs_dev_uart_register(void) add /dev/uart virtual filesystem driver This function is called from startup code to enable serial output - void esp_vfs_dev_uart_set_rx_line_endings(esp_line_endings_t mode) Set the line endings expected to be received on UART. This specifies the conversion between line endings received on UART and newlines (' ', LF) passed into stdin: ESP_LINE_ENDINGS_CRLF: convert CRLF to LF ESP_LINE_ENDINGS_CR: convert CR to LF ESP_LINE_ENDINGS_LF: no modification Note this function is not thread safe w.r.t. reading from UART - Parameters mode -- line endings expected on UART - - void esp_vfs_dev_uart_set_tx_line_endings(esp_line_endings_t mode) Set the line endings to sent to UART. This specifies the conversion between newlines (' ', LF) on stdout and line endings sent over UART: ESP_LINE_ENDINGS_CRLF: convert LF to CRLF ESP_LINE_ENDINGS_CR: convert LF to CR ESP_LINE_ENDINGS_LF: no modification Note this function is not thread safe w.r.t. writing to UART - Parameters mode -- line endings to send to UART - - int esp_vfs_dev_uart_port_set_rx_line_endings(int uart_num, esp_line_endings_t mode) Set the line endings expected to be received on specified UART. This specifies the conversion between line endings received on UART and newlines (' ', LF) passed into stdin: ESP_LINE_ENDINGS_CRLF: convert CRLF to LF ESP_LINE_ENDINGS_CR: convert CR to LF ESP_LINE_ENDINGS_LF: no modification Note this function is not thread safe w.r.t. reading from UART - Parameters uart_num -- the UART number mode -- line endings to send to UART - - Returns 0 if successed, or -1 when an error (specified by errno) have occurred. - - int esp_vfs_dev_uart_port_set_tx_line_endings(int uart_num, esp_line_endings_t mode) Set the line endings to sent to specified UART. This specifies the conversion between newlines (' ', LF) on stdout and line endings sent over UART: ESP_LINE_ENDINGS_CRLF: convert LF to CRLF ESP_LINE_ENDINGS_CR: convert LF to CR ESP_LINE_ENDINGS_LF: no modification Note this function is not thread safe w.r.t. writing to UART - Parameters uart_num -- the UART number mode -- line endings to send to UART - - Returns 0 if successed, or -1 when an error (specified by errno) have occurred. - - void esp_vfs_dev_uart_use_nonblocking(int uart_num) set VFS to use simple functions for reading and writing UART Read is non-blocking, write is busy waiting until TX FIFO has enough space. These functions are used by default. - Parameters uart_num -- UART peripheral number - void esp_vfs_dev_uart_use_driver(int uart_num) set VFS to use UART driver for reading and writing Note application must configure UART driver before calling these functions With these functions, read and write are blocking and interrupt-driven. - Parameters uart_num -- UART peripheral number - void esp_vfs_usb_serial_jtag_use_driver(void) set VFS to use USB-SERIAL-JTAG driver for reading and writing Note application must configure USB-SERIAL-JTAG driver before calling these functions With these functions, read and write are blocking and interrupt-driven. - void esp_vfs_usb_serial_jtag_use_nonblocking(void) set VFS to use simple functions for reading and writing UART Read is non-blocking, write is busy waiting until TX FIFO has enough space. These functions are used by default. Header File This header file can be included with: #include "esp_vfs_eventfd.h" This header file is a part of the API provided by the vfscomponent. To declare that your component depends on vfs, add the following to your CMakeLists.txt: REQUIRES vfs or PRIV_REQUIRES vfs Functions - esp_err_t esp_vfs_eventfd_register(const esp_vfs_eventfd_config_t *config) Registers the event vfs. - Returns ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are registered. - esp_err_t esp_vfs_eventfd_unregister(void) Unregisters the event vfs. - Returns ESP_OK if successful, ESP_ERR_INVALID_STATE if VFS for given prefix hasn't been registered - int eventfd(unsigned int initval, int flags) Structures Macros - EFD_SUPPORT_ISR - ESP_VFS_EVENTD_CONFIG_DEFAULT()
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/storage/vfs.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Page Not Found
null
espressif.com
2016-01-01
7c7a989a6f8437ed
null
null
Page Not Found Note We are sorry. The page you requested could not be found. This error occurs maybe because the current chip or version you choose does not support the feature you are looking for. If you want to provide feedback about this document, please let us know what exact document you want to access, so that we can better help you. Please use the menu on the left to navigate through documentation contents. Optionally type the phrase you are looking for in the search box above the menu and press enter.
Page Not Found Note We are sorry. The page you requested could not be found. This error occurs maybe because the current chip or version you choose does not support the feature you are looking for. If you want to provide feedback about this document, please let us know what exact document you want to access, so that we can better help you. Please use the menu on the left to navigate through documentation contents. Optionally type the phrase you are looking for in the search box above the menu and press enter.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/404.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Application Level Tracing
null
espressif.com
2016-01-01
b043ef4ee899f6d3
null
null
Application Level Tracing Overview ESP-IDF provides a useful feature for application behavior analysis called Application Level Tracing. The feature can be enabled in menuconfig and allows transfer of arbitrary data between the host and ESP32 via JTAG interface with minimal overhead on program execution. Developers can use this library to send application specific state of execution to the host, and receive commands or other types of information in the opposite direction at runtime. The main use cases of this library are: Collecting application specific data, see Application Specific Tracing. Lightweight logging to the host, see Logging to Host. System behaviour analysis, see System Behavior Analysis with SEGGER SystemView. API Reference Header File This header file can be included with: #include "esp_app_trace.h" This header file is a part of the API provided by the app_trace component. To declare that your component depends on app_trace , add the following to your CMakeLists.txt: REQUIRES app_trace or PRIV_REQUIRES app_trace Functions esp_err_t esp_apptrace_init(void) Initializes application tracing module. Note Should be called before any esp_apptrace_xxx call. Returns ESP_OK on success, otherwise see esp_err_t Returns ESP_OK on success, otherwise see esp_err_t void esp_apptrace_down_buffer_config(uint8_t *buf, uint32_t size) Configures down buffer. Note Needs to be called before attempting to receive any data using esp_apptrace_down_buffer_get and esp_apptrace_read. This function does not protect internal data by lock. Parameters buf -- Address of buffer to use for down channel (host to target) data. size -- Size of the buffer. buf -- Address of buffer to use for down channel (host to target) data. size -- Size of the buffer. buf -- Address of buffer to use for down channel (host to target) data. Parameters buf -- Address of buffer to use for down channel (host to target) data. size -- Size of the buffer. uint8_t *esp_apptrace_buffer_get(esp_apptrace_dest_t dest, uint32_t size, uint32_t tmo) Allocates buffer for trace data. Once the data in the buffer is ready to be sent, esp_apptrace_buffer_put must be called to indicate it. Parameters dest -- Indicates HW interface to send data. size -- Size of data to write to trace buffer. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to send data. size -- Size of data to write to trace buffer. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to send data. Returns non-NULL on success, otherwise NULL. Parameters dest -- Indicates HW interface to send data. size -- Size of data to write to trace buffer. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. Returns non-NULL on success, otherwise NULL. esp_err_t esp_apptrace_buffer_put(esp_apptrace_dest_t dest, uint8_t *ptr, uint32_t tmo) Indicates that the data in the buffer is ready to be sent. This function is a counterpart of and must be preceded by esp_apptrace_buffer_get. Parameters dest -- Indicates HW interface to send data. Should be identical to the same parameter in call to esp_apptrace_buffer_get. ptr -- Address of trace buffer to release. Should be the value returned by call to esp_apptrace_buffer_get. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to send data. Should be identical to the same parameter in call to esp_apptrace_buffer_get. ptr -- Address of trace buffer to release. Should be the value returned by call to esp_apptrace_buffer_get. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to send data. Should be identical to the same parameter in call to esp_apptrace_buffer_get. Returns ESP_OK on success, otherwise see esp_err_t Parameters dest -- Indicates HW interface to send data. Should be identical to the same parameter in call to esp_apptrace_buffer_get. ptr -- Address of trace buffer to release. Should be the value returned by call to esp_apptrace_buffer_get. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. Returns ESP_OK on success, otherwise see esp_err_t esp_err_t esp_apptrace_write(esp_apptrace_dest_t dest, const void *data, uint32_t size, uint32_t tmo) Writes data to trace buffer. Parameters dest -- Indicates HW interface to send data. data -- Address of data to write to trace buffer. size -- Size of data to write to trace buffer. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to send data. data -- Address of data to write to trace buffer. size -- Size of data to write to trace buffer. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to send data. Returns ESP_OK on success, otherwise see esp_err_t Parameters dest -- Indicates HW interface to send data. data -- Address of data to write to trace buffer. size -- Size of data to write to trace buffer. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. Returns ESP_OK on success, otherwise see esp_err_t int esp_apptrace_vprintf_to(esp_apptrace_dest_t dest, uint32_t tmo, const char *fmt, va_list ap) vprintf-like function to send log messages to host via specified HW interface. Parameters dest -- Indicates HW interface to send data. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. fmt -- Address of format string. ap -- List of arguments. dest -- Indicates HW interface to send data. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. fmt -- Address of format string. ap -- List of arguments. dest -- Indicates HW interface to send data. Returns Number of bytes written. Parameters dest -- Indicates HW interface to send data. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. fmt -- Address of format string. ap -- List of arguments. Returns Number of bytes written. int esp_apptrace_vprintf(const char *fmt, va_list ap) vprintf-like function to send log messages to host. Parameters fmt -- Address of format string. ap -- List of arguments. fmt -- Address of format string. ap -- List of arguments. fmt -- Address of format string. Returns Number of bytes written. Parameters fmt -- Address of format string. ap -- List of arguments. Returns Number of bytes written. esp_err_t esp_apptrace_flush(esp_apptrace_dest_t dest, uint32_t tmo) Flushes remaining data in trace buffer to host. Parameters dest -- Indicates HW interface to flush data on. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to flush data on. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to flush data on. Returns ESP_OK on success, otherwise see esp_err_t Parameters dest -- Indicates HW interface to flush data on. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. Returns ESP_OK on success, otherwise see esp_err_t esp_err_t esp_apptrace_flush_nolock(esp_apptrace_dest_t dest, uint32_t min_sz, uint32_t tmo) Flushes remaining data in trace buffer to host without locking internal data. This is a special version of esp_apptrace_flush which should be called from panic handler. Parameters dest -- Indicates HW interface to flush data on. min_sz -- Threshold for flushing data. If current filling level is above this value, data will be flushed. TRAX destinations only. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to flush data on. min_sz -- Threshold for flushing data. If current filling level is above this value, data will be flushed. TRAX destinations only. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to flush data on. Returns ESP_OK on success, otherwise see esp_err_t Parameters dest -- Indicates HW interface to flush data on. min_sz -- Threshold for flushing data. If current filling level is above this value, data will be flushed. TRAX destinations only. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. Returns ESP_OK on success, otherwise see esp_err_t esp_err_t esp_apptrace_read(esp_apptrace_dest_t dest, void *data, uint32_t *size, uint32_t tmo) Reads host data from trace buffer. Parameters dest -- Indicates HW interface to read the data on. data -- Address of buffer to put data from trace buffer. size -- Pointer to store size of read data. Before call to this function pointed memory must hold requested size of data tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to read the data on. data -- Address of buffer to put data from trace buffer. size -- Pointer to store size of read data. Before call to this function pointed memory must hold requested size of data tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to read the data on. Returns ESP_OK on success, otherwise see esp_err_t Parameters dest -- Indicates HW interface to read the data on. data -- Address of buffer to put data from trace buffer. size -- Pointer to store size of read data. Before call to this function pointed memory must hold requested size of data tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. Returns ESP_OK on success, otherwise see esp_err_t uint8_t *esp_apptrace_down_buffer_get(esp_apptrace_dest_t dest, uint32_t *size, uint32_t tmo) Retrieves incoming data buffer if any. Once data in the buffer is processed, esp_apptrace_down_buffer_put must be called to indicate it. Parameters dest -- Indicates HW interface to receive data. size -- Address to store size of available data in down buffer. Must be initialized with requested value. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to receive data. size -- Address to store size of available data in down buffer. Must be initialized with requested value. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to receive data. Returns non-NULL on success, otherwise NULL. Parameters dest -- Indicates HW interface to receive data. size -- Address to store size of available data in down buffer. Must be initialized with requested value. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. Returns non-NULL on success, otherwise NULL. esp_err_t esp_apptrace_down_buffer_put(esp_apptrace_dest_t dest, uint8_t *ptr, uint32_t tmo) Indicates that the data in the down buffer is processed. This function is a counterpart of and must be preceded by esp_apptrace_down_buffer_get. Parameters dest -- Indicates HW interface to receive data. Should be identical to the same parameter in call to esp_apptrace_down_buffer_get. ptr -- Address of trace buffer to release. Should be the value returned by call to esp_apptrace_down_buffer_get. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to receive data. Should be identical to the same parameter in call to esp_apptrace_down_buffer_get. ptr -- Address of trace buffer to release. Should be the value returned by call to esp_apptrace_down_buffer_get. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. dest -- Indicates HW interface to receive data. Should be identical to the same parameter in call to esp_apptrace_down_buffer_get. Returns ESP_OK on success, otherwise see esp_err_t Parameters dest -- Indicates HW interface to receive data. Should be identical to the same parameter in call to esp_apptrace_down_buffer_get. ptr -- Address of trace buffer to release. Should be the value returned by call to esp_apptrace_down_buffer_get. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. Returns ESP_OK on success, otherwise see esp_err_t bool esp_apptrace_host_is_connected(esp_apptrace_dest_t dest) Checks whether host is connected. Parameters dest -- Indicates HW interface to use. Returns true if host is connected, otherwise false Parameters dest -- Indicates HW interface to use. Returns true if host is connected, otherwise false void *esp_apptrace_fopen(esp_apptrace_dest_t dest, const char *path, const char *mode) Opens file on host. This function has the same semantic as 'fopen' except for the first argument. Parameters dest -- Indicates HW interface to use. path -- Path to file. mode -- Mode string. See fopen for details. dest -- Indicates HW interface to use. path -- Path to file. mode -- Mode string. See fopen for details. dest -- Indicates HW interface to use. Returns non zero file handle on success, otherwise 0 Parameters dest -- Indicates HW interface to use. path -- Path to file. mode -- Mode string. See fopen for details. Returns non zero file handle on success, otherwise 0 int esp_apptrace_fclose(esp_apptrace_dest_t dest, void *stream) Closes file on host. This function has the same semantic as 'fclose' except for the first argument. Parameters dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. dest -- Indicates HW interface to use. Returns Zero on success, otherwise non-zero. See fclose for details. Parameters dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. Returns Zero on success, otherwise non-zero. See fclose for details. size_t esp_apptrace_fwrite(esp_apptrace_dest_t dest, const void *ptr, size_t size, size_t nmemb, void *stream) Writes to file on host. This function has the same semantic as 'fwrite' except for the first argument. Parameters dest -- Indicates HW interface to use. ptr -- Address of data to write. size -- Size of an item. nmemb -- Number of items to write. stream -- File handle returned by esp_apptrace_fopen. dest -- Indicates HW interface to use. ptr -- Address of data to write. size -- Size of an item. nmemb -- Number of items to write. stream -- File handle returned by esp_apptrace_fopen. dest -- Indicates HW interface to use. Returns Number of written items. See fwrite for details. Parameters dest -- Indicates HW interface to use. ptr -- Address of data to write. size -- Size of an item. nmemb -- Number of items to write. stream -- File handle returned by esp_apptrace_fopen. Returns Number of written items. See fwrite for details. size_t esp_apptrace_fread(esp_apptrace_dest_t dest, void *ptr, size_t size, size_t nmemb, void *stream) Read file on host. This function has the same semantic as 'fread' except for the first argument. Parameters dest -- Indicates HW interface to use. ptr -- Address to store read data. size -- Size of an item. nmemb -- Number of items to read. stream -- File handle returned by esp_apptrace_fopen. dest -- Indicates HW interface to use. ptr -- Address to store read data. size -- Size of an item. nmemb -- Number of items to read. stream -- File handle returned by esp_apptrace_fopen. dest -- Indicates HW interface to use. Returns Number of read items. See fread for details. Parameters dest -- Indicates HW interface to use. ptr -- Address to store read data. size -- Size of an item. nmemb -- Number of items to read. stream -- File handle returned by esp_apptrace_fopen. Returns Number of read items. See fread for details. int esp_apptrace_fseek(esp_apptrace_dest_t dest, void *stream, long offset, int whence) Set position indicator in file on host. This function has the same semantic as 'fseek' except for the first argument. Parameters dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. offset -- Offset. See fseek for details. whence -- Position in file. See fseek for details. dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. offset -- Offset. See fseek for details. whence -- Position in file. See fseek for details. dest -- Indicates HW interface to use. Returns Zero on success, otherwise non-zero. See fseek for details. Parameters dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. offset -- Offset. See fseek for details. whence -- Position in file. See fseek for details. Returns Zero on success, otherwise non-zero. See fseek for details. int esp_apptrace_ftell(esp_apptrace_dest_t dest, void *stream) Get current position indicator for file on host. This function has the same semantic as 'ftell' except for the first argument. Parameters dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. dest -- Indicates HW interface to use. Returns Current position in file. See ftell for details. Parameters dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. Returns Current position in file. See ftell for details. int esp_apptrace_fstop(esp_apptrace_dest_t dest) Indicates to the host that all file operations are complete. This function should be called after all file operations are finished and indicate to the host that it can perform cleanup operations (close open files etc.). Parameters dest -- Indicates HW interface to use. Returns ESP_OK on success, otherwise see esp_err_t Parameters dest -- Indicates HW interface to use. Returns ESP_OK on success, otherwise see esp_err_t int esp_apptrace_feof(esp_apptrace_dest_t dest, void *stream) Test end-of-file indicator on a stream. This function has the same semantic as 'feof' except for the first argument. Parameters dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. dest -- Indicates HW interface to use. Returns Non-Zero if end-of-file indicator is set for stream. See feof for details. Parameters dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. Returns Non-Zero if end-of-file indicator is set for stream. See feof for details. void esp_gcov_dump(void) Triggers gcov info dump. This function waits for the host to connect to target before dumping data. Enumerations enum esp_apptrace_dest_t Application trace data destinations bits. Values: enumerator ESP_APPTRACE_DEST_JTAG JTAG destination. enumerator ESP_APPTRACE_DEST_JTAG JTAG destination. enumerator ESP_APPTRACE_DEST_TRAX xxx_TRAX name is obsolete, use more common xxx_JTAG enumerator ESP_APPTRACE_DEST_TRAX xxx_TRAX name is obsolete, use more common xxx_JTAG enumerator ESP_APPTRACE_DEST_UART UART destination. enumerator ESP_APPTRACE_DEST_UART UART destination. enumerator ESP_APPTRACE_DEST_MAX enumerator ESP_APPTRACE_DEST_MAX enumerator ESP_APPTRACE_DEST_NUM enumerator ESP_APPTRACE_DEST_NUM enumerator ESP_APPTRACE_DEST_JTAG Header File This header file can be included with: #include "esp_sysview_trace.h" This header file is a part of the API provided by the app_trace component. To declare that your component depends on app_trace , add the following to your CMakeLists.txt: REQUIRES app_trace or PRIV_REQUIRES app_trace Functions static inline esp_err_t esp_sysview_flush(uint32_t tmo) Flushes remaining data in SystemView trace buffer to host. Parameters tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly. Returns ESP_OK. Parameters tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly. Returns ESP_OK. int esp_sysview_vprintf(const char *format, va_list args) vprintf-like function to sent log messages to the host. Parameters format -- Address of format string. args -- List of arguments. format -- Address of format string. args -- List of arguments. format -- Address of format string. Returns Number of bytes written. Parameters format -- Address of format string. args -- List of arguments. Returns Number of bytes written. esp_err_t esp_sysview_heap_trace_start(uint32_t tmo) Starts SystemView heap tracing. Parameters tmo -- Timeout (in us) to wait for the host to be connected. Use -1 to wait forever. Returns ESP_OK on success, ESP_ERR_TIMEOUT if operation has been timed out. Parameters tmo -- Timeout (in us) to wait for the host to be connected. Use -1 to wait forever. Returns ESP_OK on success, ESP_ERR_TIMEOUT if operation has been timed out. void esp_sysview_heap_trace_alloc(void *addr, uint32_t size, const void *callers) Sends heap allocation event to the host. Parameters addr -- Address of allocated block. size -- Size of allocated block. callers -- Pointer to array with callstack addresses. Array size must be CONFIG_HEAP_TRACING_STACK_DEPTH. addr -- Address of allocated block. size -- Size of allocated block. callers -- Pointer to array with callstack addresses. Array size must be CONFIG_HEAP_TRACING_STACK_DEPTH. addr -- Address of allocated block. Parameters addr -- Address of allocated block. size -- Size of allocated block. callers -- Pointer to array with callstack addresses. Array size must be CONFIG_HEAP_TRACING_STACK_DEPTH. void esp_sysview_heap_trace_free(void *addr, const void *callers) Sends heap de-allocation event to the host. Parameters addr -- Address of de-allocated block. callers -- Pointer to array with callstack addresses. Array size must be CONFIG_HEAP_TRACING_STACK_DEPTH. addr -- Address of de-allocated block. callers -- Pointer to array with callstack addresses. Array size must be CONFIG_HEAP_TRACING_STACK_DEPTH. addr -- Address of de-allocated block. Parameters addr -- Address of de-allocated block. callers -- Pointer to array with callstack addresses. Array size must be CONFIG_HEAP_TRACING_STACK_DEPTH.
Application Level Tracing Overview ESP-IDF provides a useful feature for application behavior analysis called Application Level Tracing. The feature can be enabled in menuconfig and allows transfer of arbitrary data between the host and ESP32 via JTAG interface with minimal overhead on program execution. Developers can use this library to send application specific state of execution to the host, and receive commands or other types of information in the opposite direction at runtime. The main use cases of this library are: Collecting application specific data, see Application Specific Tracing. Lightweight logging to the host, see Logging to Host. System behaviour analysis, see System Behavior Analysis with SEGGER SystemView. API Reference Header File This header file can be included with: #include "esp_app_trace.h" This header file is a part of the API provided by the app_tracecomponent. To declare that your component depends on app_trace, add the following to your CMakeLists.txt: REQUIRES app_trace or PRIV_REQUIRES app_trace Functions - esp_err_t esp_apptrace_init(void) Initializes application tracing module. Note Should be called before any esp_apptrace_xxx call. - Returns ESP_OK on success, otherwise see esp_err_t - void esp_apptrace_down_buffer_config(uint8_t *buf, uint32_t size) Configures down buffer. Note Needs to be called before attempting to receive any data using esp_apptrace_down_buffer_get and esp_apptrace_read. This function does not protect internal data by lock. - Parameters buf -- Address of buffer to use for down channel (host to target) data. size -- Size of the buffer. - - uint8_t *esp_apptrace_buffer_get(esp_apptrace_dest_t dest, uint32_t size, uint32_t tmo) Allocates buffer for trace data. Once the data in the buffer is ready to be sent, esp_apptrace_buffer_put must be called to indicate it. - Parameters dest -- Indicates HW interface to send data. size -- Size of data to write to trace buffer. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. - - Returns non-NULL on success, otherwise NULL. - esp_err_t esp_apptrace_buffer_put(esp_apptrace_dest_t dest, uint8_t *ptr, uint32_t tmo) Indicates that the data in the buffer is ready to be sent. This function is a counterpart of and must be preceded by esp_apptrace_buffer_get. - Parameters dest -- Indicates HW interface to send data. Should be identical to the same parameter in call to esp_apptrace_buffer_get. ptr -- Address of trace buffer to release. Should be the value returned by call to esp_apptrace_buffer_get. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. - - Returns ESP_OK on success, otherwise see esp_err_t - esp_err_t esp_apptrace_write(esp_apptrace_dest_t dest, const void *data, uint32_t size, uint32_t tmo) Writes data to trace buffer. - Parameters dest -- Indicates HW interface to send data. data -- Address of data to write to trace buffer. size -- Size of data to write to trace buffer. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. - - Returns ESP_OK on success, otherwise see esp_err_t - int esp_apptrace_vprintf_to(esp_apptrace_dest_t dest, uint32_t tmo, const char *fmt, va_list ap) vprintf-like function to send log messages to host via specified HW interface. - Parameters dest -- Indicates HW interface to send data. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. fmt -- Address of format string. ap -- List of arguments. - - Returns Number of bytes written. - int esp_apptrace_vprintf(const char *fmt, va_list ap) vprintf-like function to send log messages to host. - Parameters fmt -- Address of format string. ap -- List of arguments. - - Returns Number of bytes written. - esp_err_t esp_apptrace_flush(esp_apptrace_dest_t dest, uint32_t tmo) Flushes remaining data in trace buffer to host. - Parameters dest -- Indicates HW interface to flush data on. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. - - Returns ESP_OK on success, otherwise see esp_err_t - esp_err_t esp_apptrace_flush_nolock(esp_apptrace_dest_t dest, uint32_t min_sz, uint32_t tmo) Flushes remaining data in trace buffer to host without locking internal data. This is a special version of esp_apptrace_flush which should be called from panic handler. - Parameters dest -- Indicates HW interface to flush data on. min_sz -- Threshold for flushing data. If current filling level is above this value, data will be flushed. TRAX destinations only. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. - - Returns ESP_OK on success, otherwise see esp_err_t - esp_err_t esp_apptrace_read(esp_apptrace_dest_t dest, void *data, uint32_t *size, uint32_t tmo) Reads host data from trace buffer. - Parameters dest -- Indicates HW interface to read the data on. data -- Address of buffer to put data from trace buffer. size -- Pointer to store size of read data. Before call to this function pointed memory must hold requested size of data tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. - - Returns ESP_OK on success, otherwise see esp_err_t - uint8_t *esp_apptrace_down_buffer_get(esp_apptrace_dest_t dest, uint32_t *size, uint32_t tmo) Retrieves incoming data buffer if any. Once data in the buffer is processed, esp_apptrace_down_buffer_put must be called to indicate it. - Parameters dest -- Indicates HW interface to receive data. size -- Address to store size of available data in down buffer. Must be initialized with requested value. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. - - Returns non-NULL on success, otherwise NULL. - esp_err_t esp_apptrace_down_buffer_put(esp_apptrace_dest_t dest, uint8_t *ptr, uint32_t tmo) Indicates that the data in the down buffer is processed. This function is a counterpart of and must be preceded by esp_apptrace_down_buffer_get. - Parameters dest -- Indicates HW interface to receive data. Should be identical to the same parameter in call to esp_apptrace_down_buffer_get. ptr -- Address of trace buffer to release. Should be the value returned by call to esp_apptrace_down_buffer_get. tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. - - Returns ESP_OK on success, otherwise see esp_err_t - bool esp_apptrace_host_is_connected(esp_apptrace_dest_t dest) Checks whether host is connected. - Parameters dest -- Indicates HW interface to use. - Returns true if host is connected, otherwise false - void *esp_apptrace_fopen(esp_apptrace_dest_t dest, const char *path, const char *mode) Opens file on host. This function has the same semantic as 'fopen' except for the first argument. - Parameters dest -- Indicates HW interface to use. path -- Path to file. mode -- Mode string. See fopen for details. - - Returns non zero file handle on success, otherwise 0 - int esp_apptrace_fclose(esp_apptrace_dest_t dest, void *stream) Closes file on host. This function has the same semantic as 'fclose' except for the first argument. - Parameters dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. - - Returns Zero on success, otherwise non-zero. See fclose for details. - size_t esp_apptrace_fwrite(esp_apptrace_dest_t dest, const void *ptr, size_t size, size_t nmemb, void *stream) Writes to file on host. This function has the same semantic as 'fwrite' except for the first argument. - Parameters dest -- Indicates HW interface to use. ptr -- Address of data to write. size -- Size of an item. nmemb -- Number of items to write. stream -- File handle returned by esp_apptrace_fopen. - - Returns Number of written items. See fwrite for details. - size_t esp_apptrace_fread(esp_apptrace_dest_t dest, void *ptr, size_t size, size_t nmemb, void *stream) Read file on host. This function has the same semantic as 'fread' except for the first argument. - Parameters dest -- Indicates HW interface to use. ptr -- Address to store read data. size -- Size of an item. nmemb -- Number of items to read. stream -- File handle returned by esp_apptrace_fopen. - - Returns Number of read items. See fread for details. - int esp_apptrace_fseek(esp_apptrace_dest_t dest, void *stream, long offset, int whence) Set position indicator in file on host. This function has the same semantic as 'fseek' except for the first argument. - Parameters dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. offset -- Offset. See fseek for details. whence -- Position in file. See fseek for details. - - Returns Zero on success, otherwise non-zero. See fseek for details. - int esp_apptrace_ftell(esp_apptrace_dest_t dest, void *stream) Get current position indicator for file on host. This function has the same semantic as 'ftell' except for the first argument. - Parameters dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. - - Returns Current position in file. See ftell for details. - int esp_apptrace_fstop(esp_apptrace_dest_t dest) Indicates to the host that all file operations are complete. This function should be called after all file operations are finished and indicate to the host that it can perform cleanup operations (close open files etc.). - Parameters dest -- Indicates HW interface to use. - Returns ESP_OK on success, otherwise see esp_err_t - int esp_apptrace_feof(esp_apptrace_dest_t dest, void *stream) Test end-of-file indicator on a stream. This function has the same semantic as 'feof' except for the first argument. - Parameters dest -- Indicates HW interface to use. stream -- File handle returned by esp_apptrace_fopen. - - Returns Non-Zero if end-of-file indicator is set for stream. See feof for details. - void esp_gcov_dump(void) Triggers gcov info dump. This function waits for the host to connect to target before dumping data. Enumerations - enum esp_apptrace_dest_t Application trace data destinations bits. Values: - enumerator ESP_APPTRACE_DEST_JTAG JTAG destination. - enumerator ESP_APPTRACE_DEST_TRAX xxx_TRAX name is obsolete, use more common xxx_JTAG - enumerator ESP_APPTRACE_DEST_UART UART destination. - enumerator ESP_APPTRACE_DEST_MAX - enumerator ESP_APPTRACE_DEST_NUM - enumerator ESP_APPTRACE_DEST_JTAG Header File This header file can be included with: #include "esp_sysview_trace.h" This header file is a part of the API provided by the app_tracecomponent. To declare that your component depends on app_trace, add the following to your CMakeLists.txt: REQUIRES app_trace or PRIV_REQUIRES app_trace Functions - static inline esp_err_t esp_sysview_flush(uint32_t tmo) Flushes remaining data in SystemView trace buffer to host. - Parameters tmo -- Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly. - Returns ESP_OK. - int esp_sysview_vprintf(const char *format, va_list args) vprintf-like function to sent log messages to the host. - Parameters format -- Address of format string. args -- List of arguments. - - Returns Number of bytes written. - esp_err_t esp_sysview_heap_trace_start(uint32_t tmo) Starts SystemView heap tracing. - Parameters tmo -- Timeout (in us) to wait for the host to be connected. Use -1 to wait forever. - Returns ESP_OK on success, ESP_ERR_TIMEOUT if operation has been timed out. - void esp_sysview_heap_trace_alloc(void *addr, uint32_t size, const void *callers) Sends heap allocation event to the host. - Parameters addr -- Address of allocated block. size -- Size of allocated block. callers -- Pointer to array with callstack addresses. Array size must be CONFIG_HEAP_TRACING_STACK_DEPTH. - - void esp_sysview_heap_trace_free(void *addr, const void *callers) Sends heap de-allocation event to the host. - Parameters addr -- Address of de-allocated block. callers -- Pointer to array with callstack addresses. Array size must be CONFIG_HEAP_TRACING_STACK_DEPTH. -
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/app_trace.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Call Function with External Stack
null
espressif.com
2016-01-01
5a876032ef12b215
null
null
Call Function with External Stack Overview A given function can be executed with a user-allocated stack space which is independent of current task stack. This mechanism can be used to save stack space wasted by tasks which call a common function with intensive stack usage such as printf . The given function can be called inside the shared stack space, which is a callback function deferred by calling esp_execute_shared_stack_function() , passing that function as a parameter. Usage esp_execute_shared_stack_function() takes four arguments: a mutex object allocated by the caller, which is used to protect if the same function shares its allocated stack a pointer to the top of stack used for that function the size of stack in bytes a pointer to the shared stack function The user-defined function is deferred as a callback and can be called using the user-allocated space without taking space from current task stack. The usage may look like the code below: void external_stack_function(void) { printf("Executing this printf from external stack! \n"); } //Let us suppose we want to call printf using a separated stack space //allowing the app to reduce its stack size. void app_main() { //Allocate a stack buffer, from heap or as a static form: StackType_t *shared_stack = malloc(8192 * sizeof(StackType_t)); assert(shared_stack != NULL); //Allocate a mutex to protect its usage: SemaphoreHandle_t printf_lock = xSemaphoreCreateMutex(); assert(printf_lock != NULL); //Call the desired function using the macro helper: esp_execute_shared_stack_function(printf_lock, shared_stack, 8192, external_stack_function); vSemaphoreDelete(printf_lock); free(shared_stack); } API Reference Header File This header file can be included with: #include "esp_expression_with_stack.h" Functions Calls user defined shared stack space function. Note if either lock, stack or stack size is invalid, the expression will be called using the current stack. Parameters lock -- Mutex object to protect in case of shared stack stack -- Pointer to user alocated stack stack_size -- Size of current stack in bytes function -- pointer to the shared stack function to be executed lock -- Mutex object to protect in case of shared stack stack -- Pointer to user alocated stack stack_size -- Size of current stack in bytes function -- pointer to the shared stack function to be executed lock -- Mutex object to protect in case of shared stack Parameters lock -- Mutex object to protect in case of shared stack stack -- Pointer to user alocated stack stack_size -- Size of current stack in bytes function -- pointer to the shared stack function to be executed Macros ESP_EXECUTE_EXPRESSION_WITH_STACK(lock, stack, stack_size, expression)
Call Function with External Stack Overview A given function can be executed with a user-allocated stack space which is independent of current task stack. This mechanism can be used to save stack space wasted by tasks which call a common function with intensive stack usage such as printf. The given function can be called inside the shared stack space, which is a callback function deferred by calling esp_execute_shared_stack_function(), passing that function as a parameter. Usage esp_execute_shared_stack_function() takes four arguments: a mutex object allocated by the caller, which is used to protect if the same function shares its allocated stack a pointer to the top of stack used for that function the size of stack in bytes a pointer to the shared stack function The user-defined function is deferred as a callback and can be called using the user-allocated space without taking space from current task stack. The usage may look like the code below: void external_stack_function(void) { printf("Executing this printf from external stack! \n"); } //Let us suppose we want to call printf using a separated stack space //allowing the app to reduce its stack size. void app_main() { //Allocate a stack buffer, from heap or as a static form: StackType_t *shared_stack = malloc(8192 * sizeof(StackType_t)); assert(shared_stack != NULL); //Allocate a mutex to protect its usage: SemaphoreHandle_t printf_lock = xSemaphoreCreateMutex(); assert(printf_lock != NULL); //Call the desired function using the macro helper: esp_execute_shared_stack_function(printf_lock, shared_stack, 8192, external_stack_function); vSemaphoreDelete(printf_lock); free(shared_stack); } API Reference Header File This header file can be included with: #include "esp_expression_with_stack.h" Functions Calls user defined shared stack space function. Note if either lock, stack or stack size is invalid, the expression will be called using the current stack. - Parameters lock -- Mutex object to protect in case of shared stack stack -- Pointer to user alocated stack stack_size -- Size of current stack in bytes function -- pointer to the shared stack function to be executed - Macros - ESP_EXECUTE_EXPRESSION_WITH_STACK(lock, stack, stack_size, expression)
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/esp_function_with_shared_stack.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Chip Revision
null
espressif.com
2016-01-01
be07eaa4ad83a7dc
null
null
Chip Revision Overview ESP32 may have different revisions. These revisions mainly fix some issues, and sometimes also bring new features to the chip. Versioning Scheme describes the versioning of these chip revisions, and the APIs to read the versions at runtime. There are some considerations of compatibility among application, ESP-IDF version, and chip revisions: Applications may depend on some fixes/features provided by a chip revision. When using updated version of hardware, the hardware may be incompatible with earlier versions of ESP-IDF. Compatibility Checks of ESP-IDF describes how the application can specify its chip revision requirements, and the way ESP-IDF checks the compatibility. After that, there is troubleshooting information for this mechanism. Versioning Scheme A chip's revision number is typically expressed as vX.Y , where: X means a Major wafer version. If it is changed, it means that the current software version is not compatible with this released chip and the software must be updated to use this chip. Y means a Minor wafer version. If it is changed that means the current software version is compatible with the released chip, and there is no need to update the software. If a newly released chip does not contain breaking changes, the chip can run the same software as the previous chip. As such, the new chip's revision number will only increment the minor version while keeping the major version the same (e.g., v1.1 to v1.2 ). Conversely, if a newly released chip contains breaking changes, the chip cannot run the same software as the previous chip. As such, the new chip's revision number will increment the major version and set the minor version to 0 (e.g., v1.1 to v2.0 ). This versioning scheme was selected to indicate the derivation relationship of chip revisions, and clearly distinguish changes in chips between breaking changes and non-breaking changes. ESP-IDF is designed to execute seamlessly on future chip minor revisions with the same logic as the chip's nearest previous minor revision. Thus,users can directly port their compiled binaries to newer MINOR chip revisions without upgrading their ESP-IDF version and re-compile the whole project. When a binary is executed on a chip revision of unexpected MAJOR revision, the software is also able to report issues according to the MAJOR revision. The major and minor versioning scheme also allows hardware changes to be branchable. Note The current chip revision scheme using major and minor versions was introduced from ESP-IDF v5.0 onwards. Thus bootloaders built using earlier versions of ESP-IDF will still use the legacy chip revision scheme of wafer versions. EFuse Bits for Chip Revisions Chips have several eFuse version fields: Major wafer version ( WAFER_VERSION_MAJOR eFuse) Minor wafer version ( WAFER_VERSION_MINOR eFuse) Ignore maximum revision ( DISABLE_WAFER_VERSION_MAJOR eFuse). See Compatibility Checks of ESP-IDF on how this is used. Note The previous versioning logic was based on a single eFuse version field ( WAFER_VERSION ). This approach makes it impossible to mark chips as breaking or non-breaking changes, and the versioning logic becomes linear. Chip Revision APIs These APIs helps to get chip revision from eFuses: efuse_hal_chip_revision() . It returns revision in the major * 100 + minor format. efuse_hal_get_major_chip_version() . It returns Major revision. efuse_hal_get_minor_chip_version() . It returns Minor revision. The following Kconfig definitions (in major * 100 + minor format) that can help add the chip revision dependency to the code: CONFIG_ESP32_REV_MIN_FULL CONFIG_ESP_REV_MIN_FULL CONFIG_ESP32_REV_MAX_FULL CONFIG_ESP_REV_MAX_FULL Compatibility Checks of ESP-IDF When building an application that needs to support multiple revisions of a particular chip, the minimum and maximum chip revision numbers supported by the build are specified via Kconfig. The minimum chip revision can be configured via the CONFIG_ESP32_REV_MIN option. Specifying the minimum chip revision will limit the software to only run on a chip revisions that are high enough to support some features or bugfixes. The maximum chip revision cannot be configured and is automatically determined by the current ESP-IDF version being used. ESP-IDF will refuse to boot any chip revision exceeding the maximum chip revision. Given that it is impossible for a particular ESP-IDF version to foresee all future chip revisions, the maximum chip revision is usually set to maximum supported MAJOR version + 99 . The "Ignore Maximum Revision" eFuse can be set to bypass the maximum revision limitation. However, the software is not guaranteed to work if the maximum revision is ignored. Below is the information about troubleshooting when the chip revision fails the compatibility check. Then there are technical details of the checking and software behavior on earlier version of ESP-IDF. Troubleshooting If the 2nd stage bootloader is run on a chip revision smaller than minimum revision specified in the image (i.e., the application), a reboot occurs. The following message will be printed: Image requires chip rev >= v3.0, but chip is v1.0 To resolve this issue, Use a chip with the required minimum revision or higher. Lower the CONFIG_ESP32_REV_MIN value and rebuild the image so that it is compatible with the chip revision being used. If application does not match minimum and maximum chip revisions, a reboot occurs. The following message will be printed: Image requires chip rev <= v2.99, but chip is v3.0 To resolve this issue, update ESP-IDF to a newer version that supports the chip's revision ( CONFIG_ESP32_REV_MAX_FULL ). Alternatively, set the Ignore maximal revision bit in eFuse or use a chip revision that is compatible with the current version of ESP-IDF. Representing Revision Requirements of a Binary Image The 2nd stage bootloader and the application binary images contain the esp_image_header_t header, which stores information specifying the chip revisions that the image is permitted to run on. This header has 3 fields related to revisions: min_chip_rev - Minimum chip MAJOR revision required by image (but for ESP32-C3 it is MINOR revision). Its value is determined by CONFIG_ESP32_REV_MIN. min_chip_rev_full - Minimum chip MINOR revision required by image in format: major * 100 + minor . Its value is determined by CONFIG_ESP32_REV_MIN. max_chip_rev_full - Maximum chip revision required by image in format: major * 100 + minor . Its value is determined by CONFIG_ESP32_REV_MAX_FULL . It can not be changed by user. Only Espressif can change it when a new version will be supported in ESP-IDF. Maximum And Minimum Revision Restrictions The order for checking the minimum and maximum revisions during application boot up is as follows: The 1st stage bootloader (ROM bootloader) does not check minimum and maximum revision fields from esp_image_header_t before running the 2nd stage bootloader. The initialization phase of the 2nd stage bootloader checks that the 2nd stage bootloader itself can be launched on the chip of this revision. It extracts the minimum revision from the header of the bootloader image and checks against the chip revision from eFuses. If the chip revision is less than the minimum revision, the bootloader refuses to boot up and aborts. The maximum revision is not checked at this phase. Then the 2nd stage bootloader checks the revision requirements of the application. It extracts the minimum and maximum revisions from the header of the application image and checks against the chip revision from eFuses. If the chip revision is less than the minimum revision or higher than the maximum revision, the bootloader refuses to boot up and aborts. However, if the Ignore maximum revision bit is set, the maximum revision constraint can be ignored. The ignore bit is set by the customer themselves when there is confirmation that the software is able to work with this chip revision. Furthermore, at the OTA update stage, the running application checks if the new software matches the chip revision. It extracts the minimum and maximum revisions from the header of the new application image and checks against the chip revision from eFuses. It checks for revision matching in the same way that the bootloader does, so that the chip revision is between the min and max revisions (logic of ignoring max revision also applies). Backward Compatibility with Bootloaders Built by Older ESP-IDF Versions The old bootloaders (ESP-IDF < v5.0) do not know about Major and Minor wafer version eFuses. They use one single eFuse for this - wafer version. The old bootloaders did not read the minor wafer version eFuse, and the major version can be only lower than or equal to v3. This means that the old bootloader can detect correctly only chip version in range v0.0 to v3.0 , where the minor version is always set to 0 . Please check the chip version using esptool chip_id command. References API Reference Header File This header file can be included with: #include "hal/efuse_hal.h" Functions void efuse_hal_get_mac(uint8_t *mac) get factory mac address uint32_t efuse_hal_chip_revision(void) Returns chip version. Returns Chip version in format: Major * 100 + Minor Returns Chip version in format: Major * 100 + Minor uint32_t efuse_hal_blk_version(void) Return block version. Returns Block version in format: Major * 100 + Minor Returns Block version in format: Major * 100 + Minor bool efuse_hal_flash_encryption_enabled(void) Is flash encryption currently enabled in hardware? Flash encryption is enabled if the FLASH_CRYPT_CNT efuse has an odd number of bits set. Returns true if flash encryption is enabled. Returns true if flash encryption is enabled. bool efuse_hal_get_disable_wafer_version_major(void) Returns the status of whether the bootloader (and OTA) will check the maximum chip version or not. Returns true - Skip the maximum chip version check. Returns true - Skip the maximum chip version check. uint32_t efuse_hal_get_major_chip_version(void) Returns major chip version. uint32_t efuse_hal_get_minor_chip_version(void) Returns minor chip version.
Chip Revision Overview ESP32 may have different revisions. These revisions mainly fix some issues, and sometimes also bring new features to the chip. Versioning Scheme describes the versioning of these chip revisions, and the APIs to read the versions at runtime. There are some considerations of compatibility among application, ESP-IDF version, and chip revisions: Applications may depend on some fixes/features provided by a chip revision. When using updated version of hardware, the hardware may be incompatible with earlier versions of ESP-IDF. Compatibility Checks of ESP-IDF describes how the application can specify its chip revision requirements, and the way ESP-IDF checks the compatibility. After that, there is troubleshooting information for this mechanism. Versioning Scheme A chip's revision number is typically expressed as vX.Y, where: Xmeans a Major wafer version. If it is changed, it means that the current software version is not compatible with this released chip and the software must be updated to use this chip. Ymeans a Minor wafer version. If it is changed that means the current software version is compatible with the released chip, and there is no need to update the software. If a newly released chip does not contain breaking changes, the chip can run the same software as the previous chip. As such, the new chip's revision number will only increment the minor version while keeping the major version the same (e.g., v1.1 to v1.2). Conversely, if a newly released chip contains breaking changes, the chip cannot run the same software as the previous chip. As such, the new chip's revision number will increment the major version and set the minor version to 0 (e.g., v1.1 to v2.0). This versioning scheme was selected to indicate the derivation relationship of chip revisions, and clearly distinguish changes in chips between breaking changes and non-breaking changes. ESP-IDF is designed to execute seamlessly on future chip minor revisions with the same logic as the chip's nearest previous minor revision. Thus,users can directly port their compiled binaries to newer MINOR chip revisions without upgrading their ESP-IDF version and re-compile the whole project. When a binary is executed on a chip revision of unexpected MAJOR revision, the software is also able to report issues according to the MAJOR revision. The major and minor versioning scheme also allows hardware changes to be branchable. Note The current chip revision scheme using major and minor versions was introduced from ESP-IDF v5.0 onwards. Thus bootloaders built using earlier versions of ESP-IDF will still use the legacy chip revision scheme of wafer versions. EFuse Bits for Chip Revisions Chips have several eFuse version fields: Major wafer version ( WAFER_VERSION_MAJOReFuse) Minor wafer version ( WAFER_VERSION_MINOReFuse) Ignore maximum revision ( DISABLE_WAFER_VERSION_MAJOReFuse). See Compatibility Checks of ESP-IDF on how this is used. Note The previous versioning logic was based on a single eFuse version field ( WAFER_VERSION). This approach makes it impossible to mark chips as breaking or non-breaking changes, and the versioning logic becomes linear. Chip Revision APIs These APIs helps to get chip revision from eFuses: efuse_hal_chip_revision(). It returns revision in the major * 100 + minorformat. efuse_hal_get_major_chip_version(). It returns Major revision. efuse_hal_get_minor_chip_version(). It returns Minor revision. The following Kconfig definitions (in major * 100 + minor format) that can help add the chip revision dependency to the code: CONFIG_ESP32_REV_MIN_FULL CONFIG_ESP_REV_MIN_FULL CONFIG_ESP32_REV_MAX_FULL CONFIG_ESP_REV_MAX_FULL Compatibility Checks of ESP-IDF When building an application that needs to support multiple revisions of a particular chip, the minimum and maximum chip revision numbers supported by the build are specified via Kconfig. The minimum chip revision can be configured via the CONFIG_ESP32_REV_MIN option. Specifying the minimum chip revision will limit the software to only run on a chip revisions that are high enough to support some features or bugfixes. The maximum chip revision cannot be configured and is automatically determined by the current ESP-IDF version being used. ESP-IDF will refuse to boot any chip revision exceeding the maximum chip revision. Given that it is impossible for a particular ESP-IDF version to foresee all future chip revisions, the maximum chip revision is usually set to maximum supported MAJOR version + 99. The "Ignore Maximum Revision" eFuse can be set to bypass the maximum revision limitation. However, the software is not guaranteed to work if the maximum revision is ignored. Below is the information about troubleshooting when the chip revision fails the compatibility check. Then there are technical details of the checking and software behavior on earlier version of ESP-IDF. Troubleshooting If the 2nd stage bootloader is run on a chip revision smaller than minimum revision specified in the image (i.e., the application), a reboot occurs. The following message will be printed: Image requires chip rev >= v3.0, but chip is v1.0 To resolve this issue, Use a chip with the required minimum revision or higher. Lower the CONFIG_ESP32_REV_MIN value and rebuild the image so that it is compatible with the chip revision being used. If application does not match minimum and maximum chip revisions, a reboot occurs. The following message will be printed: Image requires chip rev <= v2.99, but chip is v3.0 To resolve this issue, update ESP-IDF to a newer version that supports the chip's revision ( CONFIG_ESP32_REV_MAX_FULL). Alternatively, set the Ignore maximal revision bit in eFuse or use a chip revision that is compatible with the current version of ESP-IDF. Representing Revision Requirements of a Binary Image The 2nd stage bootloader and the application binary images contain the esp_image_header_t header, which stores information specifying the chip revisions that the image is permitted to run on. This header has 3 fields related to revisions: min_chip_rev- Minimum chip MAJOR revision required by image (but for ESP32-C3 it is MINOR revision). Its value is determined by CONFIG_ESP32_REV_MIN. min_chip_rev_full- Minimum chip MINOR revision required by image in format: major * 100 + minor. Its value is determined by CONFIG_ESP32_REV_MIN. max_chip_rev_full- Maximum chip revision required by image in format: major * 100 + minor. Its value is determined by CONFIG_ESP32_REV_MAX_FULL. It can not be changed by user. Only Espressif can change it when a new version will be supported in ESP-IDF. Maximum And Minimum Revision Restrictions The order for checking the minimum and maximum revisions during application boot up is as follows: The 1st stage bootloader (ROM bootloader) does not check minimum and maximum revision fields from esp_image_header_tbefore running the 2nd stage bootloader. The initialization phase of the 2nd stage bootloader checks that the 2nd stage bootloader itself can be launched on the chip of this revision. It extracts the minimum revision from the header of the bootloader image and checks against the chip revision from eFuses. If the chip revision is less than the minimum revision, the bootloader refuses to boot up and aborts. The maximum revision is not checked at this phase. Then the 2nd stage bootloader checks the revision requirements of the application. It extracts the minimum and maximum revisions from the header of the application image and checks against the chip revision from eFuses. If the chip revision is less than the minimum revision or higher than the maximum revision, the bootloader refuses to boot up and aborts. However, if the Ignore maximum revision bit is set, the maximum revision constraint can be ignored. The ignore bit is set by the customer themselves when there is confirmation that the software is able to work with this chip revision. Furthermore, at the OTA update stage, the running application checks if the new software matches the chip revision. It extracts the minimum and maximum revisions from the header of the new application image and checks against the chip revision from eFuses. It checks for revision matching in the same way that the bootloader does, so that the chip revision is between the min and max revisions (logic of ignoring max revision also applies). Backward Compatibility with Bootloaders Built by Older ESP-IDF Versions The old bootloaders (ESP-IDF < v5.0) do not know about Major and Minor wafer version eFuses. They use one single eFuse for this - wafer version. The old bootloaders did not read the minor wafer version eFuse, and the major version can be only lower than or equal to v3. This means that the old bootloader can detect correctly only chip version in range v0.0 to v3.0, where the minor version is always set to 0. Please check the chip version using esptool chip_id command. References API Reference Header File This header file can be included with: #include "hal/efuse_hal.h" Functions - void efuse_hal_get_mac(uint8_t *mac) get factory mac address - uint32_t efuse_hal_chip_revision(void) Returns chip version. - Returns Chip version in format: Major * 100 + Minor - uint32_t efuse_hal_blk_version(void) Return block version. - Returns Block version in format: Major * 100 + Minor - bool efuse_hal_flash_encryption_enabled(void) Is flash encryption currently enabled in hardware? Flash encryption is enabled if the FLASH_CRYPT_CNT efuse has an odd number of bits set. - Returns true if flash encryption is enabled. - bool efuse_hal_get_disable_wafer_version_major(void) Returns the status of whether the bootloader (and OTA) will check the maximum chip version or not. - Returns true - Skip the maximum chip version check. - uint32_t efuse_hal_get_major_chip_version(void) Returns major chip version. - uint32_t efuse_hal_get_minor_chip_version(void) Returns minor chip version.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/chip_revision.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Console
null
espressif.com
2016-01-01
d6d9dfd12217bbb9
null
null
Console ESP-IDF provides console component, which includes building blocks needed to develop an interactive console over serial port. This component includes the following features: Line editing, provided by linenoise library. This includes handling of backspace and arrow keys, scrolling through command history, command auto-completion, and argument hints. Splitting of command line into arguments. Argument parsing, provided by argtable3 library. This library includes APIs used for parsing GNU style command line arguments. Functions for registration and dispatching of commands. Functions to establish a basic REPL (Read-Evaluate-Print-Loop) environment. Note These features can be used together or independently. For example, it is possible to use line editing and command registration features, but use getopt or custom code for argument parsing, instead of argtable3. Likewise, it is possible to use simpler means of command input (such as fgets ) together with the rest of the means for command splitting and argument parsing. Note When using a console application on a chip that supports a hardware USB serial interface, we suggest to disable the secondary serial console output. The secondary output will be output-only and consequently does not make sense in an interactive application. Line Editing Line editing feature lets users compose commands by typing them, erasing symbols using the backspace key, navigating within the command using the left/right keys, navigating to previously typed commands using the up/down keys, and performing autocompletion using the tab key. Note This feature relies on ANSI escape sequence support in the terminal application. As such, serial monitors which display raw UART data can not be used together with the line editing library. If you see [6n or similar escape sequence when running system/console example instead of a command prompt (e.g., esp> ), it means that the serial monitor does not support escape sequences. Programs which are known to work are GNU screen, minicom, and esp-idf-monitor (which can be invoked using idf.py monitor from project directory). Here is an overview of functions provided by linenoise library. Configuration Linenoise library does not need explicit initialization. However, some configuration defaults may need to be changed before invoking the main line editing function. linenoiseClearScreen() Clear terminal screen using an escape sequence and position the cursor at the top left corner. linenoiseSetMultiLine() Switch between single line and multi line editing modes. In single line mode, if the length of the command exceeds the width of the terminal, the command text is scrolled within the line to show the end of the text. In this case the beginning of the text is hidden. Single line mode needs less data to be sent to refresh screen on each key press, so exhibits less glitching compared to the multi line mode. On the flip side, editing commands and copying command text from terminal in single line mode is harder. Default is single line mode. linenoiseAllowEmpty() Set whether linenoise library returns a zero-length string (if true ) or NULL (if false ) for empty lines. By default, zero-length strings are returned. linenoiseSetMaxLineLen() Set maximum length of the line for linenoise library. Default length is 4096 bytes. The default value can be updated to optimize RAM memory usage. Main Loop linenoise() In most cases, console applications have some form of read/eval loop. linenoise() is the single function which handles user's key presses and returns the completed line once the enter key is pressed. As such, it handles the read part of the loop. linenoiseFree() This function must be called to release the command line buffer obtained from linenoise() function. Hints and Completions linenoiseSetCompletionCallback() When the user presses the tab key, linenoise library invokes the completion callback. The callback should inspect the contents of the command typed so far and provide a list of possible completions using calls to linenoiseAddCompletion() function. linenoiseSetCompletionCallback() function should be called to register this completion callback, if completion feature is desired. console component provides a ready made function to provide completions for registered commands, esp_console_get_completion() (see below). linenoiseAddCompletion() Function to be called by completion callback to inform the library about possible completions of the currently typed command. linenoiseSetHintsCallback() Whenever user input changes, linenoise invokes the hints callback. This callback can inspect the command line typed so far, and provide a string with hints (which can include list of command arguments, for example). The library then displays the hint text on the same line where editing happens, possibly with a different color. linenoiseSetFreeHintsCallback() If the hint string returned by hints callback is dynamically allocated or needs to be otherwise recycled, the function which performs such cleanup should be registered via linenoiseSetFreeHintsCallback() . History linenoiseHistorySetMaxLen() This function sets the number of most recently typed commands to be kept in memory. Users can navigate the history using the up/down arrows keys. linenoiseHistoryAdd() Linenoise does not automatically add commands to history. Instead, applications need to call this function to add command strings to the history. linenoiseHistorySave() Function saves command history from RAM to a text file, for example on an SD card or on a filesystem in flash memory. linenoiseHistoryLoad() Counterpart to linenoiseHistorySave() , loads history from a file. linenoiseHistoryFree() Releases memory used to store command history. Call this function when done working with linenoise library. Splitting of Command Line into Arguments console component provides esp_console_split_argv() function to split command line string into arguments. The function returns the number of arguments found ( argc ) and fills an array of pointers which can be passed as argv argument to any function which accepts arguments in argc, argv format. The command line is split into arguments according to the following rules: Arguments are separated by spaces If spaces within arguments are required, they can be escaped using \ (backslash) character. Other escape sequences which are recognized are \\ (which produces literal backslash) and \" , which produces a double quote. Arguments can be quoted using double quotes. Quotes may appear only in the beginning and at the end of the argument. Quotes within the argument must be escaped as mentioned above. Quotes surrounding the argument are stripped by esp_console_split_argv function. Examples: abc def 1 20 .3 > [ abc , def , 1 , 20 , .3 ] abc "123 456" def > [ abc , 123 456 , def ] `a\ b\\c\" > [ a b\c" ] Argument Parsing For argument parsing, console component includes argtable3 library. Please see tutorial for an introduction to argtable3. Github repository also includes examples. Command Registration and Dispatching console component includes utility functions which handle registration of commands, matching commands typed by the user to registered ones, and calling these commands with the arguments given on the command line. Application first initializes command registration module using a call to esp_console_init() , and calls esp_console_cmd_register() function to register command handlers. For each command, application provides the following information (in the form of esp_console_cmd_t structure): Command name (string without spaces) Help text explaining what the command does Optional hint text listing the arguments of the command. If application uses Argtable3 for argument parsing, hint text can be generated automatically by providing a pointer to argtable argument definitions structure instead. The command handler function. A few other functions are provided by the command registration module: This function takes the command line string, splits it into argc/argv argument list using esp_console_split_argv() , looks up the command in the list of registered components, and if it is found, executes its handler. esp_console_register_help_command() Adds help command to the list of registered commands. This command prints the list of all the registered commands, along with their arguments and help texts. Callback function to be used with linenoiseSetCompletionCallback() from linenoise library. Provides completions to linenoise based on the list of registered commands. Callback function to be used with linenoiseSetHintsCallback() from linenoise library. Provides argument hints for registered commands to linenoise. Initialize Console REPL Environment To establish a basic REPL environment, console component provides several useful APIs, combining those functions described above. In a typical application, you only need to call esp_console_new_repl_uart() to initialize the REPL environment based on UART device, including driver install, basic console configuration, spawning a thread to do REPL task and register several useful commands (e.g., help). After that, you can register your own commands with esp_console_cmd_register() . The REPL environment keeps in init state until you call esp_console_start_repl() . Application Example Example application illustrating usage of the console component is available in system/console directory. This example shows how to initialize UART and VFS functions, set up linenoise library, read and handle commands from UART, and store command history in Flash. See README.md in the example directory for more details. Besides that, ESP-IDF contains several useful examples which are based on the console component and can be treated as "tools" when developing applications. For example, peripherals/i2c/i2c_tools, wifi/iperf. API Reference Header File This header file can be included with: #include "esp_console.h" This header file is a part of the API provided by the console component. To declare that your component depends on console , add the following to your CMakeLists.txt: REQUIRES console or PRIV_REQUIRES console Functions esp_err_t esp_console_init(const esp_console_config_t *config) initialize console module Note Call this once before using other console module features Parameters config -- console configuration Returns ESP_OK on success ESP_ERR_NO_MEM if out of memory ESP_ERR_INVALID_STATE if already initialized ESP_ERR_INVALID_ARG if the configuration is invalid ESP_OK on success ESP_ERR_NO_MEM if out of memory ESP_ERR_INVALID_STATE if already initialized ESP_ERR_INVALID_ARG if the configuration is invalid ESP_OK on success Parameters config -- console configuration Returns ESP_OK on success ESP_ERR_NO_MEM if out of memory ESP_ERR_INVALID_STATE if already initialized ESP_ERR_INVALID_ARG if the configuration is invalid esp_err_t esp_console_deinit(void) de-initialize console module Note Call this once when done using console module functions Returns ESP_OK on success ESP_ERR_INVALID_STATE if not initialized yet ESP_OK on success ESP_ERR_INVALID_STATE if not initialized yet ESP_OK on success Returns ESP_OK on success ESP_ERR_INVALID_STATE if not initialized yet esp_err_t esp_console_cmd_register(const esp_console_cmd_t *cmd) Register console command. Parameters cmd -- pointer to the command description; can point to a temporary value Returns ESP_OK on success ESP_ERR_NO_MEM if out of memory ESP_ERR_INVALID_ARG if command description includes invalid arguments ESP_OK on success ESP_ERR_NO_MEM if out of memory ESP_ERR_INVALID_ARG if command description includes invalid arguments ESP_OK on success Parameters cmd -- pointer to the command description; can point to a temporary value Returns ESP_OK on success ESP_ERR_NO_MEM if out of memory ESP_ERR_INVALID_ARG if command description includes invalid arguments esp_err_t esp_console_run(const char *cmdline, int *cmd_ret) Run command line. Parameters cmdline -- command line (command name followed by a number of arguments) cmd_ret -- [out] return code from the command (set if command was run) cmdline -- command line (command name followed by a number of arguments) cmd_ret -- [out] return code from the command (set if command was run) cmdline -- command line (command name followed by a number of arguments) Returns ESP_OK, if command was run ESP_ERR_INVALID_ARG, if the command line is empty, or only contained whitespace ESP_ERR_NOT_FOUND, if command with given name wasn't registered ESP_ERR_INVALID_STATE, if esp_console_init wasn't called ESP_OK, if command was run ESP_ERR_INVALID_ARG, if the command line is empty, or only contained whitespace ESP_ERR_NOT_FOUND, if command with given name wasn't registered ESP_ERR_INVALID_STATE, if esp_console_init wasn't called ESP_OK, if command was run Parameters cmdline -- command line (command name followed by a number of arguments) cmd_ret -- [out] return code from the command (set if command was run) Returns ESP_OK, if command was run ESP_ERR_INVALID_ARG, if the command line is empty, or only contained whitespace ESP_ERR_NOT_FOUND, if command with given name wasn't registered ESP_ERR_INVALID_STATE, if esp_console_init wasn't called size_t esp_console_split_argv(char *line, char **argv, size_t argv_size) Split command line into arguments in place. * - This function finds whitespace-separated arguments in the given input line. * * 'abc def 1 20 .3' -> [ 'abc', 'def', '1', '20', '.3' ] * * - Argument which include spaces may be surrounded with quotes. In this case * spaces are preserved and quotes are stripped. * * 'abc "123 456" def' -> [ 'abc', '123 456', 'def' ] * * - Escape sequences may be used to produce backslash, double quote, and space: * * 'a\ b\\c\"' -> [ 'a b\c"' ] * Note Pointers to at most argv_size - 1 arguments are returned in argv array. The pointer after the last one (i.e. argv[argc]) is set to NULL. Parameters line -- pointer to buffer to parse; it is modified in place argv -- array where the pointers to arguments are written argv_size -- number of elements in argv_array (max. number of arguments) line -- pointer to buffer to parse; it is modified in place argv -- array where the pointers to arguments are written argv_size -- number of elements in argv_array (max. number of arguments) line -- pointer to buffer to parse; it is modified in place Returns number of arguments found (argc) Parameters line -- pointer to buffer to parse; it is modified in place argv -- array where the pointers to arguments are written argv_size -- number of elements in argv_array (max. number of arguments) Returns number of arguments found (argc) void esp_console_get_completion(const char *buf, linenoiseCompletions *lc) Callback which provides command completion for linenoise library. When using linenoise for line editing, command completion support can be enabled like this: linenoiseSetCompletionCallback(&esp_console_get_completion); Parameters buf -- the string typed by the user lc -- linenoiseCompletions to be filled in buf -- the string typed by the user lc -- linenoiseCompletions to be filled in buf -- the string typed by the user Parameters buf -- the string typed by the user lc -- linenoiseCompletions to be filled in const char *esp_console_get_hint(const char *buf, int *color, int *bold) Callback which provides command hints for linenoise library. When using linenoise for line editing, hints support can be enabled as follows: linenoiseSetHintsCallback((linenoiseHintsCallback*) &esp_console_get_hint); The extra cast is needed because linenoiseHintsCallback is defined as returning a char* instead of const char*. Parameters buf -- line typed by the user color -- [out] ANSI color code to be used when displaying the hint bold -- [out] set to 1 if hint has to be displayed in bold buf -- line typed by the user color -- [out] ANSI color code to be used when displaying the hint bold -- [out] set to 1 if hint has to be displayed in bold buf -- line typed by the user Returns string containing the hint text. This string is persistent and should not be freed (i.e. linenoiseSetFreeHintsCallback should not be used). Parameters buf -- line typed by the user color -- [out] ANSI color code to be used when displaying the hint bold -- [out] set to 1 if hint has to be displayed in bold Returns string containing the hint text. This string is persistent and should not be freed (i.e. linenoiseSetFreeHintsCallback should not be used). esp_err_t esp_console_register_help_command(void) Register a 'help' command. Default 'help' command prints the list of registered commands along with hints and help strings if no additional argument is given. If an additional argument is given, the help command will look for a command with the same name and only print the hints and help strings of that command. Returns ESP_OK on success ESP_ERR_INVALID_STATE, if esp_console_init wasn't called ESP_OK on success ESP_ERR_INVALID_STATE, if esp_console_init wasn't called ESP_OK on success Returns ESP_OK on success ESP_ERR_INVALID_STATE, if esp_console_init wasn't called esp_err_t esp_console_new_repl_uart(const esp_console_dev_uart_config_t *dev_config, const esp_console_repl_config_t *repl_config, esp_console_repl_t **ret_repl) Establish a console REPL environment over UART driver. Attention This function is meant to be used in the examples to make the code more compact. Applications which use console functionality should be based on the underlying linenoise and esp_console functions. Attention This function is meant to be used in the examples to make the code more compact. Applications which use console functionality should be based on the underlying linenoise and esp_console functions. Note This is an all-in-one function to establish the environment needed for REPL, includes: Install the UART driver on the console UART (8n1, 115200, REF_TICK clock source) Configures the stdin/stdout to go through the UART driver Initializes linenoise Spawn new thread to run REPL in the background Install the UART driver on the console UART (8n1, 115200, REF_TICK clock source) Configures the stdin/stdout to go through the UART driver Initializes linenoise Spawn new thread to run REPL in the background Parameters dev_config -- [in] UART device configuration repl_config -- [in] REPL configuration ret_repl -- [out] return REPL handle after initialization succeed, return NULL otherwise dev_config -- [in] UART device configuration repl_config -- [in] REPL configuration ret_repl -- [out] return REPL handle after initialization succeed, return NULL otherwise dev_config -- [in] UART device configuration Returns ESP_OK on success ESP_FAIL Parameter error ESP_OK on success ESP_FAIL Parameter error ESP_OK on success Parameters dev_config -- [in] UART device configuration repl_config -- [in] REPL configuration ret_repl -- [out] return REPL handle after initialization succeed, return NULL otherwise Returns ESP_OK on success ESP_FAIL Parameter error esp_err_t esp_console_start_repl(esp_console_repl_t *repl) Start REPL environment. Note Once the REPL gets started, it won't be stopped until the user calls repl->del(repl) to destroy the REPL environment. Parameters repl -- [in] REPL handle returned from esp_console_new_repl_xxx Returns ESP_OK on success ESP_ERR_INVALID_STATE, if repl has started already ESP_OK on success ESP_ERR_INVALID_STATE, if repl has started already ESP_OK on success Parameters repl -- [in] REPL handle returned from esp_console_new_repl_xxx Returns ESP_OK on success ESP_ERR_INVALID_STATE, if repl has started already Structures struct esp_console_config_t Parameters for console initialization. Public Members size_t max_cmdline_length length of command line buffer, in bytes size_t max_cmdline_length length of command line buffer, in bytes size_t max_cmdline_args maximum number of command line arguments to parse size_t max_cmdline_args maximum number of command line arguments to parse uint32_t heap_alloc_caps where to (e.g. MALLOC_CAP_SPIRAM) allocate heap objects such as cmds used by esp_console uint32_t heap_alloc_caps where to (e.g. MALLOC_CAP_SPIRAM) allocate heap objects such as cmds used by esp_console int hint_color ASCII color code of hint text. int hint_color ASCII color code of hint text. int hint_bold Set to 1 to print hint text in bold. int hint_bold Set to 1 to print hint text in bold. size_t max_cmdline_length struct esp_console_repl_config_t Parameters for console REPL (Read Eval Print Loop) Public Members uint32_t max_history_len maximum length for the history uint32_t max_history_len maximum length for the history const char *history_save_path file path used to save history commands, set to NULL won't save to file system const char *history_save_path file path used to save history commands, set to NULL won't save to file system uint32_t task_stack_size repl task stack size uint32_t task_stack_size repl task stack size uint32_t task_priority repl task priority uint32_t task_priority repl task priority const char *prompt prompt (NULL represents default: "esp> ") const char *prompt prompt (NULL represents default: "esp> ") size_t max_cmdline_length maximum length of a command line. If 0, default value will be used size_t max_cmdline_length maximum length of a command line. If 0, default value will be used uint32_t max_history_len struct esp_console_dev_uart_config_t Parameters for console device: UART. struct esp_console_cmd_t Console command description. Public Members const char *command Command name. Must not be NULL, must not contain spaces. The pointer must be valid until the call to esp_console_deinit. const char *command Command name. Must not be NULL, must not contain spaces. The pointer must be valid until the call to esp_console_deinit. const char *help Help text for the command, shown by help command. If set, the pointer must be valid until the call to esp_console_deinit. If not set, the command will not be listed in 'help' output. const char *help Help text for the command, shown by help command. If set, the pointer must be valid until the call to esp_console_deinit. If not set, the command will not be listed in 'help' output. const char *hint Hint text, usually lists possible arguments. If set to NULL, and 'argtable' field is non-NULL, hint will be generated automatically const char *hint Hint text, usually lists possible arguments. If set to NULL, and 'argtable' field is non-NULL, hint will be generated automatically esp_console_cmd_func_t func Pointer to a function which implements the command. esp_console_cmd_func_t func Pointer to a function which implements the command. void *argtable Array or structure of pointers to arg_xxx structures, may be NULL. Used to generate hint text if 'hint' is set to NULL. Array/structure which this field points to must end with an arg_end. Only used for the duration of esp_console_cmd_register call. void *argtable Array or structure of pointers to arg_xxx structures, may be NULL. Used to generate hint text if 'hint' is set to NULL. Array/structure which this field points to must end with an arg_end. Only used for the duration of esp_console_cmd_register call. const char *command struct esp_console_repl_s Console REPL base structure. Public Members esp_err_t (*del)(esp_console_repl_t *repl) Delete console REPL environment. Param repl [in] REPL handle returned from esp_console_new_repl_xxx Return ESP_OK on success ESP_FAIL on errors ESP_OK on success ESP_FAIL on errors ESP_OK on success Param repl [in] REPL handle returned from esp_console_new_repl_xxx Return ESP_OK on success ESP_FAIL on errors esp_err_t (*del)(esp_console_repl_t *repl) Delete console REPL environment. Param repl [in] REPL handle returned from esp_console_new_repl_xxx Return ESP_OK on success ESP_FAIL on errors esp_err_t (*del)(esp_console_repl_t *repl) Macros ESP_CONSOLE_CONFIG_DEFAULT() Default console configuration value. ESP_CONSOLE_REPL_CONFIG_DEFAULT() Default console repl configuration value. ESP_CONSOLE_DEV_UART_CONFIG_DEFAULT() Type Definitions typedef struct linenoiseCompletions linenoiseCompletions typedef int (*esp_console_cmd_func_t)(int argc, char **argv) Console command main function. Param argc number of arguments Param argv array with argc entries, each pointing to a zero-terminated string argument Return console command return code, 0 indicates "success" Param argc number of arguments Param argv array with argc entries, each pointing to a zero-terminated string argument Return console command return code, 0 indicates "success" typedef struct esp_console_repl_s esp_console_repl_t Type defined for console REPL.
Console ESP-IDF provides console component, which includes building blocks needed to develop an interactive console over serial port. This component includes the following features: Line editing, provided by linenoise library. This includes handling of backspace and arrow keys, scrolling through command history, command auto-completion, and argument hints. Splitting of command line into arguments. Argument parsing, provided by argtable3 library. This library includes APIs used for parsing GNU style command line arguments. Functions for registration and dispatching of commands. Functions to establish a basic REPL (Read-Evaluate-Print-Loop) environment. Note These features can be used together or independently. For example, it is possible to use line editing and command registration features, but use getopt or custom code for argument parsing, instead of argtable3. Likewise, it is possible to use simpler means of command input (such as fgets) together with the rest of the means for command splitting and argument parsing. Note When using a console application on a chip that supports a hardware USB serial interface, we suggest to disable the secondary serial console output. The secondary output will be output-only and consequently does not make sense in an interactive application. Line Editing Line editing feature lets users compose commands by typing them, erasing symbols using the backspace key, navigating within the command using the left/right keys, navigating to previously typed commands using the up/down keys, and performing autocompletion using the tab key. Note This feature relies on ANSI escape sequence support in the terminal application. As such, serial monitors which display raw UART data can not be used together with the line editing library. If you see [6n or similar escape sequence when running system/console example instead of a command prompt (e.g., esp> ), it means that the serial monitor does not support escape sequences. Programs which are known to work are GNU screen, minicom, and esp-idf-monitor (which can be invoked using idf.py monitor from project directory). Here is an overview of functions provided by linenoise library. Configuration Linenoise library does not need explicit initialization. However, some configuration defaults may need to be changed before invoking the main line editing function. linenoiseClearScreen() Clear terminal screen using an escape sequence and position the cursor at the top left corner. linenoiseSetMultiLine() Switch between single line and multi line editing modes. In single line mode, if the length of the command exceeds the width of the terminal, the command text is scrolled within the line to show the end of the text. In this case the beginning of the text is hidden. Single line mode needs less data to be sent to refresh screen on each key press, so exhibits less glitching compared to the multi line mode. On the flip side, editing commands and copying command text from terminal in single line mode is harder. Default is single line mode. linenoiseAllowEmpty() Set whether linenoise library returns a zero-length string (if true) or NULL(if false) for empty lines. By default, zero-length strings are returned. linenoiseSetMaxLineLen() Set maximum length of the line for linenoise library. Default length is 4096 bytes. The default value can be updated to optimize RAM memory usage. Main Loop linenoise() In most cases, console applications have some form of read/eval loop. linenoise()is the single function which handles user's key presses and returns the completed line once the enterkey is pressed. As such, it handles the readpart of the loop. linenoiseFree() This function must be called to release the command line buffer obtained from linenoise()function. Hints and Completions linenoiseSetCompletionCallback() When the user presses the tabkey, linenoise library invokes the completion callback. The callback should inspect the contents of the command typed so far and provide a list of possible completions using calls to linenoiseAddCompletion()function. linenoiseSetCompletionCallback()function should be called to register this completion callback, if completion feature is desired. consolecomponent provides a ready made function to provide completions for registered commands, esp_console_get_completion()(see below). linenoiseAddCompletion() Function to be called by completion callback to inform the library about possible completions of the currently typed command. linenoiseSetHintsCallback() Whenever user input changes, linenoise invokes the hints callback. This callback can inspect the command line typed so far, and provide a string with hints (which can include list of command arguments, for example). The library then displays the hint text on the same line where editing happens, possibly with a different color. linenoiseSetFreeHintsCallback() If the hint string returned by hints callback is dynamically allocated or needs to be otherwise recycled, the function which performs such cleanup should be registered via linenoiseSetFreeHintsCallback(). History linenoiseHistorySetMaxLen() This function sets the number of most recently typed commands to be kept in memory. Users can navigate the history using the up/down arrows keys. linenoiseHistoryAdd() Linenoise does not automatically add commands to history. Instead, applications need to call this function to add command strings to the history. linenoiseHistorySave() Function saves command history from RAM to a text file, for example on an SD card or on a filesystem in flash memory. linenoiseHistoryLoad() Counterpart to linenoiseHistorySave(), loads history from a file. linenoiseHistoryFree() Releases memory used to store command history. Call this function when done working with linenoise library. Splitting of Command Line into Arguments console component provides esp_console_split_argv() function to split command line string into arguments. The function returns the number of arguments found ( argc) and fills an array of pointers which can be passed as argv argument to any function which accepts arguments in argc, argv format. The command line is split into arguments according to the following rules: Arguments are separated by spaces If spaces within arguments are required, they can be escaped using \(backslash) character. Other escape sequences which are recognized are \\(which produces literal backslash) and \", which produces a double quote. Arguments can be quoted using double quotes. Quotes may appear only in the beginning and at the end of the argument. Quotes within the argument must be escaped as mentioned above. Quotes surrounding the argument are stripped by esp_console_split_argvfunction. Examples: abc def 1 20 .3> [ abc, def, 1, 20, .3] abc "123 456" def> [ abc, 123 456, def] `a\ b\\c\"> [ a b\c"] Argument Parsing For argument parsing, console component includes argtable3 library. Please see tutorial for an introduction to argtable3. Github repository also includes examples. Command Registration and Dispatching console component includes utility functions which handle registration of commands, matching commands typed by the user to registered ones, and calling these commands with the arguments given on the command line. Application first initializes command registration module using a call to esp_console_init(), and calls esp_console_cmd_register() function to register command handlers. For each command, application provides the following information (in the form of esp_console_cmd_t structure): Command name (string without spaces) Help text explaining what the command does Optional hint text listing the arguments of the command. If application uses Argtable3 for argument parsing, hint text can be generated automatically by providing a pointer to argtable argument definitions structure instead. The command handler function. A few other functions are provided by the command registration module: This function takes the command line string, splits it into argc/argv argument list using esp_console_split_argv(), looks up the command in the list of registered components, and if it is found, executes its handler. esp_console_register_help_command() Adds helpcommand to the list of registered commands. This command prints the list of all the registered commands, along with their arguments and help texts. Callback function to be used with linenoiseSetCompletionCallback()from linenoise library. Provides completions to linenoise based on the list of registered commands. Callback function to be used with linenoiseSetHintsCallback()from linenoise library. Provides argument hints for registered commands to linenoise. Initialize Console REPL Environment To establish a basic REPL environment, console component provides several useful APIs, combining those functions described above. In a typical application, you only need to call esp_console_new_repl_uart() to initialize the REPL environment based on UART device, including driver install, basic console configuration, spawning a thread to do REPL task and register several useful commands (e.g., help). After that, you can register your own commands with esp_console_cmd_register(). The REPL environment keeps in init state until you call esp_console_start_repl(). Application Example Example application illustrating usage of the console component is available in system/console directory. This example shows how to initialize UART and VFS functions, set up linenoise library, read and handle commands from UART, and store command history in Flash. See README.md in the example directory for more details. Besides that, ESP-IDF contains several useful examples which are based on the console component and can be treated as "tools" when developing applications. For example, peripherals/i2c/i2c_tools, wifi/iperf. API Reference Header File This header file can be included with: #include "esp_console.h" This header file is a part of the API provided by the consolecomponent. To declare that your component depends on console, add the following to your CMakeLists.txt: REQUIRES console or PRIV_REQUIRES console Functions - esp_err_t esp_console_init(const esp_console_config_t *config) initialize console module Note Call this once before using other console module features - Parameters config -- console configuration - Returns ESP_OK on success ESP_ERR_NO_MEM if out of memory ESP_ERR_INVALID_STATE if already initialized ESP_ERR_INVALID_ARG if the configuration is invalid - - esp_err_t esp_console_deinit(void) de-initialize console module Note Call this once when done using console module functions - Returns ESP_OK on success ESP_ERR_INVALID_STATE if not initialized yet - - esp_err_t esp_console_cmd_register(const esp_console_cmd_t *cmd) Register console command. - Parameters cmd -- pointer to the command description; can point to a temporary value - Returns ESP_OK on success ESP_ERR_NO_MEM if out of memory ESP_ERR_INVALID_ARG if command description includes invalid arguments - - esp_err_t esp_console_run(const char *cmdline, int *cmd_ret) Run command line. - Parameters cmdline -- command line (command name followed by a number of arguments) cmd_ret -- [out] return code from the command (set if command was run) - - Returns ESP_OK, if command was run ESP_ERR_INVALID_ARG, if the command line is empty, or only contained whitespace ESP_ERR_NOT_FOUND, if command with given name wasn't registered ESP_ERR_INVALID_STATE, if esp_console_init wasn't called - - size_t esp_console_split_argv(char *line, char **argv, size_t argv_size) Split command line into arguments in place. * - This function finds whitespace-separated arguments in the given input line. * * 'abc def 1 20 .3' -> [ 'abc', 'def', '1', '20', '.3' ] * * - Argument which include spaces may be surrounded with quotes. In this case * spaces are preserved and quotes are stripped. * * 'abc "123 456" def' -> [ 'abc', '123 456', 'def' ] * * - Escape sequences may be used to produce backslash, double quote, and space: * * 'a\ b\\c\"' -> [ 'a b\c"' ] * Note Pointers to at most argv_size - 1 arguments are returned in argv array. The pointer after the last one (i.e. argv[argc]) is set to NULL. - Parameters line -- pointer to buffer to parse; it is modified in place argv -- array where the pointers to arguments are written argv_size -- number of elements in argv_array (max. number of arguments) - - Returns number of arguments found (argc) - void esp_console_get_completion(const char *buf, linenoiseCompletions *lc) Callback which provides command completion for linenoise library. When using linenoise for line editing, command completion support can be enabled like this: linenoiseSetCompletionCallback(&esp_console_get_completion); - Parameters buf -- the string typed by the user lc -- linenoiseCompletions to be filled in - - const char *esp_console_get_hint(const char *buf, int *color, int *bold) Callback which provides command hints for linenoise library. When using linenoise for line editing, hints support can be enabled as follows: linenoiseSetHintsCallback((linenoiseHintsCallback*) &esp_console_get_hint); The extra cast is needed because linenoiseHintsCallback is defined as returning a char* instead of const char*. - Parameters buf -- line typed by the user color -- [out] ANSI color code to be used when displaying the hint bold -- [out] set to 1 if hint has to be displayed in bold - - Returns string containing the hint text. This string is persistent and should not be freed (i.e. linenoiseSetFreeHintsCallback should not be used). - esp_err_t esp_console_register_help_command(void) Register a 'help' command. Default 'help' command prints the list of registered commands along with hints and help strings if no additional argument is given. If an additional argument is given, the help command will look for a command with the same name and only print the hints and help strings of that command. - Returns ESP_OK on success ESP_ERR_INVALID_STATE, if esp_console_init wasn't called - - esp_err_t esp_console_new_repl_uart(const esp_console_dev_uart_config_t *dev_config, const esp_console_repl_config_t *repl_config, esp_console_repl_t **ret_repl) Establish a console REPL environment over UART driver. - Attention This function is meant to be used in the examples to make the code more compact. Applications which use console functionality should be based on the underlying linenoise and esp_console functions. Note This is an all-in-one function to establish the environment needed for REPL, includes: Install the UART driver on the console UART (8n1, 115200, REF_TICK clock source) Configures the stdin/stdout to go through the UART driver Initializes linenoise Spawn new thread to run REPL in the background - Parameters dev_config -- [in] UART device configuration repl_config -- [in] REPL configuration ret_repl -- [out] return REPL handle after initialization succeed, return NULL otherwise - - Returns ESP_OK on success ESP_FAIL Parameter error - - esp_err_t esp_console_start_repl(esp_console_repl_t *repl) Start REPL environment. Note Once the REPL gets started, it won't be stopped until the user calls repl->del(repl) to destroy the REPL environment. - Parameters repl -- [in] REPL handle returned from esp_console_new_repl_xxx - Returns ESP_OK on success ESP_ERR_INVALID_STATE, if repl has started already - Structures - struct esp_console_config_t Parameters for console initialization. Public Members - size_t max_cmdline_length length of command line buffer, in bytes - size_t max_cmdline_args maximum number of command line arguments to parse - uint32_t heap_alloc_caps where to (e.g. MALLOC_CAP_SPIRAM) allocate heap objects such as cmds used by esp_console - int hint_color ASCII color code of hint text. - int hint_bold Set to 1 to print hint text in bold. - size_t max_cmdline_length - struct esp_console_repl_config_t Parameters for console REPL (Read Eval Print Loop) Public Members - uint32_t max_history_len maximum length for the history - const char *history_save_path file path used to save history commands, set to NULL won't save to file system - uint32_t task_stack_size repl task stack size - uint32_t task_priority repl task priority - const char *prompt prompt (NULL represents default: "esp> ") - size_t max_cmdline_length maximum length of a command line. If 0, default value will be used - uint32_t max_history_len - struct esp_console_dev_uart_config_t Parameters for console device: UART. - struct esp_console_cmd_t Console command description. Public Members - const char *command Command name. Must not be NULL, must not contain spaces. The pointer must be valid until the call to esp_console_deinit. - const char *help Help text for the command, shown by help command. If set, the pointer must be valid until the call to esp_console_deinit. If not set, the command will not be listed in 'help' output. - const char *hint Hint text, usually lists possible arguments. If set to NULL, and 'argtable' field is non-NULL, hint will be generated automatically - esp_console_cmd_func_t func Pointer to a function which implements the command. - void *argtable Array or structure of pointers to arg_xxx structures, may be NULL. Used to generate hint text if 'hint' is set to NULL. Array/structure which this field points to must end with an arg_end. Only used for the duration of esp_console_cmd_register call. - const char *command - struct esp_console_repl_s Console REPL base structure. Public Members - esp_err_t (*del)(esp_console_repl_t *repl) Delete console REPL environment. - Param repl [in] REPL handle returned from esp_console_new_repl_xxx - Return ESP_OK on success ESP_FAIL on errors - - esp_err_t (*del)(esp_console_repl_t *repl) Macros - ESP_CONSOLE_CONFIG_DEFAULT() Default console configuration value. - ESP_CONSOLE_REPL_CONFIG_DEFAULT() Default console repl configuration value. - ESP_CONSOLE_DEV_UART_CONFIG_DEFAULT() Type Definitions - typedef struct linenoiseCompletions linenoiseCompletions - typedef int (*esp_console_cmd_func_t)(int argc, char **argv) Console command main function. - Param argc number of arguments - Param argv array with argc entries, each pointing to a zero-terminated string argument - Return console command return code, 0 indicates "success" - typedef struct esp_console_repl_s esp_console_repl_t Type defined for console REPL.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/console.html
ESP-IDF Programming Guide v5.2.1 documentation
null
eFuse Manager
null
espressif.com
2016-01-01
e9afcdee450ea41
null
null
eFuse Manager Introduction The eFuse Manager library is designed to structure access to eFuse bits and make using these easy. This library operates eFuse bits by a structure name which is assigned in eFuse table. This sections introduces some concepts used by eFuse Manager. Hardware Description The ESP32 has a number of eFuses which can store system and user parameters. Each eFuse is a one-bit field which can be programmed to 1 after which it cannot be reverted back to 0. Some of system parameters are using these eFuse bits directly by hardware modules and have special place (for example EFUSE_BLK0). For more details, see ESP32 Technical Reference Manual > eFuse Controller (eFuse) [PDF]. Some eFuse bits are available for user applications. ESP32 has 4 eFuse blocks each of the size of 256 bits (not all bits are available): EFUSE_BLK0 is used entirely for system purposes; EFUSE_BLK1 is used for flash encrypt key. If not using that Flash Encryption feature, they can be used for another purpose; EFUSE_BLK2 is used for security boot key. If not using that Secure Boot feature, they can be used for another purpose; EFUSE_BLK3 can be partially reserved for the custom MAC address, or used entirely for user application. Note that some bits are already used in ESP-IDF. Each block is divided into 8 32-bits registers. eFuse Manager Component The component has API functions for reading and writing fields. Access to the fields is carried out through the structures that describe the location of the eFuse bits in the blocks. The component provides the ability to form fields of any length and from any number of individual bits. The description of the fields is made in a CSV file in a table form. To generate from a tabular form (CSV file) in the C-source uses the tool efuse_table_gen.py . The tool checks the CSV file for uniqueness of field names and bit intersection, in case of using a custom file from the user's project directory, the utility checks with the common CSV file. CSV files: common (esp_efuse_table.csv) - contains eFuse fields which are used inside the ESP-IDF. C-source generation should be done manually when changing this file (run command idf.py efuse-common-table ). Note that changes in this file can lead to incorrect operation. custom - (optional and can be enabled by CONFIG_EFUSE_CUSTOM_TABLE) contains eFuse fields that are used by the user in their application. C-source generation should be done manually when changing this file and running idf.py efuse-custom-table . Description CSV File The CSV file contains a description of the eFuse fields. In the simple case, one field has one line of description. Table header: # field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count(1..256), comment Individual params in CSV file the following meanings: field_name Name of field. The prefix ESP_EFUSE_ is added to the name, and this field name is available in the code. This name is used to access the fields. The name must be unique for all fields. If the line has an empty name, then this line is combined with the previous field. This allows you to set an arbitrary order of bits in the field, and expand the field as well (see MAC_FACTORY field in the common table). The field_name supports structured format using . to show that the field belongs to another field (see WR_DIS and RD_DIS in the common table). efuse_block Block number. It determines where the eFuse bits are placed for this field. Available EFUSE_BLK0..EFUSE_BLK3. bit_start Start bit number (0..255). The bit_start field can be omitted. In this case, it is set to bit_start + bit_count from the previous record, if it has the same efuse_block. Otherwise (if efuse_block is different, or this is the first entry), an error will be generated. bit_count The number of bits to use in this field (1..-). This parameter cannot be omitted. This field also may be MAX_BLK_LEN in this case, the field length has the maximum block length, taking into account the coding scheme (applicable for ESP_EFUSE_SECURE_BOOT_KEY and ESP_EFUSE_ENCRYPT_FLASH_KEY fields). The value MAX_BLK_LEN depends on CONFIG_EFUSE_CODE_SCHEME_SELECTOR, which will be replaced with "None" - 256, "3/4" - 192, "REPEAT" - 128. comment This param is using for comment field, it also move to C-header file. The comment field can be omitted. If a non-sequential bit order is required to describe a field, then the field description in the following lines should be continued without specifying a name, indicating that it belongs to one field. For example two fields MAC_FACTORY and MAC_FACTORY_CRC : # Factory MAC address # ####################### MAC_FACTORY, EFUSE_BLK0, 72, 8, Factory MAC addr [0] , EFUSE_BLK0, 64, 8, Factory MAC addr [1] , EFUSE_BLK0, 56, 8, Factory MAC addr [2] , EFUSE_BLK0, 48, 8, Factory MAC addr [3] , EFUSE_BLK0, 40, 8, Factory MAC addr [4] , EFUSE_BLK0, 32, 8, Factory MAC addr [5] MAC_FACTORY_CRC, EFUSE_BLK0, 80, 8, CRC8 for factory MAC address This field is available in code as ESP_EFUSE_MAC_FACTORY and ESP_EFUSE_MAC_FACTORY_CRC . Structured eFuse Fields WR_DIS, EFUSE_BLK0, 0, 32, Write protection WR_DIS.RD_DIS, EFUSE_BLK0, 0, 1, Write protection for RD_DIS WR_DIS.FIELD_1, EFUSE_BLK0, 1, 1, Write protection for FIELD_1 WR_DIS.FIELD_2, EFUSE_BLK0, 2, 4, Write protection for FIELD_2 (includes B1 and B2) WR_DIS.FIELD_2.B1, EFUSE_BLK0, 2, 2, Write protection for FIELD_2.B1 WR_DIS.FIELD_2.B2, EFUSE_BLK0, 4, 2, Write protection for FIELD_2.B2 WR_DIS.FIELD_3, EFUSE_BLK0, 5, 1, Write protection for FIELD_3 WR_DIS.FIELD_3.ALIAS, EFUSE_BLK0, 5, 1, Write protection for FIELD_3 (just a alias for WR_DIS.FIELD_3) WR_DIS.FIELD_4, EFUSE_BLK0, 7, 1, Write protection for FIELD_4 The structured eFuse field looks like WR_DIS.RD_DIS where the dot points that this field belongs to the parent field - WR_DIS and cannot be out of the parent's range. It is possible to use some levels of structured fields as WR_DIS.FIELD_2.B1 and B2. These fields should not be crossed each other and should be in the range of two fields: WR_DIS and WR_DIS.FIELD_2 . It is possible to create aliases for fields with the same range, see WR_DIS.FIELD_3 and WR_DIS.FIELD_3.ALIAS . The ESP-IDF names for structured eFuse fields should be unique. The efuse_table_gen tool generates the final names where the dot is replaced by _ . The names for using in ESP-IDF are ESP_EFUSE_WR_DIS, ESP_EFUSE_WR_DIS_RD_DIS, ESP_EFUSE_WR_DIS_FIELD_2_B1, etc. The efuse_table_gen tool checks that the fields do not overlap each other and must be within the range of a field if there is a violation, then throws the following error: Field at USER_DATA, EFUSE_BLK3, 0, 256 intersected with SERIAL_NUMBER, EFUSE_BLK3, 0, 32 Solution: Describe SERIAL_NUMBER to be included in USER_DATA . ( USER_DATA.SERIAL_NUMBER ). Field at FEILD, EFUSE_BLK3, 0, 50 out of range FEILD.MAJOR_NUMBER, EFUSE_BLK3, 60, 32 Solution: Change bit_start for FIELD.MAJOR_NUMBER from 60 to 0, so MAJOR_NUMBER is in the FEILD range. efuse_table_gen.py Tool efuse_table_gen.py Tool The tool is designed to generate C-source files from CSV file and validate fields. First of all, the check is carried out on the uniqueness of the names and overlaps of the field bits. If an additional custom file is used, it will be checked with the existing common file (esp_efuse_table.csv). In case of errors, a message will be displayed and the string that caused the error. C-source files contain structures of type esp_efuse_desc_t. To generate a common files, use the following command idf.py efuse-common-table or: cd $IDF_PATH/components/efuse/ ./efuse_table_gen.py --idf_target esp32 esp32/esp_efuse_table.csv After generation in the folder $IDF_PATH/components/efuse/esp32 create: esp_efuse_table.c file. In include folder esp_efuse_table.c file. To generate a custom files, use the following command idf.py efuse-custom-table or: cd $IDF_PATH/components/efuse/ ./efuse_table_gen.py --idf_target esp32 esp32/esp_efuse_table.csv PROJECT_PATH/main/esp_efuse_custom_table.csv After generation in the folder PROJECT_PATH/main create: esp_efuse_custom_table.c file. In include folder esp_efuse_custom_table.c file. To use the generated fields, you need to include two files: #include "esp_efuse.h" #include "esp_efuse_table.h" // or "esp_efuse_custom_table.h" Supported Coding Scheme eFuse have three coding schemes: None (value 0). 3/4 (value 1). Repeat (value 2). The coding scheme affects only EFUSE_BLK1, EFUSE_BLK2 and EFUSE_BLK3 blocks. EUSE_BLK0 block always has a coding scheme None . Coding changes the number of bits that can be written into a block, the block length is constant 256, some of these bits are used for encoding and not avaliable for the user. When using a coding scheme, the length of the payload that can be written is limited (for more details 20.3.1.3 System Parameter coding_scheme ): None 256 bits. 3/4 192 bits. Repeat 128 bits. You can find out the coding scheme of your chip: run a espefuse.py -p PORT summary command. from esptool utility logs (during flashing). calling the function in the code esp_efuse_get_coding_scheme() for the EFUSE_BLK3 block. eFuse tables must always comply with the coding scheme in the chip. There is an CONFIG_EFUSE_CODE_SCHEME_SELECTOR option to select the coding type for tables in a Kconfig. When generating source files, if your tables do not follow the coding scheme, an error message will be displayed. Adjust the length or offset fields. If your program was compiled with None encoding and 3/4 is used in the chip, then the ESP_ERR_CODING error may occur when calling the eFuse API (the field is outside the block boundaries). If the field matches the new block boundaries, then the API will work without errors. Also, 3/4 coding scheme imposes restrictions on writing bits belonging to one coding unit. The whole block with a length of 256 bits is divided into 4 coding units, and in each coding unit there are 6 bytes of useful data and 2 service bytes. These 2 service bytes contain the checksum of the previous 6 data bytes. It turns out that only one field can be written into one coding unit. Repeated rewriting in one coding unit is prohibited. But if the record was made in advance or through a esp_efuse_write_block() function, then reading the fields belonging to one coding unit is possible. In case 3/4 coding scheme, the writing process is divided into the coding units and we cannot use the usual mode of writing some fields. We can prepare all the data for writing and burn it in one time. You can also use this mode for None coding scheme but it is not necessary. It is important for 3/4 coding scheme. The batch writing mode blocks esp_efuse_read_... operations. After changing the coding scheme, run efuse_common_table and efuse_custom_table commands to check the tables of the new coding scheme. To write some fields into one block, or different blocks in one time, you need to use the batch writing mode . Firstly set this mode through esp_efuse_batch_write_begin() function then write some fields as usual using the esp_efuse_write_... functions. At the end to burn them, call the esp_efuse_batch_write_commit() function. It burns prepared data to the eFuse blocks and disables the batch recording mode . Note If there is already pre-written data in the eFuse block using the 3/4 or Repeat encoding scheme, then it is not possible to write anything extra (even if the required bits are empty) without breaking the previous encoding data. This encoding data will be overwritten with new encoding data and completely destroyed (however, the payload eFuses are not damaged). It can be related to: CUSTOM_MAC, SPI_PAD_CONFIG_HD, SPI_PAD_CONFIG_CS, etc. Please contact Espressif to order the required pre-burnt eFuses. FOR TESTING ONLY (NOT RECOMMENDED): You can ignore or suppress errors that violate encoding scheme data in order to burn the necessary bits in the eFuse block. eFuse API Access to the fields is via a pointer to the description structure. API functions have some basic operation: esp_efuse_read_field_blob() - returns an array of read eFuse bits. esp_efuse_read_field_cnt() - returns the number of bits programmed as "1". esp_efuse_write_field_blob() - writes an array. esp_efuse_write_field_cnt() - writes a required count of bits as "1". esp_efuse_get_field_size() - returns the number of bits by the field name. esp_efuse_read_reg() - returns value of eFuse register. esp_efuse_write_reg() - writes value to eFuse register. esp_efuse_get_coding_scheme() - returns eFuse coding scheme for blocks. esp_efuse_read_block() - reads key to eFuse block starting at the offset and the required size. esp_efuse_write_block() - writes key to eFuse block starting at the offset and the required size. esp_efuse_batch_write_begin() - set the batch mode of writing fields. esp_efuse_batch_write_commit() - writes all prepared data for batch writing mode and reset the batch writing mode. esp_efuse_batch_write_cancel() - reset the batch writing mode and prepared data. esp_efuse_get_key_dis_read() - Returns a read protection for the key block. esp_efuse_set_key_dis_read() - Sets a read protection for the key block. esp_efuse_get_key_dis_write() - Returns a write protection for the key block. esp_efuse_set_key_dis_write() - Sets a write protection for the key block. esp_efuse_get_key_purpose() - Returns the current purpose set for an eFuse key block. esp_efuse_write_key() - Programs a block of key data to an eFuse block esp_efuse_write_keys() - Programs keys to unused eFuse blocks esp_efuse_find_purpose() - Finds a key block with the particular purpose set. esp_efuse_get_keypurpose_dis_write() - Returns a write protection of the key purpose field for an eFuse key block (for esp32 always true). esp_efuse_key_block_unused() - Returns true if the key block is unused, false otherwise. For frequently used fields, special functions are made, like this esp_efuse_get_pkg_ver() . How to Add a New Field Find a free bits for field. Show esp_efuse_table.csv file or run idf.py show-efuse-table or the next command: $ ./efuse_table_gen.py esp32/esp_efuse_table.csv --info Parsing efuse CSV input file $IDF_PATH/components/efuse/esp32/esp_efuse_table.csv ... Verifying efuse table... Max number of bits in BLK 192 Sorted efuse table: # field_name efuse_block bit_start bit_count 1 WR_DIS EFUSE_BLK0 0 16 2 WR_DIS.RD_DIS EFUSE_BLK0 0 1 3 WR_DIS.WR_DIS EFUSE_BLK0 1 1 4 WR_DIS.FLASH_CRYPT_CNT EFUSE_BLK0 2 1 5 WR_DIS.UART_DOWNLOAD_DIS EFUSE_BLK0 2 1 6 WR_DIS.MAC EFUSE_BLK0 3 1 7 WR_DIS.MAC_CRC EFUSE_BLK0 3 1 8 WR_DIS.DISABLE_APP_CPU EFUSE_BLK0 3 1 9 WR_DIS.DISABLE_BT EFUSE_BLK0 3 1 10 WR_DIS.DIS_CACHE EFUSE_BLK0 3 1 11 WR_DIS.VOL_LEVEL_HP_INV EFUSE_BLK0 3 1 12 WR_DIS.CLK8M_FREQ EFUSE_BLK0 4 1 13 WR_DIS.ADC_VREF EFUSE_BLK0 4 1 14 WR_DIS.XPD_SDIO_REG EFUSE_BLK0 5 1 15 WR_DIS.XPD_SDIO_TIEH EFUSE_BLK0 5 1 16 WR_DIS.XPD_SDIO_FORCE EFUSE_BLK0 5 1 17 WR_DIS.SPI_PAD_CONFIG_CLK EFUSE_BLK0 6 1 18 WR_DIS.SPI_PAD_CONFIG_Q EFUSE_BLK0 6 1 19 WR_DIS.SPI_PAD_CONFIG_D EFUSE_BLK0 6 1 20 WR_DIS.SPI_PAD_CONFIG_CS0 EFUSE_BLK0 6 1 21 WR_DIS.BLOCK1 EFUSE_BLK0 7 1 22 WR_DIS.BLOCK2 EFUSE_BLK0 8 1 23 WR_DIS.BLOCK3 EFUSE_BLK0 9 1 24 WR_DIS.CUSTOM_MAC_CRC EFUSE_BLK0 9 1 25 WR_DIS.CUSTOM_MAC EFUSE_BLK0 9 1 26 WR_DIS.ADC1_TP_LOW EFUSE_BLK0 9 1 27 WR_DIS.ADC1_TP_HIGH EFUSE_BLK0 9 1 28 WR_DIS.ADC2_TP_LOW EFUSE_BLK0 9 1 29 WR_DIS.ADC2_TP_HIGH EFUSE_BLK0 9 1 30 WR_DIS.SECURE_VERSION EFUSE_BLK0 9 1 31 WR_DIS.MAC_VERSION EFUSE_BLK0 9 1 32 WR_DIS.BLK3_PART_RESERVE EFUSE_BLK0 10 1 33 WR_DIS.FLASH_CRYPT_CONFIG EFUSE_BLK0 10 1 34 WR_DIS.CODING_SCHEME EFUSE_BLK0 10 1 35 WR_DIS.KEY_STATUS EFUSE_BLK0 10 1 36 WR_DIS.ABS_DONE_0 EFUSE_BLK0 12 1 37 WR_DIS.ABS_DONE_1 EFUSE_BLK0 13 1 38 WR_DIS.JTAG_DISABLE EFUSE_BLK0 14 1 39 WR_DIS.CONSOLE_DEBUG_DISABLE EFUSE_BLK0 15 1 40 WR_DIS.DISABLE_DL_ENCRYPT EFUSE_BLK0 15 1 41 WR_DIS.DISABLE_DL_DECRYPT EFUSE_BLK0 15 1 42 WR_DIS.DISABLE_DL_CACHE EFUSE_BLK0 15 1 43 RD_DIS EFUSE_BLK0 16 4 44 RD_DIS.BLOCK1 EFUSE_BLK0 16 1 45 RD_DIS.BLOCK2 EFUSE_BLK0 17 1 46 RD_DIS.BLOCK3 EFUSE_BLK0 18 1 47 RD_DIS.CUSTOM_MAC_CRC EFUSE_BLK0 18 1 48 RD_DIS.CUSTOM_MAC EFUSE_BLK0 18 1 49 RD_DIS.ADC1_TP_LOW EFUSE_BLK0 18 1 50 RD_DIS.ADC1_TP_HIGH EFUSE_BLK0 18 1 51 RD_DIS.ADC2_TP_LOW EFUSE_BLK0 18 1 52 RD_DIS.ADC2_TP_HIGH EFUSE_BLK0 18 1 53 RD_DIS.SECURE_VERSION EFUSE_BLK0 18 1 54 RD_DIS.MAC_VERSION EFUSE_BLK0 18 1 55 RD_DIS.BLK3_PART_RESERVE EFUSE_BLK0 19 1 56 RD_DIS.FLASH_CRYPT_CONFIG EFUSE_BLK0 19 1 57 RD_DIS.CODING_SCHEME EFUSE_BLK0 19 1 58 RD_DIS.KEY_STATUS EFUSE_BLK0 19 1 59 FLASH_CRYPT_CNT EFUSE_BLK0 20 7 60 UART_DOWNLOAD_DIS EFUSE_BLK0 27 1 61 MAC EFUSE_BLK0 32 8 62 MAC EFUSE_BLK0 40 8 63 MAC EFUSE_BLK0 48 8 64 MAC EFUSE_BLK0 56 8 65 MAC EFUSE_BLK0 64 8 66 MAC EFUSE_BLK0 72 8 67 MAC_CRC EFUSE_BLK0 80 8 68 DISABLE_APP_CPU EFUSE_BLK0 96 1 69 DISABLE_BT EFUSE_BLK0 97 1 70 CHIP_PACKAGE_4BIT EFUSE_BLK0 98 1 71 DIS_CACHE EFUSE_BLK0 99 1 72 SPI_PAD_CONFIG_HD EFUSE_BLK0 100 5 73 CHIP_PACKAGE EFUSE_BLK0 105 3 74 CHIP_CPU_FREQ_LOW EFUSE_BLK0 108 1 75 CHIP_CPU_FREQ_RATED EFUSE_BLK0 109 1 76 BLK3_PART_RESERVE EFUSE_BLK0 110 1 77 CHIP_VER_REV1 EFUSE_BLK0 111 1 78 CLK8M_FREQ EFUSE_BLK0 128 8 79 ADC_VREF EFUSE_BLK0 136 5 80 XPD_SDIO_REG EFUSE_BLK0 142 1 81 XPD_SDIO_TIEH EFUSE_BLK0 143 1 82 XPD_SDIO_FORCE EFUSE_BLK0 144 1 83 SPI_PAD_CONFIG_CLK EFUSE_BLK0 160 5 84 SPI_PAD_CONFIG_Q EFUSE_BLK0 165 5 85 SPI_PAD_CONFIG_D EFUSE_BLK0 170 5 86 SPI_PAD_CONFIG_CS0 EFUSE_BLK0 175 5 87 CHIP_VER_REV2 EFUSE_BLK0 180 1 88 VOL_LEVEL_HP_INV EFUSE_BLK0 182 2 89 WAFER_VERSION_MINOR EFUSE_BLK0 184 2 90 FLASH_CRYPT_CONFIG EFUSE_BLK0 188 4 91 CODING_SCHEME EFUSE_BLK0 192 2 92 CONSOLE_DEBUG_DISABLE EFUSE_BLK0 194 1 93 DISABLE_SDIO_HOST EFUSE_BLK0 195 1 94 ABS_DONE_0 EFUSE_BLK0 196 1 95 ABS_DONE_1 EFUSE_BLK0 197 1 96 JTAG_DISABLE EFUSE_BLK0 198 1 97 DISABLE_DL_ENCRYPT EFUSE_BLK0 199 1 98 DISABLE_DL_DECRYPT EFUSE_BLK0 200 1 99 DISABLE_DL_CACHE EFUSE_BLK0 201 1 100 KEY_STATUS EFUSE_BLK0 202 1 101 BLOCK1 EFUSE_BLK1 0 192 102 BLOCK2 EFUSE_BLK2 0 192 103 CUSTOM_MAC_CRC EFUSE_BLK3 0 8 104 MAC_CUSTOM EFUSE_BLK3 8 48 105 ADC1_TP_LOW EFUSE_BLK3 96 7 106 ADC1_TP_HIGH EFUSE_BLK3 103 9 107 ADC2_TP_LOW EFUSE_BLK3 112 7 108 ADC2_TP_HIGH EFUSE_BLK3 119 9 109 SECURE_VERSION EFUSE_BLK3 128 32 110 MAC_VERSION EFUSE_BLK3 184 8 Used bits in efuse table: EFUSE_BLK0 [0 15] [0 2] [2 3] ... [19 19] [19 27] [32 87] [96 111] [128 140] [142 144] [160 180] [182 185] [188 202] EFUSE_BLK1 [0 191] EFUSE_BLK2 [0 191] EFUSE_BLK3 [0 55] [96 159] [184 191] Note: Not printed ranges are free for using. (bits in EFUSE_BLK0 are reserved for Espressif) The number of bits not included in square brackets is free (some bits are reserved for Espressif). All fields are checked for overlapping. To add fields to an existing field, use the Structured efuse fields technique. For example, adding the fields: SERIAL_NUMBER, MODEL_NUMBER and HARDWARE REV to an existing USER_DATA field. Use . (dot) to show an attachment in a field. USER_DATA.SERIAL_NUMBER, EFUSE_BLK3, 0, 32, USER_DATA.MODEL_NUMBER, EFUSE_BLK3, 32, 10, USER_DATA.HARDWARE_REV, EFUSE_BLK3, 42, 10, Fill a line for field: field_name, efuse_block, bit_start, bit_count, comment. Run a show_efuse_table command to check eFuse table. To generate source files run efuse_common_table or efuse_custom_table command. You may get errors such as intersects with or out of range . Please see how to solve them in the Structured efuse fields article. Bit Order The eFuses bit order is little endian (see the example below), it means that eFuse bits are read and written from LSB to MSB: $ espefuse.py dump USER_DATA (BLOCK3 ) [3 ] read_regs: 03020100 07060504 0B0A0908 0F0E0D0C 13121111 17161514 1B1A1918 1F1E1D1C BLOCK4 (BLOCK4 ) [4 ] read_regs: 03020100 07060504 0B0A0908 0F0E0D0C 13121111 17161514 1B1A1918 1F1E1D1C where is the register representation: EFUSE_RD_USR_DATA0_REG = 0x03020100 EFUSE_RD_USR_DATA1_REG = 0x07060504 EFUSE_RD_USR_DATA2_REG = 0x0B0A0908 EFUSE_RD_USR_DATA3_REG = 0x0F0E0D0C EFUSE_RD_USR_DATA4_REG = 0x13121111 EFUSE_RD_USR_DATA5_REG = 0x17161514 EFUSE_RD_USR_DATA6_REG = 0x1B1A1918 EFUSE_RD_USR_DATA7_REG = 0x1F1E1D1C where is the byte representation: byte[0] = 0x00, byte[1] = 0x01, ... byte[3] = 0x03, byte[4] = 0x04, ..., byte[31] = 0x1F For example, csv file describes the USER_DATA field, which occupies all 256 bits (a whole block). USER_DATA, EFUSE_BLK3, 0, 256, User data USER_DATA.FIELD1, EFUSE_BLK3, 16, 16, Field1 ID, EFUSE_BLK4, 8, 3, ID bit[0..2] , EFUSE_BLK4, 16, 2, ID bit[3..4] , EFUSE_BLK4, 32, 3, ID bit[5..7] Thus, reading the eFuse USER_DATA block written as above gives the following results: uint8_t buf[32] = { 0 }; esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA, &buf, sizeof(buf) * 8); // buf[0] = 0x00, buf[1] = 0x01, ... buf[31] = 0x1F uint32_t field1 = 0; size_t field1_size = ESP_EFUSE_USER_DATA[0]->bit_count; // can be used for this case because it only consists of one entry esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA, &field1, field1_size); // field1 = 0x0302 uint32_t field1_1 = 0; esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA, &field1_1, 2); // reads only first 2 bits // field1 = 0x0002 uint8_t id = 0; size_t id_size = esp_efuse_get_field_size(ESP_EFUSE_ID); // returns 6 // size_t id_size = ESP_EFUSE_USER_DATA[0]->bit_count; // cannot be used because it consists of 3 entries. It returns 3 not 6. esp_efuse_read_field_blob(ESP_EFUSE_ID, &id, id_size); // id = 0x91 // b'100 10 001 // [3] [2] [3] uint8_t id_1 = 0; esp_efuse_read_field_blob(ESP_EFUSE_ID, &id_1, 3); // id = 0x01 // b'001 Get eFuses During Build There is a way to get the state of eFuses at the build stage of the project. There are two cmake functions for this: espefuse_get_json_summary() - It calls the espefuse.py summary --format json command and returns a json string (it is not stored in a file). espefuse_get_efuse() - It finds a given eFuse name in the json string and returns its property. The json string has the following properties: { "MAC": { "bit_len": 48, "block": 0, "category": "identity", "description": "Factory MAC Address", "efuse_type": "bytes:6", "name": "MAC", "pos": 0, "readable": true, "value": "94:b9:7e:5a:6e:58 (CRC 0xe2 OK)", "word": 1, "writeable": true }, } These functions can be used from a top-level project CMakeLists.txt (get-started/hello_world/CMakeLists.txt): # ... project(hello_world) espefuse_get_json_summary(efuse_json) espefuse_get_efuse(ret_data ${efuse_json} "MAC" "value") message("MAC:" ${ret_data}) The format of the value property is the same as shown in espefuse.py summary . MAC:94:b9:7e:5a:6e:58 (CRC 0xe2 OK) There is an example test system/efuse/CMakeLists.txt which adds a custom target efuse-summary . This allows you to run the idf.py efuse-summary command to read the required eFuses (specified in the efuse_names list) at any time, not just at project build time. Debug eFuse & Unit Tests Virtual eFuses The Kconfig option CONFIG_EFUSE_VIRTUAL virtualizes eFuse values inside the eFuse Manager, so writes are emulated and no eFuse values are permanently changed. This can be useful for debugging app and unit tests. During startup, the eFuses are copied to RAM. All eFuse operations (read and write) are performed with RAM instead of the real eFuse registers. In addition to the CONFIG_EFUSE_VIRTUAL option there is CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH option that adds a feature to keep eFuses in flash memory. To use this mode the partition_table should have the efuse partition. partition.csv: "efuse_em, data, efuse,   ,   0x2000," . During startup, the eFuses are copied from flash or, in case if flash is empty, from real eFuse to RAM and then update flash. This option allows keeping eFuses after reboots (possible to test secure_boot and flash_encryption features with this option). Flash Encryption Testing Flash Encryption (FE) is a hardware feature that requires the physical burning of eFuses: key and FLASH_CRYPT_CNT. If FE is not actually enabled then enabling the CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH option just gives testing possibilities and does not encrypt anything in the flash, even though the logs say encryption happens. The bootloader_flash_write() is adapted for this purpose. But if FE is already enabled on the chip and you run an application or bootloader created with the CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH option then the flash encryption/decryption operations will work properly (data are encrypted as it is written into an encrypted flash partition and decrypted when they are read from an encrypted partition). espefuse.py  espefuse.py  esptool includes a useful tool for reading/writing ESP32 eFuse bits - espefuse.py. espefuse.py -p PORT summary espefuse.py v4.6-dev Connecting.... Detecting chip type... Unsupported detection protocol, switching and trying again... Connecting..... Detecting chip type... ESP32 === Run "summary" command === EFUSE_NAME (Block) Description = [Meaningful Value] [Readable/Writeable] (Hex Value) ---------------------------------------------------------------------------------------- Calibration fuses: ADC_VREF (BLOCK0) True ADC reference voltage = 1121 R/W (0b00011) Config fuses: WR_DIS (BLOCK0) Efuse write disable mask = 0 R/W (0x0000) RD_DIS (BLOCK0) Disable reading from BlOCK1-3 = 0 R/W (0x0) DISABLE_APP_CPU (BLOCK0) Disables APP CPU = False R/W (0b0) DISABLE_BT (BLOCK0) Disables Bluetooth = False R/W (0b0) DIS_CACHE (BLOCK0) Disables cache = False R/W (0b0) CHIP_CPU_FREQ_LOW (BLOCK0) If set alongside EFUSE_RD_CHIP_CPU_FREQ_RATED; the = False R/W (0b0) ESP32's max CPU frequency is rated for 160MHz. 24 0MHz otherwise CHIP_CPU_FREQ_RATED (BLOCK0) If set; the ESP32's maximum CPU frequency has been = True R/W (0b1) rated BLK3_PART_RESERVE (BLOCK0) BLOCK3 partially served for ADC calibration data = False R/W (0b0) CLK8M_FREQ (BLOCK0) 8MHz clock freq override = 51 R/W (0x33) VOL_LEVEL_HP_INV (BLOCK0) This field stores the voltage level for CPU to run = 0 R/W (0b00) at 240 MHz; or for flash/PSRAM to run at 80 MHz.0 x0: level 7; 0x1: level 6; 0x2: level 5; 0x3: leve l 4. (RO) CODING_SCHEME (BLOCK0) Efuse variable block length scheme = NONE (BLK1-3 len=256 bits) R/W (0b00) CONSOLE_DEBUG_DISABLE (BLOCK0) Disable ROM BASIC interpreter fallback = True R/W (0b1) DISABLE_SDIO_HOST (BLOCK0) = False R/W (0b0) DISABLE_DL_CACHE (BLOCK0) Disable flash cache in UART bootloader = False R/W (0b0) Flash fuses: FLASH_CRYPT_CNT (BLOCK0) Flash encryption is enabled if this field has an o = 0 R/W (0b0000000) dd number of bits set FLASH_CRYPT_CONFIG (BLOCK0) Flash encryption config (key tweak bits) = 0 R/W (0x0) Identity fuses: CHIP_PACKAGE_4BIT (BLOCK0) Chip package identifier #4bit = False R/W (0b0) CHIP_PACKAGE (BLOCK0) Chip package identifier = 1 R/W (0b001) CHIP_VER_REV1 (BLOCK0) bit is set to 1 for rev1 silicon = True R/W (0b1) CHIP_VER_REV2 (BLOCK0) = True R/W (0b1) WAFER_VERSION_MINOR (BLOCK0) = 0 R/W (0b00) WAFER_VERSION_MAJOR (BLOCK0) calc WAFER VERSION MAJOR from CHIP_VER_REV1 and CH = 3 R/W (0b011) IP_VER_REV2 and apb_ctl_date (read only) PKG_VERSION (BLOCK0) calc Chip package = CHIP_PACKAGE_4BIT << 3 + CHIP_ = 1 R/W (0x1) PACKAGE (read only) Jtag fuses: JTAG_DISABLE (BLOCK0) Disable JTAG = False R/W (0b0) Mac fuses: MAC (BLOCK0) MAC address = 94:b9:7e:5a:6e:58 (CRC 0xe2 OK) R/W MAC_CRC (BLOCK0) CRC8 for MAC address = 226 R/W (0xe2) MAC_VERSION (BLOCK3) Version of the MAC field = 0 R/W (0x00) Security fuses: UART_DOWNLOAD_DIS (BLOCK0) Disable UART download mode. Valid for ESP32 V3 and = False R/W (0b0) newer; only ABS_DONE_0 (BLOCK0) Secure boot V1 is enabled for bootloader image = False R/W (0b0) ABS_DONE_1 (BLOCK0) Secure boot V2 is enabled for bootloader image = False R/W (0b0) DISABLE_DL_ENCRYPT (BLOCK0) Disable flash encryption in UART bootloader = False R/W (0b0) DISABLE_DL_DECRYPT (BLOCK0) Disable flash decryption in UART bootloader = False R/W (0b0) KEY_STATUS (BLOCK0) Usage of efuse block 3 (reserved) = False R/W (0b0) SECURE_VERSION (BLOCK3) Secure version for anti-rollback = 0 R/W (0x00000000) BLOCK1 (BLOCK1) Flash encryption key = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 R/W BLOCK2 (BLOCK2) Security boot key = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 R/W BLOCK3 (BLOCK3) Variable Block 3 = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 R/W Spi Pad fuses: SPI_PAD_CONFIG_HD (BLOCK0) read for SPI_pad_config_hd = 0 R/W (0b00000) SPI_PAD_CONFIG_CLK (BLOCK0) Override SD_CLK pad (GPIO6/SPICLK) = 0 R/W (0b00000) SPI_PAD_CONFIG_Q (BLOCK0) Override SD_DATA_0 pad (GPIO7/SPIQ) = 0 R/W (0b00000) SPI_PAD_CONFIG_D (BLOCK0) Override SD_DATA_1 pad (GPIO8/SPID) = 0 R/W (0b00000) SPI_PAD_CONFIG_CS0 (BLOCK0) Override SD_CMD pad (GPIO11/SPICS0) = 0 R/W (0b00000) Vdd fuses: XPD_SDIO_REG (BLOCK0) read for XPD_SDIO_REG = False R/W (0b0) XPD_SDIO_TIEH (BLOCK0) If XPD_SDIO_FORCE & XPD_SDIO_REG = 1.8V R/W (0b0) XPD_SDIO_FORCE (BLOCK0) Ignore MTDI pin (GPIO12) for VDD_SDIO on reset = False R/W (0b0) Flash voltage (VDD_SDIO) determined by GPIO12 on reset (High for 1.8V, Low/NC for 3.3V) To get a dump for all eFuse registers. espefuse.py -p PORT dump espefuse.py v4.6-dev Connecting.... Detecting chip type... Unsupported detection protocol, switching and trying again... Connecting....... Detecting chip type... ESP32 BLOCK0 ( ) [0 ] read_regs: 00000000 7e5a6e58 00e294b9 0000a200 00000333 00100000 00000004 BLOCK1 (flash_encryption) [1 ] read_regs: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 BLOCK2 (secure_boot_v1 s) [2 ] read_regs: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 BLOCK3 ( ) [3 ] read_regs: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 EFUSE_REG_DEC_STATUS 0x00000000 === Run "dump" command === Header File This header file can be included with: #include "esp_efuse_chip.h" This header file is a part of the API provided by the efuse component. To declare that your component depends on efuse , add the following to your CMakeLists.txt: REQUIRES efuse or PRIV_REQUIRES efuse Enumerations enum esp_efuse_block_t Type of eFuse blocks for ESP32. Values: enumerator EFUSE_BLK0 Number of eFuse block. Reserved. enumerator EFUSE_BLK0 Number of eFuse block. Reserved. enumerator EFUSE_BLK1 Number of eFuse block. Used for Flash Encryption. If not using that Flash Encryption feature, they can be used for another purpose. enumerator EFUSE_BLK1 Number of eFuse block. Used for Flash Encryption. If not using that Flash Encryption feature, they can be used for another purpose. enumerator EFUSE_BLK_KEY0 Number of eFuse block. Used for Flash Encryption. If not using that Flash Encryption feature, they can be used for another purpose. enumerator EFUSE_BLK_KEY0 Number of eFuse block. Used for Flash Encryption. If not using that Flash Encryption feature, they can be used for another purpose. enumerator EFUSE_BLK_ENCRYPT_FLASH Number of eFuse block. Used for Flash Encryption. If not using that Flash Encryption feature, they can be used for another purpose. enumerator EFUSE_BLK_ENCRYPT_FLASH Number of eFuse block. Used for Flash Encryption. If not using that Flash Encryption feature, they can be used for another purpose. enumerator EFUSE_BLK2 Number of eFuse block. Used for Secure Boot. If not using that Secure Boot feature, they can be used for another purpose. enumerator EFUSE_BLK2 Number of eFuse block. Used for Secure Boot. If not using that Secure Boot feature, they can be used for another purpose. enumerator EFUSE_BLK_KEY1 Number of eFuse block. Used for Secure Boot. If not using that Secure Boot feature, they can be used for another purpose. enumerator EFUSE_BLK_KEY1 Number of eFuse block. Used for Secure Boot. If not using that Secure Boot feature, they can be used for another purpose. enumerator EFUSE_BLK_SECURE_BOOT Number of eFuse block. Used for Secure Boot. If not using that Secure Boot feature, they can be used for another purpose. enumerator EFUSE_BLK_SECURE_BOOT Number of eFuse block. Used for Secure Boot. If not using that Secure Boot feature, they can be used for another purpose. enumerator EFUSE_BLK3 Number of eFuse block. Uses for the purpose of the user. enumerator EFUSE_BLK3 Number of eFuse block. Uses for the purpose of the user. enumerator EFUSE_BLK_KEY2 Number of eFuse block. Uses for the purpose of the user. enumerator EFUSE_BLK_KEY2 Number of eFuse block. Uses for the purpose of the user. enumerator EFUSE_BLK_KEY_MAX enumerator EFUSE_BLK_KEY_MAX enumerator EFUSE_BLK_MAX enumerator EFUSE_BLK_MAX enumerator EFUSE_BLK0 enum esp_efuse_coding_scheme_t Type of coding scheme. Values: enumerator EFUSE_CODING_SCHEME_NONE None enumerator EFUSE_CODING_SCHEME_NONE None enumerator EFUSE_CODING_SCHEME_3_4 3/4 coding enumerator EFUSE_CODING_SCHEME_3_4 3/4 coding enumerator EFUSE_CODING_SCHEME_REPEAT Repeat coding enumerator EFUSE_CODING_SCHEME_REPEAT Repeat coding enumerator EFUSE_CODING_SCHEME_NONE enum esp_efuse_purpose_t Type of key purpose (virtual because ESP32 has only fixed purposes for blocks) Values: enumerator ESP_EFUSE_KEY_PURPOSE_USER BLOCK3 enumerator ESP_EFUSE_KEY_PURPOSE_USER BLOCK3 enumerator ESP_EFUSE_KEY_PURPOSE_SYSTEM BLOCK0 enumerator ESP_EFUSE_KEY_PURPOSE_SYSTEM BLOCK0 enumerator ESP_EFUSE_KEY_PURPOSE_FLASH_ENCRYPTION BLOCK1 enumerator ESP_EFUSE_KEY_PURPOSE_FLASH_ENCRYPTION BLOCK1 enumerator ESP_EFUSE_KEY_PURPOSE_SECURE_BOOT_V2 BLOCK2 enumerator ESP_EFUSE_KEY_PURPOSE_SECURE_BOOT_V2 BLOCK2 enumerator ESP_EFUSE_KEY_PURPOSE_MAX MAX PURPOSE enumerator ESP_EFUSE_KEY_PURPOSE_MAX MAX PURPOSE enumerator ESP_EFUSE_KEY_PURPOSE_USER Header File This header file can be included with: #include "esp_efuse.h" This header file is a part of the API provided by the efuse component. To declare that your component depends on efuse , add the following to your CMakeLists.txt: REQUIRES efuse or PRIV_REQUIRES efuse Functions esp_err_t esp_efuse_read_field_blob(const esp_efuse_desc_t *field[], void *dst, size_t dst_size_bits) Reads bits from EFUSE field and writes it into an array. The number of read bits will be limited to the minimum value from the description of the bits in "field" structure or "dst_size_bits" required size. Use "esp_efuse_get_field_size()" function to determine the length of the field. Note Please note that reading in the batch mode does not show uncommitted changes. Parameters field -- [in] A pointer to the structure describing the fields of efuse. dst -- [out] A pointer to array that will contain the result of reading. dst_size_bits -- [in] The number of bits required to read. If the requested number of bits is greater than the field, the number will be limited to the field size. field -- [in] A pointer to the structure describing the fields of efuse. dst -- [out] A pointer to array that will contain the result of reading. dst_size_bits -- [in] The number of bits required to read. If the requested number of bits is greater than the field, the number will be limited to the field size. field -- [in] A pointer to the structure describing the fields of efuse. Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_OK: The operation was successfully completed. Parameters field -- [in] A pointer to the structure describing the fields of efuse. dst -- [out] A pointer to array that will contain the result of reading. dst_size_bits -- [in] The number of bits required to read. If the requested number of bits is greater than the field, the number will be limited to the field size. Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. bool esp_efuse_read_field_bit(const esp_efuse_desc_t *field[]) Read a single bit eFuse field as a boolean value. Note The value must exist and must be a single bit wide. If there is any possibility of an error in the provided arguments, call esp_efuse_read_field_blob() and check the returned value instead. Note If assertions are enabled and the parameter is invalid, execution will abort Note Please note that reading in the batch mode does not show uncommitted changes. Parameters field -- [in] A pointer to the structure describing the fields of efuse. Returns true: The field parameter is valid and the bit is set. false: The bit is not set, or the parameter is invalid and assertions are disabled. true: The field parameter is valid and the bit is set. false: The bit is not set, or the parameter is invalid and assertions are disabled. true: The field parameter is valid and the bit is set. Parameters field -- [in] A pointer to the structure describing the fields of efuse. Returns true: The field parameter is valid and the bit is set. false: The bit is not set, or the parameter is invalid and assertions are disabled. esp_err_t esp_efuse_read_field_cnt(const esp_efuse_desc_t *field[], size_t *out_cnt) Reads bits from EFUSE field and returns number of bits programmed as "1". If the bits are set not sequentially, they will still be counted. Note Please note that reading in the batch mode does not show uncommitted changes. Parameters field -- [in] A pointer to the structure describing the fields of efuse. out_cnt -- [out] A pointer that will contain the number of programmed as "1" bits. field -- [in] A pointer to the structure describing the fields of efuse. out_cnt -- [out] A pointer that will contain the number of programmed as "1" bits. field -- [in] A pointer to the structure describing the fields of efuse. Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_OK: The operation was successfully completed. Parameters field -- [in] A pointer to the structure describing the fields of efuse. out_cnt -- [out] A pointer that will contain the number of programmed as "1" bits. Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. esp_err_t esp_efuse_write_field_blob(const esp_efuse_desc_t *field[], const void *src, size_t src_size_bits) Writes array to EFUSE field. The number of write bits will be limited to the minimum value from the description of the bits in "field" structure or "src_size_bits" required size. Use "esp_efuse_get_field_size()" function to determine the length of the field. After the function is completed, the writing registers are cleared. Parameters field -- [in] A pointer to the structure describing the fields of efuse. src -- [in] A pointer to array that contains the data for writing. src_size_bits -- [in] The number of bits required to write. field -- [in] A pointer to the structure describing the fields of efuse. src -- [in] A pointer to array that contains the data for writing. src_size_bits -- [in] The number of bits required to write. field -- [in] A pointer to the structure describing the fields of efuse. Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_OK: The operation was successfully completed. Parameters field -- [in] A pointer to the structure describing the fields of efuse. src -- [in] A pointer to array that contains the data for writing. src_size_bits -- [in] The number of bits required to write. Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. esp_err_t esp_efuse_write_field_cnt(const esp_efuse_desc_t *field[], size_t cnt) Writes a required count of bits as "1" to EFUSE field. If there are no free bits in the field to set the required number of bits to "1", ESP_ERR_EFUSE_CNT_IS_FULL error is returned, the field will not be partially recorded. After the function is completed, the writing registers are cleared. Parameters field -- [in] A pointer to the structure describing the fields of efuse. cnt -- [in] Required number of programmed as "1" bits. field -- [in] A pointer to the structure describing the fields of efuse. cnt -- [in] Required number of programmed as "1" bits. field -- [in] A pointer to the structure describing the fields of efuse. Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. ESP_OK: The operation was successfully completed. Parameters field -- [in] A pointer to the structure describing the fields of efuse. cnt -- [in] Required number of programmed as "1" bits. Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. esp_err_t esp_efuse_write_field_bit(const esp_efuse_desc_t *field[]) Write a single bit eFuse field to 1. For use with eFuse fields that are a single bit. This function will write the bit to value 1 if it is not already set, or does nothing if the bit is already set. This is equivalent to calling esp_efuse_write_field_cnt() with the cnt parameter equal to 1, except that it will return ESP_OK if the field is already set to 1. Parameters field -- [in] Pointer to the structure describing the efuse field. Returns ESP_OK: The operation was successfully completed, or the bit was already set to value 1. ESP_ERR_INVALID_ARG: Error in the passed arugments, including if the efuse field is not 1 bit wide. ESP_OK: The operation was successfully completed, or the bit was already set to value 1. ESP_ERR_INVALID_ARG: Error in the passed arugments, including if the efuse field is not 1 bit wide. ESP_OK: The operation was successfully completed, or the bit was already set to value 1. Parameters field -- [in] Pointer to the structure describing the efuse field. Returns ESP_OK: The operation was successfully completed, or the bit was already set to value 1. ESP_ERR_INVALID_ARG: Error in the passed arugments, including if the efuse field is not 1 bit wide. esp_err_t esp_efuse_set_write_protect(esp_efuse_block_t blk) Sets a write protection for the whole block. After that, it is impossible to write to this block. The write protection does not apply to block 0. Parameters blk -- [in] Block number of eFuse. (EFUSE_BLK1, EFUSE_BLK2 and EFUSE_BLK3) Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. ESP_ERR_NOT_SUPPORTED: The block does not support this command. ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. ESP_ERR_NOT_SUPPORTED: The block does not support this command. ESP_OK: The operation was successfully completed. Parameters blk -- [in] Block number of eFuse. (EFUSE_BLK1, EFUSE_BLK2 and EFUSE_BLK3) Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. ESP_ERR_NOT_SUPPORTED: The block does not support this command. esp_err_t esp_efuse_set_read_protect(esp_efuse_block_t blk) Sets a read protection for the whole block. After that, it is impossible to read from this block. The read protection does not apply to block 0. Parameters blk -- [in] Block number of eFuse. (EFUSE_BLK1, EFUSE_BLK2 and EFUSE_BLK3) Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. ESP_ERR_NOT_SUPPORTED: The block does not support this command. ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. ESP_ERR_NOT_SUPPORTED: The block does not support this command. ESP_OK: The operation was successfully completed. Parameters blk -- [in] Block number of eFuse. (EFUSE_BLK1, EFUSE_BLK2 and EFUSE_BLK3) Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. ESP_ERR_NOT_SUPPORTED: The block does not support this command. int esp_efuse_get_field_size(const esp_efuse_desc_t *field[]) Returns the number of bits used by field. Parameters field -- [in] A pointer to the structure describing the fields of efuse. Returns Returns the number of bits used by field. Parameters field -- [in] A pointer to the structure describing the fields of efuse. Returns Returns the number of bits used by field. uint32_t esp_efuse_read_reg(esp_efuse_block_t blk, unsigned int num_reg) Returns value of efuse register. This is a thread-safe implementation. Example: EFUSE_BLK2_RDATA3_REG where (blk=2, num_reg=3) Note Please note that reading in the batch mode does not show uncommitted changes. Parameters blk -- [in] Block number of eFuse. num_reg -- [in] The register number in the block. blk -- [in] Block number of eFuse. num_reg -- [in] The register number in the block. blk -- [in] Block number of eFuse. Returns Value of register Parameters blk -- [in] Block number of eFuse. num_reg -- [in] The register number in the block. Returns Value of register esp_err_t esp_efuse_write_reg(esp_efuse_block_t blk, unsigned int num_reg, uint32_t val) Write value to efuse register. Apply a coding scheme if necessary. This is a thread-safe implementation. Example: EFUSE_BLK3_WDATA0_REG where (blk=3, num_reg=0) Parameters blk -- [in] Block number of eFuse. num_reg -- [in] The register number in the block. val -- [in] Value to write. blk -- [in] Block number of eFuse. num_reg -- [in] The register number in the block. val -- [in] Value to write. blk -- [in] Block number of eFuse. Returns ESP_OK: The operation was successfully completed. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_OK: The operation was successfully completed. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_OK: The operation was successfully completed. Parameters blk -- [in] Block number of eFuse. num_reg -- [in] The register number in the block. val -- [in] Value to write. Returns ESP_OK: The operation was successfully completed. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. esp_efuse_coding_scheme_t esp_efuse_get_coding_scheme(esp_efuse_block_t blk) Return efuse coding scheme for blocks. Note The coding scheme is applicable only to 1, 2 and 3 blocks. For 0 block, the coding scheme is always NONE . Parameters blk -- [in] Block number of eFuse. Returns Return efuse coding scheme for blocks Parameters blk -- [in] Block number of eFuse. Returns Return efuse coding scheme for blocks esp_err_t esp_efuse_read_block(esp_efuse_block_t blk, void *dst_key, size_t offset_in_bits, size_t size_bits) Read key to efuse block starting at the offset and the required size. Note Please note that reading in the batch mode does not show uncommitted changes. Parameters blk -- [in] Block number of eFuse. dst_key -- [in] A pointer to array that will contain the result of reading. offset_in_bits -- [in] Start bit in block. size_bits -- [in] The number of bits required to read. blk -- [in] Block number of eFuse. dst_key -- [in] A pointer to array that will contain the result of reading. offset_in_bits -- [in] Start bit in block. size_bits -- [in] The number of bits required to read. blk -- [in] Block number of eFuse. Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_OK: The operation was successfully completed. Parameters blk -- [in] Block number of eFuse. dst_key -- [in] A pointer to array that will contain the result of reading. offset_in_bits -- [in] Start bit in block. size_bits -- [in] The number of bits required to read. Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_CODING: Error range of data does not match the coding scheme. esp_err_t esp_efuse_write_block(esp_efuse_block_t blk, const void *src_key, size_t offset_in_bits, size_t size_bits) Write key to efuse block starting at the offset and the required size. Parameters blk -- [in] Block number of eFuse. src_key -- [in] A pointer to array that contains the key for writing. offset_in_bits -- [in] Start bit in block. size_bits -- [in] The number of bits required to write. blk -- [in] Block number of eFuse. src_key -- [in] A pointer to array that contains the key for writing. offset_in_bits -- [in] Start bit in block. size_bits -- [in] The number of bits required to write. blk -- [in] Block number of eFuse. Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits ESP_OK: The operation was successfully completed. Parameters blk -- [in] Block number of eFuse. src_key -- [in] A pointer to array that contains the key for writing. offset_in_bits -- [in] Start bit in block. size_bits -- [in] The number of bits required to write. Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits uint32_t esp_efuse_get_pkg_ver(void) Returns chip package from efuse. Returns chip package Returns chip package void esp_efuse_reset(void) Reset efuse write registers. Efuse write registers are written to zero, to negate any changes that have been staged here. Note This function is not threadsafe, if calling code updates efuse values from multiple tasks then this is caller's responsibility to serialise. void esp_efuse_disable_basic_rom_console(void) Disable BASIC ROM Console via efuse. By default, if booting from flash fails the ESP32 will boot a BASIC console in ROM. Call this function (from bootloader or app) to permanently disable the console on this chip. esp_err_t esp_efuse_disable_rom_download_mode(void) Disable ROM Download Mode via eFuse. Permanently disables the ROM Download Mode feature. Once disabled, if the SoC is booted with strapping pins set for ROM Download Mode then an error is printed instead. Note Not all SoCs support this option. An error will be returned if called on an ESP32 with a silicon revision lower than 3, as these revisions do not support this option. Note If ROM Download Mode is already disabled, this function does nothing and returns success. Returns ESP_OK If the eFuse was successfully burned, or had already been burned. ESP_ERR_NOT_SUPPORTED (ESP32 only) This SoC is not capable of disabling UART download mode ESP_ERR_INVALID_STATE (ESP32 only) This eFuse is write protected and cannot be written ESP_OK If the eFuse was successfully burned, or had already been burned. ESP_ERR_NOT_SUPPORTED (ESP32 only) This SoC is not capable of disabling UART download mode ESP_ERR_INVALID_STATE (ESP32 only) This eFuse is write protected and cannot be written ESP_OK If the eFuse was successfully burned, or had already been burned. Returns ESP_OK If the eFuse was successfully burned, or had already been burned. ESP_ERR_NOT_SUPPORTED (ESP32 only) This SoC is not capable of disabling UART download mode ESP_ERR_INVALID_STATE (ESP32 only) This eFuse is write protected and cannot be written esp_err_t esp_efuse_set_rom_log_scheme(esp_efuse_rom_log_scheme_t log_scheme) Set boot ROM log scheme via eFuse. Note By default, the boot ROM will always print to console. This API can be called to set the log scheme only once per chip, once the value is changed from the default it can't be changed again. Parameters log_scheme -- Supported ROM log scheme Returns ESP_OK If the eFuse was successfully burned, or had already been burned. ESP_ERR_NOT_SUPPORTED (ESP32 only) This SoC is not capable of setting ROM log scheme ESP_ERR_INVALID_STATE This eFuse is write protected or has been burned already ESP_OK If the eFuse was successfully burned, or had already been burned. ESP_ERR_NOT_SUPPORTED (ESP32 only) This SoC is not capable of setting ROM log scheme ESP_ERR_INVALID_STATE This eFuse is write protected or has been burned already ESP_OK If the eFuse was successfully burned, or had already been burned. Parameters log_scheme -- Supported ROM log scheme Returns ESP_OK If the eFuse was successfully burned, or had already been burned. ESP_ERR_NOT_SUPPORTED (ESP32 only) This SoC is not capable of setting ROM log scheme ESP_ERR_INVALID_STATE This eFuse is write protected or has been burned already uint32_t esp_efuse_read_secure_version(void) Return secure_version from efuse field. Returns Secure version from efuse field Returns Secure version from efuse field bool esp_efuse_check_secure_version(uint32_t secure_version) Check secure_version from app and secure_version and from efuse field. Parameters secure_version -- Secure version from app. Returns True: If version of app is equal or more then secure_version from efuse. True: If version of app is equal or more then secure_version from efuse. True: If version of app is equal or more then secure_version from efuse. Parameters secure_version -- Secure version from app. Returns True: If version of app is equal or more then secure_version from efuse. esp_err_t esp_efuse_update_secure_version(uint32_t secure_version) Write efuse field by secure_version value. Update the secure_version value is available if the coding scheme is None. Note: Do not use this function in your applications. This function is called as part of the other API. Parameters secure_version -- [in] Secure version from app. Returns ESP_OK: Successful. ESP_FAIL: secure version of app cannot be set to efuse field. ESP_ERR_NOT_SUPPORTED: Anti rollback is not supported with the 3/4 and Repeat coding scheme. ESP_OK: Successful. ESP_FAIL: secure version of app cannot be set to efuse field. ESP_ERR_NOT_SUPPORTED: Anti rollback is not supported with the 3/4 and Repeat coding scheme. ESP_OK: Successful. Parameters secure_version -- [in] Secure version from app. Returns ESP_OK: Successful. ESP_FAIL: secure version of app cannot be set to efuse field. ESP_ERR_NOT_SUPPORTED: Anti rollback is not supported with the 3/4 and Repeat coding scheme. esp_err_t esp_efuse_batch_write_begin(void) Set the batch mode of writing fields. This mode allows you to write the fields in the batch mode when need to burn several efuses at one time. To enable batch mode call begin() then perform as usually the necessary operations read and write and at the end call commit() to actually burn all written efuses. The batch mode can be used nested. The commit will be done by the last commit() function. The number of begin() functions should be equal to the number of commit() functions. Note: If batch mode is enabled by the first task, at this time the second task cannot write/read efuses. The second task will wait for the first task to complete the batch operation. // Example of using the batch writing mode. // set the batch writing mode esp_efuse_batch_write_begin(); // use any writing functions as usual esp_efuse_write_field_blob(ESP_EFUSE_...); esp_efuse_write_field_cnt(ESP_EFUSE_...); esp_efuse_set_write_protect(EFUSE_BLKx); esp_efuse_write_reg(EFUSE_BLKx, ...); esp_efuse_write_block(EFUSE_BLKx, ...); esp_efuse_write(ESP_EFUSE_1, 3); // ESP_EFUSE_1 == 1, here we write a new value = 3. The changes will be burn by the commit() function. esp_efuse_read_...(ESP_EFUSE_1); // this function returns ESP_EFUSE_1 == 1 because uncommitted changes are not readable, it will be available only after commit. ... // esp_efuse_batch_write APIs can be called recursively. esp_efuse_batch_write_begin(); esp_efuse_set_write_protect(EFUSE_BLKx); esp_efuse_batch_write_commit(); // the burn will be skipped here, it will be done in the last commit(). ... // Write all of these fields to the efuse registers esp_efuse_batch_write_commit(); esp_efuse_read_...(ESP_EFUSE_1); // this function returns ESP_EFUSE_1 == 3. Note Please note that reading in the batch mode does not show uncommitted changes. Returns ESP_OK: Successful. ESP_OK: Successful. ESP_OK: Successful. Returns ESP_OK: Successful. esp_err_t esp_efuse_batch_write_cancel(void) Reset the batch mode of writing fields. It will reset the batch writing mode and any written changes. Returns ESP_OK: Successful. ESP_ERR_INVALID_STATE: Tha batch mode was not set. ESP_OK: Successful. ESP_ERR_INVALID_STATE: Tha batch mode was not set. ESP_OK: Successful. Returns ESP_OK: Successful. ESP_ERR_INVALID_STATE: Tha batch mode was not set. esp_err_t esp_efuse_batch_write_commit(void) Writes all prepared data for the batch mode. Must be called to ensure changes are written to the efuse registers. After this the batch writing mode will be reset. Returns ESP_OK: Successful. ESP_ERR_INVALID_STATE: The deferred writing mode was not set. ESP_OK: Successful. ESP_ERR_INVALID_STATE: The deferred writing mode was not set. ESP_OK: Successful. Returns ESP_OK: Successful. ESP_ERR_INVALID_STATE: The deferred writing mode was not set. bool esp_efuse_block_is_empty(esp_efuse_block_t block) Checks that the given block is empty. Returns True: The block is empty. False: The block is not empty or was an error. True: The block is empty. False: The block is not empty or was an error. True: The block is empty. Returns True: The block is empty. False: The block is not empty or was an error. bool esp_efuse_get_key_dis_read(esp_efuse_block_t block) Returns a read protection for the key block. Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX Returns True: The key block is read protected False: The key block is readable. Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX Returns True: The key block is read protected False: The key block is readable. esp_err_t esp_efuse_set_key_dis_read(esp_efuse_block_t block) Sets a read protection for the key block. Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX Returns ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_OK: Successful. Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX Returns ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. bool esp_efuse_get_key_dis_write(esp_efuse_block_t block) Returns a write protection for the key block. Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX Returns True: The key block is write protected False: The key block is writeable. Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX Returns True: The key block is write protected False: The key block is writeable. esp_err_t esp_efuse_set_key_dis_write(esp_efuse_block_t block) Sets a write protection for the key block. Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX Returns ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_OK: Successful. Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX Returns ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. bool esp_efuse_key_block_unused(esp_efuse_block_t block) Returns true if the key block is unused, false otherwise. An unused key block is all zero content, not read or write protected, and has purpose 0 (ESP_EFUSE_KEY_PURPOSE_USER) Parameters block -- key block to check. Returns True if key block is unused, False if key block is used or the specified block index is not a key block. True if key block is unused, False if key block is used or the specified block index is not a key block. True if key block is unused, Parameters block -- key block to check. Returns True if key block is unused, False if key block is used or the specified block index is not a key block. bool esp_efuse_find_purpose(esp_efuse_purpose_t purpose, esp_efuse_block_t *block) Find a key block with the particular purpose set. Parameters purpose -- [in] Purpose to search for. block -- [out] Pointer in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX which will be set to the key block if found. Can be NULL, if only need to test the key block exists. purpose -- [in] Purpose to search for. block -- [out] Pointer in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX which will be set to the key block if found. Can be NULL, if only need to test the key block exists. purpose -- [in] Purpose to search for. Returns True: If found, False: If not found (value at block pointer is unchanged). True: If found, False: If not found (value at block pointer is unchanged). True: If found, Parameters purpose -- [in] Purpose to search for. block -- [out] Pointer in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX which will be set to the key block if found. Can be NULL, if only need to test the key block exists. Returns True: If found, False: If not found (value at block pointer is unchanged). bool esp_efuse_get_keypurpose_dis_write(esp_efuse_block_t block) Returns a write protection of the key purpose field for an efuse key block. Note For ESP32: no keypurpose, it returns always True. Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX Returns True: The key purpose is write protected. False: The key purpose is writeable. Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX Returns True: The key purpose is write protected. False: The key purpose is writeable. esp_efuse_purpose_t esp_efuse_get_key_purpose(esp_efuse_block_t block) Returns the current purpose set for an efuse key block. Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX Returns Value: If Successful, it returns the value of the purpose related to the given key block. ESP_EFUSE_KEY_PURPOSE_MAX: Otherwise. Value: If Successful, it returns the value of the purpose related to the given key block. ESP_EFUSE_KEY_PURPOSE_MAX: Otherwise. Value: If Successful, it returns the value of the purpose related to the given key block. Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX Returns Value: If Successful, it returns the value of the purpose related to the given key block. ESP_EFUSE_KEY_PURPOSE_MAX: Otherwise. esp_err_t esp_efuse_write_key(esp_efuse_block_t block, esp_efuse_purpose_t purpose, const void *key, size_t key_size_bytes) Program a block of key data to an efuse block. The burn of a key, protection bits, and a purpose happens in batch mode. Note This API also enables the read protection efuse bit for certain key blocks like XTS-AES, HMAC, ECDSA etc. This ensures that the key is only accessible to hardware peripheral. Note For SoC's with capability SOC_EFUSE_ECDSA_USE_HARDWARE_K (e.g., ESP32-H2), this API writes an additional efuse bit for ECDSA key purpose to enforce hardware TRNG generated k mode in the peripheral. Parameters block -- [in] Block to read purpose for. Must be in range EFUSE_BLK_KEY0 to EFUSE_BLK_KEY_MAX. Key block must be unused (esp_efuse_key_block_unused). purpose -- [in] Purpose to set for this key. Purpose must be already unset. key -- [in] Pointer to data to write. key_size_bytes -- [in] Bytes length of data to write. block -- [in] Block to read purpose for. Must be in range EFUSE_BLK_KEY0 to EFUSE_BLK_KEY_MAX. Key block must be unused (esp_efuse_key_block_unused). purpose -- [in] Purpose to set for this key. Purpose must be already unset. key -- [in] Pointer to data to write. key_size_bytes -- [in] Bytes length of data to write. block -- [in] Block to read purpose for. Must be in range EFUSE_BLK_KEY0 to EFUSE_BLK_KEY_MAX. Key block must be unused (esp_efuse_key_block_unused). Returns ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_INVALID_STATE: Error in efuses state, unused block not found. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_INVALID_STATE: Error in efuses state, unused block not found. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_OK: Successful. Parameters block -- [in] Block to read purpose for. Must be in range EFUSE_BLK_KEY0 to EFUSE_BLK_KEY_MAX. Key block must be unused (esp_efuse_key_block_unused). purpose -- [in] Purpose to set for this key. Purpose must be already unset. key -- [in] Pointer to data to write. key_size_bytes -- [in] Bytes length of data to write. Returns ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_INVALID_STATE: Error in efuses state, unused block not found. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. esp_err_t esp_efuse_write_keys(const esp_efuse_purpose_t purposes[], uint8_t keys[][32], unsigned number_of_keys) Program keys to unused efuse blocks. The burn of keys, protection bits, and purposes happens in batch mode. Note This API also enables the read protection efuse bit for certain key blocks like XTS-AES, HMAC, ECDSA etc. This ensures that the key is only accessible to hardware peripheral. Note For SoC's with capability SOC_EFUSE_ECDSA_USE_HARDWARE_K (e.g., ESP32-H2), this API writes an additional efuse bit for ECDSA key purpose to enforce hardware TRNG generated k mode in the peripheral. Parameters purposes -- [in] Array of purposes (purpose[number_of_keys]). keys -- [in] Array of keys (uint8_t keys[number_of_keys][32]). Each key is 32 bytes long. number_of_keys -- [in] The number of keys to write (up to 6 keys). purposes -- [in] Array of purposes (purpose[number_of_keys]). keys -- [in] Array of keys (uint8_t keys[number_of_keys][32]). Each key is 32 bytes long. number_of_keys -- [in] The number of keys to write (up to 6 keys). purposes -- [in] Array of purposes (purpose[number_of_keys]). Returns ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_INVALID_STATE: Error in efuses state, unused block not found. ESP_ERR_NOT_ENOUGH_UNUSED_KEY_BLOCKS: Error not enough unused key blocks available ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_INVALID_STATE: Error in efuses state, unused block not found. ESP_ERR_NOT_ENOUGH_UNUSED_KEY_BLOCKS: Error not enough unused key blocks available ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_OK: Successful. Parameters purposes -- [in] Array of purposes (purpose[number_of_keys]). keys -- [in] Array of keys (uint8_t keys[number_of_keys][32]). Each key is 32 bytes long. number_of_keys -- [in] The number of keys to write (up to 6 keys). Returns ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_INVALID_STATE: Error in efuses state, unused block not found. ESP_ERR_NOT_ENOUGH_UNUSED_KEY_BLOCKS: Error not enough unused key blocks available ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. esp_err_t esp_efuse_check_errors(void) Checks eFuse errors in BLOCK0. It does a BLOCK0 check if eFuse EFUSE_ERR_RST_ENABLE is set. If BLOCK0 has an error, it prints the error and returns ESP_FAIL, which should be treated as esp_restart. Note Refers to ESP32-C3 only. Returns ESP_OK: No errors in BLOCK0. ESP_FAIL: Error in BLOCK0 requiring reboot. ESP_OK: No errors in BLOCK0. ESP_FAIL: Error in BLOCK0 requiring reboot. ESP_OK: No errors in BLOCK0. Returns ESP_OK: No errors in BLOCK0. ESP_FAIL: Error in BLOCK0 requiring reboot. Structures struct esp_efuse_desc_t Type definition for an eFuse field. Public Members esp_efuse_block_t efuse_block Block of eFuse esp_efuse_block_t efuse_block Block of eFuse uint8_t bit_start Start bit [0..255] uint8_t bit_start Start bit [0..255] uint16_t bit_count Length of bit field [1..-] uint16_t bit_count Length of bit field [1..-] esp_efuse_block_t efuse_block Macros ESP_ERR_EFUSE Base error code for efuse api. ESP_OK_EFUSE_CNT OK the required number of bits is set. ESP_ERR_EFUSE_CNT_IS_FULL Error field is full. ESP_ERR_EFUSE_REPEATED_PROG Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING Error while a encoding operation. ESP_ERR_NOT_ENOUGH_UNUSED_KEY_BLOCKS Error not enough unused key blocks available ESP_ERR_DAMAGED_READING Error. Burn or reset was done during a reading operation leads to damage read data. This error is internal to the efuse component and not returned by any public API. Enumerations enum esp_efuse_rom_log_scheme_t Type definition for ROM log scheme. Values: enumerator ESP_EFUSE_ROM_LOG_ALWAYS_ON Always enable ROM logging enumerator ESP_EFUSE_ROM_LOG_ALWAYS_ON Always enable ROM logging enumerator ESP_EFUSE_ROM_LOG_ON_GPIO_LOW ROM logging is enabled when specific GPIO level is low during start up enumerator ESP_EFUSE_ROM_LOG_ON_GPIO_LOW ROM logging is enabled when specific GPIO level is low during start up enumerator ESP_EFUSE_ROM_LOG_ON_GPIO_HIGH ROM logging is enabled when specific GPIO level is high during start up enumerator ESP_EFUSE_ROM_LOG_ON_GPIO_HIGH ROM logging is enabled when specific GPIO level is high during start up enumerator ESP_EFUSE_ROM_LOG_ALWAYS_OFF Disable ROM logging permanently enumerator ESP_EFUSE_ROM_LOG_ALWAYS_OFF Disable ROM logging permanently enumerator ESP_EFUSE_ROM_LOG_ALWAYS_ON
eFuse Manager Introduction The eFuse Manager library is designed to structure access to eFuse bits and make using these easy. This library operates eFuse bits by a structure name which is assigned in eFuse table. This sections introduces some concepts used by eFuse Manager. Hardware Description The ESP32 has a number of eFuses which can store system and user parameters. Each eFuse is a one-bit field which can be programmed to 1 after which it cannot be reverted back to 0. Some of system parameters are using these eFuse bits directly by hardware modules and have special place (for example EFUSE_BLK0). For more details, see ESP32 Technical Reference Manual > eFuse Controller (eFuse) [PDF]. Some eFuse bits are available for user applications. ESP32 has 4 eFuse blocks each of the size of 256 bits (not all bits are available): EFUSE_BLK0 is used entirely for system purposes; EFUSE_BLK1 is used for flash encrypt key. If not using that Flash Encryption feature, they can be used for another purpose; EFUSE_BLK2 is used for security boot key. If not using that Secure Boot feature, they can be used for another purpose; EFUSE_BLK3 can be partially reserved for the custom MAC address, or used entirely for user application. Note that some bits are already used in ESP-IDF. Each block is divided into 8 32-bits registers. eFuse Manager Component The component has API functions for reading and writing fields. Access to the fields is carried out through the structures that describe the location of the eFuse bits in the blocks. The component provides the ability to form fields of any length and from any number of individual bits. The description of the fields is made in a CSV file in a table form. To generate from a tabular form (CSV file) in the C-source uses the tool efuse_table_gen.py. The tool checks the CSV file for uniqueness of field names and bit intersection, in case of using a custom file from the user's project directory, the utility checks with the common CSV file. CSV files: common (esp_efuse_table.csv) - contains eFuse fields which are used inside the ESP-IDF. C-source generation should be done manually when changing this file (run command idf.py efuse-common-table). Note that changes in this file can lead to incorrect operation. custom - (optional and can be enabled by CONFIG_EFUSE_CUSTOM_TABLE) contains eFuse fields that are used by the user in their application. C-source generation should be done manually when changing this file and running idf.py efuse-custom-table. Description CSV File The CSV file contains a description of the eFuse fields. In the simple case, one field has one line of description. Table header: # field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count(1..256), comment Individual params in CSV file the following meanings: field_name Name of field. The prefix ESP_EFUSE_ is added to the name, and this field name is available in the code. This name is used to access the fields. The name must be unique for all fields. If the line has an empty name, then this line is combined with the previous field. This allows you to set an arbitrary order of bits in the field, and expand the field as well (see MAC_FACTORYfield in the common table). The field_name supports structured format using . to show that the field belongs to another field (see WR_DISand RD_DISin the common table). efuse_block Block number. It determines where the eFuse bits are placed for this field. Available EFUSE_BLK0..EFUSE_BLK3. bit_start Start bit number (0..255). The bit_start field can be omitted. In this case, it is set to bit_start + bit_count from the previous record, if it has the same efuse_block. Otherwise (if efuse_block is different, or this is the first entry), an error will be generated. bit_count The number of bits to use in this field (1..-). This parameter cannot be omitted. This field also may be MAX_BLK_LENin this case, the field length has the maximum block length, taking into account the coding scheme (applicable for ESP_EFUSE_SECURE_BOOT_KEYand ESP_EFUSE_ENCRYPT_FLASH_KEYfields). The value MAX_BLK_LENdepends on CONFIG_EFUSE_CODE_SCHEME_SELECTOR, which will be replaced with "None" - 256, "3/4" - 192, "REPEAT" - 128. comment This param is using for comment field, it also move to C-header file. The comment field can be omitted. If a non-sequential bit order is required to describe a field, then the field description in the following lines should be continued without specifying a name, indicating that it belongs to one field. For example two fields MAC_FACTORY and MAC_FACTORY_CRC: # Factory MAC address # ####################### MAC_FACTORY, EFUSE_BLK0, 72, 8, Factory MAC addr [0] , EFUSE_BLK0, 64, 8, Factory MAC addr [1] , EFUSE_BLK0, 56, 8, Factory MAC addr [2] , EFUSE_BLK0, 48, 8, Factory MAC addr [3] , EFUSE_BLK0, 40, 8, Factory MAC addr [4] , EFUSE_BLK0, 32, 8, Factory MAC addr [5] MAC_FACTORY_CRC, EFUSE_BLK0, 80, 8, CRC8 for factory MAC address This field is available in code as ESP_EFUSE_MAC_FACTORY and ESP_EFUSE_MAC_FACTORY_CRC. Structured eFuse Fields WR_DIS, EFUSE_BLK0, 0, 32, Write protection WR_DIS.RD_DIS, EFUSE_BLK0, 0, 1, Write protection for RD_DIS WR_DIS.FIELD_1, EFUSE_BLK0, 1, 1, Write protection for FIELD_1 WR_DIS.FIELD_2, EFUSE_BLK0, 2, 4, Write protection for FIELD_2 (includes B1 and B2) WR_DIS.FIELD_2.B1, EFUSE_BLK0, 2, 2, Write protection for FIELD_2.B1 WR_DIS.FIELD_2.B2, EFUSE_BLK0, 4, 2, Write protection for FIELD_2.B2 WR_DIS.FIELD_3, EFUSE_BLK0, 5, 1, Write protection for FIELD_3 WR_DIS.FIELD_3.ALIAS, EFUSE_BLK0, 5, 1, Write protection for FIELD_3 (just a alias for WR_DIS.FIELD_3) WR_DIS.FIELD_4, EFUSE_BLK0, 7, 1, Write protection for FIELD_4 The structured eFuse field looks like WR_DIS.RD_DIS where the dot points that this field belongs to the parent field - WR_DIS and cannot be out of the parent's range. It is possible to use some levels of structured fields as WR_DIS.FIELD_2.B1 and B2. These fields should not be crossed each other and should be in the range of two fields: WR_DIS and WR_DIS.FIELD_2. It is possible to create aliases for fields with the same range, see WR_DIS.FIELD_3 and WR_DIS.FIELD_3.ALIAS. The ESP-IDF names for structured eFuse fields should be unique. The efuse_table_gen tool generates the final names where the dot is replaced by _. The names for using in ESP-IDF are ESP_EFUSE_WR_DIS, ESP_EFUSE_WR_DIS_RD_DIS, ESP_EFUSE_WR_DIS_FIELD_2_B1, etc. The efuse_table_gen tool checks that the fields do not overlap each other and must be within the range of a field if there is a violation, then throws the following error: Field at USER_DATA, EFUSE_BLK3, 0, 256 intersected with SERIAL_NUMBER, EFUSE_BLK3, 0, 32 Solution: Describe SERIAL_NUMBER to be included in USER_DATA. ( USER_DATA.SERIAL_NUMBER). Field at FEILD, EFUSE_BLK3, 0, 50 out of range FEILD.MAJOR_NUMBER, EFUSE_BLK3, 60, 32 Solution: Change bit_start for FIELD.MAJOR_NUMBER from 60 to 0, so MAJOR_NUMBER is in the FEILD range. efuse_table_gen.py Tool The tool is designed to generate C-source files from CSV file and validate fields. First of all, the check is carried out on the uniqueness of the names and overlaps of the field bits. If an additional custom file is used, it will be checked with the existing common file (esp_efuse_table.csv). In case of errors, a message will be displayed and the string that caused the error. C-source files contain structures of type esp_efuse_desc_t. To generate a common files, use the following command idf.py efuse-common-table or: cd $IDF_PATH/components/efuse/ ./efuse_table_gen.py --idf_target esp32 esp32/esp_efuse_table.csv After generation in the folder $IDF_PATH/components/efuse/esp32 create: esp_efuse_table.c file. In include folder esp_efuse_table.c file. To generate a custom files, use the following command idf.py efuse-custom-table or: cd $IDF_PATH/components/efuse/ ./efuse_table_gen.py --idf_target esp32 esp32/esp_efuse_table.csv PROJECT_PATH/main/esp_efuse_custom_table.csv After generation in the folder PROJECT_PATH/main create: esp_efuse_custom_table.c file. In include folder esp_efuse_custom_table.c file. To use the generated fields, you need to include two files: #include "esp_efuse.h" #include "esp_efuse_table.h" // or "esp_efuse_custom_table.h" Supported Coding Scheme eFuse have three coding schemes: None(value 0). 3/4(value 1). Repeat(value 2). The coding scheme affects only EFUSE_BLK1, EFUSE_BLK2 and EFUSE_BLK3 blocks. EUSE_BLK0 block always has a coding scheme None. Coding changes the number of bits that can be written into a block, the block length is constant 256, some of these bits are used for encoding and not avaliable for the user. When using a coding scheme, the length of the payload that can be written is limited (for more details 20.3.1.3 System Parameter coding_scheme): None 256 bits. 3/4 192 bits. Repeat 128 bits. You can find out the coding scheme of your chip: run a espefuse.py -p PORT summarycommand. from esptoolutility logs (during flashing). calling the function in the code esp_efuse_get_coding_scheme()for the EFUSE_BLK3 block. eFuse tables must always comply with the coding scheme in the chip. There is an CONFIG_EFUSE_CODE_SCHEME_SELECTOR option to select the coding type for tables in a Kconfig. When generating source files, if your tables do not follow the coding scheme, an error message will be displayed. Adjust the length or offset fields. If your program was compiled with None encoding and 3/4 is used in the chip, then the ESP_ERR_CODING error may occur when calling the eFuse API (the field is outside the block boundaries). If the field matches the new block boundaries, then the API will work without errors. Also, 3/4 coding scheme imposes restrictions on writing bits belonging to one coding unit. The whole block with a length of 256 bits is divided into 4 coding units, and in each coding unit there are 6 bytes of useful data and 2 service bytes. These 2 service bytes contain the checksum of the previous 6 data bytes. It turns out that only one field can be written into one coding unit. Repeated rewriting in one coding unit is prohibited. But if the record was made in advance or through a esp_efuse_write_block() function, then reading the fields belonging to one coding unit is possible. In case 3/4 coding scheme, the writing process is divided into the coding units and we cannot use the usual mode of writing some fields. We can prepare all the data for writing and burn it in one time. You can also use this mode for None coding scheme but it is not necessary. It is important for 3/4 coding scheme. The batch writing mode blocks esp_efuse_read_... operations. After changing the coding scheme, run efuse_common_table and efuse_custom_table commands to check the tables of the new coding scheme. To write some fields into one block, or different blocks in one time, you need to use the batch writing mode. Firstly set this mode through esp_efuse_batch_write_begin() function then write some fields as usual using the esp_efuse_write_... functions. At the end to burn them, call the esp_efuse_batch_write_commit() function. It burns prepared data to the eFuse blocks and disables the batch recording mode. Note If there is already pre-written data in the eFuse block using the 3/4 or Repeat encoding scheme, then it is not possible to write anything extra (even if the required bits are empty) without breaking the previous encoding data. This encoding data will be overwritten with new encoding data and completely destroyed (however, the payload eFuses are not damaged). It can be related to: CUSTOM_MAC, SPI_PAD_CONFIG_HD, SPI_PAD_CONFIG_CS, etc. Please contact Espressif to order the required pre-burnt eFuses. FOR TESTING ONLY (NOT RECOMMENDED): You can ignore or suppress errors that violate encoding scheme data in order to burn the necessary bits in the eFuse block. eFuse API Access to the fields is via a pointer to the description structure. API functions have some basic operation: esp_efuse_read_field_blob()- returns an array of read eFuse bits. esp_efuse_read_field_cnt()- returns the number of bits programmed as "1". esp_efuse_write_field_blob()- writes an array. esp_efuse_write_field_cnt()- writes a required count of bits as "1". esp_efuse_get_field_size()- returns the number of bits by the field name. esp_efuse_read_reg()- returns value of eFuse register. esp_efuse_write_reg()- writes value to eFuse register. esp_efuse_get_coding_scheme()- returns eFuse coding scheme for blocks. esp_efuse_read_block()- reads key to eFuse block starting at the offset and the required size. esp_efuse_write_block()- writes key to eFuse block starting at the offset and the required size. esp_efuse_batch_write_begin()- set the batch mode of writing fields. esp_efuse_batch_write_commit()- writes all prepared data for batch writing mode and reset the batch writing mode. esp_efuse_batch_write_cancel()- reset the batch writing mode and prepared data. esp_efuse_get_key_dis_read()- Returns a read protection for the key block. esp_efuse_set_key_dis_read()- Sets a read protection for the key block. esp_efuse_get_key_dis_write()- Returns a write protection for the key block. esp_efuse_set_key_dis_write()- Sets a write protection for the key block. esp_efuse_get_key_purpose()- Returns the current purpose set for an eFuse key block. esp_efuse_write_key()- Programs a block of key data to an eFuse block esp_efuse_write_keys()- Programs keys to unused eFuse blocks esp_efuse_find_purpose()- Finds a key block with the particular purpose set. esp_efuse_get_keypurpose_dis_write()- Returns a write protection of the key purpose field for an eFuse key block (for esp32 always true). esp_efuse_key_block_unused()- Returns true if the key block is unused, false otherwise. For frequently used fields, special functions are made, like this esp_efuse_get_pkg_ver(). How to Add a New Field Find a free bits for field. Show esp_efuse_table.csv file or run idf.py show-efuse-tableor the next command: $ ./efuse_table_gen.py esp32/esp_efuse_table.csv --info Parsing efuse CSV input file $IDF_PATH/components/efuse/esp32/esp_efuse_table.csv ... Verifying efuse table... Max number of bits in BLK 192 Sorted efuse table: # field_name efuse_block bit_start bit_count 1 WR_DIS EFUSE_BLK0 0 16 2 WR_DIS.RD_DIS EFUSE_BLK0 0 1 3 WR_DIS.WR_DIS EFUSE_BLK0 1 1 4 WR_DIS.FLASH_CRYPT_CNT EFUSE_BLK0 2 1 5 WR_DIS.UART_DOWNLOAD_DIS EFUSE_BLK0 2 1 6 WR_DIS.MAC EFUSE_BLK0 3 1 7 WR_DIS.MAC_CRC EFUSE_BLK0 3 1 8 WR_DIS.DISABLE_APP_CPU EFUSE_BLK0 3 1 9 WR_DIS.DISABLE_BT EFUSE_BLK0 3 1 10 WR_DIS.DIS_CACHE EFUSE_BLK0 3 1 11 WR_DIS.VOL_LEVEL_HP_INV EFUSE_BLK0 3 1 12 WR_DIS.CLK8M_FREQ EFUSE_BLK0 4 1 13 WR_DIS.ADC_VREF EFUSE_BLK0 4 1 14 WR_DIS.XPD_SDIO_REG EFUSE_BLK0 5 1 15 WR_DIS.XPD_SDIO_TIEH EFUSE_BLK0 5 1 16 WR_DIS.XPD_SDIO_FORCE EFUSE_BLK0 5 1 17 WR_DIS.SPI_PAD_CONFIG_CLK EFUSE_BLK0 6 1 18 WR_DIS.SPI_PAD_CONFIG_Q EFUSE_BLK0 6 1 19 WR_DIS.SPI_PAD_CONFIG_D EFUSE_BLK0 6 1 20 WR_DIS.SPI_PAD_CONFIG_CS0 EFUSE_BLK0 6 1 21 WR_DIS.BLOCK1 EFUSE_BLK0 7 1 22 WR_DIS.BLOCK2 EFUSE_BLK0 8 1 23 WR_DIS.BLOCK3 EFUSE_BLK0 9 1 24 WR_DIS.CUSTOM_MAC_CRC EFUSE_BLK0 9 1 25 WR_DIS.CUSTOM_MAC EFUSE_BLK0 9 1 26 WR_DIS.ADC1_TP_LOW EFUSE_BLK0 9 1 27 WR_DIS.ADC1_TP_HIGH EFUSE_BLK0 9 1 28 WR_DIS.ADC2_TP_LOW EFUSE_BLK0 9 1 29 WR_DIS.ADC2_TP_HIGH EFUSE_BLK0 9 1 30 WR_DIS.SECURE_VERSION EFUSE_BLK0 9 1 31 WR_DIS.MAC_VERSION EFUSE_BLK0 9 1 32 WR_DIS.BLK3_PART_RESERVE EFUSE_BLK0 10 1 33 WR_DIS.FLASH_CRYPT_CONFIG EFUSE_BLK0 10 1 34 WR_DIS.CODING_SCHEME EFUSE_BLK0 10 1 35 WR_DIS.KEY_STATUS EFUSE_BLK0 10 1 36 WR_DIS.ABS_DONE_0 EFUSE_BLK0 12 1 37 WR_DIS.ABS_DONE_1 EFUSE_BLK0 13 1 38 WR_DIS.JTAG_DISABLE EFUSE_BLK0 14 1 39 WR_DIS.CONSOLE_DEBUG_DISABLE EFUSE_BLK0 15 1 40 WR_DIS.DISABLE_DL_ENCRYPT EFUSE_BLK0 15 1 41 WR_DIS.DISABLE_DL_DECRYPT EFUSE_BLK0 15 1 42 WR_DIS.DISABLE_DL_CACHE EFUSE_BLK0 15 1 43 RD_DIS EFUSE_BLK0 16 4 44 RD_DIS.BLOCK1 EFUSE_BLK0 16 1 45 RD_DIS.BLOCK2 EFUSE_BLK0 17 1 46 RD_DIS.BLOCK3 EFUSE_BLK0 18 1 47 RD_DIS.CUSTOM_MAC_CRC EFUSE_BLK0 18 1 48 RD_DIS.CUSTOM_MAC EFUSE_BLK0 18 1 49 RD_DIS.ADC1_TP_LOW EFUSE_BLK0 18 1 50 RD_DIS.ADC1_TP_HIGH EFUSE_BLK0 18 1 51 RD_DIS.ADC2_TP_LOW EFUSE_BLK0 18 1 52 RD_DIS.ADC2_TP_HIGH EFUSE_BLK0 18 1 53 RD_DIS.SECURE_VERSION EFUSE_BLK0 18 1 54 RD_DIS.MAC_VERSION EFUSE_BLK0 18 1 55 RD_DIS.BLK3_PART_RESERVE EFUSE_BLK0 19 1 56 RD_DIS.FLASH_CRYPT_CONFIG EFUSE_BLK0 19 1 57 RD_DIS.CODING_SCHEME EFUSE_BLK0 19 1 58 RD_DIS.KEY_STATUS EFUSE_BLK0 19 1 59 FLASH_CRYPT_CNT EFUSE_BLK0 20 7 60 UART_DOWNLOAD_DIS EFUSE_BLK0 27 1 61 MAC EFUSE_BLK0 32 8 62 MAC EFUSE_BLK0 40 8 63 MAC EFUSE_BLK0 48 8 64 MAC EFUSE_BLK0 56 8 65 MAC EFUSE_BLK0 64 8 66 MAC EFUSE_BLK0 72 8 67 MAC_CRC EFUSE_BLK0 80 8 68 DISABLE_APP_CPU EFUSE_BLK0 96 1 69 DISABLE_BT EFUSE_BLK0 97 1 70 CHIP_PACKAGE_4BIT EFUSE_BLK0 98 1 71 DIS_CACHE EFUSE_BLK0 99 1 72 SPI_PAD_CONFIG_HD EFUSE_BLK0 100 5 73 CHIP_PACKAGE EFUSE_BLK0 105 3 74 CHIP_CPU_FREQ_LOW EFUSE_BLK0 108 1 75 CHIP_CPU_FREQ_RATED EFUSE_BLK0 109 1 76 BLK3_PART_RESERVE EFUSE_BLK0 110 1 77 CHIP_VER_REV1 EFUSE_BLK0 111 1 78 CLK8M_FREQ EFUSE_BLK0 128 8 79 ADC_VREF EFUSE_BLK0 136 5 80 XPD_SDIO_REG EFUSE_BLK0 142 1 81 XPD_SDIO_TIEH EFUSE_BLK0 143 1 82 XPD_SDIO_FORCE EFUSE_BLK0 144 1 83 SPI_PAD_CONFIG_CLK EFUSE_BLK0 160 5 84 SPI_PAD_CONFIG_Q EFUSE_BLK0 165 5 85 SPI_PAD_CONFIG_D EFUSE_BLK0 170 5 86 SPI_PAD_CONFIG_CS0 EFUSE_BLK0 175 5 87 CHIP_VER_REV2 EFUSE_BLK0 180 1 88 VOL_LEVEL_HP_INV EFUSE_BLK0 182 2 89 WAFER_VERSION_MINOR EFUSE_BLK0 184 2 90 FLASH_CRYPT_CONFIG EFUSE_BLK0 188 4 91 CODING_SCHEME EFUSE_BLK0 192 2 92 CONSOLE_DEBUG_DISABLE EFUSE_BLK0 194 1 93 DISABLE_SDIO_HOST EFUSE_BLK0 195 1 94 ABS_DONE_0 EFUSE_BLK0 196 1 95 ABS_DONE_1 EFUSE_BLK0 197 1 96 JTAG_DISABLE EFUSE_BLK0 198 1 97 DISABLE_DL_ENCRYPT EFUSE_BLK0 199 1 98 DISABLE_DL_DECRYPT EFUSE_BLK0 200 1 99 DISABLE_DL_CACHE EFUSE_BLK0 201 1 100 KEY_STATUS EFUSE_BLK0 202 1 101 BLOCK1 EFUSE_BLK1 0 192 102 BLOCK2 EFUSE_BLK2 0 192 103 CUSTOM_MAC_CRC EFUSE_BLK3 0 8 104 MAC_CUSTOM EFUSE_BLK3 8 48 105 ADC1_TP_LOW EFUSE_BLK3 96 7 106 ADC1_TP_HIGH EFUSE_BLK3 103 9 107 ADC2_TP_LOW EFUSE_BLK3 112 7 108 ADC2_TP_HIGH EFUSE_BLK3 119 9 109 SECURE_VERSION EFUSE_BLK3 128 32 110 MAC_VERSION EFUSE_BLK3 184 8 Used bits in efuse table: EFUSE_BLK0 [0 15] [0 2] [2 3] ... [19 19] [19 27] [32 87] [96 111] [128 140] [142 144] [160 180] [182 185] [188 202] EFUSE_BLK1 [0 191] EFUSE_BLK2 [0 191] EFUSE_BLK3 [0 55] [96 159] [184 191] Note: Not printed ranges are free for using. (bits in EFUSE_BLK0 are reserved for Espressif) The number of bits not included in square brackets is free (some bits are reserved for Espressif). All fields are checked for overlapping. To add fields to an existing field, use the Structured efuse fields technique. For example, adding the fields: SERIAL_NUMBER, MODEL_NUMBER and HARDWARE REV to an existing USER_DATA field. Use . (dot) to show an attachment in a field. USER_DATA.SERIAL_NUMBER, EFUSE_BLK3, 0, 32, USER_DATA.MODEL_NUMBER, EFUSE_BLK3, 32, 10, USER_DATA.HARDWARE_REV, EFUSE_BLK3, 42, 10, Fill a line for field: field_name, efuse_block, bit_start, bit_count, comment. Run a show_efuse_tablecommand to check eFuse table. To generate source files run efuse_common_tableor efuse_custom_tablecommand. You may get errors such as intersects with or out of range. Please see how to solve them in the Structured efuse fields article. Bit Order The eFuses bit order is little endian (see the example below), it means that eFuse bits are read and written from LSB to MSB: $ espefuse.py dump USER_DATA (BLOCK3 ) [3 ] read_regs: 03020100 07060504 0B0A0908 0F0E0D0C 13121111 17161514 1B1A1918 1F1E1D1C BLOCK4 (BLOCK4 ) [4 ] read_regs: 03020100 07060504 0B0A0908 0F0E0D0C 13121111 17161514 1B1A1918 1F1E1D1C where is the register representation: EFUSE_RD_USR_DATA0_REG = 0x03020100 EFUSE_RD_USR_DATA1_REG = 0x07060504 EFUSE_RD_USR_DATA2_REG = 0x0B0A0908 EFUSE_RD_USR_DATA3_REG = 0x0F0E0D0C EFUSE_RD_USR_DATA4_REG = 0x13121111 EFUSE_RD_USR_DATA5_REG = 0x17161514 EFUSE_RD_USR_DATA6_REG = 0x1B1A1918 EFUSE_RD_USR_DATA7_REG = 0x1F1E1D1C where is the byte representation: byte[0] = 0x00, byte[1] = 0x01, ... byte[3] = 0x03, byte[4] = 0x04, ..., byte[31] = 0x1F For example, csv file describes the USER_DATA field, which occupies all 256 bits (a whole block). USER_DATA, EFUSE_BLK3, 0, 256, User data USER_DATA.FIELD1, EFUSE_BLK3, 16, 16, Field1 ID, EFUSE_BLK4, 8, 3, ID bit[0..2] , EFUSE_BLK4, 16, 2, ID bit[3..4] , EFUSE_BLK4, 32, 3, ID bit[5..7] Thus, reading the eFuse USER_DATA block written as above gives the following results: uint8_t buf[32] = { 0 }; esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA, &buf, sizeof(buf) * 8); // buf[0] = 0x00, buf[1] = 0x01, ... buf[31] = 0x1F uint32_t field1 = 0; size_t field1_size = ESP_EFUSE_USER_DATA[0]->bit_count; // can be used for this case because it only consists of one entry esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA, &field1, field1_size); // field1 = 0x0302 uint32_t field1_1 = 0; esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA, &field1_1, 2); // reads only first 2 bits // field1 = 0x0002 uint8_t id = 0; size_t id_size = esp_efuse_get_field_size(ESP_EFUSE_ID); // returns 6 // size_t id_size = ESP_EFUSE_USER_DATA[0]->bit_count; // cannot be used because it consists of 3 entries. It returns 3 not 6. esp_efuse_read_field_blob(ESP_EFUSE_ID, &id, id_size); // id = 0x91 // b'100 10 001 // [3] [2] [3] uint8_t id_1 = 0; esp_efuse_read_field_blob(ESP_EFUSE_ID, &id_1, 3); // id = 0x01 // b'001 Get eFuses During Build There is a way to get the state of eFuses at the build stage of the project. There are two cmake functions for this: espefuse_get_json_summary()- It calls the espefuse.py summary --format jsoncommand and returns a json string (it is not stored in a file). espefuse_get_efuse()- It finds a given eFuse name in the json string and returns its property. The json string has the following properties: { "MAC": { "bit_len": 48, "block": 0, "category": "identity", "description": "Factory MAC Address", "efuse_type": "bytes:6", "name": "MAC", "pos": 0, "readable": true, "value": "94:b9:7e:5a:6e:58 (CRC 0xe2 OK)", "word": 1, "writeable": true }, } These functions can be used from a top-level project CMakeLists.txt (get-started/hello_world/CMakeLists.txt): # ... project(hello_world) espefuse_get_json_summary(efuse_json) espefuse_get_efuse(ret_data ${efuse_json} "MAC" "value") message("MAC:" ${ret_data}) The format of the value property is the same as shown in espefuse.py summary. MAC:94:b9:7e:5a:6e:58 (CRC 0xe2 OK) There is an example test system/efuse/CMakeLists.txt which adds a custom target efuse-summary. This allows you to run the idf.py efuse-summary command to read the required eFuses (specified in the efuse_names list) at any time, not just at project build time. Debug eFuse & Unit Tests Virtual eFuses The Kconfig option CONFIG_EFUSE_VIRTUAL virtualizes eFuse values inside the eFuse Manager, so writes are emulated and no eFuse values are permanently changed. This can be useful for debugging app and unit tests. During startup, the eFuses are copied to RAM. All eFuse operations (read and write) are performed with RAM instead of the real eFuse registers. In addition to the CONFIG_EFUSE_VIRTUAL option there is CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH option that adds a feature to keep eFuses in flash memory. To use this mode the partition_table should have the efuse partition. partition.csv: "efuse_em, data, efuse, , 0x2000,". During startup, the eFuses are copied from flash or, in case if flash is empty, from real eFuse to RAM and then update flash. This option allows keeping eFuses after reboots (possible to test secure_boot and flash_encryption features with this option). Flash Encryption Testing Flash Encryption (FE) is a hardware feature that requires the physical burning of eFuses: key and FLASH_CRYPT_CNT. If FE is not actually enabled then enabling the CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH option just gives testing possibilities and does not encrypt anything in the flash, even though the logs say encryption happens. The bootloader_flash_write() is adapted for this purpose. But if FE is already enabled on the chip and you run an application or bootloader created with the CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH option then the flash encryption/decryption operations will work properly (data are encrypted as it is written into an encrypted flash partition and decrypted when they are read from an encrypted partition). espefuse.py esptool includes a useful tool for reading/writing ESP32 eFuse bits - espefuse.py. espefuse.py -p PORT summary espefuse.py v4.6-dev Connecting.... Detecting chip type... Unsupported detection protocol, switching and trying again... Connecting..... Detecting chip type... ESP32 === Run "summary" command === EFUSE_NAME (Block) Description = [Meaningful Value] [Readable/Writeable] (Hex Value) ---------------------------------------------------------------------------------------- Calibration fuses: ADC_VREF (BLOCK0) True ADC reference voltage = 1121 R/W (0b00011) Config fuses: WR_DIS (BLOCK0) Efuse write disable mask = 0 R/W (0x0000) RD_DIS (BLOCK0) Disable reading from BlOCK1-3 = 0 R/W (0x0) DISABLE_APP_CPU (BLOCK0) Disables APP CPU = False R/W (0b0) DISABLE_BT (BLOCK0) Disables Bluetooth = False R/W (0b0) DIS_CACHE (BLOCK0) Disables cache = False R/W (0b0) CHIP_CPU_FREQ_LOW (BLOCK0) If set alongside EFUSE_RD_CHIP_CPU_FREQ_RATED; the = False R/W (0b0) ESP32's max CPU frequency is rated for 160MHz. 24 0MHz otherwise CHIP_CPU_FREQ_RATED (BLOCK0) If set; the ESP32's maximum CPU frequency has been = True R/W (0b1) rated BLK3_PART_RESERVE (BLOCK0) BLOCK3 partially served for ADC calibration data = False R/W (0b0) CLK8M_FREQ (BLOCK0) 8MHz clock freq override = 51 R/W (0x33) VOL_LEVEL_HP_INV (BLOCK0) This field stores the voltage level for CPU to run = 0 R/W (0b00) at 240 MHz; or for flash/PSRAM to run at 80 MHz.0 x0: level 7; 0x1: level 6; 0x2: level 5; 0x3: leve l 4. (RO) CODING_SCHEME (BLOCK0) Efuse variable block length scheme = NONE (BLK1-3 len=256 bits) R/W (0b00) CONSOLE_DEBUG_DISABLE (BLOCK0) Disable ROM BASIC interpreter fallback = True R/W (0b1) DISABLE_SDIO_HOST (BLOCK0) = False R/W (0b0) DISABLE_DL_CACHE (BLOCK0) Disable flash cache in UART bootloader = False R/W (0b0) Flash fuses: FLASH_CRYPT_CNT (BLOCK0) Flash encryption is enabled if this field has an o = 0 R/W (0b0000000) dd number of bits set FLASH_CRYPT_CONFIG (BLOCK0) Flash encryption config (key tweak bits) = 0 R/W (0x0) Identity fuses: CHIP_PACKAGE_4BIT (BLOCK0) Chip package identifier #4bit = False R/W (0b0) CHIP_PACKAGE (BLOCK0) Chip package identifier = 1 R/W (0b001) CHIP_VER_REV1 (BLOCK0) bit is set to 1 for rev1 silicon = True R/W (0b1) CHIP_VER_REV2 (BLOCK0) = True R/W (0b1) WAFER_VERSION_MINOR (BLOCK0) = 0 R/W (0b00) WAFER_VERSION_MAJOR (BLOCK0) calc WAFER VERSION MAJOR from CHIP_VER_REV1 and CH = 3 R/W (0b011) IP_VER_REV2 and apb_ctl_date (read only) PKG_VERSION (BLOCK0) calc Chip package = CHIP_PACKAGE_4BIT << 3 + CHIP_ = 1 R/W (0x1) PACKAGE (read only) Jtag fuses: JTAG_DISABLE (BLOCK0) Disable JTAG = False R/W (0b0) Mac fuses: MAC (BLOCK0) MAC address = 94:b9:7e:5a:6e:58 (CRC 0xe2 OK) R/W MAC_CRC (BLOCK0) CRC8 for MAC address = 226 R/W (0xe2) MAC_VERSION (BLOCK3) Version of the MAC field = 0 R/W (0x00) Security fuses: UART_DOWNLOAD_DIS (BLOCK0) Disable UART download mode. Valid for ESP32 V3 and = False R/W (0b0) newer; only ABS_DONE_0 (BLOCK0) Secure boot V1 is enabled for bootloader image = False R/W (0b0) ABS_DONE_1 (BLOCK0) Secure boot V2 is enabled for bootloader image = False R/W (0b0) DISABLE_DL_ENCRYPT (BLOCK0) Disable flash encryption in UART bootloader = False R/W (0b0) DISABLE_DL_DECRYPT (BLOCK0) Disable flash decryption in UART bootloader = False R/W (0b0) KEY_STATUS (BLOCK0) Usage of efuse block 3 (reserved) = False R/W (0b0) SECURE_VERSION (BLOCK3) Secure version for anti-rollback = 0 R/W (0x00000000) BLOCK1 (BLOCK1) Flash encryption key = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 R/W BLOCK2 (BLOCK2) Security boot key = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 R/W BLOCK3 (BLOCK3) Variable Block 3 = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 R/W Spi Pad fuses: SPI_PAD_CONFIG_HD (BLOCK0) read for SPI_pad_config_hd = 0 R/W (0b00000) SPI_PAD_CONFIG_CLK (BLOCK0) Override SD_CLK pad (GPIO6/SPICLK) = 0 R/W (0b00000) SPI_PAD_CONFIG_Q (BLOCK0) Override SD_DATA_0 pad (GPIO7/SPIQ) = 0 R/W (0b00000) SPI_PAD_CONFIG_D (BLOCK0) Override SD_DATA_1 pad (GPIO8/SPID) = 0 R/W (0b00000) SPI_PAD_CONFIG_CS0 (BLOCK0) Override SD_CMD pad (GPIO11/SPICS0) = 0 R/W (0b00000) Vdd fuses: XPD_SDIO_REG (BLOCK0) read for XPD_SDIO_REG = False R/W (0b0) XPD_SDIO_TIEH (BLOCK0) If XPD_SDIO_FORCE & XPD_SDIO_REG = 1.8V R/W (0b0) XPD_SDIO_FORCE (BLOCK0) Ignore MTDI pin (GPIO12) for VDD_SDIO on reset = False R/W (0b0) Flash voltage (VDD_SDIO) determined by GPIO12 on reset (High for 1.8V, Low/NC for 3.3V) To get a dump for all eFuse registers. espefuse.py -p PORT dump espefuse.py v4.6-dev Connecting.... Detecting chip type... Unsupported detection protocol, switching and trying again... Connecting....... Detecting chip type... ESP32 BLOCK0 ( ) [0 ] read_regs: 00000000 7e5a6e58 00e294b9 0000a200 00000333 00100000 00000004 BLOCK1 (flash_encryption) [1 ] read_regs: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 BLOCK2 (secure_boot_v1 s) [2 ] read_regs: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 BLOCK3 ( ) [3 ] read_regs: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 EFUSE_REG_DEC_STATUS 0x00000000 === Run "dump" command === Header File This header file can be included with: #include "esp_efuse_chip.h" This header file is a part of the API provided by the efusecomponent. To declare that your component depends on efuse, add the following to your CMakeLists.txt: REQUIRES efuse or PRIV_REQUIRES efuse Enumerations - enum esp_efuse_block_t Type of eFuse blocks for ESP32. Values: - enumerator EFUSE_BLK0 Number of eFuse block. Reserved. - enumerator EFUSE_BLK1 Number of eFuse block. Used for Flash Encryption. If not using that Flash Encryption feature, they can be used for another purpose. - enumerator EFUSE_BLK_KEY0 Number of eFuse block. Used for Flash Encryption. If not using that Flash Encryption feature, they can be used for another purpose. - enumerator EFUSE_BLK_ENCRYPT_FLASH Number of eFuse block. Used for Flash Encryption. If not using that Flash Encryption feature, they can be used for another purpose. - enumerator EFUSE_BLK2 Number of eFuse block. Used for Secure Boot. If not using that Secure Boot feature, they can be used for another purpose. - enumerator EFUSE_BLK_KEY1 Number of eFuse block. Used for Secure Boot. If not using that Secure Boot feature, they can be used for another purpose. - enumerator EFUSE_BLK_SECURE_BOOT Number of eFuse block. Used for Secure Boot. If not using that Secure Boot feature, they can be used for another purpose. - enumerator EFUSE_BLK3 Number of eFuse block. Uses for the purpose of the user. - enumerator EFUSE_BLK_KEY2 Number of eFuse block. Uses for the purpose of the user. - enumerator EFUSE_BLK_KEY_MAX - enumerator EFUSE_BLK_MAX - enumerator EFUSE_BLK0 - enum esp_efuse_coding_scheme_t Type of coding scheme. Values: - enumerator EFUSE_CODING_SCHEME_NONE None - enumerator EFUSE_CODING_SCHEME_3_4 3/4 coding - enumerator EFUSE_CODING_SCHEME_REPEAT Repeat coding - enumerator EFUSE_CODING_SCHEME_NONE - enum esp_efuse_purpose_t Type of key purpose (virtual because ESP32 has only fixed purposes for blocks) Values: - enumerator ESP_EFUSE_KEY_PURPOSE_USER BLOCK3 - enumerator ESP_EFUSE_KEY_PURPOSE_SYSTEM BLOCK0 - enumerator ESP_EFUSE_KEY_PURPOSE_FLASH_ENCRYPTION BLOCK1 - enumerator ESP_EFUSE_KEY_PURPOSE_SECURE_BOOT_V2 BLOCK2 - enumerator ESP_EFUSE_KEY_PURPOSE_MAX MAX PURPOSE - enumerator ESP_EFUSE_KEY_PURPOSE_USER Header File This header file can be included with: #include "esp_efuse.h" This header file is a part of the API provided by the efusecomponent. To declare that your component depends on efuse, add the following to your CMakeLists.txt: REQUIRES efuse or PRIV_REQUIRES efuse Functions - esp_err_t esp_efuse_read_field_blob(const esp_efuse_desc_t *field[], void *dst, size_t dst_size_bits) Reads bits from EFUSE field and writes it into an array. The number of read bits will be limited to the minimum value from the description of the bits in "field" structure or "dst_size_bits" required size. Use "esp_efuse_get_field_size()" function to determine the length of the field. Note Please note that reading in the batch mode does not show uncommitted changes. - Parameters field -- [in] A pointer to the structure describing the fields of efuse. dst -- [out] A pointer to array that will contain the result of reading. dst_size_bits -- [in] The number of bits required to read. If the requested number of bits is greater than the field, the number will be limited to the field size. - - Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. - - bool esp_efuse_read_field_bit(const esp_efuse_desc_t *field[]) Read a single bit eFuse field as a boolean value. Note The value must exist and must be a single bit wide. If there is any possibility of an error in the provided arguments, call esp_efuse_read_field_blob() and check the returned value instead. Note If assertions are enabled and the parameter is invalid, execution will abort Note Please note that reading in the batch mode does not show uncommitted changes. - Parameters field -- [in] A pointer to the structure describing the fields of efuse. - Returns true: The field parameter is valid and the bit is set. false: The bit is not set, or the parameter is invalid and assertions are disabled. - - esp_err_t esp_efuse_read_field_cnt(const esp_efuse_desc_t *field[], size_t *out_cnt) Reads bits from EFUSE field and returns number of bits programmed as "1". If the bits are set not sequentially, they will still be counted. Note Please note that reading in the batch mode does not show uncommitted changes. - Parameters field -- [in] A pointer to the structure describing the fields of efuse. out_cnt -- [out] A pointer that will contain the number of programmed as "1" bits. - - Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. - - esp_err_t esp_efuse_write_field_blob(const esp_efuse_desc_t *field[], const void *src, size_t src_size_bits) Writes array to EFUSE field. The number of write bits will be limited to the minimum value from the description of the bits in "field" structure or "src_size_bits" required size. Use "esp_efuse_get_field_size()" function to determine the length of the field. After the function is completed, the writing registers are cleared. - Parameters field -- [in] A pointer to the structure describing the fields of efuse. src -- [in] A pointer to array that contains the data for writing. src_size_bits -- [in] The number of bits required to write. - - Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. - - esp_err_t esp_efuse_write_field_cnt(const esp_efuse_desc_t *field[], size_t cnt) Writes a required count of bits as "1" to EFUSE field. If there are no free bits in the field to set the required number of bits to "1", ESP_ERR_EFUSE_CNT_IS_FULL error is returned, the field will not be partially recorded. After the function is completed, the writing registers are cleared. - Parameters field -- [in] A pointer to the structure describing the fields of efuse. cnt -- [in] Required number of programmed as "1" bits. - - Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. - - esp_err_t esp_efuse_write_field_bit(const esp_efuse_desc_t *field[]) Write a single bit eFuse field to 1. For use with eFuse fields that are a single bit. This function will write the bit to value 1 if it is not already set, or does nothing if the bit is already set. This is equivalent to calling esp_efuse_write_field_cnt() with the cnt parameter equal to 1, except that it will return ESP_OK if the field is already set to 1. - Parameters field -- [in] Pointer to the structure describing the efuse field. - Returns ESP_OK: The operation was successfully completed, or the bit was already set to value 1. ESP_ERR_INVALID_ARG: Error in the passed arugments, including if the efuse field is not 1 bit wide. - - esp_err_t esp_efuse_set_write_protect(esp_efuse_block_t blk) Sets a write protection for the whole block. After that, it is impossible to write to this block. The write protection does not apply to block 0. - Parameters blk -- [in] Block number of eFuse. (EFUSE_BLK1, EFUSE_BLK2 and EFUSE_BLK3) - Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. ESP_ERR_NOT_SUPPORTED: The block does not support this command. - - esp_err_t esp_efuse_set_read_protect(esp_efuse_block_t blk) Sets a read protection for the whole block. After that, it is impossible to read from this block. The read protection does not apply to block 0. - Parameters blk -- [in] Block number of eFuse. (EFUSE_BLK1, EFUSE_BLK2 and EFUSE_BLK3) - Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. ESP_ERR_NOT_SUPPORTED: The block does not support this command. - - int esp_efuse_get_field_size(const esp_efuse_desc_t *field[]) Returns the number of bits used by field. - Parameters field -- [in] A pointer to the structure describing the fields of efuse. - Returns Returns the number of bits used by field. - uint32_t esp_efuse_read_reg(esp_efuse_block_t blk, unsigned int num_reg) Returns value of efuse register. This is a thread-safe implementation. Example: EFUSE_BLK2_RDATA3_REG where (blk=2, num_reg=3) Note Please note that reading in the batch mode does not show uncommitted changes. - Parameters blk -- [in] Block number of eFuse. num_reg -- [in] The register number in the block. - - Returns Value of register - esp_err_t esp_efuse_write_reg(esp_efuse_block_t blk, unsigned int num_reg, uint32_t val) Write value to efuse register. Apply a coding scheme if necessary. This is a thread-safe implementation. Example: EFUSE_BLK3_WDATA0_REG where (blk=3, num_reg=0) - Parameters blk -- [in] Block number of eFuse. num_reg -- [in] The register number in the block. val -- [in] Value to write. - - Returns ESP_OK: The operation was successfully completed. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. - - esp_efuse_coding_scheme_t esp_efuse_get_coding_scheme(esp_efuse_block_t blk) Return efuse coding scheme for blocks. Note The coding scheme is applicable only to 1, 2 and 3 blocks. For 0 block, the coding scheme is always NONE. - Parameters blk -- [in] Block number of eFuse. - Returns Return efuse coding scheme for blocks - esp_err_t esp_efuse_read_block(esp_efuse_block_t blk, void *dst_key, size_t offset_in_bits, size_t size_bits) Read key to efuse block starting at the offset and the required size. Note Please note that reading in the batch mode does not show uncommitted changes. - Parameters blk -- [in] Block number of eFuse. dst_key -- [in] A pointer to array that will contain the result of reading. offset_in_bits -- [in] Start bit in block. size_bits -- [in] The number of bits required to read. - - Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_CODING: Error range of data does not match the coding scheme. - - esp_err_t esp_efuse_write_block(esp_efuse_block_t blk, const void *src_key, size_t offset_in_bits, size_t size_bits) Write key to efuse block starting at the offset and the required size. - Parameters blk -- [in] Block number of eFuse. src_key -- [in] A pointer to array that contains the key for writing. offset_in_bits -- [in] Start bit in block. size_bits -- [in] The number of bits required to write. - - Returns ESP_OK: The operation was successfully completed. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_CODING: Error range of data does not match the coding scheme. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits - - uint32_t esp_efuse_get_pkg_ver(void) Returns chip package from efuse. - Returns chip package - void esp_efuse_reset(void) Reset efuse write registers. Efuse write registers are written to zero, to negate any changes that have been staged here. Note This function is not threadsafe, if calling code updates efuse values from multiple tasks then this is caller's responsibility to serialise. - void esp_efuse_disable_basic_rom_console(void) Disable BASIC ROM Console via efuse. By default, if booting from flash fails the ESP32 will boot a BASIC console in ROM. Call this function (from bootloader or app) to permanently disable the console on this chip. - esp_err_t esp_efuse_disable_rom_download_mode(void) Disable ROM Download Mode via eFuse. Permanently disables the ROM Download Mode feature. Once disabled, if the SoC is booted with strapping pins set for ROM Download Mode then an error is printed instead. Note Not all SoCs support this option. An error will be returned if called on an ESP32 with a silicon revision lower than 3, as these revisions do not support this option. Note If ROM Download Mode is already disabled, this function does nothing and returns success. - Returns ESP_OK If the eFuse was successfully burned, or had already been burned. ESP_ERR_NOT_SUPPORTED (ESP32 only) This SoC is not capable of disabling UART download mode ESP_ERR_INVALID_STATE (ESP32 only) This eFuse is write protected and cannot be written - - esp_err_t esp_efuse_set_rom_log_scheme(esp_efuse_rom_log_scheme_t log_scheme) Set boot ROM log scheme via eFuse. Note By default, the boot ROM will always print to console. This API can be called to set the log scheme only once per chip, once the value is changed from the default it can't be changed again. - Parameters log_scheme -- Supported ROM log scheme - Returns ESP_OK If the eFuse was successfully burned, or had already been burned. ESP_ERR_NOT_SUPPORTED (ESP32 only) This SoC is not capable of setting ROM log scheme ESP_ERR_INVALID_STATE This eFuse is write protected or has been burned already - - uint32_t esp_efuse_read_secure_version(void) Return secure_version from efuse field. - Returns Secure version from efuse field - bool esp_efuse_check_secure_version(uint32_t secure_version) Check secure_version from app and secure_version and from efuse field. - Parameters secure_version -- Secure version from app. - Returns True: If version of app is equal or more then secure_version from efuse. - - esp_err_t esp_efuse_update_secure_version(uint32_t secure_version) Write efuse field by secure_version value. Update the secure_version value is available if the coding scheme is None. Note: Do not use this function in your applications. This function is called as part of the other API. - Parameters secure_version -- [in] Secure version from app. - Returns ESP_OK: Successful. ESP_FAIL: secure version of app cannot be set to efuse field. ESP_ERR_NOT_SUPPORTED: Anti rollback is not supported with the 3/4 and Repeat coding scheme. - - esp_err_t esp_efuse_batch_write_begin(void) Set the batch mode of writing fields. This mode allows you to write the fields in the batch mode when need to burn several efuses at one time. To enable batch mode call begin() then perform as usually the necessary operations read and write and at the end call commit() to actually burn all written efuses. The batch mode can be used nested. The commit will be done by the last commit() function. The number of begin() functions should be equal to the number of commit() functions. Note: If batch mode is enabled by the first task, at this time the second task cannot write/read efuses. The second task will wait for the first task to complete the batch operation. // Example of using the batch writing mode. // set the batch writing mode esp_efuse_batch_write_begin(); // use any writing functions as usual esp_efuse_write_field_blob(ESP_EFUSE_...); esp_efuse_write_field_cnt(ESP_EFUSE_...); esp_efuse_set_write_protect(EFUSE_BLKx); esp_efuse_write_reg(EFUSE_BLKx, ...); esp_efuse_write_block(EFUSE_BLKx, ...); esp_efuse_write(ESP_EFUSE_1, 3); // ESP_EFUSE_1 == 1, here we write a new value = 3. The changes will be burn by the commit() function. esp_efuse_read_...(ESP_EFUSE_1); // this function returns ESP_EFUSE_1 == 1 because uncommitted changes are not readable, it will be available only after commit. ... // esp_efuse_batch_write APIs can be called recursively. esp_efuse_batch_write_begin(); esp_efuse_set_write_protect(EFUSE_BLKx); esp_efuse_batch_write_commit(); // the burn will be skipped here, it will be done in the last commit(). ... // Write all of these fields to the efuse registers esp_efuse_batch_write_commit(); esp_efuse_read_...(ESP_EFUSE_1); // this function returns ESP_EFUSE_1 == 3. Note Please note that reading in the batch mode does not show uncommitted changes. - Returns ESP_OK: Successful. - - esp_err_t esp_efuse_batch_write_cancel(void) Reset the batch mode of writing fields. It will reset the batch writing mode and any written changes. - Returns ESP_OK: Successful. ESP_ERR_INVALID_STATE: Tha batch mode was not set. - - esp_err_t esp_efuse_batch_write_commit(void) Writes all prepared data for the batch mode. Must be called to ensure changes are written to the efuse registers. After this the batch writing mode will be reset. - Returns ESP_OK: Successful. ESP_ERR_INVALID_STATE: The deferred writing mode was not set. - - bool esp_efuse_block_is_empty(esp_efuse_block_t block) Checks that the given block is empty. - Returns True: The block is empty. False: The block is not empty or was an error. - - bool esp_efuse_get_key_dis_read(esp_efuse_block_t block) Returns a read protection for the key block. - Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX - Returns True: The key block is read protected False: The key block is readable. - esp_err_t esp_efuse_set_key_dis_read(esp_efuse_block_t block) Sets a read protection for the key block. - Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX - Returns ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. - - bool esp_efuse_get_key_dis_write(esp_efuse_block_t block) Returns a write protection for the key block. - Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX - Returns True: The key block is write protected False: The key block is writeable. - esp_err_t esp_efuse_set_key_dis_write(esp_efuse_block_t block) Sets a write protection for the key block. - Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX - Returns ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. - - bool esp_efuse_key_block_unused(esp_efuse_block_t block) Returns true if the key block is unused, false otherwise. An unused key block is all zero content, not read or write protected, and has purpose 0 (ESP_EFUSE_KEY_PURPOSE_USER) - Parameters block -- key block to check. - Returns True if key block is unused, False if key block is used or the specified block index is not a key block. - - bool esp_efuse_find_purpose(esp_efuse_purpose_t purpose, esp_efuse_block_t *block) Find a key block with the particular purpose set. - Parameters purpose -- [in] Purpose to search for. block -- [out] Pointer in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX which will be set to the key block if found. Can be NULL, if only need to test the key block exists. - - Returns True: If found, False: If not found (value at block pointer is unchanged). - - bool esp_efuse_get_keypurpose_dis_write(esp_efuse_block_t block) Returns a write protection of the key purpose field for an efuse key block. Note For ESP32: no keypurpose, it returns always True. - Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX - Returns True: The key purpose is write protected. False: The key purpose is writeable. - esp_efuse_purpose_t esp_efuse_get_key_purpose(esp_efuse_block_t block) Returns the current purpose set for an efuse key block. - Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX - Returns Value: If Successful, it returns the value of the purpose related to the given key block. ESP_EFUSE_KEY_PURPOSE_MAX: Otherwise. - - esp_err_t esp_efuse_write_key(esp_efuse_block_t block, esp_efuse_purpose_t purpose, const void *key, size_t key_size_bytes) Program a block of key data to an efuse block. The burn of a key, protection bits, and a purpose happens in batch mode. Note This API also enables the read protection efuse bit for certain key blocks like XTS-AES, HMAC, ECDSA etc. This ensures that the key is only accessible to hardware peripheral. Note For SoC's with capability SOC_EFUSE_ECDSA_USE_HARDWARE_K(e.g., ESP32-H2), this API writes an additional efuse bit for ECDSA key purpose to enforce hardware TRNG generated k mode in the peripheral. - Parameters block -- [in] Block to read purpose for. Must be in range EFUSE_BLK_KEY0 to EFUSE_BLK_KEY_MAX. Key block must be unused (esp_efuse_key_block_unused). purpose -- [in] Purpose to set for this key. Purpose must be already unset. key -- [in] Pointer to data to write. key_size_bytes -- [in] Bytes length of data to write. - - Returns ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_INVALID_STATE: Error in efuses state, unused block not found. ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. - - esp_err_t esp_efuse_write_keys(const esp_efuse_purpose_t purposes[], uint8_t keys[][32], unsigned number_of_keys) Program keys to unused efuse blocks. The burn of keys, protection bits, and purposes happens in batch mode. Note This API also enables the read protection efuse bit for certain key blocks like XTS-AES, HMAC, ECDSA etc. This ensures that the key is only accessible to hardware peripheral. Note For SoC's with capability SOC_EFUSE_ECDSA_USE_HARDWARE_K(e.g., ESP32-H2), this API writes an additional efuse bit for ECDSA key purpose to enforce hardware TRNG generated k mode in the peripheral. - Parameters purposes -- [in] Array of purposes (purpose[number_of_keys]). keys -- [in] Array of keys (uint8_t keys[number_of_keys][32]). Each key is 32 bytes long. number_of_keys -- [in] The number of keys to write (up to 6 keys). - - Returns ESP_OK: Successful. ESP_ERR_INVALID_ARG: Error in the passed arguments. ESP_ERR_INVALID_STATE: Error in efuses state, unused block not found. ESP_ERR_NOT_ENOUGH_UNUSED_KEY_BLOCKS: Error not enough unused key blocks available ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. - - esp_err_t esp_efuse_check_errors(void) Checks eFuse errors in BLOCK0. It does a BLOCK0 check if eFuse EFUSE_ERR_RST_ENABLE is set. If BLOCK0 has an error, it prints the error and returns ESP_FAIL, which should be treated as esp_restart. Note Refers to ESP32-C3 only. - Returns ESP_OK: No errors in BLOCK0. ESP_FAIL: Error in BLOCK0 requiring reboot. - Structures - struct esp_efuse_desc_t Type definition for an eFuse field. Public Members - esp_efuse_block_t efuse_block Block of eFuse - uint8_t bit_start Start bit [0..255] - uint16_t bit_count Length of bit field [1..-] - esp_efuse_block_t efuse_block Macros - ESP_ERR_EFUSE Base error code for efuse api. - ESP_OK_EFUSE_CNT OK the required number of bits is set. - ESP_ERR_EFUSE_CNT_IS_FULL Error field is full. - ESP_ERR_EFUSE_REPEATED_PROG Error repeated programming of programmed bits is strictly forbidden. - ESP_ERR_CODING Error while a encoding operation. - ESP_ERR_NOT_ENOUGH_UNUSED_KEY_BLOCKS Error not enough unused key blocks available - ESP_ERR_DAMAGED_READING Error. Burn or reset was done during a reading operation leads to damage read data. This error is internal to the efuse component and not returned by any public API. Enumerations - enum esp_efuse_rom_log_scheme_t Type definition for ROM log scheme. Values: - enumerator ESP_EFUSE_ROM_LOG_ALWAYS_ON Always enable ROM logging - enumerator ESP_EFUSE_ROM_LOG_ON_GPIO_LOW ROM logging is enabled when specific GPIO level is low during start up - enumerator ESP_EFUSE_ROM_LOG_ON_GPIO_HIGH ROM logging is enabled when specific GPIO level is high during start up - enumerator ESP_EFUSE_ROM_LOG_ALWAYS_OFF Disable ROM logging permanently - enumerator ESP_EFUSE_ROM_LOG_ALWAYS_ON
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/efuse.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Error Code and Helper Functions
null
espressif.com
2016-01-01
a80eea12e48ca1dc
null
null
Error Code and Helper Functions This section lists definitions of common ESP-IDF error codes and several helper functions related to error handling. For general information about error codes in ESP-IDF, see Error Handling. For the full list of error codes defined in ESP-IDF, see Error Codes Reference. API Reference Header File This header file can be included with: #include "esp_check.h" Macros ESP_RETURN_ON_ERROR(x, log_tag, format, ...) Macro which can be used to check the error code. If the code is not ESP_OK, it prints the message and returns. In the future, we want to switch to C++20. We also want to become compatible with clang. Hence, we provide two versions of the following macros. The first one is using the GNU extension ##__VA_ARGS__. The second one is using the C++20 feature VA_OPT(,). This allows users to compile their code with standard C++20 enabled instead of the GNU extension. Below C++20, we haven't found any good alternative to using ##__VA_ARGS__. Macro which can be used to check the error code. If the code is not ESP_OK, it prints the message and returns. ESP_RETURN_ON_ERROR_ISR(x, log_tag, format, ...) A version of ESP_RETURN_ON_ERROR() macro that can be called from ISR. ESP_GOTO_ON_ERROR(x, goto_tag, log_tag, format, ...) Macro which can be used to check the error code. If the code is not ESP_OK, it prints the message, sets the local variable 'ret' to the code, and then exits by jumping to 'goto_tag'. ESP_GOTO_ON_ERROR_ISR(x, goto_tag, log_tag, format, ...) A version of ESP_GOTO_ON_ERROR() macro that can be called from ISR. ESP_RETURN_ON_FALSE(a, err_code, log_tag, format, ...) Macro which can be used to check the condition. If the condition is not 'true', it prints the message and returns with the supplied 'err_code'. ESP_RETURN_ON_FALSE_ISR(a, err_code, log_tag, format, ...) A version of ESP_RETURN_ON_FALSE() macro that can be called from ISR. ESP_GOTO_ON_FALSE(a, err_code, goto_tag, log_tag, format, ...) Macro which can be used to check the condition. If the condition is not 'true', it prints the message, sets the local variable 'ret' to the supplied 'err_code', and then exits by jumping to 'goto_tag'. ESP_GOTO_ON_FALSE_ISR(a, err_code, goto_tag, log_tag, format, ...) A version of ESP_GOTO_ON_FALSE() macro that can be called from ISR. Header File This header file can be included with: #include "esp_err.h" Functions const char *esp_err_to_name(esp_err_t code) Returns string for esp_err_t error codes. This function finds the error code in a pre-generated lookup-table and returns its string representation. The function is generated by the Python script tools/gen_esp_err_to_name.py which should be run each time an esp_err_t error is modified, created or removed from the IDF project. Parameters code -- esp_err_t error code Returns string error message Parameters code -- esp_err_t error code Returns string error message const char *esp_err_to_name_r(esp_err_t code, char *buf, size_t buflen) Returns string for esp_err_t and system error codes. This function finds the error code in a pre-generated lookup-table of esp_err_t errors and returns its string representation. If the error code is not found then it is attempted to be found among system errors. The function is generated by the Python script tools/gen_esp_err_to_name.py which should be run each time an esp_err_t error is modified, created or removed from the IDF project. Parameters code -- esp_err_t error code buf -- [out] buffer where the error message should be written buflen -- Size of buffer buf. At most buflen bytes are written into the buf buffer (including the terminating null byte). code -- esp_err_t error code buf -- [out] buffer where the error message should be written buflen -- Size of buffer buf. At most buflen bytes are written into the buf buffer (including the terminating null byte). code -- esp_err_t error code Returns buf containing the string error message Parameters code -- esp_err_t error code buf -- [out] buffer where the error message should be written buflen -- Size of buffer buf. At most buflen bytes are written into the buf buffer (including the terminating null byte). Returns buf containing the string error message Macros ESP_OK esp_err_t value indicating success (no error) ESP_FAIL Generic esp_err_t code indicating failure ESP_ERR_NO_MEM Out of memory ESP_ERR_INVALID_ARG Invalid argument ESP_ERR_INVALID_STATE Invalid state ESP_ERR_INVALID_SIZE Invalid size ESP_ERR_NOT_FOUND Requested resource not found ESP_ERR_NOT_SUPPORTED Operation or feature not supported ESP_ERR_TIMEOUT Operation timed out ESP_ERR_INVALID_RESPONSE Received response was invalid ESP_ERR_INVALID_CRC CRC or checksum was invalid ESP_ERR_INVALID_VERSION Version was invalid ESP_ERR_INVALID_MAC MAC address was invalid ESP_ERR_NOT_FINISHED Operation has not fully completed ESP_ERR_NOT_ALLOWED Operation is not allowed ESP_ERR_WIFI_BASE Starting number of WiFi error codes ESP_ERR_MESH_BASE Starting number of MESH error codes ESP_ERR_FLASH_BASE Starting number of flash error codes ESP_ERR_HW_CRYPTO_BASE Starting number of HW cryptography module error codes ESP_ERR_MEMPROT_BASE Starting number of Memory Protection API error codes ESP_ERROR_CHECK(x) Macro which can be used to check the error code, and terminate the program in case the code is not ESP_OK. Prints the error code, error location, and the failed statement to serial output. Disabled if assertions are disabled. ESP_ERROR_CHECK_WITHOUT_ABORT(x) Macro which can be used to check the error code. Prints the error code, error location, and the failed statement to serial output. In comparison with ESP_ERROR_CHECK(), this prints the same error message but isn't terminating the program. Type Definitions typedef int esp_err_t
Error Code and Helper Functions This section lists definitions of common ESP-IDF error codes and several helper functions related to error handling. For general information about error codes in ESP-IDF, see Error Handling. For the full list of error codes defined in ESP-IDF, see Error Codes Reference. API Reference Header File This header file can be included with: #include "esp_check.h" Macros - ESP_RETURN_ON_ERROR(x, log_tag, format, ...) Macro which can be used to check the error code. If the code is not ESP_OK, it prints the message and returns. In the future, we want to switch to C++20. We also want to become compatible with clang. Hence, we provide two versions of the following macros. The first one is using the GNU extension ##__VA_ARGS__. The second one is using the C++20 feature VA_OPT(,). This allows users to compile their code with standard C++20 enabled instead of the GNU extension. Below C++20, we haven't found any good alternative to using ##__VA_ARGS__. Macro which can be used to check the error code. If the code is not ESP_OK, it prints the message and returns. - ESP_RETURN_ON_ERROR_ISR(x, log_tag, format, ...) A version of ESP_RETURN_ON_ERROR() macro that can be called from ISR. - ESP_GOTO_ON_ERROR(x, goto_tag, log_tag, format, ...) Macro which can be used to check the error code. If the code is not ESP_OK, it prints the message, sets the local variable 'ret' to the code, and then exits by jumping to 'goto_tag'. - ESP_GOTO_ON_ERROR_ISR(x, goto_tag, log_tag, format, ...) A version of ESP_GOTO_ON_ERROR() macro that can be called from ISR. - ESP_RETURN_ON_FALSE(a, err_code, log_tag, format, ...) Macro which can be used to check the condition. If the condition is not 'true', it prints the message and returns with the supplied 'err_code'. - ESP_RETURN_ON_FALSE_ISR(a, err_code, log_tag, format, ...) A version of ESP_RETURN_ON_FALSE() macro that can be called from ISR. - ESP_GOTO_ON_FALSE(a, err_code, goto_tag, log_tag, format, ...) Macro which can be used to check the condition. If the condition is not 'true', it prints the message, sets the local variable 'ret' to the supplied 'err_code', and then exits by jumping to 'goto_tag'. - ESP_GOTO_ON_FALSE_ISR(a, err_code, goto_tag, log_tag, format, ...) A version of ESP_GOTO_ON_FALSE() macro that can be called from ISR. Header File This header file can be included with: #include "esp_err.h" Functions - const char *esp_err_to_name(esp_err_t code) Returns string for esp_err_t error codes. This function finds the error code in a pre-generated lookup-table and returns its string representation. The function is generated by the Python script tools/gen_esp_err_to_name.py which should be run each time an esp_err_t error is modified, created or removed from the IDF project. - Parameters code -- esp_err_t error code - Returns string error message - const char *esp_err_to_name_r(esp_err_t code, char *buf, size_t buflen) Returns string for esp_err_t and system error codes. This function finds the error code in a pre-generated lookup-table of esp_err_t errors and returns its string representation. If the error code is not found then it is attempted to be found among system errors. The function is generated by the Python script tools/gen_esp_err_to_name.py which should be run each time an esp_err_t error is modified, created or removed from the IDF project. - Parameters code -- esp_err_t error code buf -- [out] buffer where the error message should be written buflen -- Size of buffer buf. At most buflen bytes are written into the buf buffer (including the terminating null byte). - - Returns buf containing the string error message Macros - ESP_OK esp_err_t value indicating success (no error) - ESP_FAIL Generic esp_err_t code indicating failure - ESP_ERR_NO_MEM Out of memory - ESP_ERR_INVALID_ARG Invalid argument - ESP_ERR_INVALID_STATE Invalid state - ESP_ERR_INVALID_SIZE Invalid size - ESP_ERR_NOT_FOUND Requested resource not found - ESP_ERR_NOT_SUPPORTED Operation or feature not supported - ESP_ERR_TIMEOUT Operation timed out - ESP_ERR_INVALID_RESPONSE Received response was invalid - ESP_ERR_INVALID_CRC CRC or checksum was invalid - ESP_ERR_INVALID_VERSION Version was invalid - ESP_ERR_INVALID_MAC MAC address was invalid - ESP_ERR_NOT_FINISHED Operation has not fully completed - ESP_ERR_NOT_ALLOWED Operation is not allowed - ESP_ERR_WIFI_BASE Starting number of WiFi error codes - ESP_ERR_MESH_BASE Starting number of MESH error codes - ESP_ERR_FLASH_BASE Starting number of flash error codes - ESP_ERR_HW_CRYPTO_BASE Starting number of HW cryptography module error codes - ESP_ERR_MEMPROT_BASE Starting number of Memory Protection API error codes - ESP_ERROR_CHECK(x) Macro which can be used to check the error code, and terminate the program in case the code is not ESP_OK. Prints the error code, error location, and the failed statement to serial output. Disabled if assertions are disabled. - ESP_ERROR_CHECK_WITHOUT_ABORT(x) Macro which can be used to check the error code. Prints the error code, error location, and the failed statement to serial output. In comparison with ESP_ERROR_CHECK(), this prints the same error message but isn't terminating the program. Type Definitions - typedef int esp_err_t
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/esp_err.html
ESP-IDF Programming Guide v5.2.1 documentation
null
ESP HTTPS OTA
null
espressif.com
2016-01-01
86439c131610d092
null
null
ESP HTTPS OTA Overview esp_https_ota provides simplified APIs to perform firmware upgrades over HTTPS. It is an abstraction layer over the existing OTA APIs. Application Example esp_err_t do_firmware_upgrade() { esp_http_client_config_t config = { .url = CONFIG_FIRMWARE_UPGRADE_URL, .cert_pem = (char *)server_cert_pem_start, }; esp_https_ota_config_t ota_config = { .http_config = &config, }; esp_err_t ret = esp_https_ota(&ota_config); if (ret == ESP_OK) { esp_restart(); } else { return ESP_FAIL; } return ESP_OK; } Server Verification Please refer to ESP-TLS: TLS Server Verification for more information on server verification. The root certificate in PEM format needs to be provided to the esp_http_client_config_t::cert_pem member. Note The server-endpoint root certificate should be used for verification instead of any intermediate ones from the certificate chain. The reason is that the root certificate has the maximum validity and usually remains the same for a long period of time. Users can also use the esp_http_client_config_t::crt_bundle_attach member for verification by the ESP x509 Certificate Bundle feature, which covers most of the trusted root certificates. Partial Image Download over HTTPS To use the partial image download feature, enable partial_http_download configuration in esp_https_ota_config_t . When this configuration is enabled, firmware image will be downloaded in multiple HTTP requests of specified sizes. Maximum content length of each request can be specified by setting max_http_request_size to the required value. This option is useful while fetching image from a service like AWS S3, where mbedTLS Rx buffer size (CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN) can be set to a lower value which is not possible without enabling this configuration. Default value of mbedTLS Rx buffer size is set to 16 KB. By using partial_http_download with max_http_request_size of 4 KB, size of mbedTLS Rx buffer can be reduced to 4 KB. With this configuration, memory saving of around 12 KB is expected. Signature Verification For additional security, signature of OTA firmware images can be verified. For more information, please refer to Secure OTA Updates Without Secure Boot. Advanced APIs esp_https_ota also provides advanced APIs which can be used if more information and control is needed during the OTA process. Example that uses advanced ESP_HTTPS_OTA APIs: system/ota/advanced_https_ota. OTA Upgrades with Pre-Encrypted Firmware To perform OTA upgrades with pre-encrypted firmware, please enable CONFIG_ESP_HTTPS_OTA_DECRYPT_CB in component menuconfig. Example that performs OTA upgrade with pre-encrypted firmware: system/ota/pre_encrypted_ota. OTA System Events ESP HTTPS OTA has various events for which a handler can be triggered by the Event Loop Library when the particular event occurs. The handler has to be registered using esp_event_handler_register() . This helps the event handling for ESP HTTPS OTA. esp_https_ota_event_t has all the events which can happen when performing OTA upgrade using ESP HTTPS OTA. Event Handler Example /* Event handler for catching system events */ static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) { if (event_base == ESP_HTTPS_OTA_EVENT) { switch (event_id) { case ESP_HTTPS_OTA_START: ESP_LOGI(TAG, "OTA started"); break; case ESP_HTTPS_OTA_CONNECTED: ESP_LOGI(TAG, "Connected to server"); break; case ESP_HTTPS_OTA_GET_IMG_DESC: ESP_LOGI(TAG, "Reading Image Description"); break; case ESP_HTTPS_OTA_VERIFY_CHIP_ID: ESP_LOGI(TAG, "Verifying chip id of new image: %d", *(esp_chip_id_t *)event_data); break; case ESP_HTTPS_OTA_DECRYPT_CB: ESP_LOGI(TAG, "Callback to decrypt function"); break; case ESP_HTTPS_OTA_WRITE_FLASH: ESP_LOGD(TAG, "Writing to flash: %d written", *(int *)event_data); break; case ESP_HTTPS_OTA_UPDATE_BOOT_PARTITION: ESP_LOGI(TAG, "Boot partition updated. Next Partition: %d", *(esp_partition_subtype_t *)event_data); break; case ESP_HTTPS_OTA_FINISH: ESP_LOGI(TAG, "OTA finish"); break; case ESP_HTTPS_OTA_ABORT: ESP_LOGI(TAG, "OTA abort"); break; } } } Expected data type for different ESP HTTPS OTA events in the system event loop: ESP_HTTPS_OTA_START : NULL ESP_HTTPS_OTA_CONNECTED : NULL ESP_HTTPS_OTA_GET_IMG_DESC : NULL ESP_HTTPS_OTA_VERIFY_CHIP_ID : esp_chip_id_t ESP_HTTPS_OTA_DECRYPT_CB : NULL ESP_HTTPS_OTA_WRITE_FLASH : int ESP_HTTPS_OTA_UPDATE_BOOT_PARTITION : esp_partition_subtype_t ESP_HTTPS_OTA_FINISH : NULL ESP_HTTPS_OTA_ABORT : NULL API Reference Header File This header file can be included with: #include "esp_https_ota.h" This header file is a part of the API provided by the esp_https_ota component. To declare that your component depends on esp_https_ota , add the following to your CMakeLists.txt: REQUIRES esp_https_ota or PRIV_REQUIRES esp_https_ota Functions esp_err_t esp_https_ota(const esp_https_ota_config_t *ota_config) HTTPS OTA Firmware upgrade. This function allocates HTTPS OTA Firmware upgrade context, establishes HTTPS connection, reads image data from HTTP stream and writes it to OTA partition and finishes HTTPS OTA Firmware upgrade operation. This API supports URL redirection, but if CA cert of URLs differ then it should be appended to cert_pem member of ota_config->http_config . Note This API handles the entire OTA operation, so if this API is being used then no other APIs from esp_https_ota component should be called. If more information and control is needed during the HTTPS OTA process, then one can use esp_https_ota_begin and subsequent APIs. If this API returns successfully, esp_restart() must be called to boot from the new firmware image. Parameters ota_config -- [in] pointer to esp_https_ota_config_t structure. Returns ESP_OK: OTA data updated, next reboot will use specified partition. ESP_FAIL: For generic failure. ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation. ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. For other return codes, refer OTA documentation in esp-idf's app_update component. ESP_OK: OTA data updated, next reboot will use specified partition. ESP_FAIL: For generic failure. ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation. ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. For other return codes, refer OTA documentation in esp-idf's app_update component. ESP_OK: OTA data updated, next reboot will use specified partition. Parameters ota_config -- [in] pointer to esp_https_ota_config_t structure. Returns ESP_OK: OTA data updated, next reboot will use specified partition. ESP_FAIL: For generic failure. ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation. ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. For other return codes, refer OTA documentation in esp-idf's app_update component. esp_err_t esp_https_ota_begin(const esp_https_ota_config_t *ota_config, esp_https_ota_handle_t *handle) Start HTTPS OTA Firmware upgrade. This function initializes ESP HTTPS OTA context and establishes HTTPS connection. This function must be invoked first. If this function returns successfully, then esp_https_ota_perform should be called to continue with the OTA process and there should be a call to esp_https_ota_finish on completion of OTA operation or on failure in subsequent operations. This API supports URL redirection, but if CA cert of URLs differ then it should be appended to cert_pem member of http_config , which is a part of ota_config . In case of error, this API explicitly sets handle to NULL. Note This API is blocking, so setting is_async member of http_config structure will result in an error. Parameters ota_config -- [in] pointer to esp_https_ota_config_t structure handle -- [out] pointer to an allocated data of type esp_https_ota_handle_t which will be initialised in this function ota_config -- [in] pointer to esp_https_ota_config_t structure handle -- [out] pointer to an allocated data of type esp_https_ota_handle_t which will be initialised in this function ota_config -- [in] pointer to esp_https_ota_config_t structure Returns ESP_OK: HTTPS OTA Firmware upgrade context initialised and HTTPS connection established ESP_FAIL: For generic failure. ESP_ERR_INVALID_ARG: Invalid argument (missing/incorrect config, certificate, etc.) For other return codes, refer documentation in app_update component and esp_http_client component in esp-idf. ESP_OK: HTTPS OTA Firmware upgrade context initialised and HTTPS connection established ESP_FAIL: For generic failure. ESP_ERR_INVALID_ARG: Invalid argument (missing/incorrect config, certificate, etc.) For other return codes, refer documentation in app_update component and esp_http_client component in esp-idf. ESP_OK: HTTPS OTA Firmware upgrade context initialised and HTTPS connection established Parameters ota_config -- [in] pointer to esp_https_ota_config_t structure handle -- [out] pointer to an allocated data of type esp_https_ota_handle_t which will be initialised in this function Returns ESP_OK: HTTPS OTA Firmware upgrade context initialised and HTTPS connection established ESP_FAIL: For generic failure. ESP_ERR_INVALID_ARG: Invalid argument (missing/incorrect config, certificate, etc.) For other return codes, refer documentation in app_update component and esp_http_client component in esp-idf. esp_err_t esp_https_ota_perform(esp_https_ota_handle_t https_ota_handle) Read image data from HTTP stream and write it to OTA partition. This function reads image data from HTTP stream and writes it to OTA partition. This function must be called only if esp_https_ota_begin() returns successfully. This function must be called in a loop since it returns after every HTTP read operation thus giving you the flexibility to stop OTA operation midway. Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure Returns ESP_ERR_HTTPS_OTA_IN_PROGRESS: OTA update is in progress, call this API again to continue. ESP_OK: OTA update was successful ESP_FAIL: OTA update failed ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_INVALID_VERSION: Invalid chip revision in image header ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation. ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. For other return codes, refer OTA documentation in esp-idf's app_update component. ESP_ERR_HTTPS_OTA_IN_PROGRESS: OTA update is in progress, call this API again to continue. ESP_OK: OTA update was successful ESP_FAIL: OTA update failed ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_INVALID_VERSION: Invalid chip revision in image header ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation. ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. For other return codes, refer OTA documentation in esp-idf's app_update component. ESP_ERR_HTTPS_OTA_IN_PROGRESS: OTA update is in progress, call this API again to continue. Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure Returns ESP_ERR_HTTPS_OTA_IN_PROGRESS: OTA update is in progress, call this API again to continue. ESP_OK: OTA update was successful ESP_FAIL: OTA update failed ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_INVALID_VERSION: Invalid chip revision in image header ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation. ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. For other return codes, refer OTA documentation in esp-idf's app_update component. bool esp_https_ota_is_complete_data_received(esp_https_ota_handle_t https_ota_handle) Checks if complete data was received or not. Note This API can be called just before esp_https_ota_finish() to validate if the complete image was indeed received. Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure Returns false true false true false Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure Returns false true esp_err_t esp_https_ota_finish(esp_https_ota_handle_t https_ota_handle) Clean-up HTTPS OTA Firmware upgrade and close HTTPS connection. This function closes the HTTP connection and frees the ESP HTTPS OTA context. This function switches the boot partition to the OTA partition containing the new firmware image. Note If this API returns successfully, esp_restart() must be called to boot from the new firmware image esp_https_ota_finish should not be called after calling esp_https_ota_abort Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure Returns ESP_OK: Clean-up successful ESP_ERR_INVALID_STATE ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image ESP_OK: Clean-up successful ESP_ERR_INVALID_STATE ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image ESP_OK: Clean-up successful Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure Returns ESP_OK: Clean-up successful ESP_ERR_INVALID_STATE ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image esp_err_t esp_https_ota_abort(esp_https_ota_handle_t https_ota_handle) Clean-up HTTPS OTA Firmware upgrade and close HTTPS connection. This function closes the HTTP connection and frees the ESP HTTPS OTA context. Note esp_https_ota_abort should not be called after calling esp_https_ota_finish Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure Returns ESP_OK: Clean-up successful ESP_ERR_INVALID_STATE: Invalid ESP HTTPS OTA state ESP_FAIL: OTA not started ESP_ERR_NOT_FOUND: OTA handle not found ESP_ERR_INVALID_ARG: Invalid argument ESP_OK: Clean-up successful ESP_ERR_INVALID_STATE: Invalid ESP HTTPS OTA state ESP_FAIL: OTA not started ESP_ERR_NOT_FOUND: OTA handle not found ESP_ERR_INVALID_ARG: Invalid argument ESP_OK: Clean-up successful Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure Returns ESP_OK: Clean-up successful ESP_ERR_INVALID_STATE: Invalid ESP HTTPS OTA state ESP_FAIL: OTA not started ESP_ERR_NOT_FOUND: OTA handle not found ESP_ERR_INVALID_ARG: Invalid argument esp_err_t esp_https_ota_get_img_desc(esp_https_ota_handle_t https_ota_handle, esp_app_desc_t *new_app_info) Reads app description from image header. The app description provides information like the "Firmware version" of the image. Note This API can be called only after esp_https_ota_begin() and before esp_https_ota_perform(). Calling this API is not mandatory. Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure new_app_info -- [out] pointer to an allocated esp_app_desc_t structure https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure new_app_info -- [out] pointer to an allocated esp_app_desc_t structure https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure Returns ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_INVALID_STATE: Invalid state to call this API. esp_https_ota_begin() not called yet. ESP_FAIL: Failed to read image descriptor ESP_OK: Successfully read image descriptor ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_INVALID_STATE: Invalid state to call this API. esp_https_ota_begin() not called yet. ESP_FAIL: Failed to read image descriptor ESP_OK: Successfully read image descriptor ESP_ERR_INVALID_ARG: Invalid arguments Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure new_app_info -- [out] pointer to an allocated esp_app_desc_t structure Returns ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_INVALID_STATE: Invalid state to call this API. esp_https_ota_begin() not called yet. ESP_FAIL: Failed to read image descriptor ESP_OK: Successfully read image descriptor int esp_https_ota_get_image_len_read(esp_https_ota_handle_t https_ota_handle) This function returns OTA image data read so far. Note This API should be called only if esp_https_ota_perform() has been called atleast once or if esp_https_ota_get_img_desc has been called before. Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure Returns -1 On failure total bytes read so far -1 On failure total bytes read so far -1 On failure Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure Returns -1 On failure total bytes read so far int esp_https_ota_get_image_size(esp_https_ota_handle_t https_ota_handle) This function returns OTA image total size. Note This API should be called after esp_https_ota_begin() has been already called. This can be used to create some sort of progress indication (in combination with esp_https_ota_get_image_len_read()) Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure Returns -1 On failure or chunked encoding total bytes of image -1 On failure or chunked encoding total bytes of image -1 On failure or chunked encoding Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure Returns -1 On failure or chunked encoding total bytes of image Structures struct esp_https_ota_config_t ESP HTTPS OTA configuration. Public Members const esp_http_client_config_t *http_config ESP HTTP client configuration const esp_http_client_config_t *http_config ESP HTTP client configuration http_client_init_cb_t http_client_init_cb Callback after ESP HTTP client is initialised http_client_init_cb_t http_client_init_cb Callback after ESP HTTP client is initialised bool bulk_flash_erase Erase entire flash partition during initialization. By default flash partition is erased during write operation and in chunk of 4K sector size bool bulk_flash_erase Erase entire flash partition during initialization. By default flash partition is erased during write operation and in chunk of 4K sector size bool partial_http_download Enable Firmware image to be downloaded over multiple HTTP requests bool partial_http_download Enable Firmware image to be downloaded over multiple HTTP requests int max_http_request_size Maximum request size for partial HTTP download int max_http_request_size Maximum request size for partial HTTP download const esp_http_client_config_t *http_config Macros ESP_ERR_HTTPS_OTA_BASE ESP_ERR_HTTPS_OTA_IN_PROGRESS Type Definitions typedef void *esp_https_ota_handle_t typedef esp_err_t (*http_client_init_cb_t)(esp_http_client_handle_t) Enumerations enum esp_https_ota_event_t Events generated by OTA process. Values: enumerator ESP_HTTPS_OTA_START OTA started enumerator ESP_HTTPS_OTA_START OTA started enumerator ESP_HTTPS_OTA_CONNECTED Connected to server enumerator ESP_HTTPS_OTA_CONNECTED Connected to server enumerator ESP_HTTPS_OTA_GET_IMG_DESC Read app description from image header enumerator ESP_HTTPS_OTA_GET_IMG_DESC Read app description from image header enumerator ESP_HTTPS_OTA_VERIFY_CHIP_ID Verify chip id of new image enumerator ESP_HTTPS_OTA_VERIFY_CHIP_ID Verify chip id of new image enumerator ESP_HTTPS_OTA_DECRYPT_CB Callback to decrypt function enumerator ESP_HTTPS_OTA_DECRYPT_CB Callback to decrypt function enumerator ESP_HTTPS_OTA_WRITE_FLASH Flash write operation enumerator ESP_HTTPS_OTA_WRITE_FLASH Flash write operation enumerator ESP_HTTPS_OTA_UPDATE_BOOT_PARTITION Boot partition update after successful ota update enumerator ESP_HTTPS_OTA_UPDATE_BOOT_PARTITION Boot partition update after successful ota update enumerator ESP_HTTPS_OTA_FINISH OTA finished enumerator ESP_HTTPS_OTA_FINISH OTA finished enumerator ESP_HTTPS_OTA_ABORT OTA aborted enumerator ESP_HTTPS_OTA_ABORT OTA aborted enumerator ESP_HTTPS_OTA_START
ESP HTTPS OTA Overview esp_https_ota provides simplified APIs to perform firmware upgrades over HTTPS. It is an abstraction layer over the existing OTA APIs. Application Example esp_err_t do_firmware_upgrade() { esp_http_client_config_t config = { .url = CONFIG_FIRMWARE_UPGRADE_URL, .cert_pem = (char *)server_cert_pem_start, }; esp_https_ota_config_t ota_config = { .http_config = &config, }; esp_err_t ret = esp_https_ota(&ota_config); if (ret == ESP_OK) { esp_restart(); } else { return ESP_FAIL; } return ESP_OK; } Server Verification Please refer to ESP-TLS: TLS Server Verification for more information on server verification. The root certificate in PEM format needs to be provided to the esp_http_client_config_t::cert_pem member. Note The server-endpoint root certificate should be used for verification instead of any intermediate ones from the certificate chain. The reason is that the root certificate has the maximum validity and usually remains the same for a long period of time. Users can also use the esp_http_client_config_t::crt_bundle_attach member for verification by the ESP x509 Certificate Bundle feature, which covers most of the trusted root certificates. Partial Image Download over HTTPS To use the partial image download feature, enable partial_http_download configuration in esp_https_ota_config_t. When this configuration is enabled, firmware image will be downloaded in multiple HTTP requests of specified sizes. Maximum content length of each request can be specified by setting max_http_request_size to the required value. This option is useful while fetching image from a service like AWS S3, where mbedTLS Rx buffer size (CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN) can be set to a lower value which is not possible without enabling this configuration. Default value of mbedTLS Rx buffer size is set to 16 KB. By using partial_http_download with max_http_request_size of 4 KB, size of mbedTLS Rx buffer can be reduced to 4 KB. With this configuration, memory saving of around 12 KB is expected. Signature Verification For additional security, signature of OTA firmware images can be verified. For more information, please refer to Secure OTA Updates Without Secure Boot. Advanced APIs esp_https_ota also provides advanced APIs which can be used if more information and control is needed during the OTA process. Example that uses advanced ESP_HTTPS_OTA APIs: system/ota/advanced_https_ota. OTA Upgrades with Pre-Encrypted Firmware To perform OTA upgrades with pre-encrypted firmware, please enable CONFIG_ESP_HTTPS_OTA_DECRYPT_CB in component menuconfig. Example that performs OTA upgrade with pre-encrypted firmware: system/ota/pre_encrypted_ota. OTA System Events ESP HTTPS OTA has various events for which a handler can be triggered by the Event Loop Library when the particular event occurs. The handler has to be registered using esp_event_handler_register(). This helps the event handling for ESP HTTPS OTA. esp_https_ota_event_t has all the events which can happen when performing OTA upgrade using ESP HTTPS OTA. Event Handler Example /* Event handler for catching system events */ static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) { if (event_base == ESP_HTTPS_OTA_EVENT) { switch (event_id) { case ESP_HTTPS_OTA_START: ESP_LOGI(TAG, "OTA started"); break; case ESP_HTTPS_OTA_CONNECTED: ESP_LOGI(TAG, "Connected to server"); break; case ESP_HTTPS_OTA_GET_IMG_DESC: ESP_LOGI(TAG, "Reading Image Description"); break; case ESP_HTTPS_OTA_VERIFY_CHIP_ID: ESP_LOGI(TAG, "Verifying chip id of new image: %d", *(esp_chip_id_t *)event_data); break; case ESP_HTTPS_OTA_DECRYPT_CB: ESP_LOGI(TAG, "Callback to decrypt function"); break; case ESP_HTTPS_OTA_WRITE_FLASH: ESP_LOGD(TAG, "Writing to flash: %d written", *(int *)event_data); break; case ESP_HTTPS_OTA_UPDATE_BOOT_PARTITION: ESP_LOGI(TAG, "Boot partition updated. Next Partition: %d", *(esp_partition_subtype_t *)event_data); break; case ESP_HTTPS_OTA_FINISH: ESP_LOGI(TAG, "OTA finish"); break; case ESP_HTTPS_OTA_ABORT: ESP_LOGI(TAG, "OTA abort"); break; } } } Expected data type for different ESP HTTPS OTA events in the system event loop: - ESP_HTTPS_OTA_START : NULL - ESP_HTTPS_OTA_CONNECTED : NULL - ESP_HTTPS_OTA_GET_IMG_DESC : NULL - ESP_HTTPS_OTA_VERIFY_CHIP_ID : esp_chip_id_t - ESP_HTTPS_OTA_DECRYPT_CB : NULL - ESP_HTTPS_OTA_WRITE_FLASH : int - ESP_HTTPS_OTA_UPDATE_BOOT_PARTITION : esp_partition_subtype_t - ESP_HTTPS_OTA_FINISH : NULL - ESP_HTTPS_OTA_ABORT : NULL API Reference Header File This header file can be included with: #include "esp_https_ota.h" This header file is a part of the API provided by the esp_https_otacomponent. To declare that your component depends on esp_https_ota, add the following to your CMakeLists.txt: REQUIRES esp_https_ota or PRIV_REQUIRES esp_https_ota Functions - esp_err_t esp_https_ota(const esp_https_ota_config_t *ota_config) HTTPS OTA Firmware upgrade. This function allocates HTTPS OTA Firmware upgrade context, establishes HTTPS connection, reads image data from HTTP stream and writes it to OTA partition and finishes HTTPS OTA Firmware upgrade operation. This API supports URL redirection, but if CA cert of URLs differ then it should be appended to cert_pemmember of ota_config->http_config. Note This API handles the entire OTA operation, so if this API is being used then no other APIs from esp_https_otacomponent should be called. If more information and control is needed during the HTTPS OTA process, then one can use esp_https_ota_beginand subsequent APIs. If this API returns successfully, esp_restart() must be called to boot from the new firmware image. - Parameters ota_config -- [in] pointer to esp_https_ota_config_t structure. - Returns ESP_OK: OTA data updated, next reboot will use specified partition. ESP_FAIL: For generic failure. ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation. ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. For other return codes, refer OTA documentation in esp-idf's app_update component. - - esp_err_t esp_https_ota_begin(const esp_https_ota_config_t *ota_config, esp_https_ota_handle_t *handle) Start HTTPS OTA Firmware upgrade. This function initializes ESP HTTPS OTA context and establishes HTTPS connection. This function must be invoked first. If this function returns successfully, then esp_https_ota_performshould be called to continue with the OTA process and there should be a call to esp_https_ota_finishon completion of OTA operation or on failure in subsequent operations. This API supports URL redirection, but if CA cert of URLs differ then it should be appended to cert_pemmember of http_config, which is a part of ota_config. In case of error, this API explicitly sets handleto NULL. Note This API is blocking, so setting is_asyncmember of http_configstructure will result in an error. - Parameters ota_config -- [in] pointer to esp_https_ota_config_t structure handle -- [out] pointer to an allocated data of type esp_https_ota_handle_twhich will be initialised in this function - - Returns ESP_OK: HTTPS OTA Firmware upgrade context initialised and HTTPS connection established ESP_FAIL: For generic failure. ESP_ERR_INVALID_ARG: Invalid argument (missing/incorrect config, certificate, etc.) For other return codes, refer documentation in app_update component and esp_http_client component in esp-idf. - - esp_err_t esp_https_ota_perform(esp_https_ota_handle_t https_ota_handle) Read image data from HTTP stream and write it to OTA partition. This function reads image data from HTTP stream and writes it to OTA partition. This function must be called only if esp_https_ota_begin() returns successfully. This function must be called in a loop since it returns after every HTTP read operation thus giving you the flexibility to stop OTA operation midway. - Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure - Returns ESP_ERR_HTTPS_OTA_IN_PROGRESS: OTA update is in progress, call this API again to continue. ESP_OK: OTA update was successful ESP_FAIL: OTA update failed ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_INVALID_VERSION: Invalid chip revision in image header ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation. ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. For other return codes, refer OTA documentation in esp-idf's app_update component. - - bool esp_https_ota_is_complete_data_received(esp_https_ota_handle_t https_ota_handle) Checks if complete data was received or not. Note This API can be called just before esp_https_ota_finish() to validate if the complete image was indeed received. - Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure - Returns false true - - esp_err_t esp_https_ota_finish(esp_https_ota_handle_t https_ota_handle) Clean-up HTTPS OTA Firmware upgrade and close HTTPS connection. This function closes the HTTP connection and frees the ESP HTTPS OTA context. This function switches the boot partition to the OTA partition containing the new firmware image. Note If this API returns successfully, esp_restart() must be called to boot from the new firmware image esp_https_ota_finish should not be called after calling esp_https_ota_abort - Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure - Returns ESP_OK: Clean-up successful ESP_ERR_INVALID_STATE ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image - - esp_err_t esp_https_ota_abort(esp_https_ota_handle_t https_ota_handle) Clean-up HTTPS OTA Firmware upgrade and close HTTPS connection. This function closes the HTTP connection and frees the ESP HTTPS OTA context. Note esp_https_ota_abort should not be called after calling esp_https_ota_finish - Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure - Returns ESP_OK: Clean-up successful ESP_ERR_INVALID_STATE: Invalid ESP HTTPS OTA state ESP_FAIL: OTA not started ESP_ERR_NOT_FOUND: OTA handle not found ESP_ERR_INVALID_ARG: Invalid argument - - esp_err_t esp_https_ota_get_img_desc(esp_https_ota_handle_t https_ota_handle, esp_app_desc_t *new_app_info) Reads app description from image header. The app description provides information like the "Firmware version" of the image. Note This API can be called only after esp_https_ota_begin() and before esp_https_ota_perform(). Calling this API is not mandatory. - Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure new_app_info -- [out] pointer to an allocated esp_app_desc_t structure - - Returns ESP_ERR_INVALID_ARG: Invalid arguments ESP_ERR_INVALID_STATE: Invalid state to call this API. esp_https_ota_begin() not called yet. ESP_FAIL: Failed to read image descriptor ESP_OK: Successfully read image descriptor - - int esp_https_ota_get_image_len_read(esp_https_ota_handle_t https_ota_handle) This function returns OTA image data read so far. Note This API should be called only if esp_https_ota_perform()has been called atleast once or if esp_https_ota_get_img_deschas been called before. - Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure - Returns -1 On failure total bytes read so far - - int esp_https_ota_get_image_size(esp_https_ota_handle_t https_ota_handle) This function returns OTA image total size. Note This API should be called after esp_https_ota_begin() has been already called. This can be used to create some sort of progress indication (in combination with esp_https_ota_get_image_len_read()) - Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure - Returns -1 On failure or chunked encoding total bytes of image - Structures - struct esp_https_ota_config_t ESP HTTPS OTA configuration. Public Members - const esp_http_client_config_t *http_config ESP HTTP client configuration - http_client_init_cb_t http_client_init_cb Callback after ESP HTTP client is initialised - bool bulk_flash_erase Erase entire flash partition during initialization. By default flash partition is erased during write operation and in chunk of 4K sector size - bool partial_http_download Enable Firmware image to be downloaded over multiple HTTP requests - int max_http_request_size Maximum request size for partial HTTP download - const esp_http_client_config_t *http_config Macros - ESP_ERR_HTTPS_OTA_BASE - ESP_ERR_HTTPS_OTA_IN_PROGRESS Type Definitions - typedef void *esp_https_ota_handle_t - typedef esp_err_t (*http_client_init_cb_t)(esp_http_client_handle_t) Enumerations - enum esp_https_ota_event_t Events generated by OTA process. Values: - enumerator ESP_HTTPS_OTA_START OTA started - enumerator ESP_HTTPS_OTA_CONNECTED Connected to server - enumerator ESP_HTTPS_OTA_GET_IMG_DESC Read app description from image header - enumerator ESP_HTTPS_OTA_VERIFY_CHIP_ID Verify chip id of new image - enumerator ESP_HTTPS_OTA_DECRYPT_CB Callback to decrypt function - enumerator ESP_HTTPS_OTA_WRITE_FLASH Flash write operation - enumerator ESP_HTTPS_OTA_UPDATE_BOOT_PARTITION Boot partition update after successful ota update - enumerator ESP_HTTPS_OTA_FINISH OTA finished - enumerator ESP_HTTPS_OTA_ABORT OTA aborted - enumerator ESP_HTTPS_OTA_START
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/esp_https_ota.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Event Loop Library
null
espressif.com
2016-01-01
f36eb6cf09f29f0e
null
null
Event Loop Library Overview The event loop library allows components to declare events so that other components can register handlers -- codes that executes when those events occur. This allows loosely-coupled components to attach desired behavior to state changes of other components without application involvement. This also simplifies event processing by serializing and deferring code execution to another context. One common case is, if a high-level library is using the Wi-Fi library: it may subscribe to ESP32 Wi-Fi Programming Model directly and act on those events. Note Various modules of the Bluetooth stack deliver events to applications via dedicated callback functions instead of via the Event Loop Library. Using esp_event APIs esp_event APIs There are two objects of concern for users of this library: events and event loops. An event indicates an important occurrence, such as a successful Wi-Fi connection to an access point. A two-part identifier should be used when referencing events, see declaring and defining events for details. The event loop is the bridge between events and event handlers. The event source publishes events to the event loop using the APIs provided by the event loop library, and event handlers registered to the event loop respond to specific types of events. Using this library roughly entails the following flow: The user defines a function that should run when an event is posted to a loop. This function is referred to as the event handler, and should have the same signature as esp_event_handler_t . An event loop is created using esp_event_loop_create() , which outputs a handle to the loop of type esp_event_loop_handle_t . Event loops created using this API are referred to as user event loops. There is, however, a special type of event loop called the default event loop which is discussed in default event loop. Components register event handlers to the loop using esp_event_handler_register_with() . Handlers can be registered with multiple loops, see notes on handler registration. Event sources post an event to the loop using esp_event_post_to() . Components wanting to remove their handlers from being called can do so by unregistering from the loop using esp_event_handler_unregister_with() . Event loops that are no longer needed can be deleted using esp_event_loop_delete() . In code, the flow above may look like as follows: // 1. Define the event handler void run_on_event(void* handler_arg, esp_event_base_t base, int32_t id, void* event_data) { // Event handler logic } void app_main() { // 2. A configuration structure of type esp_event_loop_args_t is needed to specify the properties of the loop to be created. A handle of type esp_event_loop_handle_t is obtained, which is needed by the other APIs to reference the loop to perform their operations. esp_event_loop_args_t loop_args = { .queue_size = ..., .task_name = ... .task_priority = ..., .task_stack_size = ..., .task_core_id = ... }; esp_event_loop_handle_t loop_handle; esp_event_loop_create(&loop_args, &loop_handle); // 3. Register event handler defined in (1). MY_EVENT_BASE and MY_EVENT_ID specify a hypothetical event that handler run_on_event should execute when it gets posted to the loop. esp_event_handler_register_with(loop_handle, MY_EVENT_BASE, MY_EVENT_ID, run_on_event, ...); ... // 4. Post events to the loop. This queues the event on the event loop. At some point, the event loop executes the event handler registered to the posted event, in this case, run_on_event. To simplify the process, this example calls esp_event_post_to from app_main, but posting can be done from any other task (which is the more interesting use case). esp_event_post_to(loop_handle, MY_EVENT_BASE, MY_EVENT_ID, ...); ... // 5. Unregistering an unneeded handler esp_event_handler_unregister_with(loop_handle, MY_EVENT_BASE, MY_EVENT_ID, run_on_event); ... // 6. Deleting an unneeded event loop esp_event_loop_delete(loop_handle); } Declaring and Defining Events As mentioned previously, events consist of two-part identifiers: the event base and the event ID. The event base identifies an independent group of events; the event ID identifies the event within that group. Think of the event base and event ID as a person's last name and first name, respectively. A last name identifies a family, and the first name identifies a person within that family. The event loop library provides macros to declare and define the event base easily. Event base declaration: ESP_EVENT_DECLARE_BASE(EVENT_BASE); Event base definition: ESP_EVENT_DEFINE_BASE(EVENT_BASE); Note In ESP-IDF, the base identifiers for system events are uppercase and are postfixed with _EVENT . For example, the base for Wi-Fi events is declared and defined as WIFI_EVENT , the Ethernet event base ETHERNET_EVENT , and so on. The purpose is to have event bases look like constants (although they are global variables considering the definitions of macros ESP_EVENT_DECLARE_BASE and ESP_EVENT_DEFINE_BASE ). For event IDs, declaring them as enumerations is recommended. Once again, for visibility, these are typically placed in public header files. Event ID: enum { EVENT_ID_1, EVENT_ID_2, EVENT_ID_3, ... } Default Event Loop The default event loop is a special type of loop used for system events (Wi-Fi events, for example). The handle for this loop is hidden from the user, and the creation, deletion, handler registration/deregistration, and posting of events are done through a variant of the APIs for user event loops. The table below enumerates those variants, and the user event loops equivalent. User Event Loops Default Event Loops If you compare the signatures for both, they are mostly similar except for the lack of loop handle specification for the default event loop APIs. Other than the API difference and the special designation to which system events are posted, there is no difference in how default event loops and user event loops behave. It is even possible for users to post their own events to the default event loop, should the user opt to not create their own loops to save memory. Notes on Handler Registration It is possible to register a single handler to multiple events individually by using multiple calls to esp_event_handler_register_with() . For those multiple calls, the specific event base and event ID can be specified with which the handler should execute. However, in some cases, it is desirable for a handler to execute on the following situations: all events that get posted to a loop all events of a particular base identifier This is possible using the special event base identifier ESP_EVENT_ANY_BASE and special event ID ESP_EVENT_ANY_ID . These special identifiers may be passed as the event base and event ID arguments for esp_event_handler_register_with() . Therefore, the valid arguments to esp_event_handler_register_with() are: <event base>, <event ID> - handler executes when the event with base <event base> and event ID <event ID> gets posted to the loop <event base>, ESP_EVENT_ANY_ID - handler executes when any event with base <event base> gets posted to the loop ESP_EVENT_ANY_BASE, ESP_EVENT_ANY_ID - handler executes when any event gets posted to the loop As an example, suppose the following handler registrations were performed: esp_event_handler_register_with(loop_handle, MY_EVENT_BASE, MY_EVENT_ID, run_on_event_1, ...); esp_event_handler_register_with(loop_handle, MY_EVENT_BASE, ESP_EVENT_ANY_ID, run_on_event_2, ...); esp_event_handler_register_with(loop_handle, ESP_EVENT_ANY_BASE, ESP_EVENT_ANY_ID, run_on_event_3, ...); If the hypothetical event MY_EVENT_BASE , MY_EVENT_ID is posted, all three handlers run_on_event_1 , run_on_event_2 , and run_on_event_3 would execute. If the hypothetical event MY_EVENT_BASE , MY_OTHER_EVENT_ID is posted, only run_on_event_2 and run_on_event_3 would execute. If the hypothetical event MY_OTHER_EVENT_BASE , MY_OTHER_EVENT_ID is posted, only run_on_event_3 would execute. Handler Un-Registering Itself In general, an event handler run by an event loop is not allowed to do any registering/unregistering activity on that event loop. There is one exception, though: un-registering itself is allowed for the handler. E.g., it is possible to do the following: void run_on_event(void* handler_arg, esp_event_base_t base, int32_t id, void* event_data) { esp_event_loop_handle_t *loop_handle = (esp_event_loop_handle_t*) handler_arg; esp_event_handler_unregister_with(*loop_handle, MY_EVENT_BASE, MY_EVENT_ID, run_on_event); } void app_main(void) { esp_event_loop_handle_t loop_handle; esp_event_loop_create(&loop_args, &loop_handle); esp_event_handler_register_with(loop_handle, MY_EVENT_BASE, MY_EVENT_ID, run_on_event, &loop_handle); // ... post-event MY_EVENT_BASE, MY_EVENT_ID and run loop at some point } Handler Registration and Handler Dispatch Order The general rule is that, for handlers that match a certain posted event during dispatch, those which are registered first also get executed first. The user can then control which handlers get executed first by registering them before other handlers, provided that all registrations are performed using a single task. If the user plans to take advantage of this behavior, caution must be exercised if there are multiple tasks registering handlers. While the 'first registered, first executed' behavior still holds true, the task which gets executed first also gets its handlers registered first. Handlers registered one after the other by a single task are still dispatched in the order relative to each other, but if that task gets pre-empted in between registration by another task that also registers handlers; then during dispatch those handlers also get executed in between. Event Loop Profiling A configuration option CONFIG_ESP_EVENT_LOOP_PROFILING can be enabled in order to activate statistics collection for all event loops created. The function esp_event_dump() can be used to output the collected statistics to a file stream. More details on the information included in the dump can be found in the esp_event_dump() API Reference. Application Example Examples of using the esp_event library can be found in system/esp_event. The examples cover event declaration, loop creation, handler registration and deregistration, and event posting. Other examples which also adopt esp_event library: NMEA Parser , which decodes the statements received from GPS. API Reference Header File This header file can be included with: #include "esp_event.h" This header file is a part of the API provided by the esp_event component. To declare that your component depends on esp_event , add the following to your CMakeLists.txt: REQUIRES esp_event or PRIV_REQUIRES esp_event Functions esp_err_t esp_event_loop_create(const esp_event_loop_args_t *event_loop_args, esp_event_loop_handle_t *event_loop) Create a new event loop. Parameters event_loop_args -- [in] configuration structure for the event loop to create event_loop -- [out] handle to the created event loop event_loop_args -- [in] configuration structure for the event loop to create event_loop -- [out] handle to the created event loop event_loop_args -- [in] configuration structure for the event loop to create Returns ESP_OK: Success ESP_ERR_INVALID_ARG: event_loop_args or event_loop was NULL ESP_ERR_NO_MEM: Cannot allocate memory for event loops list ESP_FAIL: Failed to create task loop Others: Fail ESP_OK: Success ESP_ERR_INVALID_ARG: event_loop_args or event_loop was NULL ESP_ERR_NO_MEM: Cannot allocate memory for event loops list ESP_FAIL: Failed to create task loop Others: Fail ESP_OK: Success Parameters event_loop_args -- [in] configuration structure for the event loop to create event_loop -- [out] handle to the created event loop Returns ESP_OK: Success ESP_ERR_INVALID_ARG: event_loop_args or event_loop was NULL ESP_ERR_NO_MEM: Cannot allocate memory for event loops list ESP_FAIL: Failed to create task loop Others: Fail esp_err_t esp_event_loop_delete(esp_event_loop_handle_t event_loop) Delete an existing event loop. Parameters event_loop -- [in] event loop to delete, must not be NULL Returns ESP_OK: Success Others: Fail ESP_OK: Success Others: Fail ESP_OK: Success Parameters event_loop -- [in] event loop to delete, must not be NULL Returns ESP_OK: Success Others: Fail esp_err_t esp_event_loop_create_default(void) Create default event loop. Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for event loops list ESP_ERR_INVALID_STATE: Default event loop has already been created ESP_FAIL: Failed to create task loop Others: Fail ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for event loops list ESP_ERR_INVALID_STATE: Default event loop has already been created ESP_FAIL: Failed to create task loop Others: Fail ESP_OK: Success Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for event loops list ESP_ERR_INVALID_STATE: Default event loop has already been created ESP_FAIL: Failed to create task loop Others: Fail esp_err_t esp_event_loop_delete_default(void) Delete the default event loop. Returns ESP_OK: Success Others: Fail ESP_OK: Success Others: Fail ESP_OK: Success Returns ESP_OK: Success Others: Fail esp_err_t esp_event_loop_run(esp_event_loop_handle_t event_loop, TickType_t ticks_to_run) Dispatch events posted to an event loop. This function is used to dispatch events posted to a loop with no dedicated task, i.e. task name was set to NULL in event_loop_args argument during loop creation. This function includes an argument to limit the amount of time it runs, returning control to the caller when that time expires (or some time afterwards). There is no guarantee that a call to this function will exit at exactly the time of expiry. There is also no guarantee that events have been dispatched during the call, as the function might have spent all the allotted time waiting on the event queue. Once an event has been dequeued, however, it is guaranteed to be dispatched. This guarantee contributes to not being able to exit exactly at time of expiry as (1) blocking on internal mutexes is necessary for dispatching the dequeued event, and (2) during dispatch of the dequeued event there is no way to control the time occupied by handler code execution. The guaranteed time of exit is therefore the allotted time + amount of time required to dispatch the last dequeued event. In cases where waiting on the queue times out, ESP_OK is returned and not ESP_ERR_TIMEOUT, since it is normal behavior. Note encountering an unknown event that has been posted to the loop will only generate a warning, not an error. Parameters event_loop -- [in] event loop to dispatch posted events from, must not be NULL ticks_to_run -- [in] number of ticks to run the loop event_loop -- [in] event loop to dispatch posted events from, must not be NULL ticks_to_run -- [in] number of ticks to run the loop event_loop -- [in] event loop to dispatch posted events from, must not be NULL Returns ESP_OK: Success Others: Fail ESP_OK: Success Others: Fail ESP_OK: Success Parameters event_loop -- [in] event loop to dispatch posted events from, must not be NULL ticks_to_run -- [in] number of ticks to run the loop Returns ESP_OK: Success Others: Fail esp_err_t esp_event_handler_register(esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler, void *event_handler_arg) Register an event handler to the system event loop (legacy). This function can be used to register a handler for either: (1) specific events, (2) all events of a certain event base, or (3) all events known by the system event loop. specific events: specify exact event_base and event_id all events of a certain base: specify exact event_base and use ESP_EVENT_ANY_ID as the event_id all events known by the loop: use ESP_EVENT_ANY_BASE for event_base and ESP_EVENT_ANY_ID as the event_id specific events: specify exact event_base and event_id all events of a certain base: specify exact event_base and use ESP_EVENT_ANY_ID as the event_id all events known by the loop: use ESP_EVENT_ANY_BASE for event_base and ESP_EVENT_ANY_ID as the event_id Registering multiple handlers to events is possible. Registering a single handler to multiple events is also possible. However, registering the same handler to the same event multiple times would cause the previous registrations to be overwritten. Note the event loop library does not maintain a copy of event_handler_arg, therefore the user should ensure that event_handler_arg still points to a valid location by the time the handler gets called Parameters event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called event_base -- [in] the base ID of the event to register the handler for Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail ESP_OK: Success Parameters event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail specific events: specify exact event_base and event_id esp_err_t esp_event_handler_register_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler, void *event_handler_arg) Register an event handler to a specific loop (legacy). This function behaves in the same manner as esp_event_handler_register, except the additional specification of the event loop to register the handler to. Note the event loop library does not maintain a copy of event_handler_arg, therefore the user should ensure that event_handler_arg still points to a valid location by the time the handler gets called Parameters event_loop -- [in] the event loop to register this handler function to, must not be NULL event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called event_loop -- [in] the event loop to register this handler function to, must not be NULL event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called event_loop -- [in] the event loop to register this handler function to, must not be NULL Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail ESP_OK: Success Parameters event_loop -- [in] the event loop to register this handler function to, must not be NULL event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail esp_err_t esp_event_handler_instance_register_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler, void *event_handler_arg, esp_event_handler_instance_t *instance) Register an instance of event handler to a specific loop. This function can be used to register a handler for either: (1) specific events, (2) all events of a certain event base, or (3) all events known by the system event loop. specific events: specify exact event_base and event_id all events of a certain base: specify exact event_base and use ESP_EVENT_ANY_ID as the event_id all events known by the loop: use ESP_EVENT_ANY_BASE for event_base and ESP_EVENT_ANY_ID as the event_id specific events: specify exact event_base and event_id all events of a certain base: specify exact event_base and use ESP_EVENT_ANY_ID as the event_id all events known by the loop: use ESP_EVENT_ANY_BASE for event_base and ESP_EVENT_ANY_ID as the event_id Besides the error, the function returns an instance object as output parameter to identify each registration. This is necessary to remove (unregister) the registration before the event loop is deleted. Registering multiple handlers to events, registering a single handler to multiple events as well as registering the same handler to the same event multiple times is possible. Each registration yields a distinct instance object which identifies it over the registration lifetime. Note the event loop library does not maintain a copy of event_handler_arg, therefore the user should ensure that event_handler_arg still points to a valid location by the time the handler gets called Parameters event_loop -- [in] the event loop to register this handler function to, must not be NULL event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called instance -- [out] An event handler instance object related to the registered event handler and data, can be NULL. This needs to be kept if the specific callback instance should be unregistered before deleting the whole event loop. Registering the same event handler multiple times is possible and yields distinct instance objects. The data can be the same for all registrations. If no unregistration is needed, but the handler should be deleted when the event loop is deleted, instance can be NULL. event_loop -- [in] the event loop to register this handler function to, must not be NULL event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called instance -- [out] An event handler instance object related to the registered event handler and data, can be NULL. This needs to be kept if the specific callback instance should be unregistered before deleting the whole event loop. Registering the same event handler multiple times is possible and yields distinct instance objects. The data can be the same for all registrations. If no unregistration is needed, but the handler should be deleted when the event loop is deleted, instance can be NULL. event_loop -- [in] the event loop to register this handler function to, must not be NULL Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID or instance is NULL Others: Fail ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID or instance is NULL Others: Fail ESP_OK: Success Parameters event_loop -- [in] the event loop to register this handler function to, must not be NULL event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called instance -- [out] An event handler instance object related to the registered event handler and data, can be NULL. This needs to be kept if the specific callback instance should be unregistered before deleting the whole event loop. Registering the same event handler multiple times is possible and yields distinct instance objects. The data can be the same for all registrations. If no unregistration is needed, but the handler should be deleted when the event loop is deleted, instance can be NULL. Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID or instance is NULL Others: Fail specific events: specify exact event_base and event_id esp_err_t esp_event_handler_instance_register(esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler, void *event_handler_arg, esp_event_handler_instance_t *instance) Register an instance of event handler to the default loop. This function does the same as esp_event_handler_instance_register_with, except that it registers the handler to the default event loop. Note the event loop library does not maintain a copy of event_handler_arg, therefore the user should ensure that event_handler_arg still points to a valid location by the time the handler gets called Parameters event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called instance -- [out] An event handler instance object related to the registered event handler and data, can be NULL. This needs to be kept if the specific callback instance should be unregistered before deleting the whole event loop. Registering the same event handler multiple times is possible and yields distinct instance objects. The data can be the same for all registrations. If no unregistration is needed, but the handler should be deleted when the event loop is deleted, instance can be NULL. event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called instance -- [out] An event handler instance object related to the registered event handler and data, can be NULL. This needs to be kept if the specific callback instance should be unregistered before deleting the whole event loop. Registering the same event handler multiple times is possible and yields distinct instance objects. The data can be the same for all registrations. If no unregistration is needed, but the handler should be deleted when the event loop is deleted, instance can be NULL. event_base -- [in] the base ID of the event to register the handler for Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID or instance is NULL Others: Fail ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID or instance is NULL Others: Fail ESP_OK: Success Parameters event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called instance -- [out] An event handler instance object related to the registered event handler and data, can be NULL. This needs to be kept if the specific callback instance should be unregistered before deleting the whole event loop. Registering the same event handler multiple times is possible and yields distinct instance objects. The data can be the same for all registrations. If no unregistration is needed, but the handler should be deleted when the event loop is deleted, instance can be NULL. Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID or instance is NULL Others: Fail esp_err_t esp_event_handler_unregister(esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler) Unregister a handler with the system event loop (legacy). Unregisters a handler, so it will no longer be called during dispatch. Handlers can be unregistered for any combination of event_base and event_id which were previously registered. To unregister a handler, the event_base and event_id arguments must match exactly the arguments passed to esp_event_handler_register() when that handler was registered. Passing ESP_EVENT_ANY_BASE and/or ESP_EVENT_ANY_ID will only unregister handlers that were registered with the same wildcard arguments. Note When using ESP_EVENT_ANY_ID, handlers registered to specific event IDs using the same base will not be unregistered. When using ESP_EVENT_ANY_BASE, events registered to specific bases will also not be unregistered. This avoids accidental unregistration of handlers registered by other users or components. Parameters event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler event_handler -- [in] the handler to unregister event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler event_handler -- [in] the handler to unregister event_base -- [in] the base of the event with which to unregister the handler Returns ESP_OK success Returns ESP_ERR_INVALID_ARG invalid combination of event base and event ID Returns others fail Parameters event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler event_handler -- [in] the handler to unregister Returns ESP_OK success Returns ESP_ERR_INVALID_ARG invalid combination of event base and event ID Returns others fail esp_err_t esp_event_handler_unregister_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler) Unregister a handler from a specific event loop (legacy). This function behaves in the same manner as esp_event_handler_unregister, except the additional specification of the event loop to unregister the handler with. Parameters event_loop -- [in] the event loop with which to unregister this handler function, must not be NULL event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler event_handler -- [in] the handler to unregister event_loop -- [in] the event loop with which to unregister this handler function, must not be NULL event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler event_handler -- [in] the handler to unregister event_loop -- [in] the event loop with which to unregister this handler function, must not be NULL Returns ESP_OK: Success ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail ESP_OK: Success ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail ESP_OK: Success Parameters event_loop -- [in] the event loop with which to unregister this handler function, must not be NULL event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler event_handler -- [in] the handler to unregister Returns ESP_OK: Success ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail esp_err_t esp_event_handler_instance_unregister_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, esp_event_handler_instance_t instance) Unregister a handler instance from a specific event loop. Unregisters a handler instance, so it will no longer be called during dispatch. Handler instances can be unregistered for any combination of event_base and event_id which were previously registered. To unregister a handler instance, the event_base and event_id arguments must match exactly the arguments passed to esp_event_handler_instance_register() when that handler instance was registered. Passing ESP_EVENT_ANY_BASE and/or ESP_EVENT_ANY_ID will only unregister handler instances that were registered with the same wildcard arguments. Note When using ESP_EVENT_ANY_ID, handlers registered to specific event IDs using the same base will not be unregistered. When using ESP_EVENT_ANY_BASE, events registered to specific bases will also not be unregistered. This avoids accidental unregistration of handlers registered by other users or components. Parameters event_loop -- [in] the event loop with which to unregister this handler function, must not be NULL event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler instance -- [in] the instance object of the registration to be unregistered event_loop -- [in] the event loop with which to unregister this handler function, must not be NULL event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler instance -- [in] the instance object of the registration to be unregistered event_loop -- [in] the event loop with which to unregister this handler function, must not be NULL Returns ESP_OK: Success ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail ESP_OK: Success ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail ESP_OK: Success Parameters event_loop -- [in] the event loop with which to unregister this handler function, must not be NULL event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler instance -- [in] the instance object of the registration to be unregistered Returns ESP_OK: Success ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail esp_err_t esp_event_handler_instance_unregister(esp_event_base_t event_base, int32_t event_id, esp_event_handler_instance_t instance) Unregister a handler from the system event loop. This function does the same as esp_event_handler_instance_unregister_with, except that it unregisters the handler instance from the default event loop. Parameters event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler instance -- [in] the instance object of the registration to be unregistered event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler instance -- [in] the instance object of the registration to be unregistered event_base -- [in] the base of the event with which to unregister the handler Returns ESP_OK: Success ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail ESP_OK: Success ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail ESP_OK: Success Parameters event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler instance -- [in] the instance object of the registration to be unregistered Returns ESP_OK: Success ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail esp_err_t esp_event_post(esp_event_base_t event_base, int32_t event_id, const void *event_data, size_t event_data_size, TickType_t ticks_to_wait) Posts an event to the system default event loop. The event loop library keeps a copy of event_data and manages the copy's lifetime automatically (allocation + deletion); this ensures that the data the handler receives is always valid. Parameters event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data ticks_to_wait -- [in] number of ticks to block on a full event queue event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data ticks_to_wait -- [in] number of ticks to block on a full event queue event_base -- [in] the event base that identifies the event Returns ESP_OK: Success ESP_ERR_TIMEOUT: Time to wait for event queue to unblock expired, queue full when posting from ISR ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail ESP_OK: Success ESP_ERR_TIMEOUT: Time to wait for event queue to unblock expired, queue full when posting from ISR ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail ESP_OK: Success Parameters event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data ticks_to_wait -- [in] number of ticks to block on a full event queue Returns ESP_OK: Success ESP_ERR_TIMEOUT: Time to wait for event queue to unblock expired, queue full when posting from ISR ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail esp_err_t esp_event_post_to(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, const void *event_data, size_t event_data_size, TickType_t ticks_to_wait) Posts an event to the specified event loop. The event loop library keeps a copy of event_data and manages the copy's lifetime automatically (allocation + deletion); this ensures that the data the handler receives is always valid. This function behaves in the same manner as esp_event_post_to, except the additional specification of the event loop to post the event to. Parameters event_loop -- [in] the event loop to post to, must not be NULL event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data ticks_to_wait -- [in] number of ticks to block on a full event queue event_loop -- [in] the event loop to post to, must not be NULL event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data ticks_to_wait -- [in] number of ticks to block on a full event queue event_loop -- [in] the event loop to post to, must not be NULL Returns ESP_OK: Success ESP_ERR_TIMEOUT: Time to wait for event queue to unblock expired, queue full when posting from ISR ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail ESP_OK: Success ESP_ERR_TIMEOUT: Time to wait for event queue to unblock expired, queue full when posting from ISR ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail ESP_OK: Success Parameters event_loop -- [in] the event loop to post to, must not be NULL event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data ticks_to_wait -- [in] number of ticks to block on a full event queue Returns ESP_OK: Success ESP_ERR_TIMEOUT: Time to wait for event queue to unblock expired, queue full when posting from ISR ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail esp_err_t esp_event_isr_post(esp_event_base_t event_base, int32_t event_id, const void *event_data, size_t event_data_size, BaseType_t *task_unblocked) Special variant of esp_event_post for posting events from interrupt handlers. Note this function is only available when CONFIG_ESP_EVENT_POST_FROM_ISR is enabled Note when this function is called from an interrupt handler placed in IRAM, this function should be placed in IRAM as well by enabling CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR Parameters event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data; max is 4 bytes task_unblocked -- [out] an optional parameter (can be NULL) which indicates that an event task with higher priority than currently running task has been unblocked by the posted event; a context switch should be requested before the interrupt is existed. event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data; max is 4 bytes task_unblocked -- [out] an optional parameter (can be NULL) which indicates that an event task with higher priority than currently running task has been unblocked by the posted event; a context switch should be requested before the interrupt is existed. event_base -- [in] the event base that identifies the event Returns ESP_OK: Success ESP_FAIL: Event queue for the default event loop full ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID, data size of more than 4 bytes Others: Fail ESP_OK: Success ESP_FAIL: Event queue for the default event loop full ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID, data size of more than 4 bytes Others: Fail ESP_OK: Success Parameters event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data; max is 4 bytes task_unblocked -- [out] an optional parameter (can be NULL) which indicates that an event task with higher priority than currently running task has been unblocked by the posted event; a context switch should be requested before the interrupt is existed. Returns ESP_OK: Success ESP_FAIL: Event queue for the default event loop full ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID, data size of more than 4 bytes Others: Fail esp_err_t esp_event_isr_post_to(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, const void *event_data, size_t event_data_size, BaseType_t *task_unblocked) Special variant of esp_event_post_to for posting events from interrupt handlers. Note this function is only available when CONFIG_ESP_EVENT_POST_FROM_ISR is enabled Note when this function is called from an interrupt handler placed in IRAM, this function should be placed in IRAM as well by enabling CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR Parameters event_loop -- [in] the event loop to post to, must not be NULL event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data task_unblocked -- [out] an optional parameter (can be NULL) which indicates that an event task with higher priority than currently running task has been unblocked by the posted event; a context switch should be requested before the interrupt is existed. event_loop -- [in] the event loop to post to, must not be NULL event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data task_unblocked -- [out] an optional parameter (can be NULL) which indicates that an event task with higher priority than currently running task has been unblocked by the posted event; a context switch should be requested before the interrupt is existed. event_loop -- [in] the event loop to post to, must not be NULL Returns ESP_OK: Success ESP_FAIL: Event queue for the loop full ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID, data size of more than 4 bytes Others: Fail ESP_OK: Success ESP_FAIL: Event queue for the loop full ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID, data size of more than 4 bytes Others: Fail ESP_OK: Success Parameters event_loop -- [in] the event loop to post to, must not be NULL event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data task_unblocked -- [out] an optional parameter (can be NULL) which indicates that an event task with higher priority than currently running task has been unblocked by the posted event; a context switch should be requested before the interrupt is existed. Returns ESP_OK: Success ESP_FAIL: Event queue for the loop full ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID, data size of more than 4 bytes Others: Fail esp_err_t esp_event_dump(FILE *file) Dumps statistics of all event loops. Dumps event loop info in the format: event loop handler handler ... event loop handler handler ... where: event loop format: address,name rx:total_received dr:total_dropped where: address - memory address of the event loop name - name of the event loop, 'none' if no dedicated task total_received - number of successfully posted events total_dropped - number of events unsuccessfully posted due to queue being full handler format: address ev:base,id inv:total_invoked run:total_runtime where: address - address of the handler function base,id - the event specified by event base and ID this handler executes total_invoked - number of times this handler has been invoked total_runtime - total amount of time used for invoking this handler Note this function is a noop when CONFIG_ESP_EVENT_LOOP_PROFILING is disabled Parameters file -- [in] the file stream to output to Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for event loops list Others: Fail ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for event loops list Others: Fail ESP_OK: Success Parameters file -- [in] the file stream to output to Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for event loops list Others: Fail Structures struct esp_event_loop_args_t Configuration for creating event loops. Public Members int32_t queue_size size of the event loop queue int32_t queue_size size of the event loop queue const char *task_name name of the event loop task; if NULL, a dedicated task is not created for event loop const char *task_name name of the event loop task; if NULL, a dedicated task is not created for event loop UBaseType_t task_priority priority of the event loop task, ignored if task name is NULL UBaseType_t task_priority priority of the event loop task, ignored if task name is NULL uint32_t task_stack_size stack size of the event loop task, ignored if task name is NULL uint32_t task_stack_size stack size of the event loop task, ignored if task name is NULL BaseType_t task_core_id core to which the event loop task is pinned to, ignored if task name is NULL BaseType_t task_core_id core to which the event loop task is pinned to, ignored if task name is NULL int32_t queue_size Header File This header file can be included with: #include "esp_event_base.h" This header file is a part of the API provided by the esp_event component. To declare that your component depends on esp_event , add the following to your CMakeLists.txt: REQUIRES esp_event or PRIV_REQUIRES esp_event Macros ESP_EVENT_DECLARE_BASE(id) ESP_EVENT_DEFINE_BASE(id) ESP_EVENT_ANY_BASE register handler for any event base ESP_EVENT_ANY_ID register handler for any event id Type Definitions typedef void *esp_event_loop_handle_t a number that identifies an event with respect to a base typedef void (*esp_event_handler_t)(void *event_handler_arg, esp_event_base_t event_base, int32_t event_id, void *event_data) function called when an event is posted to the queue typedef void *esp_event_handler_instance_t context identifying an instance of a registered event handler
Event Loop Library Overview The event loop library allows components to declare events so that other components can register handlers -- codes that executes when those events occur. This allows loosely-coupled components to attach desired behavior to state changes of other components without application involvement. This also simplifies event processing by serializing and deferring code execution to another context. One common case is, if a high-level library is using the Wi-Fi library: it may subscribe to ESP32 Wi-Fi Programming Model directly and act on those events. Note Various modules of the Bluetooth stack deliver events to applications via dedicated callback functions instead of via the Event Loop Library. Using esp_event APIs There are two objects of concern for users of this library: events and event loops. An event indicates an important occurrence, such as a successful Wi-Fi connection to an access point. A two-part identifier should be used when referencing events, see declaring and defining events for details. The event loop is the bridge between events and event handlers. The event source publishes events to the event loop using the APIs provided by the event loop library, and event handlers registered to the event loop respond to specific types of events. Using this library roughly entails the following flow: The user defines a function that should run when an event is posted to a loop. This function is referred to as the event handler, and should have the same signature as esp_event_handler_t. An event loop is created using esp_event_loop_create(), which outputs a handle to the loop of type esp_event_loop_handle_t. Event loops created using this API are referred to as user event loops. There is, however, a special type of event loop called the default event loop which is discussed in default event loop. Components register event handlers to the loop using esp_event_handler_register_with(). Handlers can be registered with multiple loops, see notes on handler registration. Event sources post an event to the loop using esp_event_post_to(). Components wanting to remove their handlers from being called can do so by unregistering from the loop using esp_event_handler_unregister_with(). Event loops that are no longer needed can be deleted using esp_event_loop_delete(). In code, the flow above may look like as follows: // 1. Define the event handler void run_on_event(void* handler_arg, esp_event_base_t base, int32_t id, void* event_data) { // Event handler logic } void app_main() { // 2. A configuration structure of type esp_event_loop_args_t is needed to specify the properties of the loop to be created. A handle of type esp_event_loop_handle_t is obtained, which is needed by the other APIs to reference the loop to perform their operations. esp_event_loop_args_t loop_args = { .queue_size = ..., .task_name = ... .task_priority = ..., .task_stack_size = ..., .task_core_id = ... }; esp_event_loop_handle_t loop_handle; esp_event_loop_create(&loop_args, &loop_handle); // 3. Register event handler defined in (1). MY_EVENT_BASE and MY_EVENT_ID specify a hypothetical event that handler run_on_event should execute when it gets posted to the loop. esp_event_handler_register_with(loop_handle, MY_EVENT_BASE, MY_EVENT_ID, run_on_event, ...); ... // 4. Post events to the loop. This queues the event on the event loop. At some point, the event loop executes the event handler registered to the posted event, in this case, run_on_event. To simplify the process, this example calls esp_event_post_to from app_main, but posting can be done from any other task (which is the more interesting use case). esp_event_post_to(loop_handle, MY_EVENT_BASE, MY_EVENT_ID, ...); ... // 5. Unregistering an unneeded handler esp_event_handler_unregister_with(loop_handle, MY_EVENT_BASE, MY_EVENT_ID, run_on_event); ... // 6. Deleting an unneeded event loop esp_event_loop_delete(loop_handle); } Declaring and Defining Events As mentioned previously, events consist of two-part identifiers: the event base and the event ID. The event base identifies an independent group of events; the event ID identifies the event within that group. Think of the event base and event ID as a person's last name and first name, respectively. A last name identifies a family, and the first name identifies a person within that family. The event loop library provides macros to declare and define the event base easily. Event base declaration: ESP_EVENT_DECLARE_BASE(EVENT_BASE); Event base definition: ESP_EVENT_DEFINE_BASE(EVENT_BASE); Note In ESP-IDF, the base identifiers for system events are uppercase and are postfixed with _EVENT. For example, the base for Wi-Fi events is declared and defined as WIFI_EVENT, the Ethernet event base ETHERNET_EVENT, and so on. The purpose is to have event bases look like constants (although they are global variables considering the definitions of macros ESP_EVENT_DECLARE_BASE and ESP_EVENT_DEFINE_BASE). For event IDs, declaring them as enumerations is recommended. Once again, for visibility, these are typically placed in public header files. Event ID: enum { EVENT_ID_1, EVENT_ID_2, EVENT_ID_3, ... } Default Event Loop The default event loop is a special type of loop used for system events (Wi-Fi events, for example). The handle for this loop is hidden from the user, and the creation, deletion, handler registration/deregistration, and posting of events are done through a variant of the APIs for user event loops. The table below enumerates those variants, and the user event loops equivalent. | User Event Loops | Default Event Loops If you compare the signatures for both, they are mostly similar except for the lack of loop handle specification for the default event loop APIs. Other than the API difference and the special designation to which system events are posted, there is no difference in how default event loops and user event loops behave. It is even possible for users to post their own events to the default event loop, should the user opt to not create their own loops to save memory. Notes on Handler Registration It is possible to register a single handler to multiple events individually by using multiple calls to esp_event_handler_register_with(). For those multiple calls, the specific event base and event ID can be specified with which the handler should execute. However, in some cases, it is desirable for a handler to execute on the following situations: all events that get posted to a loop all events of a particular base identifier This is possible using the special event base identifier ESP_EVENT_ANY_BASE and special event ID ESP_EVENT_ANY_ID. These special identifiers may be passed as the event base and event ID arguments for esp_event_handler_register_with(). Therefore, the valid arguments to esp_event_handler_register_with() are: <event base>, <event ID> - handler executes when the event with base <event base> and event ID <event ID> gets posted to the loop <event base>, ESP_EVENT_ANY_ID - handler executes when any event with base <event base> gets posted to the loop ESP_EVENT_ANY_BASE, ESP_EVENT_ANY_ID - handler executes when any event gets posted to the loop As an example, suppose the following handler registrations were performed: esp_event_handler_register_with(loop_handle, MY_EVENT_BASE, MY_EVENT_ID, run_on_event_1, ...); esp_event_handler_register_with(loop_handle, MY_EVENT_BASE, ESP_EVENT_ANY_ID, run_on_event_2, ...); esp_event_handler_register_with(loop_handle, ESP_EVENT_ANY_BASE, ESP_EVENT_ANY_ID, run_on_event_3, ...); If the hypothetical event MY_EVENT_BASE, MY_EVENT_ID is posted, all three handlers run_on_event_1, run_on_event_2, and run_on_event_3 would execute. If the hypothetical event MY_EVENT_BASE, MY_OTHER_EVENT_ID is posted, only run_on_event_2 and run_on_event_3 would execute. If the hypothetical event MY_OTHER_EVENT_BASE, MY_OTHER_EVENT_ID is posted, only run_on_event_3 would execute. Handler Un-Registering Itself In general, an event handler run by an event loop is not allowed to do any registering/unregistering activity on that event loop. There is one exception, though: un-registering itself is allowed for the handler. E.g., it is possible to do the following: void run_on_event(void* handler_arg, esp_event_base_t base, int32_t id, void* event_data) { esp_event_loop_handle_t *loop_handle = (esp_event_loop_handle_t*) handler_arg; esp_event_handler_unregister_with(*loop_handle, MY_EVENT_BASE, MY_EVENT_ID, run_on_event); } void app_main(void) { esp_event_loop_handle_t loop_handle; esp_event_loop_create(&loop_args, &loop_handle); esp_event_handler_register_with(loop_handle, MY_EVENT_BASE, MY_EVENT_ID, run_on_event, &loop_handle); // ... post-event MY_EVENT_BASE, MY_EVENT_ID and run loop at some point } Handler Registration and Handler Dispatch Order The general rule is that, for handlers that match a certain posted event during dispatch, those which are registered first also get executed first. The user can then control which handlers get executed first by registering them before other handlers, provided that all registrations are performed using a single task. If the user plans to take advantage of this behavior, caution must be exercised if there are multiple tasks registering handlers. While the 'first registered, first executed' behavior still holds true, the task which gets executed first also gets its handlers registered first. Handlers registered one after the other by a single task are still dispatched in the order relative to each other, but if that task gets pre-empted in between registration by another task that also registers handlers; then during dispatch those handlers also get executed in between. Event Loop Profiling A configuration option CONFIG_ESP_EVENT_LOOP_PROFILING can be enabled in order to activate statistics collection for all event loops created. The function esp_event_dump() can be used to output the collected statistics to a file stream. More details on the information included in the dump can be found in the esp_event_dump() API Reference. Application Example Examples of using the esp_event library can be found in system/esp_event. The examples cover event declaration, loop creation, handler registration and deregistration, and event posting. Other examples which also adopt esp_event library: - NMEA Parser , which decodes the statements received from GPS. API Reference Header File This header file can be included with: #include "esp_event.h" This header file is a part of the API provided by the esp_eventcomponent. To declare that your component depends on esp_event, add the following to your CMakeLists.txt: REQUIRES esp_event or PRIV_REQUIRES esp_event Functions - esp_err_t esp_event_loop_create(const esp_event_loop_args_t *event_loop_args, esp_event_loop_handle_t *event_loop) Create a new event loop. - Parameters event_loop_args -- [in] configuration structure for the event loop to create event_loop -- [out] handle to the created event loop - - Returns ESP_OK: Success ESP_ERR_INVALID_ARG: event_loop_args or event_loop was NULL ESP_ERR_NO_MEM: Cannot allocate memory for event loops list ESP_FAIL: Failed to create task loop Others: Fail - - esp_err_t esp_event_loop_delete(esp_event_loop_handle_t event_loop) Delete an existing event loop. - Parameters event_loop -- [in] event loop to delete, must not be NULL - Returns ESP_OK: Success Others: Fail - - esp_err_t esp_event_loop_create_default(void) Create default event loop. - Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for event loops list ESP_ERR_INVALID_STATE: Default event loop has already been created ESP_FAIL: Failed to create task loop Others: Fail - - esp_err_t esp_event_loop_delete_default(void) Delete the default event loop. - Returns ESP_OK: Success Others: Fail - - esp_err_t esp_event_loop_run(esp_event_loop_handle_t event_loop, TickType_t ticks_to_run) Dispatch events posted to an event loop. This function is used to dispatch events posted to a loop with no dedicated task, i.e. task name was set to NULL in event_loop_args argument during loop creation. This function includes an argument to limit the amount of time it runs, returning control to the caller when that time expires (or some time afterwards). There is no guarantee that a call to this function will exit at exactly the time of expiry. There is also no guarantee that events have been dispatched during the call, as the function might have spent all the allotted time waiting on the event queue. Once an event has been dequeued, however, it is guaranteed to be dispatched. This guarantee contributes to not being able to exit exactly at time of expiry as (1) blocking on internal mutexes is necessary for dispatching the dequeued event, and (2) during dispatch of the dequeued event there is no way to control the time occupied by handler code execution. The guaranteed time of exit is therefore the allotted time + amount of time required to dispatch the last dequeued event. In cases where waiting on the queue times out, ESP_OK is returned and not ESP_ERR_TIMEOUT, since it is normal behavior. Note encountering an unknown event that has been posted to the loop will only generate a warning, not an error. - Parameters event_loop -- [in] event loop to dispatch posted events from, must not be NULL ticks_to_run -- [in] number of ticks to run the loop - - Returns ESP_OK: Success Others: Fail - - esp_err_t esp_event_handler_register(esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler, void *event_handler_arg) Register an event handler to the system event loop (legacy). This function can be used to register a handler for either: (1) specific events, (2) all events of a certain event base, or (3) all events known by the system event loop. specific events: specify exact event_base and event_id all events of a certain base: specify exact event_base and use ESP_EVENT_ANY_ID as the event_id all events known by the loop: use ESP_EVENT_ANY_BASE for event_base and ESP_EVENT_ANY_ID as the event_id Registering multiple handlers to events is possible. Registering a single handler to multiple events is also possible. However, registering the same handler to the same event multiple times would cause the previous registrations to be overwritten. Note the event loop library does not maintain a copy of event_handler_arg, therefore the user should ensure that event_handler_arg still points to a valid location by the time the handler gets called - Parameters event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called - - Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail - - - esp_err_t esp_event_handler_register_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler, void *event_handler_arg) Register an event handler to a specific loop (legacy). This function behaves in the same manner as esp_event_handler_register, except the additional specification of the event loop to register the handler to. Note the event loop library does not maintain a copy of event_handler_arg, therefore the user should ensure that event_handler_arg still points to a valid location by the time the handler gets called - Parameters event_loop -- [in] the event loop to register this handler function to, must not be NULL event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called - - Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail - - esp_err_t esp_event_handler_instance_register_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler, void *event_handler_arg, esp_event_handler_instance_t *instance) Register an instance of event handler to a specific loop. This function can be used to register a handler for either: (1) specific events, (2) all events of a certain event base, or (3) all events known by the system event loop. specific events: specify exact event_base and event_id all events of a certain base: specify exact event_base and use ESP_EVENT_ANY_ID as the event_id all events known by the loop: use ESP_EVENT_ANY_BASE for event_base and ESP_EVENT_ANY_ID as the event_id Besides the error, the function returns an instance object as output parameter to identify each registration. This is necessary to remove (unregister) the registration before the event loop is deleted. Registering multiple handlers to events, registering a single handler to multiple events as well as registering the same handler to the same event multiple times is possible. Each registration yields a distinct instance object which identifies it over the registration lifetime. Note the event loop library does not maintain a copy of event_handler_arg, therefore the user should ensure that event_handler_arg still points to a valid location by the time the handler gets called - Parameters event_loop -- [in] the event loop to register this handler function to, must not be NULL event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called instance -- [out] An event handler instance object related to the registered event handler and data, can be NULL. This needs to be kept if the specific callback instance should be unregistered before deleting the whole event loop. Registering the same event handler multiple times is possible and yields distinct instance objects. The data can be the same for all registrations. If no unregistration is needed, but the handler should be deleted when the event loop is deleted, instance can be NULL. - - Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID or instance is NULL Others: Fail - - - esp_err_t esp_event_handler_instance_register(esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler, void *event_handler_arg, esp_event_handler_instance_t *instance) Register an instance of event handler to the default loop. This function does the same as esp_event_handler_instance_register_with, except that it registers the handler to the default event loop. Note the event loop library does not maintain a copy of event_handler_arg, therefore the user should ensure that event_handler_arg still points to a valid location by the time the handler gets called - Parameters event_base -- [in] the base ID of the event to register the handler for event_id -- [in] the ID of the event to register the handler for event_handler -- [in] the handler function which gets called when the event is dispatched event_handler_arg -- [in] data, aside from event data, that is passed to the handler when it is called instance -- [out] An event handler instance object related to the registered event handler and data, can be NULL. This needs to be kept if the specific callback instance should be unregistered before deleting the whole event loop. Registering the same event handler multiple times is possible and yields distinct instance objects. The data can be the same for all registrations. If no unregistration is needed, but the handler should be deleted when the event loop is deleted, instance can be NULL. - - Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for the handler ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID or instance is NULL Others: Fail - - esp_err_t esp_event_handler_unregister(esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler) Unregister a handler with the system event loop (legacy). Unregisters a handler, so it will no longer be called during dispatch. Handlers can be unregistered for any combination of event_base and event_id which were previously registered. To unregister a handler, the event_base and event_id arguments must match exactly the arguments passed to esp_event_handler_register() when that handler was registered. Passing ESP_EVENT_ANY_BASE and/or ESP_EVENT_ANY_ID will only unregister handlers that were registered with the same wildcard arguments. Note When using ESP_EVENT_ANY_ID, handlers registered to specific event IDs using the same base will not be unregistered. When using ESP_EVENT_ANY_BASE, events registered to specific bases will also not be unregistered. This avoids accidental unregistration of handlers registered by other users or components. - Parameters event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler event_handler -- [in] the handler to unregister - - Returns ESP_OK success - Returns ESP_ERR_INVALID_ARG invalid combination of event base and event ID - Returns others fail - esp_err_t esp_event_handler_unregister_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler) Unregister a handler from a specific event loop (legacy). This function behaves in the same manner as esp_event_handler_unregister, except the additional specification of the event loop to unregister the handler with. - Parameters event_loop -- [in] the event loop with which to unregister this handler function, must not be NULL event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler event_handler -- [in] the handler to unregister - - Returns ESP_OK: Success ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail - - esp_err_t esp_event_handler_instance_unregister_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, esp_event_handler_instance_t instance) Unregister a handler instance from a specific event loop. Unregisters a handler instance, so it will no longer be called during dispatch. Handler instances can be unregistered for any combination of event_base and event_id which were previously registered. To unregister a handler instance, the event_base and event_id arguments must match exactly the arguments passed to esp_event_handler_instance_register() when that handler instance was registered. Passing ESP_EVENT_ANY_BASE and/or ESP_EVENT_ANY_ID will only unregister handler instances that were registered with the same wildcard arguments. Note When using ESP_EVENT_ANY_ID, handlers registered to specific event IDs using the same base will not be unregistered. When using ESP_EVENT_ANY_BASE, events registered to specific bases will also not be unregistered. This avoids accidental unregistration of handlers registered by other users or components. - Parameters event_loop -- [in] the event loop with which to unregister this handler function, must not be NULL event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler instance -- [in] the instance object of the registration to be unregistered - - Returns ESP_OK: Success ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail - - esp_err_t esp_event_handler_instance_unregister(esp_event_base_t event_base, int32_t event_id, esp_event_handler_instance_t instance) Unregister a handler from the system event loop. This function does the same as esp_event_handler_instance_unregister_with, except that it unregisters the handler instance from the default event loop. - Parameters event_base -- [in] the base of the event with which to unregister the handler event_id -- [in] the ID of the event with which to unregister the handler instance -- [in] the instance object of the registration to be unregistered - - Returns ESP_OK: Success ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail - - esp_err_t esp_event_post(esp_event_base_t event_base, int32_t event_id, const void *event_data, size_t event_data_size, TickType_t ticks_to_wait) Posts an event to the system default event loop. The event loop library keeps a copy of event_data and manages the copy's lifetime automatically (allocation + deletion); this ensures that the data the handler receives is always valid. - Parameters event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data ticks_to_wait -- [in] number of ticks to block on a full event queue - - Returns ESP_OK: Success ESP_ERR_TIMEOUT: Time to wait for event queue to unblock expired, queue full when posting from ISR ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail - - esp_err_t esp_event_post_to(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, const void *event_data, size_t event_data_size, TickType_t ticks_to_wait) Posts an event to the specified event loop. The event loop library keeps a copy of event_data and manages the copy's lifetime automatically (allocation + deletion); this ensures that the data the handler receives is always valid. This function behaves in the same manner as esp_event_post_to, except the additional specification of the event loop to post the event to. - Parameters event_loop -- [in] the event loop to post to, must not be NULL event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data ticks_to_wait -- [in] number of ticks to block on a full event queue - - Returns ESP_OK: Success ESP_ERR_TIMEOUT: Time to wait for event queue to unblock expired, queue full when posting from ISR ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID Others: Fail - - esp_err_t esp_event_isr_post(esp_event_base_t event_base, int32_t event_id, const void *event_data, size_t event_data_size, BaseType_t *task_unblocked) Special variant of esp_event_post for posting events from interrupt handlers. Note this function is only available when CONFIG_ESP_EVENT_POST_FROM_ISR is enabled Note when this function is called from an interrupt handler placed in IRAM, this function should be placed in IRAM as well by enabling CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR - Parameters event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data; max is 4 bytes task_unblocked -- [out] an optional parameter (can be NULL) which indicates that an event task with higher priority than currently running task has been unblocked by the posted event; a context switch should be requested before the interrupt is existed. - - Returns ESP_OK: Success ESP_FAIL: Event queue for the default event loop full ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID, data size of more than 4 bytes Others: Fail - - esp_err_t esp_event_isr_post_to(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, const void *event_data, size_t event_data_size, BaseType_t *task_unblocked) Special variant of esp_event_post_to for posting events from interrupt handlers. Note this function is only available when CONFIG_ESP_EVENT_POST_FROM_ISR is enabled Note when this function is called from an interrupt handler placed in IRAM, this function should be placed in IRAM as well by enabling CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR - Parameters event_loop -- [in] the event loop to post to, must not be NULL event_base -- [in] the event base that identifies the event event_id -- [in] the event ID that identifies the event event_data -- [in] the data, specific to the event occurrence, that gets passed to the handler event_data_size -- [in] the size of the event data task_unblocked -- [out] an optional parameter (can be NULL) which indicates that an event task with higher priority than currently running task has been unblocked by the posted event; a context switch should be requested before the interrupt is existed. - - Returns ESP_OK: Success ESP_FAIL: Event queue for the loop full ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID, data size of more than 4 bytes Others: Fail - - esp_err_t esp_event_dump(FILE *file) Dumps statistics of all event loops. Dumps event loop info in the format: event loop handler handler ... event loop handler handler ... where: event loop format: address,name rx:total_received dr:total_dropped where: address - memory address of the event loop name - name of the event loop, 'none' if no dedicated task total_received - number of successfully posted events total_dropped - number of events unsuccessfully posted due to queue being full handler format: address ev:base,id inv:total_invoked run:total_runtime where: address - address of the handler function base,id - the event specified by event base and ID this handler executes total_invoked - number of times this handler has been invoked total_runtime - total amount of time used for invoking this handler Note this function is a noop when CONFIG_ESP_EVENT_LOOP_PROFILING is disabled - Parameters file -- [in] the file stream to output to - Returns ESP_OK: Success ESP_ERR_NO_MEM: Cannot allocate memory for event loops list Others: Fail - Structures - struct esp_event_loop_args_t Configuration for creating event loops. Public Members - int32_t queue_size size of the event loop queue - const char *task_name name of the event loop task; if NULL, a dedicated task is not created for event loop - UBaseType_t task_priority priority of the event loop task, ignored if task name is NULL - uint32_t task_stack_size stack size of the event loop task, ignored if task name is NULL - BaseType_t task_core_id core to which the event loop task is pinned to, ignored if task name is NULL - int32_t queue_size Header File This header file can be included with: #include "esp_event_base.h" This header file is a part of the API provided by the esp_eventcomponent. To declare that your component depends on esp_event, add the following to your CMakeLists.txt: REQUIRES esp_event or PRIV_REQUIRES esp_event Macros - ESP_EVENT_DECLARE_BASE(id) - ESP_EVENT_DEFINE_BASE(id) - ESP_EVENT_ANY_BASE register handler for any event base - ESP_EVENT_ANY_ID register handler for any event id Type Definitions - typedef void *esp_event_loop_handle_t a number that identifies an event with respect to a base - typedef void (*esp_event_handler_t)(void *event_handler_arg, esp_event_base_t event_base, int32_t event_id, void *event_data) function called when an event is posted to the queue - typedef void *esp_event_handler_instance_t context identifying an instance of a registered event handler
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/esp_event.html
ESP-IDF Programming Guide v5.2.1 documentation
null
FreeRTOS Overview
null
espressif.com
2016-01-01
b4ad3f751413431c
null
null
FreeRTOS Overview Overview FreeRTOS is an open source RTOS (real-time operating system) kernel that is integrated into ESP-IDF as a component. Thus, all ESP-IDF applications and many ESP-IDF components are written based on FreeRTOS. The FreeRTOS kernel is ported to all architectures (i.e., Xtensa and RISC-V) available of ESP chips. Furthermore, ESP-IDF provides different implementations of FreeRTOS in order to support SMP (Symmetric Multiprocessing) on multi-core ESP chips. This document provides an overview of the FreeRTOS component, the different FreeRTOS implementations offered by ESP-IDF, and the common aspects across all implementations. Implementations The official FreeRTOS (henceforth referred to as Vanilla FreeRTOS) is a single-core RTOS. In order to support the various multi-core ESP targets, ESP-IDF supports different FreeRTOS implementations as listed below: ESP-IDF FreeRTOS ESP-IDF FreeRTOS is a FreeRTOS implementation based on Vanilla FreeRTOS v10.5.1, but contains significant modifications to support SMP. ESP-IDF FreeRTOS only supports two cores at most (i.e., dual core SMP), but is more optimized for this scenario by design. For more details regarding ESP-IDF FreeRTOS and its modifications, please refer to the FreeRTOS (IDF) document. Note ESP-IDF FreeRTOS is currently the default FreeRTOS implementation for ESP-IDF. Amazon SMP FreeRTOS Amazon SMP FreeRTOS is an SMP implementation of FreeRTOS that is officially supported by Amazon. Amazon SMP FreeRTOS is able to support N-cores (i.e., more than two cores). Amazon SMP FreeRTOS can be enabled via the CONFIG_FREERTOS_SMP option. For more details regarding Amazon SMP FreeRTOS, please refer to the official Amazon SMP FreeRTOS documentation. Warning The Amazon SMP FreeRTOS implementation (and its port in ESP-IDF) are currently in experimental/beta state. Therefore, significant behavioral changes and breaking API changes can occur. Configuration Kernel Configuration Vanilla FreeRTOS requires that ports and applications configure the kernel by adding various #define config... macro definitions to the FreeRTOSConfig.h header file. Vanilla FreeRTOS supports a list of kernel configuration options which allow various kernel behaviors and features to be enabled or disabled. However, for all FreeRTOS ports in ESP-IDF, the FreeRTOSConfig.h header file is considered private and must not be modified by users. A large number of kernel configuration options in FreeRTOSConfig.h are hard-coded as they are either required/not supported by ESP-IDF. All kernel configuration options that are configurable by the user are exposed via menuconfig under Component Config/FreeRTOS/Kernel . For the full list of user configurable kernel options, see Project Configuration. The list below highlights some commonly used kernel configuration options: CONFIG_FREERTOS_UNICORE runs FreeRTOS only on Core 0. Note that this is not equivalent to running Vanilla FreeRTOS. Furthermore, this option may affect behavior of components other than freertos. For more details regarding the effects of running FreeRTOS on a single core, refer to Single-Core Mode (if using ESP-IDF FreeRTOS) or the official Amazon SMP FreeRTOS documentation. Alternatively, users can also search for occurrences of CONFIG_FREERTOS_UNICORE in the ESP-IDF components. CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY enables backward compatibility with some FreeRTOS macros/types/functions that were deprecated from v8.0 onwards. Port Configuration All other FreeRTOS related configuration options that are not part of the kernel configuration are exposed via menuconfig under Component Config/FreeRTOS/Port . These options configure aspects such as: The FreeRTOS ports themselves (e.g., tick timer selection, ISR stack size) Additional features added to the FreeRTOS implementation or ports Using FreeRTOS Application Entry Point Unlike Vanilla FreeRTOS, users of FreeRTOS in ESP-IDF must never call vTaskStartScheduler() and vTaskEndScheduler() . Instead, ESP-IDF starts FreeRTOS automatically. Users must define a void app_main(void) function which acts as the entry point for user's application and is automatically invoked on ESP-IDF startup. Typically, users would spawn the rest of their application's task from app_main . The app_main function is allowed to return at any point (i.e., before the application terminates). The app_main function is called from the main task. Background Tasks During startup, ESP-IDF and the FreeRTOS kernel automatically create multiple tasks that run in the background (listed in the the table below). Task Name Description Stack Size Affinity Priority Idle Tasks ( An idle task ( Core x FreeRTOS Timer Task ( FreeRTOS will create the Timer Service/Daemon Task if any FreeRTOS Timer APIs are called by the application Core 0 Main Task ( Task that simply calls IPC Tasks ( When CONFIG_FREERTOS_UNICORE is false, an IPC task ( Core x ESP Timer Task ( ESP-IDF creates the ESP Timer Task used to process ESP Timer callbacks Core 0 Note Note that if an application uses other ESP-IDF features (e.g., Wi-Fi or Bluetooth), those features may create their own background tasks in addition to the tasks listed in the table above. FreeRTOS Additions ESP-IDF provides some supplemental features to FreeRTOS such as Ring Buffers, ESP-IDF style Tick and Idle Hooks, and TLSP deletion callbacks. See FreeRTOS (Supplemental Features) for more details. FreeRTOS Heap Vanilla FreeRTOS provides its own selection of heap implementations. However, ESP-IDF already implements its own heap (see Heap Memory Allocation), thus ESP-IDF does not make use of the heap implementations provided by Vanilla FreeRTOS. All FreeRTOS ports in ESP-IDF map FreeRTOS memory allocation or free calls (e.g., pvPortMalloc() and pvPortFree() ) to ESP-IDF heap API (i.e., heap_caps_malloc() and heap_caps_free() ). However, the FreeRTOS ports ensure that all dynamic memory allocated by FreeRTOS is placed in internal memory. Note If users wish to place FreeRTOS tasks/objects in external memory, users can use the following methods: Allocate the task or object using one of the ...CreateWithCaps() API, such as xTaskCreateWithCaps() and xQueueCreateWithCaps() (see IDF Additional API for more details). Manually allocate external memory for those objects using heap_caps_malloc() , then create the objects from the allocated memory using on of the ...CreateStatic() FreeRTOS functions.
FreeRTOS Overview Overview FreeRTOS is an open source RTOS (real-time operating system) kernel that is integrated into ESP-IDF as a component. Thus, all ESP-IDF applications and many ESP-IDF components are written based on FreeRTOS. The FreeRTOS kernel is ported to all architectures (i.e., Xtensa and RISC-V) available of ESP chips. Furthermore, ESP-IDF provides different implementations of FreeRTOS in order to support SMP (Symmetric Multiprocessing) on multi-core ESP chips. This document provides an overview of the FreeRTOS component, the different FreeRTOS implementations offered by ESP-IDF, and the common aspects across all implementations. Implementations The official FreeRTOS (henceforth referred to as Vanilla FreeRTOS) is a single-core RTOS. In order to support the various multi-core ESP targets, ESP-IDF supports different FreeRTOS implementations as listed below: ESP-IDF FreeRTOS ESP-IDF FreeRTOS is a FreeRTOS implementation based on Vanilla FreeRTOS v10.5.1, but contains significant modifications to support SMP. ESP-IDF FreeRTOS only supports two cores at most (i.e., dual core SMP), but is more optimized for this scenario by design. For more details regarding ESP-IDF FreeRTOS and its modifications, please refer to the FreeRTOS (IDF) document. Note ESP-IDF FreeRTOS is currently the default FreeRTOS implementation for ESP-IDF. Amazon SMP FreeRTOS Amazon SMP FreeRTOS is an SMP implementation of FreeRTOS that is officially supported by Amazon. Amazon SMP FreeRTOS is able to support N-cores (i.e., more than two cores). Amazon SMP FreeRTOS can be enabled via the CONFIG_FREERTOS_SMP option. For more details regarding Amazon SMP FreeRTOS, please refer to the official Amazon SMP FreeRTOS documentation. Warning The Amazon SMP FreeRTOS implementation (and its port in ESP-IDF) are currently in experimental/beta state. Therefore, significant behavioral changes and breaking API changes can occur. Configuration Kernel Configuration Vanilla FreeRTOS requires that ports and applications configure the kernel by adding various #define config... macro definitions to the FreeRTOSConfig.h header file. Vanilla FreeRTOS supports a list of kernel configuration options which allow various kernel behaviors and features to be enabled or disabled. However, for all FreeRTOS ports in ESP-IDF, the FreeRTOSConfig.h header file is considered private and must not be modified by users. A large number of kernel configuration options in FreeRTOSConfig.h are hard-coded as they are either required/not supported by ESP-IDF. All kernel configuration options that are configurable by the user are exposed via menuconfig under Component Config/FreeRTOS/Kernel. For the full list of user configurable kernel options, see Project Configuration. The list below highlights some commonly used kernel configuration options: CONFIG_FREERTOS_UNICORE runs FreeRTOS only on Core 0. Note that this is not equivalent to running Vanilla FreeRTOS. Furthermore, this option may affect behavior of components other than freertos. For more details regarding the effects of running FreeRTOS on a single core, refer to Single-Core Mode (if using ESP-IDF FreeRTOS) or the official Amazon SMP FreeRTOS documentation. Alternatively, users can also search for occurrences of CONFIG_FREERTOS_UNICOREin the ESP-IDF components. CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY enables backward compatibility with some FreeRTOS macros/types/functions that were deprecated from v8.0 onwards. Port Configuration All other FreeRTOS related configuration options that are not part of the kernel configuration are exposed via menuconfig under Component Config/FreeRTOS/Port. These options configure aspects such as: The FreeRTOS ports themselves (e.g., tick timer selection, ISR stack size) Additional features added to the FreeRTOS implementation or ports Using FreeRTOS Application Entry Point Unlike Vanilla FreeRTOS, users of FreeRTOS in ESP-IDF must never call vTaskStartScheduler() and vTaskEndScheduler(). Instead, ESP-IDF starts FreeRTOS automatically. Users must define a void app_main(void) function which acts as the entry point for user's application and is automatically invoked on ESP-IDF startup. Typically, users would spawn the rest of their application's task from app_main. The app_mainfunction is allowed to return at any point (i.e., before the application terminates). The app_mainfunction is called from the maintask. Background Tasks During startup, ESP-IDF and the FreeRTOS kernel automatically create multiple tasks that run in the background (listed in the the table below). | Task Name | Description | Stack Size | Affinity | Priority | Idle Tasks ( | An idle task ( | Core x | | FreeRTOS Timer Task ( | FreeRTOS will create the Timer Service/Daemon Task if any FreeRTOS Timer APIs are called by the application | Core 0 | Main Task ( | Task that simply calls | | IPC Tasks ( | When CONFIG_FREERTOS_UNICORE is false, an IPC task ( | Core x | | ESP Timer Task ( | ESP-IDF creates the ESP Timer Task used to process ESP Timer callbacks | Core 0 | Note Note that if an application uses other ESP-IDF features (e.g., Wi-Fi or Bluetooth), those features may create their own background tasks in addition to the tasks listed in the table above. FreeRTOS Additions ESP-IDF provides some supplemental features to FreeRTOS such as Ring Buffers, ESP-IDF style Tick and Idle Hooks, and TLSP deletion callbacks. See FreeRTOS (Supplemental Features) for more details. FreeRTOS Heap Vanilla FreeRTOS provides its own selection of heap implementations. However, ESP-IDF already implements its own heap (see Heap Memory Allocation), thus ESP-IDF does not make use of the heap implementations provided by Vanilla FreeRTOS. All FreeRTOS ports in ESP-IDF map FreeRTOS memory allocation or free calls (e.g., pvPortMalloc() and pvPortFree()) to ESP-IDF heap API (i.e., heap_caps_malloc() and heap_caps_free()). However, the FreeRTOS ports ensure that all dynamic memory allocated by FreeRTOS is placed in internal memory. Note If users wish to place FreeRTOS tasks/objects in external memory, users can use the following methods: Allocate the task or object using one of the ...CreateWithCaps()API, such as xTaskCreateWithCaps()and xQueueCreateWithCaps()(see IDF Additional API for more details). Manually allocate external memory for those objects using heap_caps_malloc(), then create the objects from the allocated memory using on of the ...CreateStatic()FreeRTOS functions.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/freertos.html
ESP-IDF Programming Guide v5.2.1 documentation
null
FreeRTOS (IDF)
null
espressif.com
2016-01-01
78c49d46e0a2978b
null
null
FreeRTOS (IDF) This document provides information regarding the dual-core SMP implementation of FreeRTOS inside ESP-IDF. This document is split into the following sections: Sections Overview The original FreeRTOS (hereinafter referred to as Vanilla FreeRTOS) is a compact and efficient real-time operating system supported on numerous single-core MCUs and SoCs. However, to support dual-core ESP targets, such as ESP32, ESP32-S3, and ESP32-P4, ESP-IDF provides a unique implementation of FreeRTOS with dual-core symmetric multiprocessing (SMP) capabilities (hereinafter referred to as IDF FreeRTOS). IDF FreeRTOS source code is based on Vanilla FreeRTOS v10.5.1 but contains significant modifications to both kernel behavior and API in order to support dual-core SMP. However, IDF FreeRTOS can also be configured for single-core by enabling the CONFIG_FREERTOS_UNICORE option (see Single-Core Mode for more details). Note This document assumes that the reader has a requisite understanding of Vanilla FreeRTOS, i.e., its features, behavior, and API usage. Refer to the Vanilla FreeRTOS documentation for more details. Symmetric Multiprocessing Basic Concepts Symmetric multiprocessing is a computing architecture where two or more identical CPU cores are connected to a single shared main memory and controlled by a single operating system. In general, an SMP system: has multiple cores running independently. Each core has its own register file, interrupts, and interrupt handling. presents an identical view of memory to each core. Thus, a piece of code that accesses a particular memory address has the same effect regardless of which core it runs on. The main advantages of an SMP system compared to single-core or asymmetric multiprocessing systems are that: the presence of multiple cores allows for multiple hardware threads, thus increasing overall processing throughput. having symmetric memory means that threads can switch cores during execution. This, in general, can lead to better CPU utilization. Although an SMP system allows threads to switch cores, there are scenarios where a thread must/should only run on a particular core. Therefore, threads in an SMP system also have a core affinity that specifies which particular core the thread is allowed to run on. A thread that is pinned to a particular core is only able to run on that core. A thread that is unpinned will be allowed to switch between cores during execution instead of being pinned to a particular core. SMP on an ESP Target ESP targets such as ESP32, ESP32-S3, and ESP32-P4 are dual-core SMP SoCs. These targets have the following hardware features that make them SMP-capable: Two identical cores are known as Core 0 and Core 1. This means that the execution of a piece of code is identical regardless of which core it runs on. Symmetric memory (with some small exceptions). If multiple cores access the same memory address simultaneously, their access will be serialized by the memory bus. True atomic access to the same memory address is achieved via an atomic compare-and-swap instruction provided by the ISA. If multiple cores access the same memory address simultaneously, their access will be serialized by the memory bus. True atomic access to the same memory address is achieved via an atomic compare-and-swap instruction provided by the ISA. If multiple cores access the same memory address simultaneously, their access will be serialized by the memory bus. Cross-core interrupts that allow one core to trigger an interrupt on the other core. This allows cores to signal events to each other (such as requesting a context switch on the other core). Note Within ESP-IDF, Core 0 and Core 1 are sometimes referred to as PRO_CPU and APP_CPU respectively. The aliases exist in ESP-IDF as they reflect how typical ESP-IDF applications utilize the two cores. Typically, the tasks responsible for handling protocol related processing such as Wi-Fi or Bluetooth are pinned to Core 0 (thus the name PRO_CPU ), where as the tasks handling the remainder of the application are pinned to Core 1, (thus the name APP_CPU ). Tasks Creation Vanilla FreeRTOS provides the following functions to create a task: xTaskCreate() creates a task. The task's memory is dynamically allocated. xTaskCreateStatic() creates a task. The task's memory is statically allocated, i.e., provided by the user. However, in an SMP system, tasks need to be assigned a particular affinity. Therefore, ESP-IDF provides a ...PinnedToCore() version of Vanilla FreeRTOS's task creation functions: xTaskCreatePinnedToCore() creates a task with a particular core affinity. The task's memory is dynamically allocated. xTaskCreateStaticPinnedToCore() creates a task with a particular core affinity. The task's memory is statically allocated, i.e., provided by the user. The ...PinnedToCore() versions of the task creation function API differ from their vanilla counterparts by having an extra xCoreID parameter that is used to specify the created task's core affinity. The valid values for core affinity are: 0 , which pins the created task to Core 0 1 , which pins the created task to Core 1 tskNO_AFFINITY , which allows the task to be run on both cores Note that IDF FreeRTOS still supports the vanilla versions of the task creation functions. However, these standard functions have been modified to essentially invoke their respective ...PinnedToCore() counterparts while setting the core affinity to tskNO_AFFINITY . Note IDF FreeRTOS also changes the units of ulStackDepth in the task creation functions. Task stack sizes in Vanilla FreeRTOS are specified in a number of words, whereas in IDF FreeRTOS, the task stack sizes are specified in bytes. Execution The anatomy of a task in IDF FreeRTOS is the same as in Vanilla FreeRTOS. More specifically, IDF FreeRTOS tasks: Can only be in one of the following states: Running, Ready, Blocked, or Suspended. Task functions are typically implemented as an infinite loop. Task functions should never return. Deletion Task deletion in Vanilla FreeRTOS is called via vTaskDelete() . The function allows deletion of another task or the currently running task if the provided task handle is NULL . The actual freeing of the task's memory is sometimes delegated to the idle task if the task being deleted is the currently running task. IDF FreeRTOS provides the same vTaskDelete() function. However, due to the dual-core nature, there are some behavioral differences when calling vTaskDelete() in IDF FreeRTOS: When deleting a task that is currently running on the other core, a yield is triggered on the other core, and the task's memory is freed by one of the idle tasks. A deleted task's memory is freed immediately if it is not running on either core. Please avoid deleting a task that is running on another core as it is difficult to determine what the task is performing, which may lead to unpredictable behavior such as: Deleting a task that is holding a mutex. Deleting a task that has yet to free memory it previously allocated. Where possible, please design your own application so that when calling vTaskDelete() , the deleted task is in a known state. For example: Tasks self-deleting via vTaskDelete(NULL) when their execution is complete and have also cleaned up all resources used within the task. Tasks placing themselves in the suspend state via vTaskSuspend() before being deleted by another task. SMP Scheduler The Vanilla FreeRTOS scheduler is best described as a fixed priority preemptive scheduler with time slicing meaning that: Each task is given a constant priority upon creation. The scheduler executes the highest priority ready-state task. The scheduler can switch execution to another task without the cooperation of the currently running task. The scheduler periodically switches execution between ready-state tasks of the same priority in a round-robin fashion. Time slicing is governed by a tick interrupt. The IDF FreeRTOS scheduler supports the same scheduling features, i.e., Fixed Priority, Preemption, and Time Slicing, albeit with some small behavioral differences. Fixed Priority In Vanilla FreeRTOS, when the scheduler selects a new task to run, it always selects the current highest priority ready-state task. In IDF FreeRTOS, each core independently schedules tasks to run. When a particular core selects a task, the core will select the highest priority ready-state task that can be run by the core. A task can be run by the core if: The task has a compatible affinity, i.e., is either pinned to that core or is unpinned. The task is not currently being run by another core. However, please do not assume that the two highest priority ready-state tasks are always run by the scheduler, as a task's core affinity must also be accounted for. For example, given the following tasks: Task A of priority 10 pinned to Core 0 Task B of priority 9 pinned to Core 0 Task C of priority 8 pinned to Core 1 The resulting schedule will have Task A running on Core 0 and Task C running on Core 1. Task B is not run even though it is the second-highest priority task. Preemption In Vanilla FreeRTOS, the scheduler can preempt the currently running task if a higher priority task becomes ready to execute. Likewise in IDF FreeRTOS, each core can be individually preempted by the scheduler if the scheduler determines that a higher-priority task can run on that core. However, there are some instances where a higher-priority task that becomes ready can be run on multiple cores. In this case, the scheduler only preempts one core. The scheduler always gives preference to the current core when multiple cores can be preempted. In other words, if the higher priority ready task is unpinned and has a higher priority than the current priority of both cores, the scheduler will always choose to preempt the current core. For example, given the following tasks: Task A of priority 8 currently running on Core 0 Task B of priority 9 currently running on Core 1 Task C of priority 10 that is unpinned and was unblocked by Task B The resulting schedule will have Task A running on Core 0 and Task C preempting Task B given that the scheduler always gives preference to the current core. Time Slicing The Vanilla FreeRTOS scheduler implements time slicing, which means that if the current highest ready priority contains multiple ready tasks, the scheduler will switch between those tasks periodically in a round-robin fashion. However, in IDF FreeRTOS, it is not possible to implement perfect Round Robin time slicing due to the fact that a particular task may not be able to run on a particular core due to the following reasons: The task is pinned to another core. For unpinned tasks, the task is already being run by another core. Therefore, when a core searches the ready-state task list for a task to run, the core may need to skip over a few tasks in the same priority list or drop to a lower priority in order to find a ready-state task that the core can run. The IDF FreeRTOS scheduler implements a Best Effort Round Robin time slicing for ready-state tasks of the same priority by ensuring that tasks that have been selected to run are placed at the back of the list, thus giving unselected tasks a higher priority on the next scheduling iteration (i.e., the next tick interrupt or yield). The following example demonstrates the Best Effort Round Robin time slicing in action. Assume that: There are four ready-state tasks of the same priority AX , B0 , C1 , and D1 where: The priority is the current highest priority with ready-state . The first character represents the task's name, i.e., A , B , C , D . The second character represents the task's core pinning, and X means unpinned. The priority is the current highest priority with ready-state . The first character represents the task's name, i.e., A , B , C , D . The second character represents the task's core pinning, and X means unpinned. The priority is the current highest priority with ready-state . The task list is always searched from the head. Starting state. None of the ready-state tasks have been selected to run. Head [ AX , B0 , C1 , D0 ] Tail Core 0 has a tick interrupt and searches for a task to run. Task A is selected and moved to the back of the list. Core 0 ─┐ ▼ Head [ AX , B0 , C1 , D0 ] Tail [0] Head [ B0 , C1 , D0 , AX ] Tail Core 1 has a tick interrupt and searches for a task to run. Task B cannot be run due to incompatible affinity, so Core 1 skips to Task C. Task C is selected and moved to the back of the list. Core 1 ──────┐ ▼ [0] Head [ B0 , C1 , D0 , AX ] Tail [0] [1] Head [ B0 , D0 , AX , C1 ] Tail Core 0 has another tick interrupt and searches for a task to run. Task B is selected and moved to the back of the list. Core 0 ─┐ ▼ [1] Head [ B0 , D0 , AX , C1 ] Tail [1] [0] Head [ D0 , AX , C1 , B0 ] Tail Core 1 has another tick and searches for a task to run. Task D cannot be run due to incompatible affinity, so Core 1 skips to Task A. Task A is selected and moved to the back of the list. Core 1 ──────┐ ▼ [0] Head [ D0 , AX , C1 , B0 ] Tail [0] [1] Head [ D0 , C1 , B0 , AX ] Tail The implications to users regarding the Best Effort Round Robin time slicing: Users cannot expect multiple ready-state tasks of the same priority to run sequentially as is the case in Vanilla FreeRTOS. As demonstrated in the example above, a core may need to skip over tasks. However, given enough ticks, a task will eventually be given some processing time. If a core cannot find a task runnable task at the highest ready-state priority, it will drop to a lower priority to search for tasks. To achieve ideal round-robin time slicing, users should ensure that all tasks of a particular priority are pinned to the same core. Tick Interrupts Vanilla FreeRTOS requires that a periodic tick interrupt occurs. The tick interrupt is responsible for: Incrementing the scheduler's tick count Unblocking any blocked tasks that have timed out Checking if time slicing is required, i.e., triggering a context switch Executing the application tick hook In IDF FreeRTOS, each core receives a periodic interrupt and independently runs the tick interrupt. The tick interrupts on each core are of the same period but can be out of phase. However, the tick responsibilities listed above are not run by all cores: Core 0 executes all of the tick interrupt responsibilities listed above Core 1 only checks for time slicing and executes the application tick hook Note Core 0 is solely responsible for keeping time in IDF FreeRTOS. Therefore, anything that prevents Core 0 from incrementing the tick count, such as suspending the scheduler on Core 0, will cause the entire scheduler's timekeeping to lag behind. Idle Tasks Vanilla FreeRTOS will implicitly create an idle task of priority 0 when the scheduler is started. The idle task runs when no other task is ready to run, and it has the following responsibilities: Freeing the memory of deleted tasks Executing the application idle hook In IDF FreeRTOS, a separate pinned idle task is created for each core. The idle tasks on each core have the same responsibilities as their vanilla counterparts. Scheduler Suspension Vanilla FreeRTOS allows the scheduler to be suspended/resumed by calling vTaskSuspendAll() and xTaskResumeAll() respectively. While the scheduler is suspended: Task switching is disabled but interrupts are left enabled. Calling any blocking/yielding function is forbidden, and time slicing is disabled. The tick count is frozen, but the tick interrupt still occurs to execute the application tick hook. On scheduler resumption, xTaskResumeAll() catches up all of the lost ticks and unblock any timed-out tasks. In IDF FreeRTOS, suspending the scheduler across multiple cores is not possible. Therefore when vTaskSuspendAll() is called on a particular core (e.g., core A): Task switching is disabled only on core A but interrupts for core A are left enabled. Calling any blocking/yielding function on core A is forbidden. Time slicing is disabled on core A. If an interrupt on core A unblocks any tasks, tasks with affinity to core A will go into core A's own pending ready task list. Unpinned tasks or tasks with affinity to other cores can be scheduled on cores with the scheduler running. If the scheduler is suspended on all cores, tasks unblocked by an interrupt will be directed to the pending ready task lists of their pinned cores. For unpinned tasks, they will be placed in the pending ready list of the core where the interrupt occurred. If core A is on Core 0, the tick count is frozen, and a pended tick count is incremented instead. However, the tick interrupt will still occur in order to execute the application tick hook. When xTaskResumeAll() is called on a particular core (e.g., core A): Any tasks added to core A's pending ready task list will be resumed. If core A is Core 0, the pended tick count is unwound to catch up with the lost ticks. Warning Given that scheduler suspension on IDF FreeRTOS only suspends scheduling on a particular core, scheduler suspension is NOT a valid method of ensuring mutual exclusion between tasks when accessing shared data. Users should use proper locking primitives such as mutexes or spinlocks if they require mutual exclusion. Critical Sections Disabling Interrupts Vanilla FreeRTOS allows interrupts to be disabled and enabled by calling taskDISABLE_INTERRUPTS and taskENABLE_INTERRUPTS respectively. IDF FreeRTOS provides the same API. However, interrupts are only disabled or enabled on the current core. Disabling interrupts is a valid method of achieving mutual exclusion in Vanilla FreeRTOS (and single-core systems in general). However, in an SMP system, disabling interrupts is not a valid method of ensuring mutual exclusion. Critical sections that utilize a spinlock should be used instead. API Changes Vanilla FreeRTOS implements critical sections by disabling interrupts, which prevents preemptive context switches and the servicing of ISRs during a critical section. Thus a task/ISR that enters a critical section is guaranteed to be the sole entity to access a shared resource. Critical sections in Vanilla FreeRTOS have the following API: taskENTER_CRITICAL() enters a critical section by disabling interrupts taskEXIT_CRITICAL() exits a critical section by reenabling interrupts taskENTER_CRITICAL_FROM_ISR() enters a critical section from an ISR by disabling interrupt nesting taskEXIT_CRITICAL_FROM_ISR() exits a critical section from an ISR by reenabling interrupt nesting However, in an SMP system, merely disabling interrupts does not constitute a critical section as the presence of other cores means that a shared resource can still be concurrently accessed. Therefore, critical sections in IDF FreeRTOS are implemented using spinlocks. To accommodate the spinlocks, the IDF FreeRTOS critical section APIs contain an additional spinlock parameter as shown below: Spinlocks are of portMUX_TYPE (not to be confused to FreeRTOS mutexes) taskENTER_CRITICAL(&spinlock) enters a critical from a task context taskEXIT_CRITICAL(&spinlock) exits a critical section from a task context taskENTER_CRITICAL_ISR(&spinlock) enters a critical section from an interrupt context taskEXIT_CRITICAL_ISR(&spinlock) exits a critical section from an interrupt context Note The critical section API can be called recursively, i.e., nested critical sections. Entering a critical section multiple times recursively is valid so long as the critical section is exited the same number of times it was entered. However, given that critical sections can target different spinlocks, users should take care to avoid deadlocking when entering critical sections recursively. Spinlocks can be allocated statically or dynamically. As such, macros are provided for both static and dynamic initialization of spinlocks, as demonstrated by the following code snippets. Allocating a static spinlock and initializing it using portMUX_INITIALIZER_UNLOCKED : // Statically allocate and initialize the spinlock static portMUX_TYPE my_spinlock = portMUX_INITIALIZER_UNLOCKED; void some_function(void) { taskENTER_CRITICAL(&my_spinlock); // We are now in a critical section taskEXIT_CRITICAL(&my_spinlock); } Allocating a dynamic spinlock and initializing it using portMUX_INITIALIZE() : // Allocate the spinlock dynamically portMUX_TYPE *my_spinlock = malloc(sizeof(portMUX_TYPE)); // Initialize the spinlock dynamically portMUX_INITIALIZE(my_spinlock); ... taskENTER_CRITICAL(my_spinlock); // Access the resource taskEXIT_CRITICAL(my_spinlock); Implementation In IDF FreeRTOS, the process of a particular core entering and exiting a critical section is as follows: For taskENTER_CRITICAL(&spinlock) or taskENTER_CRITICAL_ISR(&spinlock) The core disables its interrupts or interrupt nesting up to configMAX_SYSCALL_INTERRUPT_PRIORITY . The core then spins on the spinlock using an atomic compare-and-set instruction until it acquires the lock. A lock is acquired when the core is able to set the lock's owner value to the core's ID. Once the spinlock is acquired, the function returns. The remainder of the critical section runs with interrupts or interrupt nesting disabled. The core disables its interrupts or interrupt nesting up to configMAX_SYSCALL_INTERRUPT_PRIORITY . The core then spins on the spinlock using an atomic compare-and-set instruction until it acquires the lock. A lock is acquired when the core is able to set the lock's owner value to the core's ID. Once the spinlock is acquired, the function returns. The remainder of the critical section runs with interrupts or interrupt nesting disabled. The core disables its interrupts or interrupt nesting up to configMAX_SYSCALL_INTERRUPT_PRIORITY . For taskEXIT_CRITICAL(&spinlock) or taskEXIT_CRITICAL_ISR(&spinlock) The core releases the spinlock by clearing the spinlock's owner value. The core re-enables interrupts or interrupt nesting. The core releases the spinlock by clearing the spinlock's owner value. The core re-enables interrupts or interrupt nesting. The core releases the spinlock by clearing the spinlock's owner value. Restrictions and Considerations Given that interrupts (or interrupt nesting) are disabled during a critical section, there are multiple restrictions regarding what can be done within critical sections. During a critical section, users should keep the following restrictions and considerations in mind: Critical sections should be kept as short as possible The longer the critical section lasts, the longer a pending interrupt can be delayed. A typical critical section should only access a few data structures and/or hardware registers. If possible, defer as much processing and/or event handling to the outside of critical sections. The longer the critical section lasts, the longer a pending interrupt can be delayed. A typical critical section should only access a few data structures and/or hardware registers. If possible, defer as much processing and/or event handling to the outside of critical sections. The longer the critical section lasts, the longer a pending interrupt can be delayed. FreeRTOS API should not be called from within a critical section Users should never call any blocking or yielding functions within a critical section Misc Floating Point Usage Usually, when a context switch occurs: the current state of a core's registers are saved to the stack of the task being switched out the previously saved state of the core's registers is loaded from the stack of the task being switched in However, IDF FreeRTOS implements Lazy Context Switching for the Floating Point Unit (FPU) registers of a core. In other words, when a context switch occurs on a particular core (e.g., Core 0), the state of the core's FPU registers is not immediately saved to the stack of the task getting switched out (e.g., Task A). The FPU registers are left untouched until: A different task (e.g., Task B) runs on the same core and uses FPU. This will trigger an exception that saves the FPU registers to Task A's stack. Task A gets scheduled to the same core and continues execution. Saving and restoring the FPU registers is not necessary in this case. However, given that tasks can be unpinned and thus can be scheduled on different cores (e.g., Task A switches to Core 1), it is unfeasible to copy and restore the FPU registers across cores. Therefore, when a task utilizes FPU by using a float type in its call flow, IDF FreeRTOS will automatically pin the task to the current core it is running on. This ensures that all tasks that use FPU are always pinned to a particular core. Furthermore, IDF FreeRTOS by default does not support the usage of FPU within an interrupt context given that the FPU register state is tied to a particular task. Note Users that require the use of the float type in an ISR routine should refer to the CONFIG_FREERTOS_FPU_IN_ISR configuration option. Note ESP targets that contain an FPU do not support hardware acceleration for double precision floating point arithmetic ( double ). Instead, double is implemented via software, hence the behavioral restrictions regarding the float type do not apply to double . Note that due to the lack of hardware acceleration, double operations may consume significantly more CPU time in comparison to float . Single-Core Mode Although IDF FreeRTOS is modified for dual-core SMP, IDF FreeRTOS can also be built for single-core by enabling the CONFIG_FREERTOS_UNICORE option. For single-core targets (such as ESP32-S2 and ESP32-C3), the CONFIG_FREERTOS_UNICORE option is always enabled. For multi-core targets (such as ESP32 and ESP32-S3), CONFIG_FREERTOS_UNICORE can also be set, but will result in the application only running Core 0. When building in single-core mode, IDF FreeRTOS is designed to be identical to Vanilla FreeRTOS, thus all aforementioned SMP changes to kernel behavior are removed. As a result, building IDF FreeRTOS in single-core mode has the following characteristics: All operations performed by the kernel inside critical sections are now deterministic (i.e., no walking of linked lists inside critical sections). Vanilla FreeRTOS scheduling algorithm is restored (including perfect Round Robin time slicing). All SMP specific data is removed from single-core builds. SMP APIs can still be called in single-core mode. These APIs remain exposed to allow source code to be built for single-core and multi-core, without needing to call a different set of APIs. However, SMP APIs will not exhibit any SMP behavior in single-core mode, thus becoming equivalent to their single-core counterparts. For example: any ...ForCore(..., BaseType_t xCoreID) SMP API will only accept 0 as a valid value for xCoreID . ...PinnedToCore() task creation APIs will simply ignore the xCoreID core affinity argument. Critical section APIs will still require a spinlock argument, but no spinlock will be taken and critical sections revert to simply disabling/enabling interrupts. API Reference This section introduces FreeRTOS types, functions, and macros. It is automatically generated from FreeRTOS header files. Task API Header File This header file can be included with: #include "freertos/task.h" Functions static inline BaseType_t xTaskCreate(TaskFunction_t pxTaskCode, const char *const pcName, const configSTACK_DEPTH_TYPE usStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *const pxCreatedTask) Create a new task and add it to the list of tasks that are ready to run. Internally, within the FreeRTOS implementation, tasks use two blocks of memory. The first block is used to hold the task's data structures. The second block is used by the task as its stack. If a task is created using xTaskCreate() then both blocks of memory are automatically dynamically allocated inside the xTaskCreate() function. (see https://www.FreeRTOS.org/a00111.html). If a task is created using xTaskCreateStatic() then the application writer must provide the required memory. xTaskCreateStatic() therefore allows a task to be created without using any dynamic memory allocation. See xTaskCreateStatic() for a version that does not use any dynamic memory allocation. xTaskCreate() can only be used to create a task that has unrestricted access to the entire microcontroller memory map. Systems that include MPU support can alternatively create an MPU constrained task using xTaskCreateRestricted(). Example usage: // Task to be created. void vTaskCode( void * pvParameters ) { for( ;; ) { // Task code goes here. } } // Function that creates a task. void vOtherFunction( void ) { static uint8_t ucParameterToPass; TaskHandle_t xHandle = NULL; // Create the task, storing the handle. Note that the passed parameter ucParameterToPass // must exist for the lifetime of the task, so in this case is declared static. If it was just an // an automatic stack variable it might no longer exist, or at least have been corrupted, by the time // the new task attempts to access it. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle ); configASSERT( xHandle ); // Use the handle to delete the task. if( xHandle != NULL ) { vTaskDelete( xHandle ); } } Note If configNUMBER_OF_CORES > 1, this function will create an unpinned task (see tskNO_AFFINITY for more details). Note If program uses thread local variables (ones specified with "__thread" keyword) then storage for them will be allocated on the task's stack. Parameters pxTaskCode -- Pointer to the task entry function. Tasks must be implemented to never return (i.e. continuous loop). pcName -- A descriptive name for the task. This is mainly used to facilitate debugging. Max length defined by configMAX_TASK_NAME_LEN - default is 16. usStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. Systems that include MPU support can optionally create tasks in a privileged (system) mode by setting bit portPRIVILEGE_BIT of the priority parameter. For example, to create a privileged task at priority 2 the uxPriority parameter should be set to ( 2 | portPRIVILEGE_BIT ). pxCreatedTask -- Used to pass back a handle by which the created task can be referenced. pxTaskCode -- Pointer to the task entry function. Tasks must be implemented to never return (i.e. continuous loop). pcName -- A descriptive name for the task. This is mainly used to facilitate debugging. Max length defined by configMAX_TASK_NAME_LEN - default is 16. usStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. Systems that include MPU support can optionally create tasks in a privileged (system) mode by setting bit portPRIVILEGE_BIT of the priority parameter. For example, to create a privileged task at priority 2 the uxPriority parameter should be set to ( 2 | portPRIVILEGE_BIT ). pxCreatedTask -- Used to pass back a handle by which the created task can be referenced. pxTaskCode -- Pointer to the task entry function. Tasks must be implemented to never return (i.e. continuous loop). Returns pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined in the file projdefs.h Parameters pxTaskCode -- Pointer to the task entry function. Tasks must be implemented to never return (i.e. continuous loop). pcName -- A descriptive name for the task. This is mainly used to facilitate debugging. Max length defined by configMAX_TASK_NAME_LEN - default is 16. usStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. Systems that include MPU support can optionally create tasks in a privileged (system) mode by setting bit portPRIVILEGE_BIT of the priority parameter. For example, to create a privileged task at priority 2 the uxPriority parameter should be set to ( 2 | portPRIVILEGE_BIT ). pxCreatedTask -- Used to pass back a handle by which the created task can be referenced. Returns pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined in the file projdefs.h static inline TaskHandle_t xTaskCreateStatic(TaskFunction_t pxTaskCode, const char *const pcName, const uint32_t ulStackDepth, void *const pvParameters, UBaseType_t uxPriority, StackType_t *const puxStackBuffer, StaticTask_t *const pxTaskBuffer) Create a new task and add it to the list of tasks that are ready to run. Internally, within the FreeRTOS implementation, tasks use two blocks of memory. The first block is used to hold the task's data structures. The second block is used by the task as its stack. If a task is created using xTaskCreate() then both blocks of memory are automatically dynamically allocated inside the xTaskCreate() function. (see https://www.FreeRTOS.org/a00111.html). If a task is created using xTaskCreateStatic() then the application writer must provide the required memory. xTaskCreateStatic() therefore allows a task to be created without using any dynamic memory allocation. Example usage: // Dimensions of the buffer that the task being created will use as its stack. // NOTE: This is the number of words the stack will hold, not the number of // bytes. For example, if each stack item is 32-bits, and this is set to 100, // then 400 bytes (100 * 32-bits) will be allocated. #define STACK_SIZE 200 // Structure that will hold the TCB of the task being created. StaticTask_t xTaskBuffer; // Buffer that the task being created will use as its stack. Note this is // an array of StackType_t variables. The size of StackType_t is dependent on // the RTOS port. StackType_t xStack[ STACK_SIZE ]; // Function that implements the task being created. void vTaskCode( void * pvParameters ) { // The parameter value is expected to be 1 as 1 is passed in the // pvParameters value in the call to xTaskCreateStatic(). configASSERT( ( uint32_t ) pvParameters == 1UL ); for( ;; ) { // Task code goes here. } } // Function that creates a task. void vOtherFunction( void ) { TaskHandle_t xHandle = NULL; // Create the task without using any dynamic memory allocation. xHandle = xTaskCreateStatic( vTaskCode, // Function that implements the task. "NAME", // Text name for the task. STACK_SIZE, // Stack size in words, not bytes. ( void * ) 1, // Parameter passed into the task. tskIDLE_PRIORITY,// Priority at which the task is created. xStack, // Array to use as the task's stack. &xTaskBuffer ); // Variable to hold the task's data structure. // puxStackBuffer and pxTaskBuffer were not NULL, so the task will have // been created, and xHandle will be the task's handle. Use the handle // to suspend the task. vTaskSuspend( xHandle ); } Note If configNUMBER_OF_CORES > 1, this function will create an unpinned task (see tskNO_AFFINITY for more details). Note If program uses thread local variables (ones specified with "__thread" keyword) then storage for them will be allocated on the task's stack. Parameters pxTaskCode -- Pointer to the task entry function. Tasks must be implemented to never return (i.e. continuous loop). pcName -- A descriptive name for the task. This is mainly used to facilitate debugging. The maximum length of the string is defined by configMAX_TASK_NAME_LEN in FreeRTOSConfig.h. ulStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task will run. puxStackBuffer -- Must point to a StackType_t array that has at least ulStackDepth indexes - the array will then be used as the task's stack, removing the need for the stack to be allocated dynamically. pxTaskBuffer -- Must point to a variable of type StaticTask_t, which will then be used to hold the task's data structures, removing the need for the memory to be allocated dynamically. pxTaskCode -- Pointer to the task entry function. Tasks must be implemented to never return (i.e. continuous loop). pcName -- A descriptive name for the task. This is mainly used to facilitate debugging. The maximum length of the string is defined by configMAX_TASK_NAME_LEN in FreeRTOSConfig.h. ulStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task will run. puxStackBuffer -- Must point to a StackType_t array that has at least ulStackDepth indexes - the array will then be used as the task's stack, removing the need for the stack to be allocated dynamically. pxTaskBuffer -- Must point to a variable of type StaticTask_t, which will then be used to hold the task's data structures, removing the need for the memory to be allocated dynamically. pxTaskCode -- Pointer to the task entry function. Tasks must be implemented to never return (i.e. continuous loop). Returns If neither puxStackBuffer nor pxTaskBuffer are NULL, then the task will be created and a handle to the created task is returned. If either puxStackBuffer or pxTaskBuffer are NULL then the task will not be created and NULL is returned. Parameters pxTaskCode -- Pointer to the task entry function. Tasks must be implemented to never return (i.e. continuous loop). pcName -- A descriptive name for the task. This is mainly used to facilitate debugging. The maximum length of the string is defined by configMAX_TASK_NAME_LEN in FreeRTOSConfig.h. ulStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task will run. puxStackBuffer -- Must point to a StackType_t array that has at least ulStackDepth indexes - the array will then be used as the task's stack, removing the need for the stack to be allocated dynamically. pxTaskBuffer -- Must point to a variable of type StaticTask_t, which will then be used to hold the task's data structures, removing the need for the memory to be allocated dynamically. Returns If neither puxStackBuffer nor pxTaskBuffer are NULL, then the task will be created and a handle to the created task is returned. If either puxStackBuffer or pxTaskBuffer are NULL then the task will not be created and NULL is returned. void vTaskAllocateMPURegions(TaskHandle_t xTask, const MemoryRegion_t *const pxRegions) Memory regions are assigned to a restricted task when the task is created by a call to xTaskCreateRestricted(). These regions can be redefined using vTaskAllocateMPURegions(). Example usage: // Define an array of MemoryRegion_t structures that configures an MPU region // allowing read/write access for 1024 bytes starting at the beginning of the // ucOneKByte array. The other two of the maximum 3 definable regions are // unused so set to zero. static const MemoryRegion_t xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] = { // Base address Length Parameters { ucOneKByte, 1024, portMPU_REGION_READ_WRITE }, { 0, 0, 0 }, { 0, 0, 0 } }; void vATask( void *pvParameters ) { // This task was created such that it has access to certain regions of // memory as defined by the MPU configuration. At some point it is // desired that these MPU regions are replaced with that defined in the // xAltRegions const struct above. Use a call to vTaskAllocateMPURegions() // for this purpose. NULL is used as the task handle to indicate that this // function should modify the MPU regions of the calling task. vTaskAllocateMPURegions( NULL, xAltRegions ); // Now the task can continue its function, but from this point on can only // access its stack and the ucOneKByte array (unless any other statically // defined or shared regions have been declared elsewhere). } Parameters xTask -- The handle of the task being updated. pxRegions -- A pointer to a MemoryRegion_t structure that contains the new memory region definitions. xTask -- The handle of the task being updated. pxRegions -- A pointer to a MemoryRegion_t structure that contains the new memory region definitions. xTask -- The handle of the task being updated. Parameters xTask -- The handle of the task being updated. pxRegions -- A pointer to a MemoryRegion_t structure that contains the new memory region definitions. void vTaskDelete(TaskHandle_t xTaskToDelete) INCLUDE_vTaskDelete must be defined as 1 for this function to be available. See the configuration section for more information. Remove a task from the RTOS real time kernel's management. The task being deleted will be removed from all ready, blocked, suspended and event lists. NOTE: The idle task is responsible for freeing the kernel allocated memory from tasks that have been deleted. It is therefore important that the idle task is not starved of microcontroller processing time if your application makes any calls to vTaskDelete (). Memory allocated by the task code is not automatically freed, and should be freed before the task is deleted. See the demo application file death.c for sample code that utilises vTaskDelete (). Example usage: void vOtherFunction( void ) { TaskHandle_t xHandle; // Create the task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // Use the handle to delete the task. vTaskDelete( xHandle ); } Parameters xTaskToDelete -- The handle of the task to be deleted. Passing NULL will cause the calling task to be deleted. Parameters xTaskToDelete -- The handle of the task to be deleted. Passing NULL will cause the calling task to be deleted. void vTaskDelay(const TickType_t xTicksToDelay) Delay a task for a given number of ticks. The actual time that the task remains blocked depends on the tick rate. The constant portTICK_PERIOD_MS can be used to calculate real time from the tick rate - with the resolution of one tick period. INCLUDE_vTaskDelay must be defined as 1 for this function to be available. See the configuration section for more information. vTaskDelay() specifies a time at which the task wishes to unblock relative to the time at which vTaskDelay() is called. For example, specifying a block period of 100 ticks will cause the task to unblock 100 ticks after vTaskDelay() is called. vTaskDelay() does not therefore provide a good method of controlling the frequency of a periodic task as the path taken through the code, as well as other task and interrupt activity, will affect the frequency at which vTaskDelay() gets called and therefore the time at which the task next executes. See xTaskDelayUntil() for an alternative API function designed to facilitate fixed frequency execution. It does this by specifying an absolute time (rather than a relative time) at which the calling task should unblock. Example usage: void vTaskFunction( void * pvParameters ) { // Block for 500ms. const TickType_t xDelay = 500 / portTICK_PERIOD_MS; for( ;; ) { // Simply toggle the LED every 500ms, blocking between each toggle. vToggleLED(); vTaskDelay( xDelay ); } } Parameters xTicksToDelay -- The amount of time, in tick periods, that the calling task should block. Parameters xTicksToDelay -- The amount of time, in tick periods, that the calling task should block. BaseType_t xTaskDelayUntil(TickType_t *const pxPreviousWakeTime, const TickType_t xTimeIncrement) INCLUDE_xTaskDelayUntil must be defined as 1 for this function to be available. See the configuration section for more information. Delay a task until a specified time. This function can be used by periodic tasks to ensure a constant execution frequency. This function differs from vTaskDelay () in one important aspect: vTaskDelay () will cause a task to block for the specified number of ticks from the time vTaskDelay () is called. It is therefore difficult to use vTaskDelay () by itself to generate a fixed execution frequency as the time between a task starting to execute and that task calling vTaskDelay () may not be fixed [the task may take a different path though the code between calls, or may get interrupted or preempted a different number of times each time it executes]. Whereas vTaskDelay () specifies a wake time relative to the time at which the function is called, xTaskDelayUntil () specifies the absolute (exact) time at which it wishes to unblock. The macro pdMS_TO_TICKS() can be used to calculate the number of ticks from a time specified in milliseconds with a resolution of one tick period. Example usage: // Perform an action every 10 ticks. void vTaskFunction( void * pvParameters ) { TickType_t xLastWakeTime; const TickType_t xFrequency = 10; BaseType_t xWasDelayed; // Initialise the xLastWakeTime variable with the current time. xLastWakeTime = xTaskGetTickCount (); for( ;; ) { // Wait for the next cycle. xWasDelayed = xTaskDelayUntil( &xLastWakeTime, xFrequency ); // Perform action here. xWasDelayed value can be used to determine // whether a deadline was missed if the code here took too long. } } Parameters pxPreviousWakeTime -- Pointer to a variable that holds the time at which the task was last unblocked. The variable must be initialised with the current time prior to its first use (see the example below). Following this the variable is automatically updated within xTaskDelayUntil (). xTimeIncrement -- The cycle time period. The task will be unblocked at time *pxPreviousWakeTime + xTimeIncrement. Calling xTaskDelayUntil with the same xTimeIncrement parameter value will cause the task to execute with a fixed interface period. pxPreviousWakeTime -- Pointer to a variable that holds the time at which the task was last unblocked. The variable must be initialised with the current time prior to its first use (see the example below). Following this the variable is automatically updated within xTaskDelayUntil (). xTimeIncrement -- The cycle time period. The task will be unblocked at time *pxPreviousWakeTime + xTimeIncrement. Calling xTaskDelayUntil with the same xTimeIncrement parameter value will cause the task to execute with a fixed interface period. pxPreviousWakeTime -- Pointer to a variable that holds the time at which the task was last unblocked. The variable must be initialised with the current time prior to its first use (see the example below). Following this the variable is automatically updated within xTaskDelayUntil (). Returns Value which can be used to check whether the task was actually delayed. Will be pdTRUE if the task way delayed and pdFALSE otherwise. A task will not be delayed if the next expected wake time is in the past. Parameters pxPreviousWakeTime -- Pointer to a variable that holds the time at which the task was last unblocked. The variable must be initialised with the current time prior to its first use (see the example below). Following this the variable is automatically updated within xTaskDelayUntil (). xTimeIncrement -- The cycle time period. The task will be unblocked at time *pxPreviousWakeTime + xTimeIncrement. Calling xTaskDelayUntil with the same xTimeIncrement parameter value will cause the task to execute with a fixed interface period. Returns Value which can be used to check whether the task was actually delayed. Will be pdTRUE if the task way delayed and pdFALSE otherwise. A task will not be delayed if the next expected wake time is in the past. BaseType_t xTaskAbortDelay(TaskHandle_t xTask) INCLUDE_xTaskAbortDelay must be defined as 1 in FreeRTOSConfig.h for this function to be available. A task will enter the Blocked state when it is waiting for an event. The event it is waiting for can be a temporal event (waiting for a time), such as when vTaskDelay() is called, or an event on an object, such as when xQueueReceive() or ulTaskNotifyTake() is called. If the handle of a task that is in the Blocked state is used in a call to xTaskAbortDelay() then the task will leave the Blocked state, and return from whichever function call placed the task into the Blocked state. There is no 'FromISR' version of this function as an interrupt would need to know which object a task was blocked on in order to know which actions to take. For example, if the task was blocked on a queue the interrupt handler would then need to know if the queue was locked. Parameters xTask -- The handle of the task to remove from the Blocked state. Returns If the task referenced by xTask was not in the Blocked state then pdFAIL is returned. Otherwise pdPASS is returned. Parameters xTask -- The handle of the task to remove from the Blocked state. Returns If the task referenced by xTask was not in the Blocked state then pdFAIL is returned. Otherwise pdPASS is returned. UBaseType_t uxTaskPriorityGet(const TaskHandle_t xTask) INCLUDE_uxTaskPriorityGet must be defined as 1 for this function to be available. See the configuration section for more information. Obtain the priority of any task. Example usage: void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to obtain the priority of the created task. // It was created with tskIDLE_PRIORITY, but may have changed // it itself. if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY ) { // The task has changed it's priority. } // ... // Is our priority higher than the created task? if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) ) { // Our priority (obtained using NULL handle) is higher. } } Parameters xTask -- Handle of the task to be queried. Passing a NULL handle results in the priority of the calling task being returned. Returns The priority of xTask. Parameters xTask -- Handle of the task to be queried. Passing a NULL handle results in the priority of the calling task being returned. Returns The priority of xTask. UBaseType_t uxTaskPriorityGetFromISR(const TaskHandle_t xTask) A version of uxTaskPriorityGet() that can be used from an ISR. eTaskState eTaskGetState(TaskHandle_t xTask) INCLUDE_eTaskGetState must be defined as 1 for this function to be available. See the configuration section for more information. Obtain the state of any task. States are encoded by the eTaskState enumerated type. Parameters xTask -- Handle of the task to be queried. Returns The state of xTask at the time the function was called. Note the state of the task might change between the function being called, and the functions return value being tested by the calling task. Parameters xTask -- Handle of the task to be queried. Returns The state of xTask at the time the function was called. Note the state of the task might change between the function being called, and the functions return value being tested by the calling task. void vTaskGetInfo(TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState) configUSE_TRACE_FACILITY must be defined as 1 for this function to be available. See the configuration section for more information. Populates a TaskStatus_t structure with information about a task. Example usage: void vAFunction( void ) { TaskHandle_t xHandle; TaskStatus_t xTaskDetails; // Obtain the handle of a task from its name. xHandle = xTaskGetHandle( "Task_Name" ); // Check the handle is not NULL. configASSERT( xHandle ); // Use the handle to obtain further information about the task. vTaskGetInfo( xHandle, &xTaskDetails, pdTRUE, // Include the high water mark in xTaskDetails. eInvalid ); // Include the task state in xTaskDetails. } Parameters xTask -- Handle of the task being queried. If xTask is NULL then information will be returned about the calling task. pxTaskStatus -- A pointer to the TaskStatus_t structure that will be filled with information about the task referenced by the handle passed using the xTask parameter. xGetFreeStackSpace -- The TaskStatus_t structure contains a member to report the stack high water mark of the task being queried. Calculating the stack high water mark takes a relatively long time, and can make the system temporarily unresponsive - so the xGetFreeStackSpace parameter is provided to allow the high water mark checking to be skipped. The high watermark value will only be written to the TaskStatus_t structure if xGetFreeStackSpace is not set to pdFALSE; eState -- The TaskStatus_t structure contains a member to report the state of the task being queried. Obtaining the task state is not as fast as a simple assignment - so the eState parameter is provided to allow the state information to be omitted from the TaskStatus_t structure. To obtain state information then set eState to eInvalid - otherwise the value passed in eState will be reported as the task state in the TaskStatus_t structure. xTask -- Handle of the task being queried. If xTask is NULL then information will be returned about the calling task. pxTaskStatus -- A pointer to the TaskStatus_t structure that will be filled with information about the task referenced by the handle passed using the xTask parameter. xGetFreeStackSpace -- The TaskStatus_t structure contains a member to report the stack high water mark of the task being queried. Calculating the stack high water mark takes a relatively long time, and can make the system temporarily unresponsive - so the xGetFreeStackSpace parameter is provided to allow the high water mark checking to be skipped. The high watermark value will only be written to the TaskStatus_t structure if xGetFreeStackSpace is not set to pdFALSE; eState -- The TaskStatus_t structure contains a member to report the state of the task being queried. Obtaining the task state is not as fast as a simple assignment - so the eState parameter is provided to allow the state information to be omitted from the TaskStatus_t structure. To obtain state information then set eState to eInvalid - otherwise the value passed in eState will be reported as the task state in the TaskStatus_t structure. xTask -- Handle of the task being queried. If xTask is NULL then information will be returned about the calling task. Parameters xTask -- Handle of the task being queried. If xTask is NULL then information will be returned about the calling task. pxTaskStatus -- A pointer to the TaskStatus_t structure that will be filled with information about the task referenced by the handle passed using the xTask parameter. xGetFreeStackSpace -- The TaskStatus_t structure contains a member to report the stack high water mark of the task being queried. Calculating the stack high water mark takes a relatively long time, and can make the system temporarily unresponsive - so the xGetFreeStackSpace parameter is provided to allow the high water mark checking to be skipped. The high watermark value will only be written to the TaskStatus_t structure if xGetFreeStackSpace is not set to pdFALSE; eState -- The TaskStatus_t structure contains a member to report the state of the task being queried. Obtaining the task state is not as fast as a simple assignment - so the eState parameter is provided to allow the state information to be omitted from the TaskStatus_t structure. To obtain state information then set eState to eInvalid - otherwise the value passed in eState will be reported as the task state in the TaskStatus_t structure. void vTaskPrioritySet(TaskHandle_t xTask, UBaseType_t uxNewPriority) INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available. See the configuration section for more information. Set the priority of any task. A context switch will occur before the function returns if the priority being set is higher than the currently executing task. Example usage: void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to raise the priority of the created task. vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 ); // ... // Use a NULL handle to raise our priority to the same value. vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 ); } Parameters xTask -- Handle to the task for which the priority is being set. Passing a NULL handle results in the priority of the calling task being set. uxNewPriority -- The priority to which the task will be set. xTask -- Handle to the task for which the priority is being set. Passing a NULL handle results in the priority of the calling task being set. uxNewPriority -- The priority to which the task will be set. xTask -- Handle to the task for which the priority is being set. Passing a NULL handle results in the priority of the calling task being set. Parameters xTask -- Handle to the task for which the priority is being set. Passing a NULL handle results in the priority of the calling task being set. uxNewPriority -- The priority to which the task will be set. void vTaskSuspend(TaskHandle_t xTaskToSuspend) INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. See the configuration section for more information. Suspend any task. When suspended a task will never get any microcontroller processing time, no matter what its priority. Calls to vTaskSuspend are not accumulative - i.e. calling vTaskSuspend () twice on the same task still only requires one call to vTaskResume () to ready the suspended task. Example usage: void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to suspend the created task. vTaskSuspend( xHandle ); // ... // The created task will not run during this period, unless // another task calls vTaskResume( xHandle ). //... // Suspend ourselves. vTaskSuspend( NULL ); // We cannot get here unless another task calls vTaskResume // with our handle as the parameter. } Parameters xTaskToSuspend -- Handle to the task being suspended. Passing a NULL handle will cause the calling task to be suspended. Parameters xTaskToSuspend -- Handle to the task being suspended. Passing a NULL handle will cause the calling task to be suspended. void vTaskResume(TaskHandle_t xTaskToResume) INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. See the configuration section for more information. Resumes a suspended task. A task that has been suspended by one or more calls to vTaskSuspend () will be made available for running again by a single call to vTaskResume (). Example usage: void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to suspend the created task. vTaskSuspend( xHandle ); // ... // The created task will not run during this period, unless // another task calls vTaskResume( xHandle ). //... // Resume the suspended task ourselves. vTaskResume( xHandle ); // The created task will once again get microcontroller processing // time in accordance with its priority within the system. } Parameters xTaskToResume -- Handle to the task being readied. Parameters xTaskToResume -- Handle to the task being readied. BaseType_t xTaskResumeFromISR(TaskHandle_t xTaskToResume) INCLUDE_xTaskResumeFromISR must be defined as 1 for this function to be available. See the configuration section for more information. An implementation of vTaskResume() that can be called from within an ISR. A task that has been suspended by one or more calls to vTaskSuspend () will be made available for running again by a single call to xTaskResumeFromISR (). xTaskResumeFromISR() should not be used to synchronise a task with an interrupt if there is a chance that the interrupt could arrive prior to the task being suspended - as this can lead to interrupts being missed. Use of a semaphore as a synchronisation mechanism would avoid this eventuality. Parameters xTaskToResume -- Handle to the task being readied. Returns pdTRUE if resuming the task should result in a context switch, otherwise pdFALSE. This is used by the ISR to determine if a context switch may be required following the ISR. Parameters xTaskToResume -- Handle to the task being readied. Returns pdTRUE if resuming the task should result in a context switch, otherwise pdFALSE. This is used by the ISR to determine if a context switch may be required following the ISR. void vTaskSuspendAll(void) Suspends the scheduler without disabling interrupts. Context switches will not occur while the scheduler is suspended. After calling vTaskSuspendAll () the calling task will continue to execute without risk of being swapped out until a call to xTaskResumeAll () has been made. API functions that have the potential to cause a context switch (for example, xTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler is suspended. Example usage: void vTask1( void * pvParameters ) { for( ;; ) { // Task code goes here. // ... // At some point the task wants to perform a long operation during // which it does not want to get swapped out. It cannot use // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the // operation may cause interrupts to be missed - including the // ticks. // Prevent the real time kernel swapping out the task. vTaskSuspendAll (); // Perform the operation here. There is no need to use critical // sections as we have all the microcontroller processing time. // During this time interrupts will still operate and the kernel // tick count will be maintained. // ... // The operation is complete. Restart the kernel. xTaskResumeAll (); } } BaseType_t xTaskResumeAll(void) Resumes scheduler activity after it was suspended by a call to vTaskSuspendAll(). xTaskResumeAll() only resumes the scheduler. It does not unsuspend tasks that were previously suspended by a call to vTaskSuspend(). Example usage: void vTask1( void * pvParameters ) { for( ;; ) { // Task code goes here. // ... // At some point the task wants to perform a long operation during // which it does not want to get swapped out. It cannot use // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the // operation may cause interrupts to be missed - including the // ticks. // Prevent the real time kernel swapping out the task. vTaskSuspendAll (); // Perform the operation here. There is no need to use critical // sections as we have all the microcontroller processing time. // During this time interrupts will still operate and the real // time kernel tick count will be maintained. // ... // The operation is complete. Restart the kernel. We want to force // a context switch - but there is no point if resuming the scheduler // caused a context switch already. if( !xTaskResumeAll () ) { taskYIELD (); } } } Returns If resuming the scheduler caused a context switch then pdTRUE is returned, otherwise pdFALSE is returned. Returns If resuming the scheduler caused a context switch then pdTRUE is returned, otherwise pdFALSE is returned. TickType_t xTaskGetTickCount(void) Returns The count of ticks since vTaskStartScheduler was called. Returns The count of ticks since vTaskStartScheduler was called. TickType_t xTaskGetTickCountFromISR(void) This is a version of xTaskGetTickCount() that is safe to be called from an ISR - provided that TickType_t is the natural word size of the microcontroller being used or interrupt nesting is either not supported or not being used. Returns The count of ticks since vTaskStartScheduler was called. Returns The count of ticks since vTaskStartScheduler was called. UBaseType_t uxTaskGetNumberOfTasks(void) Returns The number of tasks that the real time kernel is currently managing. This includes all ready, blocked and suspended tasks. A task that has been deleted but not yet freed by the idle task will also be included in the count. Returns The number of tasks that the real time kernel is currently managing. This includes all ready, blocked and suspended tasks. A task that has been deleted but not yet freed by the idle task will also be included in the count. char *pcTaskGetName(TaskHandle_t xTaskToQuery) Returns The text (human readable) name of the task referenced by the handle xTaskToQuery. A task can query its own name by either passing in its own handle, or by setting xTaskToQuery to NULL. Returns The text (human readable) name of the task referenced by the handle xTaskToQuery. A task can query its own name by either passing in its own handle, or by setting xTaskToQuery to NULL. TaskHandle_t xTaskGetHandle(const char *pcNameToQuery) NOTE: This function takes a relatively long time to complete and should be used sparingly. Returns The handle of the task that has the human readable name pcNameToQuery. NULL is returned if no matching name is found. INCLUDE_xTaskGetHandle must be set to 1 in FreeRTOSConfig.h for pcTaskGetHandle() to be available. Returns The handle of the task that has the human readable name pcNameToQuery. NULL is returned if no matching name is found. INCLUDE_xTaskGetHandle must be set to 1 in FreeRTOSConfig.h for pcTaskGetHandle() to be available. BaseType_t xTaskGetStaticBuffers(TaskHandle_t xTask, StackType_t **ppuxStackBuffer, StaticTask_t **ppxTaskBuffer) Retrieve pointers to a statically created task's data structure buffer and stack buffer. These are the same buffers that are supplied at the time of creation. Parameters xTask -- The task for which to retrieve the buffers. ppuxStackBuffer -- Used to return a pointer to the task's stack buffer. ppxTaskBuffer -- Used to return a pointer to the task's data structure buffer. xTask -- The task for which to retrieve the buffers. ppuxStackBuffer -- Used to return a pointer to the task's stack buffer. ppxTaskBuffer -- Used to return a pointer to the task's data structure buffer. xTask -- The task for which to retrieve the buffers. Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. Parameters xTask -- The task for which to retrieve the buffers. ppuxStackBuffer -- Used to return a pointer to the task's stack buffer. ppxTaskBuffer -- Used to return a pointer to the task's data structure buffer. Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. UBaseType_t uxTaskGetStackHighWaterMark(TaskHandle_t xTask) INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for this function to be available. Returns the high water mark of the stack associated with xTask. That is, the minimum free stack space there has been (in words, so on a 32 bit machine a value of 1 means 4 bytes) since the task started. The smaller the returned number the closer the task has come to overflowing its stack. uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the same except for their return type. Using configSTACK_DEPTH_TYPE allows the user to determine the return type. It gets around the problem of the value overflowing on 8-bit types without breaking backward compatibility for applications that expect an 8-bit return type. Parameters xTask -- Handle of the task associated with the stack to be checked. Set xTask to NULL to check the stack of the calling task. Returns The smallest amount of free stack space there has been (in words, so actual spaces on the stack rather than bytes) since the task referenced by xTask was created. Parameters xTask -- Handle of the task associated with the stack to be checked. Set xTask to NULL to check the stack of the calling task. Returns The smallest amount of free stack space there has been (in words, so actual spaces on the stack rather than bytes) since the task referenced by xTask was created. configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2(TaskHandle_t xTask) INCLUDE_uxTaskGetStackHighWaterMark2 must be set to 1 in FreeRTOSConfig.h for this function to be available. Returns the high water mark of the stack associated with xTask. That is, the minimum free stack space there has been (in words, so on a 32 bit machine a value of 1 means 4 bytes) since the task started. The smaller the returned number the closer the task has come to overflowing its stack. uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the same except for their return type. Using configSTACK_DEPTH_TYPE allows the user to determine the return type. It gets around the problem of the value overflowing on 8-bit types without breaking backward compatibility for applications that expect an 8-bit return type. Parameters xTask -- Handle of the task associated with the stack to be checked. Set xTask to NULL to check the stack of the calling task. Returns The smallest amount of free stack space there has been (in words, so actual spaces on the stack rather than bytes) since the task referenced by xTask was created. Parameters xTask -- Handle of the task associated with the stack to be checked. Set xTask to NULL to check the stack of the calling task. Returns The smallest amount of free stack space there has been (in words, so actual spaces on the stack rather than bytes) since the task referenced by xTask was created. void vTaskSetApplicationTaskTag(TaskHandle_t xTask, TaskHookFunction_t pxHookFunction) Sets pxHookFunction to be the task hook function used by the task xTask. Passing xTask as NULL has the effect of setting the calling tasks hook function. TaskHookFunction_t xTaskGetApplicationTaskTag(TaskHandle_t xTask) Returns the pxHookFunction value assigned to the task xTask. Do not call from an interrupt service routine - call xTaskGetApplicationTaskTagFromISR() instead. TaskHookFunction_t xTaskGetApplicationTaskTagFromISR(TaskHandle_t xTask) Returns the pxHookFunction value assigned to the task xTask. Can be called from an interrupt service routine. void vTaskSetThreadLocalStoragePointer(TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue) Each task contains an array of pointers that is dimensioned by the configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The kernel does not use the pointers itself, so the application writer can use the pointers for any purpose they wish. The following two functions are used to set and query a pointer respectively. void *pvTaskGetThreadLocalStoragePointer(TaskHandle_t xTaskToQuery, BaseType_t xIndex) void vApplicationGetIdleTaskMemory(StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize) This function is used to provide a statically allocated block of memory to FreeRTOS to hold the Idle Task TCB. This function is required when configSUPPORT_STATIC_ALLOCATION is set. For more information see this URI: https://www.FreeRTOS.org/a00110.html#configSUPPORT_STATIC_ALLOCATION Parameters ppxIdleTaskTCBBuffer -- A handle to a statically allocated TCB buffer ppxIdleTaskStackBuffer -- A handle to a statically allocated Stack buffer for the idle task pulIdleTaskStackSize -- A pointer to the number of elements that will fit in the allocated stack buffer ppxIdleTaskTCBBuffer -- A handle to a statically allocated TCB buffer ppxIdleTaskStackBuffer -- A handle to a statically allocated Stack buffer for the idle task pulIdleTaskStackSize -- A pointer to the number of elements that will fit in the allocated stack buffer ppxIdleTaskTCBBuffer -- A handle to a statically allocated TCB buffer Parameters ppxIdleTaskTCBBuffer -- A handle to a statically allocated TCB buffer ppxIdleTaskStackBuffer -- A handle to a statically allocated Stack buffer for the idle task pulIdleTaskStackSize -- A pointer to the number of elements that will fit in the allocated stack buffer BaseType_t xTaskCallApplicationTaskHook(TaskHandle_t xTask, void *pvParameter) Calls the hook function associated with xTask. Passing xTask as NULL has the effect of calling the Running tasks (the calling task) hook function. pvParameter is passed to the hook function for the task to interpret as it wants. The return value is the value returned by the task hook function registered by the user. TaskHandle_t xTaskGetIdleTaskHandle(void) xTaskGetIdleTaskHandle() is only available if INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h. Simply returns the handle of the idle task of the current core. It is not valid to call xTaskGetIdleTaskHandle() before the scheduler has been started. UBaseType_t uxTaskGetSystemState(TaskStatus_t *const pxTaskStatusArray, const UBaseType_t uxArraySize, configRUN_TIME_COUNTER_TYPE *const pulTotalRunTime) configUSE_TRACE_FACILITY must be defined as 1 in FreeRTOSConfig.h for uxTaskGetSystemState() to be available. uxTaskGetSystemState() populates an TaskStatus_t structure for each task in the system. TaskStatus_t structures contain, among other things, members for the task handle, task name, task priority, task state, and total amount of run time consumed by the task. See the TaskStatus_t structure definition in this file for the full member list. NOTE: This function is intended for debugging use only as its use results in the scheduler remaining suspended for an extended period. Example usage: // This example demonstrates how a human readable table of run time stats // information is generated from raw data provided by uxTaskGetSystemState(). // The human readable table is written to pcWriteBuffer void vTaskGetRunTimeStats( char *pcWriteBuffer ) { TaskStatus_t *pxTaskStatusArray; volatile UBaseType_t uxArraySize, x; configRUN_TIME_COUNTER_TYPE ulTotalRunTime, ulStatsAsPercentage; // Make sure the write buffer does not contain a string. pcWriteBuffer = 0x00; // Take a snapshot of the number of tasks in case it changes while this // function is executing. uxArraySize = uxTaskGetNumberOfTasks(); // Allocate a TaskStatus_t structure for each task. An array could be // allocated statically at compile time. pxTaskStatusArray = pvPortMalloc( uxArraySize * sizeof( TaskStatus_t ) ); if( pxTaskStatusArray != NULL ) { // Generate raw status information about each task. uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime ); // For percentage calculations. ulTotalRunTime /= 100UL; // Avoid divide by zero errors. if( ulTotalRunTime > 0 ) { // For each populated position in the pxTaskStatusArray array, // format the raw data as human readable ASCII data for( x = 0; x < uxArraySize; x++ ) { // What percentage of the total run time has the task used? // This will always be rounded down to the nearest integer. // ulTotalRunTimeDiv100 has already been divided by 100. ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime; if( ulStatsAsPercentage > 0UL ) { sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage ); } else { // If the percentage is zero here then the task has // consumed less than 1% of the total run time. sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter ); } pcWriteBuffer += strlen( ( char * ) pcWriteBuffer ); } } // The array is no longer needed, free the memory it consumes. vPortFree( pxTaskStatusArray ); } } Parameters pxTaskStatusArray -- A pointer to an array of TaskStatus_t structures. The array must contain at least one TaskStatus_t structure for each task that is under the control of the RTOS. The number of tasks under the control of the RTOS can be determined using the uxTaskGetNumberOfTasks() API function. uxArraySize -- The size of the array pointed to by the pxTaskStatusArray parameter. The size is specified as the number of indexes in the array, or the number of TaskStatus_t structures contained in the array, not by the number of bytes in the array. pulTotalRunTime -- If configGENERATE_RUN_TIME_STATS is set to 1 in FreeRTOSConfig.h then *pulTotalRunTime is set by uxTaskGetSystemState() to the total run time (as defined by the run time stats clock, see https://www.FreeRTOS.org/rtos-run-time-stats.html) since the target booted. pulTotalRunTime can be set to NULL to omit the total run time information. pxTaskStatusArray -- A pointer to an array of TaskStatus_t structures. The array must contain at least one TaskStatus_t structure for each task that is under the control of the RTOS. The number of tasks under the control of the RTOS can be determined using the uxTaskGetNumberOfTasks() API function. uxArraySize -- The size of the array pointed to by the pxTaskStatusArray parameter. The size is specified as the number of indexes in the array, or the number of TaskStatus_t structures contained in the array, not by the number of bytes in the array. pulTotalRunTime -- If configGENERATE_RUN_TIME_STATS is set to 1 in FreeRTOSConfig.h then *pulTotalRunTime is set by uxTaskGetSystemState() to the total run time (as defined by the run time stats clock, see https://www.FreeRTOS.org/rtos-run-time-stats.html) since the target booted. pulTotalRunTime can be set to NULL to omit the total run time information. pxTaskStatusArray -- A pointer to an array of TaskStatus_t structures. The array must contain at least one TaskStatus_t structure for each task that is under the control of the RTOS. The number of tasks under the control of the RTOS can be determined using the uxTaskGetNumberOfTasks() API function. Returns The number of TaskStatus_t structures that were populated by uxTaskGetSystemState(). This should equal the number returned by the uxTaskGetNumberOfTasks() API function, but will be zero if the value passed in the uxArraySize parameter was too small. Parameters pxTaskStatusArray -- A pointer to an array of TaskStatus_t structures. The array must contain at least one TaskStatus_t structure for each task that is under the control of the RTOS. The number of tasks under the control of the RTOS can be determined using the uxTaskGetNumberOfTasks() API function. uxArraySize -- The size of the array pointed to by the pxTaskStatusArray parameter. The size is specified as the number of indexes in the array, or the number of TaskStatus_t structures contained in the array, not by the number of bytes in the array. pulTotalRunTime -- If configGENERATE_RUN_TIME_STATS is set to 1 in FreeRTOSConfig.h then *pulTotalRunTime is set by uxTaskGetSystemState() to the total run time (as defined by the run time stats clock, see https://www.FreeRTOS.org/rtos-run-time-stats.html) since the target booted. pulTotalRunTime can be set to NULL to omit the total run time information. Returns The number of TaskStatus_t structures that were populated by uxTaskGetSystemState(). This should equal the number returned by the uxTaskGetNumberOfTasks() API function, but will be zero if the value passed in the uxArraySize parameter was too small. void vTaskList(char *pcWriteBuffer) configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must both be defined as 1 for this function to be available. See the configuration section of the FreeRTOS.org website for more information. NOTE 1: This function will disable interrupts for its duration. It is not intended for normal application runtime use but as a debug aid. Lists all the current tasks, along with their current state and stack usage high water mark. Tasks are reported as blocked ('B'), ready ('R'), deleted ('D') or suspended ('S'). PLEASE NOTE: This function is provided for convenience only, and is used by many of the demo applications. Do not consider it to be part of the scheduler. vTaskList() calls uxTaskGetSystemState(), then formats part of the uxTaskGetSystemState() output into a human readable table that displays task: names, states, priority, stack usage and task number. Stack usage specified as the number of unused StackType_t words stack can hold on top of stack - not the number of bytes. vTaskList() has a dependency on the sprintf() C library function that might bloat the code size, use a lot of stack, and provide different results on different platforms. An alternative, tiny, third party, and limited functionality implementation of sprintf() is provided in many of the FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note printf-stdarg.c does not provide a full snprintf() implementation!). It is recommended that production systems call uxTaskGetSystemState() directly to get access to raw stats data, rather than indirectly through a call to vTaskList(). Parameters pcWriteBuffer -- A buffer into which the above mentioned details will be written, in ASCII form. This buffer is assumed to be large enough to contain the generated report. Approximately 40 bytes per task should be sufficient. Parameters pcWriteBuffer -- A buffer into which the above mentioned details will be written, in ASCII form. This buffer is assumed to be large enough to contain the generated report. Approximately 40 bytes per task should be sufficient. void vTaskGetRunTimeStats(char *pcWriteBuffer) configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS must both be defined as 1 for this function to be available. The application must also then provide definitions for portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() to configure a peripheral timer/counter and return the timers current count value respectively. The counter should be at least 10 times the frequency of the tick count. NOTE 1: This function will disable interrupts for its duration. It is not intended for normal application runtime use but as a debug aid. Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total accumulated execution time being stored for each task. The resolution of the accumulated time value depends on the frequency of the timer configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. Calling vTaskGetRunTimeStats() writes the total execution time of each task into a buffer, both as an absolute count value and as a percentage of the total system execution time. NOTE 2: This function is provided for convenience only, and is used by many of the demo applications. Do not consider it to be part of the scheduler. vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the uxTaskGetSystemState() output into a human readable table that displays the amount of time each task has spent in the Running state in both absolute and percentage terms. vTaskGetRunTimeStats() has a dependency on the sprintf() C library function that might bloat the code size, use a lot of stack, and provide different results on different platforms. An alternative, tiny, third party, and limited functionality implementation of sprintf() is provided in many of the FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note printf-stdarg.c does not provide a full snprintf() implementation!). It is recommended that production systems call uxTaskGetSystemState() directly to get access to raw stats data, rather than indirectly through a call to vTaskGetRunTimeStats(). Parameters pcWriteBuffer -- A buffer into which the execution times will be written, in ASCII form. This buffer is assumed to be large enough to contain the generated report. Approximately 40 bytes per task should be sufficient. Parameters pcWriteBuffer -- A buffer into which the execution times will be written, in ASCII form. This buffer is assumed to be large enough to contain the generated report. Approximately 40 bytes per task should be sufficient. configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimeCounter(void) configGENERATE_RUN_TIME_STATS, configUSE_STATS_FORMATTING_FUNCTIONS and INCLUDE_xTaskGetIdleTaskHandle must all be defined as 1 for these functions to be available. The application must also then provide definitions for portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() to configure a peripheral timer/counter and return the timers current count value respectively. The counter should be at least 10 times the frequency of the tick count. Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total accumulated execution time being stored for each task. The resolution of the accumulated time value depends on the frequency of the timer configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. While uxTaskGetSystemState() and vTaskGetRunTimeStats() writes the total execution time of each task into a buffer, ulTaskGetIdleRunTimeCounter() returns the total execution time of just the idle task and ulTaskGetIdleRunTimePercent() returns the percentage of the CPU time used by just the idle task. Note the amount of idle time is only a good measure of the slack time in a system if there are no other tasks executing at the idle priority, tickless idle is not used, and configIDLE_SHOULD_YIELD is set to 0. Note If configNUMBER_OF_CORES > 1, calling this function will query the idle task of the current core. Returns The total run time of the idle task or the percentage of the total run time consumed by the idle task. This is the amount of time the idle task has actually been executing. The unit of time is dependent on the frequency configured using the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() macros. Returns The total run time of the idle task or the percentage of the total run time consumed by the idle task. This is the amount of time the idle task has actually been executing. The unit of time is dependent on the frequency configured using the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() macros. configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimePercent(void) BaseType_t xTaskGenericNotifyWait(UBaseType_t uxIndexToWaitOn, uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait) Waits for a direct to task notification to be pending at a given index within an array of direct to task notifications. See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this function to be available. Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of the task's notification values. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. A notification sent to a task will remain pending until it is cleared by the task calling xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() (or their un-indexed equivalents). If the task was already in the Blocked state to wait for a notification when the notification arrives then the task will automatically be removed from the Blocked state (unblocked) and the notification cleared. A task can use xTaskNotifyWaitIndexed() to [optionally] block to wait for a notification to be pending, or ulTaskNotifyTakeIndexed() to [optionally] block to wait for a notification value to have a non-zero value. The task does not consume any CPU time while it is in the Blocked state. NOTE Each notification within the array operates independently - a task can only block on one notification within the array at a time and will not be unblocked by a notification sent to any other array index. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. xTaskNotifyWait() is the original API function, and remains backward compatible by always operating on the notification value at index 0 in the array. Calling xTaskNotifyWait() is equivalent to calling xTaskNotifyWaitIndexed() with the uxIndexToWaitOn parameter set to 0. Parameters uxIndexToWaitOn -- The index within the calling task's array of notification values on which the calling task will wait for a notification to be received. uxIndexToWaitOn must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyWait() does not have this parameter and always waits for notifications on index 0. ulBitsToClearOnEntry -- Bits that are set in ulBitsToClearOnEntry value will be cleared in the calling task's notification value before the task checks to see if any notifications are pending, and optionally blocks if no notifications are pending. Setting ulBitsToClearOnEntry to ULONG_MAX (if limits.h is included) or 0xffffffffUL (if limits.h is not included) will have the effect of resetting the task's notification value to 0. Setting ulBitsToClearOnEntry to 0 will leave the task's notification value unchanged. ulBitsToClearOnExit -- If a notification is pending or received before the calling task exits the xTaskNotifyWait() function then the task's notification value (see the xTaskNotify() API function) is passed out using the pulNotificationValue parameter. Then any bits that are set in ulBitsToClearOnExit will be cleared in the task's notification value (note *pulNotificationValue is set before any bits are cleared). Setting ulBitsToClearOnExit to ULONG_MAX (if limits.h is included) or 0xffffffffUL (if limits.h is not included) will have the effect of resetting the task's notification value to 0 before the function exits. Setting ulBitsToClearOnExit to 0 will leave the task's notification value unchanged when the function exits (in which case the value passed out in pulNotificationValue will match the task's notification value). pulNotificationValue -- Used to pass the task's notification value out of the function. Note the value passed out will not be effected by the clearing of any bits caused by ulBitsToClearOnExit being non-zero. xTicksToWait -- The maximum amount of time that the task should wait in the Blocked state for a notification to be received, should a notification not already be pending when xTaskNotifyWait() was called. The task will not consume any processing time while it is in the Blocked state. This is specified in kernel ticks, the macro pdMS_TO_TICKS( value_in_ms ) can be used to convert a time specified in milliseconds to a time specified in ticks. uxIndexToWaitOn -- The index within the calling task's array of notification values on which the calling task will wait for a notification to be received. uxIndexToWaitOn must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyWait() does not have this parameter and always waits for notifications on index 0. ulBitsToClearOnEntry -- Bits that are set in ulBitsToClearOnEntry value will be cleared in the calling task's notification value before the task checks to see if any notifications are pending, and optionally blocks if no notifications are pending. Setting ulBitsToClearOnEntry to ULONG_MAX (if limits.h is included) or 0xffffffffUL (if limits.h is not included) will have the effect of resetting the task's notification value to 0. Setting ulBitsToClearOnEntry to 0 will leave the task's notification value unchanged. ulBitsToClearOnExit -- If a notification is pending or received before the calling task exits the xTaskNotifyWait() function then the task's notification value (see the xTaskNotify() API function) is passed out using the pulNotificationValue parameter. Then any bits that are set in ulBitsToClearOnExit will be cleared in the task's notification value (note *pulNotificationValue is set before any bits are cleared). Setting ulBitsToClearOnExit to ULONG_MAX (if limits.h is included) or 0xffffffffUL (if limits.h is not included) will have the effect of resetting the task's notification value to 0 before the function exits. Setting ulBitsToClearOnExit to 0 will leave the task's notification value unchanged when the function exits (in which case the value passed out in pulNotificationValue will match the task's notification value). pulNotificationValue -- Used to pass the task's notification value out of the function. Note the value passed out will not be effected by the clearing of any bits caused by ulBitsToClearOnExit being non-zero. xTicksToWait -- The maximum amount of time that the task should wait in the Blocked state for a notification to be received, should a notification not already be pending when xTaskNotifyWait() was called. The task will not consume any processing time while it is in the Blocked state. This is specified in kernel ticks, the macro pdMS_TO_TICKS( value_in_ms ) can be used to convert a time specified in milliseconds to a time specified in ticks. uxIndexToWaitOn -- The index within the calling task's array of notification values on which the calling task will wait for a notification to be received. uxIndexToWaitOn must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyWait() does not have this parameter and always waits for notifications on index 0. Returns If a notification was received (including notifications that were already pending when xTaskNotifyWait was called) then pdPASS is returned. Otherwise pdFAIL is returned. Parameters uxIndexToWaitOn -- The index within the calling task's array of notification values on which the calling task will wait for a notification to be received. uxIndexToWaitOn must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyWait() does not have this parameter and always waits for notifications on index 0. ulBitsToClearOnEntry -- Bits that are set in ulBitsToClearOnEntry value will be cleared in the calling task's notification value before the task checks to see if any notifications are pending, and optionally blocks if no notifications are pending. Setting ulBitsToClearOnEntry to ULONG_MAX (if limits.h is included) or 0xffffffffUL (if limits.h is not included) will have the effect of resetting the task's notification value to 0. Setting ulBitsToClearOnEntry to 0 will leave the task's notification value unchanged. ulBitsToClearOnExit -- If a notification is pending or received before the calling task exits the xTaskNotifyWait() function then the task's notification value (see the xTaskNotify() API function) is passed out using the pulNotificationValue parameter. Then any bits that are set in ulBitsToClearOnExit will be cleared in the task's notification value (note *pulNotificationValue is set before any bits are cleared). Setting ulBitsToClearOnExit to ULONG_MAX (if limits.h is included) or 0xffffffffUL (if limits.h is not included) will have the effect of resetting the task's notification value to 0 before the function exits. Setting ulBitsToClearOnExit to 0 will leave the task's notification value unchanged when the function exits (in which case the value passed out in pulNotificationValue will match the task's notification value). pulNotificationValue -- Used to pass the task's notification value out of the function. Note the value passed out will not be effected by the clearing of any bits caused by ulBitsToClearOnExit being non-zero. xTicksToWait -- The maximum amount of time that the task should wait in the Blocked state for a notification to be received, should a notification not already be pending when xTaskNotifyWait() was called. The task will not consume any processing time while it is in the Blocked state. This is specified in kernel ticks, the macro pdMS_TO_TICKS( value_in_ms ) can be used to convert a time specified in milliseconds to a time specified in ticks. Returns If a notification was received (including notifications that were already pending when xTaskNotifyWait was called) then pdPASS is returned. Otherwise pdFAIL is returned. void vTaskGenericNotifyGiveFromISR(TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, BaseType_t *pxHigherPriorityTaskWoken) A version of xTaskNotifyGiveIndexed() that can be called from an interrupt service routine (ISR). See https://www.FreeRTOS.org/RTOS-task-notifications.html for more details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro to be available. Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of the task's notification values. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. vTaskNotifyGiveIndexedFromISR() is intended for use when task notifications are used as light weight and faster binary or counting semaphore equivalents. Actual FreeRTOS semaphores are given from an ISR using the xSemaphoreGiveFromISR() API function, the equivalent action that instead uses a task notification is vTaskNotifyGiveIndexedFromISR(). When task notifications are being used as a binary or counting semaphore equivalent then the task being notified should wait for the notification using the ulTaskNotifyTakeIndexed() API function rather than the xTaskNotifyWaitIndexed() API function. NOTE Each notification within the array operates independently - a task can only block on one notification within the array at a time and will not be unblocked by a notification sent to any other array index. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. xTaskNotifyFromISR() is the original API function, and remains backward compatible by always operating on the notification value at index 0 within the array. Calling xTaskNotifyGiveFromISR() is equivalent to calling xTaskNotifyGiveIndexedFromISR() with the uxIndexToNotify parameter set to 0. Parameters xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyGiveFromISR() does not have this parameter and always sends notifications to index 0. pxHigherPriorityTaskWoken -- vTaskNotifyGiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the task to which the notification was sent to leave the Blocked state, and the unblocked task has a priority higher than the currently running task. If vTaskNotifyGiveFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. How a context switch is requested from an ISR is dependent on the port - see the documentation page for the port in use. xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyGiveFromISR() does not have this parameter and always sends notifications to index 0. pxHigherPriorityTaskWoken -- vTaskNotifyGiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the task to which the notification was sent to leave the Blocked state, and the unblocked task has a priority higher than the currently running task. If vTaskNotifyGiveFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. How a context switch is requested from an ISR is dependent on the port - see the documentation page for the port in use. xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). Parameters xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyGiveFromISR() does not have this parameter and always sends notifications to index 0. pxHigherPriorityTaskWoken -- vTaskNotifyGiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the task to which the notification was sent to leave the Blocked state, and the unblocked task has a priority higher than the currently running task. If vTaskNotifyGiveFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. How a context switch is requested from an ISR is dependent on the port - see the documentation page for the port in use. BaseType_t xTaskGenericNotifyStateClear(TaskHandle_t xTask, UBaseType_t uxIndexToClear) See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these functions to be available. Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. If a notification is sent to an index within the array of notifications then the notification at that index is said to be 'pending' until it is read or explicitly cleared by the receiving task. xTaskNotifyStateClearIndexed() is the function that clears a pending notification without reading the notification value. The notification value at the same array index is not altered. Set xTask to NULL to clear the notification state of the calling task. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. xTaskNotifyStateClear() is the original API function, and remains backward compatible by always operating on the notification value at index 0 within the array. Calling xTaskNotifyStateClear() is equivalent to calling xTaskNotifyStateClearIndexed() with the uxIndexToNotify parameter set to 0. Parameters xTask -- The handle of the RTOS task that will have a notification state cleared. Set xTask to NULL to clear a notification state in the calling task. To obtain a task's handle create the task using xTaskCreate() and make use of the pxCreatedTask parameter, or create the task using xTaskCreateStatic() and store the returned value, or use the task's name in a call to xTaskGetHandle(). uxIndexToClear -- The index within the target task's array of notification values to act upon. For example, setting uxIndexToClear to 1 will clear the state of the notification at index 1 within the array. uxIndexToClear must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. ulTaskNotifyStateClear() does not have this parameter and always acts on the notification at index 0. xTask -- The handle of the RTOS task that will have a notification state cleared. Set xTask to NULL to clear a notification state in the calling task. To obtain a task's handle create the task using xTaskCreate() and make use of the pxCreatedTask parameter, or create the task using xTaskCreateStatic() and store the returned value, or use the task's name in a call to xTaskGetHandle(). uxIndexToClear -- The index within the target task's array of notification values to act upon. For example, setting uxIndexToClear to 1 will clear the state of the notification at index 1 within the array. uxIndexToClear must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. ulTaskNotifyStateClear() does not have this parameter and always acts on the notification at index 0. xTask -- The handle of the RTOS task that will have a notification state cleared. Set xTask to NULL to clear a notification state in the calling task. To obtain a task's handle create the task using xTaskCreate() and make use of the pxCreatedTask parameter, or create the task using xTaskCreateStatic() and store the returned value, or use the task's name in a call to xTaskGetHandle(). Returns pdTRUE if the task's notification state was set to eNotWaitingNotification, otherwise pdFALSE. Parameters xTask -- The handle of the RTOS task that will have a notification state cleared. Set xTask to NULL to clear a notification state in the calling task. To obtain a task's handle create the task using xTaskCreate() and make use of the pxCreatedTask parameter, or create the task using xTaskCreateStatic() and store the returned value, or use the task's name in a call to xTaskGetHandle(). uxIndexToClear -- The index within the target task's array of notification values to act upon. For example, setting uxIndexToClear to 1 will clear the state of the notification at index 1 within the array. uxIndexToClear must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. ulTaskNotifyStateClear() does not have this parameter and always acts on the notification at index 0. Returns pdTRUE if the task's notification state was set to eNotWaitingNotification, otherwise pdFALSE. uint32_t ulTaskGenericNotifyValueClear(TaskHandle_t xTask, UBaseType_t uxIndexToClear, uint32_t ulBitsToClear) See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these functions to be available. Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. ulTaskNotifyValueClearIndexed() clears the bits specified by the ulBitsToClear bit mask in the notification value at array index uxIndexToClear of the task referenced by xTask. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. ulTaskNotifyValueClear() is the original API function, and remains backward compatible by always operating on the notification value at index 0 within the array. Calling ulTaskNotifyValueClear() is equivalent to calling ulTaskNotifyValueClearIndexed() with the uxIndexToClear parameter set to 0. Parameters xTask -- The handle of the RTOS task that will have bits in one of its notification values cleared. Set xTask to NULL to clear bits in a notification value of the calling task. To obtain a task's handle create the task using xTaskCreate() and make use of the pxCreatedTask parameter, or create the task using xTaskCreateStatic() and store the returned value, or use the task's name in a call to xTaskGetHandle(). uxIndexToClear -- The index within the target task's array of notification values in which to clear the bits. uxIndexToClear must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. ulTaskNotifyValueClear() does not have this parameter and always clears bits in the notification value at index 0. ulBitsToClear -- Bit mask of the bits to clear in the notification value of xTask. Set a bit to 1 to clear the corresponding bits in the task's notification value. Set ulBitsToClear to 0xffffffff (UINT_MAX on 32-bit architectures) to clear the notification value to 0. Set ulBitsToClear to 0 to query the task's notification value without clearing any bits. xTask -- The handle of the RTOS task that will have bits in one of its notification values cleared. Set xTask to NULL to clear bits in a notification value of the calling task. To obtain a task's handle create the task using xTaskCreate() and make use of the pxCreatedTask parameter, or create the task using xTaskCreateStatic() and store the returned value, or use the task's name in a call to xTaskGetHandle(). uxIndexToClear -- The index within the target task's array of notification values in which to clear the bits. uxIndexToClear must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. ulTaskNotifyValueClear() does not have this parameter and always clears bits in the notification value at index 0. ulBitsToClear -- Bit mask of the bits to clear in the notification value of xTask. Set a bit to 1 to clear the corresponding bits in the task's notification value. Set ulBitsToClear to 0xffffffff (UINT_MAX on 32-bit architectures) to clear the notification value to 0. Set ulBitsToClear to 0 to query the task's notification value without clearing any bits. xTask -- The handle of the RTOS task that will have bits in one of its notification values cleared. Set xTask to NULL to clear bits in a notification value of the calling task. To obtain a task's handle create the task using xTaskCreate() and make use of the pxCreatedTask parameter, or create the task using xTaskCreateStatic() and store the returned value, or use the task's name in a call to xTaskGetHandle(). Returns The value of the target task's notification value before the bits specified by ulBitsToClear were cleared. Parameters xTask -- The handle of the RTOS task that will have bits in one of its notification values cleared. Set xTask to NULL to clear bits in a notification value of the calling task. To obtain a task's handle create the task using xTaskCreate() and make use of the pxCreatedTask parameter, or create the task using xTaskCreateStatic() and store the returned value, or use the task's name in a call to xTaskGetHandle(). uxIndexToClear -- The index within the target task's array of notification values in which to clear the bits. uxIndexToClear must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. ulTaskNotifyValueClear() does not have this parameter and always clears bits in the notification value at index 0. ulBitsToClear -- Bit mask of the bits to clear in the notification value of xTask. Set a bit to 1 to clear the corresponding bits in the task's notification value. Set ulBitsToClear to 0xffffffff (UINT_MAX on 32-bit architectures) to clear the notification value to 0. Set ulBitsToClear to 0 to query the task's notification value without clearing any bits. Returns The value of the target task's notification value before the bits specified by ulBitsToClear were cleared. void vTaskSetTimeOutState(TimeOut_t *const pxTimeOut) Capture the current time for future use with xTaskCheckForTimeOut(). Parameters pxTimeOut -- Pointer to a timeout object into which the current time is to be captured. The captured time includes the tick count and the number of times the tick count has overflowed since the system first booted. Parameters pxTimeOut -- Pointer to a timeout object into which the current time is to be captured. The captured time includes the tick count and the number of times the tick count has overflowed since the system first booted. BaseType_t xTaskCheckForTimeOut(TimeOut_t *const pxTimeOut, TickType_t *const pxTicksToWait) Determines if pxTicksToWait ticks has passed since a time was captured using a call to vTaskSetTimeOutState(). The captured time includes the tick count and the number of times the tick count has overflowed. Example Usage: // Driver library function used to receive uxWantedBytes from an Rx buffer // that is filled by a UART interrupt. If there are not enough bytes in the // Rx buffer then the task enters the Blocked state until it is notified that // more data has been placed into the buffer. If there is still not enough // data then the task re-enters the Blocked state, and xTaskCheckForTimeOut() // is used to re-calculate the Block time to ensure the total amount of time // spent in the Blocked state does not exceed MAX_TIME_TO_WAIT. This // continues until either the buffer contains at least uxWantedBytes bytes, // or the total amount of time spent in the Blocked state reaches // MAX_TIME_TO_WAIT - at which point the task reads however many bytes are // available up to a maximum of uxWantedBytes. size_t xUART_Receive( uint8_t *pucBuffer, size_t uxWantedBytes ) { size_t uxReceived = 0; TickType_t xTicksToWait = MAX_TIME_TO_WAIT; TimeOut_t xTimeOut; // Initialize xTimeOut. This records the time at which this function // was entered. vTaskSetTimeOutState( &xTimeOut ); // Loop until the buffer contains the wanted number of bytes, or a // timeout occurs. while( UART_bytes_in_rx_buffer( pxUARTInstance ) < uxWantedBytes ) { // The buffer didn't contain enough data so this task is going to // enter the Blocked state. Adjusting xTicksToWait to account for // any time that has been spent in the Blocked state within this // function so far to ensure the total amount of time spent in the // Blocked state does not exceed MAX_TIME_TO_WAIT. if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) != pdFALSE ) { //Timed out before the wanted number of bytes were available, // exit the loop. break; } // Wait for a maximum of xTicksToWait ticks to be notified that the // receive interrupt has placed more data into the buffer. ulTaskNotifyTake( pdTRUE, xTicksToWait ); } // Attempt to read uxWantedBytes from the receive buffer into pucBuffer. // The actual number of bytes read (which might be less than // uxWantedBytes) is returned. uxReceived = UART_read_from_receive_buffer( pxUARTInstance, pucBuffer, uxWantedBytes ); return uxReceived; } Parameters pxTimeOut -- The time status as captured previously using vTaskSetTimeOutState. If the timeout has not yet occurred, it is updated to reflect the current time status. pxTicksToWait -- The number of ticks to check for timeout i.e. if pxTicksToWait ticks have passed since pxTimeOut was last updated (either by vTaskSetTimeOutState() or xTaskCheckForTimeOut()), the timeout has occurred. If the timeout has not occurred, pxTicksToWait is updated to reflect the number of remaining ticks. pxTimeOut -- The time status as captured previously using vTaskSetTimeOutState. If the timeout has not yet occurred, it is updated to reflect the current time status. pxTicksToWait -- The number of ticks to check for timeout i.e. if pxTicksToWait ticks have passed since pxTimeOut was last updated (either by vTaskSetTimeOutState() or xTaskCheckForTimeOut()), the timeout has occurred. If the timeout has not occurred, pxTicksToWait is updated to reflect the number of remaining ticks. pxTimeOut -- The time status as captured previously using vTaskSetTimeOutState. If the timeout has not yet occurred, it is updated to reflect the current time status. Returns If timeout has occurred, pdTRUE is returned. Otherwise pdFALSE is returned and pxTicksToWait is updated to reflect the number of remaining ticks. Parameters pxTimeOut -- The time status as captured previously using vTaskSetTimeOutState. If the timeout has not yet occurred, it is updated to reflect the current time status. pxTicksToWait -- The number of ticks to check for timeout i.e. if pxTicksToWait ticks have passed since pxTimeOut was last updated (either by vTaskSetTimeOutState() or xTaskCheckForTimeOut()), the timeout has occurred. If the timeout has not occurred, pxTicksToWait is updated to reflect the number of remaining ticks. Returns If timeout has occurred, pdTRUE is returned. Otherwise pdFALSE is returned and pxTicksToWait is updated to reflect the number of remaining ticks. BaseType_t xTaskCatchUpTicks(TickType_t xTicksToCatchUp) This function corrects the tick count value after the application code has held interrupts disabled for an extended period resulting in tick interrupts having been missed. This function is similar to vTaskStepTick(), however, unlike vTaskStepTick(), xTaskCatchUpTicks() may move the tick count forward past a time at which a task should be removed from the blocked state. That means tasks may have to be removed from the blocked state as the tick count is moved. Parameters xTicksToCatchUp -- The number of tick interrupts that have been missed due to interrupts being disabled. Its value is not computed automatically, so must be computed by the application writer. Returns pdTRUE if moving the tick count forward resulted in a task leaving the blocked state and a context switch being performed. Otherwise pdFALSE. Parameters xTicksToCatchUp -- The number of tick interrupts that have been missed due to interrupts being disabled. Its value is not computed automatically, so must be computed by the application writer. Returns pdTRUE if moving the tick count forward resulted in a task leaving the blocked state and a context switch being performed. Otherwise pdFALSE. Structures struct xTASK_STATUS Used with the uxTaskGetSystemState() function to return the state of each task in the system. Public Members TaskHandle_t xHandle The handle of the task to which the rest of the information in the structure relates. TaskHandle_t xHandle The handle of the task to which the rest of the information in the structure relates. const char *pcTaskName A pointer to the task's name. This value will be invalid if the task was deleted since the structure was populated! const char *pcTaskName A pointer to the task's name. This value will be invalid if the task was deleted since the structure was populated! UBaseType_t xTaskNumber A number unique to the task. UBaseType_t xTaskNumber A number unique to the task. eTaskState eCurrentState The state in which the task existed when the structure was populated. eTaskState eCurrentState The state in which the task existed when the structure was populated. UBaseType_t uxCurrentPriority The priority at which the task was running (may be inherited) when the structure was populated. UBaseType_t uxCurrentPriority The priority at which the task was running (may be inherited) when the structure was populated. UBaseType_t uxBasePriority The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex. Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. UBaseType_t uxBasePriority The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex. Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. configRUN_TIME_COUNTER_TYPE ulRunTimeCounter The total run time allocated to the task so far, as defined by the run time stats clock. See https://www.FreeRTOS.org/rtos-run-time-stats.html. Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. configRUN_TIME_COUNTER_TYPE ulRunTimeCounter The total run time allocated to the task so far, as defined by the run time stats clock. See https://www.FreeRTOS.org/rtos-run-time-stats.html. Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. StackType_t *pxStackBase Points to the lowest address of the task's stack area. StackType_t *pxStackBase Points to the lowest address of the task's stack area. configSTACK_DEPTH_TYPE usStackHighWaterMark The minimum amount of stack space that has remained for the task since the task was created. The closer this value is to zero the closer the task has come to overflowing its stack. configSTACK_DEPTH_TYPE usStackHighWaterMark The minimum amount of stack space that has remained for the task since the task was created. The closer this value is to zero the closer the task has come to overflowing its stack. BaseType_t xCoreID Core this task is pinned to (0, 1, or tskNO_AFFINITY). If configNUMBER_OF_CORES == 1, this will always be 0. BaseType_t xCoreID Core this task is pinned to (0, 1, or tskNO_AFFINITY). If configNUMBER_OF_CORES == 1, this will always be 0. TaskHandle_t xHandle Macros tskIDLE_PRIORITY Defines the priority used by the idle task. This must not be modified. tskNO_AFFINITY Macro representing and unpinned (i.e., "no affinity") task in xCoreID parameters taskVALID_CORE_ID(xCoreID) Macro to check if an xCoreID value is valid Returns pdTRUE if valid, pdFALSE otherwise. Returns pdTRUE if valid, pdFALSE otherwise. taskYIELD() Macro for forcing a context switch. taskENTER_CRITICAL(x) Macro to mark the start of a critical code region. Preemptive context switches cannot occur when in a critical region. NOTE: This may alter the stack (depending on the portable implementation) so must be used with care! taskENTER_CRITICAL_FROM_ISR() taskENTER_CRITICAL_ISR(x) taskEXIT_CRITICAL(x) Macro to mark the end of a critical code region. Preemptive context switches cannot occur when in a critical region. NOTE: This may alter the stack (depending on the portable implementation) so must be used with care! taskEXIT_CRITICAL_FROM_ISR(x) taskEXIT_CRITICAL_ISR(x) taskDISABLE_INTERRUPTS() Macro to disable all maskable interrupts. taskENABLE_INTERRUPTS() Macro to enable microcontroller interrupts. taskSCHEDULER_SUSPENDED Definitions returned by xTaskGetSchedulerState(). taskSCHEDULER_SUSPENDED is 0 to generate more optimal code when configASSERT() is defined as the constant is used in assert() statements. taskSCHEDULER_NOT_STARTED taskSCHEDULER_RUNNING xTaskNotifyIndexed(xTaskToNotify, uxIndexToNotify, ulValue, eAction) See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these functions to be available. Sends a direct to task notification to a task, with an optional value and action. Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of the task's notification values. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. A task can use xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() to [optionally] block to wait for a notification to be pending. The task does not consume any CPU time while it is in the Blocked state. A notification sent to a task will remain pending until it is cleared by the task calling xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() (or their un-indexed equivalents). If the task was already in the Blocked state to wait for a notification when the notification arrives then the task will automatically be removed from the Blocked state (unblocked) and the notification cleared. NOTE Each notification within the array operates independently - a task can only block on one notification within the array at a time and will not be unblocked by a notification sent to any other array index. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. xTaskNotify() is the original API function, and remains backward compatible by always operating on the notification value at index 0 in the array. Calling xTaskNotify() is equivalent to calling xTaskNotifyIndexed() with the uxIndexToNotify parameter set to 0. eSetBits - The target notification value is bitwise ORed with ulValue. xTaskNotifyIndexed() always returns pdPASS in this case. eIncrement - The target notification value is incremented. ulValue is not used and xTaskNotifyIndexed() always returns pdPASS in this case. eSetValueWithOverwrite - The target notification value is set to the value of ulValue, even if the task being notified had not yet processed the previous notification at the same array index (the task already had a notification pending at that index). xTaskNotifyIndexed() always returns pdPASS in this case. eSetValueWithoutOverwrite - If the task being notified did not already have a notification pending at the same array index then the target notification value is set to ulValue and xTaskNotifyIndexed() will return pdPASS. If the task being notified already had a notification pending at the same array index then no action is performed and pdFAIL is returned. eNoAction - The task receives a notification at the specified array index without the notification value at that index being updated. ulValue is not used and xTaskNotifyIndexed() always returns pdPASS in this case. pulPreviousNotificationValue - Can be used to pass out the subject task's notification value before any bits are modified by the notify function. Parameters xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotify() does not have this parameter and always sends notifications to index 0. ulValue -- Data that can be sent with the notification. How the data is used depends on the value of the eAction parameter. eAction -- Specifies how the notification updates the task's notification value, if at all. Valid values for eAction are as follows: xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotify() does not have this parameter and always sends notifications to index 0. ulValue -- Data that can be sent with the notification. How the data is used depends on the value of the eAction parameter. eAction -- Specifies how the notification updates the task's notification value, if at all. Valid values for eAction are as follows: xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). Returns Dependent on the value of eAction. See the description of the eAction parameter. Parameters xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotify() does not have this parameter and always sends notifications to index 0. ulValue -- Data that can be sent with the notification. How the data is used depends on the value of the eAction parameter. eAction -- Specifies how the notification updates the task's notification value, if at all. Valid values for eAction are as follows: Returns Dependent on the value of eAction. See the description of the eAction parameter. xTaskNotifyAndQueryIndexed(xTaskToNotify, uxIndexToNotify, ulValue, eAction, pulPreviousNotifyValue) See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. xTaskNotifyAndQueryIndexed() performs the same operation as xTaskNotifyIndexed() with the addition that it also returns the subject task's prior notification value (the notification value at the time the function is called rather than when the function returns) in the additional pulPreviousNotifyValue parameter. xTaskNotifyAndQuery() performs the same operation as xTaskNotify() with the addition that it also returns the subject task's prior notification value (the notification value as it was at the time the function is called, rather than when the function returns) in the additional pulPreviousNotifyValue parameter. xTaskNotifyIndexedFromISR(xTaskToNotify, uxIndexToNotify, ulValue, eAction, pxHigherPriorityTaskWoken) See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these functions to be available. A version of xTaskNotifyIndexed() that can be used from an interrupt service routine (ISR). Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of the task's notification values. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. A task can use xTaskNotifyWaitIndexed() to [optionally] block to wait for a notification to be pending, or ulTaskNotifyTakeIndexed() to [optionally] block to wait for a notification value to have a non-zero value. The task does not consume any CPU time while it is in the Blocked state. A notification sent to a task will remain pending until it is cleared by the task calling xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() (or their un-indexed equivalents). If the task was already in the Blocked state to wait for a notification when the notification arrives then the task will automatically be removed from the Blocked state (unblocked) and the notification cleared. NOTE Each notification within the array operates independently - a task can only block on one notification within the array at a time and will not be unblocked by a notification sent to any other array index. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. xTaskNotifyFromISR() is the original API function, and remains backward compatible by always operating on the notification value at index 0 within the array. Calling xTaskNotifyFromISR() is equivalent to calling xTaskNotifyIndexedFromISR() with the uxIndexToNotify parameter set to 0. eSetBits - The task's notification value is bitwise ORed with ulValue. xTaskNotify() always returns pdPASS in this case. eIncrement - The task's notification value is incremented. ulValue is not used and xTaskNotify() always returns pdPASS in this case. eSetValueWithOverwrite - The task's notification value is set to the value of ulValue, even if the task being notified had not yet processed the previous notification (the task already had a notification pending). xTaskNotify() always returns pdPASS in this case. eSetValueWithoutOverwrite - If the task being notified did not already have a notification pending then the task's notification value is set to ulValue and xTaskNotify() will return pdPASS. If the task being notified already had a notification pending then no action is performed and pdFAIL is returned. eNoAction - The task receives a notification without its notification value being updated. ulValue is not used and xTaskNotify() always returns pdPASS in this case. Parameters uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyFromISR() does not have this parameter and always sends notifications to index 0. xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). ulValue -- Data that can be sent with the notification. How the data is used depends on the value of the eAction parameter. eAction -- Specifies how the notification updates the task's notification value, if at all. Valid values for eAction are as follows: pxHigherPriorityTaskWoken -- xTaskNotifyFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the task to which the notification was sent to leave the Blocked state, and the unblocked task has a priority higher than the currently running task. If xTaskNotifyFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. How a context switch is requested from an ISR is dependent on the port - see the documentation page for the port in use. uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyFromISR() does not have this parameter and always sends notifications to index 0. xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). ulValue -- Data that can be sent with the notification. How the data is used depends on the value of the eAction parameter. eAction -- Specifies how the notification updates the task's notification value, if at all. Valid values for eAction are as follows: pxHigherPriorityTaskWoken -- xTaskNotifyFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the task to which the notification was sent to leave the Blocked state, and the unblocked task has a priority higher than the currently running task. If xTaskNotifyFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. How a context switch is requested from an ISR is dependent on the port - see the documentation page for the port in use. uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyFromISR() does not have this parameter and always sends notifications to index 0. Returns Dependent on the value of eAction. See the description of the eAction parameter. Parameters uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyFromISR() does not have this parameter and always sends notifications to index 0. xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). ulValue -- Data that can be sent with the notification. How the data is used depends on the value of the eAction parameter. eAction -- Specifies how the notification updates the task's notification value, if at all. Valid values for eAction are as follows: pxHigherPriorityTaskWoken -- xTaskNotifyFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the task to which the notification was sent to leave the Blocked state, and the unblocked task has a priority higher than the currently running task. If xTaskNotifyFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. How a context switch is requested from an ISR is dependent on the port - see the documentation page for the port in use. Returns Dependent on the value of eAction. See the description of the eAction parameter. xTaskNotifyAndQueryIndexedFromISR(xTaskToNotify, uxIndexToNotify, ulValue, eAction, pulPreviousNotificationValue, pxHigherPriorityTaskWoken) See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. xTaskNotifyAndQueryIndexedFromISR() performs the same operation as xTaskNotifyIndexedFromISR() with the addition that it also returns the subject task's prior notification value (the notification value at the time the function is called rather than at the time the function returns) in the additional pulPreviousNotifyValue parameter. xTaskNotifyAndQueryFromISR() performs the same operation as xTaskNotifyFromISR() with the addition that it also returns the subject task's prior notification value (the notification value at the time the function is called rather than at the time the function returns) in the additional pulPreviousNotifyValue parameter. xTaskNotifyWait(ulBitsToClearOnEntry, ulBitsToClearOnExit, pulNotificationValue, xTicksToWait) xTaskNotifyWaitIndexed(uxIndexToWaitOn, ulBitsToClearOnEntry, ulBitsToClearOnExit, pulNotificationValue, xTicksToWait) xTaskNotifyGiveIndexed(xTaskToNotify, uxIndexToNotify) Sends a direct to task notification to a particular index in the target task's notification array in a manner similar to giving a counting semaphore. See https://www.FreeRTOS.org/RTOS-task-notifications.html for more details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these macros to be available. Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of the task's notification values. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. xTaskNotifyGiveIndexed() is a helper macro intended for use when task notifications are used as light weight and faster binary or counting semaphore equivalents. Actual FreeRTOS semaphores are given using the xSemaphoreGive() API function, the equivalent action that instead uses a task notification is xTaskNotifyGiveIndexed(). When task notifications are being used as a binary or counting semaphore equivalent then the task being notified should wait for the notification using the ulTaskNotifyTakeIndexed() API function rather than the xTaskNotifyWaitIndexed() API function. NOTE Each notification within the array operates independently - a task can only block on one notification within the array at a time and will not be unblocked by a notification sent to any other array index. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. xTaskNotifyGive() is the original API function, and remains backward compatible by always operating on the notification value at index 0 in the array. Calling xTaskNotifyGive() is equivalent to calling xTaskNotifyGiveIndexed() with the uxIndexToNotify parameter set to 0. Parameters xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyGive() does not have this parameter and always sends notifications to index 0. xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyGive() does not have this parameter and always sends notifications to index 0. xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). Returns xTaskNotifyGive() is a macro that calls xTaskNotify() with the eAction parameter set to eIncrement - so pdPASS is always returned. Parameters xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyGive() does not have this parameter and always sends notifications to index 0. Returns xTaskNotifyGive() is a macro that calls xTaskNotify() with the eAction parameter set to eIncrement - so pdPASS is always returned. vTaskNotifyGiveFromISR(xTaskToNotify, pxHigherPriorityTaskWoken) vTaskNotifyGiveIndexedFromISR(xTaskToNotify, uxIndexToNotify, pxHigherPriorityTaskWoken) ulTaskNotifyTakeIndexed(uxIndexToWaitOn, xClearCountOnExit, xTicksToWait) Waits for a direct to task notification on a particular index in the calling task's notification array in a manner similar to taking a counting semaphore. See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this function to be available. Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of the task's notification values. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. ulTaskNotifyTakeIndexed() is intended for use when a task notification is used as a faster and lighter weight binary or counting semaphore alternative. Actual FreeRTOS semaphores are taken using the xSemaphoreTake() API function, the equivalent action that instead uses a task notification is ulTaskNotifyTakeIndexed(). When a task is using its notification value as a binary or counting semaphore other tasks should send notifications to it using the xTaskNotifyGiveIndexed() macro, or xTaskNotifyIndex() function with the eAction parameter set to eIncrement. ulTaskNotifyTakeIndexed() can either clear the task's notification value at the array index specified by the uxIndexToWaitOn parameter to zero on exit, in which case the notification value acts like a binary semaphore, or decrement the notification value on exit, in which case the notification value acts like a counting semaphore. A task can use ulTaskNotifyTakeIndexed() to [optionally] block to wait for a notification. The task does not consume any CPU time while it is in the Blocked state. Where as xTaskNotifyWaitIndexed() will return when a notification is pending, ulTaskNotifyTakeIndexed() will return when the task's notification value is not zero. NOTE Each notification within the array operates independently - a task can only block on one notification within the array at a time and will not be unblocked by a notification sent to any other array index. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. ulTaskNotifyTake() is the original API function, and remains backward compatible by always operating on the notification value at index 0 in the array. Calling ulTaskNotifyTake() is equivalent to calling ulTaskNotifyTakeIndexed() with the uxIndexToWaitOn parameter set to 0. Parameters uxIndexToWaitOn -- The index within the calling task's array of notification values on which the calling task will wait for a notification to be non-zero. uxIndexToWaitOn must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyTake() does not have this parameter and always waits for notifications on index 0. xClearCountOnExit -- if xClearCountOnExit is pdFALSE then the task's notification value is decremented when the function exits. In this way the notification value acts like a counting semaphore. If xClearCountOnExit is not pdFALSE then the task's notification value is cleared to zero when the function exits. In this way the notification value acts like a binary semaphore. xTicksToWait -- The maximum amount of time that the task should wait in the Blocked state for the task's notification value to be greater than zero, should the count not already be greater than zero when ulTaskNotifyTake() was called. The task will not consume any processing time while it is in the Blocked state. This is specified in kernel ticks, the macro pdMS_TO_TICKS( value_in_ms ) can be used to convert a time specified in milliseconds to a time specified in ticks. uxIndexToWaitOn -- The index within the calling task's array of notification values on which the calling task will wait for a notification to be non-zero. uxIndexToWaitOn must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyTake() does not have this parameter and always waits for notifications on index 0. xClearCountOnExit -- if xClearCountOnExit is pdFALSE then the task's notification value is decremented when the function exits. In this way the notification value acts like a counting semaphore. If xClearCountOnExit is not pdFALSE then the task's notification value is cleared to zero when the function exits. In this way the notification value acts like a binary semaphore. xTicksToWait -- The maximum amount of time that the task should wait in the Blocked state for the task's notification value to be greater than zero, should the count not already be greater than zero when ulTaskNotifyTake() was called. The task will not consume any processing time while it is in the Blocked state. This is specified in kernel ticks, the macro pdMS_TO_TICKS( value_in_ms ) can be used to convert a time specified in milliseconds to a time specified in ticks. uxIndexToWaitOn -- The index within the calling task's array of notification values on which the calling task will wait for a notification to be non-zero. uxIndexToWaitOn must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyTake() does not have this parameter and always waits for notifications on index 0. Returns The task's notification count before it is either cleared to zero or decremented (see the xClearCountOnExit parameter). Parameters uxIndexToWaitOn -- The index within the calling task's array of notification values on which the calling task will wait for a notification to be non-zero. uxIndexToWaitOn must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyTake() does not have this parameter and always waits for notifications on index 0. xClearCountOnExit -- if xClearCountOnExit is pdFALSE then the task's notification value is decremented when the function exits. In this way the notification value acts like a counting semaphore. If xClearCountOnExit is not pdFALSE then the task's notification value is cleared to zero when the function exits. In this way the notification value acts like a binary semaphore. xTicksToWait -- The maximum amount of time that the task should wait in the Blocked state for the task's notification value to be greater than zero, should the count not already be greater than zero when ulTaskNotifyTake() was called. The task will not consume any processing time while it is in the Blocked state. This is specified in kernel ticks, the macro pdMS_TO_TICKS( value_in_ms ) can be used to convert a time specified in milliseconds to a time specified in ticks. Returns The task's notification count before it is either cleared to zero or decremented (see the xClearCountOnExit parameter). xTaskNotifyStateClear(xTask) xTaskNotifyStateClearIndexed(xTask, uxIndexToClear) ulTaskNotifyValueClear(xTask, ulBitsToClear) ulTaskNotifyValueClearIndexed(xTask, uxIndexToClear, ulBitsToClear) Type Definitions typedef struct tskTaskControlBlock *TaskHandle_t typedef BaseType_t (*TaskHookFunction_t)(void*) Defines the prototype to which the application task hook function must conform. typedef struct xTASK_STATUS TaskStatus_t Used with the uxTaskGetSystemState() function to return the state of each task in the system. Enumerations enum eTaskState Task states returned by eTaskGetState. Values: enumerator eRunning A task is querying the state of itself, so must be running. enumerator eRunning A task is querying the state of itself, so must be running. enumerator eReady The task being queried is in a ready or pending ready list. enumerator eReady The task being queried is in a ready or pending ready list. enumerator eBlocked The task being queried is in the Blocked state. enumerator eBlocked The task being queried is in the Blocked state. enumerator eSuspended The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. enumerator eSuspended The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. enumerator eDeleted The task being queried has been deleted, but its TCB has not yet been freed. enumerator eDeleted The task being queried has been deleted, but its TCB has not yet been freed. enumerator eInvalid Used as an 'invalid state' value. enumerator eInvalid Used as an 'invalid state' value. enumerator eRunning enum eNotifyAction Actions that can be performed when vTaskNotify() is called. Values: enumerator eNoAction Notify the task without updating its notify value. enumerator eNoAction Notify the task without updating its notify value. enumerator eSetBits Set bits in the task's notification value. enumerator eSetBits Set bits in the task's notification value. enumerator eIncrement Increment the task's notification value. enumerator eIncrement Increment the task's notification value. enumerator eSetValueWithOverwrite Set the task's notification value to a specific value even if the previous value has not yet been read by the task. enumerator eSetValueWithOverwrite Set the task's notification value to a specific value even if the previous value has not yet been read by the task. enumerator eSetValueWithoutOverwrite Set the task's notification value if the previous value has been read by the task. enumerator eSetValueWithoutOverwrite Set the task's notification value if the previous value has been read by the task. enumerator eNoAction enum eSleepModeStatus Possible return values for eTaskConfirmSleepModeStatus(). Values: enumerator eAbortSleep A task has been made ready or a context switch pended since portSUPPRESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. enumerator eAbortSleep A task has been made ready or a context switch pended since portSUPPRESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. enumerator eStandardSleep Enter a sleep mode that will not last any longer than the expected idle time. enumerator eStandardSleep Enter a sleep mode that will not last any longer than the expected idle time. enumerator eAbortSleep Queue API Header File components/freertos/FreeRTOS-Kernel/include/freertos/queue.h This header file can be included with: #include "freertos/queue.h" Functions BaseType_t xQueueGenericSend(QueueHandle_t xQueue, const void *const pvItemToQueue, TickType_t xTicksToWait, const BaseType_t xCopyPosition) It is preferred that the macros xQueueSend(), xQueueSendToFront() and xQueueSendToBack() are used in place of calling this function directly. Post an item on a queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueSendFromISR () for an alternative which may be used in an ISR. Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; uint32_t ulVar = 10UL; void vATask( void *pvParameters ) { QueueHandle_t xQueue1, xQueue2; struct AMessage *pxMessage; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); // ... if( xQueue1 != 0 ) { // Send an uint32_t. Wait for 10 ticks for space to become // available if necessary. if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10, queueSEND_TO_BACK ) != pdPASS ) { // Failed to post the message, even after 10 ticks. } } if( xQueue2 != 0 ) { // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0, queueSEND_TO_BACK ); } // ... Rest of task code. } Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xCopyPosition -- Can take the value queueSEND_TO_BACK to place the item at the back of the queue, or queueSEND_TO_FRONT to place the item at the front of the queue (for high priority messages). xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xCopyPosition -- Can take the value queueSEND_TO_BACK to place the item at the back of the queue, or queueSEND_TO_FRONT to place the item at the front of the queue (for high priority messages). xQueue -- The handle to the queue on which the item is to be posted. Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xCopyPosition -- Can take the value queueSEND_TO_BACK to place the item at the back of the queue, or queueSEND_TO_FRONT to place the item at the front of the queue (for high priority messages). Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. BaseType_t xQueuePeek(QueueHandle_t xQueue, void *const pvBuffer, TickType_t xTicksToWait) Receive an item from a queue without removing the item from the queue. The item is received by copy so a buffer of adequate size must be provided. The number of bytes copied into the buffer was defined when the queue was created. Successfully received items remain on the queue so will be returned again by the next call, or a call to xQueueReceive(). This macro must not be used in an interrupt service routine. See xQueuePeekFromISR() for an alternative that can be called from an interrupt service routine. Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; QueueHandle_t xQueue; // Task to create a queue and post a value. void vATask( void *pvParameters ) { struct AMessage *pxMessage; // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) ); if( xQueue == 0 ) { // Failed to create the queue. } // ... // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 ); // ... Rest of task code. } // Task to peek the data from the queue. void vADifferentTask( void *pvParameters ) { struct AMessage *pxRxedMessage; if( xQueue != 0 ) { // Peek a message on the created queue. Block for 10 ticks if a // message is not immediately available. if( xQueuePeek( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) ) { // pcRxedMessage now points to the struct AMessage variable posted // by vATask, but the item still remains on the queue. } } // ... Rest of task code. } Parameters xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. xTicksToWait -- The maximum amount of time the task should block waiting for an item to receive should the queue be empty at the time of the call. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xQueuePeek() will return immediately if xTicksToWait is 0 and the queue is empty. xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. xTicksToWait -- The maximum amount of time the task should block waiting for an item to receive should the queue be empty at the time of the call. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xQueuePeek() will return immediately if xTicksToWait is 0 and the queue is empty. xQueue -- The handle to the queue from which the item is to be received. Returns pdTRUE if an item was successfully received from the queue, otherwise pdFALSE. Parameters xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. xTicksToWait -- The maximum amount of time the task should block waiting for an item to receive should the queue be empty at the time of the call. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xQueuePeek() will return immediately if xTicksToWait is 0 and the queue is empty. Returns pdTRUE if an item was successfully received from the queue, otherwise pdFALSE. BaseType_t xQueuePeekFromISR(QueueHandle_t xQueue, void *const pvBuffer) A version of xQueuePeek() that can be called from an interrupt service routine (ISR). Receive an item from a queue without removing the item from the queue. The item is received by copy so a buffer of adequate size must be provided. The number of bytes copied into the buffer was defined when the queue was created. Successfully received items remain on the queue so will be returned again by the next call, or a call to xQueueReceive(). Parameters xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. xQueue -- The handle to the queue from which the item is to be received. Returns pdTRUE if an item was successfully received from the queue, otherwise pdFALSE. Parameters xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. Returns pdTRUE if an item was successfully received from the queue, otherwise pdFALSE. BaseType_t xQueueReceive(QueueHandle_t xQueue, void *const pvBuffer, TickType_t xTicksToWait) Receive an item from a queue. The item is received by copy so a buffer of adequate size must be provided. The number of bytes copied into the buffer was defined when the queue was created. Successfully received items are removed from the queue. This function must not be used in an interrupt service routine. See xQueueReceiveFromISR for an alternative that can. Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; QueueHandle_t xQueue; // Task to create a queue and post a value. void vATask( void *pvParameters ) { struct AMessage *pxMessage; // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) ); if( xQueue == 0 ) { // Failed to create the queue. } // ... // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 ); // ... Rest of task code. } // Task to receive from the queue. void vADifferentTask( void *pvParameters ) { struct AMessage *pxRxedMessage; if( xQueue != 0 ) { // Receive a message on the created queue. Block for 10 ticks if a // message is not immediately available. if( xQueueReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) ) { // pcRxedMessage now points to the struct AMessage variable posted // by vATask. } } // ... Rest of task code. } Parameters xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. xTicksToWait -- The maximum amount of time the task should block waiting for an item to receive should the queue be empty at the time of the call. xQueueReceive() will return immediately if xTicksToWait is zero and the queue is empty. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. xTicksToWait -- The maximum amount of time the task should block waiting for an item to receive should the queue be empty at the time of the call. xQueueReceive() will return immediately if xTicksToWait is zero and the queue is empty. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xQueue -- The handle to the queue from which the item is to be received. Returns pdTRUE if an item was successfully received from the queue, otherwise pdFALSE. Parameters xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. xTicksToWait -- The maximum amount of time the task should block waiting for an item to receive should the queue be empty at the time of the call. xQueueReceive() will return immediately if xTicksToWait is zero and the queue is empty. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. Returns pdTRUE if an item was successfully received from the queue, otherwise pdFALSE. UBaseType_t uxQueueMessagesWaiting(const QueueHandle_t xQueue) Return the number of messages stored in a queue. Parameters xQueue -- A handle to the queue being queried. Returns The number of messages available in the queue. Parameters xQueue -- A handle to the queue being queried. Returns The number of messages available in the queue. UBaseType_t uxQueueSpacesAvailable(const QueueHandle_t xQueue) Return the number of free spaces available in a queue. This is equal to the number of items that can be sent to the queue before the queue becomes full if no items are removed. Parameters xQueue -- A handle to the queue being queried. Returns The number of spaces available in the queue. Parameters xQueue -- A handle to the queue being queried. Returns The number of spaces available in the queue. void vQueueDelete(QueueHandle_t xQueue) Delete a queue - freeing all the memory allocated for storing of items placed on the queue. Parameters xQueue -- A handle to the queue to be deleted. Parameters xQueue -- A handle to the queue to be deleted. BaseType_t xQueueGenericSendFromISR(QueueHandle_t xQueue, const void *const pvItemToQueue, BaseType_t *const pxHigherPriorityTaskWoken, const BaseType_t xCopyPosition) It is preferred that the macros xQueueSendFromISR(), xQueueSendToFrontFromISR() and xQueueSendToBackFromISR() be used in place of calling this function directly. xQueueGiveFromISR() is an equivalent for use by semaphores that don't actually copy any data. Post an item on a queue. It is safe to use this function from within an interrupt service routine. Items are queued by copy not reference so it is preferable to only queue small items, especially when called from an ISR. In most cases it would be preferable to store a pointer to the item being queued. Example usage for buffered IO (where the ISR can obtain more than one value per call): void vBufferISR( void ) { char cIn; BaseType_t xHigherPriorityTaskWokenByPost; // We have not woken a task at the start of the ISR. xHigherPriorityTaskWokenByPost = pdFALSE; // Loop until the buffer is empty. do { // Obtain a byte from the buffer. cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); // Post each byte. xQueueGenericSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWokenByPost, queueSEND_TO_BACK ); } while( portINPUT_BYTE( BUFFER_COUNT ) ); // Now the buffer is empty we can switch context if necessary. Note that the // name of the yield function required is port specific. if( xHigherPriorityTaskWokenByPost ) { portYIELD_FROM_ISR(); } } Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueGenericSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueGenericSendFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xCopyPosition -- Can take the value queueSEND_TO_BACK to place the item at the back of the queue, or queueSEND_TO_FRONT to place the item at the front of the queue (for high priority messages). xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueGenericSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueGenericSendFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xCopyPosition -- Can take the value queueSEND_TO_BACK to place the item at the back of the queue, or queueSEND_TO_FRONT to place the item at the front of the queue (for high priority messages). xQueue -- The handle to the queue on which the item is to be posted. Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL. Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueGenericSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueGenericSendFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xCopyPosition -- Can take the value queueSEND_TO_BACK to place the item at the back of the queue, or queueSEND_TO_FRONT to place the item at the front of the queue (for high priority messages). Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL. BaseType_t xQueueGiveFromISR(QueueHandle_t xQueue, BaseType_t *const pxHigherPriorityTaskWoken) BaseType_t xQueueReceiveFromISR(QueueHandle_t xQueue, void *const pvBuffer, BaseType_t *const pxHigherPriorityTaskWoken) Receive an item from a queue. It is safe to use this function from within an interrupt service routine. Example usage: QueueHandle_t xQueue; // Function to create a queue and post some values. void vAFunction( void *pvParameters ) { char cValueToPost; const TickType_t xTicksToWait = ( TickType_t )0xff; // Create a queue capable of containing 10 characters. xQueue = xQueueCreate( 10, sizeof( char ) ); if( xQueue == 0 ) { // Failed to create the queue. } // ... // Post some characters that will be used within an ISR. If the queue // is full then this task will block for xTicksToWait ticks. cValueToPost = 'a'; xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); cValueToPost = 'b'; xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); // ... keep posting characters ... this task may block when the queue // becomes full. cValueToPost = 'c'; xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); } // ISR that outputs all the characters received on the queue. void vISR_Routine( void ) { BaseType_t xTaskWokenByReceive = pdFALSE; char cRxedChar; while( xQueueReceiveFromISR( xQueue, ( void * ) &cRxedChar, &xTaskWokenByReceive) ) { // A character was received. Output the character now. vOutputCharacter( cRxedChar ); // If removing the character from the queue woke the task that was // posting onto the queue xTaskWokenByReceive will have been set to // pdTRUE. No matter how many times this loop iterates only one // task will be woken. } if( xTaskWokenByReceive != ( char ) pdFALSE; { taskYIELD (); } } Parameters xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. pxHigherPriorityTaskWoken -- A task may be blocked waiting for space to become available on the queue. If xQueueReceiveFromISR causes such a task to unblock *pxTaskWoken will get set to pdTRUE, otherwise *pxTaskWoken will remain unchanged. xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. pxHigherPriorityTaskWoken -- A task may be blocked waiting for space to become available on the queue. If xQueueReceiveFromISR causes such a task to unblock *pxTaskWoken will get set to pdTRUE, otherwise *pxTaskWoken will remain unchanged. xQueue -- The handle to the queue from which the item is to be received. Returns pdTRUE if an item was successfully received from the queue, otherwise pdFALSE. Parameters xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. pxHigherPriorityTaskWoken -- A task may be blocked waiting for space to become available on the queue. If xQueueReceiveFromISR causes such a task to unblock *pxTaskWoken will get set to pdTRUE, otherwise *pxTaskWoken will remain unchanged. Returns pdTRUE if an item was successfully received from the queue, otherwise pdFALSE. BaseType_t xQueueIsQueueEmptyFromISR(const QueueHandle_t xQueue) Queries a queue to determine if the queue is empty. This function should only be used in an ISR. Parameters xQueue -- The handle of the queue being queried Returns pdFALSE if the queue is not empty, or pdTRUE if the queue is empty. Parameters xQueue -- The handle of the queue being queried Returns pdFALSE if the queue is not empty, or pdTRUE if the queue is empty. BaseType_t xQueueIsQueueFullFromISR(const QueueHandle_t xQueue) Queries a queue to determine if the queue is full. This function should only be used in an ISR. Parameters xQueue -- The handle of the queue being queried Returns pdFALSE if the queue is not full, or pdTRUE if the queue is full. Parameters xQueue -- The handle of the queue being queried Returns pdFALSE if the queue is not full, or pdTRUE if the queue is full. UBaseType_t uxQueueMessagesWaitingFromISR(const QueueHandle_t xQueue) A version of uxQueueMessagesWaiting() that can be called from an ISR. Return the number of messages stored in a queue. Parameters xQueue -- A handle to the queue being queried. Returns The number of messages available in the queue. Parameters xQueue -- A handle to the queue being queried. Returns The number of messages available in the queue. void vQueueAddToRegistry(QueueHandle_t xQueue, const char *pcQueueName) The registry is provided as a means for kernel aware debuggers to locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add a queue, semaphore or mutex handle to the registry if you want the handle to be available to a kernel aware debugger. If you are not using a kernel aware debugger then this function can be ignored. configQUEUE_REGISTRY_SIZE defines the maximum number of handles the registry can hold. configQUEUE_REGISTRY_SIZE must be greater than 0 within FreeRTOSConfig.h for the registry to be available. Its value does not affect the number of queues, semaphores and mutexes that can be created - just the number that the registry can hold. If vQueueAddToRegistry is called more than once with the same xQueue parameter, the registry will store the pcQueueName parameter from the most recent call to vQueueAddToRegistry. Parameters xQueue -- The handle of the queue being added to the registry. This is the handle returned by a call to xQueueCreate(). Semaphore and mutex handles can also be passed in here. pcQueueName -- The name to be associated with the handle. This is the name that the kernel aware debugger will display. The queue registry only stores a pointer to the string - so the string must be persistent (global or preferably in ROM/Flash), not on the stack. xQueue -- The handle of the queue being added to the registry. This is the handle returned by a call to xQueueCreate(). Semaphore and mutex handles can also be passed in here. pcQueueName -- The name to be associated with the handle. This is the name that the kernel aware debugger will display. The queue registry only stores a pointer to the string - so the string must be persistent (global or preferably in ROM/Flash), not on the stack. xQueue -- The handle of the queue being added to the registry. This is the handle returned by a call to xQueueCreate(). Semaphore and mutex handles can also be passed in here. Parameters xQueue -- The handle of the queue being added to the registry. This is the handle returned by a call to xQueueCreate(). Semaphore and mutex handles can also be passed in here. pcQueueName -- The name to be associated with the handle. This is the name that the kernel aware debugger will display. The queue registry only stores a pointer to the string - so the string must be persistent (global or preferably in ROM/Flash), not on the stack. void vQueueUnregisterQueue(QueueHandle_t xQueue) The registry is provided as a means for kernel aware debuggers to locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add a queue, semaphore or mutex handle to the registry if you want the handle to be available to a kernel aware debugger, and vQueueUnregisterQueue() to remove the queue, semaphore or mutex from the register. If you are not using a kernel aware debugger then this function can be ignored. Parameters xQueue -- The handle of the queue being removed from the registry. Parameters xQueue -- The handle of the queue being removed from the registry. const char *pcQueueGetName(QueueHandle_t xQueue) The queue registry is provided as a means for kernel aware debuggers to locate queues, semaphores and mutexes. Call pcQueueGetName() to look up and return the name of a queue in the queue registry from the queue's handle. Parameters xQueue -- The handle of the queue the name of which will be returned. Returns If the queue is in the registry then a pointer to the name of the queue is returned. If the queue is not in the registry then NULL is returned. Parameters xQueue -- The handle of the queue the name of which will be returned. Returns If the queue is in the registry then a pointer to the name of the queue is returned. If the queue is not in the registry then NULL is returned. QueueSetHandle_t xQueueCreateSet(const UBaseType_t uxEventQueueLength) Queue sets provide a mechanism to allow a task to block (pend) on a read operation from multiple queues or semaphores simultaneously. See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this function. A queue set must be explicitly created using a call to xQueueCreateSet() before it can be used. Once created, standard FreeRTOS queues and semaphores can be added to the set using calls to xQueueAddToSet(). xQueueSelectFromSet() is then used to determine which, if any, of the queues or semaphores contained in the set is in a state where a queue read or semaphore take operation would be successful. Note 1: See the documentation on https://www.FreeRTOS.org/RTOS-queue-sets.html for reasons why queue sets are very rarely needed in practice as there are simpler methods of blocking on multiple objects. Note 2: Blocking on a queue set that contains a mutex will not cause the mutex holder to inherit the priority of the blocked task. Note 3: An additional 4 bytes of RAM is required for each space in a every queue added to a queue set. Therefore counting semaphores that have a high maximum count value should not be added to a queue set. Note 4: A receive (in the case of a queue) or take (in the case of a semaphore) operation must not be performed on a member of a queue set unless a call to xQueueSelectFromSet() has first returned a handle to that set member. Parameters uxEventQueueLength -- Queue sets store events that occur on the queues and semaphores contained in the set. uxEventQueueLength specifies the maximum number of events that can be queued at once. To be absolutely certain that events are not lost uxEventQueueLength should be set to the total sum of the length of the queues added to the set, where binary semaphores and mutexes have a length of 1, and counting semaphores have a length set by their maximum count value. Examples: If a queue set is to hold a queue of length 5, another queue of length 12, and a binary semaphore, then uxEventQueueLength should be set to (5 + 12 + 1), or 18. If a queue set is to hold three binary semaphores then uxEventQueueLength should be set to (1 + 1 + 1 ), or 3. If a queue set is to hold a counting semaphore that has a maximum count of 5, and a counting semaphore that has a maximum count of 3, then uxEventQueueLength should be set to (5 + 3), or 8. If a queue set is to hold a queue of length 5, another queue of length 12, and a binary semaphore, then uxEventQueueLength should be set to (5 + 12 + 1), or 18. If a queue set is to hold three binary semaphores then uxEventQueueLength should be set to (1 + 1 + 1 ), or 3. If a queue set is to hold a counting semaphore that has a maximum count of 5, and a counting semaphore that has a maximum count of 3, then uxEventQueueLength should be set to (5 + 3), or 8. If a queue set is to hold a queue of length 5, another queue of length 12, and a binary semaphore, then uxEventQueueLength should be set to (5 + 12 + 1), or 18. Returns If the queue set is created successfully then a handle to the created queue set is returned. Otherwise NULL is returned. Parameters uxEventQueueLength -- Queue sets store events that occur on the queues and semaphores contained in the set. uxEventQueueLength specifies the maximum number of events that can be queued at once. To be absolutely certain that events are not lost uxEventQueueLength should be set to the total sum of the length of the queues added to the set, where binary semaphores and mutexes have a length of 1, and counting semaphores have a length set by their maximum count value. Examples: If a queue set is to hold a queue of length 5, another queue of length 12, and a binary semaphore, then uxEventQueueLength should be set to (5 + 12 + 1), or 18. If a queue set is to hold three binary semaphores then uxEventQueueLength should be set to (1 + 1 + 1 ), or 3. If a queue set is to hold a counting semaphore that has a maximum count of 5, and a counting semaphore that has a maximum count of 3, then uxEventQueueLength should be set to (5 + 3), or 8. Returns If the queue set is created successfully then a handle to the created queue set is returned. Otherwise NULL is returned. BaseType_t xQueueAddToSet(QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet) Adds a queue or semaphore to a queue set that was previously created by a call to xQueueCreateSet(). See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this function. Note 1: A receive (in the case of a queue) or take (in the case of a semaphore) operation must not be performed on a member of a queue set unless a call to xQueueSelectFromSet() has first returned a handle to that set member. Parameters xQueueOrSemaphore -- The handle of the queue or semaphore being added to the queue set (cast to an QueueSetMemberHandle_t type). xQueueSet -- The handle of the queue set to which the queue or semaphore is being added. xQueueOrSemaphore -- The handle of the queue or semaphore being added to the queue set (cast to an QueueSetMemberHandle_t type). xQueueSet -- The handle of the queue set to which the queue or semaphore is being added. xQueueOrSemaphore -- The handle of the queue or semaphore being added to the queue set (cast to an QueueSetMemberHandle_t type). Returns If the queue or semaphore was successfully added to the queue set then pdPASS is returned. If the queue could not be successfully added to the queue set because it is already a member of a different queue set then pdFAIL is returned. Parameters xQueueOrSemaphore -- The handle of the queue or semaphore being added to the queue set (cast to an QueueSetMemberHandle_t type). xQueueSet -- The handle of the queue set to which the queue or semaphore is being added. Returns If the queue or semaphore was successfully added to the queue set then pdPASS is returned. If the queue could not be successfully added to the queue set because it is already a member of a different queue set then pdFAIL is returned. BaseType_t xQueueRemoveFromSet(QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet) Removes a queue or semaphore from a queue set. A queue or semaphore can only be removed from a set if the queue or semaphore is empty. See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this function. Parameters xQueueOrSemaphore -- The handle of the queue or semaphore being removed from the queue set (cast to an QueueSetMemberHandle_t type). xQueueSet -- The handle of the queue set in which the queue or semaphore is included. xQueueOrSemaphore -- The handle of the queue or semaphore being removed from the queue set (cast to an QueueSetMemberHandle_t type). xQueueSet -- The handle of the queue set in which the queue or semaphore is included. xQueueOrSemaphore -- The handle of the queue or semaphore being removed from the queue set (cast to an QueueSetMemberHandle_t type). Returns If the queue or semaphore was successfully removed from the queue set then pdPASS is returned. If the queue was not in the queue set, or the queue (or semaphore) was not empty, then pdFAIL is returned. Parameters xQueueOrSemaphore -- The handle of the queue or semaphore being removed from the queue set (cast to an QueueSetMemberHandle_t type). xQueueSet -- The handle of the queue set in which the queue or semaphore is included. Returns If the queue or semaphore was successfully removed from the queue set then pdPASS is returned. If the queue was not in the queue set, or the queue (or semaphore) was not empty, then pdFAIL is returned. QueueSetMemberHandle_t xQueueSelectFromSet(QueueSetHandle_t xQueueSet, const TickType_t xTicksToWait) xQueueSelectFromSet() selects from the members of a queue set a queue or semaphore that either contains data (in the case of a queue) or is available to take (in the case of a semaphore). xQueueSelectFromSet() effectively allows a task to block (pend) on a read operation on all the queues and semaphores in a queue set simultaneously. See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this function. Note 1: See the documentation on https://www.FreeRTOS.org/RTOS-queue-sets.html for reasons why queue sets are very rarely needed in practice as there are simpler methods of blocking on multiple objects. Note 2: Blocking on a queue set that contains a mutex will not cause the mutex holder to inherit the priority of the blocked task. Note 3: A receive (in the case of a queue) or take (in the case of a semaphore) operation must not be performed on a member of a queue set unless a call to xQueueSelectFromSet() has first returned a handle to that set member. Parameters xQueueSet -- The queue set on which the task will (potentially) block. xTicksToWait -- The maximum time, in ticks, that the calling task will remain in the Blocked state (with other tasks executing) to wait for a member of the queue set to be ready for a successful queue read or semaphore take operation. xQueueSet -- The queue set on which the task will (potentially) block. xTicksToWait -- The maximum time, in ticks, that the calling task will remain in the Blocked state (with other tasks executing) to wait for a member of the queue set to be ready for a successful queue read or semaphore take operation. xQueueSet -- The queue set on which the task will (potentially) block. Returns xQueueSelectFromSet() will return the handle of a queue (cast to a QueueSetMemberHandle_t type) contained in the queue set that contains data, or the handle of a semaphore (cast to a QueueSetMemberHandle_t type) contained in the queue set that is available, or NULL if no such queue or semaphore exists before before the specified block time expires. Parameters xQueueSet -- The queue set on which the task will (potentially) block. xTicksToWait -- The maximum time, in ticks, that the calling task will remain in the Blocked state (with other tasks executing) to wait for a member of the queue set to be ready for a successful queue read or semaphore take operation. Returns xQueueSelectFromSet() will return the handle of a queue (cast to a QueueSetMemberHandle_t type) contained in the queue set that contains data, or the handle of a semaphore (cast to a QueueSetMemberHandle_t type) contained in the queue set that is available, or NULL if no such queue or semaphore exists before before the specified block time expires. QueueSetMemberHandle_t xQueueSelectFromSetFromISR(QueueSetHandle_t xQueueSet) A version of xQueueSelectFromSet() that can be used from an ISR. Macros xQueueCreate(uxQueueLength, uxItemSize) Creates a new queue instance, and returns a handle by which the new queue can be referenced. Internally, within the FreeRTOS implementation, queues use two blocks of memory. The first block is used to hold the queue's data structures. The second block is used to hold items placed into the queue. If a queue is created using xQueueCreate() then both blocks of memory are automatically dynamically allocated inside the xQueueCreate() function. (see https://www.FreeRTOS.org/a00111.html). If a queue is created using xQueueCreateStatic() then the application writer must provide the memory that will get used by the queue. xQueueCreateStatic() therefore allows a queue to be created without using any dynamic memory allocation. https://www.FreeRTOS.org/Embedded-RTOS-Queues.html Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; }; void vATask( void *pvParameters ) { QueueHandle_t xQueue1, xQueue2; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); if( xQueue1 == 0 ) { // Queue was not created and must not be used. } // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); if( xQueue2 == 0 ) { // Queue was not created and must not be used. } // ... Rest of task code. } Parameters uxQueueLength -- The maximum number of items that the queue can contain. uxItemSize -- The number of bytes each item in the queue will require. Items are queued by copy, not by reference, so this is the number of bytes that will be copied for each posted item. Each item on the queue must be the same size. uxQueueLength -- The maximum number of items that the queue can contain. uxItemSize -- The number of bytes each item in the queue will require. Items are queued by copy, not by reference, so this is the number of bytes that will be copied for each posted item. Each item on the queue must be the same size. uxQueueLength -- The maximum number of items that the queue can contain. Returns If the queue is successfully create then a handle to the newly created queue is returned. If the queue cannot be created then 0 is returned. Parameters uxQueueLength -- The maximum number of items that the queue can contain. uxItemSize -- The number of bytes each item in the queue will require. Items are queued by copy, not by reference, so this is the number of bytes that will be copied for each posted item. Each item on the queue must be the same size. Returns If the queue is successfully create then a handle to the newly created queue is returned. If the queue cannot be created then 0 is returned. xQueueCreateStatic(uxQueueLength, uxItemSize, pucQueueStorage, pxQueueBuffer) Creates a new queue instance, and returns a handle by which the new queue can be referenced. Internally, within the FreeRTOS implementation, queues use two blocks of memory. The first block is used to hold the queue's data structures. The second block is used to hold items placed into the queue. If a queue is created using xQueueCreate() then both blocks of memory are automatically dynamically allocated inside the xQueueCreate() function. (see https://www.FreeRTOS.org/a00111.html). If a queue is created using xQueueCreateStatic() then the application writer must provide the memory that will get used by the queue. xQueueCreateStatic() therefore allows a queue to be created without using any dynamic memory allocation. https://www.FreeRTOS.org/Embedded-RTOS-Queues.html Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; }; #define QUEUE_LENGTH 10 #define ITEM_SIZE sizeof( uint32_t ) // xQueueBuffer will hold the queue structure. StaticQueue_t xQueueBuffer; // ucQueueStorage will hold the items posted to the queue. Must be at least // [(queue length) * ( queue item size)] bytes long. uint8_t ucQueueStorage[ QUEUE_LENGTH * ITEM_SIZE ]; void vATask( void *pvParameters ) { QueueHandle_t xQueue1; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( QUEUE_LENGTH, // The number of items the queue can hold. ITEM_SIZE // The size of each item in the queue &( ucQueueStorage[ 0 ] ), // The buffer that will hold the items in the queue. &xQueueBuffer ); // The buffer that will hold the queue structure. // The queue is guaranteed to be created successfully as no dynamic memory // allocation is used. Therefore xQueue1 is now a handle to a valid queue. // ... Rest of task code. } Parameters uxQueueLength -- The maximum number of items that the queue can contain. uxItemSize -- The number of bytes each item in the queue will require. Items are queued by copy, not by reference, so this is the number of bytes that will be copied for each posted item. Each item on the queue must be the same size. pucQueueStorage -- If uxItemSize is not zero then pucQueueStorage must point to a uint8_t array that is at least large enough to hold the maximum number of items that can be in the queue at any one time - which is ( uxQueueLength * uxItemsSize ) bytes. If uxItemSize is zero then pucQueueStorage can be NULL. pxQueueBuffer -- Must point to a variable of type StaticQueue_t, which will be used to hold the queue's data structure. uxQueueLength -- The maximum number of items that the queue can contain. uxItemSize -- The number of bytes each item in the queue will require. Items are queued by copy, not by reference, so this is the number of bytes that will be copied for each posted item. Each item on the queue must be the same size. pucQueueStorage -- If uxItemSize is not zero then pucQueueStorage must point to a uint8_t array that is at least large enough to hold the maximum number of items that can be in the queue at any one time - which is ( uxQueueLength * uxItemsSize ) bytes. If uxItemSize is zero then pucQueueStorage can be NULL. pxQueueBuffer -- Must point to a variable of type StaticQueue_t, which will be used to hold the queue's data structure. uxQueueLength -- The maximum number of items that the queue can contain. Returns If the queue is created then a handle to the created queue is returned. If pxQueueBuffer is NULL then NULL is returned. Parameters uxQueueLength -- The maximum number of items that the queue can contain. uxItemSize -- The number of bytes each item in the queue will require. Items are queued by copy, not by reference, so this is the number of bytes that will be copied for each posted item. Each item on the queue must be the same size. pucQueueStorage -- If uxItemSize is not zero then pucQueueStorage must point to a uint8_t array that is at least large enough to hold the maximum number of items that can be in the queue at any one time - which is ( uxQueueLength * uxItemsSize ) bytes. If uxItemSize is zero then pucQueueStorage can be NULL. pxQueueBuffer -- Must point to a variable of type StaticQueue_t, which will be used to hold the queue's data structure. Returns If the queue is created then a handle to the created queue is returned. If pxQueueBuffer is NULL then NULL is returned. xQueueGetStaticBuffers(xQueue, ppucQueueStorage, ppxStaticQueue) Retrieve pointers to a statically created queue's data structure buffer and storage area buffer. These are the same buffers that are supplied at the time of creation. Parameters xQueue -- The queue for which to retrieve the buffers. ppucQueueStorage -- Used to return a pointer to the queue's storage area buffer. ppxStaticQueue -- Used to return a pointer to the queue's data structure buffer. xQueue -- The queue for which to retrieve the buffers. ppucQueueStorage -- Used to return a pointer to the queue's storage area buffer. ppxStaticQueue -- Used to return a pointer to the queue's data structure buffer. xQueue -- The queue for which to retrieve the buffers. Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. Parameters xQueue -- The queue for which to retrieve the buffers. ppucQueueStorage -- Used to return a pointer to the queue's storage area buffer. ppxStaticQueue -- Used to return a pointer to the queue's data structure buffer. Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. xQueueSendToFront(xQueue, pvItemToQueue, xTicksToWait) Post an item to the front of a queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueSendFromISR () for an alternative which may be used in an ISR. Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; uint32_t ulVar = 10UL; void vATask( void *pvParameters ) { QueueHandle_t xQueue1, xQueue2; struct AMessage *pxMessage; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); // ... if( xQueue1 != 0 ) { // Send an uint32_t. Wait for 10 ticks for space to become // available if necessary. if( xQueueSendToFront( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) { // Failed to post the message, even after 10 ticks. } } if( xQueue2 != 0 ) { // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSendToFront( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); } // ... Rest of task code. } Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xQueue -- The handle to the queue on which the item is to be posted. Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. xQueueSendToBack(xQueue, pvItemToQueue, xTicksToWait) This is a macro that calls xQueueGenericSend(). Post an item to the back of a queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueSendFromISR () for an alternative which may be used in an ISR. Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; uint32_t ulVar = 10UL; void vATask( void *pvParameters ) { QueueHandle_t xQueue1, xQueue2; struct AMessage *pxMessage; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); // ... if( xQueue1 != 0 ) { // Send an uint32_t. Wait for 10 ticks for space to become // available if necessary. if( xQueueSendToBack( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) { // Failed to post the message, even after 10 ticks. } } if( xQueue2 != 0 ) { // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSendToBack( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); } // ... Rest of task code. } Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xQueue -- The handle to the queue on which the item is to be posted. Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. xQueueSend(xQueue, pvItemToQueue, xTicksToWait) This is a macro that calls xQueueGenericSend(). It is included for backward compatibility with versions of FreeRTOS.org that did not include the xQueueSendToFront() and xQueueSendToBack() macros. It is equivalent to xQueueSendToBack(). Post an item on a queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueSendFromISR () for an alternative which may be used in an ISR. Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; uint32_t ulVar = 10UL; void vATask( void *pvParameters ) { QueueHandle_t xQueue1, xQueue2; struct AMessage *pxMessage; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); // ... if( xQueue1 != 0 ) { // Send an uint32_t. Wait for 10 ticks for space to become // available if necessary. if( xQueueSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) { // Failed to post the message, even after 10 ticks. } } if( xQueue2 != 0 ) { // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); } // ... Rest of task code. } Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xQueue -- The handle to the queue on which the item is to be posted. Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. xQueueOverwrite(xQueue, pvItemToQueue) Only for use with queues that have a length of one - so the queue is either empty or full. Post an item on a queue. If the queue is already full then overwrite the value held in the queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueOverwriteFromISR () for an alternative which may be used in an ISR. Example usage: void vFunction( void *pvParameters ) { QueueHandle_t xQueue; uint32_t ulVarToSend, ulValReceived; // Create a queue to hold one uint32_t value. It is strongly // recommended *not* to use xQueueOverwrite() on queues that can // contain more than one value, and doing so will trigger an assertion // if configASSERT() is defined. xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); // Write the value 10 to the queue using xQueueOverwrite(). ulVarToSend = 10; xQueueOverwrite( xQueue, &ulVarToSend ); // Peeking the queue should now return 10, but leave the value 10 in // the queue. A block time of zero is used as it is known that the // queue holds a value. ulValReceived = 0; xQueuePeek( xQueue, &ulValReceived, 0 ); if( ulValReceived != 10 ) { // Error unless the item was removed by a different task. } // The queue is still full. Use xQueueOverwrite() to overwrite the // value held in the queue with 100. ulVarToSend = 100; xQueueOverwrite( xQueue, &ulVarToSend ); // This time read from the queue, leaving the queue empty once more. // A block time of 0 is used again. xQueueReceive( xQueue, &ulValReceived, 0 ); // The value read should be the last value written, even though the // queue was already full when the value was written. if( ulValReceived != 100 ) { // Error! } // ... } Parameters xQueue -- The handle of the queue to which the data is being sent. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xQueue -- The handle of the queue to which the data is being sent. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xQueue -- The handle of the queue to which the data is being sent. Returns xQueueOverwrite() is a macro that calls xQueueGenericSend(), and therefore has the same return values as xQueueSendToFront(). However, pdPASS is the only value that can be returned because xQueueOverwrite() will write to the queue even when the queue is already full. Parameters xQueue -- The handle of the queue to which the data is being sent. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. Returns xQueueOverwrite() is a macro that calls xQueueGenericSend(), and therefore has the same return values as xQueueSendToFront(). However, pdPASS is the only value that can be returned because xQueueOverwrite() will write to the queue even when the queue is already full. xQueueSendToFrontFromISR(xQueue, pvItemToQueue, pxHigherPriorityTaskWoken) This is a macro that calls xQueueGenericSendFromISR(). Post an item to the front of a queue. It is safe to use this macro from within an interrupt service routine. Items are queued by copy not reference so it is preferable to only queue small items, especially when called from an ISR. In most cases it would be preferable to store a pointer to the item being queued. Example usage for buffered IO (where the ISR can obtain more than one value per call): void vBufferISR( void ) { char cIn; BaseType_t xHigherPriorityTaskWoken; // We have not woken a task at the start of the ISR. xHigherPriorityTaskWoken = pdFALSE; // Loop until the buffer is empty. do { // Obtain a byte from the buffer. cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); // Post the byte. xQueueSendToFrontFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); } while( portINPUT_BYTE( BUFFER_COUNT ) ); // Now the buffer is empty we can switch context if necessary. if( xHigherPriorityTaskWoken ) { taskYIELD (); } } Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueSendToFrontFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueSendToFromFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueSendToFrontFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueSendToFromFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xQueue -- The handle to the queue on which the item is to be posted. Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL. Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueSendToFrontFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueSendToFromFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL. xQueueSendToBackFromISR(xQueue, pvItemToQueue, pxHigherPriorityTaskWoken) This is a macro that calls xQueueGenericSendFromISR(). Post an item to the back of a queue. It is safe to use this macro from within an interrupt service routine. Items are queued by copy not reference so it is preferable to only queue small items, especially when called from an ISR. In most cases it would be preferable to store a pointer to the item being queued. Example usage for buffered IO (where the ISR can obtain more than one value per call): void vBufferISR( void ) { char cIn; BaseType_t xHigherPriorityTaskWoken; // We have not woken a task at the start of the ISR. xHigherPriorityTaskWoken = pdFALSE; // Loop until the buffer is empty. do { // Obtain a byte from the buffer. cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); // Post the byte. xQueueSendToBackFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); } while( portINPUT_BYTE( BUFFER_COUNT ) ); // Now the buffer is empty we can switch context if necessary. if( xHigherPriorityTaskWoken ) { taskYIELD (); } } Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueSendToBackFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueSendToBackFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueSendToBackFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueSendToBackFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xQueue -- The handle to the queue on which the item is to be posted. Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL. Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueSendToBackFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueSendToBackFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL. xQueueOverwriteFromISR(xQueue, pvItemToQueue, pxHigherPriorityTaskWoken) A version of xQueueOverwrite() that can be used in an interrupt service routine (ISR). Only for use with queues that can hold a single item - so the queue is either empty or full. Post an item on a queue. If the queue is already full then overwrite the value held in the queue. The item is queued by copy, not by reference. Example usage: QueueHandle_t xQueue; void vFunction( void *pvParameters ) { // Create a queue to hold one uint32_t value. It is strongly // recommended *not* to use xQueueOverwriteFromISR() on queues that can // contain more than one value, and doing so will trigger an assertion // if configASSERT() is defined. xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); } void vAnInterruptHandler( void ) { // xHigherPriorityTaskWoken must be set to pdFALSE before it is used. BaseType_t xHigherPriorityTaskWoken = pdFALSE; uint32_t ulVarToSend, ulValReceived; // Write the value 10 to the queue using xQueueOverwriteFromISR(). ulVarToSend = 10; xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); // The queue is full, but calling xQueueOverwriteFromISR() again will still // pass because the value held in the queue will be overwritten with the // new value. ulVarToSend = 100; xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); // Reading from the queue will now return 100. // ... if( xHigherPrioritytaskWoken == pdTRUE ) { // Writing to the queue caused a task to unblock and the unblocked task // has a priority higher than or equal to the priority of the currently // executing task (the task this interrupt interrupted). Perform a context // switch so this interrupt returns directly to the unblocked task. portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port. } } Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueOverwriteFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueOverwriteFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueOverwriteFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueOverwriteFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xQueue -- The handle to the queue on which the item is to be posted. Returns xQueueOverwriteFromISR() is a macro that calls xQueueGenericSendFromISR(), and therefore has the same return values as xQueueSendToFrontFromISR(). However, pdPASS is the only value that can be returned because xQueueOverwriteFromISR() will write to the queue even when the queue is already full. Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueOverwriteFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueOverwriteFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. Returns xQueueOverwriteFromISR() is a macro that calls xQueueGenericSendFromISR(), and therefore has the same return values as xQueueSendToFrontFromISR(). However, pdPASS is the only value that can be returned because xQueueOverwriteFromISR() will write to the queue even when the queue is already full. xQueueSendFromISR(xQueue, pvItemToQueue, pxHigherPriorityTaskWoken) This is a macro that calls xQueueGenericSendFromISR(). It is included for backward compatibility with versions of FreeRTOS.org that did not include the xQueueSendToBackFromISR() and xQueueSendToFrontFromISR() macros. Post an item to the back of a queue. It is safe to use this function from within an interrupt service routine. Items are queued by copy not reference so it is preferable to only queue small items, especially when called from an ISR. In most cases it would be preferable to store a pointer to the item being queued. Example usage for buffered IO (where the ISR can obtain more than one value per call): void vBufferISR( void ) { char cIn; BaseType_t xHigherPriorityTaskWoken; // We have not woken a task at the start of the ISR. xHigherPriorityTaskWoken = pdFALSE; // Loop until the buffer is empty. do { // Obtain a byte from the buffer. cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); // Post the byte. xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); } while( portINPUT_BYTE( BUFFER_COUNT ) ); // Now the buffer is empty we can switch context if necessary. if( xHigherPriorityTaskWoken ) { // Actual macro used here is port specific. portYIELD_FROM_ISR (); } } Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueSendFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueSendFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xQueue -- The handle to the queue on which the item is to be posted. Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL. Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueSendFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL. xQueueReset(xQueue) Reset a queue back to its original empty state. The return value is now obsolete and is always set to pdPASS. Type Definitions typedef struct QueueDefinition *QueueHandle_t typedef struct QueueDefinition *QueueSetHandle_t Type by which queue sets are referenced. For example, a call to xQueueCreateSet() returns an xQueueSet variable that can then be used as a parameter to xQueueSelectFromSet(), xQueueAddToSet(), etc. typedef struct QueueDefinition *QueueSetMemberHandle_t Queue sets can contain both queues and semaphores, so the QueueSetMemberHandle_t is defined as a type to be used where a parameter or return value can be either an QueueHandle_t or an SemaphoreHandle_t. Semaphore API Header File components/freertos/FreeRTOS-Kernel/include/freertos/semphr.h This header file can be included with: #include "freertos/semphr.h" Macros semBINARY_SEMAPHORE_QUEUE_LENGTH semSEMAPHORE_QUEUE_ITEM_LENGTH semGIVE_BLOCK_TIME vSemaphoreCreateBinary(xSemaphore) In many usage scenarios it is faster and more memory efficient to use a direct to task notification in place of a binary semaphore! https://www.FreeRTOS.org/RTOS-task-notifications.html This old vSemaphoreCreateBinary() macro is now deprecated in favour of the xSemaphoreCreateBinary() function. Note that binary semaphores created using the vSemaphoreCreateBinary() macro are created in a state such that the first call to 'take' the semaphore would pass, whereas binary semaphores created using xSemaphoreCreateBinary() are created in a state such that the the semaphore must first be 'given' before it can be 'taken'. Macro that implements a semaphore by using the existing queue mechanism. The queue length is 1 as this is a binary semaphore. The data size is 0 as we don't want to actually store any data - we just want to know if the queue is empty or full. This type of semaphore can be used for pure synchronisation between tasks or between an interrupt and a task. The semaphore need not be given back once obtained, so one task/interrupt can continuously 'give' the semaphore while another continuously 'takes' the semaphore. For this reason this type of semaphore does not use a priority inheritance mechanism. For an alternative that does use priority inheritance see xSemaphoreCreateMutex(). Example usage: SemaphoreHandle_t xSemaphore = NULL; void vATask( void * pvParameters ) { // Semaphore cannot be used before a call to vSemaphoreCreateBinary (). // This is a macro so pass the variable in directly. vSemaphoreCreateBinary( xSemaphore ); if( xSemaphore != NULL ) { // The semaphore was created successfully. // The semaphore can now be used. } } Parameters xSemaphore -- Handle to the created semaphore. Should be of type SemaphoreHandle_t. xSemaphore -- Handle to the created semaphore. Should be of type SemaphoreHandle_t. xSemaphore -- Handle to the created semaphore. Should be of type SemaphoreHandle_t. Parameters xSemaphore -- Handle to the created semaphore. Should be of type SemaphoreHandle_t. xSemaphoreCreateBinary() Creates a new binary semaphore instance, and returns a handle by which the new semaphore can be referenced. In many usage scenarios it is faster and more memory efficient to use a direct to task notification in place of a binary semaphore! https://www.FreeRTOS.org/RTOS-task-notifications.html Internally, within the FreeRTOS implementation, binary semaphores use a block of memory, in which the semaphore structure is stored. If a binary semaphore is created using xSemaphoreCreateBinary() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateBinary() function. (see https://www.FreeRTOS.org/a00111.html). If a binary semaphore is created using xSemaphoreCreateBinaryStatic() then the application writer must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a binary semaphore to be created without using any dynamic memory allocation. The old vSemaphoreCreateBinary() macro is now deprecated in favour of this xSemaphoreCreateBinary() function. Note that binary semaphores created using the vSemaphoreCreateBinary() macro are created in a state such that the first call to 'take' the semaphore would pass, whereas binary semaphores created using xSemaphoreCreateBinary() are created in a state such that the the semaphore must first be 'given' before it can be 'taken'. This type of semaphore can be used for pure synchronisation between tasks or between an interrupt and a task. The semaphore need not be given back once obtained, so one task/interrupt can continuously 'give' the semaphore while another continuously 'takes' the semaphore. For this reason this type of semaphore does not use a priority inheritance mechanism. For an alternative that does use priority inheritance see xSemaphoreCreateMutex(). Example usage: SemaphoreHandle_t xSemaphore = NULL; void vATask( void * pvParameters ) { // Semaphore cannot be used before a call to xSemaphoreCreateBinary(). // This is a macro so pass the variable in directly. xSemaphore = xSemaphoreCreateBinary(); if( xSemaphore != NULL ) { // The semaphore was created successfully. // The semaphore can now be used. } } Returns Handle to the created semaphore, or NULL if the memory required to hold the semaphore's data structures could not be allocated. Returns Handle to the created semaphore, or NULL if the memory required to hold the semaphore's data structures could not be allocated. xSemaphoreCreateBinaryStatic(pxStaticSemaphore) Creates a new binary semaphore instance, and returns a handle by which the new semaphore can be referenced. NOTE: In many usage scenarios it is faster and more memory efficient to use a direct to task notification in place of a binary semaphore! https://www.FreeRTOS.org/RTOS-task-notifications.html Internally, within the FreeRTOS implementation, binary semaphores use a block of memory, in which the semaphore structure is stored. If a binary semaphore is created using xSemaphoreCreateBinary() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateBinary() function. (see https://www.FreeRTOS.org/a00111.html). If a binary semaphore is created using xSemaphoreCreateBinaryStatic() then the application writer must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a binary semaphore to be created without using any dynamic memory allocation. This type of semaphore can be used for pure synchronisation between tasks or between an interrupt and a task. The semaphore need not be given back once obtained, so one task/interrupt can continuously 'give' the semaphore while another continuously 'takes' the semaphore. For this reason this type of semaphore does not use a priority inheritance mechanism. For an alternative that does use priority inheritance see xSemaphoreCreateMutex(). Example usage: SemaphoreHandle_t xSemaphore = NULL; StaticSemaphore_t xSemaphoreBuffer; void vATask( void * pvParameters ) { // Semaphore cannot be used before a call to xSemaphoreCreateBinary(). // The semaphore's data structures will be placed in the xSemaphoreBuffer // variable, the address of which is passed into the function. The // function's parameter is not NULL, so the function will not attempt any // dynamic memory allocation, and therefore the function will not return // return NULL. xSemaphore = xSemaphoreCreateBinary( &xSemaphoreBuffer ); // Rest of task code goes here. } Parameters pxStaticSemaphore -- Must point to a variable of type StaticSemaphore_t, which will then be used to hold the semaphore's data structure, removing the need for the memory to be allocated dynamically. pxStaticSemaphore -- Must point to a variable of type StaticSemaphore_t, which will then be used to hold the semaphore's data structure, removing the need for the memory to be allocated dynamically. pxStaticSemaphore -- Must point to a variable of type StaticSemaphore_t, which will then be used to hold the semaphore's data structure, removing the need for the memory to be allocated dynamically. Returns If the semaphore is created then a handle to the created semaphore is returned. If pxSemaphoreBuffer is NULL then NULL is returned. Parameters pxStaticSemaphore -- Must point to a variable of type StaticSemaphore_t, which will then be used to hold the semaphore's data structure, removing the need for the memory to be allocated dynamically. Returns If the semaphore is created then a handle to the created semaphore is returned. If pxSemaphoreBuffer is NULL then NULL is returned. xSemaphoreTake(xSemaphore, xBlockTime) Macro to obtain a semaphore. The semaphore must have previously been created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or xSemaphoreCreateCounting(). Example usage: SemaphoreHandle_t xSemaphore = NULL; // A task that creates a semaphore. void vATask( void * pvParameters ) { // Create the semaphore to guard a shared resource. xSemaphore = xSemaphoreCreateBinary(); } // A task that uses the semaphore. void vAnotherTask( void * pvParameters ) { // ... Do other things. if( xSemaphore != NULL ) { // See if we can obtain the semaphore. If the semaphore is not available // wait 10 ticks to see if it becomes free. if( xSemaphoreTake( xSemaphore, ( TickType_t ) 10 ) == pdTRUE ) { // We were able to obtain the semaphore and can now access the // shared resource. // ... // We have finished accessing the shared resource. Release the // semaphore. xSemaphoreGive( xSemaphore ); } else { // We could not obtain the semaphore and can therefore not access // the shared resource safely. } } } Parameters xSemaphore -- A handle to the semaphore being taken - obtained when the semaphore was created. xBlockTime -- The time in ticks to wait for the semaphore to become available. The macro portTICK_PERIOD_MS can be used to convert this to a real time. A block time of zero can be used to poll the semaphore. A block time of portMAX_DELAY can be used to block indefinitely (provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). xSemaphore -- A handle to the semaphore being taken - obtained when the semaphore was created. xBlockTime -- The time in ticks to wait for the semaphore to become available. The macro portTICK_PERIOD_MS can be used to convert this to a real time. A block time of zero can be used to poll the semaphore. A block time of portMAX_DELAY can be used to block indefinitely (provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). xSemaphore -- A handle to the semaphore being taken - obtained when the semaphore was created. Returns pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime expired without the semaphore becoming available. Parameters xSemaphore -- A handle to the semaphore being taken - obtained when the semaphore was created. xBlockTime -- The time in ticks to wait for the semaphore to become available. The macro portTICK_PERIOD_MS can be used to convert this to a real time. A block time of zero can be used to poll the semaphore. A block time of portMAX_DELAY can be used to block indefinitely (provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). Returns pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime expired without the semaphore becoming available. xSemaphoreTakeRecursive(xMutex, xBlockTime) Macro to recursively obtain, or 'take', a mutex type semaphore. The mutex must have previously been created using a call to xSemaphoreCreateRecursiveMutex(); configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this macro to be available. This macro must not be used on mutexes created using xSemaphoreCreateMutex(). A mutex used recursively can be 'taken' repeatedly by the owner. The mutex doesn't become available again until the owner has called xSemaphoreGiveRecursive() for each successful 'take' request. For example, if a task successfully 'takes' the same mutex 5 times then the mutex will not be available to any other task until it has also 'given' the mutex back exactly five times. Example usage: SemaphoreHandle_t xMutex = NULL; // A task that creates a mutex. void vATask( void * pvParameters ) { // Create the mutex to guard a shared resource. xMutex = xSemaphoreCreateRecursiveMutex(); } // A task that uses the mutex. void vAnotherTask( void * pvParameters ) { // ... Do other things. if( xMutex != NULL ) { // See if we can obtain the mutex. If the mutex is not available // wait 10 ticks to see if it becomes free. if( xSemaphoreTakeRecursive( xSemaphore, ( TickType_t ) 10 ) == pdTRUE ) { // We were able to obtain the mutex and can now access the // shared resource. // ... // For some reason due to the nature of the code further calls to // xSemaphoreTakeRecursive() are made on the same mutex. In real // code these would not be just sequential calls as this would make // no sense. Instead the calls are likely to be buried inside // a more complex call structure. xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); // The mutex has now been 'taken' three times, so will not be // available to another task until it has also been given back // three times. Again it is unlikely that real code would have // these calls sequentially, but instead buried in a more complex // call structure. This is just for illustrative purposes. xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); // Now the mutex can be taken by other tasks. } else { // We could not obtain the mutex and can therefore not access // the shared resource safely. } } } Parameters xMutex -- A handle to the mutex being obtained. This is the handle returned by xSemaphoreCreateRecursiveMutex(); xBlockTime -- The time in ticks to wait for the semaphore to become available. The macro portTICK_PERIOD_MS can be used to convert this to a real time. A block time of zero can be used to poll the semaphore. If the task already owns the semaphore then xSemaphoreTakeRecursive() will return immediately no matter what the value of xBlockTime. xMutex -- A handle to the mutex being obtained. This is the handle returned by xSemaphoreCreateRecursiveMutex(); xBlockTime -- The time in ticks to wait for the semaphore to become available. The macro portTICK_PERIOD_MS can be used to convert this to a real time. A block time of zero can be used to poll the semaphore. If the task already owns the semaphore then xSemaphoreTakeRecursive() will return immediately no matter what the value of xBlockTime. xMutex -- A handle to the mutex being obtained. This is the handle returned by xSemaphoreCreateRecursiveMutex(); Returns pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime expired without the semaphore becoming available. Parameters xMutex -- A handle to the mutex being obtained. This is the handle returned by xSemaphoreCreateRecursiveMutex(); xBlockTime -- The time in ticks to wait for the semaphore to become available. The macro portTICK_PERIOD_MS can be used to convert this to a real time. A block time of zero can be used to poll the semaphore. If the task already owns the semaphore then xSemaphoreTakeRecursive() will return immediately no matter what the value of xBlockTime. Returns pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime expired without the semaphore becoming available. xSemaphoreGive(xSemaphore) Macro to release a semaphore. The semaphore must have previously been created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or xSemaphoreCreateCounting(). and obtained using sSemaphoreTake(). This macro must not be used from an ISR. See xSemaphoreGiveFromISR () for an alternative which can be used from an ISR. This macro must also not be used on semaphores created using xSemaphoreCreateRecursiveMutex(). Example usage: SemaphoreHandle_t xSemaphore = NULL; void vATask( void * pvParameters ) { // Create the semaphore to guard a shared resource. xSemaphore = vSemaphoreCreateBinary(); if( xSemaphore != NULL ) { if( xSemaphoreGive( xSemaphore ) != pdTRUE ) { // We would expect this call to fail because we cannot give // a semaphore without first "taking" it! } // Obtain the semaphore - don't block if the semaphore is not // immediately available. if( xSemaphoreTake( xSemaphore, ( TickType_t ) 0 ) ) { // We now have the semaphore and can access the shared resource. // ... // We have finished accessing the shared resource so can free the // semaphore. if( xSemaphoreGive( xSemaphore ) != pdTRUE ) { // We would not expect this call to fail because we must have // obtained the semaphore to get here. } } } } Parameters xSemaphore -- A handle to the semaphore being released. This is the handle returned when the semaphore was created. xSemaphore -- A handle to the semaphore being released. This is the handle returned when the semaphore was created. xSemaphore -- A handle to the semaphore being released. This is the handle returned when the semaphore was created. Returns pdTRUE if the semaphore was released. pdFALSE if an error occurred. Semaphores are implemented using queues. An error can occur if there is no space on the queue to post a message - indicating that the semaphore was not first obtained correctly. Parameters xSemaphore -- A handle to the semaphore being released. This is the handle returned when the semaphore was created. Returns pdTRUE if the semaphore was released. pdFALSE if an error occurred. Semaphores are implemented using queues. An error can occur if there is no space on the queue to post a message - indicating that the semaphore was not first obtained correctly. xSemaphoreGiveRecursive(xMutex) Macro to recursively release, or 'give', a mutex type semaphore. The mutex must have previously been created using a call to xSemaphoreCreateRecursiveMutex(); configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this macro to be available. This macro must not be used on mutexes created using xSemaphoreCreateMutex(). A mutex used recursively can be 'taken' repeatedly by the owner. The mutex doesn't become available again until the owner has called xSemaphoreGiveRecursive() for each successful 'take' request. For example, if a task successfully 'takes' the same mutex 5 times then the mutex will not be available to any other task until it has also 'given' the mutex back exactly five times. Example usage: SemaphoreHandle_t xMutex = NULL; // A task that creates a mutex. void vATask( void * pvParameters ) { // Create the mutex to guard a shared resource. xMutex = xSemaphoreCreateRecursiveMutex(); } // A task that uses the mutex. void vAnotherTask( void * pvParameters ) { // ... Do other things. if( xMutex != NULL ) { // See if we can obtain the mutex. If the mutex is not available // wait 10 ticks to see if it becomes free. if( xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ) == pdTRUE ) { // We were able to obtain the mutex and can now access the // shared resource. // ... // For some reason due to the nature of the code further calls to // xSemaphoreTakeRecursive() are made on the same mutex. In real // code these would not be just sequential calls as this would make // no sense. Instead the calls are likely to be buried inside // a more complex call structure. xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); // The mutex has now been 'taken' three times, so will not be // available to another task until it has also been given back // three times. Again it is unlikely that real code would have // these calls sequentially, it would be more likely that the calls // to xSemaphoreGiveRecursive() would be called as a call stack // unwound. This is just for demonstrative purposes. xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); // Now the mutex can be taken by other tasks. } else { // We could not obtain the mutex and can therefore not access // the shared resource safely. } } } Parameters xMutex -- A handle to the mutex being released, or 'given'. This is the handle returned by xSemaphoreCreateMutex(); xMutex -- A handle to the mutex being released, or 'given'. This is the handle returned by xSemaphoreCreateMutex(); xMutex -- A handle to the mutex being released, or 'given'. This is the handle returned by xSemaphoreCreateMutex(); Returns pdTRUE if the semaphore was given. Parameters xMutex -- A handle to the mutex being released, or 'given'. This is the handle returned by xSemaphoreCreateMutex(); Returns pdTRUE if the semaphore was given. xSemaphoreGiveFromISR(xSemaphore, pxHigherPriorityTaskWoken) Macro to release a semaphore. The semaphore must have previously been created with a call to xSemaphoreCreateBinary() or xSemaphoreCreateCounting(). Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) must not be used with this macro. This macro can be used from an ISR. Example usage: #define LONG_TIME 0xffff #define TICKS_TO_WAIT 10 SemaphoreHandle_t xSemaphore = NULL; // Repetitive task. void vATask( void * pvParameters ) { for( ;; ) { // We want this task to run every 10 ticks of a timer. The semaphore // was created before this task was started. // Block waiting for the semaphore to become available. if( xSemaphoreTake( xSemaphore, LONG_TIME ) == pdTRUE ) { // It is time to execute. // ... // We have finished our task. Return to the top of the loop where // we will block on the semaphore until it is time to execute // again. Note when using the semaphore for synchronisation with an // ISR in this manner there is no need to 'give' the semaphore back. } } } // Timer ISR void vTimerISR( void * pvParameters ) { static uint8_t ucLocalTickCount = 0; static BaseType_t xHigherPriorityTaskWoken; // A timer tick has occurred. // ... Do other time functions. // Is it time for vATask () to run? xHigherPriorityTaskWoken = pdFALSE; ucLocalTickCount++; if( ucLocalTickCount >= TICKS_TO_WAIT ) { // Unblock the task by releasing the semaphore. xSemaphoreGiveFromISR( xSemaphore, &xHigherPriorityTaskWoken ); // Reset the count so we release the semaphore again in 10 ticks time. ucLocalTickCount = 0; } if( xHigherPriorityTaskWoken != pdFALSE ) { // We can force a context switch here. Context switching from an // ISR uses port specific syntax. Check the demo task for your port // to find the syntax required. } } Parameters xSemaphore -- A handle to the semaphore being released. This is the handle returned when the semaphore was created. pxHigherPriorityTaskWoken -- xSemaphoreGiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if giving the semaphore caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xSemaphoreGiveFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xSemaphore -- A handle to the semaphore being released. This is the handle returned when the semaphore was created. pxHigherPriorityTaskWoken -- xSemaphoreGiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if giving the semaphore caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xSemaphoreGiveFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xSemaphore -- A handle to the semaphore being released. This is the handle returned when the semaphore was created. Returns pdTRUE if the semaphore was successfully given, otherwise errQUEUE_FULL. Parameters xSemaphore -- A handle to the semaphore being released. This is the handle returned when the semaphore was created. pxHigherPriorityTaskWoken -- xSemaphoreGiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if giving the semaphore caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xSemaphoreGiveFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. Returns pdTRUE if the semaphore was successfully given, otherwise errQUEUE_FULL. xSemaphoreTakeFromISR(xSemaphore, pxHigherPriorityTaskWoken) Macro to take a semaphore from an ISR. The semaphore must have previously been created with a call to xSemaphoreCreateBinary() or xSemaphoreCreateCounting(). Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) must not be used with this macro. This macro can be used from an ISR, however taking a semaphore from an ISR is not a common operation. It is likely to only be useful when taking a counting semaphore when an interrupt is obtaining an object from a resource pool (when the semaphore count indicates the number of resources available). Parameters xSemaphore -- A handle to the semaphore being taken. This is the handle returned when the semaphore was created. pxHigherPriorityTaskWoken -- xSemaphoreTakeFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if taking the semaphore caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xSemaphoreTakeFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xSemaphore -- A handle to the semaphore being taken. This is the handle returned when the semaphore was created. pxHigherPriorityTaskWoken -- xSemaphoreTakeFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if taking the semaphore caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xSemaphoreTakeFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xSemaphore -- A handle to the semaphore being taken. This is the handle returned when the semaphore was created. Returns pdTRUE if the semaphore was successfully taken, otherwise pdFALSE Parameters xSemaphore -- A handle to the semaphore being taken. This is the handle returned when the semaphore was created. pxHigherPriorityTaskWoken -- xSemaphoreTakeFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if taking the semaphore caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xSemaphoreTakeFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. Returns pdTRUE if the semaphore was successfully taken, otherwise pdFALSE xSemaphoreCreateMutex() Creates a new mutex type semaphore instance, and returns a handle by which the new mutex can be referenced. Internally, within the FreeRTOS implementation, mutex semaphores use a block of memory, in which the mutex structure is stored. If a mutex is created using xSemaphoreCreateMutex() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateMutex() function. (see https://www.FreeRTOS.org/a00111.html). If a mutex is created using xSemaphoreCreateMutexStatic() then the application writer must provided the memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created without using any dynamic memory allocation. Mutexes created using this function can be accessed using the xSemaphoreTake() and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros must not be used. This type of semaphore uses a priority inheritance mechanism so a task 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the semaphore it is no longer required. Mutex type semaphores cannot be used from within interrupt service routines. See xSemaphoreCreateBinary() for an alternative implementation that can be used for pure synchronisation (where one task or interrupt always 'gives' the semaphore and another always 'takes' the semaphore) and from within interrupt service routines. Example usage: SemaphoreHandle_t xSemaphore; void vATask( void * pvParameters ) { // Semaphore cannot be used before a call to xSemaphoreCreateMutex(). // This is a macro so pass the variable in directly. xSemaphore = xSemaphoreCreateMutex(); if( xSemaphore != NULL ) { // The semaphore was created successfully. // The semaphore can now be used. } } Returns If the mutex was successfully created then a handle to the created semaphore is returned. If there was not enough heap to allocate the mutex data structures then NULL is returned. Returns If the mutex was successfully created then a handle to the created semaphore is returned. If there was not enough heap to allocate the mutex data structures then NULL is returned. xSemaphoreCreateMutexStatic(pxMutexBuffer) Creates a new mutex type semaphore instance, and returns a handle by which the new mutex can be referenced. Internally, within the FreeRTOS implementation, mutex semaphores use a block of memory, in which the mutex structure is stored. If a mutex is created using xSemaphoreCreateMutex() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateMutex() function. (see https://www.FreeRTOS.org/a00111.html). If a mutex is created using xSemaphoreCreateMutexStatic() then the application writer must provided the memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created without using any dynamic memory allocation. Mutexes created using this function can be accessed using the xSemaphoreTake() and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros must not be used. This type of semaphore uses a priority inheritance mechanism so a task 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the semaphore it is no longer required. Mutex type semaphores cannot be used from within interrupt service routines. See xSemaphoreCreateBinary() for an alternative implementation that can be used for pure synchronisation (where one task or interrupt always 'gives' the semaphore and another always 'takes' the semaphore) and from within interrupt service routines. Example usage: SemaphoreHandle_t xSemaphore; StaticSemaphore_t xMutexBuffer; void vATask( void * pvParameters ) { // A mutex cannot be used before it has been created. xMutexBuffer is // into xSemaphoreCreateMutexStatic() so no dynamic memory allocation is // attempted. xSemaphore = xSemaphoreCreateMutexStatic( &xMutexBuffer ); // As no dynamic memory allocation was performed, xSemaphore cannot be NULL, // so there is no need to check it. } Parameters pxMutexBuffer -- Must point to a variable of type StaticSemaphore_t, which will be used to hold the mutex's data structure, removing the need for the memory to be allocated dynamically. pxMutexBuffer -- Must point to a variable of type StaticSemaphore_t, which will be used to hold the mutex's data structure, removing the need for the memory to be allocated dynamically. pxMutexBuffer -- Must point to a variable of type StaticSemaphore_t, which will be used to hold the mutex's data structure, removing the need for the memory to be allocated dynamically. Returns If the mutex was successfully created then a handle to the created mutex is returned. If pxMutexBuffer was NULL then NULL is returned. Parameters pxMutexBuffer -- Must point to a variable of type StaticSemaphore_t, which will be used to hold the mutex's data structure, removing the need for the memory to be allocated dynamically. Returns If the mutex was successfully created then a handle to the created mutex is returned. If pxMutexBuffer was NULL then NULL is returned. xSemaphoreCreateRecursiveMutex() Creates a new recursive mutex type semaphore instance, and returns a handle by which the new recursive mutex can be referenced. Internally, within the FreeRTOS implementation, recursive mutexes use a block of memory, in which the mutex structure is stored. If a recursive mutex is created using xSemaphoreCreateRecursiveMutex() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateRecursiveMutex() function. (see https://www.FreeRTOS.org/a00111.html). If a recursive mutex is created using xSemaphoreCreateRecursiveMutexStatic() then the application writer must provide the memory that will get used by the mutex. xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to be created without using any dynamic memory allocation. Mutexes created using this macro can be accessed using the xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The xSemaphoreTake() and xSemaphoreGive() macros must not be used. A mutex used recursively can be 'taken' repeatedly by the owner. The mutex doesn't become available again until the owner has called xSemaphoreGiveRecursive() for each successful 'take' request. For example, if a task successfully 'takes' the same mutex 5 times then the mutex will not be available to any other task until it has also 'given' the mutex back exactly five times. This type of semaphore uses a priority inheritance mechanism so a task 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the semaphore it is no longer required. Mutex type semaphores cannot be used from within interrupt service routines. See xSemaphoreCreateBinary() for an alternative implementation that can be used for pure synchronisation (where one task or interrupt always 'gives' the semaphore and another always 'takes' the semaphore) and from within interrupt service routines. Example usage: SemaphoreHandle_t xSemaphore; void vATask( void * pvParameters ) { // Semaphore cannot be used before a call to xSemaphoreCreateMutex(). // This is a macro so pass the variable in directly. xSemaphore = xSemaphoreCreateRecursiveMutex(); if( xSemaphore != NULL ) { // The semaphore was created successfully. // The semaphore can now be used. } } Returns xSemaphore Handle to the created mutex semaphore. Should be of type SemaphoreHandle_t. Returns xSemaphore Handle to the created mutex semaphore. Should be of type SemaphoreHandle_t. xSemaphoreCreateRecursiveMutexStatic(pxStaticSemaphore) Creates a new recursive mutex type semaphore instance, and returns a handle by which the new recursive mutex can be referenced. Internally, within the FreeRTOS implementation, recursive mutexes use a block of memory, in which the mutex structure is stored. If a recursive mutex is created using xSemaphoreCreateRecursiveMutex() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateRecursiveMutex() function. (see https://www.FreeRTOS.org/a00111.html). If a recursive mutex is created using xSemaphoreCreateRecursiveMutexStatic() then the application writer must provide the memory that will get used by the mutex. xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to be created without using any dynamic memory allocation. Mutexes created using this macro can be accessed using the xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The xSemaphoreTake() and xSemaphoreGive() macros must not be used. A mutex used recursively can be 'taken' repeatedly by the owner. The mutex doesn't become available again until the owner has called xSemaphoreGiveRecursive() for each successful 'take' request. For example, if a task successfully 'takes' the same mutex 5 times then the mutex will not be available to any other task until it has also 'given' the mutex back exactly five times. This type of semaphore uses a priority inheritance mechanism so a task 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the semaphore it is no longer required. Mutex type semaphores cannot be used from within interrupt service routines. See xSemaphoreCreateBinary() for an alternative implementation that can be used for pure synchronisation (where one task or interrupt always 'gives' the semaphore and another always 'takes' the semaphore) and from within interrupt service routines. Example usage: SemaphoreHandle_t xSemaphore; StaticSemaphore_t xMutexBuffer; void vATask( void * pvParameters ) { // A recursive semaphore cannot be used before it is created. Here a // recursive mutex is created using xSemaphoreCreateRecursiveMutexStatic(). // The address of xMutexBuffer is passed into the function, and will hold // the mutexes data structures - so no dynamic memory allocation will be // attempted. xSemaphore = xSemaphoreCreateRecursiveMutexStatic( &xMutexBuffer ); // As no dynamic memory allocation was performed, xSemaphore cannot be NULL, // so there is no need to check it. } Parameters pxStaticSemaphore -- Must point to a variable of type StaticSemaphore_t, which will then be used to hold the recursive mutex's data structure, removing the need for the memory to be allocated dynamically. pxStaticSemaphore -- Must point to a variable of type StaticSemaphore_t, which will then be used to hold the recursive mutex's data structure, removing the need for the memory to be allocated dynamically. pxStaticSemaphore -- Must point to a variable of type StaticSemaphore_t, which will then be used to hold the recursive mutex's data structure, removing the need for the memory to be allocated dynamically. Returns If the recursive mutex was successfully created then a handle to the created recursive mutex is returned. If pxStaticSemaphore was NULL then NULL is returned. Parameters pxStaticSemaphore -- Must point to a variable of type StaticSemaphore_t, which will then be used to hold the recursive mutex's data structure, removing the need for the memory to be allocated dynamically. Returns If the recursive mutex was successfully created then a handle to the created recursive mutex is returned. If pxStaticSemaphore was NULL then NULL is returned. xSemaphoreCreateCounting(uxMaxCount, uxInitialCount) Creates a new counting semaphore instance, and returns a handle by which the new counting semaphore can be referenced. In many usage scenarios it is faster and more memory efficient to use a direct to task notification in place of a counting semaphore! https://www.FreeRTOS.org/RTOS-task-notifications.html Internally, within the FreeRTOS implementation, counting semaphores use a block of memory, in which the counting semaphore structure is stored. If a counting semaphore is created using xSemaphoreCreateCounting() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateCounting() function. (see https://www.FreeRTOS.org/a00111.html). If a counting semaphore is created using xSemaphoreCreateCountingStatic() then the application writer can instead optionally provide the memory that will get used by the counting semaphore. xSemaphoreCreateCountingStatic() therefore allows a counting semaphore to be created without using any dynamic memory allocation. Counting semaphores are typically used for two things: 1) Counting events. In this usage scenario an event handler will 'give' a semaphore each time an event occurs (incrementing the semaphore count value), and a handler task will 'take' a semaphore each time it processes an event (decrementing the semaphore count value). The count value is therefore the difference between the number of events that have occurred and the number that have been processed. In this case it is desirable for the initial count value to be zero. 2) Resource management. In this usage scenario the count value indicates the number of resources available. To obtain control of a resource a task must first obtain a semaphore - decrementing the semaphore count value. When the count value reaches zero there are no free resources. When a task finishes with the resource it 'gives' the semaphore back - incrementing the semaphore count value. In this case it is desirable for the initial count value to be equal to the maximum count value, indicating that all resources are free. Example usage: SemaphoreHandle_t xSemaphore; void vATask( void * pvParameters ) { SemaphoreHandle_t xSemaphore = NULL; // Semaphore cannot be used before a call to xSemaphoreCreateCounting(). // The max value to which the semaphore can count should be 10, and the // initial value assigned to the count should be 0. xSemaphore = xSemaphoreCreateCounting( 10, 0 ); if( xSemaphore != NULL ) { // The semaphore was created successfully. // The semaphore can now be used. } } Parameters uxMaxCount -- The maximum count value that can be reached. When the semaphore reaches this value it can no longer be 'given'. uxInitialCount -- The count value assigned to the semaphore when it is created. uxMaxCount -- The maximum count value that can be reached. When the semaphore reaches this value it can no longer be 'given'. uxInitialCount -- The count value assigned to the semaphore when it is created. uxMaxCount -- The maximum count value that can be reached. When the semaphore reaches this value it can no longer be 'given'. Returns Handle to the created semaphore. Null if the semaphore could not be created. Parameters uxMaxCount -- The maximum count value that can be reached. When the semaphore reaches this value it can no longer be 'given'. uxInitialCount -- The count value assigned to the semaphore when it is created. Returns Handle to the created semaphore. Null if the semaphore could not be created. xSemaphoreCreateCountingStatic(uxMaxCount, uxInitialCount, pxSemaphoreBuffer) Creates a new counting semaphore instance, and returns a handle by which the new counting semaphore can be referenced. In many usage scenarios it is faster and more memory efficient to use a direct to task notification in place of a counting semaphore! https://www.FreeRTOS.org/RTOS-task-notifications.html Internally, within the FreeRTOS implementation, counting semaphores use a block of memory, in which the counting semaphore structure is stored. If a counting semaphore is created using xSemaphoreCreateCounting() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateCounting() function. (see https://www.FreeRTOS.org/a00111.html). If a counting semaphore is created using xSemaphoreCreateCountingStatic() then the application writer must provide the memory. xSemaphoreCreateCountingStatic() therefore allows a counting semaphore to be created without using any dynamic memory allocation. Counting semaphores are typically used for two things: 1) Counting events. In this usage scenario an event handler will 'give' a semaphore each time an event occurs (incrementing the semaphore count value), and a handler task will 'take' a semaphore each time it processes an event (decrementing the semaphore count value). The count value is therefore the difference between the number of events that have occurred and the number that have been processed. In this case it is desirable for the initial count value to be zero. 2) Resource management. In this usage scenario the count value indicates the number of resources available. To obtain control of a resource a task must first obtain a semaphore - decrementing the semaphore count value. When the count value reaches zero there are no free resources. When a task finishes with the resource it 'gives' the semaphore back - incrementing the semaphore count value. In this case it is desirable for the initial count value to be equal to the maximum count value, indicating that all resources are free. Example usage: SemaphoreHandle_t xSemaphore; StaticSemaphore_t xSemaphoreBuffer; void vATask( void * pvParameters ) { SemaphoreHandle_t xSemaphore = NULL; // Counting semaphore cannot be used before they have been created. Create // a counting semaphore using xSemaphoreCreateCountingStatic(). The max // value to which the semaphore can count is 10, and the initial value // assigned to the count will be 0. The address of xSemaphoreBuffer is // passed in and will be used to hold the semaphore structure, so no dynamic // memory allocation will be used. xSemaphore = xSemaphoreCreateCounting( 10, 0, &xSemaphoreBuffer ); // No memory allocation was attempted so xSemaphore cannot be NULL, so there // is no need to check its value. } Parameters uxMaxCount -- The maximum count value that can be reached. When the semaphore reaches this value it can no longer be 'given'. uxInitialCount -- The count value assigned to the semaphore when it is created. pxSemaphoreBuffer -- Must point to a variable of type StaticSemaphore_t, which will then be used to hold the semaphore's data structure, removing the need for the memory to be allocated dynamically. uxMaxCount -- The maximum count value that can be reached. When the semaphore reaches this value it can no longer be 'given'. uxInitialCount -- The count value assigned to the semaphore when it is created. pxSemaphoreBuffer -- Must point to a variable of type StaticSemaphore_t, which will then be used to hold the semaphore's data structure, removing the need for the memory to be allocated dynamically. uxMaxCount -- The maximum count value that can be reached. When the semaphore reaches this value it can no longer be 'given'. Returns If the counting semaphore was successfully created then a handle to the created counting semaphore is returned. If pxSemaphoreBuffer was NULL then NULL is returned. Parameters uxMaxCount -- The maximum count value that can be reached. When the semaphore reaches this value it can no longer be 'given'. uxInitialCount -- The count value assigned to the semaphore when it is created. pxSemaphoreBuffer -- Must point to a variable of type StaticSemaphore_t, which will then be used to hold the semaphore's data structure, removing the need for the memory to be allocated dynamically. Returns If the counting semaphore was successfully created then a handle to the created counting semaphore is returned. If pxSemaphoreBuffer was NULL then NULL is returned. vSemaphoreDelete(xSemaphore) Delete a semaphore. This function must be used with care. For example, do not delete a mutex type semaphore if the mutex is held by a task. Parameters xSemaphore -- A handle to the semaphore to be deleted. xSemaphore -- A handle to the semaphore to be deleted. xSemaphore -- A handle to the semaphore to be deleted. Parameters xSemaphore -- A handle to the semaphore to be deleted. xSemaphoreGetMutexHolder(xSemaphore) If xMutex is indeed a mutex type semaphore, return the current mutex holder. If xMutex is not a mutex type semaphore, or the mutex is available (not held by a task), return NULL. Note: This is a good way of determining if the calling task is the mutex holder, but not a good way of determining the identity of the mutex holder as the holder may change between the function exiting and the returned value being tested. xSemaphoreGetMutexHolderFromISR(xSemaphore) If xMutex is indeed a mutex type semaphore, return the current mutex holder. If xMutex is not a mutex type semaphore, or the mutex is available (not held by a task), return NULL. uxSemaphoreGetCount(xSemaphore) If the semaphore is a counting semaphore then uxSemaphoreGetCount() returns its current count value. If the semaphore is a binary semaphore then uxSemaphoreGetCount() returns 1 if the semaphore is available, and 0 if the semaphore is not available. uxSemaphoreGetCountFromISR(xSemaphore) semphr.h UBaseType_t uxSemaphoreGetCountFromISR( SemaphoreHandle_t xSemaphore ); If the semaphore is a counting semaphore then uxSemaphoreGetCountFromISR() returns its current count value. If the semaphore is a binary semaphore then uxSemaphoreGetCountFromISR() returns 1 if the semaphore is available, and 0 if the semaphore is not available. xSemaphoreGetStaticBuffer(xSemaphore, ppxSemaphoreBuffer) Retrieve pointer to a statically created binary semaphore, counting semaphore, or mutex semaphore's data structure buffer. This is the same buffer that is supplied at the time of creation. Parameters xSemaphore -- The semaphore for which to retrieve the buffer. ppxSemaphoreBuffer -- Used to return a pointer to the semaphore's data structure buffer. xSemaphore -- The semaphore for which to retrieve the buffer. ppxSemaphoreBuffer -- Used to return a pointer to the semaphore's data structure buffer. xSemaphore -- The semaphore for which to retrieve the buffer. Returns pdTRUE if buffer was retrieved, pdFALSE otherwise. Parameters xSemaphore -- The semaphore for which to retrieve the buffer. ppxSemaphoreBuffer -- Used to return a pointer to the semaphore's data structure buffer. Returns pdTRUE if buffer was retrieved, pdFALSE otherwise. Type Definitions typedef QueueHandle_t SemaphoreHandle_t Timer API Header File components/freertos/FreeRTOS-Kernel/include/freertos/timers.h This header file can be included with: #include "freertos/timers.h" Functions TimerHandle_t xTimerCreate(const char *const pcTimerName, const TickType_t xTimerPeriodInTicks, const BaseType_t xAutoReload, void *const pvTimerID, TimerCallbackFunction_t pxCallbackFunction) Creates a new software timer instance, and returns a handle by which the created software timer can be referenced. Internally, within the FreeRTOS implementation, software timers use a block of memory, in which the timer data structure is stored. If a software timer is created using xTimerCreate() then the required memory is automatically dynamically allocated inside the xTimerCreate() function. (see https://www.FreeRTOS.org/a00111.html). If a software timer is created using xTimerCreateStatic() then the application writer must provide the memory that will get used by the software timer. xTimerCreateStatic() therefore allows a software timer to be created without using any dynamic memory allocation. Timers are created in the dormant state. The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the active state. Example usage: * #define NUM_TIMERS 5 * * // An array to hold handles to the created timers. * TimerHandle_t xTimers[ NUM_TIMERS ]; * * // An array to hold a count of the number of times each timer expires. * int32_t lExpireCounters[ NUM_TIMERS ] = { 0 }; * * // Define a callback function that will be used by multiple timer instances. * // The callback function does nothing but count the number of times the * // associated timer expires, and stop the timer once the timer has expired * // 10 times. * void vTimerCallback( TimerHandle_t pxTimer ) * { * int32_t lArrayIndex; * const int32_t xMaxExpiryCountBeforeStopping = 10; * * // Optionally do something if the pxTimer parameter is NULL. * configASSERT( pxTimer ); * * // Which timer expired? * lArrayIndex = ( int32_t ) pvTimerGetTimerID( pxTimer ); * * // Increment the number of times that pxTimer has expired. * lExpireCounters[ lArrayIndex ] += 1; * * // If the timer has expired 10 times then stop it from running. * if( lExpireCounters[ lArrayIndex ] == xMaxExpiryCountBeforeStopping ) * { * // Do not use a block time if calling a timer API function from a * // timer callback function, as doing so could cause a deadlock! * xTimerStop( pxTimer, 0 ); * } * } * * void main( void ) * { * int32_t x; * * // Create then start some timers. Starting the timers before the scheduler * // has been started means the timers will start running immediately that * // the scheduler starts. * for( x = 0; x < NUM_TIMERS; x++ ) * { * xTimers[ x ] = xTimerCreate( "Timer", // Just a text name, not used by the kernel. * ( 100 * ( x + 1 ) ), // The timer period in ticks. * pdTRUE, // The timers will auto-reload themselves when they expire. * ( void * ) x, // Assign each timer a unique id equal to its array index. * vTimerCallback // Each timer calls the same callback when it expires. * ); * * if( xTimers[ x ] == NULL ) * { * // The timer was not created. * } * else * { * // Start the timer. No block time is specified, and even if one was * // it would be ignored because the scheduler has not yet been * // started. * if( xTimerStart( xTimers[ x ], 0 ) != pdPASS ) * { * // The timer could not be set into the Active state. * } * } * } * * // ... * // Create tasks here. * // ... * * // Starting the scheduler will start the timers running as they have already * // been set into the active state. * vTaskStartScheduler(); * * // Should not reach here. * for( ;; ); * } * Parameters pcTimerName -- A text name that is assigned to the timer. This is done purely to assist debugging. The kernel itself only ever references a timer by its handle, and never by its name. xTimerPeriodInTicks -- The timer period. The time is defined in tick periods so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xTimerPeriodInTicks should be set to 100. Alternatively, if the timer must expire after 500ms, then xPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. Time timer period must be greater than 0. xAutoReload -- If xAutoReload is set to pdTRUE then the timer will expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. If xAutoReload is set to pdFALSE then the timer will be a one-shot timer and enter the dormant state after it expires. pvTimerID -- An identifier that is assigned to the timer being created. Typically this would be used in the timer callback function to identify which timer expired when the same callback function is assigned to more than one timer. pxCallbackFunction -- The function to call when the timer expires. Callback functions must have the prototype defined by TimerCallbackFunction_t, which is "void vCallbackFunction( TimerHandle_t xTimer );". pcTimerName -- A text name that is assigned to the timer. This is done purely to assist debugging. The kernel itself only ever references a timer by its handle, and never by its name. xTimerPeriodInTicks -- The timer period. The time is defined in tick periods so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xTimerPeriodInTicks should be set to 100. Alternatively, if the timer must expire after 500ms, then xPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. Time timer period must be greater than 0. xAutoReload -- If xAutoReload is set to pdTRUE then the timer will expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. If xAutoReload is set to pdFALSE then the timer will be a one-shot timer and enter the dormant state after it expires. pvTimerID -- An identifier that is assigned to the timer being created. Typically this would be used in the timer callback function to identify which timer expired when the same callback function is assigned to more than one timer. pxCallbackFunction -- The function to call when the timer expires. Callback functions must have the prototype defined by TimerCallbackFunction_t, which is "void vCallbackFunction( TimerHandle_t xTimer );". pcTimerName -- A text name that is assigned to the timer. This is done purely to assist debugging. The kernel itself only ever references a timer by its handle, and never by its name. Returns If the timer is successfully created then a handle to the newly created timer is returned. If the timer cannot be created because there is insufficient FreeRTOS heap remaining to allocate the timer structures then NULL is returned. Parameters pcTimerName -- A text name that is assigned to the timer. This is done purely to assist debugging. The kernel itself only ever references a timer by its handle, and never by its name. xTimerPeriodInTicks -- The timer period. The time is defined in tick periods so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xTimerPeriodInTicks should be set to 100. Alternatively, if the timer must expire after 500ms, then xPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. Time timer period must be greater than 0. xAutoReload -- If xAutoReload is set to pdTRUE then the timer will expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. If xAutoReload is set to pdFALSE then the timer will be a one-shot timer and enter the dormant state after it expires. pvTimerID -- An identifier that is assigned to the timer being created. Typically this would be used in the timer callback function to identify which timer expired when the same callback function is assigned to more than one timer. pxCallbackFunction -- The function to call when the timer expires. Callback functions must have the prototype defined by TimerCallbackFunction_t, which is "void vCallbackFunction( TimerHandle_t xTimer );". Returns If the timer is successfully created then a handle to the newly created timer is returned. If the timer cannot be created because there is insufficient FreeRTOS heap remaining to allocate the timer structures then NULL is returned. TimerHandle_t xTimerCreateStatic(const char *const pcTimerName, const TickType_t xTimerPeriodInTicks, const BaseType_t xAutoReload, void *const pvTimerID, TimerCallbackFunction_t pxCallbackFunction, StaticTimer_t *pxTimerBuffer) Creates a new software timer instance, and returns a handle by which the created software timer can be referenced. Internally, within the FreeRTOS implementation, software timers use a block of memory, in which the timer data structure is stored. If a software timer is created using xTimerCreate() then the required memory is automatically dynamically allocated inside the xTimerCreate() function. (see https://www.FreeRTOS.org/a00111.html). If a software timer is created using xTimerCreateStatic() then the application writer must provide the memory that will get used by the software timer. xTimerCreateStatic() therefore allows a software timer to be created without using any dynamic memory allocation. Timers are created in the dormant state. The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the active state. Example usage: * * // The buffer used to hold the software timer's data structure. * static StaticTimer_t xTimerBuffer; * * // A variable that will be incremented by the software timer's callback * // function. * UBaseType_t uxVariableToIncrement = 0; * * // A software timer callback function that increments a variable passed to * // it when the software timer was created. After the 5th increment the * // callback function stops the software timer. * static void prvTimerCallback( TimerHandle_t xExpiredTimer ) * { * UBaseType_t *puxVariableToIncrement; * BaseType_t xReturned; * * // Obtain the address of the variable to increment from the timer ID. * puxVariableToIncrement = ( UBaseType_t * ) pvTimerGetTimerID( xExpiredTimer ); * * // Increment the variable to show the timer callback has executed. * ( *puxVariableToIncrement )++; * * // If this callback has executed the required number of times, stop the * // timer. * if( *puxVariableToIncrement == 5 ) * { * // This is called from a timer callback so must not block. * xTimerStop( xExpiredTimer, staticDONT_BLOCK ); * } * } * * * void main( void ) * { * // Create the software time. xTimerCreateStatic() has an extra parameter * // than the normal xTimerCreate() API function. The parameter is a pointer * // to the StaticTimer_t structure that will hold the software timer * // structure. If the parameter is passed as NULL then the structure will be * // allocated dynamically, just as if xTimerCreate() had been called. * xTimer = xTimerCreateStatic( "T1", // Text name for the task. Helps debugging only. Not used by FreeRTOS. * xTimerPeriod, // The period of the timer in ticks. * pdTRUE, // This is an auto-reload timer. * ( void * ) &uxVariableToIncrement, // A variable incremented by the software timer's callback function * prvTimerCallback, // The function to execute when the timer expires. * &xTimerBuffer ); // The buffer that will hold the software timer structure. * * // The scheduler has not started yet so a block time is not used. * xReturned = xTimerStart( xTimer, 0 ); * * // ... * // Create tasks here. * // ... * * // Starting the scheduler will start the timers running as they have already * // been set into the active state. * vTaskStartScheduler(); * * // Should not reach here. * for( ;; ); * } * Parameters pcTimerName -- A text name that is assigned to the timer. This is done purely to assist debugging. The kernel itself only ever references a timer by its handle, and never by its name. xTimerPeriodInTicks -- The timer period. The time is defined in tick periods so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xTimerPeriodInTicks should be set to 100. Alternatively, if the timer must expire after 500ms, then xPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. The timer period must be greater than 0. xAutoReload -- If xAutoReload is set to pdTRUE then the timer will expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. If xAutoReload is set to pdFALSE then the timer will be a one-shot timer and enter the dormant state after it expires. pvTimerID -- An identifier that is assigned to the timer being created. Typically this would be used in the timer callback function to identify which timer expired when the same callback function is assigned to more than one timer. pxCallbackFunction -- The function to call when the timer expires. Callback functions must have the prototype defined by TimerCallbackFunction_t, which is "void vCallbackFunction( TimerHandle_t xTimer );". pxTimerBuffer -- Must point to a variable of type StaticTimer_t, which will be then be used to hold the software timer's data structures, removing the need for the memory to be allocated dynamically. pcTimerName -- A text name that is assigned to the timer. This is done purely to assist debugging. The kernel itself only ever references a timer by its handle, and never by its name. xTimerPeriodInTicks -- The timer period. The time is defined in tick periods so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xTimerPeriodInTicks should be set to 100. Alternatively, if the timer must expire after 500ms, then xPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. The timer period must be greater than 0. xAutoReload -- If xAutoReload is set to pdTRUE then the timer will expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. If xAutoReload is set to pdFALSE then the timer will be a one-shot timer and enter the dormant state after it expires. pvTimerID -- An identifier that is assigned to the timer being created. Typically this would be used in the timer callback function to identify which timer expired when the same callback function is assigned to more than one timer. pxCallbackFunction -- The function to call when the timer expires. Callback functions must have the prototype defined by TimerCallbackFunction_t, which is "void vCallbackFunction( TimerHandle_t xTimer );". pxTimerBuffer -- Must point to a variable of type StaticTimer_t, which will be then be used to hold the software timer's data structures, removing the need for the memory to be allocated dynamically. pcTimerName -- A text name that is assigned to the timer. This is done purely to assist debugging. The kernel itself only ever references a timer by its handle, and never by its name. Returns If the timer is created then a handle to the created timer is returned. If pxTimerBuffer was NULL then NULL is returned. Parameters pcTimerName -- A text name that is assigned to the timer. This is done purely to assist debugging. The kernel itself only ever references a timer by its handle, and never by its name. xTimerPeriodInTicks -- The timer period. The time is defined in tick periods so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xTimerPeriodInTicks should be set to 100. Alternatively, if the timer must expire after 500ms, then xPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. The timer period must be greater than 0. xAutoReload -- If xAutoReload is set to pdTRUE then the timer will expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. If xAutoReload is set to pdFALSE then the timer will be a one-shot timer and enter the dormant state after it expires. pvTimerID -- An identifier that is assigned to the timer being created. Typically this would be used in the timer callback function to identify which timer expired when the same callback function is assigned to more than one timer. pxCallbackFunction -- The function to call when the timer expires. Callback functions must have the prototype defined by TimerCallbackFunction_t, which is "void vCallbackFunction( TimerHandle_t xTimer );". pxTimerBuffer -- Must point to a variable of type StaticTimer_t, which will be then be used to hold the software timer's data structures, removing the need for the memory to be allocated dynamically. Returns If the timer is created then a handle to the created timer is returned. If pxTimerBuffer was NULL then NULL is returned. void *pvTimerGetTimerID(const TimerHandle_t xTimer) Returns the ID assigned to the timer. IDs are assigned to timers using the pvTimerID parameter of the call to xTimerCreated() that was used to create the timer, and by calling the vTimerSetTimerID() API function. If the same callback function is assigned to multiple timers then the timer ID can be used as time specific (timer local) storage. Example usage: See the xTimerCreate() API function example usage scenario. Parameters xTimer -- The timer being queried. Returns The ID assigned to the timer being queried. Parameters xTimer -- The timer being queried. Returns The ID assigned to the timer being queried. void vTimerSetTimerID(TimerHandle_t xTimer, void *pvNewID) Sets the ID assigned to the timer. IDs are assigned to timers using the pvTimerID parameter of the call to xTimerCreated() that was used to create the timer. If the same callback function is assigned to multiple timers then the timer ID can be used as time specific (timer local) storage. Example usage: See the xTimerCreate() API function example usage scenario. Parameters xTimer -- The timer being updated. pvNewID -- The ID to assign to the timer. xTimer -- The timer being updated. pvNewID -- The ID to assign to the timer. xTimer -- The timer being updated. Parameters xTimer -- The timer being updated. pvNewID -- The ID to assign to the timer. BaseType_t xTimerIsTimerActive(TimerHandle_t xTimer) Queries a timer to see if it is active or dormant. A timer will be dormant if: 1) It has been created but not started, or 2) It is an expired one-shot timer that has not been restarted. Timers are created in the dormant state. The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the active state. Example usage: * // This function assumes xTimer has already been created. * void vAFunction( TimerHandle_t xTimer ) * { * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" * { * // xTimer is active, do something. * } * else * { * // xTimer is not active, do something else. * } * } * Parameters xTimer -- The timer being queried. Returns pdFALSE will be returned if the timer is dormant. A value other than pdFALSE will be returned if the timer is active. Parameters xTimer -- The timer being queried. Returns pdFALSE will be returned if the timer is dormant. A value other than pdFALSE will be returned if the timer is active. TaskHandle_t xTimerGetTimerDaemonTaskHandle(void) Simply returns the handle of the timer service/daemon task. It it not valid to call xTimerGetTimerDaemonTaskHandle() before the scheduler has been started. BaseType_t xTimerPendFunctionCallFromISR(PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken) Used from application interrupt service routines to defer the execution of a function to the RTOS daemon task (the timer service task, hence this function is implemented in timers.c and is prefixed with 'Timer'). Ideally an interrupt service routine (ISR) is kept as short as possible, but sometimes an ISR either has a lot of processing to do, or needs to perform processing that is not deterministic. In these cases xTimerPendFunctionCallFromISR() can be used to defer processing of a function to the RTOS daemon task. A mechanism is provided that allows the interrupt to return directly to the task that will subsequently execute the pended callback function. This allows the callback function to execute contiguously in time with the interrupt - just as if the callback had executed in the interrupt itself. Example usage: * * // The callback function that will execute in the context of the daemon task. * // Note callback functions must all use this same prototype. * void vProcessInterface( void *pvParameter1, uint32_t ulParameter2 ) * { * BaseType_t xInterfaceToService; * * // The interface that requires servicing is passed in the second * // parameter. The first parameter is not used in this case. * xInterfaceToService = ( BaseType_t ) ulParameter2; * * // ...Perform the processing here... * } * * // An ISR that receives data packets from multiple interfaces * void vAnISR( void ) * { * BaseType_t xInterfaceToService, xHigherPriorityTaskWoken; * * // Query the hardware to determine which interface needs processing. * xInterfaceToService = prvCheckInterfaces(); * * // The actual processing is to be deferred to a task. Request the * // vProcessInterface() callback function is executed, passing in the * // number of the interface that needs processing. The interface to * // service is passed in the second parameter. The first parameter is * // not used in this case. * xHigherPriorityTaskWoken = pdFALSE; * xTimerPendFunctionCallFromISR( vProcessInterface, NULL, ( uint32_t ) xInterfaceToService, &xHigherPriorityTaskWoken ); * * // If xHigherPriorityTaskWoken is now set to pdTRUE then a context * // switch should be requested. The macro used is port specific and will * // be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to * // the documentation page for the port being used. * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); * * } * Parameters xFunctionToPend -- The function to execute from the timer service/ daemon task. The function must conform to the PendedFunction_t prototype. pvParameter1 -- The value of the callback function's first parameter. The parameter has a void * type to allow it to be used to pass any type. For example, unsigned longs can be cast to a void *, or the void * can be used to point to a structure. ulParameter2 -- The value of the callback function's second parameter. pxHigherPriorityTaskWoken -- As mentioned above, calling this function will result in a message being sent to the timer daemon task. If the priority of the timer daemon task (which is set using configTIMER_TASK_PRIORITY in FreeRTOSConfig.h) is higher than the priority of the currently running task (the task the interrupt interrupted) then *pxHigherPriorityTaskWoken will be set to pdTRUE within xTimerPendFunctionCallFromISR(), indicating that a context switch should be requested before the interrupt exits. For that reason *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the example code below. xFunctionToPend -- The function to execute from the timer service/ daemon task. The function must conform to the PendedFunction_t prototype. pvParameter1 -- The value of the callback function's first parameter. The parameter has a void * type to allow it to be used to pass any type. For example, unsigned longs can be cast to a void *, or the void * can be used to point to a structure. ulParameter2 -- The value of the callback function's second parameter. pxHigherPriorityTaskWoken -- As mentioned above, calling this function will result in a message being sent to the timer daemon task. If the priority of the timer daemon task (which is set using configTIMER_TASK_PRIORITY in FreeRTOSConfig.h) is higher than the priority of the currently running task (the task the interrupt interrupted) then *pxHigherPriorityTaskWoken will be set to pdTRUE within xTimerPendFunctionCallFromISR(), indicating that a context switch should be requested before the interrupt exits. For that reason *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the example code below. xFunctionToPend -- The function to execute from the timer service/ daemon task. The function must conform to the PendedFunction_t prototype. Returns pdPASS is returned if the message was successfully sent to the timer daemon task, otherwise pdFALSE is returned. Parameters xFunctionToPend -- The function to execute from the timer service/ daemon task. The function must conform to the PendedFunction_t prototype. pvParameter1 -- The value of the callback function's first parameter. The parameter has a void * type to allow it to be used to pass any type. For example, unsigned longs can be cast to a void *, or the void * can be used to point to a structure. ulParameter2 -- The value of the callback function's second parameter. pxHigherPriorityTaskWoken -- As mentioned above, calling this function will result in a message being sent to the timer daemon task. If the priority of the timer daemon task (which is set using configTIMER_TASK_PRIORITY in FreeRTOSConfig.h) is higher than the priority of the currently running task (the task the interrupt interrupted) then *pxHigherPriorityTaskWoken will be set to pdTRUE within xTimerPendFunctionCallFromISR(), indicating that a context switch should be requested before the interrupt exits. For that reason *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the example code below. Returns pdPASS is returned if the message was successfully sent to the timer daemon task, otherwise pdFALSE is returned. BaseType_t xTimerPendFunctionCall(PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait) Used to defer the execution of a function to the RTOS daemon task (the timer service task, hence this function is implemented in timers.c and is prefixed with 'Timer'). Parameters xFunctionToPend -- The function to execute from the timer service/ daemon task. The function must conform to the PendedFunction_t prototype. pvParameter1 -- The value of the callback function's first parameter. The parameter has a void * type to allow it to be used to pass any type. For example, unsigned longs can be cast to a void *, or the void * can be used to point to a structure. ulParameter2 -- The value of the callback function's second parameter. xTicksToWait -- Calling this function will result in a message being sent to the timer daemon task on a queue. xTicksToWait is the amount of time the calling task should remain in the Blocked state (so not using any processing time) for space to become available on the timer queue if the queue is found to be full. xFunctionToPend -- The function to execute from the timer service/ daemon task. The function must conform to the PendedFunction_t prototype. pvParameter1 -- The value of the callback function's first parameter. The parameter has a void * type to allow it to be used to pass any type. For example, unsigned longs can be cast to a void *, or the void * can be used to point to a structure. ulParameter2 -- The value of the callback function's second parameter. xTicksToWait -- Calling this function will result in a message being sent to the timer daemon task on a queue. xTicksToWait is the amount of time the calling task should remain in the Blocked state (so not using any processing time) for space to become available on the timer queue if the queue is found to be full. xFunctionToPend -- The function to execute from the timer service/ daemon task. The function must conform to the PendedFunction_t prototype. Returns pdPASS is returned if the message was successfully sent to the timer daemon task, otherwise pdFALSE is returned. Parameters xFunctionToPend -- The function to execute from the timer service/ daemon task. The function must conform to the PendedFunction_t prototype. pvParameter1 -- The value of the callback function's first parameter. The parameter has a void * type to allow it to be used to pass any type. For example, unsigned longs can be cast to a void *, or the void * can be used to point to a structure. ulParameter2 -- The value of the callback function's second parameter. xTicksToWait -- Calling this function will result in a message being sent to the timer daemon task on a queue. xTicksToWait is the amount of time the calling task should remain in the Blocked state (so not using any processing time) for space to become available on the timer queue if the queue is found to be full. Returns pdPASS is returned if the message was successfully sent to the timer daemon task, otherwise pdFALSE is returned. const char *pcTimerGetName(TimerHandle_t xTimer) Returns the name that was assigned to a timer when the timer was created. Parameters xTimer -- The handle of the timer being queried. Returns The name assigned to the timer specified by the xTimer parameter. Parameters xTimer -- The handle of the timer being queried. Returns The name assigned to the timer specified by the xTimer parameter. void vTimerSetReloadMode(TimerHandle_t xTimer, const BaseType_t xAutoReload) Updates a timer to be either an auto-reload timer, in which case the timer automatically resets itself each time it expires, or a one-shot timer, in which case the timer will only expire once unless it is manually restarted. Parameters xTimer -- The handle of the timer being updated. xAutoReload -- If xAutoReload is set to pdTRUE then the timer will expire repeatedly with a frequency set by the timer's period (see the xTimerPeriodInTicks parameter of the xTimerCreate() API function). If xAutoReload is set to pdFALSE then the timer will be a one-shot timer and enter the dormant state after it expires. xTimer -- The handle of the timer being updated. xAutoReload -- If xAutoReload is set to pdTRUE then the timer will expire repeatedly with a frequency set by the timer's period (see the xTimerPeriodInTicks parameter of the xTimerCreate() API function). If xAutoReload is set to pdFALSE then the timer will be a one-shot timer and enter the dormant state after it expires. xTimer -- The handle of the timer being updated. Parameters xTimer -- The handle of the timer being updated. xAutoReload -- If xAutoReload is set to pdTRUE then the timer will expire repeatedly with a frequency set by the timer's period (see the xTimerPeriodInTicks parameter of the xTimerCreate() API function). If xAutoReload is set to pdFALSE then the timer will be a one-shot timer and enter the dormant state after it expires. BaseType_t xTimerGetReloadMode(TimerHandle_t xTimer) Queries a timer to determine if it is an auto-reload timer, in which case the timer automatically resets itself each time it expires, or a one-shot timer, in which case the timer will only expire once unless it is manually restarted. Parameters xTimer -- The handle of the timer being queried. Returns If the timer is an auto-reload timer then pdTRUE is returned, otherwise pdFALSE is returned. Parameters xTimer -- The handle of the timer being queried. Returns If the timer is an auto-reload timer then pdTRUE is returned, otherwise pdFALSE is returned. UBaseType_t uxTimerGetReloadMode(TimerHandle_t xTimer) Queries a timer to determine if it is an auto-reload timer, in which case the timer automatically resets itself each time it expires, or a one-shot timer, in which case the timer will only expire once unless it is manually restarted. Parameters xTimer -- The handle of the timer being queried. Returns If the timer is an auto-reload timer then pdTRUE is returned, otherwise pdFALSE is returned. Parameters xTimer -- The handle of the timer being queried. Returns If the timer is an auto-reload timer then pdTRUE is returned, otherwise pdFALSE is returned. TickType_t xTimerGetPeriod(TimerHandle_t xTimer) Returns the period of a timer. Parameters xTimer -- The handle of the timer being queried. Returns The period of the timer in ticks. Parameters xTimer -- The handle of the timer being queried. Returns The period of the timer in ticks. TickType_t xTimerGetExpiryTime(TimerHandle_t xTimer) Returns the time in ticks at which the timer will expire. If this is less than the current tick count then the expiry time has overflowed from the current time. Parameters xTimer -- The handle of the timer being queried. Returns If the timer is running then the time in ticks at which the timer will next expire is returned. If the timer is not running then the return value is undefined. Parameters xTimer -- The handle of the timer being queried. Returns If the timer is running then the time in ticks at which the timer will next expire is returned. If the timer is not running then the return value is undefined. BaseType_t xTimerGetStaticBuffer(TimerHandle_t xTimer, StaticTimer_t **ppxTimerBuffer) Retrieve pointer to a statically created timer's data structure buffer. This is the same buffer that is supplied at the time of creation. Parameters xTimer -- The timer for which to retrieve the buffer. ppxTimerBuffer -- Used to return a pointer to the timers's data structure buffer. xTimer -- The timer for which to retrieve the buffer. ppxTimerBuffer -- Used to return a pointer to the timers's data structure buffer. xTimer -- The timer for which to retrieve the buffer. Returns pdTRUE if the buffer was retrieved, pdFALSE otherwise. Parameters xTimer -- The timer for which to retrieve the buffer. ppxTimerBuffer -- Used to return a pointer to the timers's data structure buffer. Returns pdTRUE if the buffer was retrieved, pdFALSE otherwise. void vApplicationGetTimerTaskMemory(StaticTask_t **ppxTimerTaskTCBBuffer, StackType_t **ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize) This function is used to provide a statically allocated block of memory to FreeRTOS to hold the Timer Task TCB. This function is required when configSUPPORT_STATIC_ALLOCATION is set. For more information see this URI: https://www.FreeRTOS.org/a00110.html#configSUPPORT_STATIC_ALLOCATION Parameters ppxTimerTaskTCBBuffer -- A handle to a statically allocated TCB buffer ppxTimerTaskStackBuffer -- A handle to a statically allocated Stack buffer for the idle task pulTimerTaskStackSize -- A pointer to the number of elements that will fit in the allocated stack buffer ppxTimerTaskTCBBuffer -- A handle to a statically allocated TCB buffer ppxTimerTaskStackBuffer -- A handle to a statically allocated Stack buffer for the idle task pulTimerTaskStackSize -- A pointer to the number of elements that will fit in the allocated stack buffer ppxTimerTaskTCBBuffer -- A handle to a statically allocated TCB buffer Parameters ppxTimerTaskTCBBuffer -- A handle to a statically allocated TCB buffer ppxTimerTaskStackBuffer -- A handle to a statically allocated Stack buffer for the idle task pulTimerTaskStackSize -- A pointer to the number of elements that will fit in the allocated stack buffer Macros xTimerStart(xTimer, xTicksToWait) Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API functions send commands to the timer service task through a queue called the timer command queue. The timer command queue is private to the kernel itself and is not directly accessible to application code. The length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant. xTimerStart() starts a timer that was previously created using the xTimerCreate() API function. If the timer had already been started and was already in the active state, then xTimerStart() has equivalent functionality to the xTimerReset() API function. Starting a timer ensures the timer is in the active state. If the timer is not stopped, deleted, or reset in the mean time, the callback function associated with the timer will get called 'n' ticks after xTimerStart() was called, where 'n' is the timers defined period. It is valid to call xTimerStart() before the scheduler has been started, but when this is done the timer will not actually start until the scheduler is started, and the timers expiry time will be relative to when the scheduler is started, not relative to when xTimerStart() was called. The configUSE_TIMERS configuration constant must be set to 1 for xTimerStart() to be available. Example usage: See the xTimerCreate() API function example usage scenario. Parameters xTimer -- The handle of the timer being started/restarted. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the start command to be successfully sent to the timer command queue, should the queue already be full when xTimerStart() was called. xTicksToWait is ignored if xTimerStart() is called before the scheduler is started. xTimer -- The handle of the timer being started/restarted. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the start command to be successfully sent to the timer command queue, should the queue already be full when xTimerStart() was called. xTicksToWait is ignored if xTimerStart() is called before the scheduler is started. xTimer -- The handle of the timer being started/restarted. Returns pdFAIL will be returned if the start command could not be sent to the timer command queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system, although the timers expiry time is relative to when xTimerStart() is actually called. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. Parameters xTimer -- The handle of the timer being started/restarted. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the start command to be successfully sent to the timer command queue, should the queue already be full when xTimerStart() was called. xTicksToWait is ignored if xTimerStart() is called before the scheduler is started. Returns pdFAIL will be returned if the start command could not be sent to the timer command queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system, although the timers expiry time is relative to when xTimerStart() is actually called. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. xTimerStop(xTimer, xTicksToWait) Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API functions send commands to the timer service task through a queue called the timer command queue. The timer command queue is private to the kernel itself and is not directly accessible to application code. The length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant. xTimerStop() stops a timer that was previously started using either of the The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() or xTimerChangePeriodFromISR() API functions. Stopping a timer ensures the timer is not in the active state. The configUSE_TIMERS configuration constant must be set to 1 for xTimerStop() to be available. Example usage: See the xTimerCreate() API function example usage scenario. Parameters xTimer -- The handle of the timer being stopped. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the stop command to be successfully sent to the timer command queue, should the queue already be full when xTimerStop() was called. xTicksToWait is ignored if xTimerStop() is called before the scheduler is started. xTimer -- The handle of the timer being stopped. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the stop command to be successfully sent to the timer command queue, should the queue already be full when xTimerStop() was called. xTicksToWait is ignored if xTimerStop() is called before the scheduler is started. xTimer -- The handle of the timer being stopped. Returns pdFAIL will be returned if the stop command could not be sent to the timer command queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. Parameters xTimer -- The handle of the timer being stopped. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the stop command to be successfully sent to the timer command queue, should the queue already be full when xTimerStop() was called. xTicksToWait is ignored if xTimerStop() is called before the scheduler is started. Returns pdFAIL will be returned if the stop command could not be sent to the timer command queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. xTimerChangePeriod(xTimer, xNewPeriod, xTicksToWait) Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API functions send commands to the timer service task through a queue called the timer command queue. The timer command queue is private to the kernel itself and is not directly accessible to application code. The length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant. xTimerChangePeriod() changes the period of a timer that was previously created using the xTimerCreate() API function. xTimerChangePeriod() can be called to change the period of an active or dormant state timer. The configUSE_TIMERS configuration constant must be set to 1 for xTimerChangePeriod() to be available. Example usage: * // This function assumes xTimer has already been created. If the timer * // referenced by xTimer is already active when it is called, then the timer * // is deleted. If the timer referenced by xTimer is not active when it is * // called, then the period of the timer is set to 500ms and the timer is * // started. * void vAFunction( TimerHandle_t xTimer ) * { * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" * { * // xTimer is already active - delete it. * xTimerDelete( xTimer ); * } * else * { * // xTimer is not active, change its period to 500ms. This will also * // cause the timer to start. Block for a maximum of 100 ticks if the * // change period command cannot immediately be sent to the timer * // command queue. * if( xTimerChangePeriod( xTimer, 500 / portTICK_PERIOD_MS, 100 ) == pdPASS ) * { * // The command was successfully sent. * } * else * { * // The command could not be sent, even after waiting for 100 ticks * // to pass. Take appropriate action here. * } * } * } * Parameters xTimer -- The handle of the timer that is having its period changed. xNewPeriod -- The new period for xTimer. Timer periods are specified in tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, if the timer must expire after 500ms, then xNewPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the change period command to be successfully sent to the timer command queue, should the queue already be full when xTimerChangePeriod() was called. xTicksToWait is ignored if xTimerChangePeriod() is called before the scheduler is started. xTimer -- The handle of the timer that is having its period changed. xNewPeriod -- The new period for xTimer. Timer periods are specified in tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, if the timer must expire after 500ms, then xNewPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the change period command to be successfully sent to the timer command queue, should the queue already be full when xTimerChangePeriod() was called. xTicksToWait is ignored if xTimerChangePeriod() is called before the scheduler is started. xTimer -- The handle of the timer that is having its period changed. Returns pdFAIL will be returned if the change period command could not be sent to the timer command queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. Parameters xTimer -- The handle of the timer that is having its period changed. xNewPeriod -- The new period for xTimer. Timer periods are specified in tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, if the timer must expire after 500ms, then xNewPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the change period command to be successfully sent to the timer command queue, should the queue already be full when xTimerChangePeriod() was called. xTicksToWait is ignored if xTimerChangePeriod() is called before the scheduler is started. Returns pdFAIL will be returned if the change period command could not be sent to the timer command queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. xTimerDelete(xTimer, xTicksToWait) Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API functions send commands to the timer service task through a queue called the timer command queue. The timer command queue is private to the kernel itself and is not directly accessible to application code. The length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant. xTimerDelete() deletes a timer that was previously created using the xTimerCreate() API function. The configUSE_TIMERS configuration constant must be set to 1 for xTimerDelete() to be available. Example usage: See the xTimerChangePeriod() API function example usage scenario. Parameters xTimer -- The handle of the timer being deleted. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the delete command to be successfully sent to the timer command queue, should the queue already be full when xTimerDelete() was called. xTicksToWait is ignored if xTimerDelete() is called before the scheduler is started. xTimer -- The handle of the timer being deleted. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the delete command to be successfully sent to the timer command queue, should the queue already be full when xTimerDelete() was called. xTicksToWait is ignored if xTimerDelete() is called before the scheduler is started. xTimer -- The handle of the timer being deleted. Returns pdFAIL will be returned if the delete command could not be sent to the timer command queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. Parameters xTimer -- The handle of the timer being deleted. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the delete command to be successfully sent to the timer command queue, should the queue already be full when xTimerDelete() was called. xTicksToWait is ignored if xTimerDelete() is called before the scheduler is started. Returns pdFAIL will be returned if the delete command could not be sent to the timer command queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. xTimerReset(xTimer, xTicksToWait) Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API functions send commands to the timer service task through a queue called the timer command queue. The timer command queue is private to the kernel itself and is not directly accessible to application code. The length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant. xTimerReset() re-starts a timer that was previously created using the xTimerCreate() API function. If the timer had already been started and was already in the active state, then xTimerReset() will cause the timer to re-evaluate its expiry time so that it is relative to when xTimerReset() was called. If the timer was in the dormant state then xTimerReset() has equivalent functionality to the xTimerStart() API function. Resetting a timer ensures the timer is in the active state. If the timer is not stopped, deleted, or reset in the mean time, the callback function associated with the timer will get called 'n' ticks after xTimerReset() was called, where 'n' is the timers defined period. It is valid to call xTimerReset() before the scheduler has been started, but when this is done the timer will not actually start until the scheduler is started, and the timers expiry time will be relative to when the scheduler is started, not relative to when xTimerReset() was called. The configUSE_TIMERS configuration constant must be set to 1 for xTimerReset() to be available. Example usage: * // When a key is pressed, an LCD back-light is switched on. If 5 seconds pass * // without a key being pressed, then the LCD back-light is switched off. In * // this case, the timer is a one-shot timer. * * TimerHandle_t xBacklightTimer = NULL; * * // The callback function assigned to the one-shot timer. In this case the * // parameter is not used. * void vBacklightTimerCallback( TimerHandle_t pxTimer ) * { * // The timer expired, therefore 5 seconds must have passed since a key * // was pressed. Switch off the LCD back-light. * vSetBacklightState( BACKLIGHT_OFF ); * } * * // The key press event handler. * void vKeyPressEventHandler( char cKey ) * { * // Ensure the LCD back-light is on, then reset the timer that is * // responsible for turning the back-light off after 5 seconds of * // key inactivity. Wait 10 ticks for the command to be successfully sent * // if it cannot be sent immediately. * vSetBacklightState( BACKLIGHT_ON ); * if( xTimerReset( xBacklightTimer, 100 ) != pdPASS ) * { * // The reset command was not executed successfully. Take appropriate * // action here. * } * * // Perform the rest of the key processing here. * } * * void main( void ) * { * int32_t x; * * // Create then start the one-shot timer that is responsible for turning * // the back-light off if no keys are pressed within a 5 second period. * xBacklightTimer = xTimerCreate( "BacklightTimer", // Just a text name, not used by the kernel. * ( 5000 / portTICK_PERIOD_MS), // The timer period in ticks. * pdFALSE, // The timer is a one-shot timer. * 0, // The id is not used by the callback so can take any value. * vBacklightTimerCallback // The callback function that switches the LCD back-light off. * ); * * if( xBacklightTimer == NULL ) * { * // The timer was not created. * } * else * { * // Start the timer. No block time is specified, and even if one was * // it would be ignored because the scheduler has not yet been * // started. * if( xTimerStart( xBacklightTimer, 0 ) != pdPASS ) * { * // The timer could not be set into the Active state. * } * } * * // ... * // Create tasks here. * // ... * * // Starting the scheduler will start the timer running as it has already * // been set into the active state. * vTaskStartScheduler(); * * // Should not reach here. * for( ;; ); * } * Parameters xTimer -- The handle of the timer being reset/started/restarted. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the reset command to be successfully sent to the timer command queue, should the queue already be full when xTimerReset() was called. xTicksToWait is ignored if xTimerReset() is called before the scheduler is started. xTimer -- The handle of the timer being reset/started/restarted. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the reset command to be successfully sent to the timer command queue, should the queue already be full when xTimerReset() was called. xTicksToWait is ignored if xTimerReset() is called before the scheduler is started. xTimer -- The handle of the timer being reset/started/restarted. Returns pdFAIL will be returned if the reset command could not be sent to the timer command queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system, although the timers expiry time is relative to when xTimerStart() is actually called. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. Parameters xTimer -- The handle of the timer being reset/started/restarted. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the reset command to be successfully sent to the timer command queue, should the queue already be full when xTimerReset() was called. xTicksToWait is ignored if xTimerReset() is called before the scheduler is started. Returns pdFAIL will be returned if the reset command could not be sent to the timer command queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system, although the timers expiry time is relative to when xTimerStart() is actually called. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. xTimerStartFromISR(xTimer, pxHigherPriorityTaskWoken) A version of xTimerStart() that can be called from an interrupt service routine. Example usage: * // This scenario assumes xBacklightTimer has already been created. When a * // key is pressed, an LCD back-light is switched on. If 5 seconds pass * // without a key being pressed, then the LCD back-light is switched off. In * // this case, the timer is a one-shot timer, and unlike the example given for * // the xTimerReset() function, the key press event handler is an interrupt * // service routine. * * // The callback function assigned to the one-shot timer. In this case the * // parameter is not used. * void vBacklightTimerCallback( TimerHandle_t pxTimer ) * { * // The timer expired, therefore 5 seconds must have passed since a key * // was pressed. Switch off the LCD back-light. * vSetBacklightState( BACKLIGHT_OFF ); * } * * // The key press interrupt service routine. * void vKeyPressEventInterruptHandler( void ) * { * BaseType_t xHigherPriorityTaskWoken = pdFALSE; * * // Ensure the LCD back-light is on, then restart the timer that is * // responsible for turning the back-light off after 5 seconds of * // key inactivity. This is an interrupt service routine so can only * // call FreeRTOS API functions that end in "FromISR". * vSetBacklightState( BACKLIGHT_ON ); * * // xTimerStartFromISR() or xTimerResetFromISR() could be called here * // as both cause the timer to re-calculate its expiry time. * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was * // declared (in this function). * if( xTimerStartFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) * { * // The start command was not executed successfully. Take appropriate * // action here. * } * * // Perform the rest of the key processing here. * * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch * // should be performed. The syntax required to perform a context switch * // from inside an ISR varies from port to port, and from compiler to * // compiler. Inspect the demos for the port you are using to find the * // actual syntax required. * if( xHigherPriorityTaskWoken != pdFALSE ) * { * // Call the interrupt safe yield function here (actual function * // depends on the FreeRTOS port being used). * } * } * Parameters xTimer -- The handle of the timer being started/restarted. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerStartFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/daemon task out of the Blocked state. If calling xTimerStartFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/ daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerStartFromISR() function. If xTimerStartFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. xTimer -- The handle of the timer being started/restarted. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerStartFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/daemon task out of the Blocked state. If calling xTimerStartFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/ daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerStartFromISR() function. If xTimerStartFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. xTimer -- The handle of the timer being started/restarted. Returns pdFAIL will be returned if the start command could not be sent to the timer command queue. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system, although the timers expiry time is relative to when xTimerStartFromISR() is actually called. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. Parameters xTimer -- The handle of the timer being started/restarted. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerStartFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/daemon task out of the Blocked state. If calling xTimerStartFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/ daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerStartFromISR() function. If xTimerStartFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. Returns pdFAIL will be returned if the start command could not be sent to the timer command queue. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system, although the timers expiry time is relative to when xTimerStartFromISR() is actually called. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. xTimerStopFromISR(xTimer, pxHigherPriorityTaskWoken) A version of xTimerStop() that can be called from an interrupt service routine. Example usage: * // This scenario assumes xTimer has already been created and started. When * // an interrupt occurs, the timer should be simply stopped. * * // The interrupt service routine that stops the timer. * void vAnExampleInterruptServiceRoutine( void ) * { * BaseType_t xHigherPriorityTaskWoken = pdFALSE; * * // The interrupt has occurred - simply stop the timer. * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined * // (within this function). As this is an interrupt service routine, only * // FreeRTOS API functions that end in "FromISR" can be used. * if( xTimerStopFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) * { * // The stop command was not executed successfully. Take appropriate * // action here. * } * * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch * // should be performed. The syntax required to perform a context switch * // from inside an ISR varies from port to port, and from compiler to * // compiler. Inspect the demos for the port you are using to find the * // actual syntax required. * if( xHigherPriorityTaskWoken != pdFALSE ) * { * // Call the interrupt safe yield function here (actual function * // depends on the FreeRTOS port being used). * } * } * Parameters xTimer -- The handle of the timer being stopped. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerStopFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/daemon task out of the Blocked state. If calling xTimerStopFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/ daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerStopFromISR() function. If xTimerStopFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. xTimer -- The handle of the timer being stopped. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerStopFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/daemon task out of the Blocked state. If calling xTimerStopFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/ daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerStopFromISR() function. If xTimerStopFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. xTimer -- The handle of the timer being stopped. Returns pdFAIL will be returned if the stop command could not be sent to the timer command queue. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. Parameters xTimer -- The handle of the timer being stopped. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerStopFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/daemon task out of the Blocked state. If calling xTimerStopFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/ daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerStopFromISR() function. If xTimerStopFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. Returns pdFAIL will be returned if the stop command could not be sent to the timer command queue. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. xTimerChangePeriodFromISR(xTimer, xNewPeriod, pxHigherPriorityTaskWoken) A version of xTimerChangePeriod() that can be called from an interrupt service routine. Example usage: * // This scenario assumes xTimer has already been created and started. When * // an interrupt occurs, the period of xTimer should be changed to 500ms. * * // The interrupt service routine that changes the period of xTimer. * void vAnExampleInterruptServiceRoutine( void ) * { * BaseType_t xHigherPriorityTaskWoken = pdFALSE; * * // The interrupt has occurred - change the period of xTimer to 500ms. * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined * // (within this function). As this is an interrupt service routine, only * // FreeRTOS API functions that end in "FromISR" can be used. * if( xTimerChangePeriodFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) * { * // The command to change the timers period was not executed * // successfully. Take appropriate action here. * } * * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch * // should be performed. The syntax required to perform a context switch * // from inside an ISR varies from port to port, and from compiler to * // compiler. Inspect the demos for the port you are using to find the * // actual syntax required. * if( xHigherPriorityTaskWoken != pdFALSE ) * { * // Call the interrupt safe yield function here (actual function * // depends on the FreeRTOS port being used). * } * } * Parameters xTimer -- The handle of the timer that is having its period changed. xNewPeriod -- The new period for xTimer. Timer periods are specified in tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, if the timer must expire after 500ms, then xNewPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerChangePeriodFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/ daemon task out of the Blocked state. If calling xTimerChangePeriodFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerChangePeriodFromISR() function. If xTimerChangePeriodFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. xTimer -- The handle of the timer that is having its period changed. xNewPeriod -- The new period for xTimer. Timer periods are specified in tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, if the timer must expire after 500ms, then xNewPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerChangePeriodFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/ daemon task out of the Blocked state. If calling xTimerChangePeriodFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerChangePeriodFromISR() function. If xTimerChangePeriodFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. xTimer -- The handle of the timer that is having its period changed. Returns pdFAIL will be returned if the command to change the timers period could not be sent to the timer command queue. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. Parameters xTimer -- The handle of the timer that is having its period changed. xNewPeriod -- The new period for xTimer. Timer periods are specified in tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, if the timer must expire after 500ms, then xNewPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerChangePeriodFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/ daemon task out of the Blocked state. If calling xTimerChangePeriodFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerChangePeriodFromISR() function. If xTimerChangePeriodFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. Returns pdFAIL will be returned if the command to change the timers period could not be sent to the timer command queue. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. xTimerResetFromISR(xTimer, pxHigherPriorityTaskWoken) A version of xTimerReset() that can be called from an interrupt service routine. Example usage: * // This scenario assumes xBacklightTimer has already been created. When a * // key is pressed, an LCD back-light is switched on. If 5 seconds pass * // without a key being pressed, then the LCD back-light is switched off. In * // this case, the timer is a one-shot timer, and unlike the example given for * // the xTimerReset() function, the key press event handler is an interrupt * // service routine. * * // The callback function assigned to the one-shot timer. In this case the * // parameter is not used. * void vBacklightTimerCallback( TimerHandle_t pxTimer ) * { * // The timer expired, therefore 5 seconds must have passed since a key * // was pressed. Switch off the LCD back-light. * vSetBacklightState( BACKLIGHT_OFF ); * } * * // The key press interrupt service routine. * void vKeyPressEventInterruptHandler( void ) * { * BaseType_t xHigherPriorityTaskWoken = pdFALSE; * * // Ensure the LCD back-light is on, then reset the timer that is * // responsible for turning the back-light off after 5 seconds of * // key inactivity. This is an interrupt service routine so can only * // call FreeRTOS API functions that end in "FromISR". * vSetBacklightState( BACKLIGHT_ON ); * * // xTimerStartFromISR() or xTimerResetFromISR() could be called here * // as both cause the timer to re-calculate its expiry time. * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was * // declared (in this function). * if( xTimerResetFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) * { * // The reset command was not executed successfully. Take appropriate * // action here. * } * * // Perform the rest of the key processing here. * * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch * // should be performed. The syntax required to perform a context switch * // from inside an ISR varies from port to port, and from compiler to * // compiler. Inspect the demos for the port you are using to find the * // actual syntax required. * if( xHigherPriorityTaskWoken != pdFALSE ) * { * // Call the interrupt safe yield function here (actual function * // depends on the FreeRTOS port being used). * } * } * Parameters xTimer -- The handle of the timer that is to be started, reset, or restarted. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerResetFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/daemon task out of the Blocked state. If calling xTimerResetFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/ daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerResetFromISR() function. If xTimerResetFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. xTimer -- The handle of the timer that is to be started, reset, or restarted. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerResetFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/daemon task out of the Blocked state. If calling xTimerResetFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/ daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerResetFromISR() function. If xTimerResetFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. xTimer -- The handle of the timer that is to be started, reset, or restarted. Returns pdFAIL will be returned if the reset command could not be sent to the timer command queue. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system, although the timers expiry time is relative to when xTimerResetFromISR() is actually called. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. Parameters xTimer -- The handle of the timer that is to be started, reset, or restarted. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerResetFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/daemon task out of the Blocked state. If calling xTimerResetFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/ daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerResetFromISR() function. If xTimerResetFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. Returns pdFAIL will be returned if the reset command could not be sent to the timer command queue. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system, although the timers expiry time is relative to when xTimerResetFromISR() is actually called. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. Type Definitions typedef struct tmrTimerControl *TimerHandle_t typedef void (*TimerCallbackFunction_t)(TimerHandle_t xTimer) Defines the prototype to which timer callback functions must conform. typedef void (*PendedFunction_t)(void*, uint32_t) Defines the prototype to which functions used with the xTimerPendFunctionCallFromISR() function must conform. Event Group API Header File components/freertos/FreeRTOS-Kernel/include/freertos/event_groups.h This header file can be included with: #include "freertos/event_groups.h" Functions EventGroupHandle_t xEventGroupCreate(void) Create a new event group. Internally, within the FreeRTOS implementation, event groups use a [small] block of memory, in which the event group's structure is stored. If an event groups is created using xEventGroupCreate() then the required memory is automatically dynamically allocated inside the xEventGroupCreate() function. (see https://www.FreeRTOS.org/a00111.html). If an event group is created using xEventGroupCreateStatic() then the application writer must instead provide the memory that will get used by the event group. xEventGroupCreateStatic() therefore allows an event group to be created without using any dynamic memory allocation. Although event groups are not related to ticks, for internal implementation reasons the number of bits available for use in an event group is dependent on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store event bits within an event group. Example usage: // Declare a variable to hold the created event group. EventGroupHandle_t xCreatedEventGroup; // Attempt to create the event group. xCreatedEventGroup = xEventGroupCreate(); // Was the event group created successfully? if( xCreatedEventGroup == NULL ) { // The event group was not created because there was insufficient // FreeRTOS heap available. } else { // The event group was created. } Returns If the event group was created then a handle to the event group is returned. If there was insufficient FreeRTOS heap available to create the event group then NULL is returned. See https://www.FreeRTOS.org/a00111.html Returns If the event group was created then a handle to the event group is returned. If there was insufficient FreeRTOS heap available to create the event group then NULL is returned. See https://www.FreeRTOS.org/a00111.html EventGroupHandle_t xEventGroupCreateStatic(StaticEventGroup_t *pxEventGroupBuffer) Create a new event group. Internally, within the FreeRTOS implementation, event groups use a [small] block of memory, in which the event group's structure is stored. If an event groups is created using xEventGroupCreate() then the required memory is automatically dynamically allocated inside the xEventGroupCreate() function. (see https://www.FreeRTOS.org/a00111.html). If an event group is created using xEventGroupCreateStatic() then the application writer must instead provide the memory that will get used by the event group. xEventGroupCreateStatic() therefore allows an event group to be created without using any dynamic memory allocation. Although event groups are not related to ticks, for internal implementation reasons the number of bits available for use in an event group is dependent on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store event bits within an event group. Example usage: // StaticEventGroup_t is a publicly accessible structure that has the same // size and alignment requirements as the real event group structure. It is // provided as a mechanism for applications to know the size of the event // group (which is dependent on the architecture and configuration file // settings) without breaking the strict data hiding policy by exposing the // real event group internals. This StaticEventGroup_t variable is passed // into the xSemaphoreCreateEventGroupStatic() function and is used to store // the event group's data structures StaticEventGroup_t xEventGroupBuffer; // Create the event group without dynamically allocating any memory. xEventGroup = xEventGroupCreateStatic( &xEventGroupBuffer ); Parameters pxEventGroupBuffer -- pxEventGroupBuffer must point to a variable of type StaticEventGroup_t, which will be then be used to hold the event group's data structures, removing the need for the memory to be allocated dynamically. Returns If the event group was created then a handle to the event group is returned. If pxEventGroupBuffer was NULL then NULL is returned. Parameters pxEventGroupBuffer -- pxEventGroupBuffer must point to a variable of type StaticEventGroup_t, which will be then be used to hold the event group's data structures, removing the need for the memory to be allocated dynamically. Returns If the event group was created then a handle to the event group is returned. If pxEventGroupBuffer was NULL then NULL is returned. EventBits_t xEventGroupWaitBits(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait) [Potentially] block to wait for one or more bits to be set within a previously created event group. This function cannot be called from an interrupt. Example usage: #define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) void aFunction( EventGroupHandle_t xEventGroup ) { EventBits_t uxBits; const TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS; // Wait a maximum of 100ms for either bit 0 or bit 4 to be set within // the event group. Clear the bits before exiting. uxBits = xEventGroupWaitBits( xEventGroup, // The event group being tested. BIT_0 | BIT_4, // The bits within the event group to wait for. pdTRUE, // BIT_0 and BIT_4 should be cleared before returning. pdFALSE, // Don't wait for both bits, either bit will do. xTicksToWait ); // Wait a maximum of 100ms for either bit to be set. if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) ) { // xEventGroupWaitBits() returned because both bits were set. } else if( ( uxBits & BIT_0 ) != 0 ) { // xEventGroupWaitBits() returned because just BIT_0 was set. } else if( ( uxBits & BIT_4 ) != 0 ) { // xEventGroupWaitBits() returned because just BIT_4 was set. } else { // xEventGroupWaitBits() returned because xTicksToWait ticks passed // without either BIT_0 or BIT_4 becoming set. } } Parameters xEventGroup -- The event group in which the bits are being tested. The event group must have previously been created using a call to xEventGroupCreate(). uxBitsToWaitFor -- A bitwise value that indicates the bit or bits to test inside the event group. For example, to wait for bit 0 and/or bit 2 set uxBitsToWaitFor to 0x05. To wait for bits 0 and/or bit 1 and/or bit 2 set uxBitsToWaitFor to 0x07. Etc. xClearOnExit -- If xClearOnExit is set to pdTRUE then any bits within uxBitsToWaitFor that are set within the event group will be cleared before xEventGroupWaitBits() returns if the wait condition was met (if the function returns for a reason other than a timeout). If xClearOnExit is set to pdFALSE then the bits set in the event group are not altered when the call to xEventGroupWaitBits() returns. xWaitForAllBits -- If xWaitForAllBits is set to pdTRUE then xEventGroupWaitBits() will return when either all the bits in uxBitsToWaitFor are set or the specified block time expires. If xWaitForAllBits is set to pdFALSE then xEventGroupWaitBits() will return when any one of the bits set in uxBitsToWaitFor is set or the specified block time expires. The block time is specified by the xTicksToWait parameter. xTicksToWait -- The maximum amount of time (specified in 'ticks') to wait for one/all (depending on the xWaitForAllBits value) of the bits specified by uxBitsToWaitFor to become set. A value of portMAX_DELAY can be used to block indefinitely (provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). xEventGroup -- The event group in which the bits are being tested. The event group must have previously been created using a call to xEventGroupCreate(). uxBitsToWaitFor -- A bitwise value that indicates the bit or bits to test inside the event group. For example, to wait for bit 0 and/or bit 2 set uxBitsToWaitFor to 0x05. To wait for bits 0 and/or bit 1 and/or bit 2 set uxBitsToWaitFor to 0x07. Etc. xClearOnExit -- If xClearOnExit is set to pdTRUE then any bits within uxBitsToWaitFor that are set within the event group will be cleared before xEventGroupWaitBits() returns if the wait condition was met (if the function returns for a reason other than a timeout). If xClearOnExit is set to pdFALSE then the bits set in the event group are not altered when the call to xEventGroupWaitBits() returns. xWaitForAllBits -- If xWaitForAllBits is set to pdTRUE then xEventGroupWaitBits() will return when either all the bits in uxBitsToWaitFor are set or the specified block time expires. If xWaitForAllBits is set to pdFALSE then xEventGroupWaitBits() will return when any one of the bits set in uxBitsToWaitFor is set or the specified block time expires. The block time is specified by the xTicksToWait parameter. xTicksToWait -- The maximum amount of time (specified in 'ticks') to wait for one/all (depending on the xWaitForAllBits value) of the bits specified by uxBitsToWaitFor to become set. A value of portMAX_DELAY can be used to block indefinitely (provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). xEventGroup -- The event group in which the bits are being tested. The event group must have previously been created using a call to xEventGroupCreate(). Returns The value of the event group at the time either the bits being waited for became set, or the block time expired. Test the return value to know which bits were set. If xEventGroupWaitBits() returned because its timeout expired then not all the bits being waited for will be set. If xEventGroupWaitBits() returned because the bits it was waiting for were set then the returned value is the event group value before any bits were automatically cleared in the case that xClearOnExit parameter was set to pdTRUE. Parameters xEventGroup -- The event group in which the bits are being tested. The event group must have previously been created using a call to xEventGroupCreate(). uxBitsToWaitFor -- A bitwise value that indicates the bit or bits to test inside the event group. For example, to wait for bit 0 and/or bit 2 set uxBitsToWaitFor to 0x05. To wait for bits 0 and/or bit 1 and/or bit 2 set uxBitsToWaitFor to 0x07. Etc. xClearOnExit -- If xClearOnExit is set to pdTRUE then any bits within uxBitsToWaitFor that are set within the event group will be cleared before xEventGroupWaitBits() returns if the wait condition was met (if the function returns for a reason other than a timeout). If xClearOnExit is set to pdFALSE then the bits set in the event group are not altered when the call to xEventGroupWaitBits() returns. xWaitForAllBits -- If xWaitForAllBits is set to pdTRUE then xEventGroupWaitBits() will return when either all the bits in uxBitsToWaitFor are set or the specified block time expires. If xWaitForAllBits is set to pdFALSE then xEventGroupWaitBits() will return when any one of the bits set in uxBitsToWaitFor is set or the specified block time expires. The block time is specified by the xTicksToWait parameter. xTicksToWait -- The maximum amount of time (specified in 'ticks') to wait for one/all (depending on the xWaitForAllBits value) of the bits specified by uxBitsToWaitFor to become set. A value of portMAX_DELAY can be used to block indefinitely (provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). Returns The value of the event group at the time either the bits being waited for became set, or the block time expired. Test the return value to know which bits were set. If xEventGroupWaitBits() returned because its timeout expired then not all the bits being waited for will be set. If xEventGroupWaitBits() returned because the bits it was waiting for were set then the returned value is the event group value before any bits were automatically cleared in the case that xClearOnExit parameter was set to pdTRUE. EventBits_t xEventGroupClearBits(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear) Clear bits within an event group. This function cannot be called from an interrupt. Example usage: #define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) void aFunction( EventGroupHandle_t xEventGroup ) { EventBits_t uxBits; // Clear bit 0 and bit 4 in xEventGroup. uxBits = xEventGroupClearBits( xEventGroup, // The event group being updated. BIT_0 | BIT_4 );// The bits being cleared. if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) ) { // Both bit 0 and bit 4 were set before xEventGroupClearBits() was // called. Both will now be clear (not set). } else if( ( uxBits & BIT_0 ) != 0 ) { // Bit 0 was set before xEventGroupClearBits() was called. It will // now be clear. } else if( ( uxBits & BIT_4 ) != 0 ) { // Bit 4 was set before xEventGroupClearBits() was called. It will // now be clear. } else { // Neither bit 0 nor bit 4 were set in the first place. } } Parameters xEventGroup -- The event group in which the bits are to be cleared. uxBitsToClear -- A bitwise value that indicates the bit or bits to clear in the event group. For example, to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3 and bit 0 set uxBitsToClear to 0x09. xEventGroup -- The event group in which the bits are to be cleared. uxBitsToClear -- A bitwise value that indicates the bit or bits to clear in the event group. For example, to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3 and bit 0 set uxBitsToClear to 0x09. xEventGroup -- The event group in which the bits are to be cleared. Returns The value of the event group before the specified bits were cleared. Parameters xEventGroup -- The event group in which the bits are to be cleared. uxBitsToClear -- A bitwise value that indicates the bit or bits to clear in the event group. For example, to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3 and bit 0 set uxBitsToClear to 0x09. Returns The value of the event group before the specified bits were cleared. EventBits_t xEventGroupSetBits(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet) Set bits within an event group. This function cannot be called from an interrupt. xEventGroupSetBitsFromISR() is a version that can be called from an interrupt. Setting bits in an event group will automatically unblock tasks that are blocked waiting for the bits. Example usage: #define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) void aFunction( EventGroupHandle_t xEventGroup ) { EventBits_t uxBits; // Set bit 0 and bit 4 in xEventGroup. uxBits = xEventGroupSetBits( xEventGroup, // The event group being updated. BIT_0 | BIT_4 );// The bits being set. if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) ) { // Both bit 0 and bit 4 remained set when the function returned. } else if( ( uxBits & BIT_0 ) != 0 ) { // Bit 0 remained set when the function returned, but bit 4 was // cleared. It might be that bit 4 was cleared automatically as a // task that was waiting for bit 4 was removed from the Blocked // state. } else if( ( uxBits & BIT_4 ) != 0 ) { // Bit 4 remained set when the function returned, but bit 0 was // cleared. It might be that bit 0 was cleared automatically as a // task that was waiting for bit 0 was removed from the Blocked // state. } else { // Neither bit 0 nor bit 4 remained set. It might be that a task // was waiting for both of the bits to be set, and the bits were // cleared as the task left the Blocked state. } } Parameters xEventGroup -- The event group in which the bits are to be set. uxBitsToSet -- A bitwise value that indicates the bit or bits to set. For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 and bit 0 set uxBitsToSet to 0x09. xEventGroup -- The event group in which the bits are to be set. uxBitsToSet -- A bitwise value that indicates the bit or bits to set. For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 and bit 0 set uxBitsToSet to 0x09. xEventGroup -- The event group in which the bits are to be set. Returns The value of the event group at the time the call to xEventGroupSetBits() returns. There are two reasons why the returned value might have the bits specified by the uxBitsToSet parameter cleared. First, if setting a bit results in a task that was waiting for the bit leaving the blocked state then it is possible the bit will be cleared automatically (see the xClearBitOnExit parameter of xEventGroupWaitBits()). Second, any unblocked (or otherwise Ready state) task that has a priority above that of the task that called xEventGroupSetBits() will execute and may change the event group value before the call to xEventGroupSetBits() returns. Parameters xEventGroup -- The event group in which the bits are to be set. uxBitsToSet -- A bitwise value that indicates the bit or bits to set. For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 and bit 0 set uxBitsToSet to 0x09. Returns The value of the event group at the time the call to xEventGroupSetBits() returns. There are two reasons why the returned value might have the bits specified by the uxBitsToSet parameter cleared. First, if setting a bit results in a task that was waiting for the bit leaving the blocked state then it is possible the bit will be cleared automatically (see the xClearBitOnExit parameter of xEventGroupWaitBits()). Second, any unblocked (or otherwise Ready state) task that has a priority above that of the task that called xEventGroupSetBits() will execute and may change the event group value before the call to xEventGroupSetBits() returns. EventBits_t xEventGroupSync(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, const EventBits_t uxBitsToWaitFor, TickType_t xTicksToWait) Atomically set bits within an event group, then wait for a combination of bits to be set within the same event group. This functionality is typically used to synchronise multiple tasks, where each task has to wait for the other tasks to reach a synchronisation point before proceeding. This function cannot be used from an interrupt. The function will return before its block time expires if the bits specified by the uxBitsToWait parameter are set, or become set within that time. In this case all the bits specified by uxBitsToWait will be automatically cleared before the function returns. Example usage: // Bits used by the three tasks. #define TASK_0_BIT ( 1 << 0 ) #define TASK_1_BIT ( 1 << 1 ) #define TASK_2_BIT ( 1 << 2 ) #define ALL_SYNC_BITS ( TASK_0_BIT | TASK_1_BIT | TASK_2_BIT ) // Use an event group to synchronise three tasks. It is assumed this event // group has already been created elsewhere. EventGroupHandle_t xEventBits; void vTask0( void *pvParameters ) { EventBits_t uxReturn; TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS; for( ;; ) { // Perform task functionality here. // Set bit 0 in the event flag to note this task has reached the // sync point. The other two tasks will set the other two bits defined // by ALL_SYNC_BITS. All three tasks have reached the synchronisation // point when all the ALL_SYNC_BITS are set. Wait a maximum of 100ms // for this to happen. uxReturn = xEventGroupSync( xEventBits, TASK_0_BIT, ALL_SYNC_BITS, xTicksToWait ); if( ( uxReturn & ALL_SYNC_BITS ) == ALL_SYNC_BITS ) { // All three tasks reached the synchronisation point before the call // to xEventGroupSync() timed out. } } } void vTask1( void *pvParameters ) { for( ;; ) { // Perform task functionality here. // Set bit 1 in the event flag to note this task has reached the // synchronisation point. The other two tasks will set the other two // bits defined by ALL_SYNC_BITS. All three tasks have reached the // synchronisation point when all the ALL_SYNC_BITS are set. Wait // indefinitely for this to happen. xEventGroupSync( xEventBits, TASK_1_BIT, ALL_SYNC_BITS, portMAX_DELAY ); // xEventGroupSync() was called with an indefinite block time, so // this task will only reach here if the synchronisation was made by all // three tasks, so there is no need to test the return value. } } void vTask2( void *pvParameters ) { for( ;; ) { // Perform task functionality here. // Set bit 2 in the event flag to note this task has reached the // synchronisation point. The other two tasks will set the other two // bits defined by ALL_SYNC_BITS. All three tasks have reached the // synchronisation point when all the ALL_SYNC_BITS are set. Wait // indefinitely for this to happen. xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY ); // xEventGroupSync() was called with an indefinite block time, so // this task will only reach here if the synchronisation was made by all // three tasks, so there is no need to test the return value. } } Parameters xEventGroup -- The event group in which the bits are being tested. The event group must have previously been created using a call to xEventGroupCreate(). uxBitsToSet -- The bits to set in the event group before determining if, and possibly waiting for, all the bits specified by the uxBitsToWait parameter are set. uxBitsToWaitFor -- A bitwise value that indicates the bit or bits to test inside the event group. For example, to wait for bit 0 and bit 2 set uxBitsToWaitFor to 0x05. To wait for bits 0 and bit 1 and bit 2 set uxBitsToWaitFor to 0x07. Etc. xTicksToWait -- The maximum amount of time (specified in 'ticks') to wait for all of the bits specified by uxBitsToWaitFor to become set. xEventGroup -- The event group in which the bits are being tested. The event group must have previously been created using a call to xEventGroupCreate(). uxBitsToSet -- The bits to set in the event group before determining if, and possibly waiting for, all the bits specified by the uxBitsToWait parameter are set. uxBitsToWaitFor -- A bitwise value that indicates the bit or bits to test inside the event group. For example, to wait for bit 0 and bit 2 set uxBitsToWaitFor to 0x05. To wait for bits 0 and bit 1 and bit 2 set uxBitsToWaitFor to 0x07. Etc. xTicksToWait -- The maximum amount of time (specified in 'ticks') to wait for all of the bits specified by uxBitsToWaitFor to become set. xEventGroup -- The event group in which the bits are being tested. The event group must have previously been created using a call to xEventGroupCreate(). Returns The value of the event group at the time either the bits being waited for became set, or the block time expired. Test the return value to know which bits were set. If xEventGroupSync() returned because its timeout expired then not all the bits being waited for will be set. If xEventGroupSync() returned because all the bits it was waiting for were set then the returned value is the event group value before any bits were automatically cleared. Parameters xEventGroup -- The event group in which the bits are being tested. The event group must have previously been created using a call to xEventGroupCreate(). uxBitsToSet -- The bits to set in the event group before determining if, and possibly waiting for, all the bits specified by the uxBitsToWait parameter are set. uxBitsToWaitFor -- A bitwise value that indicates the bit or bits to test inside the event group. For example, to wait for bit 0 and bit 2 set uxBitsToWaitFor to 0x05. To wait for bits 0 and bit 1 and bit 2 set uxBitsToWaitFor to 0x07. Etc. xTicksToWait -- The maximum amount of time (specified in 'ticks') to wait for all of the bits specified by uxBitsToWaitFor to become set. Returns The value of the event group at the time either the bits being waited for became set, or the block time expired. Test the return value to know which bits were set. If xEventGroupSync() returned because its timeout expired then not all the bits being waited for will be set. If xEventGroupSync() returned because all the bits it was waiting for were set then the returned value is the event group value before any bits were automatically cleared. EventBits_t xEventGroupGetBitsFromISR(EventGroupHandle_t xEventGroup) A version of xEventGroupGetBits() that can be called from an ISR. Parameters xEventGroup -- The event group being queried. Returns The event group bits at the time xEventGroupGetBitsFromISR() was called. Parameters xEventGroup -- The event group being queried. Returns The event group bits at the time xEventGroupGetBitsFromISR() was called. void vEventGroupDelete(EventGroupHandle_t xEventGroup) Delete an event group that was previously created by a call to xEventGroupCreate(). Tasks that are blocked on the event group will be unblocked and obtain 0 as the event group's value. Parameters xEventGroup -- The event group being deleted. Parameters xEventGroup -- The event group being deleted. BaseType_t xEventGroupGetStaticBuffer(EventGroupHandle_t xEventGroup, StaticEventGroup_t **ppxEventGroupBuffer) Retrieve a pointer to a statically created event groups's data structure buffer. It is the same buffer that is supplied at the time of creation. Parameters xEventGroup -- The event group for which to retrieve the buffer. ppxEventGroupBuffer -- Used to return a pointer to the event groups's data structure buffer. xEventGroup -- The event group for which to retrieve the buffer. ppxEventGroupBuffer -- Used to return a pointer to the event groups's data structure buffer. xEventGroup -- The event group for which to retrieve the buffer. Returns pdTRUE if the buffer was retrieved, pdFALSE otherwise. Parameters xEventGroup -- The event group for which to retrieve the buffer. ppxEventGroupBuffer -- Used to return a pointer to the event groups's data structure buffer. Returns pdTRUE if the buffer was retrieved, pdFALSE otherwise. Macros xEventGroupClearBitsFromISR(xEventGroup, uxBitsToClear) A version of xEventGroupClearBits() that can be called from an interrupt. Setting bits in an event group is not a deterministic operation because there are an unknown number of tasks that may be waiting for the bit or bits being set. FreeRTOS does not allow nondeterministic operations to be performed while interrupts are disabled, so protects event groups that are accessed from tasks by suspending the scheduler rather than disabling interrupts. As a result event groups cannot be accessed directly from an interrupt service routine. Therefore xEventGroupClearBitsFromISR() sends a message to the timer task to have the clear operation performed in the context of the timer task. Example usage: #define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) // An event group which it is assumed has already been created by a call to // xEventGroupCreate(). EventGroupHandle_t xEventGroup; void anInterruptHandler( void ) { // Clear bit 0 and bit 4 in xEventGroup. xResult = xEventGroupClearBitsFromISR( xEventGroup, // The event group being updated. BIT_0 | BIT_4 ); // The bits being set. if( xResult == pdPASS ) { // The message was posted successfully. portYIELD_FROM_ISR(pdTRUE); } } Note If this function returns pdPASS then the timer task is ready to run and a portYIELD_FROM_ISR(pdTRUE) should be executed to perform the needed clear on the event group. This behavior is different from xEventGroupSetBitsFromISR because the parameter xHigherPriorityTaskWoken is not present. Parameters xEventGroup -- The event group in which the bits are to be cleared. uxBitsToClear -- A bitwise value that indicates the bit or bits to clear. For example, to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3 and bit 0 set uxBitsToClear to 0x09. xEventGroup -- The event group in which the bits are to be cleared. uxBitsToClear -- A bitwise value that indicates the bit or bits to clear. For example, to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3 and bit 0 set uxBitsToClear to 0x09. xEventGroup -- The event group in which the bits are to be cleared. Returns If the request to execute the function was posted successfully then pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned if the timer service queue was full. Parameters xEventGroup -- The event group in which the bits are to be cleared. uxBitsToClear -- A bitwise value that indicates the bit or bits to clear. For example, to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3 and bit 0 set uxBitsToClear to 0x09. Returns If the request to execute the function was posted successfully then pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned if the timer service queue was full. xEventGroupSetBitsFromISR(xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken) A version of xEventGroupSetBits() that can be called from an interrupt. Setting bits in an event group is not a deterministic operation because there are an unknown number of tasks that may be waiting for the bit or bits being set. FreeRTOS does not allow nondeterministic operations to be performed in interrupts or from critical sections. Therefore xEventGroupSetBitsFromISR() sends a message to the timer task to have the set operation performed in the context of the timer task - where a scheduler lock is used in place of a critical section. Example usage: #define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) // An event group which it is assumed has already been created by a call to // xEventGroupCreate(). EventGroupHandle_t xEventGroup; void anInterruptHandler( void ) { BaseType_t xHigherPriorityTaskWoken, xResult; // xHigherPriorityTaskWoken must be initialised to pdFALSE. xHigherPriorityTaskWoken = pdFALSE; // Set bit 0 and bit 4 in xEventGroup. xResult = xEventGroupSetBitsFromISR( xEventGroup, // The event group being updated. BIT_0 | BIT_4 // The bits being set. &xHigherPriorityTaskWoken ); // Was the message posted successfully? if( xResult == pdPASS ) { // If xHigherPriorityTaskWoken is now set to pdTRUE then a context // switch should be requested. The macro used is port specific and // will be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - // refer to the documentation page for the port being used. portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } } Parameters xEventGroup -- The event group in which the bits are to be set. uxBitsToSet -- A bitwise value that indicates the bit or bits to set. For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 and bit 0 set uxBitsToSet to 0x09. pxHigherPriorityTaskWoken -- As mentioned above, calling this function will result in a message being sent to the timer daemon task. If the priority of the timer daemon task is higher than the priority of the currently running task (the task the interrupt interrupted) then *pxHigherPriorityTaskWoken will be set to pdTRUE by xEventGroupSetBitsFromISR(), indicating that a context switch should be requested before the interrupt exits. For that reason *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the example code below. xEventGroup -- The event group in which the bits are to be set. uxBitsToSet -- A bitwise value that indicates the bit or bits to set. For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 and bit 0 set uxBitsToSet to 0x09. pxHigherPriorityTaskWoken -- As mentioned above, calling this function will result in a message being sent to the timer daemon task. If the priority of the timer daemon task is higher than the priority of the currently running task (the task the interrupt interrupted) then *pxHigherPriorityTaskWoken will be set to pdTRUE by xEventGroupSetBitsFromISR(), indicating that a context switch should be requested before the interrupt exits. For that reason *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the example code below. xEventGroup -- The event group in which the bits are to be set. Returns If the request to execute the function was posted successfully then pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned if the timer service queue was full. Parameters xEventGroup -- The event group in which the bits are to be set. uxBitsToSet -- A bitwise value that indicates the bit or bits to set. For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 and bit 0 set uxBitsToSet to 0x09. pxHigherPriorityTaskWoken -- As mentioned above, calling this function will result in a message being sent to the timer daemon task. If the priority of the timer daemon task is higher than the priority of the currently running task (the task the interrupt interrupted) then *pxHigherPriorityTaskWoken will be set to pdTRUE by xEventGroupSetBitsFromISR(), indicating that a context switch should be requested before the interrupt exits. For that reason *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the example code below. Returns If the request to execute the function was posted successfully then pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned if the timer service queue was full. xEventGroupGetBits(xEventGroup) Returns the current value of the bits in an event group. This function cannot be used from an interrupt. Parameters xEventGroup -- The event group being queried. xEventGroup -- The event group being queried. xEventGroup -- The event group being queried. Returns The event group bits at the time xEventGroupGetBits() was called. Parameters xEventGroup -- The event group being queried. Returns The event group bits at the time xEventGroupGetBits() was called. Type Definitions typedef struct EventGroupDef_t *EventGroupHandle_t typedef TickType_t EventBits_t Stream Buffer API Header File components/freertos/FreeRTOS-Kernel/include/freertos/stream_buffer.h This header file can be included with: #include "freertos/stream_buffer.h" Functions BaseType_t xStreamBufferGetStaticBuffers(StreamBufferHandle_t xStreamBuffer, uint8_t **ppucStreamBufferStorageArea, StaticStreamBuffer_t **ppxStaticStreamBuffer) Retrieve pointers to a statically created stream buffer's data structure buffer and storage area buffer. These are the same buffers that are supplied at the time of creation. Parameters xStreamBuffer -- The stream buffer for which to retrieve the buffers. ppucStreamBufferStorageArea -- Used to return a pointer to the stream buffer's storage area buffer. ppxStaticStreamBuffer -- Used to return a pointer to the stream buffer's data structure buffer. xStreamBuffer -- The stream buffer for which to retrieve the buffers. ppucStreamBufferStorageArea -- Used to return a pointer to the stream buffer's storage area buffer. ppxStaticStreamBuffer -- Used to return a pointer to the stream buffer's data structure buffer. xStreamBuffer -- The stream buffer for which to retrieve the buffers. Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. Parameters xStreamBuffer -- The stream buffer for which to retrieve the buffers. ppucStreamBufferStorageArea -- Used to return a pointer to the stream buffer's storage area buffer. ppxStaticStreamBuffer -- Used to return a pointer to the stream buffer's data structure buffer. Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. size_t xStreamBufferSend(StreamBufferHandle_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, TickType_t xTicksToWait) Sends bytes to a stream buffer. The bytes are copied into the stream buffer. NOTE: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xStreamBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xStreamBufferReceive()) inside a critical section and set the receive block time to 0. Use xStreamBufferSend() to write to a stream buffer from a task. Use xStreamBufferSendFromISR() to write to a stream buffer from an interrupt service routine (ISR). Example use: void vAFunction( StreamBufferHandle_t xStreamBuffer ) { size_t xBytesSent; uint8_t ucArrayToSend[] = { 0, 1, 2, 3 }; char *pcStringToSend = "String to send"; const TickType_t x100ms = pdMS_TO_TICKS( 100 ); // Send an array to the stream buffer, blocking for a maximum of 100ms to // wait for enough space to be available in the stream buffer. xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms ); if( xBytesSent != sizeof( ucArrayToSend ) ) { // The call to xStreamBufferSend() times out before there was enough // space in the buffer for the data to be written, but it did // successfully write xBytesSent bytes. } // Send the string to the stream buffer. Return immediately if there is not // enough space in the buffer. xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 ); if( xBytesSent != strlen( pcStringToSend ) ) { // The entire string could not be added to the stream buffer because // there was not enough free space in the buffer, but xBytesSent bytes // were sent. Could try again to send the remaining bytes. } } Parameters xStreamBuffer -- The handle of the stream buffer to which a stream is being sent. pvTxData -- A pointer to the buffer that holds the bytes to be copied into the stream buffer. xDataLengthBytes -- The maximum number of bytes to copy from pvTxData into the stream buffer. xTicksToWait -- The maximum amount of time the task should remain in the Blocked state to wait for enough space to become available in the stream buffer, should the stream buffer contain too little space to hold the another xDataLengthBytes bytes. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. If a task times out before it can write all xDataLengthBytes into the buffer it will still write as many bytes as possible. A task does not use any CPU time when it is in the blocked state. xStreamBuffer -- The handle of the stream buffer to which a stream is being sent. pvTxData -- A pointer to the buffer that holds the bytes to be copied into the stream buffer. xDataLengthBytes -- The maximum number of bytes to copy from pvTxData into the stream buffer. xTicksToWait -- The maximum amount of time the task should remain in the Blocked state to wait for enough space to become available in the stream buffer, should the stream buffer contain too little space to hold the another xDataLengthBytes bytes. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. If a task times out before it can write all xDataLengthBytes into the buffer it will still write as many bytes as possible. A task does not use any CPU time when it is in the blocked state. xStreamBuffer -- The handle of the stream buffer to which a stream is being sent. Returns The number of bytes written to the stream buffer. If a task times out before it can write all xDataLengthBytes into the buffer it will still write as many bytes as possible. Parameters xStreamBuffer -- The handle of the stream buffer to which a stream is being sent. pvTxData -- A pointer to the buffer that holds the bytes to be copied into the stream buffer. xDataLengthBytes -- The maximum number of bytes to copy from pvTxData into the stream buffer. xTicksToWait -- The maximum amount of time the task should remain in the Blocked state to wait for enough space to become available in the stream buffer, should the stream buffer contain too little space to hold the another xDataLengthBytes bytes. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. If a task times out before it can write all xDataLengthBytes into the buffer it will still write as many bytes as possible. A task does not use any CPU time when it is in the blocked state. Returns The number of bytes written to the stream buffer. If a task times out before it can write all xDataLengthBytes into the buffer it will still write as many bytes as possible. size_t xStreamBufferSendFromISR(StreamBufferHandle_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, BaseType_t *const pxHigherPriorityTaskWoken) Interrupt safe version of the API function that sends a stream of bytes to the stream buffer. NOTE: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xStreamBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xStreamBufferReceive()) inside a critical section and set the receive block time to 0. Use xStreamBufferSend() to write to a stream buffer from a task. Use xStreamBufferSendFromISR() to write to a stream buffer from an interrupt service routine (ISR). Example use: // A stream buffer that has already been created. StreamBufferHandle_t xStreamBuffer; void vAnInterruptServiceRoutine( void ) { size_t xBytesSent; char *pcStringToSend = "String to send"; BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. // Attempt to send the string to the stream buffer. xBytesSent = xStreamBufferSendFromISR( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), &xHigherPriorityTaskWoken ); if( xBytesSent != strlen( pcStringToSend ) ) { // There was not enough free space in the stream buffer for the entire // string to be written, ut xBytesSent bytes were written. } // If xHigherPriorityTaskWoken was set to pdTRUE inside // xStreamBufferSendFromISR() then a task that has a priority above the // priority of the currently executing task was unblocked and a context // switch should be performed to ensure the ISR returns to the unblocked // task. In most FreeRTOS ports this is done by simply passing // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the // variables value, and perform the context switch if necessary. Check the // documentation for the port in use for port specific instructions. portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } Parameters xStreamBuffer -- The handle of the stream buffer to which a stream is being sent. pvTxData -- A pointer to the data that is to be copied into the stream buffer. xDataLengthBytes -- The maximum number of bytes to copy from pvTxData into the stream buffer. pxHigherPriorityTaskWoken -- It is possible that a stream buffer will have a task blocked on it waiting for data. Calling xStreamBufferSendFromISR() can make data available, and so cause a task that was waiting for data to leave the Blocked state. If calling xStreamBufferSendFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xStreamBufferSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xStreamBufferSendFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. This will ensure that the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the example code below for an example. xStreamBuffer -- The handle of the stream buffer to which a stream is being sent. pvTxData -- A pointer to the data that is to be copied into the stream buffer. xDataLengthBytes -- The maximum number of bytes to copy from pvTxData into the stream buffer. pxHigherPriorityTaskWoken -- It is possible that a stream buffer will have a task blocked on it waiting for data. Calling xStreamBufferSendFromISR() can make data available, and so cause a task that was waiting for data to leave the Blocked state. If calling xStreamBufferSendFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xStreamBufferSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xStreamBufferSendFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. This will ensure that the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the example code below for an example. xStreamBuffer -- The handle of the stream buffer to which a stream is being sent. Returns The number of bytes actually written to the stream buffer, which will be less than xDataLengthBytes if the stream buffer didn't have enough free space for all the bytes to be written. Parameters xStreamBuffer -- The handle of the stream buffer to which a stream is being sent. pvTxData -- A pointer to the data that is to be copied into the stream buffer. xDataLengthBytes -- The maximum number of bytes to copy from pvTxData into the stream buffer. pxHigherPriorityTaskWoken -- It is possible that a stream buffer will have a task blocked on it waiting for data. Calling xStreamBufferSendFromISR() can make data available, and so cause a task that was waiting for data to leave the Blocked state. If calling xStreamBufferSendFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xStreamBufferSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xStreamBufferSendFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. This will ensure that the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the example code below for an example. Returns The number of bytes actually written to the stream buffer, which will be less than xDataLengthBytes if the stream buffer didn't have enough free space for all the bytes to be written. size_t xStreamBufferReceive(StreamBufferHandle_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, TickType_t xTicksToWait) Receives bytes from a stream buffer. NOTE: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xStreamBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xStreamBufferReceive()) inside a critical section and set the receive block time to 0. Use xStreamBufferReceive() to read from a stream buffer from a task. Use xStreamBufferReceiveFromISR() to read from a stream buffer from an interrupt service routine (ISR). Example use: void vAFunction( StreamBuffer_t xStreamBuffer ) { uint8_t ucRxData[ 20 ]; size_t xReceivedBytes; const TickType_t xBlockTime = pdMS_TO_TICKS( 20 ); // Receive up to another sizeof( ucRxData ) bytes from the stream buffer. // Wait in the Blocked state (so not using any CPU processing time) for a // maximum of 100ms for the full sizeof( ucRxData ) number of bytes to be // available. xReceivedBytes = xStreamBufferReceive( xStreamBuffer, ( void * ) ucRxData, sizeof( ucRxData ), xBlockTime ); if( xReceivedBytes > 0 ) { // A ucRxData contains another xReceivedBytes bytes of data, which can // be processed here.... } } Parameters xStreamBuffer -- The handle of the stream buffer from which bytes are to be received. pvRxData -- A pointer to the buffer into which the received bytes will be copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum number of bytes to receive in one call. xStreamBufferReceive will return as many bytes as possible up to a maximum set by xBufferLengthBytes. xTicksToWait -- The maximum amount of time the task should remain in the Blocked state to wait for data to become available if the stream buffer is empty. xStreamBufferReceive() will return immediately if xTicksToWait is zero. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. A task does not use any CPU time when it is in the Blocked state. xStreamBuffer -- The handle of the stream buffer from which bytes are to be received. pvRxData -- A pointer to the buffer into which the received bytes will be copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum number of bytes to receive in one call. xStreamBufferReceive will return as many bytes as possible up to a maximum set by xBufferLengthBytes. xTicksToWait -- The maximum amount of time the task should remain in the Blocked state to wait for data to become available if the stream buffer is empty. xStreamBufferReceive() will return immediately if xTicksToWait is zero. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. A task does not use any CPU time when it is in the Blocked state. xStreamBuffer -- The handle of the stream buffer from which bytes are to be received. Returns The number of bytes actually read from the stream buffer, which will be less than xBufferLengthBytes if the call to xStreamBufferReceive() timed out before xBufferLengthBytes were available. Parameters xStreamBuffer -- The handle of the stream buffer from which bytes are to be received. pvRxData -- A pointer to the buffer into which the received bytes will be copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum number of bytes to receive in one call. xStreamBufferReceive will return as many bytes as possible up to a maximum set by xBufferLengthBytes. xTicksToWait -- The maximum amount of time the task should remain in the Blocked state to wait for data to become available if the stream buffer is empty. xStreamBufferReceive() will return immediately if xTicksToWait is zero. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. A task does not use any CPU time when it is in the Blocked state. Returns The number of bytes actually read from the stream buffer, which will be less than xBufferLengthBytes if the call to xStreamBufferReceive() timed out before xBufferLengthBytes were available. size_t xStreamBufferReceiveFromISR(StreamBufferHandle_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, BaseType_t *const pxHigherPriorityTaskWoken) An interrupt safe version of the API function that receives bytes from a stream buffer. Use xStreamBufferReceive() to read bytes from a stream buffer from a task. Use xStreamBufferReceiveFromISR() to read bytes from a stream buffer from an interrupt service routine (ISR). Example use: // A stream buffer that has already been created. StreamBuffer_t xStreamBuffer; void vAnInterruptServiceRoutine( void ) { uint8_t ucRxData[ 20 ]; size_t xReceivedBytes; BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. // Receive the next stream from the stream buffer. xReceivedBytes = xStreamBufferReceiveFromISR( xStreamBuffer, ( void * ) ucRxData, sizeof( ucRxData ), &xHigherPriorityTaskWoken ); if( xReceivedBytes > 0 ) { // ucRxData contains xReceivedBytes read from the stream buffer. // Process the stream here.... } // If xHigherPriorityTaskWoken was set to pdTRUE inside // xStreamBufferReceiveFromISR() then a task that has a priority above the // priority of the currently executing task was unblocked and a context // switch should be performed to ensure the ISR returns to the unblocked // task. In most FreeRTOS ports this is done by simply passing // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the // variables value, and perform the context switch if necessary. Check the // documentation for the port in use for port specific instructions. portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } Parameters xStreamBuffer -- The handle of the stream buffer from which a stream is being received. pvRxData -- A pointer to the buffer into which the received bytes are copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum number of bytes to receive in one call. xStreamBufferReceive will return as many bytes as possible up to a maximum set by xBufferLengthBytes. pxHigherPriorityTaskWoken -- It is possible that a stream buffer will have a task blocked on it waiting for space to become available. Calling xStreamBufferReceiveFromISR() can make space available, and so cause a task that is waiting for space to leave the Blocked state. If calling xStreamBufferReceiveFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xStreamBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xStreamBufferReceiveFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. That will ensure the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the code example below for an example. xStreamBuffer -- The handle of the stream buffer from which a stream is being received. pvRxData -- A pointer to the buffer into which the received bytes are copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum number of bytes to receive in one call. xStreamBufferReceive will return as many bytes as possible up to a maximum set by xBufferLengthBytes. pxHigherPriorityTaskWoken -- It is possible that a stream buffer will have a task blocked on it waiting for space to become available. Calling xStreamBufferReceiveFromISR() can make space available, and so cause a task that is waiting for space to leave the Blocked state. If calling xStreamBufferReceiveFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xStreamBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xStreamBufferReceiveFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. That will ensure the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the code example below for an example. xStreamBuffer -- The handle of the stream buffer from which a stream is being received. Returns The number of bytes read from the stream buffer, if any. Parameters xStreamBuffer -- The handle of the stream buffer from which a stream is being received. pvRxData -- A pointer to the buffer into which the received bytes are copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum number of bytes to receive in one call. xStreamBufferReceive will return as many bytes as possible up to a maximum set by xBufferLengthBytes. pxHigherPriorityTaskWoken -- It is possible that a stream buffer will have a task blocked on it waiting for space to become available. Calling xStreamBufferReceiveFromISR() can make space available, and so cause a task that is waiting for space to leave the Blocked state. If calling xStreamBufferReceiveFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xStreamBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xStreamBufferReceiveFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. That will ensure the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the code example below for an example. Returns The number of bytes read from the stream buffer, if any. void vStreamBufferDelete(StreamBufferHandle_t xStreamBuffer) Deletes a stream buffer that was previously created using a call to xStreamBufferCreate() or xStreamBufferCreateStatic(). If the stream buffer was created using dynamic memory (that is, by xStreamBufferCreate()), then the allocated memory is freed. A stream buffer handle must not be used after the stream buffer has been deleted. Parameters xStreamBuffer -- The handle of the stream buffer to be deleted. Parameters xStreamBuffer -- The handle of the stream buffer to be deleted. BaseType_t xStreamBufferIsFull(StreamBufferHandle_t xStreamBuffer) Queries a stream buffer to see if it is full. A stream buffer is full if it does not have any free space, and therefore cannot accept any more data. Parameters xStreamBuffer -- The handle of the stream buffer being queried. Returns If the stream buffer is full then pdTRUE is returned. Otherwise pdFALSE is returned. Parameters xStreamBuffer -- The handle of the stream buffer being queried. Returns If the stream buffer is full then pdTRUE is returned. Otherwise pdFALSE is returned. BaseType_t xStreamBufferIsEmpty(StreamBufferHandle_t xStreamBuffer) Queries a stream buffer to see if it is empty. A stream buffer is empty if it does not contain any data. Parameters xStreamBuffer -- The handle of the stream buffer being queried. Returns If the stream buffer is empty then pdTRUE is returned. Otherwise pdFALSE is returned. Parameters xStreamBuffer -- The handle of the stream buffer being queried. Returns If the stream buffer is empty then pdTRUE is returned. Otherwise pdFALSE is returned. BaseType_t xStreamBufferReset(StreamBufferHandle_t xStreamBuffer) Resets a stream buffer to its initial, empty, state. Any data that was in the stream buffer is discarded. A stream buffer can only be reset if there are no tasks blocked waiting to either send to or receive from the stream buffer. Parameters xStreamBuffer -- The handle of the stream buffer being reset. Returns If the stream buffer is reset then pdPASS is returned. If there was a task blocked waiting to send to or read from the stream buffer then the stream buffer is not reset and pdFAIL is returned. Parameters xStreamBuffer -- The handle of the stream buffer being reset. Returns If the stream buffer is reset then pdPASS is returned. If there was a task blocked waiting to send to or read from the stream buffer then the stream buffer is not reset and pdFAIL is returned. size_t xStreamBufferSpacesAvailable(StreamBufferHandle_t xStreamBuffer) Queries a stream buffer to see how much free space it contains, which is equal to the amount of data that can be sent to the stream buffer before it is full. Parameters xStreamBuffer -- The handle of the stream buffer being queried. Returns The number of bytes that can be written to the stream buffer before the stream buffer would be full. Parameters xStreamBuffer -- The handle of the stream buffer being queried. Returns The number of bytes that can be written to the stream buffer before the stream buffer would be full. size_t xStreamBufferBytesAvailable(StreamBufferHandle_t xStreamBuffer) Queries a stream buffer to see how much data it contains, which is equal to the number of bytes that can be read from the stream buffer before the stream buffer would be empty. Parameters xStreamBuffer -- The handle of the stream buffer being queried. Returns The number of bytes that can be read from the stream buffer before the stream buffer would be empty. Parameters xStreamBuffer -- The handle of the stream buffer being queried. Returns The number of bytes that can be read from the stream buffer before the stream buffer would be empty. BaseType_t xStreamBufferSetTriggerLevel(StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel) A stream buffer's trigger level is the number of bytes that must be in the stream buffer before a task that is blocked on the stream buffer to wait for data is moved out of the blocked state. For example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 1 then the task will be unblocked when a single byte is written to the buffer or the task's block time expires. As another example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 10 then the task will not be unblocked until the stream buffer contains at least 10 bytes or the task's block time expires. If a reading task's block time expires before the trigger level is reached then the task will still receive however many bytes are actually available. Setting a trigger level of 0 will result in a trigger level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer size. A trigger level is set when the stream buffer is created, and can be modified using xStreamBufferSetTriggerLevel(). Parameters xStreamBuffer -- The handle of the stream buffer being updated. xTriggerLevel -- The new trigger level for the stream buffer. xStreamBuffer -- The handle of the stream buffer being updated. xTriggerLevel -- The new trigger level for the stream buffer. xStreamBuffer -- The handle of the stream buffer being updated. Returns If xTriggerLevel was less than or equal to the stream buffer's length then the trigger level will be updated and pdTRUE is returned. Otherwise pdFALSE is returned. Parameters xStreamBuffer -- The handle of the stream buffer being updated. xTriggerLevel -- The new trigger level for the stream buffer. Returns If xTriggerLevel was less than or equal to the stream buffer's length then the trigger level will be updated and pdTRUE is returned. Otherwise pdFALSE is returned. BaseType_t xStreamBufferSendCompletedFromISR(StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken) For advanced users only. The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when data is sent to a message buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting for data to arrive then the sbSEND_COMPLETED() macro sends a notification to the task to remove it from the Blocked state. xStreamBufferSendCompletedFromISR() does the same thing. It is provided to enable application writers to implement their own version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information. Parameters xStreamBuffer -- The handle of the stream buffer to which data was written. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xStreamBufferSendCompletedFromISR(). If calling xStreamBufferSendCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. xStreamBuffer -- The handle of the stream buffer to which data was written. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xStreamBufferSendCompletedFromISR(). If calling xStreamBufferSendCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. xStreamBuffer -- The handle of the stream buffer to which data was written. Returns If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned. Parameters xStreamBuffer -- The handle of the stream buffer to which data was written. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xStreamBufferSendCompletedFromISR(). If calling xStreamBufferSendCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. Returns If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned. BaseType_t xStreamBufferReceiveCompletedFromISR(StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken) For advanced users only. The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when data is read out of a message buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting for data to arrive then the sbRECEIVE_COMPLETED() macro sends a notification to the task to remove it from the Blocked state. xStreamBufferReceiveCompletedFromISR() does the same thing. It is provided to enable application writers to implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information. Parameters xStreamBuffer -- The handle of the stream buffer from which data was read. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xStreamBufferReceiveCompletedFromISR(). If calling xStreamBufferReceiveCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. xStreamBuffer -- The handle of the stream buffer from which data was read. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xStreamBufferReceiveCompletedFromISR(). If calling xStreamBufferReceiveCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. xStreamBuffer -- The handle of the stream buffer from which data was read. Returns If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned. Parameters xStreamBuffer -- The handle of the stream buffer from which data was read. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xStreamBufferReceiveCompletedFromISR(). If calling xStreamBufferReceiveCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. Returns If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned. Macros xStreamBufferCreateWithCallback(xBufferSizeBytes, xTriggerLevelBytes, pxSendCompletedCallback, pxReceiveCompletedCallback) Creates a new stream buffer using dynamically allocated memory. See xStreamBufferCreateStatic() for a version that uses statically allocated memory (memory that is allocated at compile time). configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in FreeRTOSConfig.h for xStreamBufferCreate() to be available. Example use: void vAFunction( void ) { StreamBufferHandle_t xStreamBuffer; const size_t xStreamBufferSizeBytes = 100, xTriggerLevel = 10; // Create a stream buffer that can hold 100 bytes. The memory used to hold // both the stream buffer structure and the data in the stream buffer is // allocated dynamically. xStreamBuffer = xStreamBufferCreate( xStreamBufferSizeBytes, xTriggerLevel ); if( xStreamBuffer == NULL ) { // There was not enough heap memory space available to create the // stream buffer. } else { // The stream buffer was created successfully and can now be used. } } Parameters xBufferSizeBytes -- The total number of bytes the stream buffer will be able to hold at any one time. xTriggerLevelBytes -- The number of bytes that must be in the stream buffer before a task that is blocked on the stream buffer to wait for data is moved out of the blocked state. For example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 1 then the task will be unblocked when a single byte is written to the buffer or the task's block time expires. As another example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 10 then the task will not be unblocked until the stream buffer contains at least 10 bytes or the task's block time expires. If a reading task's block time expires before the trigger level is reached then the task will still receive however many bytes are actually available. Setting a trigger level of 0 will result in a trigger level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer size. pxSendCompletedCallback -- Callback invoked when number of bytes at least equal to trigger level is sent to the stream buffer. If the parameter is NULL, it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when more than zero bytes are read from a stream buffer. If the parameter is NULL, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. xBufferSizeBytes -- The total number of bytes the stream buffer will be able to hold at any one time. xTriggerLevelBytes -- The number of bytes that must be in the stream buffer before a task that is blocked on the stream buffer to wait for data is moved out of the blocked state. For example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 1 then the task will be unblocked when a single byte is written to the buffer or the task's block time expires. As another example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 10 then the task will not be unblocked until the stream buffer contains at least 10 bytes or the task's block time expires. If a reading task's block time expires before the trigger level is reached then the task will still receive however many bytes are actually available. Setting a trigger level of 0 will result in a trigger level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer size. pxSendCompletedCallback -- Callback invoked when number of bytes at least equal to trigger level is sent to the stream buffer. If the parameter is NULL, it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when more than zero bytes are read from a stream buffer. If the parameter is NULL, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. xBufferSizeBytes -- The total number of bytes the stream buffer will be able to hold at any one time. Returns If NULL is returned, then the stream buffer cannot be created because there is insufficient heap memory available for FreeRTOS to allocate the stream buffer data structures and storage area. A non-NULL value being returned indicates that the stream buffer has been created successfully - the returned value should be stored as the handle to the created stream buffer. Parameters xBufferSizeBytes -- The total number of bytes the stream buffer will be able to hold at any one time. xTriggerLevelBytes -- The number of bytes that must be in the stream buffer before a task that is blocked on the stream buffer to wait for data is moved out of the blocked state. For example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 1 then the task will be unblocked when a single byte is written to the buffer or the task's block time expires. As another example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 10 then the task will not be unblocked until the stream buffer contains at least 10 bytes or the task's block time expires. If a reading task's block time expires before the trigger level is reached then the task will still receive however many bytes are actually available. Setting a trigger level of 0 will result in a trigger level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer size. pxSendCompletedCallback -- Callback invoked when number of bytes at least equal to trigger level is sent to the stream buffer. If the parameter is NULL, it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when more than zero bytes are read from a stream buffer. If the parameter is NULL, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. Returns If NULL is returned, then the stream buffer cannot be created because there is insufficient heap memory available for FreeRTOS to allocate the stream buffer data structures and storage area. A non-NULL value being returned indicates that the stream buffer has been created successfully - the returned value should be stored as the handle to the created stream buffer. xStreamBufferCreateStaticWithCallback(xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea, pxStaticStreamBuffer, pxSendCompletedCallback, pxReceiveCompletedCallback) Creates a new stream buffer using statically allocated memory. See xStreamBufferCreate() for a version that uses dynamically allocated memory. configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h for xStreamBufferCreateStatic() to be available. Example use: // Used to dimension the array used to hold the streams. The available space // will actually be one less than this, so 999. #define STORAGE_SIZE_BYTES 1000 // Defines the memory that will actually hold the streams within the stream // buffer. static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ]; // The variable used to hold the stream buffer structure. StaticStreamBuffer_t xStreamBufferStruct; void MyFunction( void ) { StreamBufferHandle_t xStreamBuffer; const size_t xTriggerLevel = 1; xStreamBuffer = xStreamBufferCreateStatic( sizeof( ucStorageBuffer ), xTriggerLevel, ucStorageBuffer, &xStreamBufferStruct ); // As neither the pucStreamBufferStorageArea or pxStaticStreamBuffer // parameters were NULL, xStreamBuffer will not be NULL, and can be used to // reference the created stream buffer in other stream buffer API calls. // Other code that uses the stream buffer can go here. } Parameters xBufferSizeBytes -- The size, in bytes, of the buffer pointed to by the pucStreamBufferStorageArea parameter. xTriggerLevelBytes -- The number of bytes that must be in the stream buffer before a task that is blocked on the stream buffer to wait for data is moved out of the blocked state. For example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 1 then the task will be unblocked when a single byte is written to the buffer or the task's block time expires. As another example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 10 then the task will not be unblocked until the stream buffer contains at least 10 bytes or the task's block time expires. If a reading task's block time expires before the trigger level is reached then the task will still receive however many bytes are actually available. Setting a trigger level of 0 will result in a trigger level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer size. pucStreamBufferStorageArea -- Must point to a uint8_t array that is at least xBufferSizeBytes big. This is the array to which streams are copied when they are written to the stream buffer. pxStaticStreamBuffer -- Must point to a variable of type StaticStreamBuffer_t, which will be used to hold the stream buffer's data structure. pxSendCompletedCallback -- Callback invoked when number of bytes at least equal to trigger level is sent to the stream buffer. If the parameter is NULL, it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when more than zero bytes are read from a stream buffer. If the parameter is NULL, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. xBufferSizeBytes -- The size, in bytes, of the buffer pointed to by the pucStreamBufferStorageArea parameter. xTriggerLevelBytes -- The number of bytes that must be in the stream buffer before a task that is blocked on the stream buffer to wait for data is moved out of the blocked state. For example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 1 then the task will be unblocked when a single byte is written to the buffer or the task's block time expires. As another example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 10 then the task will not be unblocked until the stream buffer contains at least 10 bytes or the task's block time expires. If a reading task's block time expires before the trigger level is reached then the task will still receive however many bytes are actually available. Setting a trigger level of 0 will result in a trigger level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer size. pucStreamBufferStorageArea -- Must point to a uint8_t array that is at least xBufferSizeBytes big. This is the array to which streams are copied when they are written to the stream buffer. pxStaticStreamBuffer -- Must point to a variable of type StaticStreamBuffer_t, which will be used to hold the stream buffer's data structure. pxSendCompletedCallback -- Callback invoked when number of bytes at least equal to trigger level is sent to the stream buffer. If the parameter is NULL, it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when more than zero bytes are read from a stream buffer. If the parameter is NULL, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. xBufferSizeBytes -- The size, in bytes, of the buffer pointed to by the pucStreamBufferStorageArea parameter. Returns If the stream buffer is created successfully then a handle to the created stream buffer is returned. If either pucStreamBufferStorageArea or pxStaticstreamBuffer are NULL then NULL is returned. Parameters xBufferSizeBytes -- The size, in bytes, of the buffer pointed to by the pucStreamBufferStorageArea parameter. xTriggerLevelBytes -- The number of bytes that must be in the stream buffer before a task that is blocked on the stream buffer to wait for data is moved out of the blocked state. For example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 1 then the task will be unblocked when a single byte is written to the buffer or the task's block time expires. As another example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 10 then the task will not be unblocked until the stream buffer contains at least 10 bytes or the task's block time expires. If a reading task's block time expires before the trigger level is reached then the task will still receive however many bytes are actually available. Setting a trigger level of 0 will result in a trigger level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer size. pucStreamBufferStorageArea -- Must point to a uint8_t array that is at least xBufferSizeBytes big. This is the array to which streams are copied when they are written to the stream buffer. pxStaticStreamBuffer -- Must point to a variable of type StaticStreamBuffer_t, which will be used to hold the stream buffer's data structure. pxSendCompletedCallback -- Callback invoked when number of bytes at least equal to trigger level is sent to the stream buffer. If the parameter is NULL, it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when more than zero bytes are read from a stream buffer. If the parameter is NULL, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. Returns If the stream buffer is created successfully then a handle to the created stream buffer is returned. If either pucStreamBufferStorageArea or pxStaticstreamBuffer are NULL then NULL is returned. Type Definitions typedef struct StreamBufferDef_t *StreamBufferHandle_t typedef void (*StreamBufferCallbackFunction_t)(StreamBufferHandle_t xStreamBuffer, BaseType_t xIsInsideISR, BaseType_t *const pxHigherPriorityTaskWoken) Type used as a stream buffer's optional callback. Message Buffer API Header File components/freertos/FreeRTOS-Kernel/include/freertos/message_buffer.h This header file can be included with: #include "freertos/message_buffer.h" Macros xMessageBufferCreateWithCallback(xBufferSizeBytes, pxSendCompletedCallback, pxReceiveCompletedCallback) Creates a new message buffer using dynamically allocated memory. See xMessageBufferCreateStatic() for a version that uses statically allocated memory (memory that is allocated at compile time). configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in FreeRTOSConfig.h for xMessageBufferCreate() to be available. Example use: void vAFunction( void ) { MessageBufferHandle_t xMessageBuffer; const size_t xMessageBufferSizeBytes = 100; // Create a message buffer that can hold 100 bytes. The memory used to hold // both the message buffer structure and the messages themselves is allocated // dynamically. Each message added to the buffer consumes an additional 4 // bytes which are used to hold the length of the message. xMessageBuffer = xMessageBufferCreate( xMessageBufferSizeBytes ); if( xMessageBuffer == NULL ) { // There was not enough heap memory space available to create the // message buffer. } else { // The message buffer was created successfully and can now be used. } Parameters xBufferSizeBytes -- The total number of bytes (not messages) the message buffer will be able to hold at any one time. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architectures a 10 byte message will take up 14 bytes of message buffer space. pxSendCompletedCallback -- Callback invoked when a send operation to the message buffer is complete. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, then it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when a receive operation from the message buffer is complete. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. xBufferSizeBytes -- The total number of bytes (not messages) the message buffer will be able to hold at any one time. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architectures a 10 byte message will take up 14 bytes of message buffer space. pxSendCompletedCallback -- Callback invoked when a send operation to the message buffer is complete. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, then it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when a receive operation from the message buffer is complete. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. xBufferSizeBytes -- The total number of bytes (not messages) the message buffer will be able to hold at any one time. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architectures a 10 byte message will take up 14 bytes of message buffer space. Returns If NULL is returned, then the message buffer cannot be created because there is insufficient heap memory available for FreeRTOS to allocate the message buffer data structures and storage area. A non-NULL value being returned indicates that the message buffer has been created successfully - the returned value should be stored as the handle to the created message buffer. Parameters xBufferSizeBytes -- The total number of bytes (not messages) the message buffer will be able to hold at any one time. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architectures a 10 byte message will take up 14 bytes of message buffer space. pxSendCompletedCallback -- Callback invoked when a send operation to the message buffer is complete. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, then it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when a receive operation from the message buffer is complete. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. Returns If NULL is returned, then the message buffer cannot be created because there is insufficient heap memory available for FreeRTOS to allocate the message buffer data structures and storage area. A non-NULL value being returned indicates that the message buffer has been created successfully - the returned value should be stored as the handle to the created message buffer. xMessageBufferCreateStaticWithCallback(xBufferSizeBytes, pucMessageBufferStorageArea, pxStaticMessageBuffer, pxSendCompletedCallback, pxReceiveCompletedCallback) Creates a new message buffer using statically allocated memory. See xMessageBufferCreate() for a version that uses dynamically allocated memory. Example use: // Used to dimension the array used to hold the messages. The available space // will actually be one less than this, so 999. #define STORAGE_SIZE_BYTES 1000 // Defines the memory that will actually hold the messages within the message // buffer. static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ]; // The variable used to hold the message buffer structure. StaticMessageBuffer_t xMessageBufferStruct; void MyFunction( void ) { MessageBufferHandle_t xMessageBuffer; xMessageBuffer = xMessageBufferCreateStatic( sizeof( ucStorageBuffer ), ucStorageBuffer, &xMessageBufferStruct ); // As neither the pucMessageBufferStorageArea or pxStaticMessageBuffer // parameters were NULL, xMessageBuffer will not be NULL, and can be used to // reference the created message buffer in other message buffer API calls. // Other code that uses the message buffer can go here. } Parameters xBufferSizeBytes -- The size, in bytes, of the buffer pointed to by the pucMessageBufferStorageArea parameter. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture a 10 byte message will take up 14 bytes of message buffer space. The maximum number of bytes that can be stored in the message buffer is actually (xBufferSizeBytes - 1). pucMessageBufferStorageArea -- Must point to a uint8_t array that is at least xBufferSizeBytes big. This is the array to which messages are copied when they are written to the message buffer. pxStaticMessageBuffer -- Must point to a variable of type StaticMessageBuffer_t, which will be used to hold the message buffer's data structure. pxSendCompletedCallback -- Callback invoked when a new message is sent to the message buffer. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, then it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when a message is read from a message buffer. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. xBufferSizeBytes -- The size, in bytes, of the buffer pointed to by the pucMessageBufferStorageArea parameter. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture a 10 byte message will take up 14 bytes of message buffer space. The maximum number of bytes that can be stored in the message buffer is actually (xBufferSizeBytes - 1). pucMessageBufferStorageArea -- Must point to a uint8_t array that is at least xBufferSizeBytes big. This is the array to which messages are copied when they are written to the message buffer. pxStaticMessageBuffer -- Must point to a variable of type StaticMessageBuffer_t, which will be used to hold the message buffer's data structure. pxSendCompletedCallback -- Callback invoked when a new message is sent to the message buffer. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, then it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when a message is read from a message buffer. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. xBufferSizeBytes -- The size, in bytes, of the buffer pointed to by the pucMessageBufferStorageArea parameter. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture a 10 byte message will take up 14 bytes of message buffer space. The maximum number of bytes that can be stored in the message buffer is actually (xBufferSizeBytes - 1). Returns If the message buffer is created successfully then a handle to the created message buffer is returned. If either pucMessageBufferStorageArea or pxStaticmessageBuffer are NULL then NULL is returned. Parameters xBufferSizeBytes -- The size, in bytes, of the buffer pointed to by the pucMessageBufferStorageArea parameter. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture a 10 byte message will take up 14 bytes of message buffer space. The maximum number of bytes that can be stored in the message buffer is actually (xBufferSizeBytes - 1). pucMessageBufferStorageArea -- Must point to a uint8_t array that is at least xBufferSizeBytes big. This is the array to which messages are copied when they are written to the message buffer. pxStaticMessageBuffer -- Must point to a variable of type StaticMessageBuffer_t, which will be used to hold the message buffer's data structure. pxSendCompletedCallback -- Callback invoked when a new message is sent to the message buffer. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, then it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when a message is read from a message buffer. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. Returns If the message buffer is created successfully then a handle to the created message buffer is returned. If either pucMessageBufferStorageArea or pxStaticmessageBuffer are NULL then NULL is returned. xMessageBufferGetStaticBuffers(xMessageBuffer, ppucMessageBufferStorageArea, ppxStaticMessageBuffer) Retrieve pointers to a statically created message buffer's data structure buffer and storage area buffer. These are the same buffers that are supplied at the time of creation. Parameters xMessageBuffer -- The message buffer for which to retrieve the buffers. ppucMessageBufferStorageArea -- Used to return a pointer to the message buffer's storage area buffer. ppxStaticMessageBuffer -- Used to return a pointer to the message buffer's data structure buffer. xMessageBuffer -- The message buffer for which to retrieve the buffers. ppucMessageBufferStorageArea -- Used to return a pointer to the message buffer's storage area buffer. ppxStaticMessageBuffer -- Used to return a pointer to the message buffer's data structure buffer. xMessageBuffer -- The message buffer for which to retrieve the buffers. Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. Parameters xMessageBuffer -- The message buffer for which to retrieve the buffers. ppucMessageBufferStorageArea -- Used to return a pointer to the message buffer's storage area buffer. ppxStaticMessageBuffer -- Used to return a pointer to the message buffer's data structure buffer. Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. xMessageBufferSend(xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait) Sends a discrete message to the message buffer. The message can be any length that fits within the buffer's free space, and is copied into the buffer. NOTE: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xMessageBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xMessageBufferRead()) inside a critical section and set the receive block time to 0. Use xMessageBufferSend() to write to a message buffer from a task. Use xMessageBufferSendFromISR() to write to a message buffer from an interrupt service routine (ISR). Example use: void vAFunction( MessageBufferHandle_t xMessageBuffer ) { size_t xBytesSent; uint8_t ucArrayToSend[] = { 0, 1, 2, 3 }; char *pcStringToSend = "String to send"; const TickType_t x100ms = pdMS_TO_TICKS( 100 ); // Send an array to the message buffer, blocking for a maximum of 100ms to // wait for enough space to be available in the message buffer. xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms ); if( xBytesSent != sizeof( ucArrayToSend ) ) { // The call to xMessageBufferSend() times out before there was enough // space in the buffer for the data to be written. } // Send the string to the message buffer. Return immediately if there is // not enough space in the buffer. xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 ); if( xBytesSent != strlen( pcStringToSend ) ) { // The string could not be added to the message buffer because there was // not enough free space in the buffer. } } Parameters xMessageBuffer -- The handle of the message buffer to which a message is being sent. pvTxData -- A pointer to the message that is to be copied into the message buffer. xDataLengthBytes -- The length of the message. That is, the number of bytes to copy from pvTxData into the message buffer. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture setting xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 bytes (20 bytes of message data and 4 bytes to hold the message length). xTicksToWait -- The maximum amount of time the calling task should remain in the Blocked state to wait for enough space to become available in the message buffer, should the message buffer have insufficient space when xMessageBufferSend() is called. The calling task will never block if xTicksToWait is zero. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any CPU time when they are in the Blocked state. xMessageBuffer -- The handle of the message buffer to which a message is being sent. pvTxData -- A pointer to the message that is to be copied into the message buffer. xDataLengthBytes -- The length of the message. That is, the number of bytes to copy from pvTxData into the message buffer. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture setting xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 bytes (20 bytes of message data and 4 bytes to hold the message length). xTicksToWait -- The maximum amount of time the calling task should remain in the Blocked state to wait for enough space to become available in the message buffer, should the message buffer have insufficient space when xMessageBufferSend() is called. The calling task will never block if xTicksToWait is zero. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any CPU time when they are in the Blocked state. xMessageBuffer -- The handle of the message buffer to which a message is being sent. Returns The number of bytes written to the message buffer. If the call to xMessageBufferSend() times out before there was enough space to write the message into the message buffer then zero is returned. If the call did not time out then xDataLengthBytes is returned. Parameters xMessageBuffer -- The handle of the message buffer to which a message is being sent. pvTxData -- A pointer to the message that is to be copied into the message buffer. xDataLengthBytes -- The length of the message. That is, the number of bytes to copy from pvTxData into the message buffer. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture setting xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 bytes (20 bytes of message data and 4 bytes to hold the message length). xTicksToWait -- The maximum amount of time the calling task should remain in the Blocked state to wait for enough space to become available in the message buffer, should the message buffer have insufficient space when xMessageBufferSend() is called. The calling task will never block if xTicksToWait is zero. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any CPU time when they are in the Blocked state. Returns The number of bytes written to the message buffer. If the call to xMessageBufferSend() times out before there was enough space to write the message into the message buffer then zero is returned. If the call did not time out then xDataLengthBytes is returned. xMessageBufferSendFromISR(xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken) Interrupt safe version of the API function that sends a discrete message to the message buffer. The message can be any length that fits within the buffer's free space, and is copied into the buffer. NOTE: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xMessageBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xMessageBufferRead()) inside a critical section and set the receive block time to 0. Use xMessageBufferSend() to write to a message buffer from a task. Use xMessageBufferSendFromISR() to write to a message buffer from an interrupt service routine (ISR). Example use: // A message buffer that has already been created. MessageBufferHandle_t xMessageBuffer; void vAnInterruptServiceRoutine( void ) { size_t xBytesSent; char *pcStringToSend = "String to send"; BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. // Attempt to send the string to the message buffer. xBytesSent = xMessageBufferSendFromISR( xMessageBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), &xHigherPriorityTaskWoken ); if( xBytesSent != strlen( pcStringToSend ) ) { // The string could not be added to the message buffer because there was // not enough free space in the buffer. } // If xHigherPriorityTaskWoken was set to pdTRUE inside // xMessageBufferSendFromISR() then a task that has a priority above the // priority of the currently executing task was unblocked and a context // switch should be performed to ensure the ISR returns to the unblocked // task. In most FreeRTOS ports this is done by simply passing // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the // variables value, and perform the context switch if necessary. Check the // documentation for the port in use for port specific instructions. portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } Parameters xMessageBuffer -- The handle of the message buffer to which a message is being sent. pvTxData -- A pointer to the message that is to be copied into the message buffer. xDataLengthBytes -- The length of the message. That is, the number of bytes to copy from pvTxData into the message buffer. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture setting xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 bytes (20 bytes of message data and 4 bytes to hold the message length). pxHigherPriorityTaskWoken -- It is possible that a message buffer will have a task blocked on it waiting for data. Calling xMessageBufferSendFromISR() can make data available, and so cause a task that was waiting for data to leave the Blocked state. If calling xMessageBufferSendFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xMessageBufferSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xMessageBufferSendFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. This will ensure that the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the code example below for an example. xMessageBuffer -- The handle of the message buffer to which a message is being sent. pvTxData -- A pointer to the message that is to be copied into the message buffer. xDataLengthBytes -- The length of the message. That is, the number of bytes to copy from pvTxData into the message buffer. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture setting xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 bytes (20 bytes of message data and 4 bytes to hold the message length). pxHigherPriorityTaskWoken -- It is possible that a message buffer will have a task blocked on it waiting for data. Calling xMessageBufferSendFromISR() can make data available, and so cause a task that was waiting for data to leave the Blocked state. If calling xMessageBufferSendFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xMessageBufferSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xMessageBufferSendFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. This will ensure that the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the code example below for an example. xMessageBuffer -- The handle of the message buffer to which a message is being sent. Returns The number of bytes actually written to the message buffer. If the message buffer didn't have enough free space for the message to be stored then 0 is returned, otherwise xDataLengthBytes is returned. Parameters xMessageBuffer -- The handle of the message buffer to which a message is being sent. pvTxData -- A pointer to the message that is to be copied into the message buffer. xDataLengthBytes -- The length of the message. That is, the number of bytes to copy from pvTxData into the message buffer. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture setting xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 bytes (20 bytes of message data and 4 bytes to hold the message length). pxHigherPriorityTaskWoken -- It is possible that a message buffer will have a task blocked on it waiting for data. Calling xMessageBufferSendFromISR() can make data available, and so cause a task that was waiting for data to leave the Blocked state. If calling xMessageBufferSendFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xMessageBufferSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xMessageBufferSendFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. This will ensure that the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the code example below for an example. Returns The number of bytes actually written to the message buffer. If the message buffer didn't have enough free space for the message to be stored then 0 is returned, otherwise xDataLengthBytes is returned. xMessageBufferReceive(xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait) Receives a discrete message from a message buffer. Messages can be of variable length and are copied out of the buffer. NOTE: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xMessageBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xMessageBufferRead()) inside a critical section and set the receive block time to 0. Use xMessageBufferReceive() to read from a message buffer from a task. Use xMessageBufferReceiveFromISR() to read from a message buffer from an interrupt service routine (ISR). Example use: void vAFunction( MessageBuffer_t xMessageBuffer ) { uint8_t ucRxData[ 20 ]; size_t xReceivedBytes; const TickType_t xBlockTime = pdMS_TO_TICKS( 20 ); // Receive the next message from the message buffer. Wait in the Blocked // state (so not using any CPU processing time) for a maximum of 100ms for // a message to become available. xReceivedBytes = xMessageBufferReceive( xMessageBuffer, ( void * ) ucRxData, sizeof( ucRxData ), xBlockTime ); if( xReceivedBytes > 0 ) { // A ucRxData contains a message that is xReceivedBytes long. Process // the message here.... } } Parameters xMessageBuffer -- The handle of the message buffer from which a message is being received. pvRxData -- A pointer to the buffer into which the received message is to be copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum length of the message that can be received. If xBufferLengthBytes is too small to hold the next message then the message will be left in the message buffer and 0 will be returned. xTicksToWait -- The maximum amount of time the task should remain in the Blocked state to wait for a message, should the message buffer be empty. xMessageBufferReceive() will return immediately if xTicksToWait is zero and the message buffer is empty. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any CPU time when they are in the Blocked state. xMessageBuffer -- The handle of the message buffer from which a message is being received. pvRxData -- A pointer to the buffer into which the received message is to be copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum length of the message that can be received. If xBufferLengthBytes is too small to hold the next message then the message will be left in the message buffer and 0 will be returned. xTicksToWait -- The maximum amount of time the task should remain in the Blocked state to wait for a message, should the message buffer be empty. xMessageBufferReceive() will return immediately if xTicksToWait is zero and the message buffer is empty. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any CPU time when they are in the Blocked state. xMessageBuffer -- The handle of the message buffer from which a message is being received. Returns The length, in bytes, of the message read from the message buffer, if any. If xMessageBufferReceive() times out before a message became available then zero is returned. If the length of the message is greater than xBufferLengthBytes then the message will be left in the message buffer and zero is returned. Parameters xMessageBuffer -- The handle of the message buffer from which a message is being received. pvRxData -- A pointer to the buffer into which the received message is to be copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum length of the message that can be received. If xBufferLengthBytes is too small to hold the next message then the message will be left in the message buffer and 0 will be returned. xTicksToWait -- The maximum amount of time the task should remain in the Blocked state to wait for a message, should the message buffer be empty. xMessageBufferReceive() will return immediately if xTicksToWait is zero and the message buffer is empty. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any CPU time when they are in the Blocked state. Returns The length, in bytes, of the message read from the message buffer, if any. If xMessageBufferReceive() times out before a message became available then zero is returned. If the length of the message is greater than xBufferLengthBytes then the message will be left in the message buffer and zero is returned. xMessageBufferReceiveFromISR(xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken) An interrupt safe version of the API function that receives a discrete message from a message buffer. Messages can be of variable length and are copied out of the buffer. NOTE: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xMessageBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xMessageBufferRead()) inside a critical section and set the receive block time to 0. Use xMessageBufferReceive() to read from a message buffer from a task. Use xMessageBufferReceiveFromISR() to read from a message buffer from an interrupt service routine (ISR). Example use: // A message buffer that has already been created. MessageBuffer_t xMessageBuffer; void vAnInterruptServiceRoutine( void ) { uint8_t ucRxData[ 20 ]; size_t xReceivedBytes; BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. // Receive the next message from the message buffer. xReceivedBytes = xMessageBufferReceiveFromISR( xMessageBuffer, ( void * ) ucRxData, sizeof( ucRxData ), &xHigherPriorityTaskWoken ); if( xReceivedBytes > 0 ) { // A ucRxData contains a message that is xReceivedBytes long. Process // the message here.... } // If xHigherPriorityTaskWoken was set to pdTRUE inside // xMessageBufferReceiveFromISR() then a task that has a priority above the // priority of the currently executing task was unblocked and a context // switch should be performed to ensure the ISR returns to the unblocked // task. In most FreeRTOS ports this is done by simply passing // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the // variables value, and perform the context switch if necessary. Check the // documentation for the port in use for port specific instructions. portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } Parameters xMessageBuffer -- The handle of the message buffer from which a message is being received. pvRxData -- A pointer to the buffer into which the received message is to be copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum length of the message that can be received. If xBufferLengthBytes is too small to hold the next message then the message will be left in the message buffer and 0 will be returned. pxHigherPriorityTaskWoken -- It is possible that a message buffer will have a task blocked on it waiting for space to become available. Calling xMessageBufferReceiveFromISR() can make space available, and so cause a task that is waiting for space to leave the Blocked state. If calling xMessageBufferReceiveFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xMessageBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xMessageBufferReceiveFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. That will ensure the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the code example below for an example. xMessageBuffer -- The handle of the message buffer from which a message is being received. pvRxData -- A pointer to the buffer into which the received message is to be copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum length of the message that can be received. If xBufferLengthBytes is too small to hold the next message then the message will be left in the message buffer and 0 will be returned. pxHigherPriorityTaskWoken -- It is possible that a message buffer will have a task blocked on it waiting for space to become available. Calling xMessageBufferReceiveFromISR() can make space available, and so cause a task that is waiting for space to leave the Blocked state. If calling xMessageBufferReceiveFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xMessageBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xMessageBufferReceiveFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. That will ensure the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the code example below for an example. xMessageBuffer -- The handle of the message buffer from which a message is being received. Returns The length, in bytes, of the message read from the message buffer, if any. Parameters xMessageBuffer -- The handle of the message buffer from which a message is being received. pvRxData -- A pointer to the buffer into which the received message is to be copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum length of the message that can be received. If xBufferLengthBytes is too small to hold the next message then the message will be left in the message buffer and 0 will be returned. pxHigherPriorityTaskWoken -- It is possible that a message buffer will have a task blocked on it waiting for space to become available. Calling xMessageBufferReceiveFromISR() can make space available, and so cause a task that is waiting for space to leave the Blocked state. If calling xMessageBufferReceiveFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xMessageBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xMessageBufferReceiveFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. That will ensure the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the code example below for an example. Returns The length, in bytes, of the message read from the message buffer, if any. vMessageBufferDelete(xMessageBuffer) Deletes a message buffer that was previously created using a call to xMessageBufferCreate() or xMessageBufferCreateStatic(). If the message buffer was created using dynamic memory (that is, by xMessageBufferCreate()), then the allocated memory is freed. A message buffer handle must not be used after the message buffer has been deleted. Parameters xMessageBuffer -- The handle of the message buffer to be deleted. xMessageBuffer -- The handle of the message buffer to be deleted. xMessageBuffer -- The handle of the message buffer to be deleted. Parameters xMessageBuffer -- The handle of the message buffer to be deleted. xMessageBufferIsFull(xMessageBuffer) Tests to see if a message buffer is full. A message buffer is full if it cannot accept any more messages, of any size, until space is made available by a message being removed from the message buffer. Parameters xMessageBuffer -- The handle of the message buffer being queried. xMessageBuffer -- The handle of the message buffer being queried. xMessageBuffer -- The handle of the message buffer being queried. Returns If the message buffer referenced by xMessageBuffer is full then pdTRUE is returned. Otherwise pdFALSE is returned. Parameters xMessageBuffer -- The handle of the message buffer being queried. Returns If the message buffer referenced by xMessageBuffer is full then pdTRUE is returned. Otherwise pdFALSE is returned. xMessageBufferIsEmpty(xMessageBuffer) Tests to see if a message buffer is empty (does not contain any messages). Parameters xMessageBuffer -- The handle of the message buffer being queried. xMessageBuffer -- The handle of the message buffer being queried. xMessageBuffer -- The handle of the message buffer being queried. Returns If the message buffer referenced by xMessageBuffer is empty then pdTRUE is returned. Otherwise pdFALSE is returned. Parameters xMessageBuffer -- The handle of the message buffer being queried. Returns If the message buffer referenced by xMessageBuffer is empty then pdTRUE is returned. Otherwise pdFALSE is returned. xMessageBufferReset(xMessageBuffer) Resets a message buffer to its initial empty state, discarding any message it contained. A message buffer can only be reset if there are no tasks blocked on it. Parameters xMessageBuffer -- The handle of the message buffer being reset. xMessageBuffer -- The handle of the message buffer being reset. xMessageBuffer -- The handle of the message buffer being reset. Returns If the message buffer was reset then pdPASS is returned. If the message buffer could not be reset because either there was a task blocked on the message queue to wait for space to become available, or to wait for a a message to be available, then pdFAIL is returned. Parameters xMessageBuffer -- The handle of the message buffer being reset. Returns If the message buffer was reset then pdPASS is returned. If the message buffer could not be reset because either there was a task blocked on the message queue to wait for space to become available, or to wait for a a message to be available, then pdFAIL is returned. xMessageBufferSpaceAvailable(xMessageBuffer) message_buffer.h Returns the number of bytes of free space in the message buffer. size_t xMessageBufferSpaceAvailable( MessageBufferHandle_t xMessageBuffer ); Parameters xMessageBuffer -- The handle of the message buffer being queried. xMessageBuffer -- The handle of the message buffer being queried. xMessageBuffer -- The handle of the message buffer being queried. Returns The number of bytes that can be written to the message buffer before the message buffer would be full. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so if xMessageBufferSpacesAvailable() returns 10, then the size of the largest message that can be written to the message buffer is 6 bytes. Parameters xMessageBuffer -- The handle of the message buffer being queried. Returns The number of bytes that can be written to the message buffer before the message buffer would be full. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so if xMessageBufferSpacesAvailable() returns 10, then the size of the largest message that can be written to the message buffer is 6 bytes. xMessageBufferSpacesAvailable(xMessageBuffer) xMessageBufferNextLengthBytes(xMessageBuffer) Returns the length (in bytes) of the next message in a message buffer. Useful if xMessageBufferReceive() returned 0 because the size of the buffer passed into xMessageBufferReceive() was too small to hold the next message. Parameters xMessageBuffer -- The handle of the message buffer being queried. xMessageBuffer -- The handle of the message buffer being queried. xMessageBuffer -- The handle of the message buffer being queried. Returns The length (in bytes) of the next message in the message buffer, or 0 if the message buffer is empty. Parameters xMessageBuffer -- The handle of the message buffer being queried. Returns The length (in bytes) of the next message in the message buffer, or 0 if the message buffer is empty. xMessageBufferSendCompletedFromISR(xMessageBuffer, pxHigherPriorityTaskWoken) For advanced users only. The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when data is sent to a message buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting for data to arrive then the sbSEND_COMPLETED() macro sends a notification to the task to remove it from the Blocked state. xMessageBufferSendCompletedFromISR() does the same thing. It is provided to enable application writers to implement their own version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information. Parameters xMessageBuffer -- The handle of the stream buffer to which data was written. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xMessageBufferSendCompletedFromISR(). If calling xMessageBufferSendCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. xMessageBuffer -- The handle of the stream buffer to which data was written. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xMessageBufferSendCompletedFromISR(). If calling xMessageBufferSendCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. xMessageBuffer -- The handle of the stream buffer to which data was written. Returns If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned. Parameters xMessageBuffer -- The handle of the stream buffer to which data was written. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xMessageBufferSendCompletedFromISR(). If calling xMessageBufferSendCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. Returns If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned. xMessageBufferReceiveCompletedFromISR(xMessageBuffer, pxHigherPriorityTaskWoken) For advanced users only. The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when data is read out of a message buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting for data to arrive then the sbRECEIVE_COMPLETED() macro sends a notification to the task to remove it from the Blocked state. xMessageBufferReceiveCompletedFromISR() does the same thing. It is provided to enable application writers to implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information. Parameters xMessageBuffer -- The handle of the stream buffer from which data was read. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xMessageBufferReceiveCompletedFromISR(). If calling xMessageBufferReceiveCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. xMessageBuffer -- The handle of the stream buffer from which data was read. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xMessageBufferReceiveCompletedFromISR(). If calling xMessageBufferReceiveCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. xMessageBuffer -- The handle of the stream buffer from which data was read. Returns If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned. Parameters xMessageBuffer -- The handle of the stream buffer from which data was read. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xMessageBufferReceiveCompletedFromISR(). If calling xMessageBufferReceiveCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. Returns If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned. Type Definitions typedef StreamBufferHandle_t MessageBufferHandle_t Type by which message buffers are referenced. For example, a call to xMessageBufferCreate() returns an MessageBufferHandle_t variable that can then be used as a parameter to xMessageBufferSend(), xMessageBufferReceive(), etc. Message buffer is essentially built as a stream buffer hence its handle is also set to same type as a stream buffer handle.
FreeRTOS (IDF) This document provides information regarding the dual-core SMP implementation of FreeRTOS inside ESP-IDF. This document is split into the following sections: Sections Overview The original FreeRTOS (hereinafter referred to as Vanilla FreeRTOS) is a compact and efficient real-time operating system supported on numerous single-core MCUs and SoCs. However, to support dual-core ESP targets, such as ESP32, ESP32-S3, and ESP32-P4, ESP-IDF provides a unique implementation of FreeRTOS with dual-core symmetric multiprocessing (SMP) capabilities (hereinafter referred to as IDF FreeRTOS). IDF FreeRTOS source code is based on Vanilla FreeRTOS v10.5.1 but contains significant modifications to both kernel behavior and API in order to support dual-core SMP. However, IDF FreeRTOS can also be configured for single-core by enabling the CONFIG_FREERTOS_UNICORE option (see Single-Core Mode for more details). Note This document assumes that the reader has a requisite understanding of Vanilla FreeRTOS, i.e., its features, behavior, and API usage. Refer to the Vanilla FreeRTOS documentation for more details. Symmetric Multiprocessing Basic Concepts Symmetric multiprocessing is a computing architecture where two or more identical CPU cores are connected to a single shared main memory and controlled by a single operating system. In general, an SMP system: has multiple cores running independently. Each core has its own register file, interrupts, and interrupt handling. presents an identical view of memory to each core. Thus, a piece of code that accesses a particular memory address has the same effect regardless of which core it runs on. The main advantages of an SMP system compared to single-core or asymmetric multiprocessing systems are that: the presence of multiple cores allows for multiple hardware threads, thus increasing overall processing throughput. having symmetric memory means that threads can switch cores during execution. This, in general, can lead to better CPU utilization. Although an SMP system allows threads to switch cores, there are scenarios where a thread must/should only run on a particular core. Therefore, threads in an SMP system also have a core affinity that specifies which particular core the thread is allowed to run on. A thread that is pinned to a particular core is only able to run on that core. A thread that is unpinned will be allowed to switch between cores during execution instead of being pinned to a particular core. SMP on an ESP Target ESP targets such as ESP32, ESP32-S3, and ESP32-P4 are dual-core SMP SoCs. These targets have the following hardware features that make them SMP-capable: Two identical cores are known as Core 0 and Core 1. This means that the execution of a piece of code is identical regardless of which core it runs on. Symmetric memory (with some small exceptions). If multiple cores access the same memory address simultaneously, their access will be serialized by the memory bus. True atomic access to the same memory address is achieved via an atomic compare-and-swap instruction provided by the ISA. - Cross-core interrupts that allow one core to trigger an interrupt on the other core. This allows cores to signal events to each other (such as requesting a context switch on the other core). Note Within ESP-IDF, Core 0 and Core 1 are sometimes referred to as PRO_CPU and APP_CPU respectively. The aliases exist in ESP-IDF as they reflect how typical ESP-IDF applications utilize the two cores. Typically, the tasks responsible for handling protocol related processing such as Wi-Fi or Bluetooth are pinned to Core 0 (thus the name PRO_CPU), where as the tasks handling the remainder of the application are pinned to Core 1, (thus the name APP_CPU). Tasks Creation Vanilla FreeRTOS provides the following functions to create a task: xTaskCreate()creates a task. The task's memory is dynamically allocated. xTaskCreateStatic()creates a task. The task's memory is statically allocated, i.e., provided by the user. However, in an SMP system, tasks need to be assigned a particular affinity. Therefore, ESP-IDF provides a ...PinnedToCore() version of Vanilla FreeRTOS's task creation functions: xTaskCreatePinnedToCore()creates a task with a particular core affinity. The task's memory is dynamically allocated. xTaskCreateStaticPinnedToCore()creates a task with a particular core affinity. The task's memory is statically allocated, i.e., provided by the user. The ...PinnedToCore() versions of the task creation function API differ from their vanilla counterparts by having an extra xCoreID parameter that is used to specify the created task's core affinity. The valid values for core affinity are: 0, which pins the created task to Core 0 1, which pins the created task to Core 1 tskNO_AFFINITY, which allows the task to be run on both cores Note that IDF FreeRTOS still supports the vanilla versions of the task creation functions. However, these standard functions have been modified to essentially invoke their respective ...PinnedToCore() counterparts while setting the core affinity to tskNO_AFFINITY. Note IDF FreeRTOS also changes the units of ulStackDepth in the task creation functions. Task stack sizes in Vanilla FreeRTOS are specified in a number of words, whereas in IDF FreeRTOS, the task stack sizes are specified in bytes. Execution The anatomy of a task in IDF FreeRTOS is the same as in Vanilla FreeRTOS. More specifically, IDF FreeRTOS tasks: Can only be in one of the following states: Running, Ready, Blocked, or Suspended. Task functions are typically implemented as an infinite loop. Task functions should never return. Deletion Task deletion in Vanilla FreeRTOS is called via vTaskDelete(). The function allows deletion of another task or the currently running task if the provided task handle is NULL. The actual freeing of the task's memory is sometimes delegated to the idle task if the task being deleted is the currently running task. IDF FreeRTOS provides the same vTaskDelete() function. However, due to the dual-core nature, there are some behavioral differences when calling vTaskDelete() in IDF FreeRTOS: When deleting a task that is currently running on the other core, a yield is triggered on the other core, and the task's memory is freed by one of the idle tasks. A deleted task's memory is freed immediately if it is not running on either core. Please avoid deleting a task that is running on another core as it is difficult to determine what the task is performing, which may lead to unpredictable behavior such as: Deleting a task that is holding a mutex. Deleting a task that has yet to free memory it previously allocated. Where possible, please design your own application so that when calling vTaskDelete(), the deleted task is in a known state. For example: Tasks self-deleting via vTaskDelete(NULL)when their execution is complete and have also cleaned up all resources used within the task. Tasks placing themselves in the suspend state via vTaskSuspend()before being deleted by another task. SMP Scheduler The Vanilla FreeRTOS scheduler is best described as a fixed priority preemptive scheduler with time slicing meaning that: Each task is given a constant priority upon creation. The scheduler executes the highest priority ready-state task. The scheduler can switch execution to another task without the cooperation of the currently running task. The scheduler periodically switches execution between ready-state tasks of the same priority in a round-robin fashion. Time slicing is governed by a tick interrupt. The IDF FreeRTOS scheduler supports the same scheduling features, i.e., Fixed Priority, Preemption, and Time Slicing, albeit with some small behavioral differences. Fixed Priority In Vanilla FreeRTOS, when the scheduler selects a new task to run, it always selects the current highest priority ready-state task. In IDF FreeRTOS, each core independently schedules tasks to run. When a particular core selects a task, the core will select the highest priority ready-state task that can be run by the core. A task can be run by the core if: The task has a compatible affinity, i.e., is either pinned to that core or is unpinned. The task is not currently being run by another core. However, please do not assume that the two highest priority ready-state tasks are always run by the scheduler, as a task's core affinity must also be accounted for. For example, given the following tasks: Task A of priority 10 pinned to Core 0 Task B of priority 9 pinned to Core 0 Task C of priority 8 pinned to Core 1 The resulting schedule will have Task A running on Core 0 and Task C running on Core 1. Task B is not run even though it is the second-highest priority task. Preemption In Vanilla FreeRTOS, the scheduler can preempt the currently running task if a higher priority task becomes ready to execute. Likewise in IDF FreeRTOS, each core can be individually preempted by the scheduler if the scheduler determines that a higher-priority task can run on that core. However, there are some instances where a higher-priority task that becomes ready can be run on multiple cores. In this case, the scheduler only preempts one core. The scheduler always gives preference to the current core when multiple cores can be preempted. In other words, if the higher priority ready task is unpinned and has a higher priority than the current priority of both cores, the scheduler will always choose to preempt the current core. For example, given the following tasks: Task A of priority 8 currently running on Core 0 Task B of priority 9 currently running on Core 1 Task C of priority 10 that is unpinned and was unblocked by Task B The resulting schedule will have Task A running on Core 0 and Task C preempting Task B given that the scheduler always gives preference to the current core. Time Slicing The Vanilla FreeRTOS scheduler implements time slicing, which means that if the current highest ready priority contains multiple ready tasks, the scheduler will switch between those tasks periodically in a round-robin fashion. However, in IDF FreeRTOS, it is not possible to implement perfect Round Robin time slicing due to the fact that a particular task may not be able to run on a particular core due to the following reasons: The task is pinned to another core. For unpinned tasks, the task is already being run by another core. Therefore, when a core searches the ready-state task list for a task to run, the core may need to skip over a few tasks in the same priority list or drop to a lower priority in order to find a ready-state task that the core can run. The IDF FreeRTOS scheduler implements a Best Effort Round Robin time slicing for ready-state tasks of the same priority by ensuring that tasks that have been selected to run are placed at the back of the list, thus giving unselected tasks a higher priority on the next scheduling iteration (i.e., the next tick interrupt or yield). The following example demonstrates the Best Effort Round Robin time slicing in action. Assume that: There are four ready-state tasks of the same priority AX, B0, C1, and D1where: The priority is the current highest priority with ready-state . The first character represents the task's name, i.e., A, B, C, D. The second character represents the task's core pinning, and Xmeans unpinned. - The task list is always searched from the head. Starting state. None of the ready-state tasks have been selected to run. Head [ AX , B0 , C1 , D0 ] Tail Core 0 has a tick interrupt and searches for a task to run. Task A is selected and moved to the back of the list. Core 0 ─┐ ▼ Head [ AX , B0 , C1 , D0 ] Tail [0] Head [ B0 , C1 , D0 , AX ] Tail Core 1 has a tick interrupt and searches for a task to run. Task B cannot be run due to incompatible affinity, so Core 1 skips to Task C. Task C is selected and moved to the back of the list. Core 1 ──────┐ ▼ [0] Head [ B0 , C1 , D0 , AX ] Tail [0] [1] Head [ B0 , D0 , AX , C1 ] Tail Core 0 has another tick interrupt and searches for a task to run. Task B is selected and moved to the back of the list. Core 0 ─┐ ▼ [1] Head [ B0 , D0 , AX , C1 ] Tail [1] [0] Head [ D0 , AX , C1 , B0 ] Tail Core 1 has another tick and searches for a task to run. Task D cannot be run due to incompatible affinity, so Core 1 skips to Task A. Task A is selected and moved to the back of the list. Core 1 ──────┐ ▼ [0] Head [ D0 , AX , C1 , B0 ] Tail [0] [1] Head [ D0 , C1 , B0 , AX ] Tail The implications to users regarding the Best Effort Round Robin time slicing: Users cannot expect multiple ready-state tasks of the same priority to run sequentially as is the case in Vanilla FreeRTOS. As demonstrated in the example above, a core may need to skip over tasks. However, given enough ticks, a task will eventually be given some processing time. If a core cannot find a task runnable task at the highest ready-state priority, it will drop to a lower priority to search for tasks. To achieve ideal round-robin time slicing, users should ensure that all tasks of a particular priority are pinned to the same core. Tick Interrupts Vanilla FreeRTOS requires that a periodic tick interrupt occurs. The tick interrupt is responsible for: Incrementing the scheduler's tick count Unblocking any blocked tasks that have timed out Checking if time slicing is required, i.e., triggering a context switch Executing the application tick hook In IDF FreeRTOS, each core receives a periodic interrupt and independently runs the tick interrupt. The tick interrupts on each core are of the same period but can be out of phase. However, the tick responsibilities listed above are not run by all cores: Core 0 executes all of the tick interrupt responsibilities listed above Core 1 only checks for time slicing and executes the application tick hook Note Core 0 is solely responsible for keeping time in IDF FreeRTOS. Therefore, anything that prevents Core 0 from incrementing the tick count, such as suspending the scheduler on Core 0, will cause the entire scheduler's timekeeping to lag behind. Idle Tasks Vanilla FreeRTOS will implicitly create an idle task of priority 0 when the scheduler is started. The idle task runs when no other task is ready to run, and it has the following responsibilities: Freeing the memory of deleted tasks Executing the application idle hook In IDF FreeRTOS, a separate pinned idle task is created for each core. The idle tasks on each core have the same responsibilities as their vanilla counterparts. Scheduler Suspension Vanilla FreeRTOS allows the scheduler to be suspended/resumed by calling vTaskSuspendAll() and xTaskResumeAll() respectively. While the scheduler is suspended: Task switching is disabled but interrupts are left enabled. Calling any blocking/yielding function is forbidden, and time slicing is disabled. The tick count is frozen, but the tick interrupt still occurs to execute the application tick hook. On scheduler resumption, xTaskResumeAll() catches up all of the lost ticks and unblock any timed-out tasks. In IDF FreeRTOS, suspending the scheduler across multiple cores is not possible. Therefore when vTaskSuspendAll() is called on a particular core (e.g., core A): Task switching is disabled only on core A but interrupts for core A are left enabled. Calling any blocking/yielding function on core A is forbidden. Time slicing is disabled on core A. If an interrupt on core A unblocks any tasks, tasks with affinity to core A will go into core A's own pending ready task list. Unpinned tasks or tasks with affinity to other cores can be scheduled on cores with the scheduler running. If the scheduler is suspended on all cores, tasks unblocked by an interrupt will be directed to the pending ready task lists of their pinned cores. For unpinned tasks, they will be placed in the pending ready list of the core where the interrupt occurred. If core A is on Core 0, the tick count is frozen, and a pended tick count is incremented instead. However, the tick interrupt will still occur in order to execute the application tick hook. When xTaskResumeAll() is called on a particular core (e.g., core A): Any tasks added to core A's pending ready task list will be resumed. If core A is Core 0, the pended tick count is unwound to catch up with the lost ticks. Warning Given that scheduler suspension on IDF FreeRTOS only suspends scheduling on a particular core, scheduler suspension is NOT a valid method of ensuring mutual exclusion between tasks when accessing shared data. Users should use proper locking primitives such as mutexes or spinlocks if they require mutual exclusion. Critical Sections Disabling Interrupts Vanilla FreeRTOS allows interrupts to be disabled and enabled by calling taskDISABLE_INTERRUPTS and taskENABLE_INTERRUPTS respectively. IDF FreeRTOS provides the same API. However, interrupts are only disabled or enabled on the current core. Disabling interrupts is a valid method of achieving mutual exclusion in Vanilla FreeRTOS (and single-core systems in general). However, in an SMP system, disabling interrupts is not a valid method of ensuring mutual exclusion. Critical sections that utilize a spinlock should be used instead. API Changes Vanilla FreeRTOS implements critical sections by disabling interrupts, which prevents preemptive context switches and the servicing of ISRs during a critical section. Thus a task/ISR that enters a critical section is guaranteed to be the sole entity to access a shared resource. Critical sections in Vanilla FreeRTOS have the following API: taskENTER_CRITICAL()enters a critical section by disabling interrupts taskEXIT_CRITICAL()exits a critical section by reenabling interrupts taskENTER_CRITICAL_FROM_ISR()enters a critical section from an ISR by disabling interrupt nesting taskEXIT_CRITICAL_FROM_ISR()exits a critical section from an ISR by reenabling interrupt nesting However, in an SMP system, merely disabling interrupts does not constitute a critical section as the presence of other cores means that a shared resource can still be concurrently accessed. Therefore, critical sections in IDF FreeRTOS are implemented using spinlocks. To accommodate the spinlocks, the IDF FreeRTOS critical section APIs contain an additional spinlock parameter as shown below: Spinlocks are of portMUX_TYPE(not to be confused to FreeRTOS mutexes) taskENTER_CRITICAL(&spinlock)enters a critical from a task context taskEXIT_CRITICAL(&spinlock)exits a critical section from a task context taskENTER_CRITICAL_ISR(&spinlock)enters a critical section from an interrupt context taskEXIT_CRITICAL_ISR(&spinlock)exits a critical section from an interrupt context Note The critical section API can be called recursively, i.e., nested critical sections. Entering a critical section multiple times recursively is valid so long as the critical section is exited the same number of times it was entered. However, given that critical sections can target different spinlocks, users should take care to avoid deadlocking when entering critical sections recursively. Spinlocks can be allocated statically or dynamically. As such, macros are provided for both static and dynamic initialization of spinlocks, as demonstrated by the following code snippets. Allocating a static spinlock and initializing it using portMUX_INITIALIZER_UNLOCKED: // Statically allocate and initialize the spinlock static portMUX_TYPE my_spinlock = portMUX_INITIALIZER_UNLOCKED; void some_function(void) { taskENTER_CRITICAL(&my_spinlock); // We are now in a critical section taskEXIT_CRITICAL(&my_spinlock); } Allocating a dynamic spinlock and initializing it using portMUX_INITIALIZE(): // Allocate the spinlock dynamically portMUX_TYPE *my_spinlock = malloc(sizeof(portMUX_TYPE)); // Initialize the spinlock dynamically portMUX_INITIALIZE(my_spinlock); ... taskENTER_CRITICAL(my_spinlock); // Access the resource taskEXIT_CRITICAL(my_spinlock); Implementation In IDF FreeRTOS, the process of a particular core entering and exiting a critical section is as follows: For taskENTER_CRITICAL(&spinlock)or taskENTER_CRITICAL_ISR(&spinlock) The core disables its interrupts or interrupt nesting up to configMAX_SYSCALL_INTERRUPT_PRIORITY. The core then spins on the spinlock using an atomic compare-and-set instruction until it acquires the lock. A lock is acquired when the core is able to set the lock's owner value to the core's ID. Once the spinlock is acquired, the function returns. The remainder of the critical section runs with interrupts or interrupt nesting disabled. - For taskEXIT_CRITICAL(&spinlock)or taskEXIT_CRITICAL_ISR(&spinlock) The core releases the spinlock by clearing the spinlock's owner value. The core re-enables interrupts or interrupt nesting. - Restrictions and Considerations Given that interrupts (or interrupt nesting) are disabled during a critical section, there are multiple restrictions regarding what can be done within critical sections. During a critical section, users should keep the following restrictions and considerations in mind: Critical sections should be kept as short as possible The longer the critical section lasts, the longer a pending interrupt can be delayed. A typical critical section should only access a few data structures and/or hardware registers. If possible, defer as much processing and/or event handling to the outside of critical sections. - FreeRTOS API should not be called from within a critical section Users should never call any blocking or yielding functions within a critical section Misc Floating Point Usage Usually, when a context switch occurs: the current state of a core's registers are saved to the stack of the task being switched out the previously saved state of the core's registers is loaded from the stack of the task being switched in However, IDF FreeRTOS implements Lazy Context Switching for the Floating Point Unit (FPU) registers of a core. In other words, when a context switch occurs on a particular core (e.g., Core 0), the state of the core's FPU registers is not immediately saved to the stack of the task getting switched out (e.g., Task A). The FPU registers are left untouched until: A different task (e.g., Task B) runs on the same core and uses FPU. This will trigger an exception that saves the FPU registers to Task A's stack. Task A gets scheduled to the same core and continues execution. Saving and restoring the FPU registers is not necessary in this case. However, given that tasks can be unpinned and thus can be scheduled on different cores (e.g., Task A switches to Core 1), it is unfeasible to copy and restore the FPU registers across cores. Therefore, when a task utilizes FPU by using a float type in its call flow, IDF FreeRTOS will automatically pin the task to the current core it is running on. This ensures that all tasks that use FPU are always pinned to a particular core. Furthermore, IDF FreeRTOS by default does not support the usage of FPU within an interrupt context given that the FPU register state is tied to a particular task. Note Users that require the use of the float type in an ISR routine should refer to the CONFIG_FREERTOS_FPU_IN_ISR configuration option. Note ESP targets that contain an FPU do not support hardware acceleration for double precision floating point arithmetic ( double). Instead, double is implemented via software, hence the behavioral restrictions regarding the float type do not apply to double. Note that due to the lack of hardware acceleration, double operations may consume significantly more CPU time in comparison to float. Single-Core Mode Although IDF FreeRTOS is modified for dual-core SMP, IDF FreeRTOS can also be built for single-core by enabling the CONFIG_FREERTOS_UNICORE option. For single-core targets (such as ESP32-S2 and ESP32-C3), the CONFIG_FREERTOS_UNICORE option is always enabled. For multi-core targets (such as ESP32 and ESP32-S3), CONFIG_FREERTOS_UNICORE can also be set, but will result in the application only running Core 0. When building in single-core mode, IDF FreeRTOS is designed to be identical to Vanilla FreeRTOS, thus all aforementioned SMP changes to kernel behavior are removed. As a result, building IDF FreeRTOS in single-core mode has the following characteristics: All operations performed by the kernel inside critical sections are now deterministic (i.e., no walking of linked lists inside critical sections). Vanilla FreeRTOS scheduling algorithm is restored (including perfect Round Robin time slicing). All SMP specific data is removed from single-core builds. SMP APIs can still be called in single-core mode. These APIs remain exposed to allow source code to be built for single-core and multi-core, without needing to call a different set of APIs. However, SMP APIs will not exhibit any SMP behavior in single-core mode, thus becoming equivalent to their single-core counterparts. For example: any ...ForCore(..., BaseType_t xCoreID)SMP API will only accept 0as a valid value for xCoreID. ...PinnedToCore()task creation APIs will simply ignore the xCoreIDcore affinity argument. Critical section APIs will still require a spinlock argument, but no spinlock will be taken and critical sections revert to simply disabling/enabling interrupts. API Reference This section introduces FreeRTOS types, functions, and macros. It is automatically generated from FreeRTOS header files. Task API Header File This header file can be included with: #include "freertos/task.h" Functions - static inline BaseType_t xTaskCreate(TaskFunction_t pxTaskCode, const char *const pcName, const configSTACK_DEPTH_TYPE usStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *const pxCreatedTask) Create a new task and add it to the list of tasks that are ready to run. Internally, within the FreeRTOS implementation, tasks use two blocks of memory. The first block is used to hold the task's data structures. The second block is used by the task as its stack. If a task is created using xTaskCreate() then both blocks of memory are automatically dynamically allocated inside the xTaskCreate() function. (see https://www.FreeRTOS.org/a00111.html). If a task is created using xTaskCreateStatic() then the application writer must provide the required memory. xTaskCreateStatic() therefore allows a task to be created without using any dynamic memory allocation. See xTaskCreateStatic() for a version that does not use any dynamic memory allocation. xTaskCreate() can only be used to create a task that has unrestricted access to the entire microcontroller memory map. Systems that include MPU support can alternatively create an MPU constrained task using xTaskCreateRestricted(). Example usage: // Task to be created. void vTaskCode( void * pvParameters ) { for( ;; ) { // Task code goes here. } } // Function that creates a task. void vOtherFunction( void ) { static uint8_t ucParameterToPass; TaskHandle_t xHandle = NULL; // Create the task, storing the handle. Note that the passed parameter ucParameterToPass // must exist for the lifetime of the task, so in this case is declared static. If it was just an // an automatic stack variable it might no longer exist, or at least have been corrupted, by the time // the new task attempts to access it. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle ); configASSERT( xHandle ); // Use the handle to delete the task. if( xHandle != NULL ) { vTaskDelete( xHandle ); } } Note If configNUMBER_OF_CORES > 1, this function will create an unpinned task (see tskNO_AFFINITY for more details). Note If program uses thread local variables (ones specified with "__thread" keyword) then storage for them will be allocated on the task's stack. - Parameters pxTaskCode -- Pointer to the task entry function. Tasks must be implemented to never return (i.e. continuous loop). pcName -- A descriptive name for the task. This is mainly used to facilitate debugging. Max length defined by configMAX_TASK_NAME_LEN - default is 16. usStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. Systems that include MPU support can optionally create tasks in a privileged (system) mode by setting bit portPRIVILEGE_BIT of the priority parameter. For example, to create a privileged task at priority 2 the uxPriority parameter should be set to ( 2 | portPRIVILEGE_BIT ). pxCreatedTask -- Used to pass back a handle by which the created task can be referenced. - - Returns pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined in the file projdefs.h - static inline TaskHandle_t xTaskCreateStatic(TaskFunction_t pxTaskCode, const char *const pcName, const uint32_t ulStackDepth, void *const pvParameters, UBaseType_t uxPriority, StackType_t *const puxStackBuffer, StaticTask_t *const pxTaskBuffer) Create a new task and add it to the list of tasks that are ready to run. Internally, within the FreeRTOS implementation, tasks use two blocks of memory. The first block is used to hold the task's data structures. The second block is used by the task as its stack. If a task is created using xTaskCreate() then both blocks of memory are automatically dynamically allocated inside the xTaskCreate() function. (see https://www.FreeRTOS.org/a00111.html). If a task is created using xTaskCreateStatic() then the application writer must provide the required memory. xTaskCreateStatic() therefore allows a task to be created without using any dynamic memory allocation. Example usage: // Dimensions of the buffer that the task being created will use as its stack. // NOTE: This is the number of words the stack will hold, not the number of // bytes. For example, if each stack item is 32-bits, and this is set to 100, // then 400 bytes (100 * 32-bits) will be allocated. #define STACK_SIZE 200 // Structure that will hold the TCB of the task being created. StaticTask_t xTaskBuffer; // Buffer that the task being created will use as its stack. Note this is // an array of StackType_t variables. The size of StackType_t is dependent on // the RTOS port. StackType_t xStack[ STACK_SIZE ]; // Function that implements the task being created. void vTaskCode( void * pvParameters ) { // The parameter value is expected to be 1 as 1 is passed in the // pvParameters value in the call to xTaskCreateStatic(). configASSERT( ( uint32_t ) pvParameters == 1UL ); for( ;; ) { // Task code goes here. } } // Function that creates a task. void vOtherFunction( void ) { TaskHandle_t xHandle = NULL; // Create the task without using any dynamic memory allocation. xHandle = xTaskCreateStatic( vTaskCode, // Function that implements the task. "NAME", // Text name for the task. STACK_SIZE, // Stack size in words, not bytes. ( void * ) 1, // Parameter passed into the task. tskIDLE_PRIORITY,// Priority at which the task is created. xStack, // Array to use as the task's stack. &xTaskBuffer ); // Variable to hold the task's data structure. // puxStackBuffer and pxTaskBuffer were not NULL, so the task will have // been created, and xHandle will be the task's handle. Use the handle // to suspend the task. vTaskSuspend( xHandle ); } Note If configNUMBER_OF_CORES > 1, this function will create an unpinned task (see tskNO_AFFINITY for more details). Note If program uses thread local variables (ones specified with "__thread" keyword) then storage for them will be allocated on the task's stack. - Parameters pxTaskCode -- Pointer to the task entry function. Tasks must be implemented to never return (i.e. continuous loop). pcName -- A descriptive name for the task. This is mainly used to facilitate debugging. The maximum length of the string is defined by configMAX_TASK_NAME_LEN in FreeRTOSConfig.h. ulStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task will run. puxStackBuffer -- Must point to a StackType_t array that has at least ulStackDepth indexes - the array will then be used as the task's stack, removing the need for the stack to be allocated dynamically. pxTaskBuffer -- Must point to a variable of type StaticTask_t, which will then be used to hold the task's data structures, removing the need for the memory to be allocated dynamically. - - Returns If neither puxStackBuffer nor pxTaskBuffer are NULL, then the task will be created and a handle to the created task is returned. If either puxStackBuffer or pxTaskBuffer are NULL then the task will not be created and NULL is returned. - void vTaskAllocateMPURegions(TaskHandle_t xTask, const MemoryRegion_t *const pxRegions) Memory regions are assigned to a restricted task when the task is created by a call to xTaskCreateRestricted(). These regions can be redefined using vTaskAllocateMPURegions(). Example usage: // Define an array of MemoryRegion_t structures that configures an MPU region // allowing read/write access for 1024 bytes starting at the beginning of the // ucOneKByte array. The other two of the maximum 3 definable regions are // unused so set to zero. static const MemoryRegion_t xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] = { // Base address Length Parameters { ucOneKByte, 1024, portMPU_REGION_READ_WRITE }, { 0, 0, 0 }, { 0, 0, 0 } }; void vATask( void *pvParameters ) { // This task was created such that it has access to certain regions of // memory as defined by the MPU configuration. At some point it is // desired that these MPU regions are replaced with that defined in the // xAltRegions const struct above. Use a call to vTaskAllocateMPURegions() // for this purpose. NULL is used as the task handle to indicate that this // function should modify the MPU regions of the calling task. vTaskAllocateMPURegions( NULL, xAltRegions ); // Now the task can continue its function, but from this point on can only // access its stack and the ucOneKByte array (unless any other statically // defined or shared regions have been declared elsewhere). } - Parameters xTask -- The handle of the task being updated. pxRegions -- A pointer to a MemoryRegion_t structure that contains the new memory region definitions. - - void vTaskDelete(TaskHandle_t xTaskToDelete) INCLUDE_vTaskDelete must be defined as 1 for this function to be available. See the configuration section for more information. Remove a task from the RTOS real time kernel's management. The task being deleted will be removed from all ready, blocked, suspended and event lists. NOTE: The idle task is responsible for freeing the kernel allocated memory from tasks that have been deleted. It is therefore important that the idle task is not starved of microcontroller processing time if your application makes any calls to vTaskDelete (). Memory allocated by the task code is not automatically freed, and should be freed before the task is deleted. See the demo application file death.c for sample code that utilises vTaskDelete (). Example usage: void vOtherFunction( void ) { TaskHandle_t xHandle; // Create the task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // Use the handle to delete the task. vTaskDelete( xHandle ); } - Parameters xTaskToDelete -- The handle of the task to be deleted. Passing NULL will cause the calling task to be deleted. - void vTaskDelay(const TickType_t xTicksToDelay) Delay a task for a given number of ticks. The actual time that the task remains blocked depends on the tick rate. The constant portTICK_PERIOD_MS can be used to calculate real time from the tick rate - with the resolution of one tick period. INCLUDE_vTaskDelay must be defined as 1 for this function to be available. See the configuration section for more information. vTaskDelay() specifies a time at which the task wishes to unblock relative to the time at which vTaskDelay() is called. For example, specifying a block period of 100 ticks will cause the task to unblock 100 ticks after vTaskDelay() is called. vTaskDelay() does not therefore provide a good method of controlling the frequency of a periodic task as the path taken through the code, as well as other task and interrupt activity, will affect the frequency at which vTaskDelay() gets called and therefore the time at which the task next executes. See xTaskDelayUntil() for an alternative API function designed to facilitate fixed frequency execution. It does this by specifying an absolute time (rather than a relative time) at which the calling task should unblock. Example usage: void vTaskFunction( void * pvParameters ) { // Block for 500ms. const TickType_t xDelay = 500 / portTICK_PERIOD_MS; for( ;; ) { // Simply toggle the LED every 500ms, blocking between each toggle. vToggleLED(); vTaskDelay( xDelay ); } } - Parameters xTicksToDelay -- The amount of time, in tick periods, that the calling task should block. - BaseType_t xTaskDelayUntil(TickType_t *const pxPreviousWakeTime, const TickType_t xTimeIncrement) INCLUDE_xTaskDelayUntil must be defined as 1 for this function to be available. See the configuration section for more information. Delay a task until a specified time. This function can be used by periodic tasks to ensure a constant execution frequency. This function differs from vTaskDelay () in one important aspect: vTaskDelay () will cause a task to block for the specified number of ticks from the time vTaskDelay () is called. It is therefore difficult to use vTaskDelay () by itself to generate a fixed execution frequency as the time between a task starting to execute and that task calling vTaskDelay () may not be fixed [the task may take a different path though the code between calls, or may get interrupted or preempted a different number of times each time it executes]. Whereas vTaskDelay () specifies a wake time relative to the time at which the function is called, xTaskDelayUntil () specifies the absolute (exact) time at which it wishes to unblock. The macro pdMS_TO_TICKS() can be used to calculate the number of ticks from a time specified in milliseconds with a resolution of one tick period. Example usage: // Perform an action every 10 ticks. void vTaskFunction( void * pvParameters ) { TickType_t xLastWakeTime; const TickType_t xFrequency = 10; BaseType_t xWasDelayed; // Initialise the xLastWakeTime variable with the current time. xLastWakeTime = xTaskGetTickCount (); for( ;; ) { // Wait for the next cycle. xWasDelayed = xTaskDelayUntil( &xLastWakeTime, xFrequency ); // Perform action here. xWasDelayed value can be used to determine // whether a deadline was missed if the code here took too long. } } - Parameters pxPreviousWakeTime -- Pointer to a variable that holds the time at which the task was last unblocked. The variable must be initialised with the current time prior to its first use (see the example below). Following this the variable is automatically updated within xTaskDelayUntil (). xTimeIncrement -- The cycle time period. The task will be unblocked at time *pxPreviousWakeTime + xTimeIncrement. Calling xTaskDelayUntil with the same xTimeIncrement parameter value will cause the task to execute with a fixed interface period. - - Returns Value which can be used to check whether the task was actually delayed. Will be pdTRUE if the task way delayed and pdFALSE otherwise. A task will not be delayed if the next expected wake time is in the past. - BaseType_t xTaskAbortDelay(TaskHandle_t xTask) INCLUDE_xTaskAbortDelay must be defined as 1 in FreeRTOSConfig.h for this function to be available. A task will enter the Blocked state when it is waiting for an event. The event it is waiting for can be a temporal event (waiting for a time), such as when vTaskDelay() is called, or an event on an object, such as when xQueueReceive() or ulTaskNotifyTake() is called. If the handle of a task that is in the Blocked state is used in a call to xTaskAbortDelay() then the task will leave the Blocked state, and return from whichever function call placed the task into the Blocked state. There is no 'FromISR' version of this function as an interrupt would need to know which object a task was blocked on in order to know which actions to take. For example, if the task was blocked on a queue the interrupt handler would then need to know if the queue was locked. - Parameters xTask -- The handle of the task to remove from the Blocked state. - Returns If the task referenced by xTask was not in the Blocked state then pdFAIL is returned. Otherwise pdPASS is returned. - UBaseType_t uxTaskPriorityGet(const TaskHandle_t xTask) INCLUDE_uxTaskPriorityGet must be defined as 1 for this function to be available. See the configuration section for more information. Obtain the priority of any task. Example usage: void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to obtain the priority of the created task. // It was created with tskIDLE_PRIORITY, but may have changed // it itself. if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY ) { // The task has changed it's priority. } // ... // Is our priority higher than the created task? if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) ) { // Our priority (obtained using NULL handle) is higher. } } - Parameters xTask -- Handle of the task to be queried. Passing a NULL handle results in the priority of the calling task being returned. - Returns The priority of xTask. - UBaseType_t uxTaskPriorityGetFromISR(const TaskHandle_t xTask) A version of uxTaskPriorityGet() that can be used from an ISR. - eTaskState eTaskGetState(TaskHandle_t xTask) INCLUDE_eTaskGetState must be defined as 1 for this function to be available. See the configuration section for more information. Obtain the state of any task. States are encoded by the eTaskState enumerated type. - Parameters xTask -- Handle of the task to be queried. - Returns The state of xTask at the time the function was called. Note the state of the task might change between the function being called, and the functions return value being tested by the calling task. - void vTaskGetInfo(TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState) configUSE_TRACE_FACILITY must be defined as 1 for this function to be available. See the configuration section for more information. Populates a TaskStatus_t structure with information about a task. Example usage: void vAFunction( void ) { TaskHandle_t xHandle; TaskStatus_t xTaskDetails; // Obtain the handle of a task from its name. xHandle = xTaskGetHandle( "Task_Name" ); // Check the handle is not NULL. configASSERT( xHandle ); // Use the handle to obtain further information about the task. vTaskGetInfo( xHandle, &xTaskDetails, pdTRUE, // Include the high water mark in xTaskDetails. eInvalid ); // Include the task state in xTaskDetails. } - Parameters xTask -- Handle of the task being queried. If xTask is NULL then information will be returned about the calling task. pxTaskStatus -- A pointer to the TaskStatus_t structure that will be filled with information about the task referenced by the handle passed using the xTask parameter. xGetFreeStackSpace -- The TaskStatus_t structure contains a member to report the stack high water mark of the task being queried. Calculating the stack high water mark takes a relatively long time, and can make the system temporarily unresponsive - so the xGetFreeStackSpace parameter is provided to allow the high water mark checking to be skipped. The high watermark value will only be written to the TaskStatus_t structure if xGetFreeStackSpace is not set to pdFALSE; eState -- The TaskStatus_t structure contains a member to report the state of the task being queried. Obtaining the task state is not as fast as a simple assignment - so the eState parameter is provided to allow the state information to be omitted from the TaskStatus_t structure. To obtain state information then set eState to eInvalid - otherwise the value passed in eState will be reported as the task state in the TaskStatus_t structure. - - void vTaskPrioritySet(TaskHandle_t xTask, UBaseType_t uxNewPriority) INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available. See the configuration section for more information. Set the priority of any task. A context switch will occur before the function returns if the priority being set is higher than the currently executing task. Example usage: void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to raise the priority of the created task. vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 ); // ... // Use a NULL handle to raise our priority to the same value. vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 ); } - Parameters xTask -- Handle to the task for which the priority is being set. Passing a NULL handle results in the priority of the calling task being set. uxNewPriority -- The priority to which the task will be set. - - void vTaskSuspend(TaskHandle_t xTaskToSuspend) INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. See the configuration section for more information. Suspend any task. When suspended a task will never get any microcontroller processing time, no matter what its priority. Calls to vTaskSuspend are not accumulative - i.e. calling vTaskSuspend () twice on the same task still only requires one call to vTaskResume () to ready the suspended task. Example usage: void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to suspend the created task. vTaskSuspend( xHandle ); // ... // The created task will not run during this period, unless // another task calls vTaskResume( xHandle ). //... // Suspend ourselves. vTaskSuspend( NULL ); // We cannot get here unless another task calls vTaskResume // with our handle as the parameter. } - Parameters xTaskToSuspend -- Handle to the task being suspended. Passing a NULL handle will cause the calling task to be suspended. - void vTaskResume(TaskHandle_t xTaskToResume) INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. See the configuration section for more information. Resumes a suspended task. A task that has been suspended by one or more calls to vTaskSuspend () will be made available for running again by a single call to vTaskResume (). Example usage: void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to suspend the created task. vTaskSuspend( xHandle ); // ... // The created task will not run during this period, unless // another task calls vTaskResume( xHandle ). //... // Resume the suspended task ourselves. vTaskResume( xHandle ); // The created task will once again get microcontroller processing // time in accordance with its priority within the system. } - Parameters xTaskToResume -- Handle to the task being readied. - BaseType_t xTaskResumeFromISR(TaskHandle_t xTaskToResume) INCLUDE_xTaskResumeFromISR must be defined as 1 for this function to be available. See the configuration section for more information. An implementation of vTaskResume() that can be called from within an ISR. A task that has been suspended by one or more calls to vTaskSuspend () will be made available for running again by a single call to xTaskResumeFromISR (). xTaskResumeFromISR() should not be used to synchronise a task with an interrupt if there is a chance that the interrupt could arrive prior to the task being suspended - as this can lead to interrupts being missed. Use of a semaphore as a synchronisation mechanism would avoid this eventuality. - Parameters xTaskToResume -- Handle to the task being readied. - Returns pdTRUE if resuming the task should result in a context switch, otherwise pdFALSE. This is used by the ISR to determine if a context switch may be required following the ISR. - void vTaskSuspendAll(void) Suspends the scheduler without disabling interrupts. Context switches will not occur while the scheduler is suspended. After calling vTaskSuspendAll () the calling task will continue to execute without risk of being swapped out until a call to xTaskResumeAll () has been made. API functions that have the potential to cause a context switch (for example, xTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler is suspended. Example usage: void vTask1( void * pvParameters ) { for( ;; ) { // Task code goes here. // ... // At some point the task wants to perform a long operation during // which it does not want to get swapped out. It cannot use // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the // operation may cause interrupts to be missed - including the // ticks. // Prevent the real time kernel swapping out the task. vTaskSuspendAll (); // Perform the operation here. There is no need to use critical // sections as we have all the microcontroller processing time. // During this time interrupts will still operate and the kernel // tick count will be maintained. // ... // The operation is complete. Restart the kernel. xTaskResumeAll (); } } - BaseType_t xTaskResumeAll(void) Resumes scheduler activity after it was suspended by a call to vTaskSuspendAll(). xTaskResumeAll() only resumes the scheduler. It does not unsuspend tasks that were previously suspended by a call to vTaskSuspend(). Example usage: void vTask1( void * pvParameters ) { for( ;; ) { // Task code goes here. // ... // At some point the task wants to perform a long operation during // which it does not want to get swapped out. It cannot use // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the // operation may cause interrupts to be missed - including the // ticks. // Prevent the real time kernel swapping out the task. vTaskSuspendAll (); // Perform the operation here. There is no need to use critical // sections as we have all the microcontroller processing time. // During this time interrupts will still operate and the real // time kernel tick count will be maintained. // ... // The operation is complete. Restart the kernel. We want to force // a context switch - but there is no point if resuming the scheduler // caused a context switch already. if( !xTaskResumeAll () ) { taskYIELD (); } } } - Returns If resuming the scheduler caused a context switch then pdTRUE is returned, otherwise pdFALSE is returned. - TickType_t xTaskGetTickCount(void) - Returns The count of ticks since vTaskStartScheduler was called. - TickType_t xTaskGetTickCountFromISR(void) This is a version of xTaskGetTickCount() that is safe to be called from an ISR - provided that TickType_t is the natural word size of the microcontroller being used or interrupt nesting is either not supported or not being used. - Returns The count of ticks since vTaskStartScheduler was called. - UBaseType_t uxTaskGetNumberOfTasks(void) - Returns The number of tasks that the real time kernel is currently managing. This includes all ready, blocked and suspended tasks. A task that has been deleted but not yet freed by the idle task will also be included in the count. - char *pcTaskGetName(TaskHandle_t xTaskToQuery) - Returns The text (human readable) name of the task referenced by the handle xTaskToQuery. A task can query its own name by either passing in its own handle, or by setting xTaskToQuery to NULL. - TaskHandle_t xTaskGetHandle(const char *pcNameToQuery) NOTE: This function takes a relatively long time to complete and should be used sparingly. - Returns The handle of the task that has the human readable name pcNameToQuery. NULL is returned if no matching name is found. INCLUDE_xTaskGetHandle must be set to 1 in FreeRTOSConfig.h for pcTaskGetHandle() to be available. - BaseType_t xTaskGetStaticBuffers(TaskHandle_t xTask, StackType_t **ppuxStackBuffer, StaticTask_t **ppxTaskBuffer) Retrieve pointers to a statically created task's data structure buffer and stack buffer. These are the same buffers that are supplied at the time of creation. - Parameters xTask -- The task for which to retrieve the buffers. ppuxStackBuffer -- Used to return a pointer to the task's stack buffer. ppxTaskBuffer -- Used to return a pointer to the task's data structure buffer. - - Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. - UBaseType_t uxTaskGetStackHighWaterMark(TaskHandle_t xTask) INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for this function to be available. Returns the high water mark of the stack associated with xTask. That is, the minimum free stack space there has been (in words, so on a 32 bit machine a value of 1 means 4 bytes) since the task started. The smaller the returned number the closer the task has come to overflowing its stack. uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the same except for their return type. Using configSTACK_DEPTH_TYPE allows the user to determine the return type. It gets around the problem of the value overflowing on 8-bit types without breaking backward compatibility for applications that expect an 8-bit return type. - Parameters xTask -- Handle of the task associated with the stack to be checked. Set xTask to NULL to check the stack of the calling task. - Returns The smallest amount of free stack space there has been (in words, so actual spaces on the stack rather than bytes) since the task referenced by xTask was created. - configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2(TaskHandle_t xTask) INCLUDE_uxTaskGetStackHighWaterMark2 must be set to 1 in FreeRTOSConfig.h for this function to be available. Returns the high water mark of the stack associated with xTask. That is, the minimum free stack space there has been (in words, so on a 32 bit machine a value of 1 means 4 bytes) since the task started. The smaller the returned number the closer the task has come to overflowing its stack. uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the same except for their return type. Using configSTACK_DEPTH_TYPE allows the user to determine the return type. It gets around the problem of the value overflowing on 8-bit types without breaking backward compatibility for applications that expect an 8-bit return type. - Parameters xTask -- Handle of the task associated with the stack to be checked. Set xTask to NULL to check the stack of the calling task. - Returns The smallest amount of free stack space there has been (in words, so actual spaces on the stack rather than bytes) since the task referenced by xTask was created. - void vTaskSetApplicationTaskTag(TaskHandle_t xTask, TaskHookFunction_t pxHookFunction) Sets pxHookFunction to be the task hook function used by the task xTask. Passing xTask as NULL has the effect of setting the calling tasks hook function. - TaskHookFunction_t xTaskGetApplicationTaskTag(TaskHandle_t xTask) Returns the pxHookFunction value assigned to the task xTask. Do not call from an interrupt service routine - call xTaskGetApplicationTaskTagFromISR() instead. - TaskHookFunction_t xTaskGetApplicationTaskTagFromISR(TaskHandle_t xTask) Returns the pxHookFunction value assigned to the task xTask. Can be called from an interrupt service routine. - void vTaskSetThreadLocalStoragePointer(TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue) Each task contains an array of pointers that is dimensioned by the configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The kernel does not use the pointers itself, so the application writer can use the pointers for any purpose they wish. The following two functions are used to set and query a pointer respectively. - void *pvTaskGetThreadLocalStoragePointer(TaskHandle_t xTaskToQuery, BaseType_t xIndex) - void vApplicationGetIdleTaskMemory(StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize) This function is used to provide a statically allocated block of memory to FreeRTOS to hold the Idle Task TCB. This function is required when configSUPPORT_STATIC_ALLOCATION is set. For more information see this URI: https://www.FreeRTOS.org/a00110.html#configSUPPORT_STATIC_ALLOCATION - Parameters ppxIdleTaskTCBBuffer -- A handle to a statically allocated TCB buffer ppxIdleTaskStackBuffer -- A handle to a statically allocated Stack buffer for the idle task pulIdleTaskStackSize -- A pointer to the number of elements that will fit in the allocated stack buffer - - BaseType_t xTaskCallApplicationTaskHook(TaskHandle_t xTask, void *pvParameter) Calls the hook function associated with xTask. Passing xTask as NULL has the effect of calling the Running tasks (the calling task) hook function. pvParameter is passed to the hook function for the task to interpret as it wants. The return value is the value returned by the task hook function registered by the user. - TaskHandle_t xTaskGetIdleTaskHandle(void) xTaskGetIdleTaskHandle() is only available if INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h. Simply returns the handle of the idle task of the current core. It is not valid to call xTaskGetIdleTaskHandle() before the scheduler has been started. - UBaseType_t uxTaskGetSystemState(TaskStatus_t *const pxTaskStatusArray, const UBaseType_t uxArraySize, configRUN_TIME_COUNTER_TYPE *const pulTotalRunTime) configUSE_TRACE_FACILITY must be defined as 1 in FreeRTOSConfig.h for uxTaskGetSystemState() to be available. uxTaskGetSystemState() populates an TaskStatus_t structure for each task in the system. TaskStatus_t structures contain, among other things, members for the task handle, task name, task priority, task state, and total amount of run time consumed by the task. See the TaskStatus_t structure definition in this file for the full member list. NOTE: This function is intended for debugging use only as its use results in the scheduler remaining suspended for an extended period. Example usage: // This example demonstrates how a human readable table of run time stats // information is generated from raw data provided by uxTaskGetSystemState(). // The human readable table is written to pcWriteBuffer void vTaskGetRunTimeStats( char *pcWriteBuffer ) { TaskStatus_t *pxTaskStatusArray; volatile UBaseType_t uxArraySize, x; configRUN_TIME_COUNTER_TYPE ulTotalRunTime, ulStatsAsPercentage; // Make sure the write buffer does not contain a string. pcWriteBuffer = 0x00; // Take a snapshot of the number of tasks in case it changes while this // function is executing. uxArraySize = uxTaskGetNumberOfTasks(); // Allocate a TaskStatus_t structure for each task. An array could be // allocated statically at compile time. pxTaskStatusArray = pvPortMalloc( uxArraySize * sizeof( TaskStatus_t ) ); if( pxTaskStatusArray != NULL ) { // Generate raw status information about each task. uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime ); // For percentage calculations. ulTotalRunTime /= 100UL; // Avoid divide by zero errors. if( ulTotalRunTime > 0 ) { // For each populated position in the pxTaskStatusArray array, // format the raw data as human readable ASCII data for( x = 0; x < uxArraySize; x++ ) { // What percentage of the total run time has the task used? // This will always be rounded down to the nearest integer. // ulTotalRunTimeDiv100 has already been divided by 100. ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime; if( ulStatsAsPercentage > 0UL ) { sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage ); } else { // If the percentage is zero here then the task has // consumed less than 1% of the total run time. sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter ); } pcWriteBuffer += strlen( ( char * ) pcWriteBuffer ); } } // The array is no longer needed, free the memory it consumes. vPortFree( pxTaskStatusArray ); } } - Parameters pxTaskStatusArray -- A pointer to an array of TaskStatus_t structures. The array must contain at least one TaskStatus_t structure for each task that is under the control of the RTOS. The number of tasks under the control of the RTOS can be determined using the uxTaskGetNumberOfTasks() API function. uxArraySize -- The size of the array pointed to by the pxTaskStatusArray parameter. The size is specified as the number of indexes in the array, or the number of TaskStatus_t structures contained in the array, not by the number of bytes in the array. pulTotalRunTime -- If configGENERATE_RUN_TIME_STATS is set to 1 in FreeRTOSConfig.h then *pulTotalRunTime is set by uxTaskGetSystemState() to the total run time (as defined by the run time stats clock, see https://www.FreeRTOS.org/rtos-run-time-stats.html) since the target booted. pulTotalRunTime can be set to NULL to omit the total run time information. - - Returns The number of TaskStatus_t structures that were populated by uxTaskGetSystemState(). This should equal the number returned by the uxTaskGetNumberOfTasks() API function, but will be zero if the value passed in the uxArraySize parameter was too small. - void vTaskList(char *pcWriteBuffer) configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must both be defined as 1 for this function to be available. See the configuration section of the FreeRTOS.org website for more information. NOTE 1: This function will disable interrupts for its duration. It is not intended for normal application runtime use but as a debug aid. Lists all the current tasks, along with their current state and stack usage high water mark. Tasks are reported as blocked ('B'), ready ('R'), deleted ('D') or suspended ('S'). PLEASE NOTE: This function is provided for convenience only, and is used by many of the demo applications. Do not consider it to be part of the scheduler. vTaskList() calls uxTaskGetSystemState(), then formats part of the uxTaskGetSystemState() output into a human readable table that displays task: names, states, priority, stack usage and task number. Stack usage specified as the number of unused StackType_t words stack can hold on top of stack - not the number of bytes. vTaskList() has a dependency on the sprintf() C library function that might bloat the code size, use a lot of stack, and provide different results on different platforms. An alternative, tiny, third party, and limited functionality implementation of sprintf() is provided in many of the FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note printf-stdarg.c does not provide a full snprintf() implementation!). It is recommended that production systems call uxTaskGetSystemState() directly to get access to raw stats data, rather than indirectly through a call to vTaskList(). - Parameters pcWriteBuffer -- A buffer into which the above mentioned details will be written, in ASCII form. This buffer is assumed to be large enough to contain the generated report. Approximately 40 bytes per task should be sufficient. - void vTaskGetRunTimeStats(char *pcWriteBuffer) configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS must both be defined as 1 for this function to be available. The application must also then provide definitions for portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() to configure a peripheral timer/counter and return the timers current count value respectively. The counter should be at least 10 times the frequency of the tick count. NOTE 1: This function will disable interrupts for its duration. It is not intended for normal application runtime use but as a debug aid. Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total accumulated execution time being stored for each task. The resolution of the accumulated time value depends on the frequency of the timer configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. Calling vTaskGetRunTimeStats() writes the total execution time of each task into a buffer, both as an absolute count value and as a percentage of the total system execution time. NOTE 2: This function is provided for convenience only, and is used by many of the demo applications. Do not consider it to be part of the scheduler. vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the uxTaskGetSystemState() output into a human readable table that displays the amount of time each task has spent in the Running state in both absolute and percentage terms. vTaskGetRunTimeStats() has a dependency on the sprintf() C library function that might bloat the code size, use a lot of stack, and provide different results on different platforms. An alternative, tiny, third party, and limited functionality implementation of sprintf() is provided in many of the FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note printf-stdarg.c does not provide a full snprintf() implementation!). It is recommended that production systems call uxTaskGetSystemState() directly to get access to raw stats data, rather than indirectly through a call to vTaskGetRunTimeStats(). - Parameters pcWriteBuffer -- A buffer into which the execution times will be written, in ASCII form. This buffer is assumed to be large enough to contain the generated report. Approximately 40 bytes per task should be sufficient. - configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimeCounter(void) configGENERATE_RUN_TIME_STATS, configUSE_STATS_FORMATTING_FUNCTIONS and INCLUDE_xTaskGetIdleTaskHandle must all be defined as 1 for these functions to be available. The application must also then provide definitions for portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() to configure a peripheral timer/counter and return the timers current count value respectively. The counter should be at least 10 times the frequency of the tick count. Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total accumulated execution time being stored for each task. The resolution of the accumulated time value depends on the frequency of the timer configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. While uxTaskGetSystemState() and vTaskGetRunTimeStats() writes the total execution time of each task into a buffer, ulTaskGetIdleRunTimeCounter() returns the total execution time of just the idle task and ulTaskGetIdleRunTimePercent() returns the percentage of the CPU time used by just the idle task. Note the amount of idle time is only a good measure of the slack time in a system if there are no other tasks executing at the idle priority, tickless idle is not used, and configIDLE_SHOULD_YIELD is set to 0. Note If configNUMBER_OF_CORES > 1, calling this function will query the idle task of the current core. - Returns The total run time of the idle task or the percentage of the total run time consumed by the idle task. This is the amount of time the idle task has actually been executing. The unit of time is dependent on the frequency configured using the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() macros. - configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimePercent(void) - BaseType_t xTaskGenericNotifyWait(UBaseType_t uxIndexToWaitOn, uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait) Waits for a direct to task notification to be pending at a given index within an array of direct to task notifications. See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this function to be available. Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of the task's notification values. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. A notification sent to a task will remain pending until it is cleared by the task calling xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() (or their un-indexed equivalents). If the task was already in the Blocked state to wait for a notification when the notification arrives then the task will automatically be removed from the Blocked state (unblocked) and the notification cleared. A task can use xTaskNotifyWaitIndexed() to [optionally] block to wait for a notification to be pending, or ulTaskNotifyTakeIndexed() to [optionally] block to wait for a notification value to have a non-zero value. The task does not consume any CPU time while it is in the Blocked state. NOTE Each notification within the array operates independently - a task can only block on one notification within the array at a time and will not be unblocked by a notification sent to any other array index. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. xTaskNotifyWait() is the original API function, and remains backward compatible by always operating on the notification value at index 0 in the array. Calling xTaskNotifyWait() is equivalent to calling xTaskNotifyWaitIndexed() with the uxIndexToWaitOn parameter set to 0. - Parameters uxIndexToWaitOn -- The index within the calling task's array of notification values on which the calling task will wait for a notification to be received. uxIndexToWaitOn must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyWait() does not have this parameter and always waits for notifications on index 0. ulBitsToClearOnEntry -- Bits that are set in ulBitsToClearOnEntry value will be cleared in the calling task's notification value before the task checks to see if any notifications are pending, and optionally blocks if no notifications are pending. Setting ulBitsToClearOnEntry to ULONG_MAX (if limits.h is included) or 0xffffffffUL (if limits.h is not included) will have the effect of resetting the task's notification value to 0. Setting ulBitsToClearOnEntry to 0 will leave the task's notification value unchanged. ulBitsToClearOnExit -- If a notification is pending or received before the calling task exits the xTaskNotifyWait() function then the task's notification value (see the xTaskNotify() API function) is passed out using the pulNotificationValue parameter. Then any bits that are set in ulBitsToClearOnExit will be cleared in the task's notification value (note *pulNotificationValue is set before any bits are cleared). Setting ulBitsToClearOnExit to ULONG_MAX (if limits.h is included) or 0xffffffffUL (if limits.h is not included) will have the effect of resetting the task's notification value to 0 before the function exits. Setting ulBitsToClearOnExit to 0 will leave the task's notification value unchanged when the function exits (in which case the value passed out in pulNotificationValue will match the task's notification value). pulNotificationValue -- Used to pass the task's notification value out of the function. Note the value passed out will not be effected by the clearing of any bits caused by ulBitsToClearOnExit being non-zero. xTicksToWait -- The maximum amount of time that the task should wait in the Blocked state for a notification to be received, should a notification not already be pending when xTaskNotifyWait() was called. The task will not consume any processing time while it is in the Blocked state. This is specified in kernel ticks, the macro pdMS_TO_TICKS( value_in_ms ) can be used to convert a time specified in milliseconds to a time specified in ticks. - - Returns If a notification was received (including notifications that were already pending when xTaskNotifyWait was called) then pdPASS is returned. Otherwise pdFAIL is returned. - void vTaskGenericNotifyGiveFromISR(TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, BaseType_t *pxHigherPriorityTaskWoken) A version of xTaskNotifyGiveIndexed() that can be called from an interrupt service routine (ISR). See https://www.FreeRTOS.org/RTOS-task-notifications.html for more details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro to be available. Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of the task's notification values. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. vTaskNotifyGiveIndexedFromISR() is intended for use when task notifications are used as light weight and faster binary or counting semaphore equivalents. Actual FreeRTOS semaphores are given from an ISR using the xSemaphoreGiveFromISR() API function, the equivalent action that instead uses a task notification is vTaskNotifyGiveIndexedFromISR(). When task notifications are being used as a binary or counting semaphore equivalent then the task being notified should wait for the notification using the ulTaskNotifyTakeIndexed() API function rather than the xTaskNotifyWaitIndexed() API function. NOTE Each notification within the array operates independently - a task can only block on one notification within the array at a time and will not be unblocked by a notification sent to any other array index. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. xTaskNotifyFromISR() is the original API function, and remains backward compatible by always operating on the notification value at index 0 within the array. Calling xTaskNotifyGiveFromISR() is equivalent to calling xTaskNotifyGiveIndexedFromISR() with the uxIndexToNotify parameter set to 0. - Parameters xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyGiveFromISR() does not have this parameter and always sends notifications to index 0. pxHigherPriorityTaskWoken -- vTaskNotifyGiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the task to which the notification was sent to leave the Blocked state, and the unblocked task has a priority higher than the currently running task. If vTaskNotifyGiveFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. How a context switch is requested from an ISR is dependent on the port - see the documentation page for the port in use. - - BaseType_t xTaskGenericNotifyStateClear(TaskHandle_t xTask, UBaseType_t uxIndexToClear) See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these functions to be available. Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. If a notification is sent to an index within the array of notifications then the notification at that index is said to be 'pending' until it is read or explicitly cleared by the receiving task. xTaskNotifyStateClearIndexed() is the function that clears a pending notification without reading the notification value. The notification value at the same array index is not altered. Set xTask to NULL to clear the notification state of the calling task. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. xTaskNotifyStateClear() is the original API function, and remains backward compatible by always operating on the notification value at index 0 within the array. Calling xTaskNotifyStateClear() is equivalent to calling xTaskNotifyStateClearIndexed() with the uxIndexToNotify parameter set to 0. - Parameters xTask -- The handle of the RTOS task that will have a notification state cleared. Set xTask to NULL to clear a notification state in the calling task. To obtain a task's handle create the task using xTaskCreate() and make use of the pxCreatedTask parameter, or create the task using xTaskCreateStatic() and store the returned value, or use the task's name in a call to xTaskGetHandle(). uxIndexToClear -- The index within the target task's array of notification values to act upon. For example, setting uxIndexToClear to 1 will clear the state of the notification at index 1 within the array. uxIndexToClear must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. ulTaskNotifyStateClear() does not have this parameter and always acts on the notification at index 0. - - Returns pdTRUE if the task's notification state was set to eNotWaitingNotification, otherwise pdFALSE. - uint32_t ulTaskGenericNotifyValueClear(TaskHandle_t xTask, UBaseType_t uxIndexToClear, uint32_t ulBitsToClear) See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these functions to be available. Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. ulTaskNotifyValueClearIndexed() clears the bits specified by the ulBitsToClear bit mask in the notification value at array index uxIndexToClear of the task referenced by xTask. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. ulTaskNotifyValueClear() is the original API function, and remains backward compatible by always operating on the notification value at index 0 within the array. Calling ulTaskNotifyValueClear() is equivalent to calling ulTaskNotifyValueClearIndexed() with the uxIndexToClear parameter set to 0. - Parameters xTask -- The handle of the RTOS task that will have bits in one of its notification values cleared. Set xTask to NULL to clear bits in a notification value of the calling task. To obtain a task's handle create the task using xTaskCreate() and make use of the pxCreatedTask parameter, or create the task using xTaskCreateStatic() and store the returned value, or use the task's name in a call to xTaskGetHandle(). uxIndexToClear -- The index within the target task's array of notification values in which to clear the bits. uxIndexToClear must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. ulTaskNotifyValueClear() does not have this parameter and always clears bits in the notification value at index 0. ulBitsToClear -- Bit mask of the bits to clear in the notification value of xTask. Set a bit to 1 to clear the corresponding bits in the task's notification value. Set ulBitsToClear to 0xffffffff (UINT_MAX on 32-bit architectures) to clear the notification value to 0. Set ulBitsToClear to 0 to query the task's notification value without clearing any bits. - - Returns The value of the target task's notification value before the bits specified by ulBitsToClear were cleared. - void vTaskSetTimeOutState(TimeOut_t *const pxTimeOut) Capture the current time for future use with xTaskCheckForTimeOut(). - Parameters pxTimeOut -- Pointer to a timeout object into which the current time is to be captured. The captured time includes the tick count and the number of times the tick count has overflowed since the system first booted. - BaseType_t xTaskCheckForTimeOut(TimeOut_t *const pxTimeOut, TickType_t *const pxTicksToWait) Determines if pxTicksToWait ticks has passed since a time was captured using a call to vTaskSetTimeOutState(). The captured time includes the tick count and the number of times the tick count has overflowed. Example Usage: // Driver library function used to receive uxWantedBytes from an Rx buffer // that is filled by a UART interrupt. If there are not enough bytes in the // Rx buffer then the task enters the Blocked state until it is notified that // more data has been placed into the buffer. If there is still not enough // data then the task re-enters the Blocked state, and xTaskCheckForTimeOut() // is used to re-calculate the Block time to ensure the total amount of time // spent in the Blocked state does not exceed MAX_TIME_TO_WAIT. This // continues until either the buffer contains at least uxWantedBytes bytes, // or the total amount of time spent in the Blocked state reaches // MAX_TIME_TO_WAIT - at which point the task reads however many bytes are // available up to a maximum of uxWantedBytes. size_t xUART_Receive( uint8_t *pucBuffer, size_t uxWantedBytes ) { size_t uxReceived = 0; TickType_t xTicksToWait = MAX_TIME_TO_WAIT; TimeOut_t xTimeOut; // Initialize xTimeOut. This records the time at which this function // was entered. vTaskSetTimeOutState( &xTimeOut ); // Loop until the buffer contains the wanted number of bytes, or a // timeout occurs. while( UART_bytes_in_rx_buffer( pxUARTInstance ) < uxWantedBytes ) { // The buffer didn't contain enough data so this task is going to // enter the Blocked state. Adjusting xTicksToWait to account for // any time that has been spent in the Blocked state within this // function so far to ensure the total amount of time spent in the // Blocked state does not exceed MAX_TIME_TO_WAIT. if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) != pdFALSE ) { //Timed out before the wanted number of bytes were available, // exit the loop. break; } // Wait for a maximum of xTicksToWait ticks to be notified that the // receive interrupt has placed more data into the buffer. ulTaskNotifyTake( pdTRUE, xTicksToWait ); } // Attempt to read uxWantedBytes from the receive buffer into pucBuffer. // The actual number of bytes read (which might be less than // uxWantedBytes) is returned. uxReceived = UART_read_from_receive_buffer( pxUARTInstance, pucBuffer, uxWantedBytes ); return uxReceived; } - Parameters pxTimeOut -- The time status as captured previously using vTaskSetTimeOutState. If the timeout has not yet occurred, it is updated to reflect the current time status. pxTicksToWait -- The number of ticks to check for timeout i.e. if pxTicksToWait ticks have passed since pxTimeOut was last updated (either by vTaskSetTimeOutState() or xTaskCheckForTimeOut()), the timeout has occurred. If the timeout has not occurred, pxTicksToWait is updated to reflect the number of remaining ticks. - - Returns If timeout has occurred, pdTRUE is returned. Otherwise pdFALSE is returned and pxTicksToWait is updated to reflect the number of remaining ticks. - BaseType_t xTaskCatchUpTicks(TickType_t xTicksToCatchUp) This function corrects the tick count value after the application code has held interrupts disabled for an extended period resulting in tick interrupts having been missed. This function is similar to vTaskStepTick(), however, unlike vTaskStepTick(), xTaskCatchUpTicks() may move the tick count forward past a time at which a task should be removed from the blocked state. That means tasks may have to be removed from the blocked state as the tick count is moved. - Parameters xTicksToCatchUp -- The number of tick interrupts that have been missed due to interrupts being disabled. Its value is not computed automatically, so must be computed by the application writer. - Returns pdTRUE if moving the tick count forward resulted in a task leaving the blocked state and a context switch being performed. Otherwise pdFALSE. Structures - struct xTASK_STATUS Used with the uxTaskGetSystemState() function to return the state of each task in the system. Public Members - TaskHandle_t xHandle The handle of the task to which the rest of the information in the structure relates. - const char *pcTaskName A pointer to the task's name. This value will be invalid if the task was deleted since the structure was populated! - UBaseType_t xTaskNumber A number unique to the task. - eTaskState eCurrentState The state in which the task existed when the structure was populated. - UBaseType_t uxCurrentPriority The priority at which the task was running (may be inherited) when the structure was populated. - UBaseType_t uxBasePriority The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex. Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. - configRUN_TIME_COUNTER_TYPE ulRunTimeCounter The total run time allocated to the task so far, as defined by the run time stats clock. See https://www.FreeRTOS.org/rtos-run-time-stats.html. Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. - StackType_t *pxStackBase Points to the lowest address of the task's stack area. - configSTACK_DEPTH_TYPE usStackHighWaterMark The minimum amount of stack space that has remained for the task since the task was created. The closer this value is to zero the closer the task has come to overflowing its stack. - BaseType_t xCoreID Core this task is pinned to (0, 1, or tskNO_AFFINITY). If configNUMBER_OF_CORES == 1, this will always be 0. - TaskHandle_t xHandle Macros - tskIDLE_PRIORITY Defines the priority used by the idle task. This must not be modified. - tskNO_AFFINITY Macro representing and unpinned (i.e., "no affinity") task in xCoreID parameters - taskVALID_CORE_ID(xCoreID) Macro to check if an xCoreID value is valid - Returns pdTRUE if valid, pdFALSE otherwise. - taskYIELD() Macro for forcing a context switch. - taskENTER_CRITICAL(x) Macro to mark the start of a critical code region. Preemptive context switches cannot occur when in a critical region. NOTE: This may alter the stack (depending on the portable implementation) so must be used with care! - taskENTER_CRITICAL_FROM_ISR() - taskENTER_CRITICAL_ISR(x) - taskEXIT_CRITICAL(x) Macro to mark the end of a critical code region. Preemptive context switches cannot occur when in a critical region. NOTE: This may alter the stack (depending on the portable implementation) so must be used with care! - taskEXIT_CRITICAL_FROM_ISR(x) - taskEXIT_CRITICAL_ISR(x) - taskDISABLE_INTERRUPTS() Macro to disable all maskable interrupts. - taskENABLE_INTERRUPTS() Macro to enable microcontroller interrupts. - taskSCHEDULER_SUSPENDED Definitions returned by xTaskGetSchedulerState(). taskSCHEDULER_SUSPENDED is 0 to generate more optimal code when configASSERT() is defined as the constant is used in assert() statements. - taskSCHEDULER_NOT_STARTED - taskSCHEDULER_RUNNING - xTaskNotifyIndexed(xTaskToNotify, uxIndexToNotify, ulValue, eAction) See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these functions to be available. Sends a direct to task notification to a task, with an optional value and action. Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of the task's notification values. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. A task can use xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() to [optionally] block to wait for a notification to be pending. The task does not consume any CPU time while it is in the Blocked state. A notification sent to a task will remain pending until it is cleared by the task calling xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() (or their un-indexed equivalents). If the task was already in the Blocked state to wait for a notification when the notification arrives then the task will automatically be removed from the Blocked state (unblocked) and the notification cleared. NOTE Each notification within the array operates independently - a task can only block on one notification within the array at a time and will not be unblocked by a notification sent to any other array index. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. xTaskNotify() is the original API function, and remains backward compatible by always operating on the notification value at index 0 in the array. Calling xTaskNotify() is equivalent to calling xTaskNotifyIndexed() with the uxIndexToNotify parameter set to 0. eSetBits - The target notification value is bitwise ORed with ulValue. xTaskNotifyIndexed() always returns pdPASS in this case. eIncrement - The target notification value is incremented. ulValue is not used and xTaskNotifyIndexed() always returns pdPASS in this case. eSetValueWithOverwrite - The target notification value is set to the value of ulValue, even if the task being notified had not yet processed the previous notification at the same array index (the task already had a notification pending at that index). xTaskNotifyIndexed() always returns pdPASS in this case. eSetValueWithoutOverwrite - If the task being notified did not already have a notification pending at the same array index then the target notification value is set to ulValue and xTaskNotifyIndexed() will return pdPASS. If the task being notified already had a notification pending at the same array index then no action is performed and pdFAIL is returned. eNoAction - The task receives a notification at the specified array index without the notification value at that index being updated. ulValue is not used and xTaskNotifyIndexed() always returns pdPASS in this case. pulPreviousNotificationValue - Can be used to pass out the subject task's notification value before any bits are modified by the notify function. - Parameters xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotify() does not have this parameter and always sends notifications to index 0. ulValue -- Data that can be sent with the notification. How the data is used depends on the value of the eAction parameter. eAction -- Specifies how the notification updates the task's notification value, if at all. Valid values for eAction are as follows: - - Returns Dependent on the value of eAction. See the description of the eAction parameter. - xTaskNotifyAndQueryIndexed(xTaskToNotify, uxIndexToNotify, ulValue, eAction, pulPreviousNotifyValue) See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. xTaskNotifyAndQueryIndexed() performs the same operation as xTaskNotifyIndexed() with the addition that it also returns the subject task's prior notification value (the notification value at the time the function is called rather than when the function returns) in the additional pulPreviousNotifyValue parameter. xTaskNotifyAndQuery() performs the same operation as xTaskNotify() with the addition that it also returns the subject task's prior notification value (the notification value as it was at the time the function is called, rather than when the function returns) in the additional pulPreviousNotifyValue parameter. - xTaskNotifyIndexedFromISR(xTaskToNotify, uxIndexToNotify, ulValue, eAction, pxHigherPriorityTaskWoken) See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these functions to be available. A version of xTaskNotifyIndexed() that can be used from an interrupt service routine (ISR). Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of the task's notification values. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. A task can use xTaskNotifyWaitIndexed() to [optionally] block to wait for a notification to be pending, or ulTaskNotifyTakeIndexed() to [optionally] block to wait for a notification value to have a non-zero value. The task does not consume any CPU time while it is in the Blocked state. A notification sent to a task will remain pending until it is cleared by the task calling xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() (or their un-indexed equivalents). If the task was already in the Blocked state to wait for a notification when the notification arrives then the task will automatically be removed from the Blocked state (unblocked) and the notification cleared. NOTE Each notification within the array operates independently - a task can only block on one notification within the array at a time and will not be unblocked by a notification sent to any other array index. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. xTaskNotifyFromISR() is the original API function, and remains backward compatible by always operating on the notification value at index 0 within the array. Calling xTaskNotifyFromISR() is equivalent to calling xTaskNotifyIndexedFromISR() with the uxIndexToNotify parameter set to 0. eSetBits - The task's notification value is bitwise ORed with ulValue. xTaskNotify() always returns pdPASS in this case. eIncrement - The task's notification value is incremented. ulValue is not used and xTaskNotify() always returns pdPASS in this case. eSetValueWithOverwrite - The task's notification value is set to the value of ulValue, even if the task being notified had not yet processed the previous notification (the task already had a notification pending). xTaskNotify() always returns pdPASS in this case. eSetValueWithoutOverwrite - If the task being notified did not already have a notification pending then the task's notification value is set to ulValue and xTaskNotify() will return pdPASS. If the task being notified already had a notification pending then no action is performed and pdFAIL is returned. eNoAction - The task receives a notification without its notification value being updated. ulValue is not used and xTaskNotify() always returns pdPASS in this case. - Parameters uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyFromISR() does not have this parameter and always sends notifications to index 0. xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). ulValue -- Data that can be sent with the notification. How the data is used depends on the value of the eAction parameter. eAction -- Specifies how the notification updates the task's notification value, if at all. Valid values for eAction are as follows: pxHigherPriorityTaskWoken -- xTaskNotifyFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the task to which the notification was sent to leave the Blocked state, and the unblocked task has a priority higher than the currently running task. If xTaskNotifyFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. How a context switch is requested from an ISR is dependent on the port - see the documentation page for the port in use. - - Returns Dependent on the value of eAction. See the description of the eAction parameter. - xTaskNotifyAndQueryIndexedFromISR(xTaskToNotify, uxIndexToNotify, ulValue, eAction, pulPreviousNotificationValue, pxHigherPriorityTaskWoken) See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. xTaskNotifyAndQueryIndexedFromISR() performs the same operation as xTaskNotifyIndexedFromISR() with the addition that it also returns the subject task's prior notification value (the notification value at the time the function is called rather than at the time the function returns) in the additional pulPreviousNotifyValue parameter. xTaskNotifyAndQueryFromISR() performs the same operation as xTaskNotifyFromISR() with the addition that it also returns the subject task's prior notification value (the notification value at the time the function is called rather than at the time the function returns) in the additional pulPreviousNotifyValue parameter. - xTaskNotifyWait(ulBitsToClearOnEntry, ulBitsToClearOnExit, pulNotificationValue, xTicksToWait) - xTaskNotifyWaitIndexed(uxIndexToWaitOn, ulBitsToClearOnEntry, ulBitsToClearOnExit, pulNotificationValue, xTicksToWait) - xTaskNotifyGiveIndexed(xTaskToNotify, uxIndexToNotify) Sends a direct to task notification to a particular index in the target task's notification array in a manner similar to giving a counting semaphore. See https://www.FreeRTOS.org/RTOS-task-notifications.html for more details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these macros to be available. Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of the task's notification values. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. xTaskNotifyGiveIndexed() is a helper macro intended for use when task notifications are used as light weight and faster binary or counting semaphore equivalents. Actual FreeRTOS semaphores are given using the xSemaphoreGive() API function, the equivalent action that instead uses a task notification is xTaskNotifyGiveIndexed(). When task notifications are being used as a binary or counting semaphore equivalent then the task being notified should wait for the notification using the ulTaskNotifyTakeIndexed() API function rather than the xTaskNotifyWaitIndexed() API function. NOTE Each notification within the array operates independently - a task can only block on one notification within the array at a time and will not be unblocked by a notification sent to any other array index. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. xTaskNotifyGive() is the original API function, and remains backward compatible by always operating on the notification value at index 0 in the array. Calling xTaskNotifyGive() is equivalent to calling xTaskNotifyGiveIndexed() with the uxIndexToNotify parameter set to 0. - Parameters xTaskToNotify -- The handle of the task being notified. The handle to a task can be returned from the xTaskCreate() API function used to create the task, and the handle of the currently running task can be obtained by calling xTaskGetCurrentTaskHandle(). uxIndexToNotify -- The index within the target task's array of notification values to which the notification is to be sent. uxIndexToNotify must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyGive() does not have this parameter and always sends notifications to index 0. - - Returns xTaskNotifyGive() is a macro that calls xTaskNotify() with the eAction parameter set to eIncrement - so pdPASS is always returned. - vTaskNotifyGiveFromISR(xTaskToNotify, pxHigherPriorityTaskWoken) - vTaskNotifyGiveIndexedFromISR(xTaskToNotify, uxIndexToNotify, pxHigherPriorityTaskWoken) - ulTaskNotifyTakeIndexed(uxIndexToWaitOn, xClearCountOnExit, xTicksToWait) Waits for a direct to task notification on a particular index in the calling task's notification array in a manner similar to taking a counting semaphore. See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this function to be available. Each task has a private array of "notification values" (or 'notifications'), each of which is a 32-bit unsigned integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores, mutexes and event groups. Task notifications are a method of sending an event directly to a task without the need for such an intermediary object. A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of the task's notification values. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. ulTaskNotifyTakeIndexed() is intended for use when a task notification is used as a faster and lighter weight binary or counting semaphore alternative. Actual FreeRTOS semaphores are taken using the xSemaphoreTake() API function, the equivalent action that instead uses a task notification is ulTaskNotifyTakeIndexed(). When a task is using its notification value as a binary or counting semaphore other tasks should send notifications to it using the xTaskNotifyGiveIndexed() macro, or xTaskNotifyIndex() function with the eAction parameter set to eIncrement. ulTaskNotifyTakeIndexed() can either clear the task's notification value at the array index specified by the uxIndexToWaitOn parameter to zero on exit, in which case the notification value acts like a binary semaphore, or decrement the notification value on exit, in which case the notification value acts like a counting semaphore. A task can use ulTaskNotifyTakeIndexed() to [optionally] block to wait for a notification. The task does not consume any CPU time while it is in the Blocked state. Where as xTaskNotifyWaitIndexed() will return when a notification is pending, ulTaskNotifyTakeIndexed() will return when the task's notification value is not zero. NOTE Each notification within the array operates independently - a task can only block on one notification within the array at a time and will not be unblocked by a notification sent to any other array index. Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single "notification value", and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications within the array. ulTaskNotifyTake() is the original API function, and remains backward compatible by always operating on the notification value at index 0 in the array. Calling ulTaskNotifyTake() is equivalent to calling ulTaskNotifyTakeIndexed() with the uxIndexToWaitOn parameter set to 0. - Parameters uxIndexToWaitOn -- The index within the calling task's array of notification values on which the calling task will wait for a notification to be non-zero. uxIndexToWaitOn must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyTake() does not have this parameter and always waits for notifications on index 0. xClearCountOnExit -- if xClearCountOnExit is pdFALSE then the task's notification value is decremented when the function exits. In this way the notification value acts like a counting semaphore. If xClearCountOnExit is not pdFALSE then the task's notification value is cleared to zero when the function exits. In this way the notification value acts like a binary semaphore. xTicksToWait -- The maximum amount of time that the task should wait in the Blocked state for the task's notification value to be greater than zero, should the count not already be greater than zero when ulTaskNotifyTake() was called. The task will not consume any processing time while it is in the Blocked state. This is specified in kernel ticks, the macro pdMS_TO_TICKS( value_in_ms ) can be used to convert a time specified in milliseconds to a time specified in ticks. - - Returns The task's notification count before it is either cleared to zero or decremented (see the xClearCountOnExit parameter). - xTaskNotifyStateClear(xTask) - xTaskNotifyStateClearIndexed(xTask, uxIndexToClear) - ulTaskNotifyValueClear(xTask, ulBitsToClear) - ulTaskNotifyValueClearIndexed(xTask, uxIndexToClear, ulBitsToClear) Type Definitions - typedef struct tskTaskControlBlock *TaskHandle_t - typedef BaseType_t (*TaskHookFunction_t)(void*) Defines the prototype to which the application task hook function must conform. - typedef struct xTASK_STATUS TaskStatus_t Used with the uxTaskGetSystemState() function to return the state of each task in the system. Enumerations - enum eTaskState Task states returned by eTaskGetState. Values: - enumerator eRunning A task is querying the state of itself, so must be running. - enumerator eReady The task being queried is in a ready or pending ready list. - enumerator eBlocked The task being queried is in the Blocked state. - enumerator eSuspended The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. - enumerator eDeleted The task being queried has been deleted, but its TCB has not yet been freed. - enumerator eInvalid Used as an 'invalid state' value. - enumerator eRunning - enum eNotifyAction Actions that can be performed when vTaskNotify() is called. Values: - enumerator eNoAction Notify the task without updating its notify value. - enumerator eSetBits Set bits in the task's notification value. - enumerator eIncrement Increment the task's notification value. - enumerator eSetValueWithOverwrite Set the task's notification value to a specific value even if the previous value has not yet been read by the task. - enumerator eSetValueWithoutOverwrite Set the task's notification value if the previous value has been read by the task. - enumerator eNoAction - enum eSleepModeStatus Possible return values for eTaskConfirmSleepModeStatus(). Values: - enumerator eAbortSleep A task has been made ready or a context switch pended since portSUPPRESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. - enumerator eStandardSleep Enter a sleep mode that will not last any longer than the expected idle time. - enumerator eAbortSleep Queue API Header File components/freertos/FreeRTOS-Kernel/include/freertos/queue.h This header file can be included with: #include "freertos/queue.h" Functions - BaseType_t xQueueGenericSend(QueueHandle_t xQueue, const void *const pvItemToQueue, TickType_t xTicksToWait, const BaseType_t xCopyPosition) It is preferred that the macros xQueueSend(), xQueueSendToFront() and xQueueSendToBack() are used in place of calling this function directly. Post an item on a queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueSendFromISR () for an alternative which may be used in an ISR. Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; uint32_t ulVar = 10UL; void vATask( void *pvParameters ) { QueueHandle_t xQueue1, xQueue2; struct AMessage *pxMessage; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); // ... if( xQueue1 != 0 ) { // Send an uint32_t. Wait for 10 ticks for space to become // available if necessary. if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10, queueSEND_TO_BACK ) != pdPASS ) { // Failed to post the message, even after 10 ticks. } } if( xQueue2 != 0 ) { // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0, queueSEND_TO_BACK ); } // ... Rest of task code. } - Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xCopyPosition -- Can take the value queueSEND_TO_BACK to place the item at the back of the queue, or queueSEND_TO_FRONT to place the item at the front of the queue (for high priority messages). - - Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. - BaseType_t xQueuePeek(QueueHandle_t xQueue, void *const pvBuffer, TickType_t xTicksToWait) Receive an item from a queue without removing the item from the queue. The item is received by copy so a buffer of adequate size must be provided. The number of bytes copied into the buffer was defined when the queue was created. Successfully received items remain on the queue so will be returned again by the next call, or a call to xQueueReceive(). This macro must not be used in an interrupt service routine. See xQueuePeekFromISR() for an alternative that can be called from an interrupt service routine. Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; QueueHandle_t xQueue; // Task to create a queue and post a value. void vATask( void *pvParameters ) { struct AMessage *pxMessage; // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) ); if( xQueue == 0 ) { // Failed to create the queue. } // ... // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 ); // ... Rest of task code. } // Task to peek the data from the queue. void vADifferentTask( void *pvParameters ) { struct AMessage *pxRxedMessage; if( xQueue != 0 ) { // Peek a message on the created queue. Block for 10 ticks if a // message is not immediately available. if( xQueuePeek( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) ) { // pcRxedMessage now points to the struct AMessage variable posted // by vATask, but the item still remains on the queue. } } // ... Rest of task code. } - Parameters xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. xTicksToWait -- The maximum amount of time the task should block waiting for an item to receive should the queue be empty at the time of the call. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. xQueuePeek() will return immediately if xTicksToWait is 0 and the queue is empty. - - Returns pdTRUE if an item was successfully received from the queue, otherwise pdFALSE. - BaseType_t xQueuePeekFromISR(QueueHandle_t xQueue, void *const pvBuffer) A version of xQueuePeek() that can be called from an interrupt service routine (ISR). Receive an item from a queue without removing the item from the queue. The item is received by copy so a buffer of adequate size must be provided. The number of bytes copied into the buffer was defined when the queue was created. Successfully received items remain on the queue so will be returned again by the next call, or a call to xQueueReceive(). - Parameters xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. - - Returns pdTRUE if an item was successfully received from the queue, otherwise pdFALSE. - BaseType_t xQueueReceive(QueueHandle_t xQueue, void *const pvBuffer, TickType_t xTicksToWait) Receive an item from a queue. The item is received by copy so a buffer of adequate size must be provided. The number of bytes copied into the buffer was defined when the queue was created. Successfully received items are removed from the queue. This function must not be used in an interrupt service routine. See xQueueReceiveFromISR for an alternative that can. Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; QueueHandle_t xQueue; // Task to create a queue and post a value. void vATask( void *pvParameters ) { struct AMessage *pxMessage; // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) ); if( xQueue == 0 ) { // Failed to create the queue. } // ... // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 ); // ... Rest of task code. } // Task to receive from the queue. void vADifferentTask( void *pvParameters ) { struct AMessage *pxRxedMessage; if( xQueue != 0 ) { // Receive a message on the created queue. Block for 10 ticks if a // message is not immediately available. if( xQueueReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) ) { // pcRxedMessage now points to the struct AMessage variable posted // by vATask. } } // ... Rest of task code. } - Parameters xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. xTicksToWait -- The maximum amount of time the task should block waiting for an item to receive should the queue be empty at the time of the call. xQueueReceive() will return immediately if xTicksToWait is zero and the queue is empty. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. - - Returns pdTRUE if an item was successfully received from the queue, otherwise pdFALSE. - UBaseType_t uxQueueMessagesWaiting(const QueueHandle_t xQueue) Return the number of messages stored in a queue. - Parameters xQueue -- A handle to the queue being queried. - Returns The number of messages available in the queue. - UBaseType_t uxQueueSpacesAvailable(const QueueHandle_t xQueue) Return the number of free spaces available in a queue. This is equal to the number of items that can be sent to the queue before the queue becomes full if no items are removed. - Parameters xQueue -- A handle to the queue being queried. - Returns The number of spaces available in the queue. - void vQueueDelete(QueueHandle_t xQueue) Delete a queue - freeing all the memory allocated for storing of items placed on the queue. - Parameters xQueue -- A handle to the queue to be deleted. - BaseType_t xQueueGenericSendFromISR(QueueHandle_t xQueue, const void *const pvItemToQueue, BaseType_t *const pxHigherPriorityTaskWoken, const BaseType_t xCopyPosition) It is preferred that the macros xQueueSendFromISR(), xQueueSendToFrontFromISR() and xQueueSendToBackFromISR() be used in place of calling this function directly. xQueueGiveFromISR() is an equivalent for use by semaphores that don't actually copy any data. Post an item on a queue. It is safe to use this function from within an interrupt service routine. Items are queued by copy not reference so it is preferable to only queue small items, especially when called from an ISR. In most cases it would be preferable to store a pointer to the item being queued. Example usage for buffered IO (where the ISR can obtain more than one value per call): void vBufferISR( void ) { char cIn; BaseType_t xHigherPriorityTaskWokenByPost; // We have not woken a task at the start of the ISR. xHigherPriorityTaskWokenByPost = pdFALSE; // Loop until the buffer is empty. do { // Obtain a byte from the buffer. cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); // Post each byte. xQueueGenericSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWokenByPost, queueSEND_TO_BACK ); } while( portINPUT_BYTE( BUFFER_COUNT ) ); // Now the buffer is empty we can switch context if necessary. Note that the // name of the yield function required is port specific. if( xHigherPriorityTaskWokenByPost ) { portYIELD_FROM_ISR(); } } - Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueGenericSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueGenericSendFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. xCopyPosition -- Can take the value queueSEND_TO_BACK to place the item at the back of the queue, or queueSEND_TO_FRONT to place the item at the front of the queue (for high priority messages). - - Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL. - BaseType_t xQueueGiveFromISR(QueueHandle_t xQueue, BaseType_t *const pxHigherPriorityTaskWoken) - BaseType_t xQueueReceiveFromISR(QueueHandle_t xQueue, void *const pvBuffer, BaseType_t *const pxHigherPriorityTaskWoken) Receive an item from a queue. It is safe to use this function from within an interrupt service routine. Example usage: QueueHandle_t xQueue; // Function to create a queue and post some values. void vAFunction( void *pvParameters ) { char cValueToPost; const TickType_t xTicksToWait = ( TickType_t )0xff; // Create a queue capable of containing 10 characters. xQueue = xQueueCreate( 10, sizeof( char ) ); if( xQueue == 0 ) { // Failed to create the queue. } // ... // Post some characters that will be used within an ISR. If the queue // is full then this task will block for xTicksToWait ticks. cValueToPost = 'a'; xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); cValueToPost = 'b'; xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); // ... keep posting characters ... this task may block when the queue // becomes full. cValueToPost = 'c'; xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); } // ISR that outputs all the characters received on the queue. void vISR_Routine( void ) { BaseType_t xTaskWokenByReceive = pdFALSE; char cRxedChar; while( xQueueReceiveFromISR( xQueue, ( void * ) &cRxedChar, &xTaskWokenByReceive) ) { // A character was received. Output the character now. vOutputCharacter( cRxedChar ); // If removing the character from the queue woke the task that was // posting onto the queue xTaskWokenByReceive will have been set to // pdTRUE. No matter how many times this loop iterates only one // task will be woken. } if( xTaskWokenByReceive != ( char ) pdFALSE; { taskYIELD (); } } - Parameters xQueue -- The handle to the queue from which the item is to be received. pvBuffer -- Pointer to the buffer into which the received item will be copied. pxHigherPriorityTaskWoken -- A task may be blocked waiting for space to become available on the queue. If xQueueReceiveFromISR causes such a task to unblock *pxTaskWoken will get set to pdTRUE, otherwise *pxTaskWoken will remain unchanged. - - Returns pdTRUE if an item was successfully received from the queue, otherwise pdFALSE. - BaseType_t xQueueIsQueueEmptyFromISR(const QueueHandle_t xQueue) Queries a queue to determine if the queue is empty. This function should only be used in an ISR. - Parameters xQueue -- The handle of the queue being queried - Returns pdFALSE if the queue is not empty, or pdTRUE if the queue is empty. - BaseType_t xQueueIsQueueFullFromISR(const QueueHandle_t xQueue) Queries a queue to determine if the queue is full. This function should only be used in an ISR. - Parameters xQueue -- The handle of the queue being queried - Returns pdFALSE if the queue is not full, or pdTRUE if the queue is full. - UBaseType_t uxQueueMessagesWaitingFromISR(const QueueHandle_t xQueue) A version of uxQueueMessagesWaiting() that can be called from an ISR. Return the number of messages stored in a queue. - Parameters xQueue -- A handle to the queue being queried. - Returns The number of messages available in the queue. - void vQueueAddToRegistry(QueueHandle_t xQueue, const char *pcQueueName) The registry is provided as a means for kernel aware debuggers to locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add a queue, semaphore or mutex handle to the registry if you want the handle to be available to a kernel aware debugger. If you are not using a kernel aware debugger then this function can be ignored. configQUEUE_REGISTRY_SIZE defines the maximum number of handles the registry can hold. configQUEUE_REGISTRY_SIZE must be greater than 0 within FreeRTOSConfig.h for the registry to be available. Its value does not affect the number of queues, semaphores and mutexes that can be created - just the number that the registry can hold. If vQueueAddToRegistry is called more than once with the same xQueue parameter, the registry will store the pcQueueName parameter from the most recent call to vQueueAddToRegistry. - Parameters xQueue -- The handle of the queue being added to the registry. This is the handle returned by a call to xQueueCreate(). Semaphore and mutex handles can also be passed in here. pcQueueName -- The name to be associated with the handle. This is the name that the kernel aware debugger will display. The queue registry only stores a pointer to the string - so the string must be persistent (global or preferably in ROM/Flash), not on the stack. - - void vQueueUnregisterQueue(QueueHandle_t xQueue) The registry is provided as a means for kernel aware debuggers to locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add a queue, semaphore or mutex handle to the registry if you want the handle to be available to a kernel aware debugger, and vQueueUnregisterQueue() to remove the queue, semaphore or mutex from the register. If you are not using a kernel aware debugger then this function can be ignored. - Parameters xQueue -- The handle of the queue being removed from the registry. - const char *pcQueueGetName(QueueHandle_t xQueue) The queue registry is provided as a means for kernel aware debuggers to locate queues, semaphores and mutexes. Call pcQueueGetName() to look up and return the name of a queue in the queue registry from the queue's handle. - Parameters xQueue -- The handle of the queue the name of which will be returned. - Returns If the queue is in the registry then a pointer to the name of the queue is returned. If the queue is not in the registry then NULL is returned. - QueueSetHandle_t xQueueCreateSet(const UBaseType_t uxEventQueueLength) Queue sets provide a mechanism to allow a task to block (pend) on a read operation from multiple queues or semaphores simultaneously. See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this function. A queue set must be explicitly created using a call to xQueueCreateSet() before it can be used. Once created, standard FreeRTOS queues and semaphores can be added to the set using calls to xQueueAddToSet(). xQueueSelectFromSet() is then used to determine which, if any, of the queues or semaphores contained in the set is in a state where a queue read or semaphore take operation would be successful. Note 1: See the documentation on https://www.FreeRTOS.org/RTOS-queue-sets.html for reasons why queue sets are very rarely needed in practice as there are simpler methods of blocking on multiple objects. Note 2: Blocking on a queue set that contains a mutex will not cause the mutex holder to inherit the priority of the blocked task. Note 3: An additional 4 bytes of RAM is required for each space in a every queue added to a queue set. Therefore counting semaphores that have a high maximum count value should not be added to a queue set. Note 4: A receive (in the case of a queue) or take (in the case of a semaphore) operation must not be performed on a member of a queue set unless a call to xQueueSelectFromSet() has first returned a handle to that set member. - Parameters uxEventQueueLength -- Queue sets store events that occur on the queues and semaphores contained in the set. uxEventQueueLength specifies the maximum number of events that can be queued at once. To be absolutely certain that events are not lost uxEventQueueLength should be set to the total sum of the length of the queues added to the set, where binary semaphores and mutexes have a length of 1, and counting semaphores have a length set by their maximum count value. Examples: If a queue set is to hold a queue of length 5, another queue of length 12, and a binary semaphore, then uxEventQueueLength should be set to (5 + 12 + 1), or 18. If a queue set is to hold three binary semaphores then uxEventQueueLength should be set to (1 + 1 + 1 ), or 3. If a queue set is to hold a counting semaphore that has a maximum count of 5, and a counting semaphore that has a maximum count of 3, then uxEventQueueLength should be set to (5 + 3), or 8. - - Returns If the queue set is created successfully then a handle to the created queue set is returned. Otherwise NULL is returned. - BaseType_t xQueueAddToSet(QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet) Adds a queue or semaphore to a queue set that was previously created by a call to xQueueCreateSet(). See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this function. Note 1: A receive (in the case of a queue) or take (in the case of a semaphore) operation must not be performed on a member of a queue set unless a call to xQueueSelectFromSet() has first returned a handle to that set member. - Parameters xQueueOrSemaphore -- The handle of the queue or semaphore being added to the queue set (cast to an QueueSetMemberHandle_t type). xQueueSet -- The handle of the queue set to which the queue or semaphore is being added. - - Returns If the queue or semaphore was successfully added to the queue set then pdPASS is returned. If the queue could not be successfully added to the queue set because it is already a member of a different queue set then pdFAIL is returned. - BaseType_t xQueueRemoveFromSet(QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet) Removes a queue or semaphore from a queue set. A queue or semaphore can only be removed from a set if the queue or semaphore is empty. See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this function. - Parameters xQueueOrSemaphore -- The handle of the queue or semaphore being removed from the queue set (cast to an QueueSetMemberHandle_t type). xQueueSet -- The handle of the queue set in which the queue or semaphore is included. - - Returns If the queue or semaphore was successfully removed from the queue set then pdPASS is returned. If the queue was not in the queue set, or the queue (or semaphore) was not empty, then pdFAIL is returned. - QueueSetMemberHandle_t xQueueSelectFromSet(QueueSetHandle_t xQueueSet, const TickType_t xTicksToWait) xQueueSelectFromSet() selects from the members of a queue set a queue or semaphore that either contains data (in the case of a queue) or is available to take (in the case of a semaphore). xQueueSelectFromSet() effectively allows a task to block (pend) on a read operation on all the queues and semaphores in a queue set simultaneously. See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this function. Note 1: See the documentation on https://www.FreeRTOS.org/RTOS-queue-sets.html for reasons why queue sets are very rarely needed in practice as there are simpler methods of blocking on multiple objects. Note 2: Blocking on a queue set that contains a mutex will not cause the mutex holder to inherit the priority of the blocked task. Note 3: A receive (in the case of a queue) or take (in the case of a semaphore) operation must not be performed on a member of a queue set unless a call to xQueueSelectFromSet() has first returned a handle to that set member. - Parameters xQueueSet -- The queue set on which the task will (potentially) block. xTicksToWait -- The maximum time, in ticks, that the calling task will remain in the Blocked state (with other tasks executing) to wait for a member of the queue set to be ready for a successful queue read or semaphore take operation. - - Returns xQueueSelectFromSet() will return the handle of a queue (cast to a QueueSetMemberHandle_t type) contained in the queue set that contains data, or the handle of a semaphore (cast to a QueueSetMemberHandle_t type) contained in the queue set that is available, or NULL if no such queue or semaphore exists before before the specified block time expires. - QueueSetMemberHandle_t xQueueSelectFromSetFromISR(QueueSetHandle_t xQueueSet) A version of xQueueSelectFromSet() that can be used from an ISR. Macros - xQueueCreate(uxQueueLength, uxItemSize) Creates a new queue instance, and returns a handle by which the new queue can be referenced. Internally, within the FreeRTOS implementation, queues use two blocks of memory. The first block is used to hold the queue's data structures. The second block is used to hold items placed into the queue. If a queue is created using xQueueCreate() then both blocks of memory are automatically dynamically allocated inside the xQueueCreate() function. (see https://www.FreeRTOS.org/a00111.html). If a queue is created using xQueueCreateStatic() then the application writer must provide the memory that will get used by the queue. xQueueCreateStatic() therefore allows a queue to be created without using any dynamic memory allocation. https://www.FreeRTOS.org/Embedded-RTOS-Queues.html Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; }; void vATask( void *pvParameters ) { QueueHandle_t xQueue1, xQueue2; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); if( xQueue1 == 0 ) { // Queue was not created and must not be used. } // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); if( xQueue2 == 0 ) { // Queue was not created and must not be used. } // ... Rest of task code. } - Parameters uxQueueLength -- The maximum number of items that the queue can contain. uxItemSize -- The number of bytes each item in the queue will require. Items are queued by copy, not by reference, so this is the number of bytes that will be copied for each posted item. Each item on the queue must be the same size. - - Returns If the queue is successfully create then a handle to the newly created queue is returned. If the queue cannot be created then 0 is returned. - xQueueCreateStatic(uxQueueLength, uxItemSize, pucQueueStorage, pxQueueBuffer) Creates a new queue instance, and returns a handle by which the new queue can be referenced. Internally, within the FreeRTOS implementation, queues use two blocks of memory. The first block is used to hold the queue's data structures. The second block is used to hold items placed into the queue. If a queue is created using xQueueCreate() then both blocks of memory are automatically dynamically allocated inside the xQueueCreate() function. (see https://www.FreeRTOS.org/a00111.html). If a queue is created using xQueueCreateStatic() then the application writer must provide the memory that will get used by the queue. xQueueCreateStatic() therefore allows a queue to be created without using any dynamic memory allocation. https://www.FreeRTOS.org/Embedded-RTOS-Queues.html Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; }; #define QUEUE_LENGTH 10 #define ITEM_SIZE sizeof( uint32_t ) // xQueueBuffer will hold the queue structure. StaticQueue_t xQueueBuffer; // ucQueueStorage will hold the items posted to the queue. Must be at least // [(queue length) * ( queue item size)] bytes long. uint8_t ucQueueStorage[ QUEUE_LENGTH * ITEM_SIZE ]; void vATask( void *pvParameters ) { QueueHandle_t xQueue1; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( QUEUE_LENGTH, // The number of items the queue can hold. ITEM_SIZE // The size of each item in the queue &( ucQueueStorage[ 0 ] ), // The buffer that will hold the items in the queue. &xQueueBuffer ); // The buffer that will hold the queue structure. // The queue is guaranteed to be created successfully as no dynamic memory // allocation is used. Therefore xQueue1 is now a handle to a valid queue. // ... Rest of task code. } - Parameters uxQueueLength -- The maximum number of items that the queue can contain. uxItemSize -- The number of bytes each item in the queue will require. Items are queued by copy, not by reference, so this is the number of bytes that will be copied for each posted item. Each item on the queue must be the same size. pucQueueStorage -- If uxItemSize is not zero then pucQueueStorage must point to a uint8_t array that is at least large enough to hold the maximum number of items that can be in the queue at any one time - which is ( uxQueueLength * uxItemsSize ) bytes. If uxItemSize is zero then pucQueueStorage can be NULL. pxQueueBuffer -- Must point to a variable of type StaticQueue_t, which will be used to hold the queue's data structure. - - Returns If the queue is created then a handle to the created queue is returned. If pxQueueBuffer is NULL then NULL is returned. - xQueueGetStaticBuffers(xQueue, ppucQueueStorage, ppxStaticQueue) Retrieve pointers to a statically created queue's data structure buffer and storage area buffer. These are the same buffers that are supplied at the time of creation. - Parameters xQueue -- The queue for which to retrieve the buffers. ppucQueueStorage -- Used to return a pointer to the queue's storage area buffer. ppxStaticQueue -- Used to return a pointer to the queue's data structure buffer. - - Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. - xQueueSendToFront(xQueue, pvItemToQueue, xTicksToWait) Post an item to the front of a queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueSendFromISR () for an alternative which may be used in an ISR. Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; uint32_t ulVar = 10UL; void vATask( void *pvParameters ) { QueueHandle_t xQueue1, xQueue2; struct AMessage *pxMessage; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); // ... if( xQueue1 != 0 ) { // Send an uint32_t. Wait for 10 ticks for space to become // available if necessary. if( xQueueSendToFront( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) { // Failed to post the message, even after 10 ticks. } } if( xQueue2 != 0 ) { // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSendToFront( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); } // ... Rest of task code. } - Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. - - Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. - xQueueSendToBack(xQueue, pvItemToQueue, xTicksToWait) This is a macro that calls xQueueGenericSend(). Post an item to the back of a queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueSendFromISR () for an alternative which may be used in an ISR. Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; uint32_t ulVar = 10UL; void vATask( void *pvParameters ) { QueueHandle_t xQueue1, xQueue2; struct AMessage *pxMessage; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); // ... if( xQueue1 != 0 ) { // Send an uint32_t. Wait for 10 ticks for space to become // available if necessary. if( xQueueSendToBack( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) { // Failed to post the message, even after 10 ticks. } } if( xQueue2 != 0 ) { // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSendToBack( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); } // ... Rest of task code. } - Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. - - Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. - xQueueSend(xQueue, pvItemToQueue, xTicksToWait) This is a macro that calls xQueueGenericSend(). It is included for backward compatibility with versions of FreeRTOS.org that did not include the xQueueSendToFront() and xQueueSendToBack() macros. It is equivalent to xQueueSendToBack(). Post an item on a queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueSendFromISR () for an alternative which may be used in an ISR. Example usage: struct AMessage { char ucMessageID; char ucData[ 20 ]; } xMessage; uint32_t ulVar = 10UL; void vATask( void *pvParameters ) { QueueHandle_t xQueue1, xQueue2; struct AMessage *pxMessage; // Create a queue capable of containing 10 uint32_t values. xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); // Create a queue capable of containing 10 pointers to AMessage structures. // These should be passed by pointer as they contain a lot of data. xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); // ... if( xQueue1 != 0 ) { // Send an uint32_t. Wait for 10 ticks for space to become // available if necessary. if( xQueueSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) { // Failed to post the message, even after 10 ticks. } } if( xQueue2 != 0 ) { // Send a pointer to a struct AMessage object. Don't block if the // queue is already full. pxMessage = & xMessage; xQueueSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); } // ... Rest of task code. } - Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. xTicksToWait -- The maximum amount of time the task should block waiting for space to become available on the queue, should it already be full. The call will return immediately if this is set to 0 and the queue is full. The time is defined in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real time if this is required. - - Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. - xQueueOverwrite(xQueue, pvItemToQueue) Only for use with queues that have a length of one - so the queue is either empty or full. Post an item on a queue. If the queue is already full then overwrite the value held in the queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueOverwriteFromISR () for an alternative which may be used in an ISR. Example usage: void vFunction( void *pvParameters ) { QueueHandle_t xQueue; uint32_t ulVarToSend, ulValReceived; // Create a queue to hold one uint32_t value. It is strongly // recommended *not* to use xQueueOverwrite() on queues that can // contain more than one value, and doing so will trigger an assertion // if configASSERT() is defined. xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); // Write the value 10 to the queue using xQueueOverwrite(). ulVarToSend = 10; xQueueOverwrite( xQueue, &ulVarToSend ); // Peeking the queue should now return 10, but leave the value 10 in // the queue. A block time of zero is used as it is known that the // queue holds a value. ulValReceived = 0; xQueuePeek( xQueue, &ulValReceived, 0 ); if( ulValReceived != 10 ) { // Error unless the item was removed by a different task. } // The queue is still full. Use xQueueOverwrite() to overwrite the // value held in the queue with 100. ulVarToSend = 100; xQueueOverwrite( xQueue, &ulVarToSend ); // This time read from the queue, leaving the queue empty once more. // A block time of 0 is used again. xQueueReceive( xQueue, &ulValReceived, 0 ); // The value read should be the last value written, even though the // queue was already full when the value was written. if( ulValReceived != 100 ) { // Error! } // ... } - Parameters xQueue -- The handle of the queue to which the data is being sent. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. - - Returns xQueueOverwrite() is a macro that calls xQueueGenericSend(), and therefore has the same return values as xQueueSendToFront(). However, pdPASS is the only value that can be returned because xQueueOverwrite() will write to the queue even when the queue is already full. - xQueueSendToFrontFromISR(xQueue, pvItemToQueue, pxHigherPriorityTaskWoken) This is a macro that calls xQueueGenericSendFromISR(). Post an item to the front of a queue. It is safe to use this macro from within an interrupt service routine. Items are queued by copy not reference so it is preferable to only queue small items, especially when called from an ISR. In most cases it would be preferable to store a pointer to the item being queued. Example usage for buffered IO (where the ISR can obtain more than one value per call): void vBufferISR( void ) { char cIn; BaseType_t xHigherPriorityTaskWoken; // We have not woken a task at the start of the ISR. xHigherPriorityTaskWoken = pdFALSE; // Loop until the buffer is empty. do { // Obtain a byte from the buffer. cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); // Post the byte. xQueueSendToFrontFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); } while( portINPUT_BYTE( BUFFER_COUNT ) ); // Now the buffer is empty we can switch context if necessary. if( xHigherPriorityTaskWoken ) { taskYIELD (); } } - Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueSendToFrontFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueSendToFromFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. - - Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL. - xQueueSendToBackFromISR(xQueue, pvItemToQueue, pxHigherPriorityTaskWoken) This is a macro that calls xQueueGenericSendFromISR(). Post an item to the back of a queue. It is safe to use this macro from within an interrupt service routine. Items are queued by copy not reference so it is preferable to only queue small items, especially when called from an ISR. In most cases it would be preferable to store a pointer to the item being queued. Example usage for buffered IO (where the ISR can obtain more than one value per call): void vBufferISR( void ) { char cIn; BaseType_t xHigherPriorityTaskWoken; // We have not woken a task at the start of the ISR. xHigherPriorityTaskWoken = pdFALSE; // Loop until the buffer is empty. do { // Obtain a byte from the buffer. cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); // Post the byte. xQueueSendToBackFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); } while( portINPUT_BYTE( BUFFER_COUNT ) ); // Now the buffer is empty we can switch context if necessary. if( xHigherPriorityTaskWoken ) { taskYIELD (); } } - Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueSendToBackFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueSendToBackFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. - - Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL. - xQueueOverwriteFromISR(xQueue, pvItemToQueue, pxHigherPriorityTaskWoken) A version of xQueueOverwrite() that can be used in an interrupt service routine (ISR). Only for use with queues that can hold a single item - so the queue is either empty or full. Post an item on a queue. If the queue is already full then overwrite the value held in the queue. The item is queued by copy, not by reference. Example usage: QueueHandle_t xQueue; void vFunction( void *pvParameters ) { // Create a queue to hold one uint32_t value. It is strongly // recommended *not* to use xQueueOverwriteFromISR() on queues that can // contain more than one value, and doing so will trigger an assertion // if configASSERT() is defined. xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); } void vAnInterruptHandler( void ) { // xHigherPriorityTaskWoken must be set to pdFALSE before it is used. BaseType_t xHigherPriorityTaskWoken = pdFALSE; uint32_t ulVarToSend, ulValReceived; // Write the value 10 to the queue using xQueueOverwriteFromISR(). ulVarToSend = 10; xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); // The queue is full, but calling xQueueOverwriteFromISR() again will still // pass because the value held in the queue will be overwritten with the // new value. ulVarToSend = 100; xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); // Reading from the queue will now return 100. // ... if( xHigherPrioritytaskWoken == pdTRUE ) { // Writing to the queue caused a task to unblock and the unblocked task // has a priority higher than or equal to the priority of the currently // executing task (the task this interrupt interrupted). Perform a context // switch so this interrupt returns directly to the unblocked task. portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port. } } - Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueOverwriteFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueOverwriteFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. - - Returns xQueueOverwriteFromISR() is a macro that calls xQueueGenericSendFromISR(), and therefore has the same return values as xQueueSendToFrontFromISR(). However, pdPASS is the only value that can be returned because xQueueOverwriteFromISR() will write to the queue even when the queue is already full. - xQueueSendFromISR(xQueue, pvItemToQueue, pxHigherPriorityTaskWoken) This is a macro that calls xQueueGenericSendFromISR(). It is included for backward compatibility with versions of FreeRTOS.org that did not include the xQueueSendToBackFromISR() and xQueueSendToFrontFromISR() macros. Post an item to the back of a queue. It is safe to use this function from within an interrupt service routine. Items are queued by copy not reference so it is preferable to only queue small items, especially when called from an ISR. In most cases it would be preferable to store a pointer to the item being queued. Example usage for buffered IO (where the ISR can obtain more than one value per call): void vBufferISR( void ) { char cIn; BaseType_t xHigherPriorityTaskWoken; // We have not woken a task at the start of the ISR. xHigherPriorityTaskWoken = pdFALSE; // Loop until the buffer is empty. do { // Obtain a byte from the buffer. cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); // Post the byte. xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); } while( portINPUT_BYTE( BUFFER_COUNT ) ); // Now the buffer is empty we can switch context if necessary. if( xHigherPriorityTaskWoken ) { // Actual macro used here is port specific. portYIELD_FROM_ISR (); } } - Parameters xQueue -- The handle to the queue on which the item is to be posted. pvItemToQueue -- A pointer to the item that is to be placed on the queue. The size of the items the queue will hold was defined when the queue was created, so this many bytes will be copied from pvItemToQueue into the queue storage area. pxHigherPriorityTaskWoken -- xQueueSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xQueueSendFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. - - Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL. - xQueueReset(xQueue) Reset a queue back to its original empty state. The return value is now obsolete and is always set to pdPASS. Type Definitions - typedef struct QueueDefinition *QueueHandle_t - typedef struct QueueDefinition *QueueSetHandle_t Type by which queue sets are referenced. For example, a call to xQueueCreateSet() returns an xQueueSet variable that can then be used as a parameter to xQueueSelectFromSet(), xQueueAddToSet(), etc. - typedef struct QueueDefinition *QueueSetMemberHandle_t Queue sets can contain both queues and semaphores, so the QueueSetMemberHandle_t is defined as a type to be used where a parameter or return value can be either an QueueHandle_t or an SemaphoreHandle_t. Semaphore API Header File components/freertos/FreeRTOS-Kernel/include/freertos/semphr.h This header file can be included with: #include "freertos/semphr.h" Macros - semBINARY_SEMAPHORE_QUEUE_LENGTH - semSEMAPHORE_QUEUE_ITEM_LENGTH - semGIVE_BLOCK_TIME - vSemaphoreCreateBinary(xSemaphore) In many usage scenarios it is faster and more memory efficient to use a direct to task notification in place of a binary semaphore! https://www.FreeRTOS.org/RTOS-task-notifications.html This old vSemaphoreCreateBinary() macro is now deprecated in favour of the xSemaphoreCreateBinary() function. Note that binary semaphores created using the vSemaphoreCreateBinary() macro are created in a state such that the first call to 'take' the semaphore would pass, whereas binary semaphores created using xSemaphoreCreateBinary() are created in a state such that the the semaphore must first be 'given' before it can be 'taken'. Macro that implements a semaphore by using the existing queue mechanism. The queue length is 1 as this is a binary semaphore. The data size is 0 as we don't want to actually store any data - we just want to know if the queue is empty or full. This type of semaphore can be used for pure synchronisation between tasks or between an interrupt and a task. The semaphore need not be given back once obtained, so one task/interrupt can continuously 'give' the semaphore while another continuously 'takes' the semaphore. For this reason this type of semaphore does not use a priority inheritance mechanism. For an alternative that does use priority inheritance see xSemaphoreCreateMutex(). Example usage: SemaphoreHandle_t xSemaphore = NULL; void vATask( void * pvParameters ) { // Semaphore cannot be used before a call to vSemaphoreCreateBinary (). // This is a macro so pass the variable in directly. vSemaphoreCreateBinary( xSemaphore ); if( xSemaphore != NULL ) { // The semaphore was created successfully. // The semaphore can now be used. } } - Parameters xSemaphore -- Handle to the created semaphore. Should be of type SemaphoreHandle_t. - - xSemaphoreCreateBinary() Creates a new binary semaphore instance, and returns a handle by which the new semaphore can be referenced. In many usage scenarios it is faster and more memory efficient to use a direct to task notification in place of a binary semaphore! https://www.FreeRTOS.org/RTOS-task-notifications.html Internally, within the FreeRTOS implementation, binary semaphores use a block of memory, in which the semaphore structure is stored. If a binary semaphore is created using xSemaphoreCreateBinary() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateBinary() function. (see https://www.FreeRTOS.org/a00111.html). If a binary semaphore is created using xSemaphoreCreateBinaryStatic() then the application writer must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a binary semaphore to be created without using any dynamic memory allocation. The old vSemaphoreCreateBinary() macro is now deprecated in favour of this xSemaphoreCreateBinary() function. Note that binary semaphores created using the vSemaphoreCreateBinary() macro are created in a state such that the first call to 'take' the semaphore would pass, whereas binary semaphores created using xSemaphoreCreateBinary() are created in a state such that the the semaphore must first be 'given' before it can be 'taken'. This type of semaphore can be used for pure synchronisation between tasks or between an interrupt and a task. The semaphore need not be given back once obtained, so one task/interrupt can continuously 'give' the semaphore while another continuously 'takes' the semaphore. For this reason this type of semaphore does not use a priority inheritance mechanism. For an alternative that does use priority inheritance see xSemaphoreCreateMutex(). Example usage: SemaphoreHandle_t xSemaphore = NULL; void vATask( void * pvParameters ) { // Semaphore cannot be used before a call to xSemaphoreCreateBinary(). // This is a macro so pass the variable in directly. xSemaphore = xSemaphoreCreateBinary(); if( xSemaphore != NULL ) { // The semaphore was created successfully. // The semaphore can now be used. } } - Returns Handle to the created semaphore, or NULL if the memory required to hold the semaphore's data structures could not be allocated. - xSemaphoreCreateBinaryStatic(pxStaticSemaphore) Creates a new binary semaphore instance, and returns a handle by which the new semaphore can be referenced. NOTE: In many usage scenarios it is faster and more memory efficient to use a direct to task notification in place of a binary semaphore! https://www.FreeRTOS.org/RTOS-task-notifications.html Internally, within the FreeRTOS implementation, binary semaphores use a block of memory, in which the semaphore structure is stored. If a binary semaphore is created using xSemaphoreCreateBinary() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateBinary() function. (see https://www.FreeRTOS.org/a00111.html). If a binary semaphore is created using xSemaphoreCreateBinaryStatic() then the application writer must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a binary semaphore to be created without using any dynamic memory allocation. This type of semaphore can be used for pure synchronisation between tasks or between an interrupt and a task. The semaphore need not be given back once obtained, so one task/interrupt can continuously 'give' the semaphore while another continuously 'takes' the semaphore. For this reason this type of semaphore does not use a priority inheritance mechanism. For an alternative that does use priority inheritance see xSemaphoreCreateMutex(). Example usage: SemaphoreHandle_t xSemaphore = NULL; StaticSemaphore_t xSemaphoreBuffer; void vATask( void * pvParameters ) { // Semaphore cannot be used before a call to xSemaphoreCreateBinary(). // The semaphore's data structures will be placed in the xSemaphoreBuffer // variable, the address of which is passed into the function. The // function's parameter is not NULL, so the function will not attempt any // dynamic memory allocation, and therefore the function will not return // return NULL. xSemaphore = xSemaphoreCreateBinary( &xSemaphoreBuffer ); // Rest of task code goes here. } - Parameters pxStaticSemaphore -- Must point to a variable of type StaticSemaphore_t, which will then be used to hold the semaphore's data structure, removing the need for the memory to be allocated dynamically. - - Returns If the semaphore is created then a handle to the created semaphore is returned. If pxSemaphoreBuffer is NULL then NULL is returned. - xSemaphoreTake(xSemaphore, xBlockTime) Macro to obtain a semaphore. The semaphore must have previously been created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or xSemaphoreCreateCounting(). Example usage: SemaphoreHandle_t xSemaphore = NULL; // A task that creates a semaphore. void vATask( void * pvParameters ) { // Create the semaphore to guard a shared resource. xSemaphore = xSemaphoreCreateBinary(); } // A task that uses the semaphore. void vAnotherTask( void * pvParameters ) { // ... Do other things. if( xSemaphore != NULL ) { // See if we can obtain the semaphore. If the semaphore is not available // wait 10 ticks to see if it becomes free. if( xSemaphoreTake( xSemaphore, ( TickType_t ) 10 ) == pdTRUE ) { // We were able to obtain the semaphore and can now access the // shared resource. // ... // We have finished accessing the shared resource. Release the // semaphore. xSemaphoreGive( xSemaphore ); } else { // We could not obtain the semaphore and can therefore not access // the shared resource safely. } } } - Parameters xSemaphore -- A handle to the semaphore being taken - obtained when the semaphore was created. xBlockTime -- The time in ticks to wait for the semaphore to become available. The macro portTICK_PERIOD_MS can be used to convert this to a real time. A block time of zero can be used to poll the semaphore. A block time of portMAX_DELAY can be used to block indefinitely (provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). - - Returns pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime expired without the semaphore becoming available. - xSemaphoreTakeRecursive(xMutex, xBlockTime) Macro to recursively obtain, or 'take', a mutex type semaphore. The mutex must have previously been created using a call to xSemaphoreCreateRecursiveMutex(); configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this macro to be available. This macro must not be used on mutexes created using xSemaphoreCreateMutex(). A mutex used recursively can be 'taken' repeatedly by the owner. The mutex doesn't become available again until the owner has called xSemaphoreGiveRecursive() for each successful 'take' request. For example, if a task successfully 'takes' the same mutex 5 times then the mutex will not be available to any other task until it has also 'given' the mutex back exactly five times. Example usage: SemaphoreHandle_t xMutex = NULL; // A task that creates a mutex. void vATask( void * pvParameters ) { // Create the mutex to guard a shared resource. xMutex = xSemaphoreCreateRecursiveMutex(); } // A task that uses the mutex. void vAnotherTask( void * pvParameters ) { // ... Do other things. if( xMutex != NULL ) { // See if we can obtain the mutex. If the mutex is not available // wait 10 ticks to see if it becomes free. if( xSemaphoreTakeRecursive( xSemaphore, ( TickType_t ) 10 ) == pdTRUE ) { // We were able to obtain the mutex and can now access the // shared resource. // ... // For some reason due to the nature of the code further calls to // xSemaphoreTakeRecursive() are made on the same mutex. In real // code these would not be just sequential calls as this would make // no sense. Instead the calls are likely to be buried inside // a more complex call structure. xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); // The mutex has now been 'taken' three times, so will not be // available to another task until it has also been given back // three times. Again it is unlikely that real code would have // these calls sequentially, but instead buried in a more complex // call structure. This is just for illustrative purposes. xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); // Now the mutex can be taken by other tasks. } else { // We could not obtain the mutex and can therefore not access // the shared resource safely. } } } - Parameters xMutex -- A handle to the mutex being obtained. This is the handle returned by xSemaphoreCreateRecursiveMutex(); xBlockTime -- The time in ticks to wait for the semaphore to become available. The macro portTICK_PERIOD_MS can be used to convert this to a real time. A block time of zero can be used to poll the semaphore. If the task already owns the semaphore then xSemaphoreTakeRecursive() will return immediately no matter what the value of xBlockTime. - - Returns pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime expired without the semaphore becoming available. - xSemaphoreGive(xSemaphore) Macro to release a semaphore. The semaphore must have previously been created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or xSemaphoreCreateCounting(). and obtained using sSemaphoreTake(). This macro must not be used from an ISR. See xSemaphoreGiveFromISR () for an alternative which can be used from an ISR. This macro must also not be used on semaphores created using xSemaphoreCreateRecursiveMutex(). Example usage: SemaphoreHandle_t xSemaphore = NULL; void vATask( void * pvParameters ) { // Create the semaphore to guard a shared resource. xSemaphore = vSemaphoreCreateBinary(); if( xSemaphore != NULL ) { if( xSemaphoreGive( xSemaphore ) != pdTRUE ) { // We would expect this call to fail because we cannot give // a semaphore without first "taking" it! } // Obtain the semaphore - don't block if the semaphore is not // immediately available. if( xSemaphoreTake( xSemaphore, ( TickType_t ) 0 ) ) { // We now have the semaphore and can access the shared resource. // ... // We have finished accessing the shared resource so can free the // semaphore. if( xSemaphoreGive( xSemaphore ) != pdTRUE ) { // We would not expect this call to fail because we must have // obtained the semaphore to get here. } } } } - Parameters xSemaphore -- A handle to the semaphore being released. This is the handle returned when the semaphore was created. - - Returns pdTRUE if the semaphore was released. pdFALSE if an error occurred. Semaphores are implemented using queues. An error can occur if there is no space on the queue to post a message - indicating that the semaphore was not first obtained correctly. - xSemaphoreGiveRecursive(xMutex) Macro to recursively release, or 'give', a mutex type semaphore. The mutex must have previously been created using a call to xSemaphoreCreateRecursiveMutex(); configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this macro to be available. This macro must not be used on mutexes created using xSemaphoreCreateMutex(). A mutex used recursively can be 'taken' repeatedly by the owner. The mutex doesn't become available again until the owner has called xSemaphoreGiveRecursive() for each successful 'take' request. For example, if a task successfully 'takes' the same mutex 5 times then the mutex will not be available to any other task until it has also 'given' the mutex back exactly five times. Example usage: SemaphoreHandle_t xMutex = NULL; // A task that creates a mutex. void vATask( void * pvParameters ) { // Create the mutex to guard a shared resource. xMutex = xSemaphoreCreateRecursiveMutex(); } // A task that uses the mutex. void vAnotherTask( void * pvParameters ) { // ... Do other things. if( xMutex != NULL ) { // See if we can obtain the mutex. If the mutex is not available // wait 10 ticks to see if it becomes free. if( xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ) == pdTRUE ) { // We were able to obtain the mutex and can now access the // shared resource. // ... // For some reason due to the nature of the code further calls to // xSemaphoreTakeRecursive() are made on the same mutex. In real // code these would not be just sequential calls as this would make // no sense. Instead the calls are likely to be buried inside // a more complex call structure. xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); // The mutex has now been 'taken' three times, so will not be // available to another task until it has also been given back // three times. Again it is unlikely that real code would have // these calls sequentially, it would be more likely that the calls // to xSemaphoreGiveRecursive() would be called as a call stack // unwound. This is just for demonstrative purposes. xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); // Now the mutex can be taken by other tasks. } else { // We could not obtain the mutex and can therefore not access // the shared resource safely. } } } - Parameters xMutex -- A handle to the mutex being released, or 'given'. This is the handle returned by xSemaphoreCreateMutex(); - - Returns pdTRUE if the semaphore was given. - xSemaphoreGiveFromISR(xSemaphore, pxHigherPriorityTaskWoken) Macro to release a semaphore. The semaphore must have previously been created with a call to xSemaphoreCreateBinary() or xSemaphoreCreateCounting(). Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) must not be used with this macro. This macro can be used from an ISR. Example usage: #define LONG_TIME 0xffff #define TICKS_TO_WAIT 10 SemaphoreHandle_t xSemaphore = NULL; // Repetitive task. void vATask( void * pvParameters ) { for( ;; ) { // We want this task to run every 10 ticks of a timer. The semaphore // was created before this task was started. // Block waiting for the semaphore to become available. if( xSemaphoreTake( xSemaphore, LONG_TIME ) == pdTRUE ) { // It is time to execute. // ... // We have finished our task. Return to the top of the loop where // we will block on the semaphore until it is time to execute // again. Note when using the semaphore for synchronisation with an // ISR in this manner there is no need to 'give' the semaphore back. } } } // Timer ISR void vTimerISR( void * pvParameters ) { static uint8_t ucLocalTickCount = 0; static BaseType_t xHigherPriorityTaskWoken; // A timer tick has occurred. // ... Do other time functions. // Is it time for vATask () to run? xHigherPriorityTaskWoken = pdFALSE; ucLocalTickCount++; if( ucLocalTickCount >= TICKS_TO_WAIT ) { // Unblock the task by releasing the semaphore. xSemaphoreGiveFromISR( xSemaphore, &xHigherPriorityTaskWoken ); // Reset the count so we release the semaphore again in 10 ticks time. ucLocalTickCount = 0; } if( xHigherPriorityTaskWoken != pdFALSE ) { // We can force a context switch here. Context switching from an // ISR uses port specific syntax. Check the demo task for your port // to find the syntax required. } } - Parameters xSemaphore -- A handle to the semaphore being released. This is the handle returned when the semaphore was created. pxHigherPriorityTaskWoken -- xSemaphoreGiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if giving the semaphore caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xSemaphoreGiveFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. - - Returns pdTRUE if the semaphore was successfully given, otherwise errQUEUE_FULL. - xSemaphoreTakeFromISR(xSemaphore, pxHigherPriorityTaskWoken) Macro to take a semaphore from an ISR. The semaphore must have previously been created with a call to xSemaphoreCreateBinary() or xSemaphoreCreateCounting(). Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) must not be used with this macro. This macro can be used from an ISR, however taking a semaphore from an ISR is not a common operation. It is likely to only be useful when taking a counting semaphore when an interrupt is obtaining an object from a resource pool (when the semaphore count indicates the number of resources available). - Parameters xSemaphore -- A handle to the semaphore being taken. This is the handle returned when the semaphore was created. pxHigherPriorityTaskWoken -- xSemaphoreTakeFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if taking the semaphore caused a task to unblock, and the unblocked task has a priority higher than the currently running task. If xSemaphoreTakeFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. - - Returns pdTRUE if the semaphore was successfully taken, otherwise pdFALSE - xSemaphoreCreateMutex() Creates a new mutex type semaphore instance, and returns a handle by which the new mutex can be referenced. Internally, within the FreeRTOS implementation, mutex semaphores use a block of memory, in which the mutex structure is stored. If a mutex is created using xSemaphoreCreateMutex() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateMutex() function. (see https://www.FreeRTOS.org/a00111.html). If a mutex is created using xSemaphoreCreateMutexStatic() then the application writer must provided the memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created without using any dynamic memory allocation. Mutexes created using this function can be accessed using the xSemaphoreTake() and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros must not be used. This type of semaphore uses a priority inheritance mechanism so a task 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the semaphore it is no longer required. Mutex type semaphores cannot be used from within interrupt service routines. See xSemaphoreCreateBinary() for an alternative implementation that can be used for pure synchronisation (where one task or interrupt always 'gives' the semaphore and another always 'takes' the semaphore) and from within interrupt service routines. Example usage: SemaphoreHandle_t xSemaphore; void vATask( void * pvParameters ) { // Semaphore cannot be used before a call to xSemaphoreCreateMutex(). // This is a macro so pass the variable in directly. xSemaphore = xSemaphoreCreateMutex(); if( xSemaphore != NULL ) { // The semaphore was created successfully. // The semaphore can now be used. } } - Returns If the mutex was successfully created then a handle to the created semaphore is returned. If there was not enough heap to allocate the mutex data structures then NULL is returned. - xSemaphoreCreateMutexStatic(pxMutexBuffer) Creates a new mutex type semaphore instance, and returns a handle by which the new mutex can be referenced. Internally, within the FreeRTOS implementation, mutex semaphores use a block of memory, in which the mutex structure is stored. If a mutex is created using xSemaphoreCreateMutex() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateMutex() function. (see https://www.FreeRTOS.org/a00111.html). If a mutex is created using xSemaphoreCreateMutexStatic() then the application writer must provided the memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created without using any dynamic memory allocation. Mutexes created using this function can be accessed using the xSemaphoreTake() and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros must not be used. This type of semaphore uses a priority inheritance mechanism so a task 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the semaphore it is no longer required. Mutex type semaphores cannot be used from within interrupt service routines. See xSemaphoreCreateBinary() for an alternative implementation that can be used for pure synchronisation (where one task or interrupt always 'gives' the semaphore and another always 'takes' the semaphore) and from within interrupt service routines. Example usage: SemaphoreHandle_t xSemaphore; StaticSemaphore_t xMutexBuffer; void vATask( void * pvParameters ) { // A mutex cannot be used before it has been created. xMutexBuffer is // into xSemaphoreCreateMutexStatic() so no dynamic memory allocation is // attempted. xSemaphore = xSemaphoreCreateMutexStatic( &xMutexBuffer ); // As no dynamic memory allocation was performed, xSemaphore cannot be NULL, // so there is no need to check it. } - Parameters pxMutexBuffer -- Must point to a variable of type StaticSemaphore_t, which will be used to hold the mutex's data structure, removing the need for the memory to be allocated dynamically. - - Returns If the mutex was successfully created then a handle to the created mutex is returned. If pxMutexBuffer was NULL then NULL is returned. - xSemaphoreCreateRecursiveMutex() Creates a new recursive mutex type semaphore instance, and returns a handle by which the new recursive mutex can be referenced. Internally, within the FreeRTOS implementation, recursive mutexes use a block of memory, in which the mutex structure is stored. If a recursive mutex is created using xSemaphoreCreateRecursiveMutex() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateRecursiveMutex() function. (see https://www.FreeRTOS.org/a00111.html). If a recursive mutex is created using xSemaphoreCreateRecursiveMutexStatic() then the application writer must provide the memory that will get used by the mutex. xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to be created without using any dynamic memory allocation. Mutexes created using this macro can be accessed using the xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The xSemaphoreTake() and xSemaphoreGive() macros must not be used. A mutex used recursively can be 'taken' repeatedly by the owner. The mutex doesn't become available again until the owner has called xSemaphoreGiveRecursive() for each successful 'take' request. For example, if a task successfully 'takes' the same mutex 5 times then the mutex will not be available to any other task until it has also 'given' the mutex back exactly five times. This type of semaphore uses a priority inheritance mechanism so a task 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the semaphore it is no longer required. Mutex type semaphores cannot be used from within interrupt service routines. See xSemaphoreCreateBinary() for an alternative implementation that can be used for pure synchronisation (where one task or interrupt always 'gives' the semaphore and another always 'takes' the semaphore) and from within interrupt service routines. Example usage: SemaphoreHandle_t xSemaphore; void vATask( void * pvParameters ) { // Semaphore cannot be used before a call to xSemaphoreCreateMutex(). // This is a macro so pass the variable in directly. xSemaphore = xSemaphoreCreateRecursiveMutex(); if( xSemaphore != NULL ) { // The semaphore was created successfully. // The semaphore can now be used. } } - Returns xSemaphore Handle to the created mutex semaphore. Should be of type SemaphoreHandle_t. - xSemaphoreCreateRecursiveMutexStatic(pxStaticSemaphore) Creates a new recursive mutex type semaphore instance, and returns a handle by which the new recursive mutex can be referenced. Internally, within the FreeRTOS implementation, recursive mutexes use a block of memory, in which the mutex structure is stored. If a recursive mutex is created using xSemaphoreCreateRecursiveMutex() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateRecursiveMutex() function. (see https://www.FreeRTOS.org/a00111.html). If a recursive mutex is created using xSemaphoreCreateRecursiveMutexStatic() then the application writer must provide the memory that will get used by the mutex. xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to be created without using any dynamic memory allocation. Mutexes created using this macro can be accessed using the xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The xSemaphoreTake() and xSemaphoreGive() macros must not be used. A mutex used recursively can be 'taken' repeatedly by the owner. The mutex doesn't become available again until the owner has called xSemaphoreGiveRecursive() for each successful 'take' request. For example, if a task successfully 'takes' the same mutex 5 times then the mutex will not be available to any other task until it has also 'given' the mutex back exactly five times. This type of semaphore uses a priority inheritance mechanism so a task 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the semaphore it is no longer required. Mutex type semaphores cannot be used from within interrupt service routines. See xSemaphoreCreateBinary() for an alternative implementation that can be used for pure synchronisation (where one task or interrupt always 'gives' the semaphore and another always 'takes' the semaphore) and from within interrupt service routines. Example usage: SemaphoreHandle_t xSemaphore; StaticSemaphore_t xMutexBuffer; void vATask( void * pvParameters ) { // A recursive semaphore cannot be used before it is created. Here a // recursive mutex is created using xSemaphoreCreateRecursiveMutexStatic(). // The address of xMutexBuffer is passed into the function, and will hold // the mutexes data structures - so no dynamic memory allocation will be // attempted. xSemaphore = xSemaphoreCreateRecursiveMutexStatic( &xMutexBuffer ); // As no dynamic memory allocation was performed, xSemaphore cannot be NULL, // so there is no need to check it. } - Parameters pxStaticSemaphore -- Must point to a variable of type StaticSemaphore_t, which will then be used to hold the recursive mutex's data structure, removing the need for the memory to be allocated dynamically. - - Returns If the recursive mutex was successfully created then a handle to the created recursive mutex is returned. If pxStaticSemaphore was NULL then NULL is returned. - xSemaphoreCreateCounting(uxMaxCount, uxInitialCount) Creates a new counting semaphore instance, and returns a handle by which the new counting semaphore can be referenced. In many usage scenarios it is faster and more memory efficient to use a direct to task notification in place of a counting semaphore! https://www.FreeRTOS.org/RTOS-task-notifications.html Internally, within the FreeRTOS implementation, counting semaphores use a block of memory, in which the counting semaphore structure is stored. If a counting semaphore is created using xSemaphoreCreateCounting() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateCounting() function. (see https://www.FreeRTOS.org/a00111.html). If a counting semaphore is created using xSemaphoreCreateCountingStatic() then the application writer can instead optionally provide the memory that will get used by the counting semaphore. xSemaphoreCreateCountingStatic() therefore allows a counting semaphore to be created without using any dynamic memory allocation. Counting semaphores are typically used for two things: 1) Counting events. In this usage scenario an event handler will 'give' a semaphore each time an event occurs (incrementing the semaphore count value), and a handler task will 'take' a semaphore each time it processes an event (decrementing the semaphore count value). The count value is therefore the difference between the number of events that have occurred and the number that have been processed. In this case it is desirable for the initial count value to be zero. 2) Resource management. In this usage scenario the count value indicates the number of resources available. To obtain control of a resource a task must first obtain a semaphore - decrementing the semaphore count value. When the count value reaches zero there are no free resources. When a task finishes with the resource it 'gives' the semaphore back - incrementing the semaphore count value. In this case it is desirable for the initial count value to be equal to the maximum count value, indicating that all resources are free. Example usage: SemaphoreHandle_t xSemaphore; void vATask( void * pvParameters ) { SemaphoreHandle_t xSemaphore = NULL; // Semaphore cannot be used before a call to xSemaphoreCreateCounting(). // The max value to which the semaphore can count should be 10, and the // initial value assigned to the count should be 0. xSemaphore = xSemaphoreCreateCounting( 10, 0 ); if( xSemaphore != NULL ) { // The semaphore was created successfully. // The semaphore can now be used. } } - Parameters uxMaxCount -- The maximum count value that can be reached. When the semaphore reaches this value it can no longer be 'given'. uxInitialCount -- The count value assigned to the semaphore when it is created. - - Returns Handle to the created semaphore. Null if the semaphore could not be created. - xSemaphoreCreateCountingStatic(uxMaxCount, uxInitialCount, pxSemaphoreBuffer) Creates a new counting semaphore instance, and returns a handle by which the new counting semaphore can be referenced. In many usage scenarios it is faster and more memory efficient to use a direct to task notification in place of a counting semaphore! https://www.FreeRTOS.org/RTOS-task-notifications.html Internally, within the FreeRTOS implementation, counting semaphores use a block of memory, in which the counting semaphore structure is stored. If a counting semaphore is created using xSemaphoreCreateCounting() then the required memory is automatically dynamically allocated inside the xSemaphoreCreateCounting() function. (see https://www.FreeRTOS.org/a00111.html). If a counting semaphore is created using xSemaphoreCreateCountingStatic() then the application writer must provide the memory. xSemaphoreCreateCountingStatic() therefore allows a counting semaphore to be created without using any dynamic memory allocation. Counting semaphores are typically used for two things: 1) Counting events. In this usage scenario an event handler will 'give' a semaphore each time an event occurs (incrementing the semaphore count value), and a handler task will 'take' a semaphore each time it processes an event (decrementing the semaphore count value). The count value is therefore the difference between the number of events that have occurred and the number that have been processed. In this case it is desirable for the initial count value to be zero. 2) Resource management. In this usage scenario the count value indicates the number of resources available. To obtain control of a resource a task must first obtain a semaphore - decrementing the semaphore count value. When the count value reaches zero there are no free resources. When a task finishes with the resource it 'gives' the semaphore back - incrementing the semaphore count value. In this case it is desirable for the initial count value to be equal to the maximum count value, indicating that all resources are free. Example usage: SemaphoreHandle_t xSemaphore; StaticSemaphore_t xSemaphoreBuffer; void vATask( void * pvParameters ) { SemaphoreHandle_t xSemaphore = NULL; // Counting semaphore cannot be used before they have been created. Create // a counting semaphore using xSemaphoreCreateCountingStatic(). The max // value to which the semaphore can count is 10, and the initial value // assigned to the count will be 0. The address of xSemaphoreBuffer is // passed in and will be used to hold the semaphore structure, so no dynamic // memory allocation will be used. xSemaphore = xSemaphoreCreateCounting( 10, 0, &xSemaphoreBuffer ); // No memory allocation was attempted so xSemaphore cannot be NULL, so there // is no need to check its value. } - Parameters uxMaxCount -- The maximum count value that can be reached. When the semaphore reaches this value it can no longer be 'given'. uxInitialCount -- The count value assigned to the semaphore when it is created. pxSemaphoreBuffer -- Must point to a variable of type StaticSemaphore_t, which will then be used to hold the semaphore's data structure, removing the need for the memory to be allocated dynamically. - - Returns If the counting semaphore was successfully created then a handle to the created counting semaphore is returned. If pxSemaphoreBuffer was NULL then NULL is returned. - vSemaphoreDelete(xSemaphore) Delete a semaphore. This function must be used with care. For example, do not delete a mutex type semaphore if the mutex is held by a task. - Parameters xSemaphore -- A handle to the semaphore to be deleted. - - xSemaphoreGetMutexHolder(xSemaphore) If xMutex is indeed a mutex type semaphore, return the current mutex holder. If xMutex is not a mutex type semaphore, or the mutex is available (not held by a task), return NULL. Note: This is a good way of determining if the calling task is the mutex holder, but not a good way of determining the identity of the mutex holder as the holder may change between the function exiting and the returned value being tested. - xSemaphoreGetMutexHolderFromISR(xSemaphore) If xMutex is indeed a mutex type semaphore, return the current mutex holder. If xMutex is not a mutex type semaphore, or the mutex is available (not held by a task), return NULL. - uxSemaphoreGetCount(xSemaphore) If the semaphore is a counting semaphore then uxSemaphoreGetCount() returns its current count value. If the semaphore is a binary semaphore then uxSemaphoreGetCount() returns 1 if the semaphore is available, and 0 if the semaphore is not available. - uxSemaphoreGetCountFromISR(xSemaphore) semphr.h UBaseType_t uxSemaphoreGetCountFromISR( SemaphoreHandle_t xSemaphore ); If the semaphore is a counting semaphore then uxSemaphoreGetCountFromISR() returns its current count value. If the semaphore is a binary semaphore then uxSemaphoreGetCountFromISR() returns 1 if the semaphore is available, and 0 if the semaphore is not available. - xSemaphoreGetStaticBuffer(xSemaphore, ppxSemaphoreBuffer) Retrieve pointer to a statically created binary semaphore, counting semaphore, or mutex semaphore's data structure buffer. This is the same buffer that is supplied at the time of creation. - Parameters xSemaphore -- The semaphore for which to retrieve the buffer. ppxSemaphoreBuffer -- Used to return a pointer to the semaphore's data structure buffer. - - Returns pdTRUE if buffer was retrieved, pdFALSE otherwise. Type Definitions - typedef QueueHandle_t SemaphoreHandle_t Timer API Header File components/freertos/FreeRTOS-Kernel/include/freertos/timers.h This header file can be included with: #include "freertos/timers.h" Functions - TimerHandle_t xTimerCreate(const char *const pcTimerName, const TickType_t xTimerPeriodInTicks, const BaseType_t xAutoReload, void *const pvTimerID, TimerCallbackFunction_t pxCallbackFunction) Creates a new software timer instance, and returns a handle by which the created software timer can be referenced. Internally, within the FreeRTOS implementation, software timers use a block of memory, in which the timer data structure is stored. If a software timer is created using xTimerCreate() then the required memory is automatically dynamically allocated inside the xTimerCreate() function. (see https://www.FreeRTOS.org/a00111.html). If a software timer is created using xTimerCreateStatic() then the application writer must provide the memory that will get used by the software timer. xTimerCreateStatic() therefore allows a software timer to be created without using any dynamic memory allocation. Timers are created in the dormant state. The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the active state. Example usage: * #define NUM_TIMERS 5 * * // An array to hold handles to the created timers. * TimerHandle_t xTimers[ NUM_TIMERS ]; * * // An array to hold a count of the number of times each timer expires. * int32_t lExpireCounters[ NUM_TIMERS ] = { 0 }; * * // Define a callback function that will be used by multiple timer instances. * // The callback function does nothing but count the number of times the * // associated timer expires, and stop the timer once the timer has expired * // 10 times. * void vTimerCallback( TimerHandle_t pxTimer ) * { * int32_t lArrayIndex; * const int32_t xMaxExpiryCountBeforeStopping = 10; * * // Optionally do something if the pxTimer parameter is NULL. * configASSERT( pxTimer ); * * // Which timer expired? * lArrayIndex = ( int32_t ) pvTimerGetTimerID( pxTimer ); * * // Increment the number of times that pxTimer has expired. * lExpireCounters[ lArrayIndex ] += 1; * * // If the timer has expired 10 times then stop it from running. * if( lExpireCounters[ lArrayIndex ] == xMaxExpiryCountBeforeStopping ) * { * // Do not use a block time if calling a timer API function from a * // timer callback function, as doing so could cause a deadlock! * xTimerStop( pxTimer, 0 ); * } * } * * void main( void ) * { * int32_t x; * * // Create then start some timers. Starting the timers before the scheduler * // has been started means the timers will start running immediately that * // the scheduler starts. * for( x = 0; x < NUM_TIMERS; x++ ) * { * xTimers[ x ] = xTimerCreate( "Timer", // Just a text name, not used by the kernel. * ( 100 * ( x + 1 ) ), // The timer period in ticks. * pdTRUE, // The timers will auto-reload themselves when they expire. * ( void * ) x, // Assign each timer a unique id equal to its array index. * vTimerCallback // Each timer calls the same callback when it expires. * ); * * if( xTimers[ x ] == NULL ) * { * // The timer was not created. * } * else * { * // Start the timer. No block time is specified, and even if one was * // it would be ignored because the scheduler has not yet been * // started. * if( xTimerStart( xTimers[ x ], 0 ) != pdPASS ) * { * // The timer could not be set into the Active state. * } * } * } * * // ... * // Create tasks here. * // ... * * // Starting the scheduler will start the timers running as they have already * // been set into the active state. * vTaskStartScheduler(); * * // Should not reach here. * for( ;; ); * } * - Parameters pcTimerName -- A text name that is assigned to the timer. This is done purely to assist debugging. The kernel itself only ever references a timer by its handle, and never by its name. xTimerPeriodInTicks -- The timer period. The time is defined in tick periods so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xTimerPeriodInTicks should be set to 100. Alternatively, if the timer must expire after 500ms, then xPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. Time timer period must be greater than 0. xAutoReload -- If xAutoReload is set to pdTRUE then the timer will expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. If xAutoReload is set to pdFALSE then the timer will be a one-shot timer and enter the dormant state after it expires. pvTimerID -- An identifier that is assigned to the timer being created. Typically this would be used in the timer callback function to identify which timer expired when the same callback function is assigned to more than one timer. pxCallbackFunction -- The function to call when the timer expires. Callback functions must have the prototype defined by TimerCallbackFunction_t, which is "void vCallbackFunction( TimerHandle_t xTimer );". - - Returns If the timer is successfully created then a handle to the newly created timer is returned. If the timer cannot be created because there is insufficient FreeRTOS heap remaining to allocate the timer structures then NULL is returned. - TimerHandle_t xTimerCreateStatic(const char *const pcTimerName, const TickType_t xTimerPeriodInTicks, const BaseType_t xAutoReload, void *const pvTimerID, TimerCallbackFunction_t pxCallbackFunction, StaticTimer_t *pxTimerBuffer) Creates a new software timer instance, and returns a handle by which the created software timer can be referenced. Internally, within the FreeRTOS implementation, software timers use a block of memory, in which the timer data structure is stored. If a software timer is created using xTimerCreate() then the required memory is automatically dynamically allocated inside the xTimerCreate() function. (see https://www.FreeRTOS.org/a00111.html). If a software timer is created using xTimerCreateStatic() then the application writer must provide the memory that will get used by the software timer. xTimerCreateStatic() therefore allows a software timer to be created without using any dynamic memory allocation. Timers are created in the dormant state. The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the active state. Example usage: * * // The buffer used to hold the software timer's data structure. * static StaticTimer_t xTimerBuffer; * * // A variable that will be incremented by the software timer's callback * // function. * UBaseType_t uxVariableToIncrement = 0; * * // A software timer callback function that increments a variable passed to * // it when the software timer was created. After the 5th increment the * // callback function stops the software timer. * static void prvTimerCallback( TimerHandle_t xExpiredTimer ) * { * UBaseType_t *puxVariableToIncrement; * BaseType_t xReturned; * * // Obtain the address of the variable to increment from the timer ID. * puxVariableToIncrement = ( UBaseType_t * ) pvTimerGetTimerID( xExpiredTimer ); * * // Increment the variable to show the timer callback has executed. * ( *puxVariableToIncrement )++; * * // If this callback has executed the required number of times, stop the * // timer. * if( *puxVariableToIncrement == 5 ) * { * // This is called from a timer callback so must not block. * xTimerStop( xExpiredTimer, staticDONT_BLOCK ); * } * } * * * void main( void ) * { * // Create the software time. xTimerCreateStatic() has an extra parameter * // than the normal xTimerCreate() API function. The parameter is a pointer * // to the StaticTimer_t structure that will hold the software timer * // structure. If the parameter is passed as NULL then the structure will be * // allocated dynamically, just as if xTimerCreate() had been called. * xTimer = xTimerCreateStatic( "T1", // Text name for the task. Helps debugging only. Not used by FreeRTOS. * xTimerPeriod, // The period of the timer in ticks. * pdTRUE, // This is an auto-reload timer. * ( void * ) &uxVariableToIncrement, // A variable incremented by the software timer's callback function * prvTimerCallback, // The function to execute when the timer expires. * &xTimerBuffer ); // The buffer that will hold the software timer structure. * * // The scheduler has not started yet so a block time is not used. * xReturned = xTimerStart( xTimer, 0 ); * * // ... * // Create tasks here. * // ... * * // Starting the scheduler will start the timers running as they have already * // been set into the active state. * vTaskStartScheduler(); * * // Should not reach here. * for( ;; ); * } * - Parameters pcTimerName -- A text name that is assigned to the timer. This is done purely to assist debugging. The kernel itself only ever references a timer by its handle, and never by its name. xTimerPeriodInTicks -- The timer period. The time is defined in tick periods so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xTimerPeriodInTicks should be set to 100. Alternatively, if the timer must expire after 500ms, then xPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. The timer period must be greater than 0. xAutoReload -- If xAutoReload is set to pdTRUE then the timer will expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. If xAutoReload is set to pdFALSE then the timer will be a one-shot timer and enter the dormant state after it expires. pvTimerID -- An identifier that is assigned to the timer being created. Typically this would be used in the timer callback function to identify which timer expired when the same callback function is assigned to more than one timer. pxCallbackFunction -- The function to call when the timer expires. Callback functions must have the prototype defined by TimerCallbackFunction_t, which is "void vCallbackFunction( TimerHandle_t xTimer );". pxTimerBuffer -- Must point to a variable of type StaticTimer_t, which will be then be used to hold the software timer's data structures, removing the need for the memory to be allocated dynamically. - - Returns If the timer is created then a handle to the created timer is returned. If pxTimerBuffer was NULL then NULL is returned. - void *pvTimerGetTimerID(const TimerHandle_t xTimer) Returns the ID assigned to the timer. IDs are assigned to timers using the pvTimerID parameter of the call to xTimerCreated() that was used to create the timer, and by calling the vTimerSetTimerID() API function. If the same callback function is assigned to multiple timers then the timer ID can be used as time specific (timer local) storage. Example usage: See the xTimerCreate() API function example usage scenario. - Parameters xTimer -- The timer being queried. - Returns The ID assigned to the timer being queried. - void vTimerSetTimerID(TimerHandle_t xTimer, void *pvNewID) Sets the ID assigned to the timer. IDs are assigned to timers using the pvTimerID parameter of the call to xTimerCreated() that was used to create the timer. If the same callback function is assigned to multiple timers then the timer ID can be used as time specific (timer local) storage. Example usage: See the xTimerCreate() API function example usage scenario. - Parameters xTimer -- The timer being updated. pvNewID -- The ID to assign to the timer. - - BaseType_t xTimerIsTimerActive(TimerHandle_t xTimer) Queries a timer to see if it is active or dormant. A timer will be dormant if: 1) It has been created but not started, or 2) It is an expired one-shot timer that has not been restarted. Timers are created in the dormant state. The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the active state. Example usage: * // This function assumes xTimer has already been created. * void vAFunction( TimerHandle_t xTimer ) * { * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" * { * // xTimer is active, do something. * } * else * { * // xTimer is not active, do something else. * } * } * - Parameters xTimer -- The timer being queried. - Returns pdFALSE will be returned if the timer is dormant. A value other than pdFALSE will be returned if the timer is active. - TaskHandle_t xTimerGetTimerDaemonTaskHandle(void) Simply returns the handle of the timer service/daemon task. It it not valid to call xTimerGetTimerDaemonTaskHandle() before the scheduler has been started. - BaseType_t xTimerPendFunctionCallFromISR(PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken) Used from application interrupt service routines to defer the execution of a function to the RTOS daemon task (the timer service task, hence this function is implemented in timers.c and is prefixed with 'Timer'). Ideally an interrupt service routine (ISR) is kept as short as possible, but sometimes an ISR either has a lot of processing to do, or needs to perform processing that is not deterministic. In these cases xTimerPendFunctionCallFromISR() can be used to defer processing of a function to the RTOS daemon task. A mechanism is provided that allows the interrupt to return directly to the task that will subsequently execute the pended callback function. This allows the callback function to execute contiguously in time with the interrupt - just as if the callback had executed in the interrupt itself. Example usage: * * // The callback function that will execute in the context of the daemon task. * // Note callback functions must all use this same prototype. * void vProcessInterface( void *pvParameter1, uint32_t ulParameter2 ) * { * BaseType_t xInterfaceToService; * * // The interface that requires servicing is passed in the second * // parameter. The first parameter is not used in this case. * xInterfaceToService = ( BaseType_t ) ulParameter2; * * // ...Perform the processing here... * } * * // An ISR that receives data packets from multiple interfaces * void vAnISR( void ) * { * BaseType_t xInterfaceToService, xHigherPriorityTaskWoken; * * // Query the hardware to determine which interface needs processing. * xInterfaceToService = prvCheckInterfaces(); * * // The actual processing is to be deferred to a task. Request the * // vProcessInterface() callback function is executed, passing in the * // number of the interface that needs processing. The interface to * // service is passed in the second parameter. The first parameter is * // not used in this case. * xHigherPriorityTaskWoken = pdFALSE; * xTimerPendFunctionCallFromISR( vProcessInterface, NULL, ( uint32_t ) xInterfaceToService, &xHigherPriorityTaskWoken ); * * // If xHigherPriorityTaskWoken is now set to pdTRUE then a context * // switch should be requested. The macro used is port specific and will * // be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to * // the documentation page for the port being used. * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); * * } * - Parameters xFunctionToPend -- The function to execute from the timer service/ daemon task. The function must conform to the PendedFunction_t prototype. pvParameter1 -- The value of the callback function's first parameter. The parameter has a void * type to allow it to be used to pass any type. For example, unsigned longs can be cast to a void *, or the void * can be used to point to a structure. ulParameter2 -- The value of the callback function's second parameter. pxHigherPriorityTaskWoken -- As mentioned above, calling this function will result in a message being sent to the timer daemon task. If the priority of the timer daemon task (which is set using configTIMER_TASK_PRIORITY in FreeRTOSConfig.h) is higher than the priority of the currently running task (the task the interrupt interrupted) then *pxHigherPriorityTaskWoken will be set to pdTRUE within xTimerPendFunctionCallFromISR(), indicating that a context switch should be requested before the interrupt exits. For that reason *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the example code below. - - Returns pdPASS is returned if the message was successfully sent to the timer daemon task, otherwise pdFALSE is returned. - BaseType_t xTimerPendFunctionCall(PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait) Used to defer the execution of a function to the RTOS daemon task (the timer service task, hence this function is implemented in timers.c and is prefixed with 'Timer'). - Parameters xFunctionToPend -- The function to execute from the timer service/ daemon task. The function must conform to the PendedFunction_t prototype. pvParameter1 -- The value of the callback function's first parameter. The parameter has a void * type to allow it to be used to pass any type. For example, unsigned longs can be cast to a void *, or the void * can be used to point to a structure. ulParameter2 -- The value of the callback function's second parameter. xTicksToWait -- Calling this function will result in a message being sent to the timer daemon task on a queue. xTicksToWait is the amount of time the calling task should remain in the Blocked state (so not using any processing time) for space to become available on the timer queue if the queue is found to be full. - - Returns pdPASS is returned if the message was successfully sent to the timer daemon task, otherwise pdFALSE is returned. - const char *pcTimerGetName(TimerHandle_t xTimer) Returns the name that was assigned to a timer when the timer was created. - Parameters xTimer -- The handle of the timer being queried. - Returns The name assigned to the timer specified by the xTimer parameter. - void vTimerSetReloadMode(TimerHandle_t xTimer, const BaseType_t xAutoReload) Updates a timer to be either an auto-reload timer, in which case the timer automatically resets itself each time it expires, or a one-shot timer, in which case the timer will only expire once unless it is manually restarted. - Parameters xTimer -- The handle of the timer being updated. xAutoReload -- If xAutoReload is set to pdTRUE then the timer will expire repeatedly with a frequency set by the timer's period (see the xTimerPeriodInTicks parameter of the xTimerCreate() API function). If xAutoReload is set to pdFALSE then the timer will be a one-shot timer and enter the dormant state after it expires. - - BaseType_t xTimerGetReloadMode(TimerHandle_t xTimer) Queries a timer to determine if it is an auto-reload timer, in which case the timer automatically resets itself each time it expires, or a one-shot timer, in which case the timer will only expire once unless it is manually restarted. - Parameters xTimer -- The handle of the timer being queried. - Returns If the timer is an auto-reload timer then pdTRUE is returned, otherwise pdFALSE is returned. - UBaseType_t uxTimerGetReloadMode(TimerHandle_t xTimer) Queries a timer to determine if it is an auto-reload timer, in which case the timer automatically resets itself each time it expires, or a one-shot timer, in which case the timer will only expire once unless it is manually restarted. - Parameters xTimer -- The handle of the timer being queried. - Returns If the timer is an auto-reload timer then pdTRUE is returned, otherwise pdFALSE is returned. - TickType_t xTimerGetPeriod(TimerHandle_t xTimer) Returns the period of a timer. - Parameters xTimer -- The handle of the timer being queried. - Returns The period of the timer in ticks. - TickType_t xTimerGetExpiryTime(TimerHandle_t xTimer) Returns the time in ticks at which the timer will expire. If this is less than the current tick count then the expiry time has overflowed from the current time. - Parameters xTimer -- The handle of the timer being queried. - Returns If the timer is running then the time in ticks at which the timer will next expire is returned. If the timer is not running then the return value is undefined. - BaseType_t xTimerGetStaticBuffer(TimerHandle_t xTimer, StaticTimer_t **ppxTimerBuffer) Retrieve pointer to a statically created timer's data structure buffer. This is the same buffer that is supplied at the time of creation. - Parameters xTimer -- The timer for which to retrieve the buffer. ppxTimerBuffer -- Used to return a pointer to the timers's data structure buffer. - - Returns pdTRUE if the buffer was retrieved, pdFALSE otherwise. - void vApplicationGetTimerTaskMemory(StaticTask_t **ppxTimerTaskTCBBuffer, StackType_t **ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize) This function is used to provide a statically allocated block of memory to FreeRTOS to hold the Timer Task TCB. This function is required when configSUPPORT_STATIC_ALLOCATION is set. For more information see this URI: https://www.FreeRTOS.org/a00110.html#configSUPPORT_STATIC_ALLOCATION - Parameters ppxTimerTaskTCBBuffer -- A handle to a statically allocated TCB buffer ppxTimerTaskStackBuffer -- A handle to a statically allocated Stack buffer for the idle task pulTimerTaskStackSize -- A pointer to the number of elements that will fit in the allocated stack buffer - Macros - xTimerStart(xTimer, xTicksToWait) Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API functions send commands to the timer service task through a queue called the timer command queue. The timer command queue is private to the kernel itself and is not directly accessible to application code. The length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant. xTimerStart() starts a timer that was previously created using the xTimerCreate() API function. If the timer had already been started and was already in the active state, then xTimerStart() has equivalent functionality to the xTimerReset() API function. Starting a timer ensures the timer is in the active state. If the timer is not stopped, deleted, or reset in the mean time, the callback function associated with the timer will get called 'n' ticks after xTimerStart() was called, where 'n' is the timers defined period. It is valid to call xTimerStart() before the scheduler has been started, but when this is done the timer will not actually start until the scheduler is started, and the timers expiry time will be relative to when the scheduler is started, not relative to when xTimerStart() was called. The configUSE_TIMERS configuration constant must be set to 1 for xTimerStart() to be available. Example usage: See the xTimerCreate() API function example usage scenario. - Parameters xTimer -- The handle of the timer being started/restarted. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the start command to be successfully sent to the timer command queue, should the queue already be full when xTimerStart() was called. xTicksToWait is ignored if xTimerStart() is called before the scheduler is started. - - Returns pdFAIL will be returned if the start command could not be sent to the timer command queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system, although the timers expiry time is relative to when xTimerStart() is actually called. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. - xTimerStop(xTimer, xTicksToWait) Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API functions send commands to the timer service task through a queue called the timer command queue. The timer command queue is private to the kernel itself and is not directly accessible to application code. The length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant. xTimerStop() stops a timer that was previously started using either of the The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() or xTimerChangePeriodFromISR() API functions. Stopping a timer ensures the timer is not in the active state. The configUSE_TIMERS configuration constant must be set to 1 for xTimerStop() to be available. Example usage: See the xTimerCreate() API function example usage scenario. - Parameters xTimer -- The handle of the timer being stopped. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the stop command to be successfully sent to the timer command queue, should the queue already be full when xTimerStop() was called. xTicksToWait is ignored if xTimerStop() is called before the scheduler is started. - - Returns pdFAIL will be returned if the stop command could not be sent to the timer command queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. - xTimerChangePeriod(xTimer, xNewPeriod, xTicksToWait) Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API functions send commands to the timer service task through a queue called the timer command queue. The timer command queue is private to the kernel itself and is not directly accessible to application code. The length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant. xTimerChangePeriod() changes the period of a timer that was previously created using the xTimerCreate() API function. xTimerChangePeriod() can be called to change the period of an active or dormant state timer. The configUSE_TIMERS configuration constant must be set to 1 for xTimerChangePeriod() to be available. Example usage: * // This function assumes xTimer has already been created. If the timer * // referenced by xTimer is already active when it is called, then the timer * // is deleted. If the timer referenced by xTimer is not active when it is * // called, then the period of the timer is set to 500ms and the timer is * // started. * void vAFunction( TimerHandle_t xTimer ) * { * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" * { * // xTimer is already active - delete it. * xTimerDelete( xTimer ); * } * else * { * // xTimer is not active, change its period to 500ms. This will also * // cause the timer to start. Block for a maximum of 100 ticks if the * // change period command cannot immediately be sent to the timer * // command queue. * if( xTimerChangePeriod( xTimer, 500 / portTICK_PERIOD_MS, 100 ) == pdPASS ) * { * // The command was successfully sent. * } * else * { * // The command could not be sent, even after waiting for 100 ticks * // to pass. Take appropriate action here. * } * } * } * - Parameters xTimer -- The handle of the timer that is having its period changed. xNewPeriod -- The new period for xTimer. Timer periods are specified in tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, if the timer must expire after 500ms, then xNewPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the change period command to be successfully sent to the timer command queue, should the queue already be full when xTimerChangePeriod() was called. xTicksToWait is ignored if xTimerChangePeriod() is called before the scheduler is started. - - Returns pdFAIL will be returned if the change period command could not be sent to the timer command queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. - xTimerDelete(xTimer, xTicksToWait) Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API functions send commands to the timer service task through a queue called the timer command queue. The timer command queue is private to the kernel itself and is not directly accessible to application code. The length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant. xTimerDelete() deletes a timer that was previously created using the xTimerCreate() API function. The configUSE_TIMERS configuration constant must be set to 1 for xTimerDelete() to be available. Example usage: See the xTimerChangePeriod() API function example usage scenario. - Parameters xTimer -- The handle of the timer being deleted. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the delete command to be successfully sent to the timer command queue, should the queue already be full when xTimerDelete() was called. xTicksToWait is ignored if xTimerDelete() is called before the scheduler is started. - - Returns pdFAIL will be returned if the delete command could not be sent to the timer command queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. - xTimerReset(xTimer, xTicksToWait) Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API functions send commands to the timer service task through a queue called the timer command queue. The timer command queue is private to the kernel itself and is not directly accessible to application code. The length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant. xTimerReset() re-starts a timer that was previously created using the xTimerCreate() API function. If the timer had already been started and was already in the active state, then xTimerReset() will cause the timer to re-evaluate its expiry time so that it is relative to when xTimerReset() was called. If the timer was in the dormant state then xTimerReset() has equivalent functionality to the xTimerStart() API function. Resetting a timer ensures the timer is in the active state. If the timer is not stopped, deleted, or reset in the mean time, the callback function associated with the timer will get called 'n' ticks after xTimerReset() was called, where 'n' is the timers defined period. It is valid to call xTimerReset() before the scheduler has been started, but when this is done the timer will not actually start until the scheduler is started, and the timers expiry time will be relative to when the scheduler is started, not relative to when xTimerReset() was called. The configUSE_TIMERS configuration constant must be set to 1 for xTimerReset() to be available. Example usage: * // When a key is pressed, an LCD back-light is switched on. If 5 seconds pass * // without a key being pressed, then the LCD back-light is switched off. In * // this case, the timer is a one-shot timer. * * TimerHandle_t xBacklightTimer = NULL; * * // The callback function assigned to the one-shot timer. In this case the * // parameter is not used. * void vBacklightTimerCallback( TimerHandle_t pxTimer ) * { * // The timer expired, therefore 5 seconds must have passed since a key * // was pressed. Switch off the LCD back-light. * vSetBacklightState( BACKLIGHT_OFF ); * } * * // The key press event handler. * void vKeyPressEventHandler( char cKey ) * { * // Ensure the LCD back-light is on, then reset the timer that is * // responsible for turning the back-light off after 5 seconds of * // key inactivity. Wait 10 ticks for the command to be successfully sent * // if it cannot be sent immediately. * vSetBacklightState( BACKLIGHT_ON ); * if( xTimerReset( xBacklightTimer, 100 ) != pdPASS ) * { * // The reset command was not executed successfully. Take appropriate * // action here. * } * * // Perform the rest of the key processing here. * } * * void main( void ) * { * int32_t x; * * // Create then start the one-shot timer that is responsible for turning * // the back-light off if no keys are pressed within a 5 second period. * xBacklightTimer = xTimerCreate( "BacklightTimer", // Just a text name, not used by the kernel. * ( 5000 / portTICK_PERIOD_MS), // The timer period in ticks. * pdFALSE, // The timer is a one-shot timer. * 0, // The id is not used by the callback so can take any value. * vBacklightTimerCallback // The callback function that switches the LCD back-light off. * ); * * if( xBacklightTimer == NULL ) * { * // The timer was not created. * } * else * { * // Start the timer. No block time is specified, and even if one was * // it would be ignored because the scheduler has not yet been * // started. * if( xTimerStart( xBacklightTimer, 0 ) != pdPASS ) * { * // The timer could not be set into the Active state. * } * } * * // ... * // Create tasks here. * // ... * * // Starting the scheduler will start the timer running as it has already * // been set into the active state. * vTaskStartScheduler(); * * // Should not reach here. * for( ;; ); * } * - Parameters xTimer -- The handle of the timer being reset/started/restarted. xTicksToWait -- Specifies the time, in ticks, that the calling task should be held in the Blocked state to wait for the reset command to be successfully sent to the timer command queue, should the queue already be full when xTimerReset() was called. xTicksToWait is ignored if xTimerReset() is called before the scheduler is started. - - Returns pdFAIL will be returned if the reset command could not be sent to the timer command queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system, although the timers expiry time is relative to when xTimerStart() is actually called. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. - xTimerStartFromISR(xTimer, pxHigherPriorityTaskWoken) A version of xTimerStart() that can be called from an interrupt service routine. Example usage: * // This scenario assumes xBacklightTimer has already been created. When a * // key is pressed, an LCD back-light is switched on. If 5 seconds pass * // without a key being pressed, then the LCD back-light is switched off. In * // this case, the timer is a one-shot timer, and unlike the example given for * // the xTimerReset() function, the key press event handler is an interrupt * // service routine. * * // The callback function assigned to the one-shot timer. In this case the * // parameter is not used. * void vBacklightTimerCallback( TimerHandle_t pxTimer ) * { * // The timer expired, therefore 5 seconds must have passed since a key * // was pressed. Switch off the LCD back-light. * vSetBacklightState( BACKLIGHT_OFF ); * } * * // The key press interrupt service routine. * void vKeyPressEventInterruptHandler( void ) * { * BaseType_t xHigherPriorityTaskWoken = pdFALSE; * * // Ensure the LCD back-light is on, then restart the timer that is * // responsible for turning the back-light off after 5 seconds of * // key inactivity. This is an interrupt service routine so can only * // call FreeRTOS API functions that end in "FromISR". * vSetBacklightState( BACKLIGHT_ON ); * * // xTimerStartFromISR() or xTimerResetFromISR() could be called here * // as both cause the timer to re-calculate its expiry time. * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was * // declared (in this function). * if( xTimerStartFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) * { * // The start command was not executed successfully. Take appropriate * // action here. * } * * // Perform the rest of the key processing here. * * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch * // should be performed. The syntax required to perform a context switch * // from inside an ISR varies from port to port, and from compiler to * // compiler. Inspect the demos for the port you are using to find the * // actual syntax required. * if( xHigherPriorityTaskWoken != pdFALSE ) * { * // Call the interrupt safe yield function here (actual function * // depends on the FreeRTOS port being used). * } * } * - Parameters xTimer -- The handle of the timer being started/restarted. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerStartFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/daemon task out of the Blocked state. If calling xTimerStartFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/ daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerStartFromISR() function. If xTimerStartFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. - - Returns pdFAIL will be returned if the start command could not be sent to the timer command queue. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system, although the timers expiry time is relative to when xTimerStartFromISR() is actually called. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. - xTimerStopFromISR(xTimer, pxHigherPriorityTaskWoken) A version of xTimerStop() that can be called from an interrupt service routine. Example usage: * // This scenario assumes xTimer has already been created and started. When * // an interrupt occurs, the timer should be simply stopped. * * // The interrupt service routine that stops the timer. * void vAnExampleInterruptServiceRoutine( void ) * { * BaseType_t xHigherPriorityTaskWoken = pdFALSE; * * // The interrupt has occurred - simply stop the timer. * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined * // (within this function). As this is an interrupt service routine, only * // FreeRTOS API functions that end in "FromISR" can be used. * if( xTimerStopFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) * { * // The stop command was not executed successfully. Take appropriate * // action here. * } * * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch * // should be performed. The syntax required to perform a context switch * // from inside an ISR varies from port to port, and from compiler to * // compiler. Inspect the demos for the port you are using to find the * // actual syntax required. * if( xHigherPriorityTaskWoken != pdFALSE ) * { * // Call the interrupt safe yield function here (actual function * // depends on the FreeRTOS port being used). * } * } * - Parameters xTimer -- The handle of the timer being stopped. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerStopFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/daemon task out of the Blocked state. If calling xTimerStopFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/ daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerStopFromISR() function. If xTimerStopFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. - - Returns pdFAIL will be returned if the stop command could not be sent to the timer command queue. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. - xTimerChangePeriodFromISR(xTimer, xNewPeriod, pxHigherPriorityTaskWoken) A version of xTimerChangePeriod() that can be called from an interrupt service routine. Example usage: * // This scenario assumes xTimer has already been created and started. When * // an interrupt occurs, the period of xTimer should be changed to 500ms. * * // The interrupt service routine that changes the period of xTimer. * void vAnExampleInterruptServiceRoutine( void ) * { * BaseType_t xHigherPriorityTaskWoken = pdFALSE; * * // The interrupt has occurred - change the period of xTimer to 500ms. * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined * // (within this function). As this is an interrupt service routine, only * // FreeRTOS API functions that end in "FromISR" can be used. * if( xTimerChangePeriodFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) * { * // The command to change the timers period was not executed * // successfully. Take appropriate action here. * } * * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch * // should be performed. The syntax required to perform a context switch * // from inside an ISR varies from port to port, and from compiler to * // compiler. Inspect the demos for the port you are using to find the * // actual syntax required. * if( xHigherPriorityTaskWoken != pdFALSE ) * { * // Call the interrupt safe yield function here (actual function * // depends on the FreeRTOS port being used). * } * } * - Parameters xTimer -- The handle of the timer that is having its period changed. xNewPeriod -- The new period for xTimer. Timer periods are specified in tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time that has been specified in milliseconds. For example, if the timer must expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, if the timer must expire after 500ms, then xNewPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerChangePeriodFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/ daemon task out of the Blocked state. If calling xTimerChangePeriodFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerChangePeriodFromISR() function. If xTimerChangePeriodFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. - - Returns pdFAIL will be returned if the command to change the timers period could not be sent to the timer command queue. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. - xTimerResetFromISR(xTimer, pxHigherPriorityTaskWoken) A version of xTimerReset() that can be called from an interrupt service routine. Example usage: * // This scenario assumes xBacklightTimer has already been created. When a * // key is pressed, an LCD back-light is switched on. If 5 seconds pass * // without a key being pressed, then the LCD back-light is switched off. In * // this case, the timer is a one-shot timer, and unlike the example given for * // the xTimerReset() function, the key press event handler is an interrupt * // service routine. * * // The callback function assigned to the one-shot timer. In this case the * // parameter is not used. * void vBacklightTimerCallback( TimerHandle_t pxTimer ) * { * // The timer expired, therefore 5 seconds must have passed since a key * // was pressed. Switch off the LCD back-light. * vSetBacklightState( BACKLIGHT_OFF ); * } * * // The key press interrupt service routine. * void vKeyPressEventInterruptHandler( void ) * { * BaseType_t xHigherPriorityTaskWoken = pdFALSE; * * // Ensure the LCD back-light is on, then reset the timer that is * // responsible for turning the back-light off after 5 seconds of * // key inactivity. This is an interrupt service routine so can only * // call FreeRTOS API functions that end in "FromISR". * vSetBacklightState( BACKLIGHT_ON ); * * // xTimerStartFromISR() or xTimerResetFromISR() could be called here * // as both cause the timer to re-calculate its expiry time. * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was * // declared (in this function). * if( xTimerResetFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) * { * // The reset command was not executed successfully. Take appropriate * // action here. * } * * // Perform the rest of the key processing here. * * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch * // should be performed. The syntax required to perform a context switch * // from inside an ISR varies from port to port, and from compiler to * // compiler. Inspect the demos for the port you are using to find the * // actual syntax required. * if( xHigherPriorityTaskWoken != pdFALSE ) * { * // Call the interrupt safe yield function here (actual function * // depends on the FreeRTOS port being used). * } * } * - Parameters xTimer -- The handle of the timer that is to be started, reset, or restarted. pxHigherPriorityTaskWoken -- The timer service/daemon task spends most of its time in the Blocked state, waiting for messages to arrive on the timer command queue. Calling xTimerResetFromISR() writes a message to the timer command queue, so has the potential to transition the timer service/daemon task out of the Blocked state. If calling xTimerResetFromISR() causes the timer service/daemon task to leave the Blocked state, and the timer service/ daemon task has a priority equal to or greater than the currently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerResetFromISR() function. If xTimerResetFromISR() sets this value to pdTRUE then a context switch should be performed before the interrupt exits. - - Returns pdFAIL will be returned if the reset command could not be sent to the timer command queue. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command is actually processed will depend on the priority of the timer service/daemon task relative to other tasks in the system, although the timers expiry time is relative to when xTimerResetFromISR() is actually called. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. Type Definitions - typedef struct tmrTimerControl *TimerHandle_t - typedef void (*TimerCallbackFunction_t)(TimerHandle_t xTimer) Defines the prototype to which timer callback functions must conform. - typedef void (*PendedFunction_t)(void*, uint32_t) Defines the prototype to which functions used with the xTimerPendFunctionCallFromISR() function must conform. Event Group API Header File components/freertos/FreeRTOS-Kernel/include/freertos/event_groups.h This header file can be included with: #include "freertos/event_groups.h" Functions - EventGroupHandle_t xEventGroupCreate(void) Create a new event group. Internally, within the FreeRTOS implementation, event groups use a [small] block of memory, in which the event group's structure is stored. If an event groups is created using xEventGroupCreate() then the required memory is automatically dynamically allocated inside the xEventGroupCreate() function. (see https://www.FreeRTOS.org/a00111.html). If an event group is created using xEventGroupCreateStatic() then the application writer must instead provide the memory that will get used by the event group. xEventGroupCreateStatic() therefore allows an event group to be created without using any dynamic memory allocation. Although event groups are not related to ticks, for internal implementation reasons the number of bits available for use in an event group is dependent on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store event bits within an event group. Example usage: // Declare a variable to hold the created event group. EventGroupHandle_t xCreatedEventGroup; // Attempt to create the event group. xCreatedEventGroup = xEventGroupCreate(); // Was the event group created successfully? if( xCreatedEventGroup == NULL ) { // The event group was not created because there was insufficient // FreeRTOS heap available. } else { // The event group was created. } - Returns If the event group was created then a handle to the event group is returned. If there was insufficient FreeRTOS heap available to create the event group then NULL is returned. See https://www.FreeRTOS.org/a00111.html - EventGroupHandle_t xEventGroupCreateStatic(StaticEventGroup_t *pxEventGroupBuffer) Create a new event group. Internally, within the FreeRTOS implementation, event groups use a [small] block of memory, in which the event group's structure is stored. If an event groups is created using xEventGroupCreate() then the required memory is automatically dynamically allocated inside the xEventGroupCreate() function. (see https://www.FreeRTOS.org/a00111.html). If an event group is created using xEventGroupCreateStatic() then the application writer must instead provide the memory that will get used by the event group. xEventGroupCreateStatic() therefore allows an event group to be created without using any dynamic memory allocation. Although event groups are not related to ticks, for internal implementation reasons the number of bits available for use in an event group is dependent on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store event bits within an event group. Example usage: // StaticEventGroup_t is a publicly accessible structure that has the same // size and alignment requirements as the real event group structure. It is // provided as a mechanism for applications to know the size of the event // group (which is dependent on the architecture and configuration file // settings) without breaking the strict data hiding policy by exposing the // real event group internals. This StaticEventGroup_t variable is passed // into the xSemaphoreCreateEventGroupStatic() function and is used to store // the event group's data structures StaticEventGroup_t xEventGroupBuffer; // Create the event group without dynamically allocating any memory. xEventGroup = xEventGroupCreateStatic( &xEventGroupBuffer ); - Parameters pxEventGroupBuffer -- pxEventGroupBuffer must point to a variable of type StaticEventGroup_t, which will be then be used to hold the event group's data structures, removing the need for the memory to be allocated dynamically. - Returns If the event group was created then a handle to the event group is returned. If pxEventGroupBuffer was NULL then NULL is returned. - EventBits_t xEventGroupWaitBits(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait) [Potentially] block to wait for one or more bits to be set within a previously created event group. This function cannot be called from an interrupt. Example usage: #define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) void aFunction( EventGroupHandle_t xEventGroup ) { EventBits_t uxBits; const TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS; // Wait a maximum of 100ms for either bit 0 or bit 4 to be set within // the event group. Clear the bits before exiting. uxBits = xEventGroupWaitBits( xEventGroup, // The event group being tested. BIT_0 | BIT_4, // The bits within the event group to wait for. pdTRUE, // BIT_0 and BIT_4 should be cleared before returning. pdFALSE, // Don't wait for both bits, either bit will do. xTicksToWait ); // Wait a maximum of 100ms for either bit to be set. if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) ) { // xEventGroupWaitBits() returned because both bits were set. } else if( ( uxBits & BIT_0 ) != 0 ) { // xEventGroupWaitBits() returned because just BIT_0 was set. } else if( ( uxBits & BIT_4 ) != 0 ) { // xEventGroupWaitBits() returned because just BIT_4 was set. } else { // xEventGroupWaitBits() returned because xTicksToWait ticks passed // without either BIT_0 or BIT_4 becoming set. } } - Parameters xEventGroup -- The event group in which the bits are being tested. The event group must have previously been created using a call to xEventGroupCreate(). uxBitsToWaitFor -- A bitwise value that indicates the bit or bits to test inside the event group. For example, to wait for bit 0 and/or bit 2 set uxBitsToWaitFor to 0x05. To wait for bits 0 and/or bit 1 and/or bit 2 set uxBitsToWaitFor to 0x07. Etc. xClearOnExit -- If xClearOnExit is set to pdTRUE then any bits within uxBitsToWaitFor that are set within the event group will be cleared before xEventGroupWaitBits() returns if the wait condition was met (if the function returns for a reason other than a timeout). If xClearOnExit is set to pdFALSE then the bits set in the event group are not altered when the call to xEventGroupWaitBits() returns. xWaitForAllBits -- If xWaitForAllBits is set to pdTRUE then xEventGroupWaitBits() will return when either all the bits in uxBitsToWaitFor are set or the specified block time expires. If xWaitForAllBits is set to pdFALSE then xEventGroupWaitBits() will return when any one of the bits set in uxBitsToWaitFor is set or the specified block time expires. The block time is specified by the xTicksToWait parameter. xTicksToWait -- The maximum amount of time (specified in 'ticks') to wait for one/all (depending on the xWaitForAllBits value) of the bits specified by uxBitsToWaitFor to become set. A value of portMAX_DELAY can be used to block indefinitely (provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). - - Returns The value of the event group at the time either the bits being waited for became set, or the block time expired. Test the return value to know which bits were set. If xEventGroupWaitBits() returned because its timeout expired then not all the bits being waited for will be set. If xEventGroupWaitBits() returned because the bits it was waiting for were set then the returned value is the event group value before any bits were automatically cleared in the case that xClearOnExit parameter was set to pdTRUE. - EventBits_t xEventGroupClearBits(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear) Clear bits within an event group. This function cannot be called from an interrupt. Example usage: #define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) void aFunction( EventGroupHandle_t xEventGroup ) { EventBits_t uxBits; // Clear bit 0 and bit 4 in xEventGroup. uxBits = xEventGroupClearBits( xEventGroup, // The event group being updated. BIT_0 | BIT_4 );// The bits being cleared. if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) ) { // Both bit 0 and bit 4 were set before xEventGroupClearBits() was // called. Both will now be clear (not set). } else if( ( uxBits & BIT_0 ) != 0 ) { // Bit 0 was set before xEventGroupClearBits() was called. It will // now be clear. } else if( ( uxBits & BIT_4 ) != 0 ) { // Bit 4 was set before xEventGroupClearBits() was called. It will // now be clear. } else { // Neither bit 0 nor bit 4 were set in the first place. } } - Parameters xEventGroup -- The event group in which the bits are to be cleared. uxBitsToClear -- A bitwise value that indicates the bit or bits to clear in the event group. For example, to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3 and bit 0 set uxBitsToClear to 0x09. - - Returns The value of the event group before the specified bits were cleared. - EventBits_t xEventGroupSetBits(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet) Set bits within an event group. This function cannot be called from an interrupt. xEventGroupSetBitsFromISR() is a version that can be called from an interrupt. Setting bits in an event group will automatically unblock tasks that are blocked waiting for the bits. Example usage: #define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) void aFunction( EventGroupHandle_t xEventGroup ) { EventBits_t uxBits; // Set bit 0 and bit 4 in xEventGroup. uxBits = xEventGroupSetBits( xEventGroup, // The event group being updated. BIT_0 | BIT_4 );// The bits being set. if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) ) { // Both bit 0 and bit 4 remained set when the function returned. } else if( ( uxBits & BIT_0 ) != 0 ) { // Bit 0 remained set when the function returned, but bit 4 was // cleared. It might be that bit 4 was cleared automatically as a // task that was waiting for bit 4 was removed from the Blocked // state. } else if( ( uxBits & BIT_4 ) != 0 ) { // Bit 4 remained set when the function returned, but bit 0 was // cleared. It might be that bit 0 was cleared automatically as a // task that was waiting for bit 0 was removed from the Blocked // state. } else { // Neither bit 0 nor bit 4 remained set. It might be that a task // was waiting for both of the bits to be set, and the bits were // cleared as the task left the Blocked state. } } - Parameters xEventGroup -- The event group in which the bits are to be set. uxBitsToSet -- A bitwise value that indicates the bit or bits to set. For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 and bit 0 set uxBitsToSet to 0x09. - - Returns The value of the event group at the time the call to xEventGroupSetBits() returns. There are two reasons why the returned value might have the bits specified by the uxBitsToSet parameter cleared. First, if setting a bit results in a task that was waiting for the bit leaving the blocked state then it is possible the bit will be cleared automatically (see the xClearBitOnExit parameter of xEventGroupWaitBits()). Second, any unblocked (or otherwise Ready state) task that has a priority above that of the task that called xEventGroupSetBits() will execute and may change the event group value before the call to xEventGroupSetBits() returns. - EventBits_t xEventGroupSync(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, const EventBits_t uxBitsToWaitFor, TickType_t xTicksToWait) Atomically set bits within an event group, then wait for a combination of bits to be set within the same event group. This functionality is typically used to synchronise multiple tasks, where each task has to wait for the other tasks to reach a synchronisation point before proceeding. This function cannot be used from an interrupt. The function will return before its block time expires if the bits specified by the uxBitsToWait parameter are set, or become set within that time. In this case all the bits specified by uxBitsToWait will be automatically cleared before the function returns. Example usage: // Bits used by the three tasks. #define TASK_0_BIT ( 1 << 0 ) #define TASK_1_BIT ( 1 << 1 ) #define TASK_2_BIT ( 1 << 2 ) #define ALL_SYNC_BITS ( TASK_0_BIT | TASK_1_BIT | TASK_2_BIT ) // Use an event group to synchronise three tasks. It is assumed this event // group has already been created elsewhere. EventGroupHandle_t xEventBits; void vTask0( void *pvParameters ) { EventBits_t uxReturn; TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS; for( ;; ) { // Perform task functionality here. // Set bit 0 in the event flag to note this task has reached the // sync point. The other two tasks will set the other two bits defined // by ALL_SYNC_BITS. All three tasks have reached the synchronisation // point when all the ALL_SYNC_BITS are set. Wait a maximum of 100ms // for this to happen. uxReturn = xEventGroupSync( xEventBits, TASK_0_BIT, ALL_SYNC_BITS, xTicksToWait ); if( ( uxReturn & ALL_SYNC_BITS ) == ALL_SYNC_BITS ) { // All three tasks reached the synchronisation point before the call // to xEventGroupSync() timed out. } } } void vTask1( void *pvParameters ) { for( ;; ) { // Perform task functionality here. // Set bit 1 in the event flag to note this task has reached the // synchronisation point. The other two tasks will set the other two // bits defined by ALL_SYNC_BITS. All three tasks have reached the // synchronisation point when all the ALL_SYNC_BITS are set. Wait // indefinitely for this to happen. xEventGroupSync( xEventBits, TASK_1_BIT, ALL_SYNC_BITS, portMAX_DELAY ); // xEventGroupSync() was called with an indefinite block time, so // this task will only reach here if the synchronisation was made by all // three tasks, so there is no need to test the return value. } } void vTask2( void *pvParameters ) { for( ;; ) { // Perform task functionality here. // Set bit 2 in the event flag to note this task has reached the // synchronisation point. The other two tasks will set the other two // bits defined by ALL_SYNC_BITS. All three tasks have reached the // synchronisation point when all the ALL_SYNC_BITS are set. Wait // indefinitely for this to happen. xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY ); // xEventGroupSync() was called with an indefinite block time, so // this task will only reach here if the synchronisation was made by all // three tasks, so there is no need to test the return value. } } - Parameters xEventGroup -- The event group in which the bits are being tested. The event group must have previously been created using a call to xEventGroupCreate(). uxBitsToSet -- The bits to set in the event group before determining if, and possibly waiting for, all the bits specified by the uxBitsToWait parameter are set. uxBitsToWaitFor -- A bitwise value that indicates the bit or bits to test inside the event group. For example, to wait for bit 0 and bit 2 set uxBitsToWaitFor to 0x05. To wait for bits 0 and bit 1 and bit 2 set uxBitsToWaitFor to 0x07. Etc. xTicksToWait -- The maximum amount of time (specified in 'ticks') to wait for all of the bits specified by uxBitsToWaitFor to become set. - - Returns The value of the event group at the time either the bits being waited for became set, or the block time expired. Test the return value to know which bits were set. If xEventGroupSync() returned because its timeout expired then not all the bits being waited for will be set. If xEventGroupSync() returned because all the bits it was waiting for were set then the returned value is the event group value before any bits were automatically cleared. - EventBits_t xEventGroupGetBitsFromISR(EventGroupHandle_t xEventGroup) A version of xEventGroupGetBits() that can be called from an ISR. - Parameters xEventGroup -- The event group being queried. - Returns The event group bits at the time xEventGroupGetBitsFromISR() was called. - void vEventGroupDelete(EventGroupHandle_t xEventGroup) Delete an event group that was previously created by a call to xEventGroupCreate(). Tasks that are blocked on the event group will be unblocked and obtain 0 as the event group's value. - Parameters xEventGroup -- The event group being deleted. - BaseType_t xEventGroupGetStaticBuffer(EventGroupHandle_t xEventGroup, StaticEventGroup_t **ppxEventGroupBuffer) Retrieve a pointer to a statically created event groups's data structure buffer. It is the same buffer that is supplied at the time of creation. - Parameters xEventGroup -- The event group for which to retrieve the buffer. ppxEventGroupBuffer -- Used to return a pointer to the event groups's data structure buffer. - - Returns pdTRUE if the buffer was retrieved, pdFALSE otherwise. Macros - xEventGroupClearBitsFromISR(xEventGroup, uxBitsToClear) A version of xEventGroupClearBits() that can be called from an interrupt. Setting bits in an event group is not a deterministic operation because there are an unknown number of tasks that may be waiting for the bit or bits being set. FreeRTOS does not allow nondeterministic operations to be performed while interrupts are disabled, so protects event groups that are accessed from tasks by suspending the scheduler rather than disabling interrupts. As a result event groups cannot be accessed directly from an interrupt service routine. Therefore xEventGroupClearBitsFromISR() sends a message to the timer task to have the clear operation performed in the context of the timer task. Example usage: #define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) // An event group which it is assumed has already been created by a call to // xEventGroupCreate(). EventGroupHandle_t xEventGroup; void anInterruptHandler( void ) { // Clear bit 0 and bit 4 in xEventGroup. xResult = xEventGroupClearBitsFromISR( xEventGroup, // The event group being updated. BIT_0 | BIT_4 ); // The bits being set. if( xResult == pdPASS ) { // The message was posted successfully. portYIELD_FROM_ISR(pdTRUE); } } Note If this function returns pdPASS then the timer task is ready to run and a portYIELD_FROM_ISR(pdTRUE) should be executed to perform the needed clear on the event group. This behavior is different from xEventGroupSetBitsFromISR because the parameter xHigherPriorityTaskWoken is not present. - Parameters xEventGroup -- The event group in which the bits are to be cleared. uxBitsToClear -- A bitwise value that indicates the bit or bits to clear. For example, to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3 and bit 0 set uxBitsToClear to 0x09. - - Returns If the request to execute the function was posted successfully then pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned if the timer service queue was full. - xEventGroupSetBitsFromISR(xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken) A version of xEventGroupSetBits() that can be called from an interrupt. Setting bits in an event group is not a deterministic operation because there are an unknown number of tasks that may be waiting for the bit or bits being set. FreeRTOS does not allow nondeterministic operations to be performed in interrupts or from critical sections. Therefore xEventGroupSetBitsFromISR() sends a message to the timer task to have the set operation performed in the context of the timer task - where a scheduler lock is used in place of a critical section. Example usage: #define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) // An event group which it is assumed has already been created by a call to // xEventGroupCreate(). EventGroupHandle_t xEventGroup; void anInterruptHandler( void ) { BaseType_t xHigherPriorityTaskWoken, xResult; // xHigherPriorityTaskWoken must be initialised to pdFALSE. xHigherPriorityTaskWoken = pdFALSE; // Set bit 0 and bit 4 in xEventGroup. xResult = xEventGroupSetBitsFromISR( xEventGroup, // The event group being updated. BIT_0 | BIT_4 // The bits being set. &xHigherPriorityTaskWoken ); // Was the message posted successfully? if( xResult == pdPASS ) { // If xHigherPriorityTaskWoken is now set to pdTRUE then a context // switch should be requested. The macro used is port specific and // will be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - // refer to the documentation page for the port being used. portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } } - Parameters xEventGroup -- The event group in which the bits are to be set. uxBitsToSet -- A bitwise value that indicates the bit or bits to set. For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 and bit 0 set uxBitsToSet to 0x09. pxHigherPriorityTaskWoken -- As mentioned above, calling this function will result in a message being sent to the timer daemon task. If the priority of the timer daemon task is higher than the priority of the currently running task (the task the interrupt interrupted) then *pxHigherPriorityTaskWoken will be set to pdTRUE by xEventGroupSetBitsFromISR(), indicating that a context switch should be requested before the interrupt exits. For that reason *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the example code below. - - Returns If the request to execute the function was posted successfully then pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned if the timer service queue was full. - xEventGroupGetBits(xEventGroup) Returns the current value of the bits in an event group. This function cannot be used from an interrupt. - Parameters xEventGroup -- The event group being queried. - - Returns The event group bits at the time xEventGroupGetBits() was called. Type Definitions - typedef struct EventGroupDef_t *EventGroupHandle_t - typedef TickType_t EventBits_t Stream Buffer API Header File components/freertos/FreeRTOS-Kernel/include/freertos/stream_buffer.h This header file can be included with: #include "freertos/stream_buffer.h" Functions - BaseType_t xStreamBufferGetStaticBuffers(StreamBufferHandle_t xStreamBuffer, uint8_t **ppucStreamBufferStorageArea, StaticStreamBuffer_t **ppxStaticStreamBuffer) Retrieve pointers to a statically created stream buffer's data structure buffer and storage area buffer. These are the same buffers that are supplied at the time of creation. - Parameters xStreamBuffer -- The stream buffer for which to retrieve the buffers. ppucStreamBufferStorageArea -- Used to return a pointer to the stream buffer's storage area buffer. ppxStaticStreamBuffer -- Used to return a pointer to the stream buffer's data structure buffer. - - Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. - size_t xStreamBufferSend(StreamBufferHandle_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, TickType_t xTicksToWait) Sends bytes to a stream buffer. The bytes are copied into the stream buffer. NOTE: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xStreamBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xStreamBufferReceive()) inside a critical section and set the receive block time to 0. Use xStreamBufferSend() to write to a stream buffer from a task. Use xStreamBufferSendFromISR() to write to a stream buffer from an interrupt service routine (ISR). Example use: void vAFunction( StreamBufferHandle_t xStreamBuffer ) { size_t xBytesSent; uint8_t ucArrayToSend[] = { 0, 1, 2, 3 }; char *pcStringToSend = "String to send"; const TickType_t x100ms = pdMS_TO_TICKS( 100 ); // Send an array to the stream buffer, blocking for a maximum of 100ms to // wait for enough space to be available in the stream buffer. xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms ); if( xBytesSent != sizeof( ucArrayToSend ) ) { // The call to xStreamBufferSend() times out before there was enough // space in the buffer for the data to be written, but it did // successfully write xBytesSent bytes. } // Send the string to the stream buffer. Return immediately if there is not // enough space in the buffer. xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 ); if( xBytesSent != strlen( pcStringToSend ) ) { // The entire string could not be added to the stream buffer because // there was not enough free space in the buffer, but xBytesSent bytes // were sent. Could try again to send the remaining bytes. } } - Parameters xStreamBuffer -- The handle of the stream buffer to which a stream is being sent. pvTxData -- A pointer to the buffer that holds the bytes to be copied into the stream buffer. xDataLengthBytes -- The maximum number of bytes to copy from pvTxData into the stream buffer. xTicksToWait -- The maximum amount of time the task should remain in the Blocked state to wait for enough space to become available in the stream buffer, should the stream buffer contain too little space to hold the another xDataLengthBytes bytes. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. If a task times out before it can write all xDataLengthBytes into the buffer it will still write as many bytes as possible. A task does not use any CPU time when it is in the blocked state. - - Returns The number of bytes written to the stream buffer. If a task times out before it can write all xDataLengthBytes into the buffer it will still write as many bytes as possible. - size_t xStreamBufferSendFromISR(StreamBufferHandle_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, BaseType_t *const pxHigherPriorityTaskWoken) Interrupt safe version of the API function that sends a stream of bytes to the stream buffer. NOTE: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xStreamBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xStreamBufferReceive()) inside a critical section and set the receive block time to 0. Use xStreamBufferSend() to write to a stream buffer from a task. Use xStreamBufferSendFromISR() to write to a stream buffer from an interrupt service routine (ISR). Example use: // A stream buffer that has already been created. StreamBufferHandle_t xStreamBuffer; void vAnInterruptServiceRoutine( void ) { size_t xBytesSent; char *pcStringToSend = "String to send"; BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. // Attempt to send the string to the stream buffer. xBytesSent = xStreamBufferSendFromISR( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), &xHigherPriorityTaskWoken ); if( xBytesSent != strlen( pcStringToSend ) ) { // There was not enough free space in the stream buffer for the entire // string to be written, ut xBytesSent bytes were written. } // If xHigherPriorityTaskWoken was set to pdTRUE inside // xStreamBufferSendFromISR() then a task that has a priority above the // priority of the currently executing task was unblocked and a context // switch should be performed to ensure the ISR returns to the unblocked // task. In most FreeRTOS ports this is done by simply passing // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the // variables value, and perform the context switch if necessary. Check the // documentation for the port in use for port specific instructions. portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } - Parameters xStreamBuffer -- The handle of the stream buffer to which a stream is being sent. pvTxData -- A pointer to the data that is to be copied into the stream buffer. xDataLengthBytes -- The maximum number of bytes to copy from pvTxData into the stream buffer. pxHigherPriorityTaskWoken -- It is possible that a stream buffer will have a task blocked on it waiting for data. Calling xStreamBufferSendFromISR() can make data available, and so cause a task that was waiting for data to leave the Blocked state. If calling xStreamBufferSendFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xStreamBufferSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xStreamBufferSendFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. This will ensure that the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the example code below for an example. - - Returns The number of bytes actually written to the stream buffer, which will be less than xDataLengthBytes if the stream buffer didn't have enough free space for all the bytes to be written. - size_t xStreamBufferReceive(StreamBufferHandle_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, TickType_t xTicksToWait) Receives bytes from a stream buffer. NOTE: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xStreamBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xStreamBufferReceive()) inside a critical section and set the receive block time to 0. Use xStreamBufferReceive() to read from a stream buffer from a task. Use xStreamBufferReceiveFromISR() to read from a stream buffer from an interrupt service routine (ISR). Example use: void vAFunction( StreamBuffer_t xStreamBuffer ) { uint8_t ucRxData[ 20 ]; size_t xReceivedBytes; const TickType_t xBlockTime = pdMS_TO_TICKS( 20 ); // Receive up to another sizeof( ucRxData ) bytes from the stream buffer. // Wait in the Blocked state (so not using any CPU processing time) for a // maximum of 100ms for the full sizeof( ucRxData ) number of bytes to be // available. xReceivedBytes = xStreamBufferReceive( xStreamBuffer, ( void * ) ucRxData, sizeof( ucRxData ), xBlockTime ); if( xReceivedBytes > 0 ) { // A ucRxData contains another xReceivedBytes bytes of data, which can // be processed here.... } } - Parameters xStreamBuffer -- The handle of the stream buffer from which bytes are to be received. pvRxData -- A pointer to the buffer into which the received bytes will be copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum number of bytes to receive in one call. xStreamBufferReceive will return as many bytes as possible up to a maximum set by xBufferLengthBytes. xTicksToWait -- The maximum amount of time the task should remain in the Blocked state to wait for data to become available if the stream buffer is empty. xStreamBufferReceive() will return immediately if xTicksToWait is zero. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. A task does not use any CPU time when it is in the Blocked state. - - Returns The number of bytes actually read from the stream buffer, which will be less than xBufferLengthBytes if the call to xStreamBufferReceive() timed out before xBufferLengthBytes were available. - size_t xStreamBufferReceiveFromISR(StreamBufferHandle_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, BaseType_t *const pxHigherPriorityTaskWoken) An interrupt safe version of the API function that receives bytes from a stream buffer. Use xStreamBufferReceive() to read bytes from a stream buffer from a task. Use xStreamBufferReceiveFromISR() to read bytes from a stream buffer from an interrupt service routine (ISR). Example use: // A stream buffer that has already been created. StreamBuffer_t xStreamBuffer; void vAnInterruptServiceRoutine( void ) { uint8_t ucRxData[ 20 ]; size_t xReceivedBytes; BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. // Receive the next stream from the stream buffer. xReceivedBytes = xStreamBufferReceiveFromISR( xStreamBuffer, ( void * ) ucRxData, sizeof( ucRxData ), &xHigherPriorityTaskWoken ); if( xReceivedBytes > 0 ) { // ucRxData contains xReceivedBytes read from the stream buffer. // Process the stream here.... } // If xHigherPriorityTaskWoken was set to pdTRUE inside // xStreamBufferReceiveFromISR() then a task that has a priority above the // priority of the currently executing task was unblocked and a context // switch should be performed to ensure the ISR returns to the unblocked // task. In most FreeRTOS ports this is done by simply passing // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the // variables value, and perform the context switch if necessary. Check the // documentation for the port in use for port specific instructions. portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } - Parameters xStreamBuffer -- The handle of the stream buffer from which a stream is being received. pvRxData -- A pointer to the buffer into which the received bytes are copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum number of bytes to receive in one call. xStreamBufferReceive will return as many bytes as possible up to a maximum set by xBufferLengthBytes. pxHigherPriorityTaskWoken -- It is possible that a stream buffer will have a task blocked on it waiting for space to become available. Calling xStreamBufferReceiveFromISR() can make space available, and so cause a task that is waiting for space to leave the Blocked state. If calling xStreamBufferReceiveFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xStreamBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xStreamBufferReceiveFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. That will ensure the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the code example below for an example. - - Returns The number of bytes read from the stream buffer, if any. - void vStreamBufferDelete(StreamBufferHandle_t xStreamBuffer) Deletes a stream buffer that was previously created using a call to xStreamBufferCreate() or xStreamBufferCreateStatic(). If the stream buffer was created using dynamic memory (that is, by xStreamBufferCreate()), then the allocated memory is freed. A stream buffer handle must not be used after the stream buffer has been deleted. - Parameters xStreamBuffer -- The handle of the stream buffer to be deleted. - BaseType_t xStreamBufferIsFull(StreamBufferHandle_t xStreamBuffer) Queries a stream buffer to see if it is full. A stream buffer is full if it does not have any free space, and therefore cannot accept any more data. - Parameters xStreamBuffer -- The handle of the stream buffer being queried. - Returns If the stream buffer is full then pdTRUE is returned. Otherwise pdFALSE is returned. - BaseType_t xStreamBufferIsEmpty(StreamBufferHandle_t xStreamBuffer) Queries a stream buffer to see if it is empty. A stream buffer is empty if it does not contain any data. - Parameters xStreamBuffer -- The handle of the stream buffer being queried. - Returns If the stream buffer is empty then pdTRUE is returned. Otherwise pdFALSE is returned. - BaseType_t xStreamBufferReset(StreamBufferHandle_t xStreamBuffer) Resets a stream buffer to its initial, empty, state. Any data that was in the stream buffer is discarded. A stream buffer can only be reset if there are no tasks blocked waiting to either send to or receive from the stream buffer. - Parameters xStreamBuffer -- The handle of the stream buffer being reset. - Returns If the stream buffer is reset then pdPASS is returned. If there was a task blocked waiting to send to or read from the stream buffer then the stream buffer is not reset and pdFAIL is returned. - size_t xStreamBufferSpacesAvailable(StreamBufferHandle_t xStreamBuffer) Queries a stream buffer to see how much free space it contains, which is equal to the amount of data that can be sent to the stream buffer before it is full. - Parameters xStreamBuffer -- The handle of the stream buffer being queried. - Returns The number of bytes that can be written to the stream buffer before the stream buffer would be full. - size_t xStreamBufferBytesAvailable(StreamBufferHandle_t xStreamBuffer) Queries a stream buffer to see how much data it contains, which is equal to the number of bytes that can be read from the stream buffer before the stream buffer would be empty. - Parameters xStreamBuffer -- The handle of the stream buffer being queried. - Returns The number of bytes that can be read from the stream buffer before the stream buffer would be empty. - BaseType_t xStreamBufferSetTriggerLevel(StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel) A stream buffer's trigger level is the number of bytes that must be in the stream buffer before a task that is blocked on the stream buffer to wait for data is moved out of the blocked state. For example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 1 then the task will be unblocked when a single byte is written to the buffer or the task's block time expires. As another example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 10 then the task will not be unblocked until the stream buffer contains at least 10 bytes or the task's block time expires. If a reading task's block time expires before the trigger level is reached then the task will still receive however many bytes are actually available. Setting a trigger level of 0 will result in a trigger level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer size. A trigger level is set when the stream buffer is created, and can be modified using xStreamBufferSetTriggerLevel(). - Parameters xStreamBuffer -- The handle of the stream buffer being updated. xTriggerLevel -- The new trigger level for the stream buffer. - - Returns If xTriggerLevel was less than or equal to the stream buffer's length then the trigger level will be updated and pdTRUE is returned. Otherwise pdFALSE is returned. - BaseType_t xStreamBufferSendCompletedFromISR(StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken) For advanced users only. The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when data is sent to a message buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting for data to arrive then the sbSEND_COMPLETED() macro sends a notification to the task to remove it from the Blocked state. xStreamBufferSendCompletedFromISR() does the same thing. It is provided to enable application writers to implement their own version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information. - Parameters xStreamBuffer -- The handle of the stream buffer to which data was written. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xStreamBufferSendCompletedFromISR(). If calling xStreamBufferSendCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. - - Returns If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned. - BaseType_t xStreamBufferReceiveCompletedFromISR(StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken) For advanced users only. The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when data is read out of a message buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting for data to arrive then the sbRECEIVE_COMPLETED() macro sends a notification to the task to remove it from the Blocked state. xStreamBufferReceiveCompletedFromISR() does the same thing. It is provided to enable application writers to implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information. - Parameters xStreamBuffer -- The handle of the stream buffer from which data was read. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xStreamBufferReceiveCompletedFromISR(). If calling xStreamBufferReceiveCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. - - Returns If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned. Macros - xStreamBufferCreateWithCallback(xBufferSizeBytes, xTriggerLevelBytes, pxSendCompletedCallback, pxReceiveCompletedCallback) Creates a new stream buffer using dynamically allocated memory. See xStreamBufferCreateStatic() for a version that uses statically allocated memory (memory that is allocated at compile time). configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in FreeRTOSConfig.h for xStreamBufferCreate() to be available. Example use: void vAFunction( void ) { StreamBufferHandle_t xStreamBuffer; const size_t xStreamBufferSizeBytes = 100, xTriggerLevel = 10; // Create a stream buffer that can hold 100 bytes. The memory used to hold // both the stream buffer structure and the data in the stream buffer is // allocated dynamically. xStreamBuffer = xStreamBufferCreate( xStreamBufferSizeBytes, xTriggerLevel ); if( xStreamBuffer == NULL ) { // There was not enough heap memory space available to create the // stream buffer. } else { // The stream buffer was created successfully and can now be used. } } - Parameters xBufferSizeBytes -- The total number of bytes the stream buffer will be able to hold at any one time. xTriggerLevelBytes -- The number of bytes that must be in the stream buffer before a task that is blocked on the stream buffer to wait for data is moved out of the blocked state. For example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 1 then the task will be unblocked when a single byte is written to the buffer or the task's block time expires. As another example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 10 then the task will not be unblocked until the stream buffer contains at least 10 bytes or the task's block time expires. If a reading task's block time expires before the trigger level is reached then the task will still receive however many bytes are actually available. Setting a trigger level of 0 will result in a trigger level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer size. pxSendCompletedCallback -- Callback invoked when number of bytes at least equal to trigger level is sent to the stream buffer. If the parameter is NULL, it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when more than zero bytes are read from a stream buffer. If the parameter is NULL, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. - - Returns If NULL is returned, then the stream buffer cannot be created because there is insufficient heap memory available for FreeRTOS to allocate the stream buffer data structures and storage area. A non-NULL value being returned indicates that the stream buffer has been created successfully - the returned value should be stored as the handle to the created stream buffer. - xStreamBufferCreateStaticWithCallback(xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea, pxStaticStreamBuffer, pxSendCompletedCallback, pxReceiveCompletedCallback) Creates a new stream buffer using statically allocated memory. See xStreamBufferCreate() for a version that uses dynamically allocated memory. configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h for xStreamBufferCreateStatic() to be available. Example use: // Used to dimension the array used to hold the streams. The available space // will actually be one less than this, so 999. #define STORAGE_SIZE_BYTES 1000 // Defines the memory that will actually hold the streams within the stream // buffer. static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ]; // The variable used to hold the stream buffer structure. StaticStreamBuffer_t xStreamBufferStruct; void MyFunction( void ) { StreamBufferHandle_t xStreamBuffer; const size_t xTriggerLevel = 1; xStreamBuffer = xStreamBufferCreateStatic( sizeof( ucStorageBuffer ), xTriggerLevel, ucStorageBuffer, &xStreamBufferStruct ); // As neither the pucStreamBufferStorageArea or pxStaticStreamBuffer // parameters were NULL, xStreamBuffer will not be NULL, and can be used to // reference the created stream buffer in other stream buffer API calls. // Other code that uses the stream buffer can go here. } - Parameters xBufferSizeBytes -- The size, in bytes, of the buffer pointed to by the pucStreamBufferStorageArea parameter. xTriggerLevelBytes -- The number of bytes that must be in the stream buffer before a task that is blocked on the stream buffer to wait for data is moved out of the blocked state. For example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 1 then the task will be unblocked when a single byte is written to the buffer or the task's block time expires. As another example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 10 then the task will not be unblocked until the stream buffer contains at least 10 bytes or the task's block time expires. If a reading task's block time expires before the trigger level is reached then the task will still receive however many bytes are actually available. Setting a trigger level of 0 will result in a trigger level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer size. pucStreamBufferStorageArea -- Must point to a uint8_t array that is at least xBufferSizeBytes big. This is the array to which streams are copied when they are written to the stream buffer. pxStaticStreamBuffer -- Must point to a variable of type StaticStreamBuffer_t, which will be used to hold the stream buffer's data structure. pxSendCompletedCallback -- Callback invoked when number of bytes at least equal to trigger level is sent to the stream buffer. If the parameter is NULL, it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when more than zero bytes are read from a stream buffer. If the parameter is NULL, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. - - Returns If the stream buffer is created successfully then a handle to the created stream buffer is returned. If either pucStreamBufferStorageArea or pxStaticstreamBuffer are NULL then NULL is returned. Type Definitions - typedef struct StreamBufferDef_t *StreamBufferHandle_t - typedef void (*StreamBufferCallbackFunction_t)(StreamBufferHandle_t xStreamBuffer, BaseType_t xIsInsideISR, BaseType_t *const pxHigherPriorityTaskWoken) Type used as a stream buffer's optional callback. Message Buffer API Header File components/freertos/FreeRTOS-Kernel/include/freertos/message_buffer.h This header file can be included with: #include "freertos/message_buffer.h" Macros - xMessageBufferCreateWithCallback(xBufferSizeBytes, pxSendCompletedCallback, pxReceiveCompletedCallback) Creates a new message buffer using dynamically allocated memory. See xMessageBufferCreateStatic() for a version that uses statically allocated memory (memory that is allocated at compile time). configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in FreeRTOSConfig.h for xMessageBufferCreate() to be available. Example use: void vAFunction( void ) { MessageBufferHandle_t xMessageBuffer; const size_t xMessageBufferSizeBytes = 100; // Create a message buffer that can hold 100 bytes. The memory used to hold // both the message buffer structure and the messages themselves is allocated // dynamically. Each message added to the buffer consumes an additional 4 // bytes which are used to hold the length of the message. xMessageBuffer = xMessageBufferCreate( xMessageBufferSizeBytes ); if( xMessageBuffer == NULL ) { // There was not enough heap memory space available to create the // message buffer. } else { // The message buffer was created successfully and can now be used. } - Parameters xBufferSizeBytes -- The total number of bytes (not messages) the message buffer will be able to hold at any one time. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architectures a 10 byte message will take up 14 bytes of message buffer space. pxSendCompletedCallback -- Callback invoked when a send operation to the message buffer is complete. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, then it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when a receive operation from the message buffer is complete. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. - - Returns If NULL is returned, then the message buffer cannot be created because there is insufficient heap memory available for FreeRTOS to allocate the message buffer data structures and storage area. A non-NULL value being returned indicates that the message buffer has been created successfully - the returned value should be stored as the handle to the created message buffer. - xMessageBufferCreateStaticWithCallback(xBufferSizeBytes, pucMessageBufferStorageArea, pxStaticMessageBuffer, pxSendCompletedCallback, pxReceiveCompletedCallback) Creates a new message buffer using statically allocated memory. See xMessageBufferCreate() for a version that uses dynamically allocated memory. Example use: // Used to dimension the array used to hold the messages. The available space // will actually be one less than this, so 999. #define STORAGE_SIZE_BYTES 1000 // Defines the memory that will actually hold the messages within the message // buffer. static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ]; // The variable used to hold the message buffer structure. StaticMessageBuffer_t xMessageBufferStruct; void MyFunction( void ) { MessageBufferHandle_t xMessageBuffer; xMessageBuffer = xMessageBufferCreateStatic( sizeof( ucStorageBuffer ), ucStorageBuffer, &xMessageBufferStruct ); // As neither the pucMessageBufferStorageArea or pxStaticMessageBuffer // parameters were NULL, xMessageBuffer will not be NULL, and can be used to // reference the created message buffer in other message buffer API calls. // Other code that uses the message buffer can go here. } - Parameters xBufferSizeBytes -- The size, in bytes, of the buffer pointed to by the pucMessageBufferStorageArea parameter. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture a 10 byte message will take up 14 bytes of message buffer space. The maximum number of bytes that can be stored in the message buffer is actually (xBufferSizeBytes - 1). pucMessageBufferStorageArea -- Must point to a uint8_t array that is at least xBufferSizeBytes big. This is the array to which messages are copied when they are written to the message buffer. pxStaticMessageBuffer -- Must point to a variable of type StaticMessageBuffer_t, which will be used to hold the message buffer's data structure. pxSendCompletedCallback -- Callback invoked when a new message is sent to the message buffer. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, then it will use the default implementation provided by sbSEND_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. pxReceiveCompletedCallback -- Callback invoked when a message is read from a message buffer. If the parameter is NULL or xMessageBufferCreate() is called without the parameter, it will use the default implementation provided by sbRECEIVE_COMPLETED macro. To enable the callback, configUSE_SB_COMPLETED_CALLBACK must be set to 1 in FreeRTOSConfig.h. - - Returns If the message buffer is created successfully then a handle to the created message buffer is returned. If either pucMessageBufferStorageArea or pxStaticmessageBuffer are NULL then NULL is returned. - xMessageBufferGetStaticBuffers(xMessageBuffer, ppucMessageBufferStorageArea, ppxStaticMessageBuffer) Retrieve pointers to a statically created message buffer's data structure buffer and storage area buffer. These are the same buffers that are supplied at the time of creation. - Parameters xMessageBuffer -- The message buffer for which to retrieve the buffers. ppucMessageBufferStorageArea -- Used to return a pointer to the message buffer's storage area buffer. ppxStaticMessageBuffer -- Used to return a pointer to the message buffer's data structure buffer. - - Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. - xMessageBufferSend(xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait) Sends a discrete message to the message buffer. The message can be any length that fits within the buffer's free space, and is copied into the buffer. NOTE: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xMessageBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xMessageBufferRead()) inside a critical section and set the receive block time to 0. Use xMessageBufferSend() to write to a message buffer from a task. Use xMessageBufferSendFromISR() to write to a message buffer from an interrupt service routine (ISR). Example use: void vAFunction( MessageBufferHandle_t xMessageBuffer ) { size_t xBytesSent; uint8_t ucArrayToSend[] = { 0, 1, 2, 3 }; char *pcStringToSend = "String to send"; const TickType_t x100ms = pdMS_TO_TICKS( 100 ); // Send an array to the message buffer, blocking for a maximum of 100ms to // wait for enough space to be available in the message buffer. xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms ); if( xBytesSent != sizeof( ucArrayToSend ) ) { // The call to xMessageBufferSend() times out before there was enough // space in the buffer for the data to be written. } // Send the string to the message buffer. Return immediately if there is // not enough space in the buffer. xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 ); if( xBytesSent != strlen( pcStringToSend ) ) { // The string could not be added to the message buffer because there was // not enough free space in the buffer. } } - Parameters xMessageBuffer -- The handle of the message buffer to which a message is being sent. pvTxData -- A pointer to the message that is to be copied into the message buffer. xDataLengthBytes -- The length of the message. That is, the number of bytes to copy from pvTxData into the message buffer. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture setting xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 bytes (20 bytes of message data and 4 bytes to hold the message length). xTicksToWait -- The maximum amount of time the calling task should remain in the Blocked state to wait for enough space to become available in the message buffer, should the message buffer have insufficient space when xMessageBufferSend() is called. The calling task will never block if xTicksToWait is zero. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any CPU time when they are in the Blocked state. - - Returns The number of bytes written to the message buffer. If the call to xMessageBufferSend() times out before there was enough space to write the message into the message buffer then zero is returned. If the call did not time out then xDataLengthBytes is returned. - xMessageBufferSendFromISR(xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken) Interrupt safe version of the API function that sends a discrete message to the message buffer. The message can be any length that fits within the buffer's free space, and is copied into the buffer. NOTE: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xMessageBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xMessageBufferRead()) inside a critical section and set the receive block time to 0. Use xMessageBufferSend() to write to a message buffer from a task. Use xMessageBufferSendFromISR() to write to a message buffer from an interrupt service routine (ISR). Example use: // A message buffer that has already been created. MessageBufferHandle_t xMessageBuffer; void vAnInterruptServiceRoutine( void ) { size_t xBytesSent; char *pcStringToSend = "String to send"; BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. // Attempt to send the string to the message buffer. xBytesSent = xMessageBufferSendFromISR( xMessageBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), &xHigherPriorityTaskWoken ); if( xBytesSent != strlen( pcStringToSend ) ) { // The string could not be added to the message buffer because there was // not enough free space in the buffer. } // If xHigherPriorityTaskWoken was set to pdTRUE inside // xMessageBufferSendFromISR() then a task that has a priority above the // priority of the currently executing task was unblocked and a context // switch should be performed to ensure the ISR returns to the unblocked // task. In most FreeRTOS ports this is done by simply passing // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the // variables value, and perform the context switch if necessary. Check the // documentation for the port in use for port specific instructions. portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } - Parameters xMessageBuffer -- The handle of the message buffer to which a message is being sent. pvTxData -- A pointer to the message that is to be copied into the message buffer. xDataLengthBytes -- The length of the message. That is, the number of bytes to copy from pvTxData into the message buffer. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture setting xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 bytes (20 bytes of message data and 4 bytes to hold the message length). pxHigherPriorityTaskWoken -- It is possible that a message buffer will have a task blocked on it waiting for data. Calling xMessageBufferSendFromISR() can make data available, and so cause a task that was waiting for data to leave the Blocked state. If calling xMessageBufferSendFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xMessageBufferSendFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xMessageBufferSendFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. This will ensure that the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the code example below for an example. - - Returns The number of bytes actually written to the message buffer. If the message buffer didn't have enough free space for the message to be stored then 0 is returned, otherwise xDataLengthBytes is returned. - xMessageBufferReceive(xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait) Receives a discrete message from a message buffer. Messages can be of variable length and are copied out of the buffer. NOTE: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xMessageBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xMessageBufferRead()) inside a critical section and set the receive block time to 0. Use xMessageBufferReceive() to read from a message buffer from a task. Use xMessageBufferReceiveFromISR() to read from a message buffer from an interrupt service routine (ISR). Example use: void vAFunction( MessageBuffer_t xMessageBuffer ) { uint8_t ucRxData[ 20 ]; size_t xReceivedBytes; const TickType_t xBlockTime = pdMS_TO_TICKS( 20 ); // Receive the next message from the message buffer. Wait in the Blocked // state (so not using any CPU processing time) for a maximum of 100ms for // a message to become available. xReceivedBytes = xMessageBufferReceive( xMessageBuffer, ( void * ) ucRxData, sizeof( ucRxData ), xBlockTime ); if( xReceivedBytes > 0 ) { // A ucRxData contains a message that is xReceivedBytes long. Process // the message here.... } } - Parameters xMessageBuffer -- The handle of the message buffer from which a message is being received. pvRxData -- A pointer to the buffer into which the received message is to be copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum length of the message that can be received. If xBufferLengthBytes is too small to hold the next message then the message will be left in the message buffer and 0 will be returned. xTicksToWait -- The maximum amount of time the task should remain in the Blocked state to wait for a message, should the message buffer be empty. xMessageBufferReceive() will return immediately if xTicksToWait is zero and the message buffer is empty. The block time is specified in tick periods, so the absolute time it represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any CPU time when they are in the Blocked state. - - Returns The length, in bytes, of the message read from the message buffer, if any. If xMessageBufferReceive() times out before a message became available then zero is returned. If the length of the message is greater than xBufferLengthBytes then the message will be left in the message buffer and zero is returned. - xMessageBufferReceiveFromISR(xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken) An interrupt safe version of the API function that receives a discrete message from a message buffer. Messages can be of variable length and are copied out of the buffer. NOTE: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implementation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to be multiple different writers then the application writer must place each call to a writing API function (such as xMessageBufferSend()) inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then the application writer must place each call to a reading API function (such as xMessageBufferRead()) inside a critical section and set the receive block time to 0. Use xMessageBufferReceive() to read from a message buffer from a task. Use xMessageBufferReceiveFromISR() to read from a message buffer from an interrupt service routine (ISR). Example use: // A message buffer that has already been created. MessageBuffer_t xMessageBuffer; void vAnInterruptServiceRoutine( void ) { uint8_t ucRxData[ 20 ]; size_t xReceivedBytes; BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. // Receive the next message from the message buffer. xReceivedBytes = xMessageBufferReceiveFromISR( xMessageBuffer, ( void * ) ucRxData, sizeof( ucRxData ), &xHigherPriorityTaskWoken ); if( xReceivedBytes > 0 ) { // A ucRxData contains a message that is xReceivedBytes long. Process // the message here.... } // If xHigherPriorityTaskWoken was set to pdTRUE inside // xMessageBufferReceiveFromISR() then a task that has a priority above the // priority of the currently executing task was unblocked and a context // switch should be performed to ensure the ISR returns to the unblocked // task. In most FreeRTOS ports this is done by simply passing // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the // variables value, and perform the context switch if necessary. Check the // documentation for the port in use for port specific instructions. portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } - Parameters xMessageBuffer -- The handle of the message buffer from which a message is being received. pvRxData -- A pointer to the buffer into which the received message is to be copied. xBufferLengthBytes -- The length of the buffer pointed to by the pvRxData parameter. This sets the maximum length of the message that can be received. If xBufferLengthBytes is too small to hold the next message then the message will be left in the message buffer and 0 will be returned. pxHigherPriorityTaskWoken -- It is possible that a message buffer will have a task blocked on it waiting for space to become available. Calling xMessageBufferReceiveFromISR() can make space available, and so cause a task that is waiting for space to leave the Blocked state. If calling xMessageBufferReceiveFromISR() causes a task to leave the Blocked state, and the unblocked task has a priority higher than the currently executing task (the task that was interrupted), then, internally, xMessageBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. If xMessageBufferReceiveFromISR() sets this value to pdTRUE, then normally a context switch should be performed before the interrupt is exited. That will ensure the interrupt returns directly to the highest priority Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is passed into the function. See the code example below for an example. - - Returns The length, in bytes, of the message read from the message buffer, if any. - vMessageBufferDelete(xMessageBuffer) Deletes a message buffer that was previously created using a call to xMessageBufferCreate() or xMessageBufferCreateStatic(). If the message buffer was created using dynamic memory (that is, by xMessageBufferCreate()), then the allocated memory is freed. A message buffer handle must not be used after the message buffer has been deleted. - Parameters xMessageBuffer -- The handle of the message buffer to be deleted. - - xMessageBufferIsFull(xMessageBuffer) Tests to see if a message buffer is full. A message buffer is full if it cannot accept any more messages, of any size, until space is made available by a message being removed from the message buffer. - Parameters xMessageBuffer -- The handle of the message buffer being queried. - - Returns If the message buffer referenced by xMessageBuffer is full then pdTRUE is returned. Otherwise pdFALSE is returned. - xMessageBufferIsEmpty(xMessageBuffer) Tests to see if a message buffer is empty (does not contain any messages). - Parameters xMessageBuffer -- The handle of the message buffer being queried. - - Returns If the message buffer referenced by xMessageBuffer is empty then pdTRUE is returned. Otherwise pdFALSE is returned. - xMessageBufferReset(xMessageBuffer) Resets a message buffer to its initial empty state, discarding any message it contained. A message buffer can only be reset if there are no tasks blocked on it. - Parameters xMessageBuffer -- The handle of the message buffer being reset. - - Returns If the message buffer was reset then pdPASS is returned. If the message buffer could not be reset because either there was a task blocked on the message queue to wait for space to become available, or to wait for a a message to be available, then pdFAIL is returned. - xMessageBufferSpaceAvailable(xMessageBuffer) message_buffer.hReturns the number of bytes of free space in the message buffer. size_t xMessageBufferSpaceAvailable( MessageBufferHandle_t xMessageBuffer ); - Parameters xMessageBuffer -- The handle of the message buffer being queried. - - Returns The number of bytes that can be written to the message buffer before the message buffer would be full. When a message is written to the message buffer an additional sizeof( size_t ) bytes are also written to store the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit architecture, so if xMessageBufferSpacesAvailable() returns 10, then the size of the largest message that can be written to the message buffer is 6 bytes. - xMessageBufferSpacesAvailable(xMessageBuffer) - xMessageBufferNextLengthBytes(xMessageBuffer) Returns the length (in bytes) of the next message in a message buffer. Useful if xMessageBufferReceive() returned 0 because the size of the buffer passed into xMessageBufferReceive() was too small to hold the next message. - Parameters xMessageBuffer -- The handle of the message buffer being queried. - - Returns The length (in bytes) of the next message in the message buffer, or 0 if the message buffer is empty. - xMessageBufferSendCompletedFromISR(xMessageBuffer, pxHigherPriorityTaskWoken) For advanced users only. The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when data is sent to a message buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting for data to arrive then the sbSEND_COMPLETED() macro sends a notification to the task to remove it from the Blocked state. xMessageBufferSendCompletedFromISR() does the same thing. It is provided to enable application writers to implement their own version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information. - Parameters xMessageBuffer -- The handle of the stream buffer to which data was written. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xMessageBufferSendCompletedFromISR(). If calling xMessageBufferSendCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. - - Returns If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned. - xMessageBufferReceiveCompletedFromISR(xMessageBuffer, pxHigherPriorityTaskWoken) For advanced users only. The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when data is read out of a message buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting for data to arrive then the sbRECEIVE_COMPLETED() macro sends a notification to the task to remove it from the Blocked state. xMessageBufferReceiveCompletedFromISR() does the same thing. It is provided to enable application writers to implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information. - Parameters xMessageBuffer -- The handle of the stream buffer from which data was read. pxHigherPriorityTaskWoken -- *pxHigherPriorityTaskWoken should be initialised to pdFALSE before it is passed into xMessageBufferReceiveCompletedFromISR(). If calling xMessageBufferReceiveCompletedFromISR() removes a task from the Blocked state, and the task has a priority above the priority of the currently running task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should be performed before exiting the ISR. - - Returns If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned. Type Definitions - typedef StreamBufferHandle_t MessageBufferHandle_t Type by which message buffers are referenced. For example, a call to xMessageBufferCreate() returns an MessageBufferHandle_t variable that can then be used as a parameter to xMessageBufferSend(), xMessageBufferReceive(), etc. Message buffer is essentially built as a stream buffer hence its handle is also set to same type as a stream buffer handle.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/freertos_idf.html
ESP-IDF Programming Guide v5.2.1 documentation
null
FreeRTOS (Supplemental Features)
null
espressif.com
2016-01-01
8893ba47e432b7ba
null
null
FreeRTOS (Supplemental Features) ESP-IDF provides multiple features to supplement the features offered by FreeRTOS. These supplemental features are available on all FreeRTOS implementations supported by ESP-IDF (i.e., ESP-IDF FreeRTOS and Amazon SMP FreeRTOS). This document describes these supplemental features and is split into the following sections: Contents Overview ESP-IDF adds various new features to supplement the capabilities of FreeRTOS as follows: Ring buffers: Ring buffers provide a FIFO buffer that can accept entries of arbitrary lengths. ESP-IDF Tick and Idle Hooks: ESP-IDF provides multiple custom tick interrupt hooks and idle task hooks that are more numerous and more flexible when compared to FreeRTOS tick and idle hooks. Thread Local Storage Pointer (TLSP) Deletion Callbacks: TLSP Deletion callbacks are run automatically when a task is deleted, thus allowing users to clean up their TLSPs automatically. IDF Additional API: ESP-IDF specific functions added to augment the features of FreeRTOS. Component Specific Properties: Currently added only one component specific property ORIG_INCLUDE_PATH . Ring Buffers FreeRTOS provides stream buffers and message buffers as the primary mechanisms to send arbitrarily sized data between tasks and ISRs. However, FreeRTOS stream buffers and message buffers have the following limitations: Strictly single sender and single receiver Data is passed by copy Unable to reserve buffer space for a deferred send (i.e., send acquire) Therefore, ESP-IDF provides a separate ring buffer implementation to address the issues above. ESP-IDF ring buffers are strictly FIFO buffers that supports arbitrarily sized items. Ring buffers are a more memory efficient alternative to FreeRTOS queues in situations where the size of items is variable. The capacity of a ring buffer is not measured by the number of items it can store, but rather by the amount of memory used for storing items. The ring buffer provides APIs to send an item, or to allocate space for an item in the ring buffer to be filled manually by the user. For efficiency reasons, items are always retrieved from the ring buffer by reference. As a result, all retrieved items must also be returned to the ring buffer by using vRingbufferReturnItem() or vRingbufferReturnItemFromISR() , in order for them to be removed from the ring buffer completely. The ring buffers are split into the three following types: No-Split buffers guarantee that an item is stored in contiguous memory and does not attempt to split an item under any circumstances. Use No-Split buffers when items must occupy contiguous memory. Only this buffer type allows reserving buffer space for deferred sending. Refer to the documentation of the functions xRingbufferSendAcquire() and xRingbufferSendComplete() for more details. Allow-Split buffers allow an item to be split in two parts when wrapping around the end of the buffer if there is enough space at the tail and the head of the buffer combined to store the item. Allow-Split buffers are more memory efficient than No-Split buffers but can return an item in two parts when retrieving. Byte buffers do not store data as separate items. All data is stored as a sequence of bytes, and any number of bytes can be sent or retrieved each time. Use byte buffers when separate items do not need to be maintained, e.g., a byte stream. Note No-Split buffers and Allow-Split buffers always store items at 32-bit aligned addresses. Therefore, when retrieving an item, the item pointer is guaranteed to be 32-bit aligned. This is useful especially when you need to send some data to the DMA. Note Each item stored in No-Split or Allow-Split buffers requires an additional 8 bytes for a header. Item sizes are also rounded up to a 32-bit aligned size, i.e., multiple of 4 bytes. However the true item size is recorded within the header. The sizes of No-Split and Allow-Split buffers will also be rounded up when created. Usage The following example demonstrates the usage of xRingbufferCreate() and xRingbufferSend() to create a ring buffer and then send an item to it: #include "freertos/ringbuf.h" static char tx_item[] = "test_item"; ... //Create ring buffer RingbufHandle_t buf_handle; buf_handle = xRingbufferCreate(1028, RINGBUF_TYPE_NOSPLIT); if (buf_handle == NULL) { printf("Failed to create ring buffer\n"); } //Send an item UBaseType_t res = xRingbufferSend(buf_handle, tx_item, sizeof(tx_item), pdMS_TO_TICKS(1000)); if (res != pdTRUE) { printf("Failed to send item\n"); } The following example demonstrates the usage of xRingbufferSendAcquire() and xRingbufferSendComplete() instead of xRingbufferSend() to acquire memory on the ring buffer (of type RINGBUF_TYPE_NOSPLIT ) and then send an item to it. This adds one more step, but allows getting the address of the memory to write to, and writing to the memory yourself. #include "freertos/ringbuf.h" #include "soc/lldesc.h" typedef struct { lldesc_t dma_desc; uint8_t buf[1]; } dma_item_t; #define DMA_ITEM_SIZE(N) (sizeof(lldesc_t)+(((N)+3)&(~3))) ... //Retrieve space for DMA descriptor and corresponding data buffer //This has to be done with SendAcquire, or the address may be different when we copy dma_item_t item; UBaseType_t res = xRingbufferSendAcquire(buf_handle, &item, DMA_ITEM_SIZE(buffer_size), pdMS_TO_TICKS(1000)); if (res != pdTRUE) { printf("Failed to acquire memory for item\n"); } item->dma_desc = (lldesc_t) { .size = buffer_size, .length = buffer_size, .eof = 0, .owner = 1, .buf = &item->buf, }; //Actually send to the ring buffer for consumer to use res = xRingbufferSendComplete(buf_handle, &item); if (res != pdTRUE) { printf("Failed to send item\n"); } The following example demonstrates retrieving and returning an item from a No-Split ring buffer using xRingbufferReceive() and vRingbufferReturnItem() ... //Receive an item from no-split ring buffer size_t item_size; char *item = (char *)xRingbufferReceive(buf_handle, &item_size, pdMS_TO_TICKS(1000)); //Check received item if (item != NULL) { //Print item for (int i = 0; i < item_size; i++) { printf("%c", item[i]); } printf("\n"); //Return Item vRingbufferReturnItem(buf_handle, (void *)item); } else { //Failed to receive item printf("Failed to receive item\n"); } The following example demonstrates retrieving and returning an item from an Allow-Split ring buffer using xRingbufferReceiveSplit() and vRingbufferReturnItem() ... //Receive an item from allow-split ring buffer size_t item_size1, item_size2; char *item1, *item2; BaseType_t ret = xRingbufferReceiveSplit(buf_handle, (void **)&item1, (void **)&item2, &item_size1, &item_size2, pdMS_TO_TICKS(1000)); //Check received item if (ret == pdTRUE && item1 != NULL) { for (int i = 0; i < item_size1; i++) { printf("%c", item1[i]); } vRingbufferReturnItem(buf_handle, (void *)item1); //Check if item was split if (item2 != NULL) { for (int i = 0; i < item_size2; i++) { printf("%c", item2[i]); } vRingbufferReturnItem(buf_handle, (void *)item2); } printf("\n"); } else { //Failed to receive item printf("Failed to receive item\n"); } The following example demonstrates retrieving and returning an item from a byte buffer using xRingbufferReceiveUpTo() and vRingbufferReturnItem() ... //Receive data from byte buffer size_t item_size; char *item = (char *)xRingbufferReceiveUpTo(buf_handle, &item_size, pdMS_TO_TICKS(1000), sizeof(tx_item)); //Check received data if (item != NULL) { //Print item for (int i = 0; i < item_size; i++) { printf("%c", item[i]); } printf("\n"); //Return Item vRingbufferReturnItem(buf_handle, (void *)item); } else { //Failed to receive item printf("Failed to receive item\n"); } For ISR safe versions of the functions used above, call xRingbufferSendFromISR() , xRingbufferReceiveFromISR() , xRingbufferReceiveSplitFromISR() , xRingbufferReceiveUpToFromISR() , and vRingbufferReturnItemFromISR() . Note Two calls to RingbufferReceive[UpTo][FromISR]() are required if the bytes wraps around the end of the ring buffer. Sending to Ring Buffer The following diagrams illustrate the differences between No-Split and Allow-Split buffers as compared to byte buffers with regard to sending items or data. The diagrams assume that three items of sizes 18, 3, and 27 bytes are sent respectively to a buffer of 128 bytes: For No-Split and Allow-Split buffers, a header of 8 bytes precedes every data item. Furthermore, the space occupied by each item is rounded up to the nearest 32-bit aligned size in order to maintain overall 32-bit alignment. However, the true size of the item is recorded inside the header which will be returned when the item is retrieved. Referring to the diagram above, the 18, 3, and 27 byte items are rounded up to 20, 4, and 28 bytes respectively. An 8 byte header is then added in front of each item. Byte buffers treat data as a sequence of bytes and does not incur any overhead (no headers). As a result, all data sent to a byte buffer is merged into a single item. Referring to the diagram above, the 18, 3, and 27 byte items are sequentially written to the byte buffer and merged into a single item of 48 bytes. Using SendAcquire and SendComplete Items in No-Split buffers are acquired (by SendAcquire ) in strict FIFO order and must be sent to the buffer by SendComplete for the data to be accessible by the consumer. Multiple items can be sent or acquired without calling SendComplete , and the items do not necessarily need to be completed in the order they were acquired. However, the receiving of data items must occur in FIFO order, therefore not calling SendComplete for the earliest acquired item prevents the subsequent items from being received. The following diagrams illustrate what will happen when SendAcquire and SendComplete do not happen in the same order. At the beginning, there is already a data item of 16 bytes sent to the ring buffer. Then SendAcquire is called to acquire space of 20, 8, 24 bytes on the ring buffer. After that, we fill (use) the buffers, and send them to the ring buffer by SendComplete in the order of 8, 24, 20. When 8 bytes and 24 bytes data are sent, the consumer still can only get the 16 bytes data item. Hence, if SendComplete is not called for the 20 bytes, it will not be available, nor will the data items following the 20 bytes item. When the 20 bytes item is finally completed, all the 3 data items can be received now, in the order of 20, 8, 24 bytes, right after the 16 bytes item existing in the buffer at the beginning. Allow-Split buffers and byte buffers do not allow using SendAcquire or SendComplete since acquired buffers are required to be complete (not wrapped). Wrap Around The following diagrams illustrate the differences between No-Split, Allow-Split, and byte buffers when a sent item requires a wrap around. The diagrams assume a buffer of 128 bytes with 56 bytes of free space that wraps around and a sent item of 28 bytes. No-Split buffers only store an item in continuous free space and do not split an item under any circumstances. When the free space at the tail of the buffer is insufficient to completely store the item and its header, the free space at the tail will be marked as dummy data. The buffer will then wrap around and store the item in the free space at the head of the buffer. Referring to the diagram above, the 16 bytes of free space at the tail of the buffer is insufficient to store the 28 byte item. Therefore, the 16 bytes is marked as dummy data and the item is written to the free space at the head of the buffer instead. Allow-Split buffers will attempt to split the item into two parts when the free space at the tail of the buffer is insufficient to store the item data and its header. Both parts of the split item will have their own headers, therefore incurring an extra 8 bytes of overhead. Referring to the diagram above, the 16 bytes of free space at the tail of the buffer is insufficient to store the 28 byte item. Therefore, the item is split into two parts (8 and 20 bytes) and written as two parts to the buffer. Note Allow-Split buffers treat both parts of the split item as two separate items, therefore call xRingbufferReceiveSplit() instead of xRingbufferReceive() to receive both parts of a split item in a thread safe manner. Byte buffers store as much data as possible into the free space at the tail of buffer. The remaining data will then be stored in the free space at the head of the buffer. No overhead is incurred when wrapping around in byte buffers. Referring to the diagram above, the 16 bytes of free space at the tail of the buffer is insufficient to completely store the 28 bytes of data. Therefore, the 16 bytes of free space is filled with data, and the remaining 12 bytes are written to the free space at the head of the buffer. The buffer now contains data in two separate continuous parts, and each continuous part is treated as a separate item by the byte buffer. Retrieving/Returning The following diagrams illustrate the differences between No-Split and Allow-Split buffers as compared to byte buffers in retrieving and returning data: Items in No-Split buffers and Allow-Split buffers are retrieved in strict FIFO order and must be returned for the occupied space to be freed. Multiple items can be retrieved before returning, and the items do not necessarily need to be returned in the order they were retrieved. However, the freeing of space must occur in FIFO order, therefore not returning the earliest retrieved item prevents the space of subsequent items from being freed. Referring to the diagram above, the 16, 20, and 8 byte items are retrieved in FIFO order. However, the items are not returned in the order they were retrieved. First, the 20 byte item is returned followed by the 8 byte and the 16 byte items. The space is not freed until the first item, i.e., the 16 byte item is returned. Byte buffers do not allow multiple retrievals before returning (every retrieval must be followed by a return before another retrieval is permitted). When using xRingbufferReceive() or xRingbufferReceiveFromISR() , all continuous stored data will be retrieved. xRingbufferReceiveUpTo() or xRingbufferReceiveUpToFromISR() can be used to restrict the maximum number of bytes retrieved. Since every retrieval must be followed by a return, the space is freed as soon as the data is returned. Referring to the diagram above, the 38 bytes of continuous stored data at the tail of the buffer is retrieved, returned, and freed. The next call to xRingbufferReceive() or xRingbufferReceiveFromISR() then wraps around and does the same to the 30 bytes of continuous stored data at the head of the buffer. Ring Buffers with Queue Sets Ring buffers can be added to FreeRTOS queue sets using xRingbufferAddToQueueSetRead() such that every time a ring buffer receives an item or data, the queue set is notified. Once added to a queue set, every attempt to retrieve an item from a ring buffer should be preceded by a call to xQueueSelectFromSet() . To check whether the selected queue set member is the ring buffer, call xRingbufferCanRead() . The following example demonstrates queue set usage with ring buffers: #include "freertos/queue.h" #include "freertos/ringbuf.h" ... //Create ring buffer and queue set RingbufHandle_t buf_handle = xRingbufferCreate(1028, RINGBUF_TYPE_NOSPLIT); QueueSetHandle_t queue_set = xQueueCreateSet(3); //Add ring buffer to queue set if (xRingbufferAddToQueueSetRead(buf_handle, queue_set) != pdTRUE) { printf("Failed to add to queue set\n"); } ... //Block on queue set QueueSetMemberHandle_t member = xQueueSelectFromSet(queue_set, pdMS_TO_TICKS(1000)); //Check if member is ring buffer if (member != NULL && xRingbufferCanRead(buf_handle, member) == pdTRUE) { //Member is ring buffer, receive item from ring buffer size_t item_size; char *item = (char *)xRingbufferReceive(buf_handle, &item_size, 0); //Handle item ... } else { ... } Ring Buffers with Static Allocation The xRingbufferCreateStatic() can be used to create ring buffers with specific memory requirements (such as a ring buffer being allocated in external RAM). All blocks of memory used by a ring buffer must be manually allocated beforehand, then passed to the xRingbufferCreateStatic() to be initialized as a ring buffer. These blocks include the following: The ring buffer's data structure of type StaticRingbuffer_t . The ring buffer's storage area of size xBufferSize . Note that xBufferSize must be 32-bit aligned for No-Split and Allow-Split buffers. The manner in which these blocks are allocated depends on the users requirements (e.g., all blocks being statically declared, or dynamically allocated with specific capabilities such as external RAM). Note When deleting a ring buffer created via xRingbufferCreateStatic() , the function vRingbufferDelete() will not free any of the memory blocks. This must be done manually by the user after vRingbufferDelete() is called. The code snippet below demonstrates a ring buffer being allocated entirely in external RAM. #include "freertos/ringbuf.h" #include "freertos/semphr.h" #include "esp_heap_caps.h" #define BUFFER_SIZE 400 //32-bit aligned size #define BUFFER_TYPE RINGBUF_TYPE_NOSPLIT ... //Allocate ring buffer data structure and storage area into external RAM StaticRingbuffer_t *buffer_struct = (StaticRingbuffer_t *)heap_caps_malloc(sizeof(StaticRingbuffer_t), MALLOC_CAP_SPIRAM); uint8_t *buffer_storage = (uint8_t *)heap_caps_malloc(sizeof(uint8_t)*BUFFER_SIZE, MALLOC_CAP_SPIRAM); //Create a ring buffer with manually allocated memory RingbufHandle_t handle = xRingbufferCreateStatic(BUFFER_SIZE, BUFFER_TYPE, buffer_storage, buffer_struct); ... //Delete the ring buffer after used vRingbufferDelete(handle); //Manually free all blocks of memory free(buffer_struct); free(buffer_storage); ESP-IDF Tick and Idle Hooks FreeRTOS allows applications to provide a tick hook and an idle hook at compile time: FreeRTOS tick hook can be enabled via the CONFIG_FREERTOS_USE_TICK_HOOK option. The application must provide the void vApplicationTickHook( void ) callback. FreeRTOS idle hook can be enabled via the CONFIG_FREERTOS_USE_IDLE_HOOK option. The application must provide the void vApplicationIdleHook( void ) callback. However, the FreeRTOS tick hook and idle hook have the following draw backs: The FreeRTOS hooks are registered at compile time Only one of each hook can be registered On multi-core targets, the FreeRTOS hooks are symmetric, meaning each core's tick interrupt and idle tasks ends up calling the same hook Therefore, ESP-IDF tick and idle hooks are provided to supplement the features of FreeRTOS tick and idle hooks. The ESP-IDF hooks have the following features: The hooks can be registered and deregistered at run-time Multiple hooks can be registered (with a maximum of 8 hooks of each type per core) On multi-core targets, the hooks can be asymmetric, meaning different hooks can be registered to each core ESP-IDF hooks can be registered and deregistered using the following APIs: For tick hooks: Register using esp_register_freertos_tick_hook() or esp_register_freertos_tick_hook_for_cpu() Deregister using esp_deregister_freertos_tick_hook() or esp_deregister_freertos_tick_hook_for_cpu() Register using esp_register_freertos_tick_hook() or esp_register_freertos_tick_hook_for_cpu() Deregister using esp_deregister_freertos_tick_hook() or esp_deregister_freertos_tick_hook_for_cpu() Register using esp_register_freertos_tick_hook() or esp_register_freertos_tick_hook_for_cpu() For idle hooks: Register using esp_register_freertos_idle_hook() or esp_register_freertos_idle_hook_for_cpu() Deregister using esp_deregister_freertos_idle_hook() or esp_deregister_freertos_idle_hook_for_cpu() Register using esp_register_freertos_idle_hook() or esp_register_freertos_idle_hook_for_cpu() Deregister using esp_deregister_freertos_idle_hook() or esp_deregister_freertos_idle_hook_for_cpu() Register using esp_register_freertos_idle_hook() or esp_register_freertos_idle_hook_for_cpu() Note The tick interrupt stays active while the cache is disabled, therefore any tick hook (FreeRTOS or ESP-IDF) functions must be placed in internal RAM. Please refer to the SPI flash API documentation for more details. TLSP Deletion Callbacks Vanilla FreeRTOS provides a Thread Local Storage Pointers (TLSP) feature. These are pointers stored directly in the Task Control Block (TCB) of a particular task. TLSPs allow each task to have its own unique set of pointers to data structures. Vanilla FreeRTOS expects users to: set a task's TLSPs by calling vTaskSetThreadLocalStoragePointer() after the task has been created. get a task's TLSPs by calling pvTaskGetThreadLocalStoragePointer() during the task's lifetime. free the memory pointed to by the TLSPs before the task is deleted. However, there can be instances where users may want the freeing of TLSP memory to be automatic. Therefore, ESP-IDF provides the additional feature of TLSP deletion callbacks. These user-provided deletion callbacks are called automatically when a task is deleted, thus allowing the TLSP memory to be cleaned up without needing to add the cleanup logic explicitly to the code of every task. The TLSP deletion callbacks are set in a similar fashion to the TLSPs themselves. vTaskSetThreadLocalStoragePointerAndDelCallback() sets both a particular TLSP and its associated callback. Calling the Vanilla FreeRTOS function vTaskSetThreadLocalStoragePointer() simply sets the TLSP's associated Deletion Callback to NULL, meaning that no callback is called for that TLSP during task deletion. When implementing TLSP callbacks, users should note the following: The callback must never attempt to block or yield and critical sections should be kept as short as possible. The callback is called shortly before a deleted task's memory is freed. Thus, the callback can either be called from vTaskDelete() itself, or from the idle task. IDF Additional API The freertos/esp_additions/include/freertos/idf_additions.h header contains FreeRTOS-related helper functions added by ESP-IDF. Users can include this header via #include "freertos/idf_additions.h" . Component Specific Properties Besides standard component variables that are available with basic cmake build properties, FreeRTOS component also provides arguments (only one so far) for simpler integration with other modules: ORIG_INCLUDE_PATH - contains an absolute path to freertos root include folder. Thus instead of #include "freertos/FreeRTOS.h" you can refer to headers directly: #include "FreeRTOS.h". API Reference Ring Buffer API Header File This header file can be included with: #include "freertos/ringbuf.h" This header file is a part of the API provided by the esp_ringbuf component. To declare that your component depends on esp_ringbuf , add the following to your CMakeLists.txt: REQUIRES esp_ringbuf or PRIV_REQUIRES esp_ringbuf Functions RingbufHandle_t xRingbufferCreate(size_t xBufferSize, RingbufferType_t xBufferType) Create a ring buffer. Note xBufferSize of no-split/allow-split buffers will be rounded up to the nearest 32-bit aligned size. Parameters xBufferSize -- [in] Size of the buffer in bytes. Note that items require space for a header in no-split/allow-split buffers xBufferType -- [in] Type of ring buffer, see documentation. xBufferSize -- [in] Size of the buffer in bytes. Note that items require space for a header in no-split/allow-split buffers xBufferType -- [in] Type of ring buffer, see documentation. xBufferSize -- [in] Size of the buffer in bytes. Note that items require space for a header in no-split/allow-split buffers Returns A handle to the created ring buffer, or NULL in case of error. Parameters xBufferSize -- [in] Size of the buffer in bytes. Note that items require space for a header in no-split/allow-split buffers xBufferType -- [in] Type of ring buffer, see documentation. Returns A handle to the created ring buffer, or NULL in case of error. RingbufHandle_t xRingbufferCreateNoSplit(size_t xItemSize, size_t xItemNum) Create a ring buffer of type RINGBUF_TYPE_NOSPLIT for a fixed item_size. This API is similar to xRingbufferCreate(), but it will internally allocate additional space for the headers. Parameters xItemSize -- [in] Size of each item to be put into the ring buffer xItemNum -- [in] Maximum number of items the buffer needs to hold simultaneously xItemSize -- [in] Size of each item to be put into the ring buffer xItemNum -- [in] Maximum number of items the buffer needs to hold simultaneously xItemSize -- [in] Size of each item to be put into the ring buffer Returns A RingbufHandle_t handle to the created ring buffer, or NULL in case of error. Parameters xItemSize -- [in] Size of each item to be put into the ring buffer xItemNum -- [in] Maximum number of items the buffer needs to hold simultaneously Returns A RingbufHandle_t handle to the created ring buffer, or NULL in case of error. RingbufHandle_t xRingbufferCreateStatic(size_t xBufferSize, RingbufferType_t xBufferType, uint8_t *pucRingbufferStorage, StaticRingbuffer_t *pxStaticRingbuffer) Create a ring buffer but manually provide the required memory. Note xBufferSize of no-split/allow-split buffers MUST be 32-bit aligned. Parameters xBufferSize -- [in] Size of the buffer in bytes. xBufferType -- [in] Type of ring buffer, see documentation pucRingbufferStorage -- [in] Pointer to the ring buffer's storage area. Storage area must have the same size as specified by xBufferSize pxStaticRingbuffer -- [in] Pointed to a struct of type StaticRingbuffer_t which will be used to hold the ring buffer's data structure xBufferSize -- [in] Size of the buffer in bytes. xBufferType -- [in] Type of ring buffer, see documentation pucRingbufferStorage -- [in] Pointer to the ring buffer's storage area. Storage area must have the same size as specified by xBufferSize pxStaticRingbuffer -- [in] Pointed to a struct of type StaticRingbuffer_t which will be used to hold the ring buffer's data structure xBufferSize -- [in] Size of the buffer in bytes. Returns A handle to the created ring buffer Parameters xBufferSize -- [in] Size of the buffer in bytes. xBufferType -- [in] Type of ring buffer, see documentation pucRingbufferStorage -- [in] Pointer to the ring buffer's storage area. Storage area must have the same size as specified by xBufferSize pxStaticRingbuffer -- [in] Pointed to a struct of type StaticRingbuffer_t which will be used to hold the ring buffer's data structure Returns A handle to the created ring buffer BaseType_t xRingbufferSend(RingbufHandle_t xRingbuffer, const void *pvItem, size_t xItemSize, TickType_t xTicksToWait) Insert an item into the ring buffer. Attempt to insert an item into the ring buffer. This function will block until enough free space is available or until it times out. Note For no-split/allow-split ring buffers, the actual size of memory that the item will occupy will be rounded up to the nearest 32-bit aligned size. This is done to ensure all items are always stored in 32-bit aligned fashion. Note For no-split/allow-split buffers, an xItemSize of 0 will result in an item with no data being set (i.e., item only contains the header). For byte buffers, an xItemSize of 0 will simply return pdTRUE without copying any data. Parameters xRingbuffer -- [in] Ring buffer to insert the item into pvItem -- [in] Pointer to data to insert. NULL is allowed if xItemSize is 0. xItemSize -- [in] Size of data to insert. xTicksToWait -- [in] Ticks to wait for room in the ring buffer. xRingbuffer -- [in] Ring buffer to insert the item into pvItem -- [in] Pointer to data to insert. NULL is allowed if xItemSize is 0. xItemSize -- [in] Size of data to insert. xTicksToWait -- [in] Ticks to wait for room in the ring buffer. xRingbuffer -- [in] Ring buffer to insert the item into Returns pdTRUE if succeeded pdFALSE on time-out or when the data is larger than the maximum permissible size of the buffer pdTRUE if succeeded pdFALSE on time-out or when the data is larger than the maximum permissible size of the buffer pdTRUE if succeeded Parameters xRingbuffer -- [in] Ring buffer to insert the item into pvItem -- [in] Pointer to data to insert. NULL is allowed if xItemSize is 0. xItemSize -- [in] Size of data to insert. xTicksToWait -- [in] Ticks to wait for room in the ring buffer. Returns pdTRUE if succeeded pdFALSE on time-out or when the data is larger than the maximum permissible size of the buffer BaseType_t xRingbufferSendFromISR(RingbufHandle_t xRingbuffer, const void *pvItem, size_t xItemSize, BaseType_t *pxHigherPriorityTaskWoken) Insert an item into the ring buffer in an ISR. Attempt to insert an item into the ring buffer from an ISR. This function will return immediately if there is insufficient free space in the buffer. Note For no-split/allow-split ring buffers, the actual size of memory that the item will occupy will be rounded up to the nearest 32-bit aligned size. This is done to ensure all items are always stored in 32-bit aligned fashion. Note For no-split/allow-split buffers, an xItemSize of 0 will result in an item with no data being set (i.e., item only contains the header). For byte buffers, an xItemSize of 0 will simply return pdTRUE without copying any data. Parameters xRingbuffer -- [in] Ring buffer to insert the item into pvItem -- [in] Pointer to data to insert. NULL is allowed if xItemSize is 0. xItemSize -- [in] Size of data to insert. pxHigherPriorityTaskWoken -- [out] Value pointed to will be set to pdTRUE if the function woke up a higher priority task. xRingbuffer -- [in] Ring buffer to insert the item into pvItem -- [in] Pointer to data to insert. NULL is allowed if xItemSize is 0. xItemSize -- [in] Size of data to insert. pxHigherPriorityTaskWoken -- [out] Value pointed to will be set to pdTRUE if the function woke up a higher priority task. xRingbuffer -- [in] Ring buffer to insert the item into Returns pdTRUE if succeeded pdFALSE when the ring buffer does not have space. pdTRUE if succeeded pdFALSE when the ring buffer does not have space. pdTRUE if succeeded Parameters xRingbuffer -- [in] Ring buffer to insert the item into pvItem -- [in] Pointer to data to insert. NULL is allowed if xItemSize is 0. xItemSize -- [in] Size of data to insert. pxHigherPriorityTaskWoken -- [out] Value pointed to will be set to pdTRUE if the function woke up a higher priority task. Returns pdTRUE if succeeded pdFALSE when the ring buffer does not have space. BaseType_t xRingbufferSendAcquire(RingbufHandle_t xRingbuffer, void **ppvItem, size_t xItemSize, TickType_t xTicksToWait) Acquire memory from the ring buffer to be written to by an external source and to be sent later. Attempt to allocate buffer for an item to be sent into the ring buffer. This function will block until enough free space is available or until it times out. The item, as well as the following items SendAcquire or Send after it, will not be able to be read from the ring buffer until this item is actually sent into the ring buffer. Note Only applicable for no-split ring buffers now, the actual size of memory that the item will occupy will be rounded up to the nearest 32-bit aligned size. This is done to ensure all items are always stored in 32-bit aligned fashion. Note An xItemSize of 0 will result in a buffer being acquired, but the buffer will have a size of 0. Parameters xRingbuffer -- [in] Ring buffer to allocate the memory ppvItem -- [out] Double pointer to memory acquired (set to NULL if no memory were retrieved) xItemSize -- [in] Size of item to acquire. xTicksToWait -- [in] Ticks to wait for room in the ring buffer. xRingbuffer -- [in] Ring buffer to allocate the memory ppvItem -- [out] Double pointer to memory acquired (set to NULL if no memory were retrieved) xItemSize -- [in] Size of item to acquire. xTicksToWait -- [in] Ticks to wait for room in the ring buffer. xRingbuffer -- [in] Ring buffer to allocate the memory Returns pdTRUE if succeeded pdFALSE on time-out or when the data is larger than the maximum permissible size of the buffer pdTRUE if succeeded pdFALSE on time-out or when the data is larger than the maximum permissible size of the buffer pdTRUE if succeeded Parameters xRingbuffer -- [in] Ring buffer to allocate the memory ppvItem -- [out] Double pointer to memory acquired (set to NULL if no memory were retrieved) xItemSize -- [in] Size of item to acquire. xTicksToWait -- [in] Ticks to wait for room in the ring buffer. Returns pdTRUE if succeeded pdFALSE on time-out or when the data is larger than the maximum permissible size of the buffer BaseType_t xRingbufferSendComplete(RingbufHandle_t xRingbuffer, void *pvItem) Actually send an item into the ring buffer allocated before by xRingbufferSendAcquire . Note Only applicable for no-split ring buffers. Only call for items allocated by xRingbufferSendAcquire . Parameters xRingbuffer -- [in] Ring buffer to insert the item into pvItem -- [in] Pointer to item in allocated memory to insert. xRingbuffer -- [in] Ring buffer to insert the item into pvItem -- [in] Pointer to item in allocated memory to insert. xRingbuffer -- [in] Ring buffer to insert the item into Returns pdTRUE if succeeded pdFALSE if fail for some reason. pdTRUE if succeeded pdFALSE if fail for some reason. pdTRUE if succeeded Parameters xRingbuffer -- [in] Ring buffer to insert the item into pvItem -- [in] Pointer to item in allocated memory to insert. Returns pdTRUE if succeeded pdFALSE if fail for some reason. void *xRingbufferReceive(RingbufHandle_t xRingbuffer, size_t *pxItemSize, TickType_t xTicksToWait) Retrieve an item from the ring buffer. Attempt to retrieve an item from the ring buffer. This function will block until an item is available or until it times out. Note A call to vRingbufferReturnItem() is required after this to free the item retrieved. Note It is possible to receive items with a pxItemSize of 0 on no-split/allow split buffers. Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. xTicksToWait -- [in] Ticks to wait for items in the ring buffer. xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. xTicksToWait -- [in] Ticks to wait for items in the ring buffer. xRingbuffer -- [in] Ring buffer to retrieve the item from Returns Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL on timeout, *pxItemSize is untouched in that case. Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL on timeout, *pxItemSize is untouched in that case. Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. xTicksToWait -- [in] Ticks to wait for items in the ring buffer. Returns Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL on timeout, *pxItemSize is untouched in that case. void *xRingbufferReceiveFromISR(RingbufHandle_t xRingbuffer, size_t *pxItemSize) Retrieve an item from the ring buffer in an ISR. Attempt to retrieve an item from the ring buffer. This function returns immediately if there are no items available for retrieval Note A call to vRingbufferReturnItemFromISR() is required after this to free the item retrieved. Note Byte buffers do not allow multiple retrievals before returning an item Note Two calls to RingbufferReceiveFromISR() are required if the bytes wrap around the end of the ring buffer. Note It is possible to receive items with a pxItemSize of 0 on no-split/allow split buffers. Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. xRingbuffer -- [in] Ring buffer to retrieve the item from Returns Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL when the ring buffer is empty, *pxItemSize is untouched in that case. Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL when the ring buffer is empty, *pxItemSize is untouched in that case. Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. Returns Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL when the ring buffer is empty, *pxItemSize is untouched in that case. BaseType_t xRingbufferReceiveSplit(RingbufHandle_t xRingbuffer, void **ppvHeadItem, void **ppvTailItem, size_t *pxHeadItemSize, size_t *pxTailItemSize, TickType_t xTicksToWait) Retrieve a split item from an allow-split ring buffer. Attempt to retrieve a split item from an allow-split ring buffer. If the item is not split, only a single item is retried. If the item is split, both parts will be retrieved. This function will block until an item is available or until it times out. Note Call(s) to vRingbufferReturnItem() is required after this to free up the item(s) retrieved. Note This function should only be called on allow-split buffers Note It is possible to receive items with a pxItemSize of 0 on allow split buffers. Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from ppvHeadItem -- [out] Double pointer to first part (set to NULL if no items were retrieved) ppvTailItem -- [out] Double pointer to second part (set to NULL if item is not split) pxHeadItemSize -- [out] Pointer to size of first part (unmodified if no items were retrieved) pxTailItemSize -- [out] Pointer to size of second part (unmodified if item is not split) xTicksToWait -- [in] Ticks to wait for items in the ring buffer. xRingbuffer -- [in] Ring buffer to retrieve the item from ppvHeadItem -- [out] Double pointer to first part (set to NULL if no items were retrieved) ppvTailItem -- [out] Double pointer to second part (set to NULL if item is not split) pxHeadItemSize -- [out] Pointer to size of first part (unmodified if no items were retrieved) pxTailItemSize -- [out] Pointer to size of second part (unmodified if item is not split) xTicksToWait -- [in] Ticks to wait for items in the ring buffer. xRingbuffer -- [in] Ring buffer to retrieve the item from Returns pdTRUE if an item (split or unsplit) was retrieved pdFALSE when no item was retrieved pdTRUE if an item (split or unsplit) was retrieved pdFALSE when no item was retrieved pdTRUE if an item (split or unsplit) was retrieved Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from ppvHeadItem -- [out] Double pointer to first part (set to NULL if no items were retrieved) ppvTailItem -- [out] Double pointer to second part (set to NULL if item is not split) pxHeadItemSize -- [out] Pointer to size of first part (unmodified if no items were retrieved) pxTailItemSize -- [out] Pointer to size of second part (unmodified if item is not split) xTicksToWait -- [in] Ticks to wait for items in the ring buffer. Returns pdTRUE if an item (split or unsplit) was retrieved pdFALSE when no item was retrieved BaseType_t xRingbufferReceiveSplitFromISR(RingbufHandle_t xRingbuffer, void **ppvHeadItem, void **ppvTailItem, size_t *pxHeadItemSize, size_t *pxTailItemSize) Retrieve a split item from an allow-split ring buffer in an ISR. Attempt to retrieve a split item from an allow-split ring buffer. If the item is not split, only a single item is retried. If the item is split, both parts will be retrieved. This function returns immediately if there are no items available for retrieval Note Calls to vRingbufferReturnItemFromISR() is required after this to free up the item(s) retrieved. Note This function should only be called on allow-split buffers Note It is possible to receive items with a pxItemSize of 0 on allow split buffers. Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from ppvHeadItem -- [out] Double pointer to first part (set to NULL if no items were retrieved) ppvTailItem -- [out] Double pointer to second part (set to NULL if item is not split) pxHeadItemSize -- [out] Pointer to size of first part (unmodified if no items were retrieved) pxTailItemSize -- [out] Pointer to size of second part (unmodified if item is not split) xRingbuffer -- [in] Ring buffer to retrieve the item from ppvHeadItem -- [out] Double pointer to first part (set to NULL if no items were retrieved) ppvTailItem -- [out] Double pointer to second part (set to NULL if item is not split) pxHeadItemSize -- [out] Pointer to size of first part (unmodified if no items were retrieved) pxTailItemSize -- [out] Pointer to size of second part (unmodified if item is not split) xRingbuffer -- [in] Ring buffer to retrieve the item from Returns pdTRUE if an item (split or unsplit) was retrieved pdFALSE when no item was retrieved pdTRUE if an item (split or unsplit) was retrieved pdFALSE when no item was retrieved pdTRUE if an item (split or unsplit) was retrieved Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from ppvHeadItem -- [out] Double pointer to first part (set to NULL if no items were retrieved) ppvTailItem -- [out] Double pointer to second part (set to NULL if item is not split) pxHeadItemSize -- [out] Pointer to size of first part (unmodified if no items were retrieved) pxTailItemSize -- [out] Pointer to size of second part (unmodified if item is not split) Returns pdTRUE if an item (split or unsplit) was retrieved pdFALSE when no item was retrieved void *xRingbufferReceiveUpTo(RingbufHandle_t xRingbuffer, size_t *pxItemSize, TickType_t xTicksToWait, size_t xMaxSize) Retrieve bytes from a byte buffer, specifying the maximum amount of bytes to retrieve. Attempt to retrieve data from a byte buffer whilst specifying a maximum number of bytes to retrieve. This function will block until there is data available for retrieval or until it times out. Note A call to vRingbufferReturnItem() is required after this to free up the data retrieved. Note This function should only be called on byte buffers Note Byte buffers do not allow multiple retrievals before returning an item Note Two calls to RingbufferReceiveUpTo() are required if the bytes wrap around the end of the ring buffer. Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. xTicksToWait -- [in] Ticks to wait for items in the ring buffer. xMaxSize -- [in] Maximum number of bytes to return. xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. xTicksToWait -- [in] Ticks to wait for items in the ring buffer. xMaxSize -- [in] Maximum number of bytes to return. xRingbuffer -- [in] Ring buffer to retrieve the item from Returns Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL on timeout, *pxItemSize is untouched in that case. Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL on timeout, *pxItemSize is untouched in that case. Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. xTicksToWait -- [in] Ticks to wait for items in the ring buffer. xMaxSize -- [in] Maximum number of bytes to return. Returns Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL on timeout, *pxItemSize is untouched in that case. void *xRingbufferReceiveUpToFromISR(RingbufHandle_t xRingbuffer, size_t *pxItemSize, size_t xMaxSize) Retrieve bytes from a byte buffer, specifying the maximum amount of bytes to retrieve. Call this from an ISR. Attempt to retrieve bytes from a byte buffer whilst specifying a maximum number of bytes to retrieve. This function will return immediately if there is no data available for retrieval. Note A call to vRingbufferReturnItemFromISR() is required after this to free up the data received. Note This function should only be called on byte buffers Note Byte buffers do not allow multiple retrievals before returning an item Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. xMaxSize -- [in] Maximum number of bytes to return. Size of 0 simply returns NULL. xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. xMaxSize -- [in] Maximum number of bytes to return. Size of 0 simply returns NULL. xRingbuffer -- [in] Ring buffer to retrieve the item from Returns Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL when the ring buffer is empty, *pxItemSize is untouched in that case. Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL when the ring buffer is empty, *pxItemSize is untouched in that case. Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. xMaxSize -- [in] Maximum number of bytes to return. Size of 0 simply returns NULL. Returns Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL when the ring buffer is empty, *pxItemSize is untouched in that case. void vRingbufferReturnItem(RingbufHandle_t xRingbuffer, void *pvItem) Return a previously-retrieved item to the ring buffer. Note If a split item is retrieved, both parts should be returned by calling this function twice Parameters xRingbuffer -- [in] Ring buffer the item was retrieved from pvItem -- [in] Item that was received earlier xRingbuffer -- [in] Ring buffer the item was retrieved from pvItem -- [in] Item that was received earlier xRingbuffer -- [in] Ring buffer the item was retrieved from Parameters xRingbuffer -- [in] Ring buffer the item was retrieved from pvItem -- [in] Item that was received earlier void vRingbufferReturnItemFromISR(RingbufHandle_t xRingbuffer, void *pvItem, BaseType_t *pxHigherPriorityTaskWoken) Return a previously-retrieved item to the ring buffer from an ISR. Note If a split item is retrieved, both parts should be returned by calling this function twice Parameters xRingbuffer -- [in] Ring buffer the item was retrieved from pvItem -- [in] Item that was received earlier pxHigherPriorityTaskWoken -- [out] Value pointed to will be set to pdTRUE if the function woke up a higher priority task. xRingbuffer -- [in] Ring buffer the item was retrieved from pvItem -- [in] Item that was received earlier pxHigherPriorityTaskWoken -- [out] Value pointed to will be set to pdTRUE if the function woke up a higher priority task. xRingbuffer -- [in] Ring buffer the item was retrieved from Parameters xRingbuffer -- [in] Ring buffer the item was retrieved from pvItem -- [in] Item that was received earlier pxHigherPriorityTaskWoken -- [out] Value pointed to will be set to pdTRUE if the function woke up a higher priority task. void vRingbufferDelete(RingbufHandle_t xRingbuffer) Delete a ring buffer. Note This function will not deallocate any memory if the ring buffer was created using xRingbufferCreateStatic(). Deallocation must be done manually be the user. Parameters xRingbuffer -- [in] Ring buffer to delete Parameters xRingbuffer -- [in] Ring buffer to delete size_t xRingbufferGetMaxItemSize(RingbufHandle_t xRingbuffer) Get maximum size of an item that can be placed in the ring buffer. This function returns the maximum size an item can have if it was placed in an empty ring buffer. Note The max item size for a no-split buffer is limited to ((buffer_size/2)-header_size). This limit is imposed so that an item of max item size can always be sent to an empty no-split buffer regardless of the internal positions of the buffer's read/write/free pointers. Parameters xRingbuffer -- [in] Ring buffer to query Returns Maximum size, in bytes, of an item that can be placed in a ring buffer. Parameters xRingbuffer -- [in] Ring buffer to query Returns Maximum size, in bytes, of an item that can be placed in a ring buffer. size_t xRingbufferGetCurFreeSize(RingbufHandle_t xRingbuffer) Get current free size available for an item/data in the buffer. This gives the real time free space available for an item/data in the ring buffer. This represents the maximum size an item/data can have if it was currently sent to the ring buffer. Note An empty no-split buffer has a max current free size for an item that is limited to ((buffer_size/2)-header_size). See API reference for xRingbufferGetMaxItemSize(). Warning This API is not thread safe. So, if multiple threads are accessing the same ring buffer, it is the application's responsibility to ensure atomic access to this API and the subsequent Send Parameters xRingbuffer -- [in] Ring buffer to query Returns Current free size, in bytes, available for an entry Parameters xRingbuffer -- [in] Ring buffer to query Returns Current free size, in bytes, available for an entry BaseType_t xRingbufferAddToQueueSetRead(RingbufHandle_t xRingbuffer, QueueSetHandle_t xQueueSet) Add the ring buffer to a queue set. Notified when data has been written to the ring buffer. This function adds the ring buffer to a queue set, thus allowing a task to block on multiple queues/ring buffers. The queue set is notified when the new data becomes available to read on the ring buffer. Parameters xRingbuffer -- [in] Ring buffer to add to the queue set xQueueSet -- [in] Queue set to add the ring buffer to xRingbuffer -- [in] Ring buffer to add to the queue set xQueueSet -- [in] Queue set to add the ring buffer to xRingbuffer -- [in] Ring buffer to add to the queue set Returns pdTRUE on success, pdFALSE otherwise pdTRUE on success, pdFALSE otherwise pdTRUE on success, pdFALSE otherwise Parameters xRingbuffer -- [in] Ring buffer to add to the queue set xQueueSet -- [in] Queue set to add the ring buffer to Returns pdTRUE on success, pdFALSE otherwise static inline BaseType_t xRingbufferCanRead(RingbufHandle_t xRingbuffer, QueueSetMemberHandle_t xMember) Check if the selected queue set member is a particular ring buffer. This API checks if queue set member returned from xQueueSelectFromSet() is a particular ring buffer. If so, this indicates the ring buffer has items waiting to be retrieved. Parameters xRingbuffer -- [in] Ring buffer to check xMember -- [in] Member returned from xQueueSelectFromSet xRingbuffer -- [in] Ring buffer to check xMember -- [in] Member returned from xQueueSelectFromSet xRingbuffer -- [in] Ring buffer to check Returns pdTRUE when selected queue set member is the ring buffer pdFALSE otherwise. pdTRUE when selected queue set member is the ring buffer pdFALSE otherwise. pdTRUE when selected queue set member is the ring buffer Parameters xRingbuffer -- [in] Ring buffer to check xMember -- [in] Member returned from xQueueSelectFromSet Returns pdTRUE when selected queue set member is the ring buffer pdFALSE otherwise. BaseType_t xRingbufferRemoveFromQueueSetRead(RingbufHandle_t xRingbuffer, QueueSetHandle_t xQueueSet) Remove the ring buffer from a queue set. This function removes a ring buffer from a queue set. The ring buffer must have been previously added to the queue set using xRingbufferAddToQueueSetRead(). Parameters xRingbuffer -- [in] Ring buffer to remove from the queue set xQueueSet -- [in] Queue set to remove the ring buffer from xRingbuffer -- [in] Ring buffer to remove from the queue set xQueueSet -- [in] Queue set to remove the ring buffer from xRingbuffer -- [in] Ring buffer to remove from the queue set Returns pdTRUE on success pdFALSE otherwise pdTRUE on success pdFALSE otherwise pdTRUE on success Parameters xRingbuffer -- [in] Ring buffer to remove from the queue set xQueueSet -- [in] Queue set to remove the ring buffer from Returns pdTRUE on success pdFALSE otherwise void vRingbufferGetInfo(RingbufHandle_t xRingbuffer, UBaseType_t *uxFree, UBaseType_t *uxRead, UBaseType_t *uxWrite, UBaseType_t *uxAcquire, UBaseType_t *uxItemsWaiting) Get information about ring buffer status. Get information of a ring buffer's current status such as free/read/write/acquire pointer positions, and number of items waiting to be retrieved. Arguments can be set to NULL if they are not required. Parameters xRingbuffer -- [in] Ring buffer to remove from the queue set uxFree -- [out] Pointer use to store free pointer position uxRead -- [out] Pointer use to store read pointer position uxWrite -- [out] Pointer use to store write pointer position uxAcquire -- [out] Pointer use to store acquire pointer position uxItemsWaiting -- [out] Pointer use to store number of items (bytes for byte buffer) waiting to be retrieved xRingbuffer -- [in] Ring buffer to remove from the queue set uxFree -- [out] Pointer use to store free pointer position uxRead -- [out] Pointer use to store read pointer position uxWrite -- [out] Pointer use to store write pointer position uxAcquire -- [out] Pointer use to store acquire pointer position uxItemsWaiting -- [out] Pointer use to store number of items (bytes for byte buffer) waiting to be retrieved xRingbuffer -- [in] Ring buffer to remove from the queue set Parameters xRingbuffer -- [in] Ring buffer to remove from the queue set uxFree -- [out] Pointer use to store free pointer position uxRead -- [out] Pointer use to store read pointer position uxWrite -- [out] Pointer use to store write pointer position uxAcquire -- [out] Pointer use to store acquire pointer position uxItemsWaiting -- [out] Pointer use to store number of items (bytes for byte buffer) waiting to be retrieved void xRingbufferPrintInfo(RingbufHandle_t xRingbuffer) Debugging function to print the internal pointers in the ring buffer. Parameters xRingbuffer -- Ring buffer to show Parameters xRingbuffer -- Ring buffer to show BaseType_t xRingbufferGetStaticBuffer(RingbufHandle_t xRingbuffer, uint8_t **ppucRingbufferStorage, StaticRingbuffer_t **ppxStaticRingbuffer) Retrieve the pointers to a statically created ring buffer. Parameters xRingbuffer -- [in] Ring buffer ppucRingbufferStorage -- [out] Used to return a pointer to the queue's storage area buffer ppxStaticRingbuffer -- [out] Used to return a pointer to the queue's data structure buffer xRingbuffer -- [in] Ring buffer ppucRingbufferStorage -- [out] Used to return a pointer to the queue's storage area buffer ppxStaticRingbuffer -- [out] Used to return a pointer to the queue's data structure buffer xRingbuffer -- [in] Ring buffer Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. Parameters xRingbuffer -- [in] Ring buffer ppucRingbufferStorage -- [out] Used to return a pointer to the queue's storage area buffer ppxStaticRingbuffer -- [out] Used to return a pointer to the queue's data structure buffer Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. RingbufHandle_t xRingbufferCreateWithCaps(size_t xBufferSize, RingbufferType_t xBufferType, UBaseType_t uxMemoryCaps) Creates a ring buffer with specific memory capabilities. This function is similar to xRingbufferCreate(), except that it allows the memory allocated for the ring buffer to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A queue created using this function must only be deleted using vRingbufferDeleteWithCaps() Parameters xBufferSize -- [in] Size of the buffer in bytes xBufferType -- [in] Type of ring buffer, see documentation. uxMemoryCaps -- [in] Memory capabilities of the queue's memory (see esp_heap_caps.h) xBufferSize -- [in] Size of the buffer in bytes xBufferType -- [in] Type of ring buffer, see documentation. uxMemoryCaps -- [in] Memory capabilities of the queue's memory (see esp_heap_caps.h) xBufferSize -- [in] Size of the buffer in bytes Returns Handle to the created ring buffer or NULL on failure. Parameters xBufferSize -- [in] Size of the buffer in bytes xBufferType -- [in] Type of ring buffer, see documentation. uxMemoryCaps -- [in] Memory capabilities of the queue's memory (see esp_heap_caps.h) Returns Handle to the created ring buffer or NULL on failure. void vRingbufferDeleteWithCaps(RingbufHandle_t xRingbuffer) Deletes a ring buffer previously created using xRingbufferCreateWithCaps() Parameters xRingbuffer -- Ring buffer Parameters xRingbuffer -- Ring buffer Structures struct xSTATIC_RINGBUFFER Struct that is equivalent in size to the ring buffer's data structure. The contents of this struct are not meant to be used directly. This structure is meant to be used when creating a statically allocated ring buffer where this struct is of the exact size required to store a ring buffer's control data structure. Type Definitions typedef void *RingbufHandle_t Type by which ring buffers are referenced. For example, a call to xRingbufferCreate() returns a RingbufHandle_t variable that can then be used as a parameter to xRingbufferSend(), xRingbufferReceive(), etc. typedef struct xSTATIC_RINGBUFFER StaticRingbuffer_t Struct that is equivalent in size to the ring buffer's data structure. The contents of this struct are not meant to be used directly. This structure is meant to be used when creating a statically allocated ring buffer where this struct is of the exact size required to store a ring buffer's control data structure. Enumerations enum RingbufferType_t Values: enumerator RINGBUF_TYPE_NOSPLIT No-split buffers will only store an item in contiguous memory and will never split an item. Each item requires an 8 byte overhead for a header and will always internally occupy a 32-bit aligned size of space. enumerator RINGBUF_TYPE_NOSPLIT No-split buffers will only store an item in contiguous memory and will never split an item. Each item requires an 8 byte overhead for a header and will always internally occupy a 32-bit aligned size of space. enumerator RINGBUF_TYPE_ALLOWSPLIT Allow-split buffers will split an item into two parts if necessary in order to store it. Each item requires an 8 byte overhead for a header, splitting incurs an extra header. Each item will always internally occupy a 32-bit aligned size of space. enumerator RINGBUF_TYPE_ALLOWSPLIT Allow-split buffers will split an item into two parts if necessary in order to store it. Each item requires an 8 byte overhead for a header, splitting incurs an extra header. Each item will always internally occupy a 32-bit aligned size of space. enumerator RINGBUF_TYPE_BYTEBUF Byte buffers store data as a sequence of bytes and do not maintain separate items, therefore byte buffers have no overhead. All data is stored as a sequence of byte and any number of bytes can be sent or retrieved each time. enumerator RINGBUF_TYPE_BYTEBUF Byte buffers store data as a sequence of bytes and do not maintain separate items, therefore byte buffers have no overhead. All data is stored as a sequence of byte and any number of bytes can be sent or retrieved each time. enumerator RINGBUF_TYPE_MAX enumerator RINGBUF_TYPE_MAX enumerator RINGBUF_TYPE_NOSPLIT Hooks API Header File This header file can be included with: #include "esp_freertos_hooks.h" Functions esp_err_t esp_register_freertos_idle_hook_for_cpu(esp_freertos_idle_cb_t new_idle_cb, UBaseType_t cpuid) Register a callback to be called from the specified core's idle hook. The callback should return true if it should be called by the idle hook once per interrupt (or FreeRTOS tick), and return false if it should be called repeatedly as fast as possible by the idle hook. Warning Idle callbacks MUST NOT, UNDER ANY CIRCUMSTANCES, CALL A FUNCTION THAT MIGHT BLOCK. Parameters new_idle_cb -- [in] Callback to be called cpuid -- [in] id of the core new_idle_cb -- [in] Callback to be called cpuid -- [in] id of the core new_idle_cb -- [in] Callback to be called Returns ESP_OK: Callback registered to the specified core's idle hook ESP_ERR_NO_MEM: No more space on the specified core's idle hook to register callback ESP_ERR_INVALID_ARG: cpuid is invalid ESP_OK: Callback registered to the specified core's idle hook ESP_ERR_NO_MEM: No more space on the specified core's idle hook to register callback ESP_ERR_INVALID_ARG: cpuid is invalid ESP_OK: Callback registered to the specified core's idle hook Parameters new_idle_cb -- [in] Callback to be called cpuid -- [in] id of the core Returns ESP_OK: Callback registered to the specified core's idle hook ESP_ERR_NO_MEM: No more space on the specified core's idle hook to register callback ESP_ERR_INVALID_ARG: cpuid is invalid esp_err_t esp_register_freertos_idle_hook(esp_freertos_idle_cb_t new_idle_cb) Register a callback to the idle hook of the core that calls this function. The callback should return true if it should be called by the idle hook once per interrupt (or FreeRTOS tick), and return false if it should be called repeatedly as fast as possible by the idle hook. Warning Idle callbacks MUST NOT, UNDER ANY CIRCUMSTANCES, CALL A FUNCTION THAT MIGHT BLOCK. Parameters new_idle_cb -- [in] Callback to be called Returns ESP_OK: Callback registered to the calling core's idle hook ESP_ERR_NO_MEM: No more space on the calling core's idle hook to register callback ESP_OK: Callback registered to the calling core's idle hook ESP_ERR_NO_MEM: No more space on the calling core's idle hook to register callback ESP_OK: Callback registered to the calling core's idle hook Parameters new_idle_cb -- [in] Callback to be called Returns ESP_OK: Callback registered to the calling core's idle hook ESP_ERR_NO_MEM: No more space on the calling core's idle hook to register callback esp_err_t esp_register_freertos_tick_hook_for_cpu(esp_freertos_tick_cb_t new_tick_cb, UBaseType_t cpuid) Register a callback to be called from the specified core's tick hook. Parameters new_tick_cb -- [in] Callback to be called cpuid -- [in] id of the core new_tick_cb -- [in] Callback to be called cpuid -- [in] id of the core new_tick_cb -- [in] Callback to be called Returns ESP_OK: Callback registered to specified core's tick hook ESP_ERR_NO_MEM: No more space on the specified core's tick hook to register the callback ESP_ERR_INVALID_ARG: cpuid is invalid ESP_OK: Callback registered to specified core's tick hook ESP_ERR_NO_MEM: No more space on the specified core's tick hook to register the callback ESP_ERR_INVALID_ARG: cpuid is invalid ESP_OK: Callback registered to specified core's tick hook Parameters new_tick_cb -- [in] Callback to be called cpuid -- [in] id of the core Returns ESP_OK: Callback registered to specified core's tick hook ESP_ERR_NO_MEM: No more space on the specified core's tick hook to register the callback ESP_ERR_INVALID_ARG: cpuid is invalid esp_err_t esp_register_freertos_tick_hook(esp_freertos_tick_cb_t new_tick_cb) Register a callback to be called from the calling core's tick hook. Parameters new_tick_cb -- [in] Callback to be called Returns ESP_OK: Callback registered to the calling core's tick hook ESP_ERR_NO_MEM: No more space on the calling core's tick hook to register the callback ESP_OK: Callback registered to the calling core's tick hook ESP_ERR_NO_MEM: No more space on the calling core's tick hook to register the callback ESP_OK: Callback registered to the calling core's tick hook Parameters new_tick_cb -- [in] Callback to be called Returns ESP_OK: Callback registered to the calling core's tick hook ESP_ERR_NO_MEM: No more space on the calling core's tick hook to register the callback void esp_deregister_freertos_idle_hook_for_cpu(esp_freertos_idle_cb_t old_idle_cb, UBaseType_t cpuid) Unregister an idle callback from the idle hook of the specified core. Parameters old_idle_cb -- [in] Callback to be unregistered cpuid -- [in] id of the core old_idle_cb -- [in] Callback to be unregistered cpuid -- [in] id of the core old_idle_cb -- [in] Callback to be unregistered Parameters old_idle_cb -- [in] Callback to be unregistered cpuid -- [in] id of the core void esp_deregister_freertos_idle_hook(esp_freertos_idle_cb_t old_idle_cb) Unregister an idle callback. If the idle callback is registered to the idle hooks of both cores, the idle hook will be unregistered from both cores. Parameters old_idle_cb -- [in] Callback to be unregistered Parameters old_idle_cb -- [in] Callback to be unregistered void esp_deregister_freertos_tick_hook_for_cpu(esp_freertos_tick_cb_t old_tick_cb, UBaseType_t cpuid) Unregister a tick callback from the tick hook of the specified core. Parameters old_tick_cb -- [in] Callback to be unregistered cpuid -- [in] id of the core old_tick_cb -- [in] Callback to be unregistered cpuid -- [in] id of the core old_tick_cb -- [in] Callback to be unregistered Parameters old_tick_cb -- [in] Callback to be unregistered cpuid -- [in] id of the core void esp_deregister_freertos_tick_hook(esp_freertos_tick_cb_t old_tick_cb) Unregister a tick callback. If the tick callback is registered to the tick hooks of both cores, the tick hook will be unregistered from both cores. Parameters old_tick_cb -- [in] Callback to be unregistered Parameters old_tick_cb -- [in] Callback to be unregistered Type Definitions typedef bool (*esp_freertos_idle_cb_t)(void) typedef void (*esp_freertos_tick_cb_t)(void) Additional API Header File components/freertos/esp_additions/include/freertos/idf_additions.h This header file can be included with: #include "freertos/idf_additions.h" Functions BaseType_t xTaskCreatePinnedToCore(TaskFunction_t pxTaskCode, const char *const pcName, const uint32_t ulStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *const pxCreatedTask, const BaseType_t xCoreID) Create a new task that is pinned to a particular core. This function is similar to xTaskCreate(), but allows the creation of a pinned task. The task's pinned core is specified by the xCoreID argument. If xCoreID is set to tskNO_AFFINITY, then the task is unpinned and can run on any core. Note If ( configNUMBER_OF_CORES == 1 ), setting xCoreID to tskNO_AFFINITY will be be treated as 0. Parameters pxTaskCode -- Pointer to the task entry function. pcName -- A descriptive name for the task. ulStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. pxCreatedTask -- Used to pass back a handle by which the created task can be referenced. xCoreID -- The core to which the task is pinned to, or tskNO_AFFINITY if the task has no core affinity. pxTaskCode -- Pointer to the task entry function. pcName -- A descriptive name for the task. ulStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. pxCreatedTask -- Used to pass back a handle by which the created task can be referenced. xCoreID -- The core to which the task is pinned to, or tskNO_AFFINITY if the task has no core affinity. pxTaskCode -- Pointer to the task entry function. Returns pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined in the file projdefs.h Parameters pxTaskCode -- Pointer to the task entry function. pcName -- A descriptive name for the task. ulStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. pxCreatedTask -- Used to pass back a handle by which the created task can be referenced. xCoreID -- The core to which the task is pinned to, or tskNO_AFFINITY if the task has no core affinity. Returns pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined in the file projdefs.h TaskHandle_t xTaskCreateStaticPinnedToCore(TaskFunction_t pxTaskCode, const char *const pcName, const uint32_t ulStackDepth, void *const pvParameters, UBaseType_t uxPriority, StackType_t *const puxStackBuffer, StaticTask_t *const pxTaskBuffer, const BaseType_t xCoreID) Create a new static task that is pinned to a particular core. This function is similar to xTaskCreateStatic(), but allows the creation of a pinned task. The task's pinned core is specified by the xCoreID argument. If xCoreID is set to tskNO_AFFINITY, then the task is unpinned and can run on any core. Note If ( configNUMBER_OF_CORES == 1 ), setting xCoreID to tskNO_AFFINITY will be be treated as 0. Parameters pxTaskCode -- Pointer to the task entry function. pcName -- A descriptive name for the task. ulStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. puxStackBuffer -- Must point to a StackType_t array that has at least ulStackDepth indexes pxTaskBuffer -- Must point to a variable of type StaticTask_t, which will then be used to hold the task's data structures, xCoreID -- The core to which the task is pinned to, or tskNO_AFFINITY if the task has no core affinity. pxTaskCode -- Pointer to the task entry function. pcName -- A descriptive name for the task. ulStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. puxStackBuffer -- Must point to a StackType_t array that has at least ulStackDepth indexes pxTaskBuffer -- Must point to a variable of type StaticTask_t, which will then be used to hold the task's data structures, xCoreID -- The core to which the task is pinned to, or tskNO_AFFINITY if the task has no core affinity. pxTaskCode -- Pointer to the task entry function. Returns The task handle if the task was created, NULL otherwise. Parameters pxTaskCode -- Pointer to the task entry function. pcName -- A descriptive name for the task. ulStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. puxStackBuffer -- Must point to a StackType_t array that has at least ulStackDepth indexes pxTaskBuffer -- Must point to a variable of type StaticTask_t, which will then be used to hold the task's data structures, xCoreID -- The core to which the task is pinned to, or tskNO_AFFINITY if the task has no core affinity. Returns The task handle if the task was created, NULL otherwise. BaseType_t xTaskGetCoreID(TaskHandle_t xTask) Get the current core ID of a particular task. Helper function to get the core ID of a particular task. If the task is pinned to a particular core, the core ID is returned. If the task is not pinned to a particular core, tskNO_AFFINITY is returned. If CONFIG_FREERTOS_UNICORE is enabled, this function simply returns 0. [refactor-todo] See if this needs to be deprecated (IDF-8145)(IDF-8164) Note If CONFIG_FREERTOS_SMP is enabled, please call vTaskCoreAffinityGet() instead. Note In IDF FreerTOS when configNUMBER_OF_CORES == 1, this function will always return 0, Parameters xTask -- The task to query Returns The task's core ID or tskNO_AFFINITY Parameters xTask -- The task to query Returns The task's core ID or tskNO_AFFINITY TaskHandle_t xTaskGetIdleTaskHandleForCore(BaseType_t xCoreID) Get the handle of idle task for the given core. [refactor-todo] See if this needs to be deprecated (IDF-8145) Note If CONFIG_FREERTOS_SMP is enabled, please call xTaskGetIdleTaskHandle() instead. Parameters xCoreID -- The core to query Returns Handle of the idle task for the queried core Parameters xCoreID -- The core to query Returns Handle of the idle task for the queried core TaskHandle_t xTaskGetCurrentTaskHandleForCore(BaseType_t xCoreID) Get the handle of the task currently running on a certain core. Because of the nature of SMP processing, there is no guarantee that this value will still be valid on return and should only be used for debugging purposes. [refactor-todo] See if this needs to be deprecated (IDF-8145) Note If CONFIG_FREERTOS_SMP is enabled, please call xTaskGetCurrentTaskHandleCPU() instead. Parameters xCoreID -- The core to query Returns Handle of the current task running on the queried core Parameters xCoreID -- The core to query Returns Handle of the current task running on the queried core uint8_t *pxTaskGetStackStart(TaskHandle_t xTask) Returns the start of the stack associated with xTask. Returns the lowest stack memory address, regardless of whether the stack grows up or down. [refactor-todo] Change return type to StackType_t (IDF-8158) Parameters xTask -- Handle of the task associated with the stack returned. Set xTask to NULL to return the stack of the calling task. Returns A pointer to the start of the stack. Parameters xTask -- Handle of the task associated with the stack returned. Set xTask to NULL to return the stack of the calling task. Returns A pointer to the start of the stack. void vTaskSetThreadLocalStoragePointerAndDelCallback(TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue, TlsDeleteCallbackFunction_t pvDelCallback) Set local storage pointer and deletion callback. Each task contains an array of pointers that is dimensioned by the configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The kernel does not use the pointers itself, so the application writer can use the pointers for any purpose they wish. Local storage pointers set for a task can reference dynamically allocated resources. This function is similar to vTaskSetThreadLocalStoragePointer, but provides a way to release these resources when the task gets deleted. For each pointer, a callback function can be set. This function will be called when task is deleted, with the local storage pointer index and value as arguments. Parameters xTaskToSet -- Task to set thread local storage pointer for xIndex -- The index of the pointer to set, from 0 to configNUM_THREAD_LOCAL_STORAGE_POINTERS - 1. pvValue -- Pointer value to set. pvDelCallback -- Function to call to dispose of the local storage pointer when the task is deleted. xTaskToSet -- Task to set thread local storage pointer for xIndex -- The index of the pointer to set, from 0 to configNUM_THREAD_LOCAL_STORAGE_POINTERS - 1. pvValue -- Pointer value to set. pvDelCallback -- Function to call to dispose of the local storage pointer when the task is deleted. xTaskToSet -- Task to set thread local storage pointer for Parameters xTaskToSet -- Task to set thread local storage pointer for xIndex -- The index of the pointer to set, from 0 to configNUM_THREAD_LOCAL_STORAGE_POINTERS - 1. pvValue -- Pointer value to set. pvDelCallback -- Function to call to dispose of the local storage pointer when the task is deleted. BaseType_t xTaskCreatePinnedToCoreWithCaps(TaskFunction_t pvTaskCode, const char *const pcName, const configSTACK_DEPTH_TYPE usStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *const pvCreatedTask, const BaseType_t xCoreID, UBaseType_t uxMemoryCaps) Creates a pinned task where its stack has specific memory capabilities. This function is similar to xTaskCreatePinnedToCore(), except that it allows the memory allocated for the task's stack to have specific capabilities (e.g., MALLOC_CAP_SPIRAM). However, the specified capabilities will NOT apply to the task's TCB as a TCB must always be in internal RAM. Parameters pvTaskCode -- Pointer to the task entry function pcName -- A descriptive name for the task usStackDepth -- The size of the task stack specified as the number of bytes pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. pvCreatedTask -- Used to pass back a handle by which the created task can be referenced. xCoreID -- Core to which the task is pinned to, or tskNO_AFFINITY if unpinned. uxMemoryCaps -- Memory capabilities of the task stack's memory (see esp_heap_caps.h) pvTaskCode -- Pointer to the task entry function pcName -- A descriptive name for the task usStackDepth -- The size of the task stack specified as the number of bytes pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. pvCreatedTask -- Used to pass back a handle by which the created task can be referenced. xCoreID -- Core to which the task is pinned to, or tskNO_AFFINITY if unpinned. uxMemoryCaps -- Memory capabilities of the task stack's memory (see esp_heap_caps.h) pvTaskCode -- Pointer to the task entry function Returns pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined in the file projdefs.h Parameters pvTaskCode -- Pointer to the task entry function pcName -- A descriptive name for the task usStackDepth -- The size of the task stack specified as the number of bytes pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. pvCreatedTask -- Used to pass back a handle by which the created task can be referenced. xCoreID -- Core to which the task is pinned to, or tskNO_AFFINITY if unpinned. uxMemoryCaps -- Memory capabilities of the task stack's memory (see esp_heap_caps.h) Returns pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined in the file projdefs.h static inline BaseType_t xTaskCreateWithCaps(TaskFunction_t pvTaskCode, const char *const pcName, configSTACK_DEPTH_TYPE usStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *pvCreatedTask, UBaseType_t uxMemoryCaps) Creates a task where its stack has specific memory capabilities. This function is similar to xTaskCreate(), except that it allows the memory allocated for the task's stack to have specific capabilities (e.g., MALLOC_CAP_SPIRAM). However, the specified capabilities will NOT apply to the task's TCB as a TCB must always be in internal RAM. Note A task created using this function must only be deleted using vTaskDeleteWithCaps() Parameters pvTaskCode -- Pointer to the task entry function pcName -- A descriptive name for the task usStackDepth -- The size of the task stack specified as the number of bytes pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. pvCreatedTask -- Used to pass back a handle by which the created task can be referenced. uxMemoryCaps -- Memory capabilities of the task stack's memory (see esp_heap_caps.h) pvTaskCode -- Pointer to the task entry function pcName -- A descriptive name for the task usStackDepth -- The size of the task stack specified as the number of bytes pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. pvCreatedTask -- Used to pass back a handle by which the created task can be referenced. uxMemoryCaps -- Memory capabilities of the task stack's memory (see esp_heap_caps.h) pvTaskCode -- Pointer to the task entry function Returns pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined in the file projdefs.h Parameters pvTaskCode -- Pointer to the task entry function pcName -- A descriptive name for the task usStackDepth -- The size of the task stack specified as the number of bytes pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. pvCreatedTask -- Used to pass back a handle by which the created task can be referenced. uxMemoryCaps -- Memory capabilities of the task stack's memory (see esp_heap_caps.h) Returns pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined in the file projdefs.h void vTaskDeleteWithCaps(TaskHandle_t xTaskToDelete) Deletes a task previously created using xTaskCreateWithCaps() or xTaskCreatePinnedToCoreWithCaps() Parameters xTaskToDelete -- A handle to the task to be deleted Parameters xTaskToDelete -- A handle to the task to be deleted QueueHandle_t xQueueCreateWithCaps(UBaseType_t uxQueueLength, UBaseType_t uxItemSize, UBaseType_t uxMemoryCaps) Creates a queue with specific memory capabilities. This function is similar to xQueueCreate(), except that it allows the memory allocated for the queue to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A queue created using this function must only be deleted using vQueueDeleteWithCaps() Parameters uxQueueLength -- The maximum number of items that the queue can contain. uxItemSize -- The number of bytes each item in the queue will require. uxMemoryCaps -- Memory capabilities of the queue's memory (see esp_heap_caps.h) uxQueueLength -- The maximum number of items that the queue can contain. uxItemSize -- The number of bytes each item in the queue will require. uxMemoryCaps -- Memory capabilities of the queue's memory (see esp_heap_caps.h) uxQueueLength -- The maximum number of items that the queue can contain. Returns Handle to the created queue or NULL on failure. Parameters uxQueueLength -- The maximum number of items that the queue can contain. uxItemSize -- The number of bytes each item in the queue will require. uxMemoryCaps -- Memory capabilities of the queue's memory (see esp_heap_caps.h) Returns Handle to the created queue or NULL on failure. void vQueueDeleteWithCaps(QueueHandle_t xQueue) Deletes a queue previously created using xQueueCreateWithCaps() Parameters xQueue -- A handle to the queue to be deleted. Parameters xQueue -- A handle to the queue to be deleted. static inline SemaphoreHandle_t xSemaphoreCreateBinaryWithCaps(UBaseType_t uxMemoryCaps) Creates a binary semaphore with specific memory capabilities. This function is similar to vSemaphoreCreateBinary(), except that it allows the memory allocated for the binary semaphore to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A binary semaphore created using this function must only be deleted using vSemaphoreDeleteWithCaps() Parameters uxMemoryCaps -- Memory capabilities of the binary semaphore's memory (see esp_heap_caps.h) Returns Handle to the created binary semaphore or NULL on failure. Parameters uxMemoryCaps -- Memory capabilities of the binary semaphore's memory (see esp_heap_caps.h) Returns Handle to the created binary semaphore or NULL on failure. static inline SemaphoreHandle_t xSemaphoreCreateCountingWithCaps(UBaseType_t uxMaxCount, UBaseType_t uxInitialCount, UBaseType_t uxMemoryCaps) Creates a counting semaphore with specific memory capabilities. This function is similar to xSemaphoreCreateCounting(), except that it allows the memory allocated for the counting semaphore to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A counting semaphore created using this function must only be deleted using vSemaphoreDeleteWithCaps() Parameters uxMaxCount -- The maximum count value that can be reached. uxInitialCount -- The count value assigned to the semaphore when it is created. uxMemoryCaps -- Memory capabilities of the counting semaphore's memory (see esp_heap_caps.h) uxMaxCount -- The maximum count value that can be reached. uxInitialCount -- The count value assigned to the semaphore when it is created. uxMemoryCaps -- Memory capabilities of the counting semaphore's memory (see esp_heap_caps.h) uxMaxCount -- The maximum count value that can be reached. Returns Handle to the created counting semaphore or NULL on failure. Parameters uxMaxCount -- The maximum count value that can be reached. uxInitialCount -- The count value assigned to the semaphore when it is created. uxMemoryCaps -- Memory capabilities of the counting semaphore's memory (see esp_heap_caps.h) Returns Handle to the created counting semaphore or NULL on failure. static inline SemaphoreHandle_t xSemaphoreCreateMutexWithCaps(UBaseType_t uxMemoryCaps) Creates a mutex semaphore with specific memory capabilities. This function is similar to xSemaphoreCreateMutex(), except that it allows the memory allocated for the mutex semaphore to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A mutex semaphore created using this function must only be deleted using vSemaphoreDeleteWithCaps() Parameters uxMemoryCaps -- Memory capabilities of the mutex semaphore's memory (see esp_heap_caps.h) Returns Handle to the created mutex semaphore or NULL on failure. Parameters uxMemoryCaps -- Memory capabilities of the mutex semaphore's memory (see esp_heap_caps.h) Returns Handle to the created mutex semaphore or NULL on failure. static inline SemaphoreHandle_t xSemaphoreCreateRecursiveMutexWithCaps(UBaseType_t uxMemoryCaps) Creates a recursive mutex with specific memory capabilities. This function is similar to xSemaphoreCreateRecursiveMutex(), except that it allows the memory allocated for the recursive mutex to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A recursive mutex created using this function must only be deleted using vSemaphoreDeleteWithCaps() Parameters uxMemoryCaps -- Memory capabilities of the recursive mutex's memory (see esp_heap_caps.h) Returns Handle to the created recursive mutex or NULL on failure. Parameters uxMemoryCaps -- Memory capabilities of the recursive mutex's memory (see esp_heap_caps.h) Returns Handle to the created recursive mutex or NULL on failure. void vSemaphoreDeleteWithCaps(SemaphoreHandle_t xSemaphore) Deletes a semaphore previously created using one of the xSemaphoreCreate...WithCaps() functions. Parameters xSemaphore -- A handle to the semaphore to be deleted. Parameters xSemaphore -- A handle to the semaphore to be deleted. static inline StreamBufferHandle_t xStreamBufferCreateWithCaps(size_t xBufferSizeBytes, size_t xTriggerLevelBytes, UBaseType_t uxMemoryCaps) Creates a stream buffer with specific memory capabilities. This function is similar to xStreamBufferCreate(), except that it allows the memory allocated for the stream buffer to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A stream buffer created using this function must only be deleted using vStreamBufferDeleteWithCaps() Parameters xBufferSizeBytes -- The total number of bytes the stream buffer will be able to hold at any one time. xTriggerLevelBytes -- The number of bytes that must be in the stream buffer before unblocking uxMemoryCaps -- Memory capabilities of the stream buffer's memory (see esp_heap_caps.h) xBufferSizeBytes -- The total number of bytes the stream buffer will be able to hold at any one time. xTriggerLevelBytes -- The number of bytes that must be in the stream buffer before unblocking uxMemoryCaps -- Memory capabilities of the stream buffer's memory (see esp_heap_caps.h) xBufferSizeBytes -- The total number of bytes the stream buffer will be able to hold at any one time. Returns Handle to the created stream buffer or NULL on failure. Parameters xBufferSizeBytes -- The total number of bytes the stream buffer will be able to hold at any one time. xTriggerLevelBytes -- The number of bytes that must be in the stream buffer before unblocking uxMemoryCaps -- Memory capabilities of the stream buffer's memory (see esp_heap_caps.h) Returns Handle to the created stream buffer or NULL on failure. static inline void vStreamBufferDeleteWithCaps(StreamBufferHandle_t xStreamBuffer) Deletes a stream buffer previously created using xStreamBufferCreateWithCaps() Parameters xStreamBuffer -- A handle to the stream buffer to be deleted. Parameters xStreamBuffer -- A handle to the stream buffer to be deleted. static inline MessageBufferHandle_t xMessageBufferCreateWithCaps(size_t xBufferSizeBytes, UBaseType_t uxMemoryCaps) Creates a message buffer with specific memory capabilities. This function is similar to xMessageBufferCreate(), except that it allows the memory allocated for the message buffer to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A message buffer created using this function must only be deleted using vMessageBufferDeleteWithCaps() Parameters xBufferSizeBytes -- The total number of bytes (not messages) the message buffer will be able to hold at any one time. uxMemoryCaps -- Memory capabilities of the message buffer's memory (see esp_heap_caps.h) xBufferSizeBytes -- The total number of bytes (not messages) the message buffer will be able to hold at any one time. uxMemoryCaps -- Memory capabilities of the message buffer's memory (see esp_heap_caps.h) xBufferSizeBytes -- The total number of bytes (not messages) the message buffer will be able to hold at any one time. Returns Handle to the created message buffer or NULL on failure. Parameters xBufferSizeBytes -- The total number of bytes (not messages) the message buffer will be able to hold at any one time. uxMemoryCaps -- Memory capabilities of the message buffer's memory (see esp_heap_caps.h) Returns Handle to the created message buffer or NULL on failure. static inline void vMessageBufferDeleteWithCaps(MessageBufferHandle_t xMessageBuffer) Deletes a stream buffer previously created using xMessageBufferCreateWithCaps() Parameters xMessageBuffer -- A handle to the message buffer to be deleted. Parameters xMessageBuffer -- A handle to the message buffer to be deleted. EventGroupHandle_t xEventGroupCreateWithCaps(UBaseType_t uxMemoryCaps) Creates an event group with specific memory capabilities. This function is similar to xEventGroupCreate(), except that it allows the memory allocated for the event group to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note An event group created using this function must only be deleted using vEventGroupDeleteWithCaps() Parameters uxMemoryCaps -- Memory capabilities of the event group's memory (see esp_heap_caps.h) Returns Handle to the created event group or NULL on failure. Parameters uxMemoryCaps -- Memory capabilities of the event group's memory (see esp_heap_caps.h) Returns Handle to the created event group or NULL on failure. void vEventGroupDeleteWithCaps(EventGroupHandle_t xEventGroup) Deletes an event group previously created using xEventGroupCreateWithCaps() Parameters xEventGroup -- A handle to the event group to be deleted. Parameters xEventGroup -- A handle to the event group to be deleted. Type Definitions typedef void (*TlsDeleteCallbackFunction_t)(int, void*) Prototype of local storage pointer deletion callback.
FreeRTOS (Supplemental Features) ESP-IDF provides multiple features to supplement the features offered by FreeRTOS. These supplemental features are available on all FreeRTOS implementations supported by ESP-IDF (i.e., ESP-IDF FreeRTOS and Amazon SMP FreeRTOS). This document describes these supplemental features and is split into the following sections: Contents Overview ESP-IDF adds various new features to supplement the capabilities of FreeRTOS as follows: Ring buffers: Ring buffers provide a FIFO buffer that can accept entries of arbitrary lengths. ESP-IDF Tick and Idle Hooks: ESP-IDF provides multiple custom tick interrupt hooks and idle task hooks that are more numerous and more flexible when compared to FreeRTOS tick and idle hooks. Thread Local Storage Pointer (TLSP) Deletion Callbacks: TLSP Deletion callbacks are run automatically when a task is deleted, thus allowing users to clean up their TLSPs automatically. IDF Additional API: ESP-IDF specific functions added to augment the features of FreeRTOS. Component Specific Properties: Currently added only one component specific property ORIG_INCLUDE_PATH. Ring Buffers FreeRTOS provides stream buffers and message buffers as the primary mechanisms to send arbitrarily sized data between tasks and ISRs. However, FreeRTOS stream buffers and message buffers have the following limitations: Strictly single sender and single receiver Data is passed by copy Unable to reserve buffer space for a deferred send (i.e., send acquire) Therefore, ESP-IDF provides a separate ring buffer implementation to address the issues above. ESP-IDF ring buffers are strictly FIFO buffers that supports arbitrarily sized items. Ring buffers are a more memory efficient alternative to FreeRTOS queues in situations where the size of items is variable. The capacity of a ring buffer is not measured by the number of items it can store, but rather by the amount of memory used for storing items. The ring buffer provides APIs to send an item, or to allocate space for an item in the ring buffer to be filled manually by the user. For efficiency reasons, items are always retrieved from the ring buffer by reference. As a result, all retrieved items must also be returned to the ring buffer by using vRingbufferReturnItem() or vRingbufferReturnItemFromISR(), in order for them to be removed from the ring buffer completely. The ring buffers are split into the three following types: No-Split buffers guarantee that an item is stored in contiguous memory and does not attempt to split an item under any circumstances. Use No-Split buffers when items must occupy contiguous memory. Only this buffer type allows reserving buffer space for deferred sending. Refer to the documentation of the functions xRingbufferSendAcquire() and xRingbufferSendComplete() for more details. Allow-Split buffers allow an item to be split in two parts when wrapping around the end of the buffer if there is enough space at the tail and the head of the buffer combined to store the item. Allow-Split buffers are more memory efficient than No-Split buffers but can return an item in two parts when retrieving. Byte buffers do not store data as separate items. All data is stored as a sequence of bytes, and any number of bytes can be sent or retrieved each time. Use byte buffers when separate items do not need to be maintained, e.g., a byte stream. Note No-Split buffers and Allow-Split buffers always store items at 32-bit aligned addresses. Therefore, when retrieving an item, the item pointer is guaranteed to be 32-bit aligned. This is useful especially when you need to send some data to the DMA. Note Each item stored in No-Split or Allow-Split buffers requires an additional 8 bytes for a header. Item sizes are also rounded up to a 32-bit aligned size, i.e., multiple of 4 bytes. However the true item size is recorded within the header. The sizes of No-Split and Allow-Split buffers will also be rounded up when created. Usage The following example demonstrates the usage of xRingbufferCreate() and xRingbufferSend() to create a ring buffer and then send an item to it: #include "freertos/ringbuf.h" static char tx_item[] = "test_item"; ... //Create ring buffer RingbufHandle_t buf_handle; buf_handle = xRingbufferCreate(1028, RINGBUF_TYPE_NOSPLIT); if (buf_handle == NULL) { printf("Failed to create ring buffer\n"); } //Send an item UBaseType_t res = xRingbufferSend(buf_handle, tx_item, sizeof(tx_item), pdMS_TO_TICKS(1000)); if (res != pdTRUE) { printf("Failed to send item\n"); } The following example demonstrates the usage of xRingbufferSendAcquire() and xRingbufferSendComplete() instead of xRingbufferSend() to acquire memory on the ring buffer (of type RINGBUF_TYPE_NOSPLIT) and then send an item to it. This adds one more step, but allows getting the address of the memory to write to, and writing to the memory yourself. #include "freertos/ringbuf.h" #include "soc/lldesc.h" typedef struct { lldesc_t dma_desc; uint8_t buf[1]; } dma_item_t; #define DMA_ITEM_SIZE(N) (sizeof(lldesc_t)+(((N)+3)&(~3))) ... //Retrieve space for DMA descriptor and corresponding data buffer //This has to be done with SendAcquire, or the address may be different when we copy dma_item_t item; UBaseType_t res = xRingbufferSendAcquire(buf_handle, &item, DMA_ITEM_SIZE(buffer_size), pdMS_TO_TICKS(1000)); if (res != pdTRUE) { printf("Failed to acquire memory for item\n"); } item->dma_desc = (lldesc_t) { .size = buffer_size, .length = buffer_size, .eof = 0, .owner = 1, .buf = &item->buf, }; //Actually send to the ring buffer for consumer to use res = xRingbufferSendComplete(buf_handle, &item); if (res != pdTRUE) { printf("Failed to send item\n"); } The following example demonstrates retrieving and returning an item from a No-Split ring buffer using xRingbufferReceive() and vRingbufferReturnItem() ... //Receive an item from no-split ring buffer size_t item_size; char *item = (char *)xRingbufferReceive(buf_handle, &item_size, pdMS_TO_TICKS(1000)); //Check received item if (item != NULL) { //Print item for (int i = 0; i < item_size; i++) { printf("%c", item[i]); } printf("\n"); //Return Item vRingbufferReturnItem(buf_handle, (void *)item); } else { //Failed to receive item printf("Failed to receive item\n"); } The following example demonstrates retrieving and returning an item from an Allow-Split ring buffer using xRingbufferReceiveSplit() and vRingbufferReturnItem() ... //Receive an item from allow-split ring buffer size_t item_size1, item_size2; char *item1, *item2; BaseType_t ret = xRingbufferReceiveSplit(buf_handle, (void **)&item1, (void **)&item2, &item_size1, &item_size2, pdMS_TO_TICKS(1000)); //Check received item if (ret == pdTRUE && item1 != NULL) { for (int i = 0; i < item_size1; i++) { printf("%c", item1[i]); } vRingbufferReturnItem(buf_handle, (void *)item1); //Check if item was split if (item2 != NULL) { for (int i = 0; i < item_size2; i++) { printf("%c", item2[i]); } vRingbufferReturnItem(buf_handle, (void *)item2); } printf("\n"); } else { //Failed to receive item printf("Failed to receive item\n"); } The following example demonstrates retrieving and returning an item from a byte buffer using xRingbufferReceiveUpTo() and vRingbufferReturnItem() ... //Receive data from byte buffer size_t item_size; char *item = (char *)xRingbufferReceiveUpTo(buf_handle, &item_size, pdMS_TO_TICKS(1000), sizeof(tx_item)); //Check received data if (item != NULL) { //Print item for (int i = 0; i < item_size; i++) { printf("%c", item[i]); } printf("\n"); //Return Item vRingbufferReturnItem(buf_handle, (void *)item); } else { //Failed to receive item printf("Failed to receive item\n"); } For ISR safe versions of the functions used above, call xRingbufferSendFromISR(), xRingbufferReceiveFromISR(), xRingbufferReceiveSplitFromISR(), xRingbufferReceiveUpToFromISR(), and vRingbufferReturnItemFromISR(). Note Two calls to RingbufferReceive[UpTo][FromISR]() are required if the bytes wraps around the end of the ring buffer. Sending to Ring Buffer The following diagrams illustrate the differences between No-Split and Allow-Split buffers as compared to byte buffers with regard to sending items or data. The diagrams assume that three items of sizes 18, 3, and 27 bytes are sent respectively to a buffer of 128 bytes: For No-Split and Allow-Split buffers, a header of 8 bytes precedes every data item. Furthermore, the space occupied by each item is rounded up to the nearest 32-bit aligned size in order to maintain overall 32-bit alignment. However, the true size of the item is recorded inside the header which will be returned when the item is retrieved. Referring to the diagram above, the 18, 3, and 27 byte items are rounded up to 20, 4, and 28 bytes respectively. An 8 byte header is then added in front of each item. Byte buffers treat data as a sequence of bytes and does not incur any overhead (no headers). As a result, all data sent to a byte buffer is merged into a single item. Referring to the diagram above, the 18, 3, and 27 byte items are sequentially written to the byte buffer and merged into a single item of 48 bytes. Using SendAcquire and SendComplete Items in No-Split buffers are acquired (by SendAcquire) in strict FIFO order and must be sent to the buffer by SendComplete for the data to be accessible by the consumer. Multiple items can be sent or acquired without calling SendComplete, and the items do not necessarily need to be completed in the order they were acquired. However, the receiving of data items must occur in FIFO order, therefore not calling SendComplete for the earliest acquired item prevents the subsequent items from being received. The following diagrams illustrate what will happen when SendAcquire and SendComplete do not happen in the same order. At the beginning, there is already a data item of 16 bytes sent to the ring buffer. Then SendAcquire is called to acquire space of 20, 8, 24 bytes on the ring buffer. After that, we fill (use) the buffers, and send them to the ring buffer by SendComplete in the order of 8, 24, 20. When 8 bytes and 24 bytes data are sent, the consumer still can only get the 16 bytes data item. Hence, if SendComplete is not called for the 20 bytes, it will not be available, nor will the data items following the 20 bytes item. When the 20 bytes item is finally completed, all the 3 data items can be received now, in the order of 20, 8, 24 bytes, right after the 16 bytes item existing in the buffer at the beginning. Allow-Split buffers and byte buffers do not allow using SendAcquire or SendComplete since acquired buffers are required to be complete (not wrapped). Wrap Around The following diagrams illustrate the differences between No-Split, Allow-Split, and byte buffers when a sent item requires a wrap around. The diagrams assume a buffer of 128 bytes with 56 bytes of free space that wraps around and a sent item of 28 bytes. No-Split buffers only store an item in continuous free space and do not split an item under any circumstances. When the free space at the tail of the buffer is insufficient to completely store the item and its header, the free space at the tail will be marked as dummy data. The buffer will then wrap around and store the item in the free space at the head of the buffer. Referring to the diagram above, the 16 bytes of free space at the tail of the buffer is insufficient to store the 28 byte item. Therefore, the 16 bytes is marked as dummy data and the item is written to the free space at the head of the buffer instead. Allow-Split buffers will attempt to split the item into two parts when the free space at the tail of the buffer is insufficient to store the item data and its header. Both parts of the split item will have their own headers, therefore incurring an extra 8 bytes of overhead. Referring to the diagram above, the 16 bytes of free space at the tail of the buffer is insufficient to store the 28 byte item. Therefore, the item is split into two parts (8 and 20 bytes) and written as two parts to the buffer. Note Allow-Split buffers treat both parts of the split item as two separate items, therefore call xRingbufferReceiveSplit() instead of xRingbufferReceive() to receive both parts of a split item in a thread safe manner. Byte buffers store as much data as possible into the free space at the tail of buffer. The remaining data will then be stored in the free space at the head of the buffer. No overhead is incurred when wrapping around in byte buffers. Referring to the diagram above, the 16 bytes of free space at the tail of the buffer is insufficient to completely store the 28 bytes of data. Therefore, the 16 bytes of free space is filled with data, and the remaining 12 bytes are written to the free space at the head of the buffer. The buffer now contains data in two separate continuous parts, and each continuous part is treated as a separate item by the byte buffer. Retrieving/Returning The following diagrams illustrate the differences between No-Split and Allow-Split buffers as compared to byte buffers in retrieving and returning data: Items in No-Split buffers and Allow-Split buffers are retrieved in strict FIFO order and must be returned for the occupied space to be freed. Multiple items can be retrieved before returning, and the items do not necessarily need to be returned in the order they were retrieved. However, the freeing of space must occur in FIFO order, therefore not returning the earliest retrieved item prevents the space of subsequent items from being freed. Referring to the diagram above, the 16, 20, and 8 byte items are retrieved in FIFO order. However, the items are not returned in the order they were retrieved. First, the 20 byte item is returned followed by the 8 byte and the 16 byte items. The space is not freed until the first item, i.e., the 16 byte item is returned. Byte buffers do not allow multiple retrievals before returning (every retrieval must be followed by a return before another retrieval is permitted). When using xRingbufferReceive() or xRingbufferReceiveFromISR(), all continuous stored data will be retrieved. xRingbufferReceiveUpTo() or xRingbufferReceiveUpToFromISR() can be used to restrict the maximum number of bytes retrieved. Since every retrieval must be followed by a return, the space is freed as soon as the data is returned. Referring to the diagram above, the 38 bytes of continuous stored data at the tail of the buffer is retrieved, returned, and freed. The next call to xRingbufferReceive() or xRingbufferReceiveFromISR() then wraps around and does the same to the 30 bytes of continuous stored data at the head of the buffer. Ring Buffers with Queue Sets Ring buffers can be added to FreeRTOS queue sets using xRingbufferAddToQueueSetRead() such that every time a ring buffer receives an item or data, the queue set is notified. Once added to a queue set, every attempt to retrieve an item from a ring buffer should be preceded by a call to xQueueSelectFromSet(). To check whether the selected queue set member is the ring buffer, call xRingbufferCanRead(). The following example demonstrates queue set usage with ring buffers: #include "freertos/queue.h" #include "freertos/ringbuf.h" ... //Create ring buffer and queue set RingbufHandle_t buf_handle = xRingbufferCreate(1028, RINGBUF_TYPE_NOSPLIT); QueueSetHandle_t queue_set = xQueueCreateSet(3); //Add ring buffer to queue set if (xRingbufferAddToQueueSetRead(buf_handle, queue_set) != pdTRUE) { printf("Failed to add to queue set\n"); } ... //Block on queue set QueueSetMemberHandle_t member = xQueueSelectFromSet(queue_set, pdMS_TO_TICKS(1000)); //Check if member is ring buffer if (member != NULL && xRingbufferCanRead(buf_handle, member) == pdTRUE) { //Member is ring buffer, receive item from ring buffer size_t item_size; char *item = (char *)xRingbufferReceive(buf_handle, &item_size, 0); //Handle item ... } else { ... } Ring Buffers with Static Allocation The xRingbufferCreateStatic() can be used to create ring buffers with specific memory requirements (such as a ring buffer being allocated in external RAM). All blocks of memory used by a ring buffer must be manually allocated beforehand, then passed to the xRingbufferCreateStatic() to be initialized as a ring buffer. These blocks include the following: The ring buffer's data structure of type StaticRingbuffer_t. The ring buffer's storage area of size xBufferSize. Note that xBufferSizemust be 32-bit aligned for No-Split and Allow-Split buffers. The manner in which these blocks are allocated depends on the users requirements (e.g., all blocks being statically declared, or dynamically allocated with specific capabilities such as external RAM). Note When deleting a ring buffer created via xRingbufferCreateStatic(), the function vRingbufferDelete() will not free any of the memory blocks. This must be done manually by the user after vRingbufferDelete() is called. The code snippet below demonstrates a ring buffer being allocated entirely in external RAM. #include "freertos/ringbuf.h" #include "freertos/semphr.h" #include "esp_heap_caps.h" #define BUFFER_SIZE 400 //32-bit aligned size #define BUFFER_TYPE RINGBUF_TYPE_NOSPLIT ... //Allocate ring buffer data structure and storage area into external RAM StaticRingbuffer_t *buffer_struct = (StaticRingbuffer_t *)heap_caps_malloc(sizeof(StaticRingbuffer_t), MALLOC_CAP_SPIRAM); uint8_t *buffer_storage = (uint8_t *)heap_caps_malloc(sizeof(uint8_t)*BUFFER_SIZE, MALLOC_CAP_SPIRAM); //Create a ring buffer with manually allocated memory RingbufHandle_t handle = xRingbufferCreateStatic(BUFFER_SIZE, BUFFER_TYPE, buffer_storage, buffer_struct); ... //Delete the ring buffer after used vRingbufferDelete(handle); //Manually free all blocks of memory free(buffer_struct); free(buffer_storage); ESP-IDF Tick and Idle Hooks FreeRTOS allows applications to provide a tick hook and an idle hook at compile time: FreeRTOS tick hook can be enabled via the CONFIG_FREERTOS_USE_TICK_HOOK option. The application must provide the void vApplicationTickHook( void )callback. FreeRTOS idle hook can be enabled via the CONFIG_FREERTOS_USE_IDLE_HOOK option. The application must provide the void vApplicationIdleHook( void )callback. However, the FreeRTOS tick hook and idle hook have the following draw backs: The FreeRTOS hooks are registered at compile time Only one of each hook can be registered On multi-core targets, the FreeRTOS hooks are symmetric, meaning each core's tick interrupt and idle tasks ends up calling the same hook Therefore, ESP-IDF tick and idle hooks are provided to supplement the features of FreeRTOS tick and idle hooks. The ESP-IDF hooks have the following features: The hooks can be registered and deregistered at run-time Multiple hooks can be registered (with a maximum of 8 hooks of each type per core) On multi-core targets, the hooks can be asymmetric, meaning different hooks can be registered to each core ESP-IDF hooks can be registered and deregistered using the following APIs: For tick hooks: Register using esp_register_freertos_tick_hook()or esp_register_freertos_tick_hook_for_cpu() Deregister using esp_deregister_freertos_tick_hook()or esp_deregister_freertos_tick_hook_for_cpu() - For idle hooks: Register using esp_register_freertos_idle_hook()or esp_register_freertos_idle_hook_for_cpu() Deregister using esp_deregister_freertos_idle_hook()or esp_deregister_freertos_idle_hook_for_cpu() - Note The tick interrupt stays active while the cache is disabled, therefore any tick hook (FreeRTOS or ESP-IDF) functions must be placed in internal RAM. Please refer to the SPI flash API documentation for more details. TLSP Deletion Callbacks Vanilla FreeRTOS provides a Thread Local Storage Pointers (TLSP) feature. These are pointers stored directly in the Task Control Block (TCB) of a particular task. TLSPs allow each task to have its own unique set of pointers to data structures. Vanilla FreeRTOS expects users to: set a task's TLSPs by calling vTaskSetThreadLocalStoragePointer()after the task has been created. get a task's TLSPs by calling pvTaskGetThreadLocalStoragePointer()during the task's lifetime. free the memory pointed to by the TLSPs before the task is deleted. However, there can be instances where users may want the freeing of TLSP memory to be automatic. Therefore, ESP-IDF provides the additional feature of TLSP deletion callbacks. These user-provided deletion callbacks are called automatically when a task is deleted, thus allowing the TLSP memory to be cleaned up without needing to add the cleanup logic explicitly to the code of every task. The TLSP deletion callbacks are set in a similar fashion to the TLSPs themselves. vTaskSetThreadLocalStoragePointerAndDelCallback()sets both a particular TLSP and its associated callback. Calling the Vanilla FreeRTOS function vTaskSetThreadLocalStoragePointer()simply sets the TLSP's associated Deletion Callback to NULL, meaning that no callback is called for that TLSP during task deletion. When implementing TLSP callbacks, users should note the following: The callback must never attempt to block or yield and critical sections should be kept as short as possible. The callback is called shortly before a deleted task's memory is freed. Thus, the callback can either be called from vTaskDelete()itself, or from the idle task. IDF Additional API The freertos/esp_additions/include/freertos/idf_additions.h header contains FreeRTOS-related helper functions added by ESP-IDF. Users can include this header via #include "freertos/idf_additions.h". Component Specific Properties Besides standard component variables that are available with basic cmake build properties, FreeRTOS component also provides arguments (only one so far) for simpler integration with other modules: ORIG_INCLUDE_PATH - contains an absolute path to freertos root include folder. Thus instead of #include "freertos/FreeRTOS.h" you can refer to headers directly: #include "FreeRTOS.h". API Reference Ring Buffer API Header File This header file can be included with: #include "freertos/ringbuf.h" This header file is a part of the API provided by the esp_ringbufcomponent. To declare that your component depends on esp_ringbuf, add the following to your CMakeLists.txt: REQUIRES esp_ringbuf or PRIV_REQUIRES esp_ringbuf Functions - RingbufHandle_t xRingbufferCreate(size_t xBufferSize, RingbufferType_t xBufferType) Create a ring buffer. Note xBufferSize of no-split/allow-split buffers will be rounded up to the nearest 32-bit aligned size. - Parameters xBufferSize -- [in] Size of the buffer in bytes. Note that items require space for a header in no-split/allow-split buffers xBufferType -- [in] Type of ring buffer, see documentation. - - Returns A handle to the created ring buffer, or NULL in case of error. - RingbufHandle_t xRingbufferCreateNoSplit(size_t xItemSize, size_t xItemNum) Create a ring buffer of type RINGBUF_TYPE_NOSPLIT for a fixed item_size. This API is similar to xRingbufferCreate(), but it will internally allocate additional space for the headers. - Parameters xItemSize -- [in] Size of each item to be put into the ring buffer xItemNum -- [in] Maximum number of items the buffer needs to hold simultaneously - - Returns A RingbufHandle_t handle to the created ring buffer, or NULL in case of error. - RingbufHandle_t xRingbufferCreateStatic(size_t xBufferSize, RingbufferType_t xBufferType, uint8_t *pucRingbufferStorage, StaticRingbuffer_t *pxStaticRingbuffer) Create a ring buffer but manually provide the required memory. Note xBufferSize of no-split/allow-split buffers MUST be 32-bit aligned. - Parameters xBufferSize -- [in] Size of the buffer in bytes. xBufferType -- [in] Type of ring buffer, see documentation pucRingbufferStorage -- [in] Pointer to the ring buffer's storage area. Storage area must have the same size as specified by xBufferSize pxStaticRingbuffer -- [in] Pointed to a struct of type StaticRingbuffer_t which will be used to hold the ring buffer's data structure - - Returns A handle to the created ring buffer - BaseType_t xRingbufferSend(RingbufHandle_t xRingbuffer, const void *pvItem, size_t xItemSize, TickType_t xTicksToWait) Insert an item into the ring buffer. Attempt to insert an item into the ring buffer. This function will block until enough free space is available or until it times out. Note For no-split/allow-split ring buffers, the actual size of memory that the item will occupy will be rounded up to the nearest 32-bit aligned size. This is done to ensure all items are always stored in 32-bit aligned fashion. Note For no-split/allow-split buffers, an xItemSize of 0 will result in an item with no data being set (i.e., item only contains the header). For byte buffers, an xItemSize of 0 will simply return pdTRUE without copying any data. - Parameters xRingbuffer -- [in] Ring buffer to insert the item into pvItem -- [in] Pointer to data to insert. NULL is allowed if xItemSize is 0. xItemSize -- [in] Size of data to insert. xTicksToWait -- [in] Ticks to wait for room in the ring buffer. - - Returns pdTRUE if succeeded pdFALSE on time-out or when the data is larger than the maximum permissible size of the buffer - - BaseType_t xRingbufferSendFromISR(RingbufHandle_t xRingbuffer, const void *pvItem, size_t xItemSize, BaseType_t *pxHigherPriorityTaskWoken) Insert an item into the ring buffer in an ISR. Attempt to insert an item into the ring buffer from an ISR. This function will return immediately if there is insufficient free space in the buffer. Note For no-split/allow-split ring buffers, the actual size of memory that the item will occupy will be rounded up to the nearest 32-bit aligned size. This is done to ensure all items are always stored in 32-bit aligned fashion. Note For no-split/allow-split buffers, an xItemSize of 0 will result in an item with no data being set (i.e., item only contains the header). For byte buffers, an xItemSize of 0 will simply return pdTRUE without copying any data. - Parameters xRingbuffer -- [in] Ring buffer to insert the item into pvItem -- [in] Pointer to data to insert. NULL is allowed if xItemSize is 0. xItemSize -- [in] Size of data to insert. pxHigherPriorityTaskWoken -- [out] Value pointed to will be set to pdTRUE if the function woke up a higher priority task. - - Returns pdTRUE if succeeded pdFALSE when the ring buffer does not have space. - - BaseType_t xRingbufferSendAcquire(RingbufHandle_t xRingbuffer, void **ppvItem, size_t xItemSize, TickType_t xTicksToWait) Acquire memory from the ring buffer to be written to by an external source and to be sent later. Attempt to allocate buffer for an item to be sent into the ring buffer. This function will block until enough free space is available or until it times out. The item, as well as the following items SendAcquireor Sendafter it, will not be able to be read from the ring buffer until this item is actually sent into the ring buffer. Note Only applicable for no-split ring buffers now, the actual size of memory that the item will occupy will be rounded up to the nearest 32-bit aligned size. This is done to ensure all items are always stored in 32-bit aligned fashion. Note An xItemSize of 0 will result in a buffer being acquired, but the buffer will have a size of 0. - Parameters xRingbuffer -- [in] Ring buffer to allocate the memory ppvItem -- [out] Double pointer to memory acquired (set to NULL if no memory were retrieved) xItemSize -- [in] Size of item to acquire. xTicksToWait -- [in] Ticks to wait for room in the ring buffer. - - Returns pdTRUE if succeeded pdFALSE on time-out or when the data is larger than the maximum permissible size of the buffer - - BaseType_t xRingbufferSendComplete(RingbufHandle_t xRingbuffer, void *pvItem) Actually send an item into the ring buffer allocated before by xRingbufferSendAcquire. Note Only applicable for no-split ring buffers. Only call for items allocated by xRingbufferSendAcquire. - Parameters xRingbuffer -- [in] Ring buffer to insert the item into pvItem -- [in] Pointer to item in allocated memory to insert. - - Returns pdTRUE if succeeded pdFALSE if fail for some reason. - - void *xRingbufferReceive(RingbufHandle_t xRingbuffer, size_t *pxItemSize, TickType_t xTicksToWait) Retrieve an item from the ring buffer. Attempt to retrieve an item from the ring buffer. This function will block until an item is available or until it times out. Note A call to vRingbufferReturnItem() is required after this to free the item retrieved. Note It is possible to receive items with a pxItemSize of 0 on no-split/allow split buffers. - Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. xTicksToWait -- [in] Ticks to wait for items in the ring buffer. - - Returns Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL on timeout, *pxItemSize is untouched in that case. - - void *xRingbufferReceiveFromISR(RingbufHandle_t xRingbuffer, size_t *pxItemSize) Retrieve an item from the ring buffer in an ISR. Attempt to retrieve an item from the ring buffer. This function returns immediately if there are no items available for retrieval Note A call to vRingbufferReturnItemFromISR() is required after this to free the item retrieved. Note Byte buffers do not allow multiple retrievals before returning an item Note Two calls to RingbufferReceiveFromISR() are required if the bytes wrap around the end of the ring buffer. Note It is possible to receive items with a pxItemSize of 0 on no-split/allow split buffers. - Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. - - Returns Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL when the ring buffer is empty, *pxItemSize is untouched in that case. - - BaseType_t xRingbufferReceiveSplit(RingbufHandle_t xRingbuffer, void **ppvHeadItem, void **ppvTailItem, size_t *pxHeadItemSize, size_t *pxTailItemSize, TickType_t xTicksToWait) Retrieve a split item from an allow-split ring buffer. Attempt to retrieve a split item from an allow-split ring buffer. If the item is not split, only a single item is retried. If the item is split, both parts will be retrieved. This function will block until an item is available or until it times out. Note Call(s) to vRingbufferReturnItem() is required after this to free up the item(s) retrieved. Note This function should only be called on allow-split buffers Note It is possible to receive items with a pxItemSize of 0 on allow split buffers. - Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from ppvHeadItem -- [out] Double pointer to first part (set to NULL if no items were retrieved) ppvTailItem -- [out] Double pointer to second part (set to NULL if item is not split) pxHeadItemSize -- [out] Pointer to size of first part (unmodified if no items were retrieved) pxTailItemSize -- [out] Pointer to size of second part (unmodified if item is not split) xTicksToWait -- [in] Ticks to wait for items in the ring buffer. - - Returns pdTRUE if an item (split or unsplit) was retrieved pdFALSE when no item was retrieved - - BaseType_t xRingbufferReceiveSplitFromISR(RingbufHandle_t xRingbuffer, void **ppvHeadItem, void **ppvTailItem, size_t *pxHeadItemSize, size_t *pxTailItemSize) Retrieve a split item from an allow-split ring buffer in an ISR. Attempt to retrieve a split item from an allow-split ring buffer. If the item is not split, only a single item is retried. If the item is split, both parts will be retrieved. This function returns immediately if there are no items available for retrieval Note Calls to vRingbufferReturnItemFromISR() is required after this to free up the item(s) retrieved. Note This function should only be called on allow-split buffers Note It is possible to receive items with a pxItemSize of 0 on allow split buffers. - Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from ppvHeadItem -- [out] Double pointer to first part (set to NULL if no items were retrieved) ppvTailItem -- [out] Double pointer to second part (set to NULL if item is not split) pxHeadItemSize -- [out] Pointer to size of first part (unmodified if no items were retrieved) pxTailItemSize -- [out] Pointer to size of second part (unmodified if item is not split) - - Returns pdTRUE if an item (split or unsplit) was retrieved pdFALSE when no item was retrieved - - void *xRingbufferReceiveUpTo(RingbufHandle_t xRingbuffer, size_t *pxItemSize, TickType_t xTicksToWait, size_t xMaxSize) Retrieve bytes from a byte buffer, specifying the maximum amount of bytes to retrieve. Attempt to retrieve data from a byte buffer whilst specifying a maximum number of bytes to retrieve. This function will block until there is data available for retrieval or until it times out. Note A call to vRingbufferReturnItem() is required after this to free up the data retrieved. Note This function should only be called on byte buffers Note Byte buffers do not allow multiple retrievals before returning an item Note Two calls to RingbufferReceiveUpTo() are required if the bytes wrap around the end of the ring buffer. - Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. xTicksToWait -- [in] Ticks to wait for items in the ring buffer. xMaxSize -- [in] Maximum number of bytes to return. - - Returns Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL on timeout, *pxItemSize is untouched in that case. - - void *xRingbufferReceiveUpToFromISR(RingbufHandle_t xRingbuffer, size_t *pxItemSize, size_t xMaxSize) Retrieve bytes from a byte buffer, specifying the maximum amount of bytes to retrieve. Call this from an ISR. Attempt to retrieve bytes from a byte buffer whilst specifying a maximum number of bytes to retrieve. This function will return immediately if there is no data available for retrieval. Note A call to vRingbufferReturnItemFromISR() is required after this to free up the data received. Note This function should only be called on byte buffers Note Byte buffers do not allow multiple retrievals before returning an item - Parameters xRingbuffer -- [in] Ring buffer to retrieve the item from pxItemSize -- [out] Pointer to a variable to which the size of the retrieved item will be written. xMaxSize -- [in] Maximum number of bytes to return. Size of 0 simply returns NULL. - - Returns Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. NULL when the ring buffer is empty, *pxItemSize is untouched in that case. - - void vRingbufferReturnItem(RingbufHandle_t xRingbuffer, void *pvItem) Return a previously-retrieved item to the ring buffer. Note If a split item is retrieved, both parts should be returned by calling this function twice - Parameters xRingbuffer -- [in] Ring buffer the item was retrieved from pvItem -- [in] Item that was received earlier - - void vRingbufferReturnItemFromISR(RingbufHandle_t xRingbuffer, void *pvItem, BaseType_t *pxHigherPriorityTaskWoken) Return a previously-retrieved item to the ring buffer from an ISR. Note If a split item is retrieved, both parts should be returned by calling this function twice - Parameters xRingbuffer -- [in] Ring buffer the item was retrieved from pvItem -- [in] Item that was received earlier pxHigherPriorityTaskWoken -- [out] Value pointed to will be set to pdTRUE if the function woke up a higher priority task. - - void vRingbufferDelete(RingbufHandle_t xRingbuffer) Delete a ring buffer. Note This function will not deallocate any memory if the ring buffer was created using xRingbufferCreateStatic(). Deallocation must be done manually be the user. - Parameters xRingbuffer -- [in] Ring buffer to delete - size_t xRingbufferGetMaxItemSize(RingbufHandle_t xRingbuffer) Get maximum size of an item that can be placed in the ring buffer. This function returns the maximum size an item can have if it was placed in an empty ring buffer. Note The max item size for a no-split buffer is limited to ((buffer_size/2)-header_size). This limit is imposed so that an item of max item size can always be sent to an empty no-split buffer regardless of the internal positions of the buffer's read/write/free pointers. - Parameters xRingbuffer -- [in] Ring buffer to query - Returns Maximum size, in bytes, of an item that can be placed in a ring buffer. - size_t xRingbufferGetCurFreeSize(RingbufHandle_t xRingbuffer) Get current free size available for an item/data in the buffer. This gives the real time free space available for an item/data in the ring buffer. This represents the maximum size an item/data can have if it was currently sent to the ring buffer. Note An empty no-split buffer has a max current free size for an item that is limited to ((buffer_size/2)-header_size). See API reference for xRingbufferGetMaxItemSize(). Warning This API is not thread safe. So, if multiple threads are accessing the same ring buffer, it is the application's responsibility to ensure atomic access to this API and the subsequent Send - Parameters xRingbuffer -- [in] Ring buffer to query - Returns Current free size, in bytes, available for an entry - BaseType_t xRingbufferAddToQueueSetRead(RingbufHandle_t xRingbuffer, QueueSetHandle_t xQueueSet) Add the ring buffer to a queue set. Notified when data has been written to the ring buffer. This function adds the ring buffer to a queue set, thus allowing a task to block on multiple queues/ring buffers. The queue set is notified when the new data becomes available to read on the ring buffer. - Parameters xRingbuffer -- [in] Ring buffer to add to the queue set xQueueSet -- [in] Queue set to add the ring buffer to - - Returns pdTRUE on success, pdFALSE otherwise - - static inline BaseType_t xRingbufferCanRead(RingbufHandle_t xRingbuffer, QueueSetMemberHandle_t xMember) Check if the selected queue set member is a particular ring buffer. This API checks if queue set member returned from xQueueSelectFromSet() is a particular ring buffer. If so, this indicates the ring buffer has items waiting to be retrieved. - Parameters xRingbuffer -- [in] Ring buffer to check xMember -- [in] Member returned from xQueueSelectFromSet - - Returns pdTRUE when selected queue set member is the ring buffer pdFALSE otherwise. - - BaseType_t xRingbufferRemoveFromQueueSetRead(RingbufHandle_t xRingbuffer, QueueSetHandle_t xQueueSet) Remove the ring buffer from a queue set. This function removes a ring buffer from a queue set. The ring buffer must have been previously added to the queue set using xRingbufferAddToQueueSetRead(). - Parameters xRingbuffer -- [in] Ring buffer to remove from the queue set xQueueSet -- [in] Queue set to remove the ring buffer from - - Returns pdTRUE on success pdFALSE otherwise - - void vRingbufferGetInfo(RingbufHandle_t xRingbuffer, UBaseType_t *uxFree, UBaseType_t *uxRead, UBaseType_t *uxWrite, UBaseType_t *uxAcquire, UBaseType_t *uxItemsWaiting) Get information about ring buffer status. Get information of a ring buffer's current status such as free/read/write/acquire pointer positions, and number of items waiting to be retrieved. Arguments can be set to NULL if they are not required. - Parameters xRingbuffer -- [in] Ring buffer to remove from the queue set uxFree -- [out] Pointer use to store free pointer position uxRead -- [out] Pointer use to store read pointer position uxWrite -- [out] Pointer use to store write pointer position uxAcquire -- [out] Pointer use to store acquire pointer position uxItemsWaiting -- [out] Pointer use to store number of items (bytes for byte buffer) waiting to be retrieved - - void xRingbufferPrintInfo(RingbufHandle_t xRingbuffer) Debugging function to print the internal pointers in the ring buffer. - Parameters xRingbuffer -- Ring buffer to show - BaseType_t xRingbufferGetStaticBuffer(RingbufHandle_t xRingbuffer, uint8_t **ppucRingbufferStorage, StaticRingbuffer_t **ppxStaticRingbuffer) Retrieve the pointers to a statically created ring buffer. - Parameters xRingbuffer -- [in] Ring buffer ppucRingbufferStorage -- [out] Used to return a pointer to the queue's storage area buffer ppxStaticRingbuffer -- [out] Used to return a pointer to the queue's data structure buffer - - Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. - RingbufHandle_t xRingbufferCreateWithCaps(size_t xBufferSize, RingbufferType_t xBufferType, UBaseType_t uxMemoryCaps) Creates a ring buffer with specific memory capabilities. This function is similar to xRingbufferCreate(), except that it allows the memory allocated for the ring buffer to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A queue created using this function must only be deleted using vRingbufferDeleteWithCaps() - Parameters xBufferSize -- [in] Size of the buffer in bytes xBufferType -- [in] Type of ring buffer, see documentation. uxMemoryCaps -- [in] Memory capabilities of the queue's memory (see esp_heap_caps.h) - - Returns Handle to the created ring buffer or NULL on failure. - void vRingbufferDeleteWithCaps(RingbufHandle_t xRingbuffer) Deletes a ring buffer previously created using xRingbufferCreateWithCaps() - Parameters xRingbuffer -- Ring buffer Structures - struct xSTATIC_RINGBUFFER Struct that is equivalent in size to the ring buffer's data structure. The contents of this struct are not meant to be used directly. This structure is meant to be used when creating a statically allocated ring buffer where this struct is of the exact size required to store a ring buffer's control data structure. Type Definitions - typedef void *RingbufHandle_t Type by which ring buffers are referenced. For example, a call to xRingbufferCreate() returns a RingbufHandle_t variable that can then be used as a parameter to xRingbufferSend(), xRingbufferReceive(), etc. - typedef struct xSTATIC_RINGBUFFER StaticRingbuffer_t Struct that is equivalent in size to the ring buffer's data structure. The contents of this struct are not meant to be used directly. This structure is meant to be used when creating a statically allocated ring buffer where this struct is of the exact size required to store a ring buffer's control data structure. Enumerations - enum RingbufferType_t Values: - enumerator RINGBUF_TYPE_NOSPLIT No-split buffers will only store an item in contiguous memory and will never split an item. Each item requires an 8 byte overhead for a header and will always internally occupy a 32-bit aligned size of space. - enumerator RINGBUF_TYPE_ALLOWSPLIT Allow-split buffers will split an item into two parts if necessary in order to store it. Each item requires an 8 byte overhead for a header, splitting incurs an extra header. Each item will always internally occupy a 32-bit aligned size of space. - enumerator RINGBUF_TYPE_BYTEBUF Byte buffers store data as a sequence of bytes and do not maintain separate items, therefore byte buffers have no overhead. All data is stored as a sequence of byte and any number of bytes can be sent or retrieved each time. - enumerator RINGBUF_TYPE_MAX - enumerator RINGBUF_TYPE_NOSPLIT Hooks API Header File This header file can be included with: #include "esp_freertos_hooks.h" Functions - esp_err_t esp_register_freertos_idle_hook_for_cpu(esp_freertos_idle_cb_t new_idle_cb, UBaseType_t cpuid) Register a callback to be called from the specified core's idle hook. The callback should return true if it should be called by the idle hook once per interrupt (or FreeRTOS tick), and return false if it should be called repeatedly as fast as possible by the idle hook. Warning Idle callbacks MUST NOT, UNDER ANY CIRCUMSTANCES, CALL A FUNCTION THAT MIGHT BLOCK. - Parameters new_idle_cb -- [in] Callback to be called cpuid -- [in] id of the core - - Returns ESP_OK: Callback registered to the specified core's idle hook ESP_ERR_NO_MEM: No more space on the specified core's idle hook to register callback ESP_ERR_INVALID_ARG: cpuid is invalid - - esp_err_t esp_register_freertos_idle_hook(esp_freertos_idle_cb_t new_idle_cb) Register a callback to the idle hook of the core that calls this function. The callback should return true if it should be called by the idle hook once per interrupt (or FreeRTOS tick), and return false if it should be called repeatedly as fast as possible by the idle hook. Warning Idle callbacks MUST NOT, UNDER ANY CIRCUMSTANCES, CALL A FUNCTION THAT MIGHT BLOCK. - Parameters new_idle_cb -- [in] Callback to be called - Returns ESP_OK: Callback registered to the calling core's idle hook ESP_ERR_NO_MEM: No more space on the calling core's idle hook to register callback - - esp_err_t esp_register_freertos_tick_hook_for_cpu(esp_freertos_tick_cb_t new_tick_cb, UBaseType_t cpuid) Register a callback to be called from the specified core's tick hook. - Parameters new_tick_cb -- [in] Callback to be called cpuid -- [in] id of the core - - Returns ESP_OK: Callback registered to specified core's tick hook ESP_ERR_NO_MEM: No more space on the specified core's tick hook to register the callback ESP_ERR_INVALID_ARG: cpuid is invalid - - esp_err_t esp_register_freertos_tick_hook(esp_freertos_tick_cb_t new_tick_cb) Register a callback to be called from the calling core's tick hook. - Parameters new_tick_cb -- [in] Callback to be called - Returns ESP_OK: Callback registered to the calling core's tick hook ESP_ERR_NO_MEM: No more space on the calling core's tick hook to register the callback - - void esp_deregister_freertos_idle_hook_for_cpu(esp_freertos_idle_cb_t old_idle_cb, UBaseType_t cpuid) Unregister an idle callback from the idle hook of the specified core. - Parameters old_idle_cb -- [in] Callback to be unregistered cpuid -- [in] id of the core - - void esp_deregister_freertos_idle_hook(esp_freertos_idle_cb_t old_idle_cb) Unregister an idle callback. If the idle callback is registered to the idle hooks of both cores, the idle hook will be unregistered from both cores. - Parameters old_idle_cb -- [in] Callback to be unregistered - void esp_deregister_freertos_tick_hook_for_cpu(esp_freertos_tick_cb_t old_tick_cb, UBaseType_t cpuid) Unregister a tick callback from the tick hook of the specified core. - Parameters old_tick_cb -- [in] Callback to be unregistered cpuid -- [in] id of the core - - void esp_deregister_freertos_tick_hook(esp_freertos_tick_cb_t old_tick_cb) Unregister a tick callback. If the tick callback is registered to the tick hooks of both cores, the tick hook will be unregistered from both cores. - Parameters old_tick_cb -- [in] Callback to be unregistered Type Definitions - typedef bool (*esp_freertos_idle_cb_t)(void) - typedef void (*esp_freertos_tick_cb_t)(void) Additional API Header File components/freertos/esp_additions/include/freertos/idf_additions.h This header file can be included with: #include "freertos/idf_additions.h" Functions - BaseType_t xTaskCreatePinnedToCore(TaskFunction_t pxTaskCode, const char *const pcName, const uint32_t ulStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *const pxCreatedTask, const BaseType_t xCoreID) Create a new task that is pinned to a particular core. This function is similar to xTaskCreate(), but allows the creation of a pinned task. The task's pinned core is specified by the xCoreID argument. If xCoreID is set to tskNO_AFFINITY, then the task is unpinned and can run on any core. Note If ( configNUMBER_OF_CORES == 1 ), setting xCoreID to tskNO_AFFINITY will be be treated as 0. - Parameters pxTaskCode -- Pointer to the task entry function. pcName -- A descriptive name for the task. ulStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. pxCreatedTask -- Used to pass back a handle by which the created task can be referenced. xCoreID -- The core to which the task is pinned to, or tskNO_AFFINITY if the task has no core affinity. - - Returns pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined in the file projdefs.h - TaskHandle_t xTaskCreateStaticPinnedToCore(TaskFunction_t pxTaskCode, const char *const pcName, const uint32_t ulStackDepth, void *const pvParameters, UBaseType_t uxPriority, StackType_t *const puxStackBuffer, StaticTask_t *const pxTaskBuffer, const BaseType_t xCoreID) Create a new static task that is pinned to a particular core. This function is similar to xTaskCreateStatic(), but allows the creation of a pinned task. The task's pinned core is specified by the xCoreID argument. If xCoreID is set to tskNO_AFFINITY, then the task is unpinned and can run on any core. Note If ( configNUMBER_OF_CORES == 1 ), setting xCoreID to tskNO_AFFINITY will be be treated as 0. - Parameters pxTaskCode -- Pointer to the task entry function. pcName -- A descriptive name for the task. ulStackDepth -- The size of the task stack specified as the NUMBER OF BYTES. Note that this differs from vanilla FreeRTOS. pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. puxStackBuffer -- Must point to a StackType_t array that has at least ulStackDepth indexes pxTaskBuffer -- Must point to a variable of type StaticTask_t, which will then be used to hold the task's data structures, xCoreID -- The core to which the task is pinned to, or tskNO_AFFINITY if the task has no core affinity. - - Returns The task handle if the task was created, NULL otherwise. - BaseType_t xTaskGetCoreID(TaskHandle_t xTask) Get the current core ID of a particular task. Helper function to get the core ID of a particular task. If the task is pinned to a particular core, the core ID is returned. If the task is not pinned to a particular core, tskNO_AFFINITY is returned. If CONFIG_FREERTOS_UNICORE is enabled, this function simply returns 0. [refactor-todo] See if this needs to be deprecated (IDF-8145)(IDF-8164) Note If CONFIG_FREERTOS_SMP is enabled, please call vTaskCoreAffinityGet() instead. Note In IDF FreerTOS when configNUMBER_OF_CORES == 1, this function will always return 0, - Parameters xTask -- The task to query - Returns The task's core ID or tskNO_AFFINITY - TaskHandle_t xTaskGetIdleTaskHandleForCore(BaseType_t xCoreID) Get the handle of idle task for the given core. [refactor-todo] See if this needs to be deprecated (IDF-8145) Note If CONFIG_FREERTOS_SMP is enabled, please call xTaskGetIdleTaskHandle() instead. - Parameters xCoreID -- The core to query - Returns Handle of the idle task for the queried core - TaskHandle_t xTaskGetCurrentTaskHandleForCore(BaseType_t xCoreID) Get the handle of the task currently running on a certain core. Because of the nature of SMP processing, there is no guarantee that this value will still be valid on return and should only be used for debugging purposes. [refactor-todo] See if this needs to be deprecated (IDF-8145) Note If CONFIG_FREERTOS_SMP is enabled, please call xTaskGetCurrentTaskHandleCPU() instead. - Parameters xCoreID -- The core to query - Returns Handle of the current task running on the queried core - uint8_t *pxTaskGetStackStart(TaskHandle_t xTask) Returns the start of the stack associated with xTask. Returns the lowest stack memory address, regardless of whether the stack grows up or down. [refactor-todo] Change return type to StackType_t (IDF-8158) - Parameters xTask -- Handle of the task associated with the stack returned. Set xTask to NULL to return the stack of the calling task. - Returns A pointer to the start of the stack. - void vTaskSetThreadLocalStoragePointerAndDelCallback(TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue, TlsDeleteCallbackFunction_t pvDelCallback) Set local storage pointer and deletion callback. Each task contains an array of pointers that is dimensioned by the configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The kernel does not use the pointers itself, so the application writer can use the pointers for any purpose they wish. Local storage pointers set for a task can reference dynamically allocated resources. This function is similar to vTaskSetThreadLocalStoragePointer, but provides a way to release these resources when the task gets deleted. For each pointer, a callback function can be set. This function will be called when task is deleted, with the local storage pointer index and value as arguments. - Parameters xTaskToSet -- Task to set thread local storage pointer for xIndex -- The index of the pointer to set, from 0 to configNUM_THREAD_LOCAL_STORAGE_POINTERS - 1. pvValue -- Pointer value to set. pvDelCallback -- Function to call to dispose of the local storage pointer when the task is deleted. - - BaseType_t xTaskCreatePinnedToCoreWithCaps(TaskFunction_t pvTaskCode, const char *const pcName, const configSTACK_DEPTH_TYPE usStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *const pvCreatedTask, const BaseType_t xCoreID, UBaseType_t uxMemoryCaps) Creates a pinned task where its stack has specific memory capabilities. This function is similar to xTaskCreatePinnedToCore(), except that it allows the memory allocated for the task's stack to have specific capabilities (e.g., MALLOC_CAP_SPIRAM). However, the specified capabilities will NOT apply to the task's TCB as a TCB must always be in internal RAM. - Parameters pvTaskCode -- Pointer to the task entry function pcName -- A descriptive name for the task usStackDepth -- The size of the task stack specified as the number of bytes pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. pvCreatedTask -- Used to pass back a handle by which the created task can be referenced. xCoreID -- Core to which the task is pinned to, or tskNO_AFFINITY if unpinned. uxMemoryCaps -- Memory capabilities of the task stack's memory (see esp_heap_caps.h) - - Returns pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined in the file projdefs.h - static inline BaseType_t xTaskCreateWithCaps(TaskFunction_t pvTaskCode, const char *const pcName, configSTACK_DEPTH_TYPE usStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *pvCreatedTask, UBaseType_t uxMemoryCaps) Creates a task where its stack has specific memory capabilities. This function is similar to xTaskCreate(), except that it allows the memory allocated for the task's stack to have specific capabilities (e.g., MALLOC_CAP_SPIRAM). However, the specified capabilities will NOT apply to the task's TCB as a TCB must always be in internal RAM. Note A task created using this function must only be deleted using vTaskDeleteWithCaps() - Parameters pvTaskCode -- Pointer to the task entry function pcName -- A descriptive name for the task usStackDepth -- The size of the task stack specified as the number of bytes pvParameters -- Pointer that will be used as the parameter for the task being created. uxPriority -- The priority at which the task should run. pvCreatedTask -- Used to pass back a handle by which the created task can be referenced. uxMemoryCaps -- Memory capabilities of the task stack's memory (see esp_heap_caps.h) - - Returns pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined in the file projdefs.h - void vTaskDeleteWithCaps(TaskHandle_t xTaskToDelete) Deletes a task previously created using xTaskCreateWithCaps() or xTaskCreatePinnedToCoreWithCaps() - Parameters xTaskToDelete -- A handle to the task to be deleted - QueueHandle_t xQueueCreateWithCaps(UBaseType_t uxQueueLength, UBaseType_t uxItemSize, UBaseType_t uxMemoryCaps) Creates a queue with specific memory capabilities. This function is similar to xQueueCreate(), except that it allows the memory allocated for the queue to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A queue created using this function must only be deleted using vQueueDeleteWithCaps() - Parameters uxQueueLength -- The maximum number of items that the queue can contain. uxItemSize -- The number of bytes each item in the queue will require. uxMemoryCaps -- Memory capabilities of the queue's memory (see esp_heap_caps.h) - - Returns Handle to the created queue or NULL on failure. - void vQueueDeleteWithCaps(QueueHandle_t xQueue) Deletes a queue previously created using xQueueCreateWithCaps() - Parameters xQueue -- A handle to the queue to be deleted. - static inline SemaphoreHandle_t xSemaphoreCreateBinaryWithCaps(UBaseType_t uxMemoryCaps) Creates a binary semaphore with specific memory capabilities. This function is similar to vSemaphoreCreateBinary(), except that it allows the memory allocated for the binary semaphore to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A binary semaphore created using this function must only be deleted using vSemaphoreDeleteWithCaps() - Parameters uxMemoryCaps -- Memory capabilities of the binary semaphore's memory (see esp_heap_caps.h) - Returns Handle to the created binary semaphore or NULL on failure. - static inline SemaphoreHandle_t xSemaphoreCreateCountingWithCaps(UBaseType_t uxMaxCount, UBaseType_t uxInitialCount, UBaseType_t uxMemoryCaps) Creates a counting semaphore with specific memory capabilities. This function is similar to xSemaphoreCreateCounting(), except that it allows the memory allocated for the counting semaphore to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A counting semaphore created using this function must only be deleted using vSemaphoreDeleteWithCaps() - Parameters uxMaxCount -- The maximum count value that can be reached. uxInitialCount -- The count value assigned to the semaphore when it is created. uxMemoryCaps -- Memory capabilities of the counting semaphore's memory (see esp_heap_caps.h) - - Returns Handle to the created counting semaphore or NULL on failure. - static inline SemaphoreHandle_t xSemaphoreCreateMutexWithCaps(UBaseType_t uxMemoryCaps) Creates a mutex semaphore with specific memory capabilities. This function is similar to xSemaphoreCreateMutex(), except that it allows the memory allocated for the mutex semaphore to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A mutex semaphore created using this function must only be deleted using vSemaphoreDeleteWithCaps() - Parameters uxMemoryCaps -- Memory capabilities of the mutex semaphore's memory (see esp_heap_caps.h) - Returns Handle to the created mutex semaphore or NULL on failure. - static inline SemaphoreHandle_t xSemaphoreCreateRecursiveMutexWithCaps(UBaseType_t uxMemoryCaps) Creates a recursive mutex with specific memory capabilities. This function is similar to xSemaphoreCreateRecursiveMutex(), except that it allows the memory allocated for the recursive mutex to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A recursive mutex created using this function must only be deleted using vSemaphoreDeleteWithCaps() - Parameters uxMemoryCaps -- Memory capabilities of the recursive mutex's memory (see esp_heap_caps.h) - Returns Handle to the created recursive mutex or NULL on failure. - void vSemaphoreDeleteWithCaps(SemaphoreHandle_t xSemaphore) Deletes a semaphore previously created using one of the xSemaphoreCreate...WithCaps() functions. - Parameters xSemaphore -- A handle to the semaphore to be deleted. - static inline StreamBufferHandle_t xStreamBufferCreateWithCaps(size_t xBufferSizeBytes, size_t xTriggerLevelBytes, UBaseType_t uxMemoryCaps) Creates a stream buffer with specific memory capabilities. This function is similar to xStreamBufferCreate(), except that it allows the memory allocated for the stream buffer to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A stream buffer created using this function must only be deleted using vStreamBufferDeleteWithCaps() - Parameters xBufferSizeBytes -- The total number of bytes the stream buffer will be able to hold at any one time. xTriggerLevelBytes -- The number of bytes that must be in the stream buffer before unblocking uxMemoryCaps -- Memory capabilities of the stream buffer's memory (see esp_heap_caps.h) - - Returns Handle to the created stream buffer or NULL on failure. - static inline void vStreamBufferDeleteWithCaps(StreamBufferHandle_t xStreamBuffer) Deletes a stream buffer previously created using xStreamBufferCreateWithCaps() - Parameters xStreamBuffer -- A handle to the stream buffer to be deleted. - static inline MessageBufferHandle_t xMessageBufferCreateWithCaps(size_t xBufferSizeBytes, UBaseType_t uxMemoryCaps) Creates a message buffer with specific memory capabilities. This function is similar to xMessageBufferCreate(), except that it allows the memory allocated for the message buffer to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note A message buffer created using this function must only be deleted using vMessageBufferDeleteWithCaps() - Parameters xBufferSizeBytes -- The total number of bytes (not messages) the message buffer will be able to hold at any one time. uxMemoryCaps -- Memory capabilities of the message buffer's memory (see esp_heap_caps.h) - - Returns Handle to the created message buffer or NULL on failure. - static inline void vMessageBufferDeleteWithCaps(MessageBufferHandle_t xMessageBuffer) Deletes a stream buffer previously created using xMessageBufferCreateWithCaps() - Parameters xMessageBuffer -- A handle to the message buffer to be deleted. - EventGroupHandle_t xEventGroupCreateWithCaps(UBaseType_t uxMemoryCaps) Creates an event group with specific memory capabilities. This function is similar to xEventGroupCreate(), except that it allows the memory allocated for the event group to have specific capabilities (e.g., MALLOC_CAP_INTERNAL). Note An event group created using this function must only be deleted using vEventGroupDeleteWithCaps() - Parameters uxMemoryCaps -- Memory capabilities of the event group's memory (see esp_heap_caps.h) - Returns Handle to the created event group or NULL on failure. - void vEventGroupDeleteWithCaps(EventGroupHandle_t xEventGroup) Deletes an event group previously created using xEventGroupCreateWithCaps() - Parameters xEventGroup -- A handle to the event group to be deleted. Type Definitions - typedef void (*TlsDeleteCallbackFunction_t)(int, void*) Prototype of local storage pointer deletion callback.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/freertos_additions.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Heap Memory Allocation
null
espressif.com
2016-01-01
a2fffd90f4b380e8
null
null
Heap Memory Allocation Stack and Heap ESP-IDF applications use the common computer architecture patterns of stack (dynamic memory allocated by program control flow), heap (dynamic memory allocated by function calls), and static memory (memory allocated at compile time). Because ESP-IDF is a multi-threaded RTOS environment, each RTOS task has its own stack. By default, each of these stacks is allocated from the heap when the task is created. See xTaskCreateStatic() for the alternative where stacks are statically allocated. Because ESP32 uses multiple types of RAM, it also contains multiple heaps with different capabilities. A capabilities-based memory allocator allows apps to make heap allocations for different purposes. For most purposes, the C Standard Library's malloc() and free() functions can be used for heap allocation without any special consideration. However, in order to fully make use of all of the memory types and their characteristics, ESP-IDF also has a capabilities-based heap memory allocator. If you want to have a memory with certain properties (e.g., DMA-Capable Memory or executable-memory), you can create an OR-mask of the required capabilities and pass that to heap_caps_malloc() . Memory Capabilities The ESP32 contains multiple types of RAM: DRAM (Data RAM) is memory that is connected to CPU's data bus and is used to hold data. This is the most common kind of memory accessed as a heap. IRAM (Instruction RAM) is memory that is connected to the CPU's instruction bus and usually holds executable data only (i.e., instructions). If accessed as generic memory, all accesses must be aligned to 32-Bit Accessible Memory. D/IRAM is RAM that is connected to CPU's data bus and instruction bus, thus can be used either Instruction or Data RAM. For more details on these internal memory types, see Memory Types. It is also possible to connect external SPI RAM to the ESP32. The external RAM is integrated into the ESP32's memory map via the cache, and accessed similarly to DRAM. All DRAM memory is single-byte accessible, thus all DRAM heaps possess the MALLOC_CAP_8BIT capability. Users can call heap_caps_get_free_size(MALLOC_CAP_8BIT) to get the free size of all DRAM heaps. If ran out of MALLOC_CAP_8BIT , the users can use MALLOC_CAP_IRAM_8BIT instead. In that case, IRAM can still be used as a "reserve" pool of internal memory if the users only access it in a 32-bit aligned manner, or if they enable CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY) . When calling malloc() , the ESP-IDF malloc() internally calls heap_caps_malloc_default(size) . This will allocate memory with the capability MALLOC_CAP_DEFAULT , which is byte-addressable. Because malloc() uses the capabilities-based allocation system, memory allocated using heap_caps_malloc() can be freed by calling the standard free() function. Available Heap DRAM At startup, the DRAM heap contains all data memory that is not statically allocated by the app. Reducing statically-allocated buffers increases the amount of available free heap. To find the amount of statically allocated memory, use the idf.py size command. Note See the DRAM (Data RAM) section for more details about the DRAM usage limitations. Note At runtime, the available heap DRAM may be less than calculated at compile time, because, at startup, some memory is allocated from the heap before the FreeRTOS scheduler is started (including memory for the stacks of initial FreeRTOS tasks). IRAM At startup, the IRAM heap contains all instruction memory that is not used by the app executable code. The idf.py size command can be used to find the amount of IRAM used by the app. D/IRAM Some memory in the ESP32 is available as either DRAM or IRAM. If memory is allocated from a D/IRAM region, the free heap size for both types of memory will decrease. Heap Sizes At startup, all ESP-IDF apps log a summary of all heap addresses (and sizes) at level Info: I (252) heap_init: Initializing. RAM available for dynamic allocation: I (259) heap_init: At 3FFAE6E0 len 00001920 (6 KiB): DRAM I (265) heap_init: At 3FFB2EC8 len 0002D138 (180 KiB): DRAM I (272) heap_init: At 3FFE0440 len 00003AE0 (14 KiB): D/IRAM I (278) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM I (284) heap_init: At 4008944C len 00016BB4 (90 KiB): IRAM Finding Available Heap See Heap Information. Special Capabilities DMA-Capable Memory Use the MALLOC_CAP_DMA flag to allocate memory which is suitable for use with hardware DMA engines (for example SPI and I2S). This capability flag excludes any external PSRAM. 32-Bit Accessible Memory If a certain memory structure is only addressed in 32-bit units, for example, an array of ints or pointers, it can be useful to allocate it with the MALLOC_CAP_32BIT flag. This also allows the allocator to give out IRAM memory, which is sometimes unavailable for a normal malloc() call. This can help to use all the available memory in the ESP32. Please note that on ESP32 series chips, MALLOC_CAP_32BIT cannot be used for storing floating-point variables. This is because MALLOC_CAP_32BIT may return instruction RAM and the floating-point assembly instructions on ESP32 cannot access instruction RAM. Memory allocated with MALLOC_CAP_32BIT can only be accessed via 32-bit reads and writes, any other type of access will generate a fatal LoadStoreError exception. External SPI Memory When external RAM is enabled, external SPI RAM can be allocated using standard malloc calls, or via heap_caps_malloc(MALLOC_CAP_SPIRAM) , depending on the configuration. See Configuring External RAM for more details. On ESP32 only external SPI RAM under 4 MiB in size can be allocated this way. To use the region above the 4 MiB limit, you can use the himem API. Thread Safety Heap functions are thread-safe, meaning they can be called from different tasks simultaneously without any limitations. It is technically possible to call malloc , free , and related functions from interrupt handler (ISR) context (see Calling Heap-Related Functions from ISR). However, this is not recommended, as heap function calls may delay other interrupts. It is strongly recommended to refactor applications so that any buffers used by an ISR are pre-allocated outside of the ISR. Support for calling heap functions from ISRs may be removed in a future update. Heap Tracing & Debugging The following features are documented on the Heap Memory Debugging page: Heap Information (free space, etc.) Heap Tracing (memory leak detection, monitoring, etc.) Implementation Notes Knowledge about the regions of memory in the chip comes from the "SoC" component, which contains memory layout information for the chip, and the different capabilities of each region. Each region's capabilities are prioritized, so that (for example) dedicated DRAM and IRAM regions are used for allocations ahead of the more versatile D/IRAM regions. Each contiguous region of memory contains its own memory heap. The heaps are created using the multi_heap functionality. multi_heap allows any contiguous region of memory to be used as a heap. The heap capabilities allocator uses knowledge of the memory regions to initialize each individual heap. Allocation functions in the heap capabilities API will find the most appropriate heap for the allocation based on desired capabilities, available space, and preferences for each region's use, and then calling multi_heap_malloc() for the heap situated in that particular region. Calling free() involves finding the particular heap corresponding to the freed address, and then call multi_heap_free() on that particular multi_heap instance. API Reference - Heap Allocation Header File This header file can be included with: #include "esp_heap_caps.h" Functions esp_err_t heap_caps_register_failed_alloc_callback(esp_alloc_failed_hook_t callback) registers a callback function to be invoked if a memory allocation operation fails Parameters callback -- caller defined callback to be invoked Returns ESP_OK if callback was registered. Parameters callback -- caller defined callback to be invoked Returns ESP_OK if callback was registered. void *heap_caps_malloc(size_t size, uint32_t caps) Allocate a chunk of memory which has the given capabilities. Equivalent semantics to libc malloc(), for capability-aware memory. Parameters size -- Size, in bytes, of the amount of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned size -- Size, in bytes, of the amount of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned size -- Size, in bytes, of the amount of memory to allocate Returns A pointer to the memory allocated on success, NULL on failure Parameters size -- Size, in bytes, of the amount of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned Returns A pointer to the memory allocated on success, NULL on failure void heap_caps_free(void *ptr) Free memory previously allocated via heap_caps_malloc() or heap_caps_realloc(). Equivalent semantics to libc free(), for capability-aware memory. In IDF, free(p) is equivalent to heap_caps_free(p) . Parameters ptr -- Pointer to memory previously returned from heap_caps_malloc() or heap_caps_realloc(). Can be NULL. Parameters ptr -- Pointer to memory previously returned from heap_caps_malloc() or heap_caps_realloc(). Can be NULL. void *heap_caps_realloc(void *ptr, size_t size, uint32_t caps) Reallocate memory previously allocated via heap_caps_malloc() or heap_caps_realloc(). Equivalent semantics to libc realloc(), for capability-aware memory. In IDF, realloc(p, s) is equivalent to heap_caps_realloc(p, s, MALLOC_CAP_8BIT) . 'caps' parameter can be different to the capabilities that any original 'ptr' was allocated with. In this way, realloc can be used to "move" a buffer if necessary to ensure it meets a new set of capabilities. Parameters ptr -- Pointer to previously allocated memory, or NULL for a new allocation. size -- Size of the new buffer requested, or 0 to free the buffer. caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory desired for the new allocation. ptr -- Pointer to previously allocated memory, or NULL for a new allocation. size -- Size of the new buffer requested, or 0 to free the buffer. caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory desired for the new allocation. ptr -- Pointer to previously allocated memory, or NULL for a new allocation. Returns Pointer to a new buffer of size 'size' with capabilities 'caps', or NULL if allocation failed. Parameters ptr -- Pointer to previously allocated memory, or NULL for a new allocation. size -- Size of the new buffer requested, or 0 to free the buffer. caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory desired for the new allocation. Returns Pointer to a new buffer of size 'size' with capabilities 'caps', or NULL if allocation failed. void *heap_caps_aligned_alloc(size_t alignment, size_t size, uint32_t caps) Allocate an aligned chunk of memory which has the given capabilities. Equivalent semantics to libc aligned_alloc(), for capability-aware memory. Parameters alignment -- How the pointer received needs to be aligned must be a power of two size -- Size, in bytes, of the amount of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned alignment -- How the pointer received needs to be aligned must be a power of two size -- Size, in bytes, of the amount of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned alignment -- How the pointer received needs to be aligned must be a power of two Returns A pointer to the memory allocated on success, NULL on failure Parameters alignment -- How the pointer received needs to be aligned must be a power of two size -- Size, in bytes, of the amount of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned Returns A pointer to the memory allocated on success, NULL on failure void heap_caps_aligned_free(void *ptr) Used to deallocate memory previously allocated with heap_caps_aligned_alloc. Note This function is deprecated, please consider using heap_caps_free() instead Parameters ptr -- Pointer to the memory allocated Parameters ptr -- Pointer to the memory allocated void *heap_caps_aligned_calloc(size_t alignment, size_t n, size_t size, uint32_t caps) Allocate an aligned chunk of memory which has the given capabilities. The initialized value in the memory is set to zero. Parameters alignment -- How the pointer received needs to be aligned must be a power of two n -- Number of continuing chunks of memory to allocate size -- Size, in bytes, of a chunk of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned alignment -- How the pointer received needs to be aligned must be a power of two n -- Number of continuing chunks of memory to allocate size -- Size, in bytes, of a chunk of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned alignment -- How the pointer received needs to be aligned must be a power of two Returns A pointer to the memory allocated on success, NULL on failure Parameters alignment -- How the pointer received needs to be aligned must be a power of two n -- Number of continuing chunks of memory to allocate size -- Size, in bytes, of a chunk of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned Returns A pointer to the memory allocated on success, NULL on failure void *heap_caps_calloc(size_t n, size_t size, uint32_t caps) Allocate a chunk of memory which has the given capabilities. The initialized value in the memory is set to zero. Equivalent semantics to libc calloc(), for capability-aware memory. In IDF, calloc(p) is equivalent to heap_caps_calloc(p, MALLOC_CAP_8BIT) . Parameters n -- Number of continuing chunks of memory to allocate size -- Size, in bytes, of a chunk of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned n -- Number of continuing chunks of memory to allocate size -- Size, in bytes, of a chunk of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned n -- Number of continuing chunks of memory to allocate Returns A pointer to the memory allocated on success, NULL on failure Parameters n -- Number of continuing chunks of memory to allocate size -- Size, in bytes, of a chunk of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned Returns A pointer to the memory allocated on success, NULL on failure size_t heap_caps_get_total_size(uint32_t caps) Get the total size of all the regions that have the given capabilities. This function takes all regions capable of having the given capabilities allocated in them and adds up the total space they have. Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory Returns total size in bytes Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory Returns total size in bytes size_t heap_caps_get_free_size(uint32_t caps) Get the total free size of all the regions that have the given capabilities. This function takes all regions capable of having the given capabilities allocated in them and adds up the free space they have. Note Note that because of heap fragmentation it is probably not possible to allocate a single block of memory of this size. Use heap_caps_get_largest_free_block() for this purpose. Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory Returns Amount of free bytes in the regions Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory Returns Amount of free bytes in the regions size_t heap_caps_get_minimum_free_size(uint32_t caps) Get the total minimum free memory of all regions with the given capabilities. This adds all the low watermarks of the regions capable of delivering the memory with the given capabilities. Note Note the result may be less than the global all-time minimum available heap of this kind, as "low watermarks" are tracked per-region. Individual regions' heaps may have reached their "low watermarks" at different points in time. However, this result still gives a "worst case" indication for all-time minimum free heap. Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory Returns Amount of free bytes in the regions Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory Returns Amount of free bytes in the regions size_t heap_caps_get_largest_free_block(uint32_t caps) Get the largest free block of memory able to be allocated with the given capabilities. Returns the largest value of s for which heap_caps_malloc(s, caps) will succeed. Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory Returns Size of the largest free block in bytes. Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory Returns Size of the largest free block in bytes. void heap_caps_get_info(multi_heap_info_t *info, uint32_t caps) Get heap info for all regions with the given capabilities. Calls multi_heap_info() on all heaps which share the given capabilities. The information returned is an aggregate across all matching heaps. The meanings of fields are the same as defined for multi_heap_info_t, except that minimum_free_bytes has the same caveats described in heap_caps_get_minimum_free_size(). Parameters info -- Pointer to a structure which will be filled with relevant heap metadata. caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory info -- Pointer to a structure which will be filled with relevant heap metadata. caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory info -- Pointer to a structure which will be filled with relevant heap metadata. Parameters info -- Pointer to a structure which will be filled with relevant heap metadata. caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory void heap_caps_print_heap_info(uint32_t caps) Print a summary of all memory with the given capabilities. Calls multi_heap_info on all heaps which share the given capabilities, and prints a two-line summary for each, then a total summary. Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory bool heap_caps_check_integrity_all(bool print_errors) Check integrity of all heap memory in the system. Calls multi_heap_check on all heaps. Optionally print errors if heaps are corrupt. Calling this function is equivalent to calling heap_caps_check_integrity with the caps argument set to MALLOC_CAP_INVALID. Note Please increase the value of CONFIG_ESP_INT_WDT_TIMEOUT_MS when using this API with PSRAM enabled. Parameters print_errors -- Print specific errors if heap corruption is found. Returns True if all heaps are valid, False if at least one heap is corrupt. Parameters print_errors -- Print specific errors if heap corruption is found. Returns True if all heaps are valid, False if at least one heap is corrupt. bool heap_caps_check_integrity(uint32_t caps, bool print_errors) Check integrity of all heaps with the given capabilities. Calls multi_heap_check on all heaps which share the given capabilities. Optionally print errors if the heaps are corrupt. See also heap_caps_check_integrity_all to check all heap memory in the system and heap_caps_check_integrity_addr to check memory around a single address. Note Please increase the value of CONFIG_ESP_INT_WDT_TIMEOUT_MS when using this API with PSRAM capability flag. Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory print_errors -- Print specific errors if heap corruption is found. caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory print_errors -- Print specific errors if heap corruption is found. caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory Returns True if all heaps are valid, False if at least one heap is corrupt. Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory print_errors -- Print specific errors if heap corruption is found. Returns True if all heaps are valid, False if at least one heap is corrupt. bool heap_caps_check_integrity_addr(intptr_t addr, bool print_errors) Check integrity of heap memory around a given address. This function can be used to check the integrity of a single region of heap memory, which contains the given address. This can be useful if debugging heap integrity for corruption at a known address, as it has a lower overhead than checking all heap regions. Note that if the corrupt address moves around between runs (due to timing or other factors) then this approach won't work, and you should call heap_caps_check_integrity or heap_caps_check_integrity_all instead. Note The entire heap region around the address is checked, not only the adjacent heap blocks. Parameters addr -- Address in memory. Check for corruption in region containing this address. print_errors -- Print specific errors if heap corruption is found. addr -- Address in memory. Check for corruption in region containing this address. print_errors -- Print specific errors if heap corruption is found. addr -- Address in memory. Check for corruption in region containing this address. Returns True if the heap containing the specified address is valid, False if at least one heap is corrupt or the address doesn't belong to a heap region. Parameters addr -- Address in memory. Check for corruption in region containing this address. print_errors -- Print specific errors if heap corruption is found. Returns True if the heap containing the specified address is valid, False if at least one heap is corrupt or the address doesn't belong to a heap region. void heap_caps_malloc_extmem_enable(size_t limit) Enable malloc() in external memory and set limit below which malloc() attempts are placed in internal memory. When external memory is in use, the allocation strategy is to initially try to satisfy smaller allocation requests with internal memory and larger requests with external memory. This sets the limit between the two, as well as generally enabling allocation in external memory. Parameters limit -- Limit, in bytes. Parameters limit -- Limit, in bytes. void *heap_caps_malloc_prefer(size_t size, size_t num, ...) Allocate a chunk of memory as preference in decreasing order. Attention The variable parameters are bitwise OR of MALLOC_CAP_* flags indicating the type of memory. This API prefers to allocate memory with the first parameter. If failed, allocate memory with the next parameter. It will try in this order until allocating a chunk of memory successfully or fail to allocate memories with any of the parameters. Attention The variable parameters are bitwise OR of MALLOC_CAP_* flags indicating the type of memory. This API prefers to allocate memory with the first parameter. If failed, allocate memory with the next parameter. It will try in this order until allocating a chunk of memory successfully or fail to allocate memories with any of the parameters. Parameters size -- Size, in bytes, of the amount of memory to allocate num -- Number of variable parameters size -- Size, in bytes, of the amount of memory to allocate num -- Number of variable parameters size -- Size, in bytes, of the amount of memory to allocate Returns A pointer to the memory allocated on success, NULL on failure Parameters size -- Size, in bytes, of the amount of memory to allocate num -- Number of variable parameters Returns A pointer to the memory allocated on success, NULL on failure void *heap_caps_realloc_prefer(void *ptr, size_t size, size_t num, ...) Reallocate a chunk of memory as preference in decreasing order. Parameters ptr -- Pointer to previously allocated memory, or NULL for a new allocation. size -- Size of the new buffer requested, or 0 to free the buffer. num -- Number of variable paramters ptr -- Pointer to previously allocated memory, or NULL for a new allocation. size -- Size of the new buffer requested, or 0 to free the buffer. num -- Number of variable paramters ptr -- Pointer to previously allocated memory, or NULL for a new allocation. Returns Pointer to a new buffer of size 'size', or NULL if allocation failed. Parameters ptr -- Pointer to previously allocated memory, or NULL for a new allocation. size -- Size of the new buffer requested, or 0 to free the buffer. num -- Number of variable paramters Returns Pointer to a new buffer of size 'size', or NULL if allocation failed. void *heap_caps_calloc_prefer(size_t n, size_t size, size_t num, ...) Allocate a chunk of memory as preference in decreasing order. Parameters n -- Number of continuing chunks of memory to allocate size -- Size, in bytes, of a chunk of memory to allocate num -- Number of variable paramters n -- Number of continuing chunks of memory to allocate size -- Size, in bytes, of a chunk of memory to allocate num -- Number of variable paramters n -- Number of continuing chunks of memory to allocate Returns A pointer to the memory allocated on success, NULL on failure Parameters n -- Number of continuing chunks of memory to allocate size -- Size, in bytes, of a chunk of memory to allocate num -- Number of variable paramters Returns A pointer to the memory allocated on success, NULL on failure void heap_caps_dump(uint32_t caps) Dump the full structure of all heaps with matching capabilities. Prints a large amount of output to serial (because of locking limitations, the output bypasses stdout/stderr). For each (variable sized) block in each matching heap, the following output is printed on a single line: Block address (the data buffer returned by malloc is 4 bytes after this if heap debugging is set to Basic, or 8 bytes otherwise). Data size (the data size may be larger than the size requested by malloc, either due to heap fragmentation or because of heap debugging level). Address of next block in the heap. If the block is free, the address of the next free block is also printed. Block address (the data buffer returned by malloc is 4 bytes after this if heap debugging is set to Basic, or 8 bytes otherwise). Data size (the data size may be larger than the size requested by malloc, either due to heap fragmentation or because of heap debugging level). Address of next block in the heap. If the block is free, the address of the next free block is also printed. Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory Block address (the data buffer returned by malloc is 4 bytes after this if heap debugging is set to Basic, or 8 bytes otherwise). void heap_caps_dump_all(void) Dump the full structure of all heaps. Covers all registered heaps. Prints a large amount of output to serial. Output is the same as for heap_caps_dump. size_t heap_caps_get_allocated_size(void *ptr) Return the size that a particular pointer was allocated with. Note The app will crash with an assertion failure if the pointer is not valid. Parameters ptr -- Pointer to currently allocated heap memory. Must be a pointer value previously returned by heap_caps_malloc, malloc, calloc, etc. and not yet freed. Returns Size of the memory allocated at this block. Parameters ptr -- Pointer to currently allocated heap memory. Must be a pointer value previously returned by heap_caps_malloc, malloc, calloc, etc. and not yet freed. Returns Size of the memory allocated at this block. Macros HEAP_IRAM_ATTR MALLOC_CAP_EXEC Flags to indicate the capabilities of the various memory systems. Memory must be able to run executable code MALLOC_CAP_32BIT Memory must allow for aligned 32-bit data accesses. MALLOC_CAP_8BIT Memory must allow for 8/16/...-bit data accesses. MALLOC_CAP_DMA Memory must be able to accessed by DMA. MALLOC_CAP_PID2 Memory must be mapped to PID2 memory space (PIDs are not currently used) MALLOC_CAP_PID3 Memory must be mapped to PID3 memory space (PIDs are not currently used) MALLOC_CAP_PID4 Memory must be mapped to PID4 memory space (PIDs are not currently used) MALLOC_CAP_PID5 Memory must be mapped to PID5 memory space (PIDs are not currently used) MALLOC_CAP_PID6 Memory must be mapped to PID6 memory space (PIDs are not currently used) MALLOC_CAP_PID7 Memory must be mapped to PID7 memory space (PIDs are not currently used) MALLOC_CAP_SPIRAM Memory must be in SPI RAM. MALLOC_CAP_INTERNAL Memory must be internal; specifically it should not disappear when flash/spiram cache is switched off. MALLOC_CAP_DEFAULT Memory can be returned in a non-capability-specific memory allocation (e.g. malloc(), calloc()) call. MALLOC_CAP_IRAM_8BIT Memory must be in IRAM and allow unaligned access. MALLOC_CAP_RETENTION Memory must be able to accessed by retention DMA. MALLOC_CAP_RTCRAM Memory must be in RTC fast memory. MALLOC_CAP_TCM Memory must be in TCM memory. MALLOC_CAP_INVALID Memory can't be used / list end marker. Type Definitions typedef void (*esp_alloc_failed_hook_t)(size_t size, uint32_t caps, const char *function_name) callback called when an allocation operation fails, if registered Param size in bytes of failed allocation Param caps capabilities requested of failed allocation Param function_name function which generated the failure Param size in bytes of failed allocation Param caps capabilities requested of failed allocation Param function_name function which generated the failure API Reference - Initialisation Header File This header file can be included with: #include "esp_heap_caps_init.h" Functions void heap_caps_init(void) Initialize the capability-aware heap allocator. This is called once in the IDF startup code. Do not call it at other times. void heap_caps_enable_nonos_stack_heaps(void) Enable heap(s) in memory regions where the startup stacks are located. On startup, the pro/app CPUs have a certain memory region they use as stack, so we cannot do allocations in the regions these stack frames are. When FreeRTOS is completely started, they do not use that memory anymore and heap(s) there can be enabled. esp_err_t heap_caps_add_region(intptr_t start, intptr_t end) Add a region of memory to the collection of heaps at runtime. Most memory regions are defined in soc_memory_layout.c for the SoC, and are registered via heap_caps_init(). Some regions can't be used immediately and are later enabled via heap_caps_enable_nonos_stack_heaps(). Call this function to add a region of memory to the heap at some later time. This function does not consider any of the "reserved" regions or other data in soc_memory_layout, caller needs to consider this themselves. All memory within the region specified by start & end parameters must be otherwise unused. The capabilities of the newly registered memory will be determined by the start address, as looked up in the regions specified in soc_memory_layout.c. Use heap_caps_add_region_with_caps() to register a region with custom capabilities. Note Please refer to following example for memory regions allowed for addition to heap based on an existing region (address range for demonstration purpose only): Existing region: 0x1000 <-> 0x3000 New region: 0x1000 <-> 0x3000 (Allowed) New region: 0x1000 <-> 0x2000 (Allowed) New region: 0x0000 <-> 0x1000 (Allowed) New region: 0x3000 <-> 0x4000 (Allowed) New region: 0x0000 <-> 0x2000 (NOT Allowed) New region: 0x0000 <-> 0x4000 (NOT Allowed) New region: 0x1000 <-> 0x4000 (NOT Allowed) New region: 0x2000 <-> 0x4000 (NOT Allowed) Parameters start -- Start address of new region. end -- End address of new region. start -- Start address of new region. end -- End address of new region. start -- Start address of new region. Returns ESP_OK on success, ESP_ERR_INVALID_ARG if a parameter is invalid, ESP_ERR_NOT_FOUND if the specified start address doesn't reside in a known region, or any error returned by heap_caps_add_region_with_caps(). Parameters start -- Start address of new region. end -- End address of new region. Returns ESP_OK on success, ESP_ERR_INVALID_ARG if a parameter is invalid, ESP_ERR_NOT_FOUND if the specified start address doesn't reside in a known region, or any error returned by heap_caps_add_region_with_caps(). esp_err_t heap_caps_add_region_with_caps(const uint32_t caps[], intptr_t start, intptr_t end) Add a region of memory to the collection of heaps at runtime, with custom capabilities. Similar to heap_caps_add_region(), only custom memory capabilities are specified by the caller. Note Please refer to following example for memory regions allowed for addition to heap based on an existing region (address range for demonstration purpose only): Existing region: 0x1000 <-> 0x3000 New region: 0x1000 <-> 0x3000 (Allowed) New region: 0x1000 <-> 0x2000 (Allowed) New region: 0x0000 <-> 0x1000 (Allowed) New region: 0x3000 <-> 0x4000 (Allowed) New region: 0x0000 <-> 0x2000 (NOT Allowed) New region: 0x0000 <-> 0x4000 (NOT Allowed) New region: 0x1000 <-> 0x4000 (NOT Allowed) New region: 0x2000 <-> 0x4000 (NOT Allowed) Parameters caps -- Ordered array of capability masks for the new region, in order of priority. Must have length SOC_MEMORY_TYPE_NO_PRIOS. Does not need to remain valid after the call returns. start -- Start address of new region. end -- End address of new region. caps -- Ordered array of capability masks for the new region, in order of priority. Must have length SOC_MEMORY_TYPE_NO_PRIOS. Does not need to remain valid after the call returns. start -- Start address of new region. end -- End address of new region. caps -- Ordered array of capability masks for the new region, in order of priority. Must have length SOC_MEMORY_TYPE_NO_PRIOS. Does not need to remain valid after the call returns. Returns ESP_OK on success ESP_ERR_INVALID_ARG if a parameter is invalid ESP_ERR_NO_MEM if no memory to register new heap. ESP_ERR_INVALID_SIZE if the memory region is too small to fit a heap ESP_FAIL if region overlaps the start and/or end of an existing region ESP_OK on success ESP_ERR_INVALID_ARG if a parameter is invalid ESP_ERR_NO_MEM if no memory to register new heap. ESP_ERR_INVALID_SIZE if the memory region is too small to fit a heap ESP_FAIL if region overlaps the start and/or end of an existing region ESP_OK on success Parameters caps -- Ordered array of capability masks for the new region, in order of priority. Must have length SOC_MEMORY_TYPE_NO_PRIOS. Does not need to remain valid after the call returns. start -- Start address of new region. end -- End address of new region. Returns ESP_OK on success ESP_ERR_INVALID_ARG if a parameter is invalid ESP_ERR_NO_MEM if no memory to register new heap. ESP_ERR_INVALID_SIZE if the memory region is too small to fit a heap ESP_FAIL if region overlaps the start and/or end of an existing region API Reference - Multi-Heap API (Note: The multi-heap API is used internally by the heap capabilities allocator. Most ESP-IDF programs never need to call this API directly.) Header File This header file can be included with: #include "multi_heap.h" Functions void *multi_heap_aligned_alloc(multi_heap_handle_t heap, size_t size, size_t alignment) allocate a chunk of memory with specific alignment Parameters heap -- Handle to a registered heap. size -- size in bytes of memory chunk alignment -- how the memory must be aligned heap -- Handle to a registered heap. size -- size in bytes of memory chunk alignment -- how the memory must be aligned heap -- Handle to a registered heap. Returns pointer to the memory allocated, NULL on failure Parameters heap -- Handle to a registered heap. size -- size in bytes of memory chunk alignment -- how the memory must be aligned Returns pointer to the memory allocated, NULL on failure void *multi_heap_malloc(multi_heap_handle_t heap, size_t size) malloc() a buffer in a given heap Semantics are the same as standard malloc(), only the returned buffer will be allocated in the specified heap. Parameters heap -- Handle to a registered heap. size -- Size of desired buffer. heap -- Handle to a registered heap. size -- Size of desired buffer. heap -- Handle to a registered heap. Returns Pointer to new memory, or NULL if allocation fails. Parameters heap -- Handle to a registered heap. size -- Size of desired buffer. Returns Pointer to new memory, or NULL if allocation fails. void multi_heap_aligned_free(multi_heap_handle_t heap, void *p) free() a buffer aligned in a given heap. Note This function is deprecated, consider using multi_heap_free() instead Parameters heap -- Handle to a registered heap. p -- NULL, or a pointer previously returned from multi_heap_aligned_alloc() for the same heap. heap -- Handle to a registered heap. p -- NULL, or a pointer previously returned from multi_heap_aligned_alloc() for the same heap. heap -- Handle to a registered heap. Parameters heap -- Handle to a registered heap. p -- NULL, or a pointer previously returned from multi_heap_aligned_alloc() for the same heap. void multi_heap_free(multi_heap_handle_t heap, void *p) free() a buffer in a given heap. Semantics are the same as standard free(), only the argument 'p' must be NULL or have been allocated in the specified heap. Parameters heap -- Handle to a registered heap. p -- NULL, or a pointer previously returned from multi_heap_malloc() or multi_heap_realloc() for the same heap. heap -- Handle to a registered heap. p -- NULL, or a pointer previously returned from multi_heap_malloc() or multi_heap_realloc() for the same heap. heap -- Handle to a registered heap. Parameters heap -- Handle to a registered heap. p -- NULL, or a pointer previously returned from multi_heap_malloc() or multi_heap_realloc() for the same heap. void *multi_heap_realloc(multi_heap_handle_t heap, void *p, size_t size) realloc() a buffer in a given heap. Semantics are the same as standard realloc(), only the argument 'p' must be NULL or have been allocated in the specified heap. Parameters heap -- Handle to a registered heap. p -- NULL, or a pointer previously returned from multi_heap_malloc() or multi_heap_realloc() for the same heap. size -- Desired new size for buffer. heap -- Handle to a registered heap. p -- NULL, or a pointer previously returned from multi_heap_malloc() or multi_heap_realloc() for the same heap. size -- Desired new size for buffer. heap -- Handle to a registered heap. Returns New buffer of 'size' containing contents of 'p', or NULL if reallocation failed. Parameters heap -- Handle to a registered heap. p -- NULL, or a pointer previously returned from multi_heap_malloc() or multi_heap_realloc() for the same heap. size -- Desired new size for buffer. Returns New buffer of 'size' containing contents of 'p', or NULL if reallocation failed. size_t multi_heap_get_allocated_size(multi_heap_handle_t heap, void *p) Return the size that a particular pointer was allocated with. Parameters heap -- Handle to a registered heap. p -- Pointer, must have been previously returned from multi_heap_malloc() or multi_heap_realloc() for the same heap. heap -- Handle to a registered heap. p -- Pointer, must have been previously returned from multi_heap_malloc() or multi_heap_realloc() for the same heap. heap -- Handle to a registered heap. Returns Size of the memory allocated at this block. May be more than the original size argument, due to padding and minimum block sizes. Parameters heap -- Handle to a registered heap. p -- Pointer, must have been previously returned from multi_heap_malloc() or multi_heap_realloc() for the same heap. Returns Size of the memory allocated at this block. May be more than the original size argument, due to padding and minimum block sizes. multi_heap_handle_t multi_heap_register(void *start, size_t size) Register a new heap for use. This function initialises a heap at the specified address, and returns a handle for future heap operations. There is no equivalent function for deregistering a heap - if all blocks in the heap are free, you can immediately start using the memory for other purposes. Parameters start -- Start address of the memory to use for a new heap. size -- Size (in bytes) of the new heap. start -- Start address of the memory to use for a new heap. size -- Size (in bytes) of the new heap. start -- Start address of the memory to use for a new heap. Returns Handle of a new heap ready for use, or NULL if the heap region was too small to be initialised. Parameters start -- Start address of the memory to use for a new heap. size -- Size (in bytes) of the new heap. Returns Handle of a new heap ready for use, or NULL if the heap region was too small to be initialised. void multi_heap_set_lock(multi_heap_handle_t heap, void *lock) Associate a private lock pointer with a heap. The lock argument is supplied to the MULTI_HEAP_LOCK() and MULTI_HEAP_UNLOCK() macros, defined in multi_heap_platform.h. The lock in question must be recursive. When the heap is first registered, the associated lock is NULL. Parameters heap -- Handle to a registered heap. lock -- Optional pointer to a locking structure to associate with this heap. heap -- Handle to a registered heap. lock -- Optional pointer to a locking structure to associate with this heap. heap -- Handle to a registered heap. Parameters heap -- Handle to a registered heap. lock -- Optional pointer to a locking structure to associate with this heap. void multi_heap_dump(multi_heap_handle_t heap) Dump heap information to stdout. For debugging purposes, this function dumps information about every block in the heap to stdout. Parameters heap -- Handle to a registered heap. Parameters heap -- Handle to a registered heap. bool multi_heap_check(multi_heap_handle_t heap, bool print_errors) Check heap integrity. Walks the heap and checks all heap data structures are valid. If any errors are detected, an error-specific message can be optionally printed to stderr. Print behaviour can be overridden at compile time by defining MULTI_CHECK_FAIL_PRINTF in multi_heap_platform.h. Note This function is not thread-safe as it sets a global variable with the value of print_errors. Parameters heap -- Handle to a registered heap. print_errors -- If true, errors will be printed to stderr. heap -- Handle to a registered heap. print_errors -- If true, errors will be printed to stderr. heap -- Handle to a registered heap. Returns true if heap is valid, false otherwise. Parameters heap -- Handle to a registered heap. print_errors -- If true, errors will be printed to stderr. Returns true if heap is valid, false otherwise. size_t multi_heap_free_size(multi_heap_handle_t heap) Return free heap size. Returns the number of bytes available in the heap. Equivalent to the total_free_bytes member returned by multi_heap_get_heap_info(). Note that the heap may be fragmented, so the actual maximum size for a single malloc() may be lower. To know this size, see the largest_free_block member returned by multi_heap_get_heap_info(). Parameters heap -- Handle to a registered heap. Returns Number of free bytes. Parameters heap -- Handle to a registered heap. Returns Number of free bytes. size_t multi_heap_minimum_free_size(multi_heap_handle_t heap) Return the lifetime minimum free heap size. Equivalent to the minimum_free_bytes member returned by multi_heap_get_info(). Returns the lifetime "low watermark" of possible values returned from multi_free_heap_size(), for the specified heap. Parameters heap -- Handle to a registered heap. Returns Number of free bytes. Parameters heap -- Handle to a registered heap. Returns Number of free bytes. void multi_heap_get_info(multi_heap_handle_t heap, multi_heap_info_t *info) Return metadata about a given heap. Fills a multi_heap_info_t structure with information about the specified heap. Parameters heap -- Handle to a registered heap. info -- Pointer to a structure to fill with heap metadata. heap -- Handle to a registered heap. info -- Pointer to a structure to fill with heap metadata. heap -- Handle to a registered heap. Parameters heap -- Handle to a registered heap. info -- Pointer to a structure to fill with heap metadata. void *multi_heap_aligned_alloc_offs(multi_heap_handle_t heap, size_t size, size_t alignment, size_t offset) Perform an aligned allocation from the provided offset. Parameters heap -- The heap in which to perform the allocation size -- The size of the allocation alignment -- How the memory must be aligned offset -- The offset at which the alignment should start heap -- The heap in which to perform the allocation size -- The size of the allocation alignment -- How the memory must be aligned offset -- The offset at which the alignment should start heap -- The heap in which to perform the allocation Returns void* The ptr to the allocated memory Parameters heap -- The heap in which to perform the allocation size -- The size of the allocation alignment -- How the memory must be aligned offset -- The offset at which the alignment should start Returns void* The ptr to the allocated memory Structures struct multi_heap_info_t Structure to access heap metadata via multi_heap_get_info. Public Members size_t total_free_bytes Total free bytes in the heap. Equivalent to multi_free_heap_size(). size_t total_free_bytes Total free bytes in the heap. Equivalent to multi_free_heap_size(). size_t total_allocated_bytes Total bytes allocated to data in the heap. size_t total_allocated_bytes Total bytes allocated to data in the heap. size_t largest_free_block Size of the largest free block in the heap. This is the largest malloc-able size. size_t largest_free_block Size of the largest free block in the heap. This is the largest malloc-able size. size_t minimum_free_bytes Lifetime minimum free heap size. Equivalent to multi_minimum_free_heap_size(). size_t minimum_free_bytes Lifetime minimum free heap size. Equivalent to multi_minimum_free_heap_size(). size_t allocated_blocks Number of (variable size) blocks allocated in the heap. size_t allocated_blocks Number of (variable size) blocks allocated in the heap. size_t free_blocks Number of (variable size) free blocks in the heap. size_t free_blocks Number of (variable size) free blocks in the heap. size_t total_blocks Total number of (variable size) blocks in the heap. size_t total_blocks Total number of (variable size) blocks in the heap. size_t total_free_bytes Type Definitions typedef struct multi_heap_info *multi_heap_handle_t Opaque handle to a registered heap.
Heap Memory Allocation Stack and Heap ESP-IDF applications use the common computer architecture patterns of stack (dynamic memory allocated by program control flow), heap (dynamic memory allocated by function calls), and static memory (memory allocated at compile time). Because ESP-IDF is a multi-threaded RTOS environment, each RTOS task has its own stack. By default, each of these stacks is allocated from the heap when the task is created. See xTaskCreateStatic() for the alternative where stacks are statically allocated. Because ESP32 uses multiple types of RAM, it also contains multiple heaps with different capabilities. A capabilities-based memory allocator allows apps to make heap allocations for different purposes. For most purposes, the C Standard Library's malloc() and free() functions can be used for heap allocation without any special consideration. However, in order to fully make use of all of the memory types and their characteristics, ESP-IDF also has a capabilities-based heap memory allocator. If you want to have a memory with certain properties (e.g., DMA-Capable Memory or executable-memory), you can create an OR-mask of the required capabilities and pass that to heap_caps_malloc(). Memory Capabilities The ESP32 contains multiple types of RAM: DRAM (Data RAM) is memory that is connected to CPU's data bus and is used to hold data. This is the most common kind of memory accessed as a heap. IRAM (Instruction RAM) is memory that is connected to the CPU's instruction bus and usually holds executable data only (i.e., instructions). If accessed as generic memory, all accesses must be aligned to 32-Bit Accessible Memory. D/IRAM is RAM that is connected to CPU's data bus and instruction bus, thus can be used either Instruction or Data RAM. For more details on these internal memory types, see Memory Types. It is also possible to connect external SPI RAM to the ESP32. The external RAM is integrated into the ESP32's memory map via the cache, and accessed similarly to DRAM. All DRAM memory is single-byte accessible, thus all DRAM heaps possess the MALLOC_CAP_8BIT capability. Users can call heap_caps_get_free_size(MALLOC_CAP_8BIT) to get the free size of all DRAM heaps. If ran out of MALLOC_CAP_8BIT, the users can use MALLOC_CAP_IRAM_8BIT instead. In that case, IRAM can still be used as a "reserve" pool of internal memory if the users only access it in a 32-bit aligned manner, or if they enable CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY). When calling malloc(), the ESP-IDF malloc() internally calls heap_caps_malloc_default(size). This will allocate memory with the capability MALLOC_CAP_DEFAULT, which is byte-addressable. Because malloc() uses the capabilities-based allocation system, memory allocated using heap_caps_malloc() can be freed by calling the standard free() function. Available Heap DRAM At startup, the DRAM heap contains all data memory that is not statically allocated by the app. Reducing statically-allocated buffers increases the amount of available free heap. To find the amount of statically allocated memory, use the idf.py size command. Note See the DRAM (Data RAM) section for more details about the DRAM usage limitations. Note At runtime, the available heap DRAM may be less than calculated at compile time, because, at startup, some memory is allocated from the heap before the FreeRTOS scheduler is started (including memory for the stacks of initial FreeRTOS tasks). IRAM At startup, the IRAM heap contains all instruction memory that is not used by the app executable code. The idf.py size command can be used to find the amount of IRAM used by the app. D/IRAM Some memory in the ESP32 is available as either DRAM or IRAM. If memory is allocated from a D/IRAM region, the free heap size for both types of memory will decrease. Heap Sizes At startup, all ESP-IDF apps log a summary of all heap addresses (and sizes) at level Info: I (252) heap_init: Initializing. RAM available for dynamic allocation: I (259) heap_init: At 3FFAE6E0 len 00001920 (6 KiB): DRAM I (265) heap_init: At 3FFB2EC8 len 0002D138 (180 KiB): DRAM I (272) heap_init: At 3FFE0440 len 00003AE0 (14 KiB): D/IRAM I (278) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM I (284) heap_init: At 4008944C len 00016BB4 (90 KiB): IRAM Finding Available Heap See Heap Information. Special Capabilities DMA-Capable Memory Use the MALLOC_CAP_DMA flag to allocate memory which is suitable for use with hardware DMA engines (for example SPI and I2S). This capability flag excludes any external PSRAM. 32-Bit Accessible Memory If a certain memory structure is only addressed in 32-bit units, for example, an array of ints or pointers, it can be useful to allocate it with the MALLOC_CAP_32BIT flag. This also allows the allocator to give out IRAM memory, which is sometimes unavailable for a normal malloc() call. This can help to use all the available memory in the ESP32. Please note that on ESP32 series chips, MALLOC_CAP_32BIT cannot be used for storing floating-point variables. This is because MALLOC_CAP_32BIT may return instruction RAM and the floating-point assembly instructions on ESP32 cannot access instruction RAM. Memory allocated with MALLOC_CAP_32BIT can only be accessed via 32-bit reads and writes, any other type of access will generate a fatal LoadStoreError exception. External SPI Memory When external RAM is enabled, external SPI RAM can be allocated using standard malloc calls, or via heap_caps_malloc(MALLOC_CAP_SPIRAM), depending on the configuration. See Configuring External RAM for more details. On ESP32 only external SPI RAM under 4 MiB in size can be allocated this way. To use the region above the 4 MiB limit, you can use the himem API. Thread Safety Heap functions are thread-safe, meaning they can be called from different tasks simultaneously without any limitations. It is technically possible to call malloc, free, and related functions from interrupt handler (ISR) context (see Calling Heap-Related Functions from ISR). However, this is not recommended, as heap function calls may delay other interrupts. It is strongly recommended to refactor applications so that any buffers used by an ISR are pre-allocated outside of the ISR. Support for calling heap functions from ISRs may be removed in a future update. Heap Tracing & Debugging The following features are documented on the Heap Memory Debugging page: Heap Information (free space, etc.) Heap Tracing (memory leak detection, monitoring, etc.) Implementation Notes Knowledge about the regions of memory in the chip comes from the "SoC" component, which contains memory layout information for the chip, and the different capabilities of each region. Each region's capabilities are prioritized, so that (for example) dedicated DRAM and IRAM regions are used for allocations ahead of the more versatile D/IRAM regions. Each contiguous region of memory contains its own memory heap. The heaps are created using the multi_heap functionality. multi_heap allows any contiguous region of memory to be used as a heap. The heap capabilities allocator uses knowledge of the memory regions to initialize each individual heap. Allocation functions in the heap capabilities API will find the most appropriate heap for the allocation based on desired capabilities, available space, and preferences for each region's use, and then calling multi_heap_malloc() for the heap situated in that particular region. Calling free() involves finding the particular heap corresponding to the freed address, and then call multi_heap_free() on that particular multi_heap instance. API Reference - Heap Allocation Header File This header file can be included with: #include "esp_heap_caps.h" Functions - esp_err_t heap_caps_register_failed_alloc_callback(esp_alloc_failed_hook_t callback) registers a callback function to be invoked if a memory allocation operation fails - Parameters callback -- caller defined callback to be invoked - Returns ESP_OK if callback was registered. - void *heap_caps_malloc(size_t size, uint32_t caps) Allocate a chunk of memory which has the given capabilities. Equivalent semantics to libc malloc(), for capability-aware memory. - Parameters size -- Size, in bytes, of the amount of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned - - Returns A pointer to the memory allocated on success, NULL on failure - void heap_caps_free(void *ptr) Free memory previously allocated via heap_caps_malloc() or heap_caps_realloc(). Equivalent semantics to libc free(), for capability-aware memory. In IDF, free(p)is equivalent to heap_caps_free(p). - Parameters ptr -- Pointer to memory previously returned from heap_caps_malloc() or heap_caps_realloc(). Can be NULL. - void *heap_caps_realloc(void *ptr, size_t size, uint32_t caps) Reallocate memory previously allocated via heap_caps_malloc() or heap_caps_realloc(). Equivalent semantics to libc realloc(), for capability-aware memory. In IDF, realloc(p, s)is equivalent to heap_caps_realloc(p, s, MALLOC_CAP_8BIT). 'caps' parameter can be different to the capabilities that any original 'ptr' was allocated with. In this way, realloc can be used to "move" a buffer if necessary to ensure it meets a new set of capabilities. - Parameters ptr -- Pointer to previously allocated memory, or NULL for a new allocation. size -- Size of the new buffer requested, or 0 to free the buffer. caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory desired for the new allocation. - - Returns Pointer to a new buffer of size 'size' with capabilities 'caps', or NULL if allocation failed. - void *heap_caps_aligned_alloc(size_t alignment, size_t size, uint32_t caps) Allocate an aligned chunk of memory which has the given capabilities. Equivalent semantics to libc aligned_alloc(), for capability-aware memory. - Parameters alignment -- How the pointer received needs to be aligned must be a power of two size -- Size, in bytes, of the amount of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned - - Returns A pointer to the memory allocated on success, NULL on failure - void heap_caps_aligned_free(void *ptr) Used to deallocate memory previously allocated with heap_caps_aligned_alloc. Note This function is deprecated, please consider using heap_caps_free() instead - Parameters ptr -- Pointer to the memory allocated - void *heap_caps_aligned_calloc(size_t alignment, size_t n, size_t size, uint32_t caps) Allocate an aligned chunk of memory which has the given capabilities. The initialized value in the memory is set to zero. - Parameters alignment -- How the pointer received needs to be aligned must be a power of two n -- Number of continuing chunks of memory to allocate size -- Size, in bytes, of a chunk of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned - - Returns A pointer to the memory allocated on success, NULL on failure - void *heap_caps_calloc(size_t n, size_t size, uint32_t caps) Allocate a chunk of memory which has the given capabilities. The initialized value in the memory is set to zero. Equivalent semantics to libc calloc(), for capability-aware memory. In IDF, calloc(p)is equivalent to heap_caps_calloc(p, MALLOC_CAP_8BIT). - Parameters n -- Number of continuing chunks of memory to allocate size -- Size, in bytes, of a chunk of memory to allocate caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be returned - - Returns A pointer to the memory allocated on success, NULL on failure - size_t heap_caps_get_total_size(uint32_t caps) Get the total size of all the regions that have the given capabilities. This function takes all regions capable of having the given capabilities allocated in them and adds up the total space they have. - Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory - Returns total size in bytes - size_t heap_caps_get_free_size(uint32_t caps) Get the total free size of all the regions that have the given capabilities. This function takes all regions capable of having the given capabilities allocated in them and adds up the free space they have. Note Note that because of heap fragmentation it is probably not possible to allocate a single block of memory of this size. Use heap_caps_get_largest_free_block() for this purpose. - Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory - Returns Amount of free bytes in the regions - size_t heap_caps_get_minimum_free_size(uint32_t caps) Get the total minimum free memory of all regions with the given capabilities. This adds all the low watermarks of the regions capable of delivering the memory with the given capabilities. Note Note the result may be less than the global all-time minimum available heap of this kind, as "low watermarks" are tracked per-region. Individual regions' heaps may have reached their "low watermarks" at different points in time. However, this result still gives a "worst case" indication for all-time minimum free heap. - Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory - Returns Amount of free bytes in the regions - size_t heap_caps_get_largest_free_block(uint32_t caps) Get the largest free block of memory able to be allocated with the given capabilities. Returns the largest value of sfor which heap_caps_malloc(s, caps)will succeed. - Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory - Returns Size of the largest free block in bytes. - void heap_caps_get_info(multi_heap_info_t *info, uint32_t caps) Get heap info for all regions with the given capabilities. Calls multi_heap_info() on all heaps which share the given capabilities. The information returned is an aggregate across all matching heaps. The meanings of fields are the same as defined for multi_heap_info_t, except that minimum_free_byteshas the same caveats described in heap_caps_get_minimum_free_size(). - Parameters info -- Pointer to a structure which will be filled with relevant heap metadata. caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory - - void heap_caps_print_heap_info(uint32_t caps) Print a summary of all memory with the given capabilities. Calls multi_heap_info on all heaps which share the given capabilities, and prints a two-line summary for each, then a total summary. - Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory - bool heap_caps_check_integrity_all(bool print_errors) Check integrity of all heap memory in the system. Calls multi_heap_check on all heaps. Optionally print errors if heaps are corrupt. Calling this function is equivalent to calling heap_caps_check_integrity with the caps argument set to MALLOC_CAP_INVALID. Note Please increase the value of CONFIG_ESP_INT_WDT_TIMEOUT_MSwhen using this API with PSRAM enabled. - Parameters print_errors -- Print specific errors if heap corruption is found. - Returns True if all heaps are valid, False if at least one heap is corrupt. - bool heap_caps_check_integrity(uint32_t caps, bool print_errors) Check integrity of all heaps with the given capabilities. Calls multi_heap_check on all heaps which share the given capabilities. Optionally print errors if the heaps are corrupt. See also heap_caps_check_integrity_all to check all heap memory in the system and heap_caps_check_integrity_addr to check memory around a single address. Note Please increase the value of CONFIG_ESP_INT_WDT_TIMEOUT_MSwhen using this API with PSRAM capability flag. - Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory print_errors -- Print specific errors if heap corruption is found. - - Returns True if all heaps are valid, False if at least one heap is corrupt. - bool heap_caps_check_integrity_addr(intptr_t addr, bool print_errors) Check integrity of heap memory around a given address. This function can be used to check the integrity of a single region of heap memory, which contains the given address. This can be useful if debugging heap integrity for corruption at a known address, as it has a lower overhead than checking all heap regions. Note that if the corrupt address moves around between runs (due to timing or other factors) then this approach won't work, and you should call heap_caps_check_integrity or heap_caps_check_integrity_all instead. Note The entire heap region around the address is checked, not only the adjacent heap blocks. - Parameters addr -- Address in memory. Check for corruption in region containing this address. print_errors -- Print specific errors if heap corruption is found. - - Returns True if the heap containing the specified address is valid, False if at least one heap is corrupt or the address doesn't belong to a heap region. - void heap_caps_malloc_extmem_enable(size_t limit) Enable malloc() in external memory and set limit below which malloc() attempts are placed in internal memory. When external memory is in use, the allocation strategy is to initially try to satisfy smaller allocation requests with internal memory and larger requests with external memory. This sets the limit between the two, as well as generally enabling allocation in external memory. - Parameters limit -- Limit, in bytes. - void *heap_caps_malloc_prefer(size_t size, size_t num, ...) Allocate a chunk of memory as preference in decreasing order. - Attention The variable parameters are bitwise OR of MALLOC_CAP_* flags indicating the type of memory. This API prefers to allocate memory with the first parameter. If failed, allocate memory with the next parameter. It will try in this order until allocating a chunk of memory successfully or fail to allocate memories with any of the parameters. - Parameters size -- Size, in bytes, of the amount of memory to allocate num -- Number of variable parameters - - Returns A pointer to the memory allocated on success, NULL on failure - void *heap_caps_realloc_prefer(void *ptr, size_t size, size_t num, ...) Reallocate a chunk of memory as preference in decreasing order. - Parameters ptr -- Pointer to previously allocated memory, or NULL for a new allocation. size -- Size of the new buffer requested, or 0 to free the buffer. num -- Number of variable paramters - - Returns Pointer to a new buffer of size 'size', or NULL if allocation failed. - void *heap_caps_calloc_prefer(size_t n, size_t size, size_t num, ...) Allocate a chunk of memory as preference in decreasing order. - Parameters n -- Number of continuing chunks of memory to allocate size -- Size, in bytes, of a chunk of memory to allocate num -- Number of variable paramters - - Returns A pointer to the memory allocated on success, NULL on failure - void heap_caps_dump(uint32_t caps) Dump the full structure of all heaps with matching capabilities. Prints a large amount of output to serial (because of locking limitations, the output bypasses stdout/stderr). For each (variable sized) block in each matching heap, the following output is printed on a single line: Block address (the data buffer returned by malloc is 4 bytes after this if heap debugging is set to Basic, or 8 bytes otherwise). Data size (the data size may be larger than the size requested by malloc, either due to heap fragmentation or because of heap debugging level). Address of next block in the heap. If the block is free, the address of the next free block is also printed. - Parameters caps -- Bitwise OR of MALLOC_CAP_* flags indicating the type of memory - - void heap_caps_dump_all(void) Dump the full structure of all heaps. Covers all registered heaps. Prints a large amount of output to serial. Output is the same as for heap_caps_dump. - size_t heap_caps_get_allocated_size(void *ptr) Return the size that a particular pointer was allocated with. Note The app will crash with an assertion failure if the pointer is not valid. - Parameters ptr -- Pointer to currently allocated heap memory. Must be a pointer value previously returned by heap_caps_malloc, malloc, calloc, etc. and not yet freed. - Returns Size of the memory allocated at this block. Macros - HEAP_IRAM_ATTR - MALLOC_CAP_EXEC Flags to indicate the capabilities of the various memory systems. Memory must be able to run executable code - MALLOC_CAP_32BIT Memory must allow for aligned 32-bit data accesses. - MALLOC_CAP_8BIT Memory must allow for 8/16/...-bit data accesses. - MALLOC_CAP_DMA Memory must be able to accessed by DMA. - MALLOC_CAP_PID2 Memory must be mapped to PID2 memory space (PIDs are not currently used) - MALLOC_CAP_PID3 Memory must be mapped to PID3 memory space (PIDs are not currently used) - MALLOC_CAP_PID4 Memory must be mapped to PID4 memory space (PIDs are not currently used) - MALLOC_CAP_PID5 Memory must be mapped to PID5 memory space (PIDs are not currently used) - MALLOC_CAP_PID6 Memory must be mapped to PID6 memory space (PIDs are not currently used) - MALLOC_CAP_PID7 Memory must be mapped to PID7 memory space (PIDs are not currently used) - MALLOC_CAP_SPIRAM Memory must be in SPI RAM. - MALLOC_CAP_INTERNAL Memory must be internal; specifically it should not disappear when flash/spiram cache is switched off. - MALLOC_CAP_DEFAULT Memory can be returned in a non-capability-specific memory allocation (e.g. malloc(), calloc()) call. - MALLOC_CAP_IRAM_8BIT Memory must be in IRAM and allow unaligned access. - MALLOC_CAP_RETENTION Memory must be able to accessed by retention DMA. - MALLOC_CAP_RTCRAM Memory must be in RTC fast memory. - MALLOC_CAP_TCM Memory must be in TCM memory. - MALLOC_CAP_INVALID Memory can't be used / list end marker. Type Definitions - typedef void (*esp_alloc_failed_hook_t)(size_t size, uint32_t caps, const char *function_name) callback called when an allocation operation fails, if registered - Param size in bytes of failed allocation - Param caps capabilities requested of failed allocation - Param function_name function which generated the failure API Reference - Initialisation Header File This header file can be included with: #include "esp_heap_caps_init.h" Functions - void heap_caps_init(void) Initialize the capability-aware heap allocator. This is called once in the IDF startup code. Do not call it at other times. - void heap_caps_enable_nonos_stack_heaps(void) Enable heap(s) in memory regions where the startup stacks are located. On startup, the pro/app CPUs have a certain memory region they use as stack, so we cannot do allocations in the regions these stack frames are. When FreeRTOS is completely started, they do not use that memory anymore and heap(s) there can be enabled. - esp_err_t heap_caps_add_region(intptr_t start, intptr_t end) Add a region of memory to the collection of heaps at runtime. Most memory regions are defined in soc_memory_layout.c for the SoC, and are registered via heap_caps_init(). Some regions can't be used immediately and are later enabled via heap_caps_enable_nonos_stack_heaps(). Call this function to add a region of memory to the heap at some later time. This function does not consider any of the "reserved" regions or other data in soc_memory_layout, caller needs to consider this themselves. All memory within the region specified by start & end parameters must be otherwise unused. The capabilities of the newly registered memory will be determined by the start address, as looked up in the regions specified in soc_memory_layout.c. Use heap_caps_add_region_with_caps() to register a region with custom capabilities. Note Please refer to following example for memory regions allowed for addition to heap based on an existing region (address range for demonstration purpose only): Existing region: 0x1000 <-> 0x3000 New region: 0x1000 <-> 0x3000 (Allowed) New region: 0x1000 <-> 0x2000 (Allowed) New region: 0x0000 <-> 0x1000 (Allowed) New region: 0x3000 <-> 0x4000 (Allowed) New region: 0x0000 <-> 0x2000 (NOT Allowed) New region: 0x0000 <-> 0x4000 (NOT Allowed) New region: 0x1000 <-> 0x4000 (NOT Allowed) New region: 0x2000 <-> 0x4000 (NOT Allowed) - Parameters start -- Start address of new region. end -- End address of new region. - - Returns ESP_OK on success, ESP_ERR_INVALID_ARG if a parameter is invalid, ESP_ERR_NOT_FOUND if the specified start address doesn't reside in a known region, or any error returned by heap_caps_add_region_with_caps(). - esp_err_t heap_caps_add_region_with_caps(const uint32_t caps[], intptr_t start, intptr_t end) Add a region of memory to the collection of heaps at runtime, with custom capabilities. Similar to heap_caps_add_region(), only custom memory capabilities are specified by the caller. Note Please refer to following example for memory regions allowed for addition to heap based on an existing region (address range for demonstration purpose only): Existing region: 0x1000 <-> 0x3000 New region: 0x1000 <-> 0x3000 (Allowed) New region: 0x1000 <-> 0x2000 (Allowed) New region: 0x0000 <-> 0x1000 (Allowed) New region: 0x3000 <-> 0x4000 (Allowed) New region: 0x0000 <-> 0x2000 (NOT Allowed) New region: 0x0000 <-> 0x4000 (NOT Allowed) New region: 0x1000 <-> 0x4000 (NOT Allowed) New region: 0x2000 <-> 0x4000 (NOT Allowed) - Parameters caps -- Ordered array of capability masks for the new region, in order of priority. Must have length SOC_MEMORY_TYPE_NO_PRIOS. Does not need to remain valid after the call returns. start -- Start address of new region. end -- End address of new region. - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if a parameter is invalid ESP_ERR_NO_MEM if no memory to register new heap. ESP_ERR_INVALID_SIZE if the memory region is too small to fit a heap ESP_FAIL if region overlaps the start and/or end of an existing region - API Reference - Multi-Heap API (Note: The multi-heap API is used internally by the heap capabilities allocator. Most ESP-IDF programs never need to call this API directly.) Header File This header file can be included with: #include "multi_heap.h" Functions - void *multi_heap_aligned_alloc(multi_heap_handle_t heap, size_t size, size_t alignment) allocate a chunk of memory with specific alignment - Parameters heap -- Handle to a registered heap. size -- size in bytes of memory chunk alignment -- how the memory must be aligned - - Returns pointer to the memory allocated, NULL on failure - void *multi_heap_malloc(multi_heap_handle_t heap, size_t size) malloc() a buffer in a given heap Semantics are the same as standard malloc(), only the returned buffer will be allocated in the specified heap. - Parameters heap -- Handle to a registered heap. size -- Size of desired buffer. - - Returns Pointer to new memory, or NULL if allocation fails. - void multi_heap_aligned_free(multi_heap_handle_t heap, void *p) free() a buffer aligned in a given heap. Note This function is deprecated, consider using multi_heap_free() instead - Parameters heap -- Handle to a registered heap. p -- NULL, or a pointer previously returned from multi_heap_aligned_alloc() for the same heap. - - void multi_heap_free(multi_heap_handle_t heap, void *p) free() a buffer in a given heap. Semantics are the same as standard free(), only the argument 'p' must be NULL or have been allocated in the specified heap. - Parameters heap -- Handle to a registered heap. p -- NULL, or a pointer previously returned from multi_heap_malloc() or multi_heap_realloc() for the same heap. - - void *multi_heap_realloc(multi_heap_handle_t heap, void *p, size_t size) realloc() a buffer in a given heap. Semantics are the same as standard realloc(), only the argument 'p' must be NULL or have been allocated in the specified heap. - Parameters heap -- Handle to a registered heap. p -- NULL, or a pointer previously returned from multi_heap_malloc() or multi_heap_realloc() for the same heap. size -- Desired new size for buffer. - - Returns New buffer of 'size' containing contents of 'p', or NULL if reallocation failed. - size_t multi_heap_get_allocated_size(multi_heap_handle_t heap, void *p) Return the size that a particular pointer was allocated with. - Parameters heap -- Handle to a registered heap. p -- Pointer, must have been previously returned from multi_heap_malloc() or multi_heap_realloc() for the same heap. - - Returns Size of the memory allocated at this block. May be more than the original size argument, due to padding and minimum block sizes. - multi_heap_handle_t multi_heap_register(void *start, size_t size) Register a new heap for use. This function initialises a heap at the specified address, and returns a handle for future heap operations. There is no equivalent function for deregistering a heap - if all blocks in the heap are free, you can immediately start using the memory for other purposes. - Parameters start -- Start address of the memory to use for a new heap. size -- Size (in bytes) of the new heap. - - Returns Handle of a new heap ready for use, or NULL if the heap region was too small to be initialised. - void multi_heap_set_lock(multi_heap_handle_t heap, void *lock) Associate a private lock pointer with a heap. The lock argument is supplied to the MULTI_HEAP_LOCK() and MULTI_HEAP_UNLOCK() macros, defined in multi_heap_platform.h. The lock in question must be recursive. When the heap is first registered, the associated lock is NULL. - Parameters heap -- Handle to a registered heap. lock -- Optional pointer to a locking structure to associate with this heap. - - void multi_heap_dump(multi_heap_handle_t heap) Dump heap information to stdout. For debugging purposes, this function dumps information about every block in the heap to stdout. - Parameters heap -- Handle to a registered heap. - bool multi_heap_check(multi_heap_handle_t heap, bool print_errors) Check heap integrity. Walks the heap and checks all heap data structures are valid. If any errors are detected, an error-specific message can be optionally printed to stderr. Print behaviour can be overridden at compile time by defining MULTI_CHECK_FAIL_PRINTF in multi_heap_platform.h. Note This function is not thread-safe as it sets a global variable with the value of print_errors. - Parameters heap -- Handle to a registered heap. print_errors -- If true, errors will be printed to stderr. - - Returns true if heap is valid, false otherwise. - size_t multi_heap_free_size(multi_heap_handle_t heap) Return free heap size. Returns the number of bytes available in the heap. Equivalent to the total_free_bytes member returned by multi_heap_get_heap_info(). Note that the heap may be fragmented, so the actual maximum size for a single malloc() may be lower. To know this size, see the largest_free_block member returned by multi_heap_get_heap_info(). - Parameters heap -- Handle to a registered heap. - Returns Number of free bytes. - size_t multi_heap_minimum_free_size(multi_heap_handle_t heap) Return the lifetime minimum free heap size. Equivalent to the minimum_free_bytes member returned by multi_heap_get_info(). Returns the lifetime "low watermark" of possible values returned from multi_free_heap_size(), for the specified heap. - Parameters heap -- Handle to a registered heap. - Returns Number of free bytes. - void multi_heap_get_info(multi_heap_handle_t heap, multi_heap_info_t *info) Return metadata about a given heap. Fills a multi_heap_info_t structure with information about the specified heap. - Parameters heap -- Handle to a registered heap. info -- Pointer to a structure to fill with heap metadata. - - void *multi_heap_aligned_alloc_offs(multi_heap_handle_t heap, size_t size, size_t alignment, size_t offset) Perform an aligned allocation from the provided offset. - Parameters heap -- The heap in which to perform the allocation size -- The size of the allocation alignment -- How the memory must be aligned offset -- The offset at which the alignment should start - - Returns void* The ptr to the allocated memory Structures - struct multi_heap_info_t Structure to access heap metadata via multi_heap_get_info. Public Members - size_t total_free_bytes Total free bytes in the heap. Equivalent to multi_free_heap_size(). - size_t total_allocated_bytes Total bytes allocated to data in the heap. - size_t largest_free_block Size of the largest free block in the heap. This is the largest malloc-able size. - size_t minimum_free_bytes Lifetime minimum free heap size. Equivalent to multi_minimum_free_heap_size(). - size_t allocated_blocks Number of (variable size) blocks allocated in the heap. - size_t free_blocks Number of (variable size) free blocks in the heap. - size_t total_blocks Total number of (variable size) blocks in the heap. - size_t total_free_bytes Type Definitions - typedef struct multi_heap_info *multi_heap_handle_t Opaque handle to a registered heap.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/mem_alloc.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Memory Management for MMU Supported Memory
null
espressif.com
2016-01-01
a6a3fc9bf4f38841
null
null
Memory Management for MMU Supported Memory Introduction ESP32 Memory Management Unit (MMU) is relatively simple. It can do memory address translation between physical memory addresses and virtual memory addresses. So CPU can access physical memories via virtual addresses. There are multiple types of virtual memory addresses, which have different capabilities. ESP-IDF provides a memory mapping driver that manages the relation between these physical memory addresses and virtual memory addresses, so as to achieve some features such as reading from SPI flash via a pointer. Memory mapping driver is actually a capabilities-based virtual memory address allocator that allows applications to make virtual memory address allocations for different purposes. In the following chapters, we call this driver esp_mmap driver. ESP-IDF also provides a memory synchronization driver which can be used for potential memory desynchronization scenarios. Physical Memory Types Memory mapping driver currently supports mapping to following physical memory type(s): SPI flash Virtual Memory Capabilities MMU_MEM_CAP_EXEC : This capability indicates that the virtual memory address has the execute permission. Note this permission scope is within the MMU hardware. MMU_MEM_CAP_READ : This capability indicates that the virtual memory address has the read permission. Note this permission scope is within the MMU hardware. MMU_MEM_CAP_WRITE : This capability indicates that the virtual memory address has the write permission. Note this permission scope is within the MMU hardware. MMU_MEM_CAP_32BIT : This capability indicates that the virtual memory address allows for 32 bits or multiples of 32 bits access. MMU_MEM_CAP_8BIT : This capability indicates that the virtual memory address allows for 8 bits or multiples of 8 bits access. 8 MB external memory addresses (from 0x40400000 to 0x40C00000) which have the MMU_MEM_CAP_EXEC and MMU_MEM_CAP_READ capabilities are not available for users to allocate, due to hardware limitations. You can call esp_mmu_map_get_max_consecutive_free_block_size() to know the largest consecutive mappable block size with certain capabilities. Memory Management Drivers Driver Concept Terminology The virtual memory pool is made up with one or multiple virtual memory regions, see below figure: A virtual memory pool stands for the whole virtual address range that can be mapped to physical memory. A virtual memory region is a range of virtual address with same attributes. A virtual memory block is a piece of virtual address range that is dynamically mapped. A slot is the virtual address range between two virtual memory blocks. A physical memory block is a piece of physical address range that is to-be-mapped or already mapped to a virtual memory block. Dynamical mapping is done by calling esp_mmap driver API esp_mmu_map() . This API maps the given physical memory block to a virtual memory block which is allocated by the esp_mmap driver. Relation Between Memory Blocks When mapping a physical memory block A, block A can have one of the following relations with another previously mapped physical memory block B: Enclosed: block A is completely enclosed within block B, see figure below: Identical: block A is completely the same as block B, see figure below: Note that esp_mmap driver considers the identical scenario the same as the enclosed scenario. Overlapped: block A is overlapped with block B, see figure below: There is a special condition, when block A entirely encloses block B, see figure below: Note that esp_mmap driver considers this scenario the same as the overlapped scenario. Driver Behaviour Memory Map You can call esp_mmu_map() to do a dynamical mapping. This API can allocate a certain size of virtual memory block according to the virtual memory capabilities you selected, then map this virtual memory block to the physical memory block as you requested. The esp_mmap driver supports mapping to one or more types of physical memory, so you should specify the physical memory target when mapping. By default, physical memory blocks and virtual memory blocks are one-to-one mapped. This means, when calling esp_mmu_map() : If it is the enclosed scenario, this API will return an ESP_ERR_INVALID_STATE . The out_ptr will be assigned to the start virtual memory address of the previously mapped one which encloses the to-be-mapped one. If it is the identical scenario, this API will behaves exactly the same as the enclosed scenario. If it is the overlapped scenario, this API will by default return an ESP_ERR_INVALID_ARG . This means, esp_mmap driver by default does not allow mapping a physical memory address to multiple virtual memory addresses. Specially, you can use ESP_MMU_MMAP_FLAG_PADDR_SHARED . This flag stands for one-to-multiple mapping between a physical address and multiple virtual addresses: If it is the overlapped scenario, this API will allocate a new virtual memory block as requested, then map to the given physical memory block. Memory Unmap You can call esp_mmu_unmap() to unmap a previously mapped memory block. This API returns an ESP_ERR_NOT_FOUND if you are trying to unmap a virtual memory block that is not mapped to any physical memory block yet. Memory Address Conversion The esp_mmap driver provides two helper APIs to do the conversion between virtual memory address and physical memory address: esp_mmu_vaddr_to_paddr() converts virtual address to physical address. esp_mmu_paddr_to_vaddr() converts physical address to virtual address. Memory Synchronization MMU supported physical memories can be accessed by one or multiple methods. SPI flash can be accessed by SPI1 (ESP-IDF esp_flash driver APIs), or by pointers. ESP-IDF esp_flash driver APIs have already considered the memory synchronization, so users do not need to worry about this. PSRAM can be accessed by pointers, hardware guarantees the data consistency when PSRAM is only accessed via pointers. Thread Safety APIs in esp_mmu_map.h are not guaranteed to be thread-safe. APIs in esp_cache.h are guaranteed to be thread-safe. API Reference API Reference - ESP MMAP Driver Header File This header file can be included with: #include "esp_mmu_map.h" This header file is a part of the API provided by the esp_mm component. To declare that your component depends on esp_mm , add the following to your CMakeLists.txt: REQUIRES esp_mm or PRIV_REQUIRES esp_mm Functions esp_err_t esp_mmu_map(esp_paddr_t paddr_start, size_t size, mmu_target_t target, mmu_mem_caps_t caps, int flags, void **out_ptr) Map a physical memory block to external virtual address block, with given capabilities. Note This API does not guarantee thread safety Parameters paddr_start -- [in] Start address of the physical memory block size -- [in] Size to be mapped. Size will be rounded up by to the nearest multiple of MMU page size target -- [in] Physical memory target you're going to map to, see mmu_target_t caps -- [in] Memory capabilities, see mmu_mem_caps_t flags -- [in] Mmap flags out_ptr -- [out] Start address of the mapped virtual memory paddr_start -- [in] Start address of the physical memory block size -- [in] Size to be mapped. Size will be rounded up by to the nearest multiple of MMU page size target -- [in] Physical memory target you're going to map to, see mmu_target_t caps -- [in] Memory capabilities, see mmu_mem_caps_t flags -- [in] Mmap flags out_ptr -- [out] Start address of the mapped virtual memory paddr_start -- [in] Start address of the physical memory block Returns ESP_OK ESP_ERR_INVALID_ARG: Invalid argument, see printed logs ESP_ERR_NOT_SUPPORTED: Only on ESP32, PSRAM is not a supported physical memory target ESP_ERR_NOT_FOUND: No enough size free block to use ESP_ERR_NO_MEM: Out of memory, this API will allocate some heap memory for internal usage ESP_ERR_INVALID_STATE: Paddr is mapped already, this API will return corresponding vaddr_start of the previously mapped block. Only to-be-mapped paddr block is totally enclosed by a previously mapped block will lead to this error. (Identical scenario will behave similarly) new_block_start new_block_end |-----— New Block -----—| |------------— Block ------------—| block_start block_end ESP_OK ESP_ERR_INVALID_ARG: Invalid argument, see printed logs ESP_ERR_NOT_SUPPORTED: Only on ESP32, PSRAM is not a supported physical memory target ESP_ERR_NOT_FOUND: No enough size free block to use ESP_ERR_NO_MEM: Out of memory, this API will allocate some heap memory for internal usage ESP_ERR_INVALID_STATE: Paddr is mapped already, this API will return corresponding vaddr_start of the previously mapped block. Only to-be-mapped paddr block is totally enclosed by a previously mapped block will lead to this error. (Identical scenario will behave similarly) new_block_start new_block_end |-----— New Block -----—| |------------— Block ------------—| block_start block_end ESP_OK Parameters paddr_start -- [in] Start address of the physical memory block size -- [in] Size to be mapped. Size will be rounded up by to the nearest multiple of MMU page size target -- [in] Physical memory target you're going to map to, see mmu_target_t caps -- [in] Memory capabilities, see mmu_mem_caps_t flags -- [in] Mmap flags out_ptr -- [out] Start address of the mapped virtual memory Returns ESP_OK ESP_ERR_INVALID_ARG: Invalid argument, see printed logs ESP_ERR_NOT_SUPPORTED: Only on ESP32, PSRAM is not a supported physical memory target ESP_ERR_NOT_FOUND: No enough size free block to use ESP_ERR_NO_MEM: Out of memory, this API will allocate some heap memory for internal usage ESP_ERR_INVALID_STATE: Paddr is mapped already, this API will return corresponding vaddr_start of the previously mapped block. Only to-be-mapped paddr block is totally enclosed by a previously mapped block will lead to this error. (Identical scenario will behave similarly) new_block_start new_block_end |-----— New Block -----—| |------------— Block ------------—| block_start block_end esp_err_t esp_mmu_unmap(void *ptr) Unmap a previously mapped virtual memory block. Note This API does not guarantee thread safety Parameters ptr -- [in] Start address of the virtual memory Returns ESP_OK ESP_ERR_INVALID_ARG: Null pointer ESP_ERR_NOT_FOUND: Vaddr is not in external memory, or it's not mapped yet ESP_OK ESP_ERR_INVALID_ARG: Null pointer ESP_ERR_NOT_FOUND: Vaddr is not in external memory, or it's not mapped yet ESP_OK Parameters ptr -- [in] Start address of the virtual memory Returns ESP_OK ESP_ERR_INVALID_ARG: Null pointer ESP_ERR_NOT_FOUND: Vaddr is not in external memory, or it's not mapped yet esp_err_t esp_mmu_map_get_max_consecutive_free_block_size(mmu_mem_caps_t caps, mmu_target_t target, size_t *out_len) Get largest consecutive free external virtual memory block size, with given capabilities and given physical target. Parameters caps -- [in] Bitwise OR of MMU_MEM_CAP_* flags indicating the memory block target -- [in] Physical memory target you're going to map to, see mmu_target_t . out_len -- [out] Largest free block length, in bytes. caps -- [in] Bitwise OR of MMU_MEM_CAP_* flags indicating the memory block target -- [in] Physical memory target you're going to map to, see mmu_target_t . out_len -- [out] Largest free block length, in bytes. caps -- [in] Bitwise OR of MMU_MEM_CAP_* flags indicating the memory block Returns ESP_OK ESP_ERR_INVALID_ARG: Invalid arguments, could be null pointer ESP_OK ESP_ERR_INVALID_ARG: Invalid arguments, could be null pointer ESP_OK Parameters caps -- [in] Bitwise OR of MMU_MEM_CAP_* flags indicating the memory block target -- [in] Physical memory target you're going to map to, see mmu_target_t . out_len -- [out] Largest free block length, in bytes. Returns ESP_OK ESP_ERR_INVALID_ARG: Invalid arguments, could be null pointer esp_err_t esp_mmu_map_dump_mapped_blocks(FILE *stream) Dump all the previously mapped blocks Note This API shall not be called from an ISR. Note This API does not guarantee thread safety Parameters stream -- stream to print information to; use stdout or stderr to print to the console; use fmemopen/open_memstream to print to a string buffer. Returns ESP_OK ESP_OK ESP_OK Parameters stream -- stream to print information to; use stdout or stderr to print to the console; use fmemopen/open_memstream to print to a string buffer. Returns ESP_OK esp_err_t esp_mmu_vaddr_to_paddr(void *vaddr, esp_paddr_t *out_paddr, mmu_target_t *out_target) Convert virtual address to physical address. Parameters vaddr -- [in] Virtual address out_paddr -- [out] Physical address out_target -- [out] Physical memory target, see mmu_target_t vaddr -- [in] Virtual address out_paddr -- [out] Physical address out_target -- [out] Physical memory target, see mmu_target_t vaddr -- [in] Virtual address Returns ESP_OK ESP_ERR_INVALID_ARG: Null pointer, or vaddr is not within external memory ESP_ERR_NOT_FOUND: Vaddr is not mapped yet ESP_OK ESP_ERR_INVALID_ARG: Null pointer, or vaddr is not within external memory ESP_ERR_NOT_FOUND: Vaddr is not mapped yet ESP_OK Parameters vaddr -- [in] Virtual address out_paddr -- [out] Physical address out_target -- [out] Physical memory target, see mmu_target_t Returns ESP_OK ESP_ERR_INVALID_ARG: Null pointer, or vaddr is not within external memory ESP_ERR_NOT_FOUND: Vaddr is not mapped yet esp_err_t esp_mmu_paddr_to_vaddr(esp_paddr_t paddr, mmu_target_t target, mmu_vaddr_t type, void **out_vaddr) Convert physical address to virtual address. Parameters paddr -- [in] Physical address target -- [in] Physical memory target, see mmu_target_t type -- [in] Virtual address type, could be either instruction or data out_vaddr -- [out] Virtual address paddr -- [in] Physical address target -- [in] Physical memory target, see mmu_target_t type -- [in] Virtual address type, could be either instruction or data out_vaddr -- [out] Virtual address paddr -- [in] Physical address Returns ESP_OK ESP_ERR_INVALID_ARG: Null pointer ESP_ERR_NOT_FOUND: Paddr is not mapped yet ESP_OK ESP_ERR_INVALID_ARG: Null pointer ESP_ERR_NOT_FOUND: Paddr is not mapped yet ESP_OK Parameters paddr -- [in] Physical address target -- [in] Physical memory target, see mmu_target_t type -- [in] Virtual address type, could be either instruction or data out_vaddr -- [out] Virtual address Returns ESP_OK ESP_ERR_INVALID_ARG: Null pointer ESP_ERR_NOT_FOUND: Paddr is not mapped yet esp_err_t esp_mmu_paddr_find_caps(const esp_paddr_t paddr, mmu_mem_caps_t *out_caps) If the physical address is mapped, this API will provide the capabilities of the virtual address where the physical address is mapped to. Note : Only return value is ESP_OK(which means physically address is successfully mapped), then caps you get make sense. Note This API only check one page (see CONFIG_MMU_PAGE_SIZE), starting from the paddr Parameters paddr -- [in] Physical address out_caps -- [out] Bitwise OR of MMU_MEM_CAP_* flags indicating the capabilities of a virtual address where the physical address is mapped to. paddr -- [in] Physical address out_caps -- [out] Bitwise OR of MMU_MEM_CAP_* flags indicating the capabilities of a virtual address where the physical address is mapped to. paddr -- [in] Physical address Returns ESP_OK: Physical address successfully mapped. ESP_ERR_INVALID_ARG: Null pointer ESP_ERR_NOT_FOUND: Physical address is not mapped successfully. ESP_OK: Physical address successfully mapped. ESP_ERR_INVALID_ARG: Null pointer ESP_ERR_NOT_FOUND: Physical address is not mapped successfully. ESP_OK: Physical address successfully mapped. Parameters paddr -- [in] Physical address out_caps -- [out] Bitwise OR of MMU_MEM_CAP_* flags indicating the capabilities of a virtual address where the physical address is mapped to. Returns ESP_OK: Physical address successfully mapped. ESP_ERR_INVALID_ARG: Null pointer ESP_ERR_NOT_FOUND: Physical address is not mapped successfully. Macros ESP_MMU_MMAP_FLAG_PADDR_SHARED Share this mapping. MMU Memory Mapping Driver APIs for MMU supported memory Driver Backgrounds: Type Definitions typedef uint32_t esp_paddr_t Physical memory type.
Memory Management for MMU Supported Memory Introduction ESP32 Memory Management Unit (MMU) is relatively simple. It can do memory address translation between physical memory addresses and virtual memory addresses. So CPU can access physical memories via virtual addresses. There are multiple types of virtual memory addresses, which have different capabilities. ESP-IDF provides a memory mapping driver that manages the relation between these physical memory addresses and virtual memory addresses, so as to achieve some features such as reading from SPI flash via a pointer. Memory mapping driver is actually a capabilities-based virtual memory address allocator that allows applications to make virtual memory address allocations for different purposes. In the following chapters, we call this driver esp_mmap driver. ESP-IDF also provides a memory synchronization driver which can be used for potential memory desynchronization scenarios. Physical Memory Types Memory mapping driver currently supports mapping to following physical memory type(s): SPI flash Virtual Memory Capabilities MMU_MEM_CAP_EXEC: This capability indicates that the virtual memory address has the execute permission. Note this permission scope is within the MMU hardware. MMU_MEM_CAP_READ: This capability indicates that the virtual memory address has the read permission. Note this permission scope is within the MMU hardware. MMU_MEM_CAP_WRITE: This capability indicates that the virtual memory address has the write permission. Note this permission scope is within the MMU hardware. MMU_MEM_CAP_32BIT: This capability indicates that the virtual memory address allows for 32 bits or multiples of 32 bits access. MMU_MEM_CAP_8BIT: This capability indicates that the virtual memory address allows for 8 bits or multiples of 8 bits access. 8 MB external memory addresses (from 0x40400000 to 0x40C00000) which have the MMU_MEM_CAP_EXEC and MMU_MEM_CAP_READ capabilities are not available for users to allocate, due to hardware limitations. You can call esp_mmu_map_get_max_consecutive_free_block_size() to know the largest consecutive mappable block size with certain capabilities. Memory Management Drivers Driver Concept Terminology The virtual memory pool is made up with one or multiple virtual memory regions, see below figure: A virtual memory pool stands for the whole virtual address range that can be mapped to physical memory. A virtual memory region is a range of virtual address with same attributes. A virtual memory block is a piece of virtual address range that is dynamically mapped. A slot is the virtual address range between two virtual memory blocks. A physical memory block is a piece of physical address range that is to-be-mapped or already mapped to a virtual memory block. Dynamical mapping is done by calling esp_mmapdriver API esp_mmu_map(). This API maps the given physical memory block to a virtual memory block which is allocated by the esp_mmapdriver. Relation Between Memory Blocks When mapping a physical memory block A, block A can have one of the following relations with another previously mapped physical memory block B: Enclosed: block A is completely enclosed within block B, see figure below: Identical: block A is completely the same as block B, see figure below: Note that esp_mmapdriver considers the identical scenario the same as the enclosed scenario. Overlapped: block A is overlapped with block B, see figure below: There is a special condition, when block A entirely encloses block B, see figure below: Note that esp_mmapdriver considers this scenario the same as the overlapped scenario. Driver Behaviour Memory Map You can call esp_mmu_map() to do a dynamical mapping. This API can allocate a certain size of virtual memory block according to the virtual memory capabilities you selected, then map this virtual memory block to the physical memory block as you requested. The esp_mmap driver supports mapping to one or more types of physical memory, so you should specify the physical memory target when mapping. By default, physical memory blocks and virtual memory blocks are one-to-one mapped. This means, when calling esp_mmu_map(): If it is the enclosed scenario, this API will return an ESP_ERR_INVALID_STATE. The out_ptrwill be assigned to the start virtual memory address of the previously mapped one which encloses the to-be-mapped one. If it is the identical scenario, this API will behaves exactly the same as the enclosed scenario. If it is the overlapped scenario, this API will by default return an ESP_ERR_INVALID_ARG. This means, esp_mmapdriver by default does not allow mapping a physical memory address to multiple virtual memory addresses. Specially, you can use ESP_MMU_MMAP_FLAG_PADDR_SHARED. This flag stands for one-to-multiple mapping between a physical address and multiple virtual addresses: If it is the overlapped scenario, this API will allocate a new virtual memory block as requested, then map to the given physical memory block. Memory Unmap You can call esp_mmu_unmap() to unmap a previously mapped memory block. This API returns an ESP_ERR_NOT_FOUND if you are trying to unmap a virtual memory block that is not mapped to any physical memory block yet. Memory Address Conversion The esp_mmap driver provides two helper APIs to do the conversion between virtual memory address and physical memory address: esp_mmu_vaddr_to_paddr()converts virtual address to physical address. esp_mmu_paddr_to_vaddr()converts physical address to virtual address. Memory Synchronization MMU supported physical memories can be accessed by one or multiple methods. SPI flash can be accessed by SPI1 (ESP-IDF esp_flash driver APIs), or by pointers. ESP-IDF esp_flash driver APIs have already considered the memory synchronization, so users do not need to worry about this. PSRAM can be accessed by pointers, hardware guarantees the data consistency when PSRAM is only accessed via pointers. Thread Safety APIs in esp_mmu_map.h are not guaranteed to be thread-safe. APIs in esp_cache.h are guaranteed to be thread-safe. API Reference API Reference - ESP MMAP Driver Header File This header file can be included with: #include "esp_mmu_map.h" This header file is a part of the API provided by the esp_mmcomponent. To declare that your component depends on esp_mm, add the following to your CMakeLists.txt: REQUIRES esp_mm or PRIV_REQUIRES esp_mm Functions - esp_err_t esp_mmu_map(esp_paddr_t paddr_start, size_t size, mmu_target_t target, mmu_mem_caps_t caps, int flags, void **out_ptr) Map a physical memory block to external virtual address block, with given capabilities. Note This API does not guarantee thread safety - Parameters paddr_start -- [in] Start address of the physical memory block size -- [in] Size to be mapped. Size will be rounded up by to the nearest multiple of MMU page size target -- [in] Physical memory target you're going to map to, see mmu_target_t caps -- [in] Memory capabilities, see mmu_mem_caps_t flags -- [in] Mmap flags out_ptr -- [out] Start address of the mapped virtual memory - - Returns ESP_OK ESP_ERR_INVALID_ARG: Invalid argument, see printed logs ESP_ERR_NOT_SUPPORTED: Only on ESP32, PSRAM is not a supported physical memory target ESP_ERR_NOT_FOUND: No enough size free block to use ESP_ERR_NO_MEM: Out of memory, this API will allocate some heap memory for internal usage ESP_ERR_INVALID_STATE: Paddr is mapped already, this API will return corresponding vaddr_start of the previously mapped block. Only to-be-mapped paddr block is totally enclosed by a previously mapped block will lead to this error. (Identical scenario will behave similarly) new_block_start new_block_end |-----— New Block -----—| |------------— Block ------------—| block_start block_end - - esp_err_t esp_mmu_unmap(void *ptr) Unmap a previously mapped virtual memory block. Note This API does not guarantee thread safety - Parameters ptr -- [in] Start address of the virtual memory - Returns ESP_OK ESP_ERR_INVALID_ARG: Null pointer ESP_ERR_NOT_FOUND: Vaddr is not in external memory, or it's not mapped yet - - esp_err_t esp_mmu_map_get_max_consecutive_free_block_size(mmu_mem_caps_t caps, mmu_target_t target, size_t *out_len) Get largest consecutive free external virtual memory block size, with given capabilities and given physical target. - Parameters caps -- [in] Bitwise OR of MMU_MEM_CAP_* flags indicating the memory block target -- [in] Physical memory target you're going to map to, see mmu_target_t. out_len -- [out] Largest free block length, in bytes. - - Returns ESP_OK ESP_ERR_INVALID_ARG: Invalid arguments, could be null pointer - - esp_err_t esp_mmu_map_dump_mapped_blocks(FILE *stream) Dump all the previously mapped blocks Note This API shall not be called from an ISR. Note This API does not guarantee thread safety - Parameters stream -- stream to print information to; use stdout or stderr to print to the console; use fmemopen/open_memstream to print to a string buffer. - Returns ESP_OK - - esp_err_t esp_mmu_vaddr_to_paddr(void *vaddr, esp_paddr_t *out_paddr, mmu_target_t *out_target) Convert virtual address to physical address. - Parameters vaddr -- [in] Virtual address out_paddr -- [out] Physical address out_target -- [out] Physical memory target, see mmu_target_t - - Returns ESP_OK ESP_ERR_INVALID_ARG: Null pointer, or vaddr is not within external memory ESP_ERR_NOT_FOUND: Vaddr is not mapped yet - - esp_err_t esp_mmu_paddr_to_vaddr(esp_paddr_t paddr, mmu_target_t target, mmu_vaddr_t type, void **out_vaddr) Convert physical address to virtual address. - Parameters paddr -- [in] Physical address target -- [in] Physical memory target, see mmu_target_t type -- [in] Virtual address type, could be either instruction or data out_vaddr -- [out] Virtual address - - Returns ESP_OK ESP_ERR_INVALID_ARG: Null pointer ESP_ERR_NOT_FOUND: Paddr is not mapped yet - - esp_err_t esp_mmu_paddr_find_caps(const esp_paddr_t paddr, mmu_mem_caps_t *out_caps) If the physical address is mapped, this API will provide the capabilities of the virtual address where the physical address is mapped to. Note : Only return value is ESP_OK(which means physically address is successfully mapped), then caps you get make sense. Note This API only check one page (see CONFIG_MMU_PAGE_SIZE), starting from the paddr - Parameters paddr -- [in] Physical address out_caps -- [out] Bitwise OR of MMU_MEM_CAP_* flags indicating the capabilities of a virtual address where the physical address is mapped to. - - Returns ESP_OK: Physical address successfully mapped. ESP_ERR_INVALID_ARG: Null pointer ESP_ERR_NOT_FOUND: Physical address is not mapped successfully. - Macros - ESP_MMU_MMAP_FLAG_PADDR_SHARED Share this mapping. MMU Memory Mapping Driver APIs for MMU supported memory Driver Backgrounds: Type Definitions - typedef uint32_t esp_paddr_t Physical memory type.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/mm.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Heap Memory Debugging
null
espressif.com
2018-11-05
2ad3ff91e0b382c9
null
null
Heap Memory Debugging Overview ESP-IDF integrates tools for requesting heap information, heap corruption detection, and heap tracing. These can help track down memory-related bugs. For general information about the heap memory allocator, see Heap Memory Allocation. Heap Information To obtain information about the state of the heap, call the following functions: heap_caps_get_free_size() can be used to return the current free memory for different memory capabilities. heap_caps_get_largest_free_block() can be used to return the largest free block in the heap, which is also the largest single allocation currently possible. Tracking this value and comparing it to the total free heap allows you to detect heap fragmentation. heap_caps_get_minimum_free_size() can be used to track the heap "low watermark" since boot. heap_caps_get_info() returns a multi_heap_info_t structure, which contains the information from the above functions, plus some additional heap-specific data (number of allocations, etc.). heap_caps_print_heap_info() prints a summary of the information returned by heap_caps_get_info() to stdout. heap_caps_dump() and heap_caps_dump_all() output detailed information about the structure of each block in the heap. Note that this can be a large amount of output. Heap Allocation and Free Function Hooks Heap allocation and free detection hooks allow you to be notified of every successful allocation and free operation: Providing a definition of esp_heap_trace_alloc_hook() allows you to be notified of every successful memory allocation operation Providing a definition of esp_heap_trace_free_hook() allows you to be notified of every successful memory-free operations This feature can be enabled by setting the CONFIG_HEAP_USE_HOOKS option. esp_heap_trace_alloc_hook() and esp_heap_trace_free_hook() have weak declarations (e.g., __attribute__((weak)) ), thus it is not necessary to provide declarations for both hooks. Given that it is technically possible to allocate and free memory from an ISR (though strongly discouraged from doing so), the esp_heap_trace_alloc_hook() and esp_heap_trace_free_hook() can potentially be called from an ISR. It is not recommended to perform (or call API functions to perform) blocking operations or memory allocation/free operations in the hook functions. In general, the best practice is to keep the implementation concise and leave the heavy computation outside of the hook functions. The example below shows how to define the allocation and free function hooks: #include "esp_heap_caps.h" void esp_heap_trace_alloc_hook(void* ptr, size_t size, uint32_t caps) { ... } void esp_heap_trace_free_hook(void* ptr) { ... } void app_main() { ... } Heap Corruption Detection Heap corruption detection allows you to detect various types of heap memory errors: Out-of-bound writes & buffer overflows Writes to freed memory Reads from freed or uninitialized memory Assertions The heap implementation (heap/multi_heap.c, etc.) includes numerous assertions that will fail if the heap memory is corrupted. To detect heap corruption most effectively, ensure that assertions are enabled in the project configuration via the CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL option. If a heap integrity assertion fails, a line will be printed like CORRUPT HEAP: multi_heap.c:225 detected at 0x3ffbb71c . The memory address printed is the address of the heap structure that has corrupt content. It is also possible to manually check heap integrity by calling heap_caps_check_integrity_all() or related functions. This function checks all of the requested heap memory for integrity and can be used even if assertions are disabled. If the integrity checks detects an error, it will print the error along with the address(es) of corrupt heap structures. Memory Allocation Failed Hook Users can use heap_caps_register_failed_alloc_callback() to register a callback that is invoked every time an allocation operation fails. Additionally, users can enable the CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS, which will automatically trigger a system abort if any allocation operation fails. The example below shows how to register an allocation failure callback: #include "esp_heap_caps.h" void heap_caps_alloc_failed_hook(size_t requested_size, uint32_t caps, const char *function_name) { printf("%s was called but failed to allocate %d bytes with 0x%X capabilities. \n",function_name, requested_size, caps); } void app_main() { ... esp_err_t error = heap_caps_register_failed_alloc_callback(heap_caps_alloc_failed_hook); ... void *ptr = heap_caps_malloc(allocation_size, MALLOC_CAP_DEFAULT); ... } Finding Heap Corruption Memory corruption can be one of the hardest classes of bugs to find and fix, as the source of the corruption could be completely unrelated to the symptoms of the corruption. Here are some tips: A crash with a CORRUPT HEAP: message usually includes a stack trace, but this stack trace is rarely useful. The crash is the symptom of memory corruption when the system realizes the heap is corrupt. But usually, the corruption happens elsewhere and earlier in time. Increasing the heap memory debugging Configuration level to "Light impact" or "Comprehensive" gives you a more accurate message with the first corrupt memory address. Adding regular calls to heap_caps_check_integrity_all() or heap_caps_check_integrity_addr() in your code helps you pin down the exact time that the corruption happened. You can move these checks around to "close in on" the section of code that corrupted the heap. Based on the memory address that has been corrupted, you can use JTAG debugging to set a watchpoint on this address and have the CPU halt when it is written to. If you do not have JTAG, but you do know roughly when the corruption happens, set a watchpoint in software just beforehand via esp_cpu_set_watchpoint() . A fatal exception will occur when the watchpoint triggers. The following is an example of how to use the function - esp_cpu_set_watchpoint(0, (void *)addr, 4, ESP_WATCHPOINT_STORE) . Note that watchpoints are per-CPU and are set on the current running CPU only. So if you do not know which CPU is corrupting memory, call this function on both CPUs. For buffer overflows, heap tracing in HEAP_TRACE_ALL mode tells which callers are allocating which addresses from the heap. See Heap Tracing To Find Heap Corruption for more details. You can try to find the function that allocates memory with an address immediately before the corrupted address, since it is probably the function that overflows the buffer. Calling heap_caps_dump() or heap_caps_dump_all() can give an indication of what heap blocks are surrounding the corrupted region and may have overflowed or underflowed, etc. Configuration Temporarily increasing the heap corruption detection level can give more detailed information about heap corruption errors. In the project configuration menu, under Component config , there is a menu Heap memory debugging . The option CONFIG_HEAP_CORRUPTION_DETECTION can be set to one of the following three levels: Basic (No Poisoning) This is the default level. By default, no special heap corruption features are enabled, but the provided assertions are enabled. A heap corruption error will be printed if any of the heap's internal data structures appear overwritten or corrupted. This usually indicates a buffer overrun or out-of-bounds write. If assertions are enabled, an assertion will also trigger if a double-free occurs (the same memory is freed twice). Calling heap_caps_check_integrity() in Basic mode checks the integrity of all heap structures, and print errors if any appear to be corrupted. Light Impact At this level, heap memory is additionally "poisoned" with head and tail "canary bytes" before and after each block that is allocated. If an application writes outside the bounds of allocated buffers, the canary bytes will be corrupted, and the integrity check will fail. The head canary word is 0xABBA1234 ( 3412BAAB in byte order), and the tail canary word is 0xBAAD5678 ( 7856ADBA in byte order). With basic heap corruption checks, most out-of-bound writes can be detected and the number of overrun bytes before a failure is detected depends on the properties of the heap. However, the Light Impact mode is more precise as even a single-byte overrun can be detected. Enabling light-impact checking increases the memory usage. Each individual allocation uses 9 to 12 additional bytes of memory depending on alignment. Each time heap_caps_free() is called in Light Impact mode, the head and tail canary bytes of the buffer being freed are checked against the expected values. When heap_caps_check_integrity() is called, all allocated blocks of heap memory have their canary bytes checked against the expected values. In both cases, the functions involve checking that the first 4 bytes of an allocated block (before the buffer is returned to the user) should be the word 0xABBA1234 , and the last 4 bytes of the allocated block (after the buffer is returned to the user) should be the word 0xBAAD5678 . Different values usually indicate buffer underrun or overrun. Overrun indicates that when writing to memory, the data written exceeds the size of the allocated memory, resulting in writing to an unallocated memory area; underrun indicates that when reading memory, the data read exceeds the allocated memory and reads data from an unallocated memory area. Comprehensive This level incorporates the "light impact" detection features plus additional checks for uninitialized-access and use-after-free bugs. In this mode, all freshly allocated memory is filled with the pattern 0xCE , and all freed memory is filled with the pattern 0xFE . Enabling Comprehensive mode has a substantial impact on runtime performance, as all memory needs to be set to the allocation patterns each time a heap_caps_malloc() or heap_caps_free() completes, and the memory also needs to be checked each time. However, this mode allows easier detection of memory corruption bugs which are much more subtle to find otherwise. It is recommended to only enable this mode when debugging, not in production. Crashes in Comprehensive Mode If an application crashes when reading or writing an address related to 0xCECECECE in Comprehensive mode, it indicates that it has read uninitialized memory. The application should be changed to either use heap_caps_calloc() (which zeroes memory), or initialize the memory before using it. The value 0xCECECECE may also be seen in stack-allocated automatic variables, because, in ESP-IDF, most task stacks are originally allocated from the heap, and in C, stack memory is uninitialized by default. If an application crashes, and the exception register dump indicates that some addresses or values were 0xFEFEFEFE , this indicates that it is reading heap memory after it has been freed, i.e., a "use-after-free bug". The application should be changed to not access heap memory after it has been freed. If a call to heap_caps_malloc() or heap_caps_realloc() causes a crash because it was expected to find the pattern 0xFEFEFEFE in free memory and a different pattern was found, it indicates that the app has a use-after-free bug where it is writing to memory that has already been freed. Manual Heap Checks in Comprehensive Mode Calls to heap_caps_check_integrity() may print errors relating to 0xFEFEFEFE , 0xABBA1234 , or 0xBAAD5678 . In each case the checker is expected to find a given pattern, and will error out if not found: For free heap blocks, the checker expects to find all bytes set to 0xFE . Any other values indicate a use-after-free bug where free memory has been incorrectly overwritten. For allocated heap blocks, the behavior is the same as for the Light Impact mode. The canary bytes 0xABBA1234 and 0xBAAD5678 are checked at the head and tail of each allocated buffer, and any variation indicates a buffer overrun or underrun. Heap Task Tracking Heap Task Tracking can be used to get per-task info for heap memory allocation. The application has to specify the heap capabilities for which the heap allocation is to be tracked. Example code is provided in system/heap_task_tracking. Heap Tracing Heap Tracing allows the tracing of code which allocates or frees memory. Two tracing modes are supported: Standalone. In this mode, traced data are kept on-board, so the size of the gathered information is limited by the buffer assigned for that purpose, and the analysis is done by the on-board code. There are a couple of APIs available for accessing and dumping collected info. Host-based. This mode does not have the limitation of the standalone mode, because traced data are sent to the host over JTAG connection using app_trace library. Later on, they can be analyzed using special tools. Heap tracing can perform two functions: Leak checking: find memory that is allocated and never freed. Heap use analysis: show all functions that are allocating or freeing memory while the trace is running. How to Diagnose Memory Leaks If you suspect a memory leak, the first step is to figure out which part of the program is leaking memory. Use the heap_caps_get_free_size() or related functions in heap information to track memory use over the life of the application. Try to narrow the leak down to a single function or sequence of functions where free memory always decreases and never recovers. Standalone Mode Once you have identified the code which you think is leaking: Enable the CONFIG_HEAP_TRACING_DEST option. Call the function heap_trace_init_standalone() early in the program, to register a buffer that can be used to record the memory trace. Call the function heap_trace_start() to begin recording all mallocs or frees in the system. Call this immediately before the piece of code which you suspect is leaking memory. Call the function heap_trace_stop() to stop the trace once the suspect piece of code has finished executing. Call the function heap_trace_dump() to dump the results of the heap trace. The following code snippet demonstrates how application code would typically initialize, start, and stop heap tracing: #include "esp_heap_trace.h" #define NUM_RECORDS 100 static heap_trace_record_t trace_record[NUM_RECORDS]; // This buffer must be in internal RAM ... void app_main() { ... ESP_ERROR_CHECK( heap_trace_init_standalone(trace_record, NUM_RECORDS) ); ... } void some_function() { ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_LEAKS) ); do_something_you_suspect_is_leaking(); ESP_ERROR_CHECK( heap_trace_stop() ); heap_trace_dump(); ... } The output from the heap trace has a similar format to the following example: 2 allocations trace (100 entry buffer) 32 bytes (@ 0x3ffaf214) allocated CPU 0 ccount 0x2e9b7384 caller 0x400d276d:0x400d27c1 0x400d276d: leak_some_memory at /path/to/idf/examples/get-started/blink/main/./blink.c:27 0x400d27c1: blink_task at /path/to/idf/examples/get-started/blink/main/./blink.c:52 8 bytes (@ 0x3ffaf804) allocated CPU 0 ccount 0x2e9b79c0 caller 0x400d2776:0x400d27c1 0x400d2776: leak_some_memory at /path/to/idf/examples/get-started/blink/main/./blink.c:29 0x400d27c1: blink_task at /path/to/idf/examples/get-started/blink/main/./blink.c:52 40 bytes 'leaked' in trace (2 allocations) total allocations 2 total frees 0 Note The above example output uses IDF Monitor to automatically decode PC addresses to their source files and line numbers. The first line indicates how many allocation entries are in the buffer, compared to its total size. In HEAP_TRACE_LEAKS mode, for each traced memory allocation that has not already been freed, a line is printed with: XX bytes is the number of bytes allocated. @ 0x... is the heap address returned from heap_caps_malloc() or heap_caps_calloc() . Internal or PSRAM is the general location of the allocated memory. CPU x is the CPU (0 or 1) running when the allocation was made. ccount 0x... is the CCOUNT (CPU cycle count) register value the allocation was made. The value is different for CPU 0 vs CPU 1. caller 0x... gives the call stack of the call to heap_caps_malloc() or heap_caps_free() , as a list of PC addresses. These can be decoded to source files and line numbers, as shown above. The depth of the call stack recorded for each trace entry can be configured in the project configuration menu, under Heap Memory Debugging > Enable heap tracing > CONFIG_HEAP_TRACING_STACK_DEPTH. Up to 32 stack frames can be recorded for each allocation (the default is 2). Each additional stack frame increases the memory usage of each heap_trace_record_t record by eight bytes. Finally, the total number of the 'leaked' bytes (bytes allocated but not freed while the trace is running) is printed together with the total number of allocations it represents. A warning will be printed if the trace buffer was not large enough to hold all the allocations happened. If you see this warning, consider either shortening the tracing period or increasing the number of records in the trace buffer. Host-Based Mode Once you have identified the code which you think is leaking: In the project configuration menu, navigate to Component settings > Heap Memory Debugging > CONFIG_HEAP_TRACING_DEST and select Host-Based . In the project configuration menu, navigate to Component settings > Application Level Tracing > CONFIG_APPTRACE_DESTINATION1 and select Trace memory . In the project configuration menu, navigate to Component settings > Application Level Tracing > FreeRTOS SystemView Tracing and enable CONFIG_APPTRACE_SV_ENABLE. Call the function heap_trace_init_tohost() early in the program, to initialize the JTAG heap tracing module. Call the function heap_trace_start() to begin recording all memory allocation and free calls in the system. Call this immediately before the piece of code which you suspect is leaking memory. In host-based mode, the argument to this function is ignored, and the heap tracing module behaves like HEAP_TRACE_ALL is passed, i.e., all allocations and deallocations are sent to the host. Call the function heap_trace_stop() to stop the trace once the suspect piece of code has finished executing. The following code snippet demonstrates how application code would typically initialize, start, and stop host-based mode heap tracing: #include "esp_heap_trace.h" ... void app_main() { ... ESP_ERROR_CHECK( heap_trace_init_tohost() ); ... } void some_function() { ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_LEAKS) ); do_something_you_suspect_is_leaking(); ESP_ERROR_CHECK( heap_trace_stop() ); ... } To gather and analyze heap trace, do the following on the host: Build the program and download it to the target as described in Step 5. First Steps on ESP-IDF. Run OpenOCD (see JTAG Debugging). Note In order to use this feature, you need OpenOCD version v0.10.0-esp32-20181105 or later. You can use GDB to start and/or stop tracing automatically. To do this you need to prepare a special gdbinit file: target remote :3333 mon reset halt maintenance flush register-cache tb heap_trace_start commands mon esp sysview start file:///tmp/heap.svdat c end tb heap_trace_stop commands mon esp sysview stop end c Using this file GDB can connect to the target, reset it, and start tracing when the program hits breakpoint at heap_trace_start() . Tracing will be stopped when the program hits breakpoint at heap_trace_stop() . Traced data will be saved to /tmp/heap_log.svdat . Run GDB using xtensa-esp32-elf-gdb -x gdbinit </path/to/program/elf> . Quit GDB when the program stops at heap_trace_stop() . Traced data are saved in /tmp/heap.svdat . Run processing script $IDF_PATH/tools/esp_app_trace/sysviewtrace_proc.py -p -b </path/to/program/elf> /tmp/heap_log.svdat . The output from the heap trace has a similar format to the following example: Parse trace from '/tmp/heap.svdat'... Stop parsing trace. (Timeout 0.000000 sec while reading 1 bytes!) Process events from '['/tmp/heap.svdat']'... [0.002244575] HEAP: Allocated 1 bytes @ 0x3ffaffd8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.002258425] HEAP: Allocated 2 bytes @ 0x3ffaffe0 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:48 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.002563725] HEAP: Freed bytes @ 0x3ffaffe0 from task "free" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:31 (discriminator 9) /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.002782950] HEAP: Freed bytes @ 0x3ffb40b8 from task "main" on core 0 by: /home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590 /home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590 [0.002798700] HEAP: Freed bytes @ 0x3ffb50bc from task "main" on core 0 by: /home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590 /home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590 [0.102436025] HEAP: Allocated 2 bytes @ 0x3ffaffe0 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.102449800] HEAP: Allocated 4 bytes @ 0x3ffaffe8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:48 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.102666150] HEAP: Freed bytes @ 0x3ffaffe8 from task "free" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:31 (discriminator 9) /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.202436200] HEAP: Allocated 3 bytes @ 0x3ffaffe8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.202451725] HEAP: Allocated 6 bytes @ 0x3ffafff0 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:48 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.202667075] HEAP: Freed bytes @ 0x3ffafff0 from task "free" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:31 (discriminator 9) /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.302436000] HEAP: Allocated 4 bytes @ 0x3ffafff0 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.302451475] HEAP: Allocated 8 bytes @ 0x3ffb40b8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:48 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.302667500] HEAP: Freed bytes @ 0x3ffb40b8 from task "free" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:31 (discriminator 9) /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) Processing completed. Processed 1019 events =============== HEAP TRACE REPORT =============== Processed 14 heap events. [0.002244575] HEAP: Allocated 1 bytes @ 0x3ffaffd8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.102436025] HEAP: Allocated 2 bytes @ 0x3ffaffe0 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.202436200] HEAP: Allocated 3 bytes @ 0x3ffaffe8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.302436000] HEAP: Allocated 4 bytes @ 0x3ffafff0 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) Found 10 leaked bytes in 4 blocks. Heap Tracing To Find Heap Corruption Heap tracing can also be used to help track down heap corruption. When a region in the heap is corrupted, it may be from some other part of the program that allocated memory at a nearby address. If you have an approximate idea of when the corruption occurred, enabling heap tracing in HEAP_TRACE_ALL mode allows you to record all the memory allocation functions used and the corresponding allocation addresses. Using heap tracing in this way is very similar to memory leak detection as described above. For memories that are allocated and not freed, the output is the same. However, records will also be shown for memory that has been freed. Performance Impact Enabling heap tracing in menuconfig increases the code size of your program, and has a very small negative impact on the performance of heap allocation or free operations even when heap tracing is not running. When heap tracing is running, heap allocation or free operations are substantially slower than when heap tracing is stopped. Increasing the depth of stack frames recorded for each allocation (see above) also increases this performance impact. To mitigate the performance loss when the heap tracing is enabled and active, enable CONFIG_HEAP_TRACE_HASH_MAP. With this configuration enabled, a hash map mechanism will be used to handle the heap trace records, thus considerably decreasing the heap allocation or free execution time. The size of the hash map can be modified by setting the value of CONFIG_HEAP_TRACE_HASH_MAP_SIZE. By default, the hash map is placed into internal RAM. It can also be placed into external RAM if CONFIG_HEAP_TRACE_HASH_MAP_IN_EXT_RAM is enabled. In order to enable this configuration, make sure to enable CONFIG_SPIRAM and CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY. False-Positive Memory Leaks Not everything printed by heap_trace_dump() is necessarily a memory leak. The following cases may also be printed: Any memory that is allocated after heap_trace_start() but freed after heap_trace_stop() appears in the leaked dump. Allocations may be made by other tasks in the system. Depending on the timing of these tasks, it is quite possible that this memory is freed after heap_trace_stop() is called. The first time a task uses stdio - e.g., when it calls heap_caps_printf() - a lock, i.e., RTOS mutex semaphore, is allocated by the libc. This allocation lasts until the task is deleted. Certain uses of heap_caps_printf() , such as printing floating point numbers and allocating some memory from the heap on demand. These allocations last until the task is deleted. The Bluetooth, Wi-Fi, and TCP/IP libraries allocate heap memory buffers to handle incoming or outgoing data. These memory buffers are usually short-lived, but some may be shown in the heap leak trace if the data has been received or transmitted by the lower levels of the network during the heap tracing. TCP connections retain some memory even after they are closed due to the TIME_WAIT state. Once the TIME_WAIT period is completed, this memory will be freed. One way to differentiate between "real" and "false positive" memory leaks is to call the suspect code multiple times while tracing is running, and look for patterns (multiple matching allocations) in the heap trace output. API Reference - Heap Tracing Header File This header file can be included with: #include "esp_heap_trace.h" Functions esp_err_t heap_trace_init_standalone(heap_trace_record_t *record_buffer, size_t num_records) Initialise heap tracing in standalone mode. This function must be called before any other heap tracing functions. To disable heap tracing and allow the buffer to be freed, stop tracing and then call heap_trace_init_standalone(NULL, 0); Parameters record_buffer -- Provide a buffer to use for heap trace data. Note: External RAM is allowed, but it prevents recording allocations made from ISR's. num_records -- Size of the heap trace buffer, as number of record structures. record_buffer -- Provide a buffer to use for heap trace data. Note: External RAM is allowed, but it prevents recording allocations made from ISR's. num_records -- Size of the heap trace buffer, as number of record structures. record_buffer -- Provide a buffer to use for heap trace data. Note: External RAM is allowed, but it prevents recording allocations made from ISR's. Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing is currently in progress. ESP_OK Heap tracing initialised successfully. ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing is currently in progress. ESP_OK Heap tracing initialised successfully. ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. Parameters record_buffer -- Provide a buffer to use for heap trace data. Note: External RAM is allowed, but it prevents recording allocations made from ISR's. num_records -- Size of the heap trace buffer, as number of record structures. Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing is currently in progress. ESP_OK Heap tracing initialised successfully. esp_err_t heap_trace_init_tohost(void) Initialise heap tracing in host-based mode. This function must be called before any other heap tracing functions. Returns ESP_ERR_INVALID_STATE Heap tracing is currently in progress. ESP_OK Heap tracing initialised successfully. ESP_ERR_INVALID_STATE Heap tracing is currently in progress. ESP_OK Heap tracing initialised successfully. ESP_ERR_INVALID_STATE Heap tracing is currently in progress. Returns ESP_ERR_INVALID_STATE Heap tracing is currently in progress. ESP_OK Heap tracing initialised successfully. esp_err_t heap_trace_start(heap_trace_mode_t mode) Start heap tracing. All heap allocations & frees will be traced, until heap_trace_stop() is called. Note heap_trace_init_standalone() must be called to provide a valid buffer, before this function is called. Note Calling this function while heap tracing is running will reset the heap trace state and continue tracing. Parameters mode -- Mode for tracing. HEAP_TRACE_ALL means all heap allocations and frees are traced. HEAP_TRACE_LEAKS means only suspected memory leaks are traced. (When memory is freed, the record is removed from the trace buffer.) HEAP_TRACE_ALL means all heap allocations and frees are traced. HEAP_TRACE_LEAKS means only suspected memory leaks are traced. (When memory is freed, the record is removed from the trace buffer.) HEAP_TRACE_ALL means all heap allocations and frees are traced. Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE A non-zero-length buffer has not been set via heap_trace_init_standalone(). ESP_OK Tracing is started. ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE A non-zero-length buffer has not been set via heap_trace_init_standalone(). ESP_OK Tracing is started. ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. Parameters mode -- Mode for tracing. HEAP_TRACE_ALL means all heap allocations and frees are traced. HEAP_TRACE_LEAKS means only suspected memory leaks are traced. (When memory is freed, the record is removed from the trace buffer.) Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE A non-zero-length buffer has not been set via heap_trace_init_standalone(). ESP_OK Tracing is started. esp_err_t heap_trace_stop(void) Stop heap tracing. Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing was not in progress. ESP_OK Heap tracing stopped.. ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing was not in progress. ESP_OK Heap tracing stopped.. ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing was not in progress. ESP_OK Heap tracing stopped.. esp_err_t heap_trace_resume(void) Resume heap tracing which was previously stopped. Unlike heap_trace_start(), this function does not clear the buffer of any pre-existing trace records. The heap trace mode is the same as when heap_trace_start() was last called (or HEAP_TRACE_ALL if heap_trace_start() was never called). Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing was already started. ESP_OK Heap tracing resumed. ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing was already started. ESP_OK Heap tracing resumed. ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing was already started. ESP_OK Heap tracing resumed. size_t heap_trace_get_count(void) Return number of records in the heap trace buffer. It is safe to call this function while heap tracing is running. esp_err_t heap_trace_get(size_t index, heap_trace_record_t *record) Return a raw record from the heap trace buffer. Note It is safe to call this function while heap tracing is running, however in HEAP_TRACE_LEAK mode record indexing may skip entries unless heap tracing is stopped first. Parameters index -- Index (zero-based) of the record to return. record -- [out] Record where the heap trace record will be copied. index -- Index (zero-based) of the record to return. record -- [out] Record where the heap trace record will be copied. index -- Index (zero-based) of the record to return. Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing was not initialised. ESP_ERR_INVALID_ARG Index is out of bounds for current heap trace record count. ESP_OK Record returned successfully. ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing was not initialised. ESP_ERR_INVALID_ARG Index is out of bounds for current heap trace record count. ESP_OK Record returned successfully. ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. Parameters index -- Index (zero-based) of the record to return. record -- [out] Record where the heap trace record will be copied. Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing was not initialised. ESP_ERR_INVALID_ARG Index is out of bounds for current heap trace record count. ESP_OK Record returned successfully. void heap_trace_dump(void) Dump heap trace record data to stdout. Note It is safe to call this function while heap tracing is running, however in HEAP_TRACE_LEAK mode the dump may skip entries unless heap tracing is stopped first. void heap_trace_dump_caps(const uint32_t caps) Dump heap trace from the memory of the capabilities passed as parameter. Parameters caps -- Capability(ies) of the memory from which to dump the trace. Set MALLOC_CAP_INTERNAL to dump heap trace data from internal memory. Set MALLOC_CAP_SPIRAM to dump heap trace data from PSRAM. Set both to dump both heap trace data. Parameters caps -- Capability(ies) of the memory from which to dump the trace. Set MALLOC_CAP_INTERNAL to dump heap trace data from internal memory. Set MALLOC_CAP_SPIRAM to dump heap trace data from PSRAM. Set both to dump both heap trace data. esp_err_t heap_trace_summary(heap_trace_summary_t *summary) Get summary information about the result of a heap trace. Note It is safe to call this function while heap tracing is running. Structures struct heap_trace_record_t Trace record data type. Stores information about an allocated region of memory. Public Members uint32_t ccount CCOUNT of the CPU when the allocation was made. LSB (bit value 1) is the CPU number (0 or 1). uint32_t ccount CCOUNT of the CPU when the allocation was made. LSB (bit value 1) is the CPU number (0 or 1). void *address Address which was allocated. If NULL, then this record is empty. void *address Address which was allocated. If NULL, then this record is empty. size_t size Size of the allocation. size_t size Size of the allocation. void *alloced_by[CONFIG_HEAP_TRACING_STACK_DEPTH] Call stack of the caller which allocated the memory. void *alloced_by[CONFIG_HEAP_TRACING_STACK_DEPTH] Call stack of the caller which allocated the memory. void *freed_by[CONFIG_HEAP_TRACING_STACK_DEPTH] Call stack of the caller which freed the memory (all zero if not freed.) void *freed_by[CONFIG_HEAP_TRACING_STACK_DEPTH] Call stack of the caller which freed the memory (all zero if not freed.) uint32_t ccount struct heap_trace_summary_t Stores information about the result of a heap trace. Public Members heap_trace_mode_t mode The heap trace mode we just completed / are running. heap_trace_mode_t mode The heap trace mode we just completed / are running. size_t total_allocations The total number of allocations made during tracing. size_t total_allocations The total number of allocations made during tracing. size_t total_frees The total number of frees made during tracing. size_t total_frees The total number of frees made during tracing. size_t count The number of records in the internal buffer. size_t count The number of records in the internal buffer. size_t capacity The capacity of the internal buffer. size_t capacity The capacity of the internal buffer. size_t high_water_mark The maximum value that 'count' got to. size_t high_water_mark The maximum value that 'count' got to. size_t has_overflowed True if the internal buffer overflowed at some point. size_t has_overflowed True if the internal buffer overflowed at some point. heap_trace_mode_t mode Macros CONFIG_HEAP_TRACING_STACK_DEPTH Type Definitions typedef struct heap_trace_record_t heap_trace_record_t Trace record data type. Stores information about an allocated region of memory.
Heap Memory Debugging Overview ESP-IDF integrates tools for requesting heap information, heap corruption detection, and heap tracing. These can help track down memory-related bugs. For general information about the heap memory allocator, see Heap Memory Allocation. Heap Information To obtain information about the state of the heap, call the following functions: heap_caps_get_free_size()can be used to return the current free memory for different memory capabilities. heap_caps_get_largest_free_block()can be used to return the largest free block in the heap, which is also the largest single allocation currently possible. Tracking this value and comparing it to the total free heap allows you to detect heap fragmentation. heap_caps_get_minimum_free_size()can be used to track the heap "low watermark" since boot. heap_caps_get_info()returns a multi_heap_info_tstructure, which contains the information from the above functions, plus some additional heap-specific data (number of allocations, etc.). heap_caps_print_heap_info()prints a summary of the information returned by heap_caps_get_info()to stdout. heap_caps_dump()and heap_caps_dump_all()output detailed information about the structure of each block in the heap. Note that this can be a large amount of output. Heap Allocation and Free Function Hooks Heap allocation and free detection hooks allow you to be notified of every successful allocation and free operation: Providing a definition of esp_heap_trace_alloc_hook()allows you to be notified of every successful memory allocation operation Providing a definition of esp_heap_trace_free_hook()allows you to be notified of every successful memory-free operations This feature can be enabled by setting the CONFIG_HEAP_USE_HOOKS option. esp_heap_trace_alloc_hook() and esp_heap_trace_free_hook() have weak declarations (e.g., __attribute__((weak))), thus it is not necessary to provide declarations for both hooks. Given that it is technically possible to allocate and free memory from an ISR (though strongly discouraged from doing so), the esp_heap_trace_alloc_hook() and esp_heap_trace_free_hook() can potentially be called from an ISR. It is not recommended to perform (or call API functions to perform) blocking operations or memory allocation/free operations in the hook functions. In general, the best practice is to keep the implementation concise and leave the heavy computation outside of the hook functions. The example below shows how to define the allocation and free function hooks: #include "esp_heap_caps.h" void esp_heap_trace_alloc_hook(void* ptr, size_t size, uint32_t caps) { ... } void esp_heap_trace_free_hook(void* ptr) { ... } void app_main() { ... } Heap Corruption Detection Heap corruption detection allows you to detect various types of heap memory errors: Out-of-bound writes & buffer overflows Writes to freed memory Reads from freed or uninitialized memory Assertions The heap implementation (heap/multi_heap.c, etc.) includes numerous assertions that will fail if the heap memory is corrupted. To detect heap corruption most effectively, ensure that assertions are enabled in the project configuration via the CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL option. If a heap integrity assertion fails, a line will be printed like CORRUPT HEAP: multi_heap.c:225 detected at 0x3ffbb71c. The memory address printed is the address of the heap structure that has corrupt content. It is also possible to manually check heap integrity by calling heap_caps_check_integrity_all() or related functions. This function checks all of the requested heap memory for integrity and can be used even if assertions are disabled. If the integrity checks detects an error, it will print the error along with the address(es) of corrupt heap structures. Memory Allocation Failed Hook Users can use heap_caps_register_failed_alloc_callback() to register a callback that is invoked every time an allocation operation fails. Additionally, users can enable the CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS, which will automatically trigger a system abort if any allocation operation fails. The example below shows how to register an allocation failure callback: #include "esp_heap_caps.h" void heap_caps_alloc_failed_hook(size_t requested_size, uint32_t caps, const char *function_name) { printf("%s was called but failed to allocate %d bytes with 0x%X capabilities. \n",function_name, requested_size, caps); } void app_main() { ... esp_err_t error = heap_caps_register_failed_alloc_callback(heap_caps_alloc_failed_hook); ... void *ptr = heap_caps_malloc(allocation_size, MALLOC_CAP_DEFAULT); ... } Finding Heap Corruption Memory corruption can be one of the hardest classes of bugs to find and fix, as the source of the corruption could be completely unrelated to the symptoms of the corruption. Here are some tips: A crash with a CORRUPT HEAP:message usually includes a stack trace, but this stack trace is rarely useful. The crash is the symptom of memory corruption when the system realizes the heap is corrupt. But usually, the corruption happens elsewhere and earlier in time. Increasing the heap memory debugging Configuration level to "Light impact" or "Comprehensive" gives you a more accurate message with the first corrupt memory address. Adding regular calls to heap_caps_check_integrity_all()or heap_caps_check_integrity_addr()in your code helps you pin down the exact time that the corruption happened. You can move these checks around to "close in on" the section of code that corrupted the heap. Based on the memory address that has been corrupted, you can use JTAG debugging to set a watchpoint on this address and have the CPU halt when it is written to. If you do not have JTAG, but you do know roughly when the corruption happens, set a watchpoint in software just beforehand via esp_cpu_set_watchpoint(). A fatal exception will occur when the watchpoint triggers. The following is an example of how to use the function - esp_cpu_set_watchpoint(0, (void *)addr, 4, ESP_WATCHPOINT_STORE). Note that watchpoints are per-CPU and are set on the current running CPU only. So if you do not know which CPU is corrupting memory, call this function on both CPUs. For buffer overflows, heap tracing in HEAP_TRACE_ALLmode tells which callers are allocating which addresses from the heap. See Heap Tracing To Find Heap Corruption for more details. You can try to find the function that allocates memory with an address immediately before the corrupted address, since it is probably the function that overflows the buffer. Calling heap_caps_dump()or heap_caps_dump_all()can give an indication of what heap blocks are surrounding the corrupted region and may have overflowed or underflowed, etc. Configuration Temporarily increasing the heap corruption detection level can give more detailed information about heap corruption errors. In the project configuration menu, under Component config, there is a menu Heap memory debugging. The option CONFIG_HEAP_CORRUPTION_DETECTION can be set to one of the following three levels: Basic (No Poisoning) This is the default level. By default, no special heap corruption features are enabled, but the provided assertions are enabled. A heap corruption error will be printed if any of the heap's internal data structures appear overwritten or corrupted. This usually indicates a buffer overrun or out-of-bounds write. If assertions are enabled, an assertion will also trigger if a double-free occurs (the same memory is freed twice). Calling heap_caps_check_integrity() in Basic mode checks the integrity of all heap structures, and print errors if any appear to be corrupted. Light Impact At this level, heap memory is additionally "poisoned" with head and tail "canary bytes" before and after each block that is allocated. If an application writes outside the bounds of allocated buffers, the canary bytes will be corrupted, and the integrity check will fail. The head canary word is 0xABBA1234 ( 3412BAAB in byte order), and the tail canary word is 0xBAAD5678 ( 7856ADBA in byte order). With basic heap corruption checks, most out-of-bound writes can be detected and the number of overrun bytes before a failure is detected depends on the properties of the heap. However, the Light Impact mode is more precise as even a single-byte overrun can be detected. Enabling light-impact checking increases the memory usage. Each individual allocation uses 9 to 12 additional bytes of memory depending on alignment. Each time heap_caps_free() is called in Light Impact mode, the head and tail canary bytes of the buffer being freed are checked against the expected values. When heap_caps_check_integrity() is called, all allocated blocks of heap memory have their canary bytes checked against the expected values. In both cases, the functions involve checking that the first 4 bytes of an allocated block (before the buffer is returned to the user) should be the word 0xABBA1234, and the last 4 bytes of the allocated block (after the buffer is returned to the user) should be the word 0xBAAD5678. Different values usually indicate buffer underrun or overrun. Overrun indicates that when writing to memory, the data written exceeds the size of the allocated memory, resulting in writing to an unallocated memory area; underrun indicates that when reading memory, the data read exceeds the allocated memory and reads data from an unallocated memory area. Comprehensive This level incorporates the "light impact" detection features plus additional checks for uninitialized-access and use-after-free bugs. In this mode, all freshly allocated memory is filled with the pattern 0xCE, and all freed memory is filled with the pattern 0xFE. Enabling Comprehensive mode has a substantial impact on runtime performance, as all memory needs to be set to the allocation patterns each time a heap_caps_malloc() or heap_caps_free() completes, and the memory also needs to be checked each time. However, this mode allows easier detection of memory corruption bugs which are much more subtle to find otherwise. It is recommended to only enable this mode when debugging, not in production. Crashes in Comprehensive Mode If an application crashes when reading or writing an address related to 0xCECECECE in Comprehensive mode, it indicates that it has read uninitialized memory. The application should be changed to either use heap_caps_calloc() (which zeroes memory), or initialize the memory before using it. The value 0xCECECECE may also be seen in stack-allocated automatic variables, because, in ESP-IDF, most task stacks are originally allocated from the heap, and in C, stack memory is uninitialized by default. If an application crashes, and the exception register dump indicates that some addresses or values were 0xFEFEFEFE, this indicates that it is reading heap memory after it has been freed, i.e., a "use-after-free bug". The application should be changed to not access heap memory after it has been freed. If a call to heap_caps_malloc() or heap_caps_realloc() causes a crash because it was expected to find the pattern 0xFEFEFEFE in free memory and a different pattern was found, it indicates that the app has a use-after-free bug where it is writing to memory that has already been freed. Manual Heap Checks in Comprehensive Mode Calls to heap_caps_check_integrity() may print errors relating to 0xFEFEFEFE, 0xABBA1234, or 0xBAAD5678. In each case the checker is expected to find a given pattern, and will error out if not found: For free heap blocks, the checker expects to find all bytes set to 0xFE. Any other values indicate a use-after-free bug where free memory has been incorrectly overwritten. For allocated heap blocks, the behavior is the same as for the Light Impact mode. The canary bytes 0xABBA1234and 0xBAAD5678are checked at the head and tail of each allocated buffer, and any variation indicates a buffer overrun or underrun. Heap Task Tracking Heap Task Tracking can be used to get per-task info for heap memory allocation. The application has to specify the heap capabilities for which the heap allocation is to be tracked. Example code is provided in system/heap_task_tracking. Heap Tracing Heap Tracing allows the tracing of code which allocates or frees memory. Two tracing modes are supported: Standalone. In this mode, traced data are kept on-board, so the size of the gathered information is limited by the buffer assigned for that purpose, and the analysis is done by the on-board code. There are a couple of APIs available for accessing and dumping collected info. Host-based. This mode does not have the limitation of the standalone mode, because traced data are sent to the host over JTAG connection using app_trace library. Later on, they can be analyzed using special tools. Heap tracing can perform two functions: Leak checking: find memory that is allocated and never freed. Heap use analysis: show all functions that are allocating or freeing memory while the trace is running. How to Diagnose Memory Leaks If you suspect a memory leak, the first step is to figure out which part of the program is leaking memory. Use the heap_caps_get_free_size() or related functions in heap information to track memory use over the life of the application. Try to narrow the leak down to a single function or sequence of functions where free memory always decreases and never recovers. Standalone Mode Once you have identified the code which you think is leaking: Enable the CONFIG_HEAP_TRACING_DEST option. Call the function heap_trace_init_standalone()early in the program, to register a buffer that can be used to record the memory trace. Call the function heap_trace_start()to begin recording all mallocs or frees in the system. Call this immediately before the piece of code which you suspect is leaking memory. Call the function heap_trace_stop()to stop the trace once the suspect piece of code has finished executing. Call the function heap_trace_dump()to dump the results of the heap trace. The following code snippet demonstrates how application code would typically initialize, start, and stop heap tracing: #include "esp_heap_trace.h" #define NUM_RECORDS 100 static heap_trace_record_t trace_record[NUM_RECORDS]; // This buffer must be in internal RAM ... void app_main() { ... ESP_ERROR_CHECK( heap_trace_init_standalone(trace_record, NUM_RECORDS) ); ... } void some_function() { ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_LEAKS) ); do_something_you_suspect_is_leaking(); ESP_ERROR_CHECK( heap_trace_stop() ); heap_trace_dump(); ... } The output from the heap trace has a similar format to the following example: 2 allocations trace (100 entry buffer) 32 bytes (@ 0x3ffaf214) allocated CPU 0 ccount 0x2e9b7384 caller 0x400d276d:0x400d27c1 0x400d276d: leak_some_memory at /path/to/idf/examples/get-started/blink/main/./blink.c:27 0x400d27c1: blink_task at /path/to/idf/examples/get-started/blink/main/./blink.c:52 8 bytes (@ 0x3ffaf804) allocated CPU 0 ccount 0x2e9b79c0 caller 0x400d2776:0x400d27c1 0x400d2776: leak_some_memory at /path/to/idf/examples/get-started/blink/main/./blink.c:29 0x400d27c1: blink_task at /path/to/idf/examples/get-started/blink/main/./blink.c:52 40 bytes 'leaked' in trace (2 allocations) total allocations 2 total frees 0 Note The above example output uses IDF Monitor to automatically decode PC addresses to their source files and line numbers. The first line indicates how many allocation entries are in the buffer, compared to its total size. In HEAP_TRACE_LEAKS mode, for each traced memory allocation that has not already been freed, a line is printed with: XX bytesis the number of bytes allocated. @ 0x...is the heap address returned from heap_caps_malloc()or heap_caps_calloc(). Internalor PSRAMis the general location of the allocated memory. CPU xis the CPU (0 or 1) running when the allocation was made. ccount 0x...is the CCOUNT (CPU cycle count) register value the allocation was made. The value is different for CPU 0 vs CPU 1. caller 0x...gives the call stack of the call to heap_caps_malloc()or heap_caps_free(), as a list of PC addresses. These can be decoded to source files and line numbers, as shown above. The depth of the call stack recorded for each trace entry can be configured in the project configuration menu, under Heap Memory Debugging > Enable heap tracing > CONFIG_HEAP_TRACING_STACK_DEPTH. Up to 32 stack frames can be recorded for each allocation (the default is 2). Each additional stack frame increases the memory usage of each heap_trace_record_t record by eight bytes. Finally, the total number of the 'leaked' bytes (bytes allocated but not freed while the trace is running) is printed together with the total number of allocations it represents. A warning will be printed if the trace buffer was not large enough to hold all the allocations happened. If you see this warning, consider either shortening the tracing period or increasing the number of records in the trace buffer. Host-Based Mode Once you have identified the code which you think is leaking: In the project configuration menu, navigate to Component settings> Heap Memory Debugging> CONFIG_HEAP_TRACING_DEST and select Host-Based. In the project configuration menu, navigate to Component settings> Application Level Tracing> CONFIG_APPTRACE_DESTINATION1 and select Trace memory. In the project configuration menu, navigate to Component settings> Application Level Tracing> FreeRTOS SystemView Tracingand enable CONFIG_APPTRACE_SV_ENABLE. Call the function heap_trace_init_tohost()early in the program, to initialize the JTAG heap tracing module. Call the function heap_trace_start()to begin recording all memory allocation and free calls in the system. Call this immediately before the piece of code which you suspect is leaking memory. In host-based mode, the argument to this function is ignored, and the heap tracing module behaves like HEAP_TRACE_ALLis passed, i.e., all allocations and deallocations are sent to the host. Call the function heap_trace_stop()to stop the trace once the suspect piece of code has finished executing. The following code snippet demonstrates how application code would typically initialize, start, and stop host-based mode heap tracing: #include "esp_heap_trace.h" ... void app_main() { ... ESP_ERROR_CHECK( heap_trace_init_tohost() ); ... } void some_function() { ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_LEAKS) ); do_something_you_suspect_is_leaking(); ESP_ERROR_CHECK( heap_trace_stop() ); ... } To gather and analyze heap trace, do the following on the host: Build the program and download it to the target as described in Step 5. First Steps on ESP-IDF. Run OpenOCD (see JTAG Debugging). Note In order to use this feature, you need OpenOCD version v0.10.0-esp32-20181105 or later. You can use GDB to start and/or stop tracing automatically. To do this you need to prepare a special gdbinitfile: target remote :3333 mon reset halt maintenance flush register-cache tb heap_trace_start commands mon esp sysview start file:///tmp/heap.svdat c end tb heap_trace_stop commands mon esp sysview stop end c Using this file GDB can connect to the target, reset it, and start tracing when the program hits breakpoint at heap_trace_start(). Tracing will be stopped when the program hits breakpoint at heap_trace_stop(). Traced data will be saved to /tmp/heap_log.svdat. Run GDB using xtensa-esp32-elf-gdb -x gdbinit </path/to/program/elf>. Quit GDB when the program stops at heap_trace_stop(). Traced data are saved in /tmp/heap.svdat. Run processing script $IDF_PATH/tools/esp_app_trace/sysviewtrace_proc.py -p -b </path/to/program/elf> /tmp/heap_log.svdat. The output from the heap trace has a similar format to the following example: Parse trace from '/tmp/heap.svdat'... Stop parsing trace. (Timeout 0.000000 sec while reading 1 bytes!) Process events from '['/tmp/heap.svdat']'... [0.002244575] HEAP: Allocated 1 bytes @ 0x3ffaffd8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.002258425] HEAP: Allocated 2 bytes @ 0x3ffaffe0 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:48 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.002563725] HEAP: Freed bytes @ 0x3ffaffe0 from task "free" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:31 (discriminator 9) /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.002782950] HEAP: Freed bytes @ 0x3ffb40b8 from task "main" on core 0 by: /home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590 /home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590 [0.002798700] HEAP: Freed bytes @ 0x3ffb50bc from task "main" on core 0 by: /home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590 /home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590 [0.102436025] HEAP: Allocated 2 bytes @ 0x3ffaffe0 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.102449800] HEAP: Allocated 4 bytes @ 0x3ffaffe8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:48 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.102666150] HEAP: Freed bytes @ 0x3ffaffe8 from task "free" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:31 (discriminator 9) /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.202436200] HEAP: Allocated 3 bytes @ 0x3ffaffe8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.202451725] HEAP: Allocated 6 bytes @ 0x3ffafff0 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:48 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.202667075] HEAP: Freed bytes @ 0x3ffafff0 from task "free" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:31 (discriminator 9) /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.302436000] HEAP: Allocated 4 bytes @ 0x3ffafff0 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.302451475] HEAP: Allocated 8 bytes @ 0x3ffb40b8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:48 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.302667500] HEAP: Freed bytes @ 0x3ffb40b8 from task "free" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:31 (discriminator 9) /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) Processing completed. Processed 1019 events =============== HEAP TRACE REPORT =============== Processed 14 heap events. [0.002244575] HEAP: Allocated 1 bytes @ 0x3ffaffd8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.102436025] HEAP: Allocated 2 bytes @ 0x3ffaffe0 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.202436200] HEAP: Allocated 3 bytes @ 0x3ffaffe8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.302436000] HEAP: Allocated 4 bytes @ 0x3ffafff0 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) Found 10 leaked bytes in 4 blocks. Heap Tracing To Find Heap Corruption Heap tracing can also be used to help track down heap corruption. When a region in the heap is corrupted, it may be from some other part of the program that allocated memory at a nearby address. If you have an approximate idea of when the corruption occurred, enabling heap tracing in HEAP_TRACE_ALL mode allows you to record all the memory allocation functions used and the corresponding allocation addresses. Using heap tracing in this way is very similar to memory leak detection as described above. For memories that are allocated and not freed, the output is the same. However, records will also be shown for memory that has been freed. Performance Impact Enabling heap tracing in menuconfig increases the code size of your program, and has a very small negative impact on the performance of heap allocation or free operations even when heap tracing is not running. When heap tracing is running, heap allocation or free operations are substantially slower than when heap tracing is stopped. Increasing the depth of stack frames recorded for each allocation (see above) also increases this performance impact. To mitigate the performance loss when the heap tracing is enabled and active, enable CONFIG_HEAP_TRACE_HASH_MAP. With this configuration enabled, a hash map mechanism will be used to handle the heap trace records, thus considerably decreasing the heap allocation or free execution time. The size of the hash map can be modified by setting the value of CONFIG_HEAP_TRACE_HASH_MAP_SIZE. By default, the hash map is placed into internal RAM. It can also be placed into external RAM if CONFIG_HEAP_TRACE_HASH_MAP_IN_EXT_RAM is enabled. In order to enable this configuration, make sure to enable CONFIG_SPIRAM and CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY. False-Positive Memory Leaks Not everything printed by heap_trace_dump() is necessarily a memory leak. The following cases may also be printed: Any memory that is allocated after heap_trace_start()but freed after heap_trace_stop()appears in the leaked dump. Allocations may be made by other tasks in the system. Depending on the timing of these tasks, it is quite possible that this memory is freed after heap_trace_stop()is called. The first time a task uses stdio - e.g., when it calls heap_caps_printf()- a lock, i.e., RTOS mutex semaphore, is allocated by the libc. This allocation lasts until the task is deleted. Certain uses of heap_caps_printf(), such as printing floating point numbers and allocating some memory from the heap on demand. These allocations last until the task is deleted. The Bluetooth, Wi-Fi, and TCP/IP libraries allocate heap memory buffers to handle incoming or outgoing data. These memory buffers are usually short-lived, but some may be shown in the heap leak trace if the data has been received or transmitted by the lower levels of the network during the heap tracing. TCP connections retain some memory even after they are closed due to the TIME_WAITstate. Once the TIME_WAITperiod is completed, this memory will be freed. One way to differentiate between "real" and "false positive" memory leaks is to call the suspect code multiple times while tracing is running, and look for patterns (multiple matching allocations) in the heap trace output. API Reference - Heap Tracing Header File This header file can be included with: #include "esp_heap_trace.h" Functions - esp_err_t heap_trace_init_standalone(heap_trace_record_t *record_buffer, size_t num_records) Initialise heap tracing in standalone mode. This function must be called before any other heap tracing functions. To disable heap tracing and allow the buffer to be freed, stop tracing and then call heap_trace_init_standalone(NULL, 0); - Parameters record_buffer -- Provide a buffer to use for heap trace data. Note: External RAM is allowed, but it prevents recording allocations made from ISR's. num_records -- Size of the heap trace buffer, as number of record structures. - - Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing is currently in progress. ESP_OK Heap tracing initialised successfully. - - esp_err_t heap_trace_init_tohost(void) Initialise heap tracing in host-based mode. This function must be called before any other heap tracing functions. - Returns ESP_ERR_INVALID_STATE Heap tracing is currently in progress. ESP_OK Heap tracing initialised successfully. - - esp_err_t heap_trace_start(heap_trace_mode_t mode) Start heap tracing. All heap allocations & frees will be traced, until heap_trace_stop() is called. Note heap_trace_init_standalone() must be called to provide a valid buffer, before this function is called. Note Calling this function while heap tracing is running will reset the heap trace state and continue tracing. - Parameters mode -- Mode for tracing. HEAP_TRACE_ALL means all heap allocations and frees are traced. HEAP_TRACE_LEAKS means only suspected memory leaks are traced. (When memory is freed, the record is removed from the trace buffer.) - - Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE A non-zero-length buffer has not been set via heap_trace_init_standalone(). ESP_OK Tracing is started. - - esp_err_t heap_trace_stop(void) Stop heap tracing. - Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing was not in progress. ESP_OK Heap tracing stopped.. - - esp_err_t heap_trace_resume(void) Resume heap tracing which was previously stopped. Unlike heap_trace_start(), this function does not clear the buffer of any pre-existing trace records. The heap trace mode is the same as when heap_trace_start() was last called (or HEAP_TRACE_ALL if heap_trace_start() was never called). - Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing was already started. ESP_OK Heap tracing resumed. - - size_t heap_trace_get_count(void) Return number of records in the heap trace buffer. It is safe to call this function while heap tracing is running. - esp_err_t heap_trace_get(size_t index, heap_trace_record_t *record) Return a raw record from the heap trace buffer. Note It is safe to call this function while heap tracing is running, however in HEAP_TRACE_LEAK mode record indexing may skip entries unless heap tracing is stopped first. - Parameters index -- Index (zero-based) of the record to return. record -- [out] Record where the heap trace record will be copied. - - Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing was not initialised. ESP_ERR_INVALID_ARG Index is out of bounds for current heap trace record count. ESP_OK Record returned successfully. - - void heap_trace_dump(void) Dump heap trace record data to stdout. Note It is safe to call this function while heap tracing is running, however in HEAP_TRACE_LEAK mode the dump may skip entries unless heap tracing is stopped first. - void heap_trace_dump_caps(const uint32_t caps) Dump heap trace from the memory of the capabilities passed as parameter. - Parameters caps -- Capability(ies) of the memory from which to dump the trace. Set MALLOC_CAP_INTERNAL to dump heap trace data from internal memory. Set MALLOC_CAP_SPIRAM to dump heap trace data from PSRAM. Set both to dump both heap trace data. - esp_err_t heap_trace_summary(heap_trace_summary_t *summary) Get summary information about the result of a heap trace. Note It is safe to call this function while heap tracing is running. Structures - struct heap_trace_record_t Trace record data type. Stores information about an allocated region of memory. Public Members - uint32_t ccount CCOUNT of the CPU when the allocation was made. LSB (bit value 1) is the CPU number (0 or 1). - void *address Address which was allocated. If NULL, then this record is empty. - size_t size Size of the allocation. - void *alloced_by[CONFIG_HEAP_TRACING_STACK_DEPTH] Call stack of the caller which allocated the memory. - void *freed_by[CONFIG_HEAP_TRACING_STACK_DEPTH] Call stack of the caller which freed the memory (all zero if not freed.) - uint32_t ccount - struct heap_trace_summary_t Stores information about the result of a heap trace. Public Members - heap_trace_mode_t mode The heap trace mode we just completed / are running. - size_t total_allocations The total number of allocations made during tracing. - size_t total_frees The total number of frees made during tracing. - size_t count The number of records in the internal buffer. - size_t capacity The capacity of the internal buffer. - size_t high_water_mark The maximum value that 'count' got to. - size_t has_overflowed True if the internal buffer overflowed at some point. - heap_trace_mode_t mode Macros - CONFIG_HEAP_TRACING_STACK_DEPTH Type Definitions - typedef struct heap_trace_record_t heap_trace_record_t Trace record data type. Stores information about an allocated region of memory.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/heap_debug.html
ESP-IDF Programming Guide v5.2.1 documentation
null
High Resolution Timer (ESP Timer)
null
espressif.com
2016-01-01
bd05d5ea30168f89
null
null
High Resolution Timer (ESP Timer) Overview Although FreeRTOS provides software timers, FreeRTOS software timers have a few limitations: Maximum resolution is equal to the RTOS tick period Timer callbacks are dispatched from a low-priority timer service (i.e., daemon) task. This task can be preempted by other tasks, leading to decreased precision and accuracy. Although hardware timers are not subject to the limitations mentioned, they may not be as user-friendly. For instance, application components may require timer events to be triggered at specific future times, but hardware timers typically have only one "compare" value for interrupt generation. This necessitates the creation of an additional system on top of the hardware timer to keep track of pending events and ensure that callbacks are executed when the corresponding hardware interrupts occur. The hardware timer interrupt's priority is configured via the CONFIG_ESP_TIMER_INTERRUPT_LEVEL option (possible priorities being 1, 2, or 3). Raising the timer interrupt's priority can reduce the timer processing delay caused by interrupt latency. esp_timer set of APIs provides one-shot and periodic timers, microsecond time resolution, and 64-bit range. Internally, esp_timer uses a 64-bit hardware timer. The exact hardware timer implementation used depends on the target, where LAC timer is used for ESP32. Timer callbacks can be dispatched by two methods: ESP_TIMER_TASK . ESP_TIMER_ISR . Available only if CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD is enabled (by default disabled). ESP_TIMER_TASK . Timer callbacks are dispatched from a high-priority esp_timer task. Because all the callbacks are dispatched from the same task, it is recommended to only do the minimal possible amount of work from the callback itself, posting an event to a lower-priority task using a queue instead. If other tasks with a priority higher than esp_timer are running, callback dispatching will be delayed until the esp_timer task has a chance to run. For example, this will happen if an SPI Flash operation is in progress. ESP_TIMER_ISR . Timer callbacks are dispatched directly from the timer interrupt handler. This method is useful for some simple callbacks which aim for lower latency. Creating and starting a timer, and dispatching the callback takes some time. Therefore, there is a lower limit to the timeout value of one-shot esp_timer . If esp_timer_start_once() is called with a timeout value of less than 20 us, the callback will be dispatched only after approximately 20 us. Periodic esp_timer also imposes a 50 us restriction on the minimal timer period. Periodic software timers with a period of less than 50 us are not practical since they would consume most of the CPU time. Consider using dedicated hardware peripherals or DMA features if you find that a timer with a small period is required. Using esp_timer APIs esp_timer APIs A single timer is represented by esp_timer_handle_t type. Each timer has a callback function associated with it. This callback function is called from the esp_timer task each time the timer elapses. To create a timer, call esp_timer_create() . To delete the timer when it is no longer needed, call esp_timer_delete() . The timer can be started in one-shot mode or in periodic mode. To start the timer in one-shot mode, call esp_timer_start_once() , passing the time interval after which the callback should be called. When the callback gets called, the timer is considered to be stopped. To start the timer in periodic mode, call esp_timer_start_periodic() , passing the period with which the callback should be called. The timer keeps running until esp_timer_stop() is called. Note that the timer must not be running when esp_timer_start_once() or esp_timer_start_periodic() is called. To restart a running timer, call esp_timer_stop() first, then call one of the start functions. Callback Functions Note Keep the callback functions as short as possible. Otherwise, it will affect all timers. Timer callbacks that are processed by the ESP_TIMER_ISR method should not call the context switch call - portYIELD_FROM_ISR() . Instead, use the esp_timer_isr_dispatch_need_yield() function. The context switch will be done after all ISR dispatch timers have been processed if required by the system. esp_timer During Light-sleep esp_timer During Light-sleep During Light-sleep, the esp_timer counter stops and no callback functions are called. Instead, the time is counted by the RTC counter. Upon waking up, the system gets the difference between the counters and calls a function that advances the esp_timer counter. Since the counter has been advanced, the system starts calling callbacks that were not called during sleep. The number of callbacks depends on the duration of the sleep and the period of the timers. It can lead to the overflow of some queues. This only applies to periodic timers, since one-shot timers are only called once. This behavior can be changed by calling esp_timer_stop() before sleeping. In some cases, this can be inconvenient, and instead of the stop function, you can use the skip_unhandled_events option during esp_timer_create() . When the skip_unhandled_events is true, if a periodic timer expires one or more times during Light-sleep, then only one callback is called on wake. Using the skip_unhandled_events option with automatic Light-sleep (see Power Management APIs) helps to reduce the power consumption of the system when it is in Light-sleep. The duration of Light-sleep is also in part determined by the next event occurs. Timers with skip_unhandled_events option does not wake up the system. Handling Callbacks esp_timer is designed to achieve a high-resolution and low-latency timer with the ability to handle delayed events. If the timer is late, then the callback will be called as soon as possible, and it will not be lost. In the worst case, when the timer has not been processed for more than one period (for periodic timers), the callbacks will be called one after the other without waiting for the set period. This can be bad for some applications, and the skip_unhandled_events option is introduced to eliminate this behavior. If skip_unhandled_events is set, then a periodic timer that has expired multiple times without being able to call the callback will still result in only one callback event once processing is possible. Obtaining Current Time esp_timer also provides a convenience function to obtain the time passed since start-up, with microsecond precision: esp_timer_get_time() . This function returns the number of microseconds since esp_timer was initialized, which usually happens shortly before app_main function is called. Unlike gettimeofday function, values returned by esp_timer_get_time() : Start from zero after the chip wakes up from Deep-sleep Do not have timezone or DST adjustments applied Application Example The following example illustrates the usage of esp_timer APIs: system/esp_timer. API Reference Header File This header file can be included with: #include "esp_timer.h" This header file is a part of the API provided by the esp_timer component. To declare that your component depends on esp_timer , add the following to your CMakeLists.txt: REQUIRES esp_timer or PRIV_REQUIRES esp_timer Functions esp_err_t esp_timer_early_init(void) Minimal initialization of esp_timer. This function can be called very early in startup process, after this call only esp_timer_get_time function can be used. Note This function is called from startup code. Applications do not need to call this function before using other esp_timer APIs. Returns ESP_OK on success ESP_OK on success ESP_OK on success Returns ESP_OK on success esp_err_t esp_timer_init(void) Initialize esp_timer library. This function will be called from startup code on every core if CONFIG_ESP_TIMER_ISR_AFFINITY_NO_AFFINITY is enabled, It allocates the timer ISR on MULTIPLE cores and creates the timer task which can be run on any core. Note This function is called from startup code. Applications do not need to call this function before using other esp_timer APIs. Before calling this function, esp_timer_early_init must be called by the startup code. Returns ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_ERR_INVALID_STATE if already initialized other errors from interrupt allocator ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_ERR_INVALID_STATE if already initialized other errors from interrupt allocator ESP_OK on success Returns ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_ERR_INVALID_STATE if already initialized other errors from interrupt allocator esp_err_t esp_timer_deinit(void) De-initialize esp_timer library. Note Normally this function should not be called from applications Returns ESP_OK on success ESP_ERR_INVALID_STATE if not yet initialized ESP_OK on success ESP_ERR_INVALID_STATE if not yet initialized ESP_OK on success Returns ESP_OK on success ESP_ERR_INVALID_STATE if not yet initialized esp_err_t esp_timer_create(const esp_timer_create_args_t *create_args, esp_timer_handle_t *out_handle) Create an esp_timer instance. Note When done using the timer, delete it with esp_timer_delete function. Parameters create_args -- Pointer to a structure with timer creation arguments. Not saved by the library, can be allocated on the stack. out_handle -- [out] Output, pointer to esp_timer_handle_t variable which will hold the created timer handle. create_args -- Pointer to a structure with timer creation arguments. Not saved by the library, can be allocated on the stack. out_handle -- [out] Output, pointer to esp_timer_handle_t variable which will hold the created timer handle. create_args -- Pointer to a structure with timer creation arguments. Not saved by the library, can be allocated on the stack. Returns ESP_OK on success ESP_ERR_INVALID_ARG if some of the create_args are not valid ESP_ERR_INVALID_STATE if esp_timer library is not initialized yet ESP_ERR_NO_MEM if memory allocation fails ESP_OK on success ESP_ERR_INVALID_ARG if some of the create_args are not valid ESP_ERR_INVALID_STATE if esp_timer library is not initialized yet ESP_ERR_NO_MEM if memory allocation fails ESP_OK on success Parameters create_args -- Pointer to a structure with timer creation arguments. Not saved by the library, can be allocated on the stack. out_handle -- [out] Output, pointer to esp_timer_handle_t variable which will hold the created timer handle. Returns ESP_OK on success ESP_ERR_INVALID_ARG if some of the create_args are not valid ESP_ERR_INVALID_STATE if esp_timer library is not initialized yet ESP_ERR_NO_MEM if memory allocation fails esp_err_t esp_timer_start_once(esp_timer_handle_t timer, uint64_t timeout_us) Start one-shot timer. Timer should not be running when this function is called. Parameters timer -- timer handle created using esp_timer_create timeout_us -- timer timeout, in microseconds relative to the current moment timer -- timer handle created using esp_timer_create timeout_us -- timer timeout, in microseconds relative to the current moment timer -- timer handle created using esp_timer_create Returns ESP_OK on success ESP_ERR_INVALID_ARG if the handle is invalid ESP_ERR_INVALID_STATE if the timer is already running ESP_OK on success ESP_ERR_INVALID_ARG if the handle is invalid ESP_ERR_INVALID_STATE if the timer is already running ESP_OK on success Parameters timer -- timer handle created using esp_timer_create timeout_us -- timer timeout, in microseconds relative to the current moment Returns ESP_OK on success ESP_ERR_INVALID_ARG if the handle is invalid ESP_ERR_INVALID_STATE if the timer is already running esp_err_t esp_timer_start_periodic(esp_timer_handle_t timer, uint64_t period) Start a periodic timer. Timer should not be running when this function is called. This function will start the timer which will trigger every 'period' microseconds. Parameters timer -- timer handle created using esp_timer_create period -- timer period, in microseconds timer -- timer handle created using esp_timer_create period -- timer period, in microseconds timer -- timer handle created using esp_timer_create Returns ESP_OK on success ESP_ERR_INVALID_ARG if the handle is invalid ESP_ERR_INVALID_STATE if the timer is already running ESP_OK on success ESP_ERR_INVALID_ARG if the handle is invalid ESP_ERR_INVALID_STATE if the timer is already running ESP_OK on success Parameters timer -- timer handle created using esp_timer_create period -- timer period, in microseconds Returns ESP_OK on success ESP_ERR_INVALID_ARG if the handle is invalid ESP_ERR_INVALID_STATE if the timer is already running esp_err_t esp_timer_restart(esp_timer_handle_t timer, uint64_t timeout_us) Restart a currently running timer. If the given timer is a one-shot timer, the timer is restarted immediately and will timeout once in timeout_us microseconds. If the given timer is a periodic timer, the timer is restarted immediately with a new period of timeout_us microseconds. Parameters timer -- timer Handle created using esp_timer_create timeout_us -- Timeout, in microseconds relative to the current time. In case of a periodic timer, also represents the new period. timer -- timer Handle created using esp_timer_create timeout_us -- Timeout, in microseconds relative to the current time. In case of a periodic timer, also represents the new period. timer -- timer Handle created using esp_timer_create Returns ESP_OK on success ESP_ERR_INVALID_ARG if the handle is invalid ESP_ERR_INVALID_STATE if the timer is not running ESP_OK on success ESP_ERR_INVALID_ARG if the handle is invalid ESP_ERR_INVALID_STATE if the timer is not running ESP_OK on success Parameters timer -- timer Handle created using esp_timer_create timeout_us -- Timeout, in microseconds relative to the current time. In case of a periodic timer, also represents the new period. Returns ESP_OK on success ESP_ERR_INVALID_ARG if the handle is invalid ESP_ERR_INVALID_STATE if the timer is not running esp_err_t esp_timer_stop(esp_timer_handle_t timer) Stop the timer. This function stops the timer previously started using esp_timer_start_once or esp_timer_start_periodic. Parameters timer -- timer handle created using esp_timer_create Returns ESP_OK on success ESP_ERR_INVALID_STATE if the timer is not running ESP_OK on success ESP_ERR_INVALID_STATE if the timer is not running ESP_OK on success Parameters timer -- timer handle created using esp_timer_create Returns ESP_OK on success ESP_ERR_INVALID_STATE if the timer is not running esp_err_t esp_timer_delete(esp_timer_handle_t timer) Delete an esp_timer instance. The timer must be stopped before deleting. A one-shot timer which has expired does not need to be stopped. Parameters timer -- timer handle allocated using esp_timer_create Returns ESP_OK on success ESP_ERR_INVALID_STATE if the timer is running ESP_OK on success ESP_ERR_INVALID_STATE if the timer is running ESP_OK on success Parameters timer -- timer handle allocated using esp_timer_create Returns ESP_OK on success ESP_ERR_INVALID_STATE if the timer is running int64_t esp_timer_get_time(void) Get time in microseconds since boot. Returns number of microseconds since underlying timer has been started Returns number of microseconds since underlying timer has been started int64_t esp_timer_get_next_alarm(void) Get the timestamp when the next timeout is expected to occur. Returns Timestamp of the nearest timer event, in microseconds. The timebase is the same as for the values returned by esp_timer_get_time. Returns Timestamp of the nearest timer event, in microseconds. The timebase is the same as for the values returned by esp_timer_get_time. int64_t esp_timer_get_next_alarm_for_wake_up(void) Get the timestamp when the next timeout is expected to occur skipping those which have skip_unhandled_events flag. Returns Timestamp of the nearest timer event, in microseconds. The timebase is the same as for the values returned by esp_timer_get_time. Returns Timestamp of the nearest timer event, in microseconds. The timebase is the same as for the values returned by esp_timer_get_time. esp_err_t esp_timer_get_period(esp_timer_handle_t timer, uint64_t *period) Get the period of a timer. This function fetches the timeout period of a timer. Note The timeout period is the time interval with which a timer restarts after expiry. For one-shot timers, the period is 0 as there is no periodicity associated with such timers. Parameters timer -- timer handle allocated using esp_timer_create period -- memory to store the timer period value in microseconds timer -- timer handle allocated using esp_timer_create period -- memory to store the timer period value in microseconds timer -- timer handle allocated using esp_timer_create Returns ESP_OK on success ESP_ERR_INVALID_ARG if the arguments are invalid ESP_OK on success ESP_ERR_INVALID_ARG if the arguments are invalid ESP_OK on success Parameters timer -- timer handle allocated using esp_timer_create period -- memory to store the timer period value in microseconds Returns ESP_OK on success ESP_ERR_INVALID_ARG if the arguments are invalid esp_err_t esp_timer_get_expiry_time(esp_timer_handle_t timer, uint64_t *expiry) Get the expiry time of a one-shot timer. This function fetches the expiry time of a one-shot timer. Note This API returns a valid expiry time only for a one-shot timer. It returns an error if the timer handle passed to the function is for a periodic timer. Parameters timer -- timer handle allocated using esp_timer_create expiry -- memory to store the timeout value in microseconds timer -- timer handle allocated using esp_timer_create expiry -- memory to store the timeout value in microseconds timer -- timer handle allocated using esp_timer_create Returns ESP_OK on success ESP_ERR_INVALID_ARG if the arguments are invalid ESP_ERR_NOT_SUPPORTED if the timer type is periodic ESP_OK on success ESP_ERR_INVALID_ARG if the arguments are invalid ESP_ERR_NOT_SUPPORTED if the timer type is periodic ESP_OK on success Parameters timer -- timer handle allocated using esp_timer_create expiry -- memory to store the timeout value in microseconds Returns ESP_OK on success ESP_ERR_INVALID_ARG if the arguments are invalid ESP_ERR_NOT_SUPPORTED if the timer type is periodic esp_err_t esp_timer_dump(FILE *stream) Dump the list of timers to a stream. If CONFIG_ESP_TIMER_PROFILING option is enabled, this prints the list of all the existing timers. Otherwise, only the list active timers is printed. The format is: name period alarm times_armed times_triggered total_callback_run_time where: name — timer name (if CONFIG_ESP_TIMER_PROFILING is defined), or timer pointer period — period of timer, in microseconds, or 0 for one-shot timer alarm - time of the next alarm, in microseconds since boot, or 0 if the timer is not started The following fields are printed if CONFIG_ESP_TIMER_PROFILING is defined: times_armed — number of times the timer was armed via esp_timer_start_X times_triggered - number of times the callback was called total_callback_run_time - total time taken by callback to execute, across all calls Parameters stream -- stream (such as stdout) to dump the information to Returns ESP_OK on success ESP_ERR_NO_MEM if can not allocate temporary buffer for the output ESP_OK on success ESP_ERR_NO_MEM if can not allocate temporary buffer for the output ESP_OK on success Parameters stream -- stream (such as stdout) to dump the information to Returns ESP_OK on success ESP_ERR_NO_MEM if can not allocate temporary buffer for the output void esp_timer_isr_dispatch_need_yield(void) Requests a context switch from a timer callback function. This only works for a timer that has an ISR dispatch method. The context switch will be called after all ISR dispatch timers have been processed. bool esp_timer_is_active(esp_timer_handle_t timer) Returns status of a timer, active or not. This function is used to identify if the timer is still active or not. Parameters timer -- timer handle created using esp_timer_create Returns 1 if timer is still active 0 if timer is not active. 1 if timer is still active 0 if timer is not active. 1 if timer is still active Parameters timer -- timer handle created using esp_timer_create Returns 1 if timer is still active 0 if timer is not active. esp_err_t esp_timer_new_etm_alarm_event(esp_etm_event_handle_t *out_event) Get the ETM event handle of esp_timer underlying alarm event. Note The created ETM event object can be deleted later by calling esp_etm_del_event Note The ETM event is generated by the underlying hardware – systimer, therefore, if the esp_timer is not clocked by systimer, then no ETM event will be generated. Parameters out_event -- [out] Returned ETM event handle Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success ESP_ERR_INVALID_ARG Parameter error ESP_OK Success Parameters out_event -- [out] Returned ETM event handle Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error Structures struct esp_timer_create_args_t Timer configuration passed to esp_timer_create. Public Members esp_timer_cb_t callback Function to call when timer expires. esp_timer_cb_t callback Function to call when timer expires. void *arg Argument to pass to the callback. void *arg Argument to pass to the callback. esp_timer_dispatch_t dispatch_method Call the callback from task or from ISR. esp_timer_dispatch_t dispatch_method Call the callback from task or from ISR. const char *name Timer name, used in esp_timer_dump function. const char *name Timer name, used in esp_timer_dump function. bool skip_unhandled_events Skip unhandled events for periodic timers. bool skip_unhandled_events Skip unhandled events for periodic timers. esp_timer_cb_t callback Type Definitions typedef struct esp_timer *esp_timer_handle_t Opaque type representing a single esp_timer. typedef void (*esp_timer_cb_t)(void *arg) Timer callback function type. Param arg pointer to opaque user-specific data Param arg pointer to opaque user-specific data
High Resolution Timer (ESP Timer) Overview Although FreeRTOS provides software timers, FreeRTOS software timers have a few limitations: Maximum resolution is equal to the RTOS tick period Timer callbacks are dispatched from a low-priority timer service (i.e., daemon) task. This task can be preempted by other tasks, leading to decreased precision and accuracy. Although hardware timers are not subject to the limitations mentioned, they may not be as user-friendly. For instance, application components may require timer events to be triggered at specific future times, but hardware timers typically have only one "compare" value for interrupt generation. This necessitates the creation of an additional system on top of the hardware timer to keep track of pending events and ensure that callbacks are executed when the corresponding hardware interrupts occur. The hardware timer interrupt's priority is configured via the CONFIG_ESP_TIMER_INTERRUPT_LEVEL option (possible priorities being 1, 2, or 3). Raising the timer interrupt's priority can reduce the timer processing delay caused by interrupt latency. esp_timer set of APIs provides one-shot and periodic timers, microsecond time resolution, and 64-bit range. Internally, esp_timer uses a 64-bit hardware timer. The exact hardware timer implementation used depends on the target, where LAC timer is used for ESP32. Timer callbacks can be dispatched by two methods: ESP_TIMER_TASK. ESP_TIMER_ISR. Available only if CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD is enabled (by default disabled). ESP_TIMER_TASK. Timer callbacks are dispatched from a high-priority esp_timer task. Because all the callbacks are dispatched from the same task, it is recommended to only do the minimal possible amount of work from the callback itself, posting an event to a lower-priority task using a queue instead. If other tasks with a priority higher than esp_timer are running, callback dispatching will be delayed until the esp_timer task has a chance to run. For example, this will happen if an SPI Flash operation is in progress. ESP_TIMER_ISR. Timer callbacks are dispatched directly from the timer interrupt handler. This method is useful for some simple callbacks which aim for lower latency. Creating and starting a timer, and dispatching the callback takes some time. Therefore, there is a lower limit to the timeout value of one-shot esp_timer. If esp_timer_start_once() is called with a timeout value of less than 20 us, the callback will be dispatched only after approximately 20 us. Periodic esp_timer also imposes a 50 us restriction on the minimal timer period. Periodic software timers with a period of less than 50 us are not practical since they would consume most of the CPU time. Consider using dedicated hardware peripherals or DMA features if you find that a timer with a small period is required. Using esp_timer APIs A single timer is represented by esp_timer_handle_t type. Each timer has a callback function associated with it. This callback function is called from the esp_timer task each time the timer elapses. To create a timer, call esp_timer_create(). To delete the timer when it is no longer needed, call esp_timer_delete(). The timer can be started in one-shot mode or in periodic mode. To start the timer in one-shot mode, call esp_timer_start_once(), passing the time interval after which the callback should be called. When the callback gets called, the timer is considered to be stopped. To start the timer in periodic mode, call esp_timer_start_periodic(), passing the period with which the callback should be called. The timer keeps running until esp_timer_stop()is called. Note that the timer must not be running when esp_timer_start_once() or esp_timer_start_periodic() is called. To restart a running timer, call esp_timer_stop() first, then call one of the start functions. Callback Functions Note Keep the callback functions as short as possible. Otherwise, it will affect all timers. Timer callbacks that are processed by the ESP_TIMER_ISR method should not call the context switch call - portYIELD_FROM_ISR(). Instead, use the esp_timer_isr_dispatch_need_yield() function. The context switch will be done after all ISR dispatch timers have been processed if required by the system. esp_timer During Light-sleep During Light-sleep, the esp_timer counter stops and no callback functions are called. Instead, the time is counted by the RTC counter. Upon waking up, the system gets the difference between the counters and calls a function that advances the esp_timer counter. Since the counter has been advanced, the system starts calling callbacks that were not called during sleep. The number of callbacks depends on the duration of the sleep and the period of the timers. It can lead to the overflow of some queues. This only applies to periodic timers, since one-shot timers are only called once. This behavior can be changed by calling esp_timer_stop() before sleeping. In some cases, this can be inconvenient, and instead of the stop function, you can use the skip_unhandled_events option during esp_timer_create(). When the skip_unhandled_events is true, if a periodic timer expires one or more times during Light-sleep, then only one callback is called on wake. Using the skip_unhandled_events option with automatic Light-sleep (see Power Management APIs) helps to reduce the power consumption of the system when it is in Light-sleep. The duration of Light-sleep is also in part determined by the next event occurs. Timers with skip_unhandled_events option does not wake up the system. Handling Callbacks esp_timer is designed to achieve a high-resolution and low-latency timer with the ability to handle delayed events. If the timer is late, then the callback will be called as soon as possible, and it will not be lost. In the worst case, when the timer has not been processed for more than one period (for periodic timers), the callbacks will be called one after the other without waiting for the set period. This can be bad for some applications, and the skip_unhandled_events option is introduced to eliminate this behavior. If skip_unhandled_events is set, then a periodic timer that has expired multiple times without being able to call the callback will still result in only one callback event once processing is possible. Obtaining Current Time esp_timer also provides a convenience function to obtain the time passed since start-up, with microsecond precision: esp_timer_get_time(). This function returns the number of microseconds since esp_timer was initialized, which usually happens shortly before app_main function is called. Unlike gettimeofday function, values returned by esp_timer_get_time(): Start from zero after the chip wakes up from Deep-sleep Do not have timezone or DST adjustments applied Application Example The following example illustrates the usage of esp_timer APIs: system/esp_timer. API Reference Header File This header file can be included with: #include "esp_timer.h" This header file is a part of the API provided by the esp_timercomponent. To declare that your component depends on esp_timer, add the following to your CMakeLists.txt: REQUIRES esp_timer or PRIV_REQUIRES esp_timer Functions - esp_err_t esp_timer_early_init(void) Minimal initialization of esp_timer. This function can be called very early in startup process, after this call only esp_timer_get_time function can be used. Note This function is called from startup code. Applications do not need to call this function before using other esp_timer APIs. - Returns ESP_OK on success - - esp_err_t esp_timer_init(void) Initialize esp_timer library. This function will be called from startup code on every core if CONFIG_ESP_TIMER_ISR_AFFINITY_NO_AFFINITY is enabled, It allocates the timer ISR on MULTIPLE cores and creates the timer task which can be run on any core. Note This function is called from startup code. Applications do not need to call this function before using other esp_timer APIs. Before calling this function, esp_timer_early_init must be called by the startup code. - Returns ESP_OK on success ESP_ERR_NO_MEM if allocation has failed ESP_ERR_INVALID_STATE if already initialized other errors from interrupt allocator - - esp_err_t esp_timer_deinit(void) De-initialize esp_timer library. Note Normally this function should not be called from applications - Returns ESP_OK on success ESP_ERR_INVALID_STATE if not yet initialized - - esp_err_t esp_timer_create(const esp_timer_create_args_t *create_args, esp_timer_handle_t *out_handle) Create an esp_timer instance. Note When done using the timer, delete it with esp_timer_delete function. - Parameters create_args -- Pointer to a structure with timer creation arguments. Not saved by the library, can be allocated on the stack. out_handle -- [out] Output, pointer to esp_timer_handle_t variable which will hold the created timer handle. - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if some of the create_args are not valid ESP_ERR_INVALID_STATE if esp_timer library is not initialized yet ESP_ERR_NO_MEM if memory allocation fails - - esp_err_t esp_timer_start_once(esp_timer_handle_t timer, uint64_t timeout_us) Start one-shot timer. Timer should not be running when this function is called. - Parameters timer -- timer handle created using esp_timer_create timeout_us -- timer timeout, in microseconds relative to the current moment - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if the handle is invalid ESP_ERR_INVALID_STATE if the timer is already running - - esp_err_t esp_timer_start_periodic(esp_timer_handle_t timer, uint64_t period) Start a periodic timer. Timer should not be running when this function is called. This function will start the timer which will trigger every 'period' microseconds. - Parameters timer -- timer handle created using esp_timer_create period -- timer period, in microseconds - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if the handle is invalid ESP_ERR_INVALID_STATE if the timer is already running - - esp_err_t esp_timer_restart(esp_timer_handle_t timer, uint64_t timeout_us) Restart a currently running timer. If the given timer is a one-shot timer, the timer is restarted immediately and will timeout once in timeout_usmicroseconds. If the given timer is a periodic timer, the timer is restarted immediately with a new period of timeout_usmicroseconds. - Parameters timer -- timer Handle created using esp_timer_create timeout_us -- Timeout, in microseconds relative to the current time. In case of a periodic timer, also represents the new period. - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if the handle is invalid ESP_ERR_INVALID_STATE if the timer is not running - - esp_err_t esp_timer_stop(esp_timer_handle_t timer) Stop the timer. This function stops the timer previously started using esp_timer_start_once or esp_timer_start_periodic. - Parameters timer -- timer handle created using esp_timer_create - Returns ESP_OK on success ESP_ERR_INVALID_STATE if the timer is not running - - esp_err_t esp_timer_delete(esp_timer_handle_t timer) Delete an esp_timer instance. The timer must be stopped before deleting. A one-shot timer which has expired does not need to be stopped. - Parameters timer -- timer handle allocated using esp_timer_create - Returns ESP_OK on success ESP_ERR_INVALID_STATE if the timer is running - - int64_t esp_timer_get_time(void) Get time in microseconds since boot. - Returns number of microseconds since underlying timer has been started - int64_t esp_timer_get_next_alarm(void) Get the timestamp when the next timeout is expected to occur. - Returns Timestamp of the nearest timer event, in microseconds. The timebase is the same as for the values returned by esp_timer_get_time. - int64_t esp_timer_get_next_alarm_for_wake_up(void) Get the timestamp when the next timeout is expected to occur skipping those which have skip_unhandled_events flag. - Returns Timestamp of the nearest timer event, in microseconds. The timebase is the same as for the values returned by esp_timer_get_time. - esp_err_t esp_timer_get_period(esp_timer_handle_t timer, uint64_t *period) Get the period of a timer. This function fetches the timeout period of a timer. Note The timeout period is the time interval with which a timer restarts after expiry. For one-shot timers, the period is 0 as there is no periodicity associated with such timers. - Parameters timer -- timer handle allocated using esp_timer_create period -- memory to store the timer period value in microseconds - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if the arguments are invalid - - esp_err_t esp_timer_get_expiry_time(esp_timer_handle_t timer, uint64_t *expiry) Get the expiry time of a one-shot timer. This function fetches the expiry time of a one-shot timer. Note This API returns a valid expiry time only for a one-shot timer. It returns an error if the timer handle passed to the function is for a periodic timer. - Parameters timer -- timer handle allocated using esp_timer_create expiry -- memory to store the timeout value in microseconds - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if the arguments are invalid ESP_ERR_NOT_SUPPORTED if the timer type is periodic - - esp_err_t esp_timer_dump(FILE *stream) Dump the list of timers to a stream. If CONFIG_ESP_TIMER_PROFILING option is enabled, this prints the list of all the existing timers. Otherwise, only the list active timers is printed. The format is: name period alarm times_armed times_triggered total_callback_run_time where: name — timer name (if CONFIG_ESP_TIMER_PROFILING is defined), or timer pointer period — period of timer, in microseconds, or 0 for one-shot timer alarm - time of the next alarm, in microseconds since boot, or 0 if the timer is not started The following fields are printed if CONFIG_ESP_TIMER_PROFILING is defined: times_armed — number of times the timer was armed via esp_timer_start_X times_triggered - number of times the callback was called total_callback_run_time - total time taken by callback to execute, across all calls - Parameters stream -- stream (such as stdout) to dump the information to - Returns ESP_OK on success ESP_ERR_NO_MEM if can not allocate temporary buffer for the output - - void esp_timer_isr_dispatch_need_yield(void) Requests a context switch from a timer callback function. This only works for a timer that has an ISR dispatch method. The context switch will be called after all ISR dispatch timers have been processed. - bool esp_timer_is_active(esp_timer_handle_t timer) Returns status of a timer, active or not. This function is used to identify if the timer is still active or not. - Parameters timer -- timer handle created using esp_timer_create - Returns 1 if timer is still active 0 if timer is not active. - - esp_err_t esp_timer_new_etm_alarm_event(esp_etm_event_handle_t *out_event) Get the ETM event handle of esp_timer underlying alarm event. Note The created ETM event object can be deleted later by calling esp_etm_del_event Note The ETM event is generated by the underlying hardware – systimer, therefore, if the esp_timer is not clocked by systimer, then no ETM event will be generated. - Parameters out_event -- [out] Returned ETM event handle - Returns ESP_OK Success ESP_ERR_INVALID_ARG Parameter error - Structures - struct esp_timer_create_args_t Timer configuration passed to esp_timer_create. Public Members - esp_timer_cb_t callback Function to call when timer expires. - void *arg Argument to pass to the callback. - esp_timer_dispatch_t dispatch_method Call the callback from task or from ISR. - const char *name Timer name, used in esp_timer_dump function. - bool skip_unhandled_events Skip unhandled events for periodic timers. - esp_timer_cb_t callback Type Definitions - typedef struct esp_timer *esp_timer_handle_t Opaque type representing a single esp_timer. - typedef void (*esp_timer_cb_t)(void *arg) Timer callback function type. - Param arg pointer to opaque user-specific data
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/esp_timer.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Internal and Unstable APIs
null
espressif.com
2016-01-01
a205da143370b4bb
null
null
Internal and Unstable APIs This section is listing some APIs that are internal or likely to be changed or removed in the next releases of ESP-IDF. API Reference Header File This header file can be included with: #include "esp_rom_sys.h" Functions void esp_rom_software_reset_system(void) Software Reset digital core include RTC. It is not recommended to use this function in esp-idf, use esp_restart() instead. void esp_rom_software_reset_cpu(int cpu_no) Software Reset cpu core. It is not recommended to use this function in esp-idf, use esp_restart() instead. Parameters cpu_no -- : The CPU to reset, 0 for PRO CPU, 1 for APP CPU. Parameters cpu_no -- : The CPU to reset, 0 for PRO CPU, 1 for APP CPU. int esp_rom_printf(const char *fmt, ...) Print formated string to console device. Note float and long long data are not supported! Parameters fmt -- Format string ... -- Additional arguments, depending on the format string fmt -- Format string ... -- Additional arguments, depending on the format string fmt -- Format string Returns int: Total number of characters written on success; A negative number on failure. Parameters fmt -- Format string ... -- Additional arguments, depending on the format string Returns int: Total number of characters written on success; A negative number on failure. void esp_rom_delay_us(uint32_t us) Pauses execution for us microseconds. Parameters us -- Number of microseconds to pause Parameters us -- Number of microseconds to pause void esp_rom_install_channel_putc(int channel, void (*putc)(char c)) esp_rom_printf can print message to different channels simultaneously. This function can help install the low level putc function for esp_rom_printf. Parameters channel -- Channel number (startting from 1) putc -- Function pointer to the putc implementation. Set NULL can disconnect esp_rom_printf with putc. channel -- Channel number (startting from 1) putc -- Function pointer to the putc implementation. Set NULL can disconnect esp_rom_printf with putc. channel -- Channel number (startting from 1) Parameters channel -- Channel number (startting from 1) putc -- Function pointer to the putc implementation. Set NULL can disconnect esp_rom_printf with putc. void esp_rom_install_uart_printf(void) Install UART1 as the default console channel, equivalent to esp_rom_install_channel_putc(1, esp_rom_uart_putc) soc_reset_reason_t esp_rom_get_reset_reason(int cpu_no) Get reset reason of CPU. Parameters cpu_no -- CPU number Returns Reset reason code (see in soc/reset_reasons.h) Parameters cpu_no -- CPU number Returns Reset reason code (see in soc/reset_reasons.h) void esp_rom_route_intr_matrix(int cpu_core, uint32_t periph_intr_id, uint32_t cpu_intr_num) Route peripheral interrupt sources to CPU's interrupt port by matrix. Usually there're 4 steps to use an interrupt: Route peripheral interrupt source to CPU. e.g. esp_rom_route_intr_matrix(0, ETS_WIFI_MAC_INTR_SOURCE, ETS_WMAC_INUM) Set interrupt handler for CPU Enable CPU interrupt Enable peripheral interrupt Route peripheral interrupt source to CPU. e.g. esp_rom_route_intr_matrix(0, ETS_WIFI_MAC_INTR_SOURCE, ETS_WMAC_INUM) Set interrupt handler for CPU Enable CPU interrupt Enable peripheral interrupt Parameters cpu_core -- The CPU number, which the peripheral interrupt will inform to periph_intr_id -- The peripheral interrupt source number cpu_intr_num -- The CPU (external) interrupt number. On targets that use CLIC as their interrupt controller, this number represents the external interrupt number. For example, passing cpu_intr_num = i to this function would in fact bind peripheral source to CPU interrupt CLIC_EXT_INTR_NUM_OFFSET + i . cpu_core -- The CPU number, which the peripheral interrupt will inform to periph_intr_id -- The peripheral interrupt source number cpu_intr_num -- The CPU (external) interrupt number. On targets that use CLIC as their interrupt controller, this number represents the external interrupt number. For example, passing cpu_intr_num = i to this function would in fact bind peripheral source to CPU interrupt CLIC_EXT_INTR_NUM_OFFSET + i . cpu_core -- The CPU number, which the peripheral interrupt will inform to Parameters cpu_core -- The CPU number, which the peripheral interrupt will inform to periph_intr_id -- The peripheral interrupt source number cpu_intr_num -- The CPU (external) interrupt number. On targets that use CLIC as their interrupt controller, this number represents the external interrupt number. For example, passing cpu_intr_num = i to this function would in fact bind peripheral source to CPU interrupt CLIC_EXT_INTR_NUM_OFFSET + i . Route peripheral interrupt source to CPU. e.g. esp_rom_route_intr_matrix(0, ETS_WIFI_MAC_INTR_SOURCE, ETS_WMAC_INUM) uint32_t esp_rom_get_cpu_ticks_per_us(void) Get the real CPU ticks per us. Returns CPU ticks per us Returns CPU ticks per us void esp_rom_set_cpu_ticks_per_us(uint32_t ticks_per_us) Set the real CPU tick rate. Note Call this function when CPU frequency is changed, otherwise the esp_rom_delay_us can be inaccurate. Parameters ticks_per_us -- CPU ticks per us Parameters ticks_per_us -- CPU ticks per us
Internal and Unstable APIs This section is listing some APIs that are internal or likely to be changed or removed in the next releases of ESP-IDF. API Reference Header File This header file can be included with: #include "esp_rom_sys.h" Functions - void esp_rom_software_reset_system(void) Software Reset digital core include RTC. It is not recommended to use this function in esp-idf, use esp_restart() instead. - void esp_rom_software_reset_cpu(int cpu_no) Software Reset cpu core. It is not recommended to use this function in esp-idf, use esp_restart() instead. - Parameters cpu_no -- : The CPU to reset, 0 for PRO CPU, 1 for APP CPU. - int esp_rom_printf(const char *fmt, ...) Print formated string to console device. Note float and long long data are not supported! - Parameters fmt -- Format string ... -- Additional arguments, depending on the format string - - Returns int: Total number of characters written on success; A negative number on failure. - void esp_rom_delay_us(uint32_t us) Pauses execution for us microseconds. - Parameters us -- Number of microseconds to pause - void esp_rom_install_channel_putc(int channel, void (*putc)(char c)) esp_rom_printf can print message to different channels simultaneously. This function can help install the low level putc function for esp_rom_printf. - Parameters channel -- Channel number (startting from 1) putc -- Function pointer to the putc implementation. Set NULL can disconnect esp_rom_printf with putc. - - void esp_rom_install_uart_printf(void) Install UART1 as the default console channel, equivalent to esp_rom_install_channel_putc(1, esp_rom_uart_putc) - soc_reset_reason_t esp_rom_get_reset_reason(int cpu_no) Get reset reason of CPU. - Parameters cpu_no -- CPU number - Returns Reset reason code (see in soc/reset_reasons.h) - void esp_rom_route_intr_matrix(int cpu_core, uint32_t periph_intr_id, uint32_t cpu_intr_num) Route peripheral interrupt sources to CPU's interrupt port by matrix. Usually there're 4 steps to use an interrupt: Route peripheral interrupt source to CPU. e.g. esp_rom_route_intr_matrix(0, ETS_WIFI_MAC_INTR_SOURCE, ETS_WMAC_INUM) Set interrupt handler for CPU Enable CPU interrupt Enable peripheral interrupt - Parameters cpu_core -- The CPU number, which the peripheral interrupt will inform to periph_intr_id -- The peripheral interrupt source number cpu_intr_num -- The CPU (external) interrupt number. On targets that use CLIC as their interrupt controller, this number represents the external interrupt number. For example, passing cpu_intr_num = ito this function would in fact bind peripheral source to CPU interrupt CLIC_EXT_INTR_NUM_OFFSET + i. - - - uint32_t esp_rom_get_cpu_ticks_per_us(void) Get the real CPU ticks per us. - Returns CPU ticks per us - void esp_rom_set_cpu_ticks_per_us(uint32_t ticks_per_us) Set the real CPU tick rate. Note Call this function when CPU frequency is changed, otherwise the esp_rom_delay_uscan be inaccurate. - Parameters ticks_per_us -- CPU ticks per us
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/internal-unstable.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Inter-Processor Call (IPC)
null
espressif.com
2016-01-01
8a033a13e87db369
null
null
Inter-Processor Call (IPC) Note IPC stands for an "Inter-Processor Call" and NOT "Inter-Process Communication" as found on other operating systems. Overview Due to the dual core nature of the ESP32, there are some scenarios where a certain callback must be executed from a particular core such as: When allocating an ISR to an interrupt source of a particular core (applies to freeing a particular core's interrupt source as well) On particular chips (such as the ESP32), accessing memory that is exclusive to a particular core (such as RTC Fast Memory) Reading the registers/state of another core The IPC (Inter-Processor Call) feature allows a particular core (the calling core) to trigger the execution of a callback function on another core (the target core). The IPC feature allows execution of a callback function on the target core in either a task context, or an interrupt context. Depending on the context that the callback function is executed in, different restrictions apply to the implementation of the callback function. IPC in Task Context The IPC feature implements callback execution in a task context by creating an IPC task for each core during application startup. When the calling core needs to execute a callback on the target core, the callback will execute in the context of the target core's IPC task. When using IPCs in a task context, users need to consider the following: IPC callbacks should ideally be simple and short. An IPC callback must never block or yield. The IPC tasks are created at the highest possible priority (i.e., configMAX_PRIORITIES - 1 ). If CONFIG_ESP_IPC_USES_CALLERS_PRIORITY is enabled, the target core's IPC task will be lowered to the current priority of the target core before executing the callback. If CONFIG_ESP_IPC_USES_CALLERS_PRIORITY is disabled, the target core will always execute the callback at the highest possible priority. If CONFIG_ESP_IPC_USES_CALLERS_PRIORITY is enabled, the target core's IPC task will be lowered to the current priority of the target core before executing the callback. If CONFIG_ESP_IPC_USES_CALLERS_PRIORITY is disabled, the target core will always execute the callback at the highest possible priority. If CONFIG_ESP_IPC_USES_CALLERS_PRIORITY is enabled, the target core's IPC task will be lowered to the current priority of the target core before executing the callback. Depending on the complexity of the callback, users may need to configure the stack size of the IPC task via CONFIG_ESP_IPC_TASK_STACK_SIZE. The IPC feature is internally protected by a mutex. Therefore, simultaneous IPC calls from two or more calling core's are serialized on a first come first serve basis. API Usage Task Context IPC callbacks have the following restrictions: The callback must be of the esp_ipc_func_t type. The callback must never block or yield as this will result in the target core's IPC task blocking or yielding. The callback must avoid changing any aspect of the IPC task's state, e.g., by calling vTaskPrioritySet(NULL, x) . The IPC feature offers the API listed below to execute a callback in a task context on a target core. The API allows the calling core to block until the callback's execution has completed, or return immediately once the callback's execution has started. esp_ipc_call() triggers an IPC call on the target core. This function will block until the target core's IPC task begins execution of the callback. esp_ipc_call_blocking() triggers an IPC on the target core. This function will block until the target core's IPC task completes execution of the callback. IPC in Interrupt Context In some cases, we need to quickly obtain the state of another core such as in a core dump, GDB stub, various unit tests, and hardware errata workarounds. The IPC ISR feature implements callback execution from a High Priority Interrupt context by reserving a High Priority Interrupt on each core for IPC usage. When a calling core needs to execute a callback on the target core, the callback will execute in the context of the High Priority Interrupt of the target core. For such scenarios, the IPC ISR feature supports execution of callbacks in a High Priority Interrupt context. When using IPCs in High Priority Interrupt context, users need to consider the following: Since the callback is executed in a High Priority Interrupt context, the callback must be written entirely in assembly. See the API Usage below for more details regarding writing assembly callbacks. The priority of the reserved High Priority Interrupt is dependent on the CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL option. When the callback executes, users need to consider the following: The calling core will disable interrupts of priority level 3 and lower. Although the priority of the reserved interrupt depends on CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL, during the execution of IPC ISR callback, the target core will disable interrupts of priority level 5 and lower regardless of what CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL is set to. API Usage High Priority Interrupt IPC callbacks have the following restrictions: The callback must be of type esp_ipc_isr_func_t but implemented entirely in assembly. The callback is invoked via the CALLX0 instruction with register windowing disabled, thus the callback: must not call any register window related instructions, e.g., entry and retw . must not call other C functions as register windowing is disabled. must not call any register window related instructions, e.g., entry and retw . must not call other C functions as register windowing is disabled. must not call any register window related instructions, e.g., entry and retw . The callback is invoked via the CALLX0 instruction with register windowing disabled, thus the callback: must not call any register window related instructions, e.g., entry and retw . must not call other C functions as register windowing is disabled. The callback is invoked via the CALLX0 instruction with register windowing disabled, thus the callback: The callback should be placed in IRAM at a 4-byte aligned address. On invocation of, or after returning from the callback, the registers a2, a3, a4 are saved/restored automatically, thus can be used in the callback. The callback should ONLY use those registers. a2 contains the void *arg of the callback. a3/a4 are free to use as scratch registers. a2 contains the void *arg of the callback. a3/a4 are free to use as scratch registers. a2 contains the void *arg of the callback. On invocation of, or after returning from the callback, the registers a2, a3, a4 are saved/restored automatically, thus can be used in the callback. The callback should ONLY use those registers. a2 contains the void *arg of the callback. a3/a4 are free to use as scratch registers. On invocation of, or after returning from the callback, the registers a2, a3, a4 are saved/restored automatically, thus can be used in the callback. The callback should ONLY use those registers. The IPC feature offers the API listed below to execute a callback in a High Priority Interrupt context: esp_ipc_isr_call() triggers an IPC call on the target core. This function will busy-wait until the target core begins execution of the callback. esp_ipc_isr_call_blocking() triggers an IPC call on the target core. This function will busy-wait until the target core completes execution of the callback. The following code-blocks demonstrates a High Priority Interrupt IPC callback written in assembly that simply reads the target core's cycle count: /* esp_test_ipc_isr_get_cycle_count_other_cpu(void *arg) */ // this function reads CCOUNT of the target core and stores it in arg. // use only a2, a3 and a4 regs here. .section .iram1, "ax" .align 4 .global esp_test_ipc_isr_get_cycle_count_other_cpu .type esp_test_ipc_isr_get_cycle_count_other_cpu, @function // Args: // a2 - void* arg esp_test_ipc_isr_get_cycle_count_other_cpu: rsr.ccount a3 s32i a3, a2, 0 ret unit32_t cycle_count; esp_ipc_isr_call_blocking(esp_test_ipc_isr_get_cycle_count_other_cpu, (void *)cycle_count); Note The number of scratch registers available for use is sufficient for most simple use cases. But if your callback requires more scratch registers, void *arg can point to a buffer that is used as a register save area. The callback can then save and restore more registers. See the system/ipc/ipc_isr. Note For more examples of High Priority Interrupt IPC callbacks, you can refer to components/esp_system/port/arch/xtensa/esp_ipc_isr_routines.S and components/esp_system/test_apps/esp_system_unity_tests/main/port/arch/xtensa/test_ipc_isr.S. See examples/system/ipc/ipc_isr/xtensa/main/main.c for an example of its use. The High Priority Interrupt IPC API also provides the following convenience functions that can stall/resume the target core. These APIs utilize the High Priority Interrupt IPC, but supply their own internal callbacks: esp_ipc_isr_stall_other_cpu() stalls the target core. The calling core disables interrupts of level 3 and lower while the target core will busy-wait with interrupts of level 5 and lower disabled. The target core will busy-wait until esp_ipc_isr_release_other_cpu() is called. esp_ipc_isr_release_other_cpu() resumes the target core. API Reference Header File This header file can be included with: #include "esp_ipc.h" Functions esp_err_t esp_ipc_call(uint32_t cpu_id, esp_ipc_func_t func, void *arg) Execute a callback on a given CPU. Execute a given callback on a particular CPU. The callback must be of type "esp_ipc_func_t" and will be invoked in the context of the target CPU's IPC task. This function will block the target CPU's IPC task has begun execution of the callback If another IPC call is ongoing, this function will block until the ongoing IPC call completes The stack size of the IPC task can be configured via the CONFIG_ESP_IPC_TASK_STACK_SIZE option This function will block the target CPU's IPC task has begun execution of the callback If another IPC call is ongoing, this function will block until the ongoing IPC call completes The stack size of the IPC task can be configured via the CONFIG_ESP_IPC_TASK_STACK_SIZE option Note In single-core mode, returns ESP_ERR_INVALID_ARG for cpu_id 1. Parameters cpu_id -- [in] CPU where the given function should be executed (0 or 1) func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function cpu_id -- [in] CPU where the given function should be executed (0 or 1) func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function cpu_id -- [in] CPU where the given function should be executed (0 or 1) Returns ESP_ERR_INVALID_ARG if cpu_id is invalid ESP_ERR_INVALID_STATE if the FreeRTOS scheduler is not running ESP_OK otherwise ESP_ERR_INVALID_ARG if cpu_id is invalid ESP_ERR_INVALID_STATE if the FreeRTOS scheduler is not running ESP_OK otherwise ESP_ERR_INVALID_ARG if cpu_id is invalid Parameters cpu_id -- [in] CPU where the given function should be executed (0 or 1) func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function Returns ESP_ERR_INVALID_ARG if cpu_id is invalid ESP_ERR_INVALID_STATE if the FreeRTOS scheduler is not running ESP_OK otherwise This function will block the target CPU's IPC task has begun execution of the callback esp_err_t esp_ipc_call_blocking(uint32_t cpu_id, esp_ipc_func_t func, void *arg) Execute a callback on a given CPU until and block until it completes. This function is identical to esp_ipc_call() except that this function will block until the execution of the callback completes. Note In single-core mode, returns ESP_ERR_INVALID_ARG for cpu_id 1. Parameters cpu_id -- [in] CPU where the given function should be executed (0 or 1) func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function cpu_id -- [in] CPU where the given function should be executed (0 or 1) func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function cpu_id -- [in] CPU where the given function should be executed (0 or 1) Returns ESP_ERR_INVALID_ARG if cpu_id is invalid ESP_ERR_INVALID_STATE if the FreeRTOS scheduler is not running ESP_OK otherwise ESP_ERR_INVALID_ARG if cpu_id is invalid ESP_ERR_INVALID_STATE if the FreeRTOS scheduler is not running ESP_OK otherwise ESP_ERR_INVALID_ARG if cpu_id is invalid Parameters cpu_id -- [in] CPU where the given function should be executed (0 or 1) func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function Returns ESP_ERR_INVALID_ARG if cpu_id is invalid ESP_ERR_INVALID_STATE if the FreeRTOS scheduler is not running ESP_OK otherwise Type Definitions typedef void (*esp_ipc_func_t)(void *arg) IPC Callback. A callback of this type should be provided as an argument when calling esp_ipc_call() or esp_ipc_call_blocking(). Header File This header file can be included with: #include "esp_ipc_isr.h" Functions void esp_ipc_isr_call(esp_ipc_isr_func_t func, void *arg) Execute an ISR callback on the other CPU. Execute a given callback on the other CPU in the context of a High Priority Interrupt. This function will busy-wait in a critical section until the other CPU has started execution of the callback The callback must be written: in assembly for XTENSA chips (such as ESP32, ESP32S3). The function is invoked using a CALLX0 instruction and can use only a2, a3, a4 registers. See :doc: IPC in Interrupt Context </api-reference/system/ipc> doc for more details. in C or assembly for RISCV chips (such as ESP32P4). in assembly for XTENSA chips (such as ESP32, ESP32S3). The function is invoked using a CALLX0 instruction and can use only a2, a3, a4 registers. See :doc: IPC in Interrupt Context </api-reference/system/ipc> doc for more details. in C or assembly for RISCV chips (such as ESP32P4). in assembly for XTENSA chips (such as ESP32, ESP32S3). The function is invoked using a CALLX0 instruction and can use only a2, a3, a4 registers. See :doc: IPC in Interrupt Context </api-reference/system/ipc> doc for more details. This function will busy-wait in a critical section until the other CPU has started execution of the callback The callback must be written: in assembly for XTENSA chips (such as ESP32, ESP32S3). The function is invoked using a CALLX0 instruction and can use only a2, a3, a4 registers. See :doc: IPC in Interrupt Context </api-reference/system/ipc> doc for more details. in C or assembly for RISCV chips (such as ESP32P4). Note This function is not available in single-core mode. Parameters func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function func -- [in] Pointer to a function of type void func(void* arg) to be executed Parameters func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function This function will busy-wait in a critical section until the other CPU has started execution of the callback void esp_ipc_isr_call_blocking(esp_ipc_isr_func_t func, void *arg) Execute an ISR callback on the other CPU and busy-wait until it completes. This function is identical to esp_ipc_isr_call() except that this function will busy-wait until the execution of the callback completes. Note This function is not available in single-core mode. Parameters func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function func -- [in] Pointer to a function of type void func(void* arg) to be executed Parameters func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function void esp_ipc_isr_stall_other_cpu(void) Stall the other CPU. This function will stall the other CPU. The other CPU is stalled by busy-waiting in the context of a High Priority Interrupt. The other CPU will not be resumed until esp_ipc_isr_release_other_cpu() is called. This function is internally implemented using IPC ISR This function is used for DPORT workaround. If the stall feature is paused using esp_ipc_isr_stall_pause(), this function will have no effect This function is internally implemented using IPC ISR This function is used for DPORT workaround. If the stall feature is paused using esp_ipc_isr_stall_pause(), this function will have no effect Note This function is not available in single-core mode. Note It is the caller's responsibility to avoid deadlocking on spinlocks This function is internally implemented using IPC ISR void esp_ipc_isr_release_other_cpu(void) Release the other CPU. This function will release the other CPU that was previously stalled from calling esp_ipc_isr_stall_other_cpu() This function is used for DPORT workaround. If the stall feature is paused using esp_ipc_isr_stall_pause(), this function will have no effect This function is used for DPORT workaround. If the stall feature is paused using esp_ipc_isr_stall_pause(), this function will have no effect Note This function is not available in single-core mode. This function is used for DPORT workaround. void esp_ipc_isr_stall_pause(void) Puase the CPU stall feature. This function will pause the CPU stall feature. Once paused, calls to esp_ipc_isr_stall_other_cpu() and esp_ipc_isr_release_other_cpu() will have no effect. If a IPC ISR call is already in progress, this function will busy-wait until the call completes before pausing the CPU stall feature. void esp_ipc_isr_stall_abort(void) Abort a CPU stall. This function will abort any stalling routine of the other CPU due to a pervious call to esp_ipc_isr_stall_other_cpu(). This function aborts the stall in a non-recoverable manner, thus should only be called in case of a panic(). This function is used in panic handling code This function is used in panic handling code This function is used in panic handling code void esp_ipc_isr_stall_resume(void) Resume the CPU stall feature. This function will resume the CPU stall feature that was previously paused by calling esp_ipc_isr_stall_pause(). Once resumed, calls to esp_ipc_isr_stall_other_cpu() and esp_ipc_isr_release_other_cpu() will have effect again. Macros esp_ipc_isr_asm_call(func, arg) Execute an ISR callback on the other CPU See esp_ipc_isr_call(). esp_ipc_isr_asm_call_blocking(func, arg) Execute an ISR callback on the other CPU and busy-wait until it completes See esp_ipc_isr_call_blocking(). Type Definitions typedef void (*esp_ipc_isr_func_t)(void *arg) IPC ISR Callback. The callback must be written: in assembly for XTENSA chips (such as ESP32, ESP32S3). in C or assembly for RISCV chips (such as ESP32P4). in assembly for XTENSA chips (such as ESP32, ESP32S3). in C or assembly for RISCV chips (such as ESP32P4). A callback of this type should be provided as an argument when calling esp_ipc_isr_call() or esp_ipc_isr_call_blocking(). in assembly for XTENSA chips (such as ESP32, ESP32S3).
Inter-Processor Call (IPC) Note IPC stands for an "Inter-Processor Call" and NOT "Inter-Process Communication" as found on other operating systems. Overview Due to the dual core nature of the ESP32, there are some scenarios where a certain callback must be executed from a particular core such as: When allocating an ISR to an interrupt source of a particular core (applies to freeing a particular core's interrupt source as well) On particular chips (such as the ESP32), accessing memory that is exclusive to a particular core (such as RTC Fast Memory) Reading the registers/state of another core The IPC (Inter-Processor Call) feature allows a particular core (the calling core) to trigger the execution of a callback function on another core (the target core). The IPC feature allows execution of a callback function on the target core in either a task context, or an interrupt context. Depending on the context that the callback function is executed in, different restrictions apply to the implementation of the callback function. IPC in Task Context The IPC feature implements callback execution in a task context by creating an IPC task for each core during application startup. When the calling core needs to execute a callback on the target core, the callback will execute in the context of the target core's IPC task. When using IPCs in a task context, users need to consider the following: IPC callbacks should ideally be simple and short. An IPC callback must never block or yield. The IPC tasks are created at the highest possible priority (i.e., configMAX_PRIORITIES - 1). If CONFIG_ESP_IPC_USES_CALLERS_PRIORITY is enabled, the target core's IPC task will be lowered to the current priority of the target core before executing the callback. If CONFIG_ESP_IPC_USES_CALLERS_PRIORITY is disabled, the target core will always execute the callback at the highest possible priority. - Depending on the complexity of the callback, users may need to configure the stack size of the IPC task via CONFIG_ESP_IPC_TASK_STACK_SIZE. The IPC feature is internally protected by a mutex. Therefore, simultaneous IPC calls from two or more calling core's are serialized on a first come first serve basis. API Usage Task Context IPC callbacks have the following restrictions: The callback must be of the esp_ipc_func_ttype. The callback must never block or yield as this will result in the target core's IPC task blocking or yielding. The callback must avoid changing any aspect of the IPC task's state, e.g., by calling vTaskPrioritySet(NULL, x). The IPC feature offers the API listed below to execute a callback in a task context on a target core. The API allows the calling core to block until the callback's execution has completed, or return immediately once the callback's execution has started. esp_ipc_call()triggers an IPC call on the target core. This function will block until the target core's IPC task begins execution of the callback. esp_ipc_call_blocking()triggers an IPC on the target core. This function will block until the target core's IPC task completes execution of the callback. IPC in Interrupt Context In some cases, we need to quickly obtain the state of another core such as in a core dump, GDB stub, various unit tests, and hardware errata workarounds. The IPC ISR feature implements callback execution from a High Priority Interrupt context by reserving a High Priority Interrupt on each core for IPC usage. When a calling core needs to execute a callback on the target core, the callback will execute in the context of the High Priority Interrupt of the target core. For such scenarios, the IPC ISR feature supports execution of callbacks in a High Priority Interrupt context. When using IPCs in High Priority Interrupt context, users need to consider the following: Since the callback is executed in a High Priority Interrupt context, the callback must be written entirely in assembly. See the API Usage below for more details regarding writing assembly callbacks. The priority of the reserved High Priority Interrupt is dependent on the CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL option. When the callback executes, users need to consider the following: The calling core will disable interrupts of priority level 3 and lower. Although the priority of the reserved interrupt depends on CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL, during the execution of IPC ISR callback, the target core will disable interrupts of priority level 5 and lower regardless of what CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL is set to. API Usage High Priority Interrupt IPC callbacks have the following restrictions: The callback must be of type esp_ipc_isr_func_tbut implemented entirely in assembly. - The callback is invoked via the CALLX0instruction with register windowing disabled, thus the callback: must not call any register window related instructions, e.g., entryand retw. must not call other C functions as register windowing is disabled. - - The callback is invoked via the The callback should be placed in IRAM at a 4-byte aligned address. - On invocation of, or after returning from the callback, the registers a2, a3, a4are saved/restored automatically, thus can be used in the callback. The callback should ONLY use those registers. a2contains the void *argof the callback. a3/a4are free to use as scratch registers. - - On invocation of, or after returning from the callback, the registers The IPC feature offers the API listed below to execute a callback in a High Priority Interrupt context: esp_ipc_isr_call()triggers an IPC call on the target core. This function will busy-wait until the target core begins execution of the callback. esp_ipc_isr_call_blocking()triggers an IPC call on the target core. This function will busy-wait until the target core completes execution of the callback. The following code-blocks demonstrates a High Priority Interrupt IPC callback written in assembly that simply reads the target core's cycle count: /* esp_test_ipc_isr_get_cycle_count_other_cpu(void *arg) */ // this function reads CCOUNT of the target core and stores it in arg. // use only a2, a3 and a4 regs here. .section .iram1, "ax" .align 4 .global esp_test_ipc_isr_get_cycle_count_other_cpu .type esp_test_ipc_isr_get_cycle_count_other_cpu, @function // Args: // a2 - void* arg esp_test_ipc_isr_get_cycle_count_other_cpu: rsr.ccount a3 s32i a3, a2, 0 ret unit32_t cycle_count; esp_ipc_isr_call_blocking(esp_test_ipc_isr_get_cycle_count_other_cpu, (void *)cycle_count); Note The number of scratch registers available for use is sufficient for most simple use cases. But if your callback requires more scratch registers, void *arg can point to a buffer that is used as a register save area. The callback can then save and restore more registers. See the system/ipc/ipc_isr. Note For more examples of High Priority Interrupt IPC callbacks, you can refer to components/esp_system/port/arch/xtensa/esp_ipc_isr_routines.S and components/esp_system/test_apps/esp_system_unity_tests/main/port/arch/xtensa/test_ipc_isr.S. See examples/system/ipc/ipc_isr/xtensa/main/main.c for an example of its use. The High Priority Interrupt IPC API also provides the following convenience functions that can stall/resume the target core. These APIs utilize the High Priority Interrupt IPC, but supply their own internal callbacks: esp_ipc_isr_stall_other_cpu()stalls the target core. The calling core disables interrupts of level 3 and lower while the target core will busy-wait with interrupts of level 5 and lower disabled. The target core will busy-wait until esp_ipc_isr_release_other_cpu()is called. esp_ipc_isr_release_other_cpu()resumes the target core. API Reference Header File This header file can be included with: #include "esp_ipc.h" Functions - esp_err_t esp_ipc_call(uint32_t cpu_id, esp_ipc_func_t func, void *arg) Execute a callback on a given CPU. Execute a given callback on a particular CPU. The callback must be of type "esp_ipc_func_t" and will be invoked in the context of the target CPU's IPC task. This function will block the target CPU's IPC task has begun execution of the callback If another IPC call is ongoing, this function will block until the ongoing IPC call completes The stack size of the IPC task can be configured via the CONFIG_ESP_IPC_TASK_STACK_SIZE option Note In single-core mode, returns ESP_ERR_INVALID_ARG for cpu_id 1. - Parameters cpu_id -- [in] CPU where the given function should be executed (0 or 1) func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function - - Returns ESP_ERR_INVALID_ARG if cpu_id is invalid ESP_ERR_INVALID_STATE if the FreeRTOS scheduler is not running ESP_OK otherwise - - - esp_err_t esp_ipc_call_blocking(uint32_t cpu_id, esp_ipc_func_t func, void *arg) Execute a callback on a given CPU until and block until it completes. This function is identical to esp_ipc_call() except that this function will block until the execution of the callback completes. Note In single-core mode, returns ESP_ERR_INVALID_ARG for cpu_id 1. - Parameters cpu_id -- [in] CPU where the given function should be executed (0 or 1) func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function - - Returns ESP_ERR_INVALID_ARG if cpu_id is invalid ESP_ERR_INVALID_STATE if the FreeRTOS scheduler is not running ESP_OK otherwise - Type Definitions - typedef void (*esp_ipc_func_t)(void *arg) IPC Callback. A callback of this type should be provided as an argument when calling esp_ipc_call() or esp_ipc_call_blocking(). Header File This header file can be included with: #include "esp_ipc_isr.h" Functions - void esp_ipc_isr_call(esp_ipc_isr_func_t func, void *arg) Execute an ISR callback on the other CPU. Execute a given callback on the other CPU in the context of a High Priority Interrupt. This function will busy-wait in a critical section until the other CPU has started execution of the callback The callback must be written: in assembly for XTENSA chips (such as ESP32, ESP32S3). The function is invoked using a CALLX0 instruction and can use only a2, a3, a4 registers. See :doc: IPC in Interrupt Context </api-reference/system/ipc>doc for more details. in C or assembly for RISCV chips (such as ESP32P4). - Note This function is not available in single-core mode. - Parameters func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function - - - void esp_ipc_isr_call_blocking(esp_ipc_isr_func_t func, void *arg) Execute an ISR callback on the other CPU and busy-wait until it completes. This function is identical to esp_ipc_isr_call() except that this function will busy-wait until the execution of the callback completes. Note This function is not available in single-core mode. - Parameters func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function - - void esp_ipc_isr_stall_other_cpu(void) Stall the other CPU. This function will stall the other CPU. The other CPU is stalled by busy-waiting in the context of a High Priority Interrupt. The other CPU will not be resumed until esp_ipc_isr_release_other_cpu() is called. This function is internally implemented using IPC ISR This function is used for DPORT workaround. If the stall feature is paused using esp_ipc_isr_stall_pause(), this function will have no effect Note This function is not available in single-core mode. Note It is the caller's responsibility to avoid deadlocking on spinlocks - - void esp_ipc_isr_release_other_cpu(void) Release the other CPU. This function will release the other CPU that was previously stalled from calling esp_ipc_isr_stall_other_cpu() This function is used for DPORT workaround. If the stall feature is paused using esp_ipc_isr_stall_pause(), this function will have no effect Note This function is not available in single-core mode. - - void esp_ipc_isr_stall_pause(void) Puase the CPU stall feature. This function will pause the CPU stall feature. Once paused, calls to esp_ipc_isr_stall_other_cpu() and esp_ipc_isr_release_other_cpu() will have no effect. If a IPC ISR call is already in progress, this function will busy-wait until the call completes before pausing the CPU stall feature. - void esp_ipc_isr_stall_abort(void) Abort a CPU stall. This function will abort any stalling routine of the other CPU due to a pervious call to esp_ipc_isr_stall_other_cpu(). This function aborts the stall in a non-recoverable manner, thus should only be called in case of a panic(). This function is used in panic handling code - - void esp_ipc_isr_stall_resume(void) Resume the CPU stall feature. This function will resume the CPU stall feature that was previously paused by calling esp_ipc_isr_stall_pause(). Once resumed, calls to esp_ipc_isr_stall_other_cpu() and esp_ipc_isr_release_other_cpu() will have effect again. Macros - esp_ipc_isr_asm_call(func, arg) Execute an ISR callback on the other CPU See esp_ipc_isr_call(). - esp_ipc_isr_asm_call_blocking(func, arg) Execute an ISR callback on the other CPU and busy-wait until it completes See esp_ipc_isr_call_blocking(). Type Definitions - typedef void (*esp_ipc_isr_func_t)(void *arg) IPC ISR Callback. The callback must be written: in assembly for XTENSA chips (such as ESP32, ESP32S3). in C or assembly for RISCV chips (such as ESP32P4). A callback of this type should be provided as an argument when calling esp_ipc_isr_call() or esp_ipc_isr_call_blocking(). -
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/ipc.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Interrupt Allocation
null
espressif.com
2016-01-01
22aeb31cb7609693
null
null
Interrupt Allocation Overview The ESP32 has two cores, with 32 interrupts each. Each interrupt has a fixed priority, most (but not all) interrupts are connected to the interrupt matrix. Because there are more interrupt sources than interrupts, sometimes it makes sense to share an interrupt in multiple drivers. The esp_intr_alloc() abstraction exists to hide all these implementation details. A driver can allocate an interrupt for a certain peripheral by calling esp_intr_alloc() (or esp_intr_alloc_intrstatus() ). It can use the flags passed to this function to specify the type, priority, and trigger method of the interrupt to allocate. The interrupt allocation code will then find an applicable interrupt, use the interrupt matrix to hook it up to the peripheral, and install the given interrupt handler and ISR to it. The interrupt allocator presents two different types of interrupts, namely shared interrupts and non-shared interrupts, both of which require different handling. Non-shared interrupts will allocate a separate interrupt for every esp_intr_alloc() call, and this interrupt is use solely for the peripheral attached to it, with only one ISR that will get called. Shared interrupts can have multiple peripherals triggering them, with multiple ISRs being called when one of the peripherals attached signals an interrupt. Thus, ISRs that are intended for shared interrupts should check the interrupt status of the peripheral they service in order to check if any action is required. Non-shared interrupts can be either level- or edge-triggered. Shared interrupts can only be level interrupts due to the chance of missed interrupts when edge interrupts are used. To illustrate why shard interrupts can only be level-triggered, take the scenario where peripheral A and peripheral B share the same edge-triggered interrupt. Peripheral B triggers an interrupt and sets its interrupt signal high, causing a low-to-high edge, which in turn latches the CPU's interrupt bit and triggers the ISR. The ISR executes, checks that peripheral A did not trigger an interrupt, and proceeds to handle and clear peripheral B's interrupt signal. Before the ISR returns, the CPU clears its interrupt bit latch. Thus, during the entire interrupt handling process, if peripheral A triggers an interrupt, it will be missed due the CPU clearing the interrupt bit latch. Multicore Issues Peripherals that can generate interrupts can be divided in two types: External peripherals, within the ESP32 but outside the Xtensa cores themselves. Most ESP32 peripherals are of this type. Internal peripherals, part of the Xtensa CPU cores themselves. Interrupt handling differs slightly between these two types of peripherals. Internal Peripheral Interrupts Each Xtensa CPU core has its own set of six internal peripherals: Three timer comparators A performance monitor Two software interrupts Internal interrupt sources are defined in esp_intr_alloc.h as ETS_INTERNAL_*_INTR_SOURCE . These peripherals can only be configured from the core they are associated with. When generating an interrupt, the interrupt they generate is hard-wired to their associated core; it is not possible to have, for example, an internal timer comparator of one core generate an interrupt on another core. That is why these sources can only be managed using a task running on that specific core. Internal interrupt sources are still allocatable using esp_intr_alloc() as normal, but they cannot be shared and will always have a fixed interrupt level (namely, the one associated in hardware with the peripheral). External Peripheral Interrupts The remaining interrupt sources are from external peripherals. These are defined in soc/soc.h as ETS_*_INTR_SOURCE . Non-internal interrupt slots in both CPU cores are wired to an interrupt matrix, which can be used to route any external interrupt source to any of these interrupt slots. Allocating an external interrupt will always allocate it on the core that does the allocation. Freeing an external interrupt must always happen on the same core it was allocated on. Disabling and enabling external interrupts from another core is allowed. Multiple external interrupt sources can share an interrupt slot by passing ESP_INTR_FLAG_SHARED as a flag to esp_intr_alloc() . Care should be taken when calling esp_intr_alloc() from a task which is not pinned to a core. During task switching, these tasks can migrate between cores. Therefore it is impossible to tell which CPU the interrupt is allocated on, which makes it difficult to free the interrupt handle and may also cause debugging difficulties. It is advised to use xTaskCreatePinnedToCore() with a specific CoreID argument to create tasks that allocate interrupts. In the case of internal interrupt sources, this is required. IRAM-Safe Interrupt Handlers The ESP_INTR_FLAG_IRAM flag registers an interrupt handler that always runs from IRAM (and reads all its data from DRAM), and therefore does not need to be disabled during flash erase and write operations. This is useful for interrupts which need a guaranteed minimum execution latency, as flash write and erase operations can be slow (erases can take tens or hundreds of milliseconds to complete). It can also be useful to keep an interrupt handler in IRAM if it is called very frequently, to avoid flash cache misses. Refer to the SPI flash API documentation for more details. Multiple Handlers Sharing A Source Several handlers can be assigned to a same source, given that all handlers are allocated using the ESP_INTR_FLAG_SHARED flag. They will all be allocated to the interrupt, which the source is attached to, and called sequentially when the source is active. The handlers can be disabled and freed individually. The source is attached to the interrupt (enabled), if one or more handlers are enabled, otherwise detached. A handler will never be called when disabled, while its source may still be triggered if any one of its handler enabled. Sources attached to non-shared interrupt do not support this feature. By default, when ESP_INTR_FLAG_SHARED flag is specified, the interrupt allocator will allocate only priority level 1 interrupts. Use ESP_INTR_FLAG_SHARED | ESP_INTR_FLAG_LOWMED to also allow allocating shared interrupts at priority levels 2 and 3. Though the framework supports this feature, you have to use it very carefully. There usually exist two ways to stop an interrupt from being triggered: disable the source or mask peripheral interrupt status. ESP-IDF only handles enabling and disabling of the source itself, leaving status and mask bits to be handled by users. Status bits shall either be masked before the handler responsible for it is disabled, or be masked and then properly handled in another enabled interrupt. Note Leaving some status bits unhandled without masking them, while disabling the handlers for them, will cause the interrupt(s) to be triggered indefinitely, resulting therefore in a system crash. Troubleshooting Interrupt Allocation On most Espressif SoCs, CPU interrupts are a limited resource. Therefore it is possible for a program to run out of CPU interrupts, for example by initializing several peripheral drivers. Typically, this will result in the driver initialization function returning ESP_ERR_NOT_FOUND error code. If this happens, you can use esp_intr_dump() function to print the list of interrupts along with their status. The output of this function typically looks like this: CPU 0 interrupt status: Int Level Type Status 0 1 Level Reserved 1 1 Level Reserved 2 1 Level Used: RTC_CORE 3 1 Level Used: TG0_LACT_LEVEL ... The columns of the output have the following meaning: Int : CPU interrupt input number. This is typically not used in software directly, and is provided for reference only. Level : Interrupt priority (1-7) of the CPU interrupt. This priority is fixed in hardware, and cannot be changed. Type : Interrupt type (Level or Edge) of the CPU interrupt. This type is fixed in hardware, and cannot be changed. Status : One of the possible statuses of the interrupt: Reserved : The interrupt is reserved either at hardware level, or by one of the parts of ESP-IDF. It can not be allocated using esp_intr_alloc() . Used: <source> : The interrupt is allocated and connected to a single peripheral. Shared: <source1> <source2> ... : The interrupt is allocated and connected to multiple peripherals. See Multiple Handlers Sharing A Source above. Free : The interrupt is not allocated and can be used by esp_intr_alloc() . Reserved : The interrupt is reserved either at hardware level, or by one of the parts of ESP-IDF. It can not be allocated using esp_intr_alloc() . Used: <source> : The interrupt is allocated and connected to a single peripheral. Shared: <source1> <source2> ... : The interrupt is allocated and connected to multiple peripherals. See Multiple Handlers Sharing A Source above. Free : The interrupt is not allocated and can be used by esp_intr_alloc() . Reserved : The interrupt is reserved either at hardware level, or by one of the parts of ESP-IDF. It can not be allocated using esp_intr_alloc() . Status : One of the possible statuses of the interrupt: Reserved : The interrupt is reserved either at hardware level, or by one of the parts of ESP-IDF. It can not be allocated using esp_intr_alloc() . Used: <source> : The interrupt is allocated and connected to a single peripheral. Shared: <source1> <source2> ... : The interrupt is allocated and connected to multiple peripherals. See Multiple Handlers Sharing A Source above. Free : The interrupt is not allocated and can be used by esp_intr_alloc() . Status : One of the possible statuses of the interrupt: Free (not general-use) : The interrupt is not allocated, but is either a high-priority interrupt (priority 4-7) or an edge-triggered interrupt. High-priority interrupts can be allocated using esp_intr_alloc() but requires the handlers to be written in Assembly, see High Priority Interrupts. Edge-triggered low- and medium-priority interrupts can also be allocated using esp_intr_alloc() , but are not used often since most peripheral interrupts are level-triggered. If you have confirmed that the application is indeed running out of interrupts, a combination of the following suggestions can help resolve the issue: On multi-core SoCs, try initializing some of the peripheral drivers from a task pinned to the second core. Interrupts are typically allocated on the same core where the peripheral driver initialization function runs. Therefore by running the initialization function on the second core, more interrupt inputs can be used. Determine the interrupts which can tolerate higher latency, and allocate them using ESP_INTR_FLAG_SHARED flag (optionally ORed with ESP_INTR_FLAG_LOWMED ). Using this flag for two or more peripherals will let them use a single interrupt input, and therefore save interrupt inputs for other peripherals. See Multiple Handlers Sharing A Source above. Some peripheral driver may default to allocating interrupts with ESP_INTR_FLAG_LEVEL1 flag, so priority 2 and 3 interrupts do not get used by default. If esp_intr_dump() shows that some priority 2 or 3 interrupts are available, try changing the interrupt allocation flags when initializing the driver to ESP_INTR_FLAG_LEVEL2 or ESP_INTR_FLAG_LEVEL3 . Check if some of the peripheral drivers do not need to be used all the time, and initialize or deinitialize them on demand. This can reduce the number of simultaneously allocated interrupts. API Reference Header File This header file can be included with: #include "esp_intr_types.h" Macros ESP_INTR_CPU_AFFINITY_TO_CORE_ID(cpu_affinity) Convert esp_intr_cpu_affinity_t to CPU core ID. Type Definitions typedef void (*intr_handler_t)(void *arg) Function prototype for interrupt handler function typedef struct intr_handle_data_t *intr_handle_t Handle to an interrupt handler Enumerations enum esp_intr_cpu_affinity_t Interrupt CPU core affinity. This type specify the CPU core that the peripheral interrupt is connected to. Values: enumerator ESP_INTR_CPU_AFFINITY_AUTO Install the peripheral interrupt to ANY CPU core, decided by on which CPU the interrupt allocator is running. enumerator ESP_INTR_CPU_AFFINITY_AUTO Install the peripheral interrupt to ANY CPU core, decided by on which CPU the interrupt allocator is running. enumerator ESP_INTR_CPU_AFFINITY_0 Install the peripheral interrupt to CPU core 0. enumerator ESP_INTR_CPU_AFFINITY_0 Install the peripheral interrupt to CPU core 0. enumerator ESP_INTR_CPU_AFFINITY_1 Install the peripheral interrupt to CPU core 1. enumerator ESP_INTR_CPU_AFFINITY_1 Install the peripheral interrupt to CPU core 1. enumerator ESP_INTR_CPU_AFFINITY_AUTO Header File This header file can be included with: #include "esp_intr_alloc.h" Functions Mark an interrupt as a shared interrupt. This will mark a certain interrupt on the specified CPU as an interrupt that can be used to hook shared interrupt handlers to. Parameters intno -- The number of the interrupt (0-31) cpu -- CPU on which the interrupt should be marked as shared (0 or 1) is_in_iram -- Shared interrupt is for handlers that reside in IRAM and the int can be left enabled while the flash cache is disabled. intno -- The number of the interrupt (0-31) cpu -- CPU on which the interrupt should be marked as shared (0 or 1) is_in_iram -- Shared interrupt is for handlers that reside in IRAM and the int can be left enabled while the flash cache is disabled. intno -- The number of the interrupt (0-31) Returns ESP_ERR_INVALID_ARG if cpu or intno is invalid ESP_OK otherwise Parameters intno -- The number of the interrupt (0-31) cpu -- CPU on which the interrupt should be marked as shared (0 or 1) is_in_iram -- Shared interrupt is for handlers that reside in IRAM and the int can be left enabled while the flash cache is disabled. Returns ESP_ERR_INVALID_ARG if cpu or intno is invalid ESP_OK otherwise esp_err_t esp_intr_reserve(int intno, int cpu) Reserve an interrupt to be used outside of this framework. This will mark a certain interrupt on the specified CPU as reserved, not to be allocated for any reason. Parameters intno -- The number of the interrupt (0-31) cpu -- CPU on which the interrupt should be marked as shared (0 or 1) intno -- The number of the interrupt (0-31) cpu -- CPU on which the interrupt should be marked as shared (0 or 1) intno -- The number of the interrupt (0-31) Returns ESP_ERR_INVALID_ARG if cpu or intno is invalid ESP_OK otherwise Parameters intno -- The number of the interrupt (0-31) cpu -- CPU on which the interrupt should be marked as shared (0 or 1) Returns ESP_ERR_INVALID_ARG if cpu or intno is invalid ESP_OK otherwise esp_err_t esp_intr_alloc(int source, int flags, intr_handler_t handler, void *arg, intr_handle_t *ret_handle) Allocate an interrupt with the given parameters. This finds an interrupt that matches the restrictions as given in the flags parameter, maps the given interrupt source to it and hooks up the given interrupt handler (with optional argument) as well. If needed, it can return a handle for the interrupt as well. The interrupt will always be allocated on the core that runs this function. If ESP_INTR_FLAG_IRAM flag is used, and handler address is not in IRAM or RTC_FAST_MEM, then ESP_ERR_INVALID_ARG is returned. Parameters source -- The interrupt source. One of the ETS_*_INTR_SOURCE interrupt mux sources, as defined in soc/soc.h, or one of the internal ETS_INTERNAL_*_INTR_SOURCE sources as defined in this header. flags -- An ORred mask of the ESP_INTR_FLAG_* defines. These restrict the choice of interrupts that this routine can choose from. If this value is 0, it will default to allocating a non-shared interrupt of level 1, 2 or 3. If this is ESP_INTR_FLAG_SHARED, it will allocate a shared interrupt of level 1. Setting ESP_INTR_FLAG_INTRDISABLED will return from this function with the interrupt disabled. handler -- The interrupt handler. Must be NULL when an interrupt of level >3 is requested, because these types of interrupts aren't C-callable. arg -- Optional argument for passed to the interrupt handler ret_handle -- Pointer to an intr_handle_t to store a handle that can later be used to request details or free the interrupt. Can be NULL if no handle is required. source -- The interrupt source. One of the ETS_*_INTR_SOURCE interrupt mux sources, as defined in soc/soc.h, or one of the internal ETS_INTERNAL_*_INTR_SOURCE sources as defined in this header. flags -- An ORred mask of the ESP_INTR_FLAG_* defines. These restrict the choice of interrupts that this routine can choose from. If this value is 0, it will default to allocating a non-shared interrupt of level 1, 2 or 3. If this is ESP_INTR_FLAG_SHARED, it will allocate a shared interrupt of level 1. Setting ESP_INTR_FLAG_INTRDISABLED will return from this function with the interrupt disabled. handler -- The interrupt handler. Must be NULL when an interrupt of level >3 is requested, because these types of interrupts aren't C-callable. arg -- Optional argument for passed to the interrupt handler ret_handle -- Pointer to an intr_handle_t to store a handle that can later be used to request details or free the interrupt. Can be NULL if no handle is required. source -- The interrupt source. One of the ETS_*_INTR_SOURCE interrupt mux sources, as defined in soc/soc.h, or one of the internal ETS_INTERNAL_*_INTR_SOURCE sources as defined in this header. Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_OK otherwise Parameters source -- The interrupt source. One of the ETS_*_INTR_SOURCE interrupt mux sources, as defined in soc/soc.h, or one of the internal ETS_INTERNAL_*_INTR_SOURCE sources as defined in this header. flags -- An ORred mask of the ESP_INTR_FLAG_* defines. These restrict the choice of interrupts that this routine can choose from. If this value is 0, it will default to allocating a non-shared interrupt of level 1, 2 or 3. If this is ESP_INTR_FLAG_SHARED, it will allocate a shared interrupt of level 1. Setting ESP_INTR_FLAG_INTRDISABLED will return from this function with the interrupt disabled. handler -- The interrupt handler. Must be NULL when an interrupt of level >3 is requested, because these types of interrupts aren't C-callable. arg -- Optional argument for passed to the interrupt handler ret_handle -- Pointer to an intr_handle_t to store a handle that can later be used to request details or free the interrupt. Can be NULL if no handle is required. Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_OK otherwise esp_err_t esp_intr_alloc_intrstatus(int source, int flags, uint32_t intrstatusreg, uint32_t intrstatusmask, intr_handler_t handler, void *arg, intr_handle_t *ret_handle) Allocate an interrupt with the given parameters. This essentially does the same as esp_intr_alloc, but allows specifying a register and mask combo. For shared interrupts, the handler is only called if a read from the specified register, ANDed with the mask, returns non-zero. By passing an interrupt status register address and a fitting mask, this can be used to accelerate interrupt handling in the case a shared interrupt is triggered; by checking the interrupt statuses first, the code can decide which ISRs can be skipped Parameters source -- The interrupt source. One of the ETS_*_INTR_SOURCE interrupt mux sources, as defined in soc/soc.h, or one of the internal ETS_INTERNAL_*_INTR_SOURCE sources as defined in this header. flags -- An ORred mask of the ESP_INTR_FLAG_* defines. These restrict the choice of interrupts that this routine can choose from. If this value is 0, it will default to allocating a non-shared interrupt of level 1, 2 or 3. If this is ESP_INTR_FLAG_SHARED, it will allocate a shared interrupt of level 1. Setting ESP_INTR_FLAG_INTRDISABLED will return from this function with the interrupt disabled. intrstatusreg -- The address of an interrupt status register intrstatusmask -- A mask. If a read of address intrstatusreg has any of the bits that are 1 in the mask set, the ISR will be called. If not, it will be skipped. handler -- The interrupt handler. Must be NULL when an interrupt of level >3 is requested, because these types of interrupts aren't C-callable. arg -- Optional argument for passed to the interrupt handler ret_handle -- Pointer to an intr_handle_t to store a handle that can later be used to request details or free the interrupt. Can be NULL if no handle is required. source -- The interrupt source. One of the ETS_*_INTR_SOURCE interrupt mux sources, as defined in soc/soc.h, or one of the internal ETS_INTERNAL_*_INTR_SOURCE sources as defined in this header. flags -- An ORred mask of the ESP_INTR_FLAG_* defines. These restrict the choice of interrupts that this routine can choose from. If this value is 0, it will default to allocating a non-shared interrupt of level 1, 2 or 3. If this is ESP_INTR_FLAG_SHARED, it will allocate a shared interrupt of level 1. Setting ESP_INTR_FLAG_INTRDISABLED will return from this function with the interrupt disabled. intrstatusreg -- The address of an interrupt status register intrstatusmask -- A mask. If a read of address intrstatusreg has any of the bits that are 1 in the mask set, the ISR will be called. If not, it will be skipped. handler -- The interrupt handler. Must be NULL when an interrupt of level >3 is requested, because these types of interrupts aren't C-callable. arg -- Optional argument for passed to the interrupt handler ret_handle -- Pointer to an intr_handle_t to store a handle that can later be used to request details or free the interrupt. Can be NULL if no handle is required. source -- The interrupt source. One of the ETS_*_INTR_SOURCE interrupt mux sources, as defined in soc/soc.h, or one of the internal ETS_INTERNAL_*_INTR_SOURCE sources as defined in this header. Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_OK otherwise Parameters source -- The interrupt source. One of the ETS_*_INTR_SOURCE interrupt mux sources, as defined in soc/soc.h, or one of the internal ETS_INTERNAL_*_INTR_SOURCE sources as defined in this header. flags -- An ORred mask of the ESP_INTR_FLAG_* defines. These restrict the choice of interrupts that this routine can choose from. If this value is 0, it will default to allocating a non-shared interrupt of level 1, 2 or 3. If this is ESP_INTR_FLAG_SHARED, it will allocate a shared interrupt of level 1. Setting ESP_INTR_FLAG_INTRDISABLED will return from this function with the interrupt disabled. intrstatusreg -- The address of an interrupt status register intrstatusmask -- A mask. If a read of address intrstatusreg has any of the bits that are 1 in the mask set, the ISR will be called. If not, it will be skipped. handler -- The interrupt handler. Must be NULL when an interrupt of level >3 is requested, because these types of interrupts aren't C-callable. arg -- Optional argument for passed to the interrupt handler ret_handle -- Pointer to an intr_handle_t to store a handle that can later be used to request details or free the interrupt. Can be NULL if no handle is required. Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_OK otherwise esp_err_t esp_intr_free(intr_handle_t handle) Disable and free an interrupt. Use an interrupt handle to disable the interrupt and release the resources associated with it. If the current core is not the core that registered this interrupt, this routine will be assigned to the core that allocated this interrupt, blocking and waiting until the resource is successfully released. Note When the handler shares its source with other handlers, the interrupt status bits it's responsible for should be managed properly before freeing it. see esp_intr_disable for more details. Please do not call this function in esp_ipc_call_blocking . Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus Returns ESP_ERR_INVALID_ARG the handle is NULL ESP_FAIL failed to release this handle ESP_OK otherwise Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus Returns ESP_ERR_INVALID_ARG the handle is NULL ESP_FAIL failed to release this handle ESP_OK otherwise int esp_intr_get_cpu(intr_handle_t handle) Get CPU number an interrupt is tied to. Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus Returns The core number where the interrupt is allocated Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus Returns The core number where the interrupt is allocated int esp_intr_get_intno(intr_handle_t handle) Get the allocated interrupt for a certain handle. Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus Returns The interrupt number Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus Returns The interrupt number esp_err_t esp_intr_disable(intr_handle_t handle) Disable the interrupt associated with the handle. Note For local interrupts (ESP_INTERNAL_* sources), this function has to be called on the CPU the interrupt is allocated on. Other interrupts have no such restriction. When several handlers sharing a same interrupt source, interrupt status bits, which are handled in the handler to be disabled, should be masked before the disabling, or handled in other enabled interrupts properly. Miss of interrupt status handling will cause infinite interrupt calls and finally system crash. For local interrupts (ESP_INTERNAL_* sources), this function has to be called on the CPU the interrupt is allocated on. Other interrupts have no such restriction. When several handlers sharing a same interrupt source, interrupt status bits, which are handled in the handler to be disabled, should be masked before the disabling, or handled in other enabled interrupts properly. Miss of interrupt status handling will cause infinite interrupt calls and finally system crash. Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_OK otherwise Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_OK otherwise For local interrupts (ESP_INTERNAL_* sources), this function has to be called on the CPU the interrupt is allocated on. Other interrupts have no such restriction. esp_err_t esp_intr_enable(intr_handle_t handle) Enable the interrupt associated with the handle. Note For local interrupts (ESP_INTERNAL_* sources), this function has to be called on the CPU the interrupt is allocated on. Other interrupts have no such restriction. Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_OK otherwise Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_OK otherwise esp_err_t esp_intr_set_in_iram(intr_handle_t handle, bool is_in_iram) Set the "in IRAM" status of the handler. Note Does not work on shared interrupts. Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus is_in_iram -- Whether the handler associated with this handle resides in IRAM. Handlers residing in IRAM can be called when cache is disabled. handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus is_in_iram -- Whether the handler associated with this handle resides in IRAM. Handlers residing in IRAM can be called when cache is disabled. handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_OK otherwise Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus is_in_iram -- Whether the handler associated with this handle resides in IRAM. Handlers residing in IRAM can be called when cache is disabled. Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_OK otherwise void esp_intr_noniram_disable(void) Disable interrupts that aren't specifically marked as running from IRAM. void esp_intr_noniram_enable(void) Re-enable interrupts disabled by esp_intr_noniram_disable. void esp_intr_enable_source(int inum) enable the interrupt source based on its number Parameters inum -- interrupt number from 0 to 31 Parameters inum -- interrupt number from 0 to 31 void esp_intr_disable_source(int inum) disable the interrupt source based on its number Parameters inum -- interrupt number from 0 to 31 Parameters inum -- interrupt number from 0 to 31 static inline int esp_intr_flags_to_level(int flags) Get the lowest interrupt level from the flags. Parameters flags -- The same flags that pass to esp_intr_alloc_intrstatus API Parameters flags -- The same flags that pass to esp_intr_alloc_intrstatus API static inline int esp_intr_level_to_flags(int level) Get the interrupt flags from the supplied level (priority) Parameters level -- The interrupt priority level Parameters level -- The interrupt priority level Macros ESP_INTR_FLAG_LEVEL1 Interrupt allocation flags. These flags can be used to specify which interrupt qualities the code calling esp_intr_alloc* needs. Accept a Level 1 interrupt vector (lowest priority) ESP_INTR_FLAG_LEVEL2 Accept a Level 2 interrupt vector. ESP_INTR_FLAG_LEVEL3 Accept a Level 3 interrupt vector. ESP_INTR_FLAG_LEVEL4 Accept a Level 4 interrupt vector. ESP_INTR_FLAG_LEVEL5 Accept a Level 5 interrupt vector. ESP_INTR_FLAG_LEVEL6 Accept a Level 6 interrupt vector. ESP_INTR_FLAG_NMI Accept a Level 7 interrupt vector (highest priority) ESP_INTR_FLAG_SHARED Interrupt can be shared between ISRs. ESP_INTR_FLAG_EDGE Edge-triggered interrupt. ESP_INTR_FLAG_IRAM ISR can be called if cache is disabled. ESP_INTR_FLAG_INTRDISABLED Return with this interrupt disabled. ESP_INTR_FLAG_LOWMED Low and medium prio interrupts. These can be handled in C. ESP_INTR_FLAG_HIGH High level interrupts. Need to be handled in assembly. ESP_INTR_FLAG_LEVELMASK Mask for all level flags. ETS_INTERNAL_TIMER0_INTR_SOURCE Platform timer 0 interrupt source. The esp_intr_alloc* functions can allocate an int for all ETS_*_INTR_SOURCE interrupt sources that are routed through the interrupt mux. Apart from these sources, each core also has some internal sources that do not pass through the interrupt mux. To allocate an interrupt for these sources, pass these pseudo-sources to the functions. ETS_INTERNAL_TIMER1_INTR_SOURCE Platform timer 1 interrupt source. ETS_INTERNAL_TIMER2_INTR_SOURCE Platform timer 2 interrupt source. ETS_INTERNAL_SW0_INTR_SOURCE Software int source 1. ETS_INTERNAL_SW1_INTR_SOURCE Software int source 2. ETS_INTERNAL_PROFILING_INTR_SOURCE Int source for profiling. ETS_INTERNAL_UNUSED_INTR_SOURCE Interrupt is not assigned to any source. ETS_INTERNAL_INTR_SOURCE_OFF Provides SystemView with positive IRQ IDs, otherwise scheduler events are not shown properly ESP_INTR_ENABLE(inum) Enable interrupt by interrupt number ESP_INTR_DISABLE(inum) Disable interrupt by interrupt number
Interrupt Allocation Overview The ESP32 has two cores, with 32 interrupts each. Each interrupt has a fixed priority, most (but not all) interrupts are connected to the interrupt matrix. Because there are more interrupt sources than interrupts, sometimes it makes sense to share an interrupt in multiple drivers. The esp_intr_alloc() abstraction exists to hide all these implementation details. A driver can allocate an interrupt for a certain peripheral by calling esp_intr_alloc() (or esp_intr_alloc_intrstatus()). It can use the flags passed to this function to specify the type, priority, and trigger method of the interrupt to allocate. The interrupt allocation code will then find an applicable interrupt, use the interrupt matrix to hook it up to the peripheral, and install the given interrupt handler and ISR to it. The interrupt allocator presents two different types of interrupts, namely shared interrupts and non-shared interrupts, both of which require different handling. Non-shared interrupts will allocate a separate interrupt for every esp_intr_alloc() call, and this interrupt is use solely for the peripheral attached to it, with only one ISR that will get called. Shared interrupts can have multiple peripherals triggering them, with multiple ISRs being called when one of the peripherals attached signals an interrupt. Thus, ISRs that are intended for shared interrupts should check the interrupt status of the peripheral they service in order to check if any action is required. Non-shared interrupts can be either level- or edge-triggered. Shared interrupts can only be level interrupts due to the chance of missed interrupts when edge interrupts are used. To illustrate why shard interrupts can only be level-triggered, take the scenario where peripheral A and peripheral B share the same edge-triggered interrupt. Peripheral B triggers an interrupt and sets its interrupt signal high, causing a low-to-high edge, which in turn latches the CPU's interrupt bit and triggers the ISR. The ISR executes, checks that peripheral A did not trigger an interrupt, and proceeds to handle and clear peripheral B's interrupt signal. Before the ISR returns, the CPU clears its interrupt bit latch. Thus, during the entire interrupt handling process, if peripheral A triggers an interrupt, it will be missed due the CPU clearing the interrupt bit latch. Multicore Issues Peripherals that can generate interrupts can be divided in two types: - External peripherals, within the ESP32 but outside the Xtensa cores themselves. Most ESP32 peripherals are of this type. - Internal peripherals, part of the Xtensa CPU cores themselves. Interrupt handling differs slightly between these two types of peripherals. Internal Peripheral Interrupts Each Xtensa CPU core has its own set of six internal peripherals: - Three timer comparators - A performance monitor - Two software interrupts Internal interrupt sources are defined in esp_intr_alloc.h as ETS_INTERNAL_*_INTR_SOURCE. These peripherals can only be configured from the core they are associated with. When generating an interrupt, the interrupt they generate is hard-wired to their associated core; it is not possible to have, for example, an internal timer comparator of one core generate an interrupt on another core. That is why these sources can only be managed using a task running on that specific core. Internal interrupt sources are still allocatable using esp_intr_alloc() as normal, but they cannot be shared and will always have a fixed interrupt level (namely, the one associated in hardware with the peripheral). External Peripheral Interrupts The remaining interrupt sources are from external peripherals. These are defined in soc/soc.h as ETS_*_INTR_SOURCE. Non-internal interrupt slots in both CPU cores are wired to an interrupt matrix, which can be used to route any external interrupt source to any of these interrupt slots. Allocating an external interrupt will always allocate it on the core that does the allocation. Freeing an external interrupt must always happen on the same core it was allocated on. Disabling and enabling external interrupts from another core is allowed. Multiple external interrupt sources can share an interrupt slot by passing ESP_INTR_FLAG_SHAREDas a flag to esp_intr_alloc(). Care should be taken when calling esp_intr_alloc() from a task which is not pinned to a core. During task switching, these tasks can migrate between cores. Therefore it is impossible to tell which CPU the interrupt is allocated on, which makes it difficult to free the interrupt handle and may also cause debugging difficulties. It is advised to use xTaskCreatePinnedToCore() with a specific CoreID argument to create tasks that allocate interrupts. In the case of internal interrupt sources, this is required. IRAM-Safe Interrupt Handlers The ESP_INTR_FLAG_IRAM flag registers an interrupt handler that always runs from IRAM (and reads all its data from DRAM), and therefore does not need to be disabled during flash erase and write operations. This is useful for interrupts which need a guaranteed minimum execution latency, as flash write and erase operations can be slow (erases can take tens or hundreds of milliseconds to complete). It can also be useful to keep an interrupt handler in IRAM if it is called very frequently, to avoid flash cache misses. Refer to the SPI flash API documentation for more details. Multiple Handlers Sharing A Source Several handlers can be assigned to a same source, given that all handlers are allocated using the ESP_INTR_FLAG_SHARED flag. They will all be allocated to the interrupt, which the source is attached to, and called sequentially when the source is active. The handlers can be disabled and freed individually. The source is attached to the interrupt (enabled), if one or more handlers are enabled, otherwise detached. A handler will never be called when disabled, while its source may still be triggered if any one of its handler enabled. Sources attached to non-shared interrupt do not support this feature. By default, when ESP_INTR_FLAG_SHARED flag is specified, the interrupt allocator will allocate only priority level 1 interrupts. Use ESP_INTR_FLAG_SHARED | ESP_INTR_FLAG_LOWMED to also allow allocating shared interrupts at priority levels 2 and 3. Though the framework supports this feature, you have to use it very carefully. There usually exist two ways to stop an interrupt from being triggered: disable the source or mask peripheral interrupt status. ESP-IDF only handles enabling and disabling of the source itself, leaving status and mask bits to be handled by users. Status bits shall either be masked before the handler responsible for it is disabled, or be masked and then properly handled in another enabled interrupt. Note Leaving some status bits unhandled without masking them, while disabling the handlers for them, will cause the interrupt(s) to be triggered indefinitely, resulting therefore in a system crash. Troubleshooting Interrupt Allocation On most Espressif SoCs, CPU interrupts are a limited resource. Therefore it is possible for a program to run out of CPU interrupts, for example by initializing several peripheral drivers. Typically, this will result in the driver initialization function returning ESP_ERR_NOT_FOUND error code. If this happens, you can use esp_intr_dump() function to print the list of interrupts along with their status. The output of this function typically looks like this: CPU 0 interrupt status: Int Level Type Status 0 1 Level Reserved 1 1 Level Reserved 2 1 Level Used: RTC_CORE 3 1 Level Used: TG0_LACT_LEVEL ... The columns of the output have the following meaning: Int: CPU interrupt input number. This is typically not used in software directly, and is provided for reference only. Level: Interrupt priority (1-7) of the CPU interrupt. This priority is fixed in hardware, and cannot be changed. Type: Interrupt type (Level or Edge) of the CPU interrupt. This type is fixed in hardware, and cannot be changed. Status: One of the possible statuses of the interrupt: Reserved: The interrupt is reserved either at hardware level, or by one of the parts of ESP-IDF. It can not be allocated using esp_intr_alloc(). Used: <source>: The interrupt is allocated and connected to a single peripheral. Shared: <source1> <source2> ...: The interrupt is allocated and connected to multiple peripherals. See Multiple Handlers Sharing A Source above. Free: The interrupt is not allocated and can be used by esp_intr_alloc(). - Free (not general-use): The interrupt is not allocated, but is either a high-priority interrupt (priority 4-7) or an edge-triggered interrupt. High-priority interrupts can be allocated using esp_intr_alloc()but requires the handlers to be written in Assembly, see High Priority Interrupts. Edge-triggered low- and medium-priority interrupts can also be allocated using esp_intr_alloc(), but are not used often since most peripheral interrupts are level-triggered. If you have confirmed that the application is indeed running out of interrupts, a combination of the following suggestions can help resolve the issue: On multi-core SoCs, try initializing some of the peripheral drivers from a task pinned to the second core. Interrupts are typically allocated on the same core where the peripheral driver initialization function runs. Therefore by running the initialization function on the second core, more interrupt inputs can be used. Determine the interrupts which can tolerate higher latency, and allocate them using ESP_INTR_FLAG_SHAREDflag (optionally ORed with ESP_INTR_FLAG_LOWMED). Using this flag for two or more peripherals will let them use a single interrupt input, and therefore save interrupt inputs for other peripherals. See Multiple Handlers Sharing A Source above. Some peripheral driver may default to allocating interrupts with ESP_INTR_FLAG_LEVEL1flag, so priority 2 and 3 interrupts do not get used by default. If esp_intr_dump()shows that some priority 2 or 3 interrupts are available, try changing the interrupt allocation flags when initializing the driver to ESP_INTR_FLAG_LEVEL2or ESP_INTR_FLAG_LEVEL3. Check if some of the peripheral drivers do not need to be used all the time, and initialize or deinitialize them on demand. This can reduce the number of simultaneously allocated interrupts. API Reference Header File This header file can be included with: #include "esp_intr_types.h" Macros - ESP_INTR_CPU_AFFINITY_TO_CORE_ID(cpu_affinity) Convert esp_intr_cpu_affinity_t to CPU core ID. Type Definitions - typedef void (*intr_handler_t)(void *arg) Function prototype for interrupt handler function - typedef struct intr_handle_data_t *intr_handle_t Handle to an interrupt handler Enumerations - enum esp_intr_cpu_affinity_t Interrupt CPU core affinity. This type specify the CPU core that the peripheral interrupt is connected to. Values: - enumerator ESP_INTR_CPU_AFFINITY_AUTO Install the peripheral interrupt to ANY CPU core, decided by on which CPU the interrupt allocator is running. - enumerator ESP_INTR_CPU_AFFINITY_0 Install the peripheral interrupt to CPU core 0. - enumerator ESP_INTR_CPU_AFFINITY_1 Install the peripheral interrupt to CPU core 1. - enumerator ESP_INTR_CPU_AFFINITY_AUTO Header File This header file can be included with: #include "esp_intr_alloc.h" Functions Mark an interrupt as a shared interrupt. This will mark a certain interrupt on the specified CPU as an interrupt that can be used to hook shared interrupt handlers to. - Parameters intno -- The number of the interrupt (0-31) cpu -- CPU on which the interrupt should be marked as shared (0 or 1) is_in_iram -- Shared interrupt is for handlers that reside in IRAM and the int can be left enabled while the flash cache is disabled. - - Returns ESP_ERR_INVALID_ARG if cpu or intno is invalid ESP_OK otherwise - esp_err_t esp_intr_reserve(int intno, int cpu) Reserve an interrupt to be used outside of this framework. This will mark a certain interrupt on the specified CPU as reserved, not to be allocated for any reason. - Parameters intno -- The number of the interrupt (0-31) cpu -- CPU on which the interrupt should be marked as shared (0 or 1) - - Returns ESP_ERR_INVALID_ARG if cpu or intno is invalid ESP_OK otherwise - esp_err_t esp_intr_alloc(int source, int flags, intr_handler_t handler, void *arg, intr_handle_t *ret_handle) Allocate an interrupt with the given parameters. This finds an interrupt that matches the restrictions as given in the flags parameter, maps the given interrupt source to it and hooks up the given interrupt handler (with optional argument) as well. If needed, it can return a handle for the interrupt as well. The interrupt will always be allocated on the core that runs this function. If ESP_INTR_FLAG_IRAM flag is used, and handler address is not in IRAM or RTC_FAST_MEM, then ESP_ERR_INVALID_ARG is returned. - Parameters source -- The interrupt source. One of the ETS_*_INTR_SOURCE interrupt mux sources, as defined in soc/soc.h, or one of the internal ETS_INTERNAL_*_INTR_SOURCE sources as defined in this header. flags -- An ORred mask of the ESP_INTR_FLAG_* defines. These restrict the choice of interrupts that this routine can choose from. If this value is 0, it will default to allocating a non-shared interrupt of level 1, 2 or 3. If this is ESP_INTR_FLAG_SHARED, it will allocate a shared interrupt of level 1. Setting ESP_INTR_FLAG_INTRDISABLED will return from this function with the interrupt disabled. handler -- The interrupt handler. Must be NULL when an interrupt of level >3 is requested, because these types of interrupts aren't C-callable. arg -- Optional argument for passed to the interrupt handler ret_handle -- Pointer to an intr_handle_t to store a handle that can later be used to request details or free the interrupt. Can be NULL if no handle is required. - - Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_OK otherwise - esp_err_t esp_intr_alloc_intrstatus(int source, int flags, uint32_t intrstatusreg, uint32_t intrstatusmask, intr_handler_t handler, void *arg, intr_handle_t *ret_handle) Allocate an interrupt with the given parameters. This essentially does the same as esp_intr_alloc, but allows specifying a register and mask combo. For shared interrupts, the handler is only called if a read from the specified register, ANDed with the mask, returns non-zero. By passing an interrupt status register address and a fitting mask, this can be used to accelerate interrupt handling in the case a shared interrupt is triggered; by checking the interrupt statuses first, the code can decide which ISRs can be skipped - Parameters source -- The interrupt source. One of the ETS_*_INTR_SOURCE interrupt mux sources, as defined in soc/soc.h, or one of the internal ETS_INTERNAL_*_INTR_SOURCE sources as defined in this header. flags -- An ORred mask of the ESP_INTR_FLAG_* defines. These restrict the choice of interrupts that this routine can choose from. If this value is 0, it will default to allocating a non-shared interrupt of level 1, 2 or 3. If this is ESP_INTR_FLAG_SHARED, it will allocate a shared interrupt of level 1. Setting ESP_INTR_FLAG_INTRDISABLED will return from this function with the interrupt disabled. intrstatusreg -- The address of an interrupt status register intrstatusmask -- A mask. If a read of address intrstatusreg has any of the bits that are 1 in the mask set, the ISR will be called. If not, it will be skipped. handler -- The interrupt handler. Must be NULL when an interrupt of level >3 is requested, because these types of interrupts aren't C-callable. arg -- Optional argument for passed to the interrupt handler ret_handle -- Pointer to an intr_handle_t to store a handle that can later be used to request details or free the interrupt. Can be NULL if no handle is required. - - Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_OK otherwise - esp_err_t esp_intr_free(intr_handle_t handle) Disable and free an interrupt. Use an interrupt handle to disable the interrupt and release the resources associated with it. If the current core is not the core that registered this interrupt, this routine will be assigned to the core that allocated this interrupt, blocking and waiting until the resource is successfully released. Note When the handler shares its source with other handlers, the interrupt status bits it's responsible for should be managed properly before freeing it. see esp_intr_disablefor more details. Please do not call this function in esp_ipc_call_blocking. - Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus - Returns ESP_ERR_INVALID_ARG the handle is NULL ESP_FAIL failed to release this handle ESP_OK otherwise - int esp_intr_get_cpu(intr_handle_t handle) Get CPU number an interrupt is tied to. - Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus - Returns The core number where the interrupt is allocated - int esp_intr_get_intno(intr_handle_t handle) Get the allocated interrupt for a certain handle. - Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus - Returns The interrupt number - esp_err_t esp_intr_disable(intr_handle_t handle) Disable the interrupt associated with the handle. Note For local interrupts (ESP_INTERNAL_* sources), this function has to be called on the CPU the interrupt is allocated on. Other interrupts have no such restriction. When several handlers sharing a same interrupt source, interrupt status bits, which are handled in the handler to be disabled, should be masked before the disabling, or handled in other enabled interrupts properly. Miss of interrupt status handling will cause infinite interrupt calls and finally system crash. - Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus - Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_OK otherwise - - esp_err_t esp_intr_enable(intr_handle_t handle) Enable the interrupt associated with the handle. Note For local interrupts (ESP_INTERNAL_* sources), this function has to be called on the CPU the interrupt is allocated on. Other interrupts have no such restriction. - Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus - Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_OK otherwise - esp_err_t esp_intr_set_in_iram(intr_handle_t handle, bool is_in_iram) Set the "in IRAM" status of the handler. Note Does not work on shared interrupts. - Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus is_in_iram -- Whether the handler associated with this handle resides in IRAM. Handlers residing in IRAM can be called when cache is disabled. - - Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_OK otherwise - void esp_intr_noniram_disable(void) Disable interrupts that aren't specifically marked as running from IRAM. - void esp_intr_noniram_enable(void) Re-enable interrupts disabled by esp_intr_noniram_disable. - void esp_intr_enable_source(int inum) enable the interrupt source based on its number - Parameters inum -- interrupt number from 0 to 31 - void esp_intr_disable_source(int inum) disable the interrupt source based on its number - Parameters inum -- interrupt number from 0 to 31 - static inline int esp_intr_flags_to_level(int flags) Get the lowest interrupt level from the flags. - Parameters flags -- The same flags that pass to esp_intr_alloc_intrstatusAPI - static inline int esp_intr_level_to_flags(int level) Get the interrupt flags from the supplied level (priority) - Parameters level -- The interrupt priority level Macros - ESP_INTR_FLAG_LEVEL1 Interrupt allocation flags. These flags can be used to specify which interrupt qualities the code calling esp_intr_alloc* needs. Accept a Level 1 interrupt vector (lowest priority) - ESP_INTR_FLAG_LEVEL2 Accept a Level 2 interrupt vector. - ESP_INTR_FLAG_LEVEL3 Accept a Level 3 interrupt vector. - ESP_INTR_FLAG_LEVEL4 Accept a Level 4 interrupt vector. - ESP_INTR_FLAG_LEVEL5 Accept a Level 5 interrupt vector. - ESP_INTR_FLAG_LEVEL6 Accept a Level 6 interrupt vector. - ESP_INTR_FLAG_NMI Accept a Level 7 interrupt vector (highest priority) - ESP_INTR_FLAG_SHARED Interrupt can be shared between ISRs. - ESP_INTR_FLAG_EDGE Edge-triggered interrupt. - ESP_INTR_FLAG_IRAM ISR can be called if cache is disabled. - ESP_INTR_FLAG_INTRDISABLED Return with this interrupt disabled. - ESP_INTR_FLAG_LOWMED Low and medium prio interrupts. These can be handled in C. - ESP_INTR_FLAG_HIGH High level interrupts. Need to be handled in assembly. - ESP_INTR_FLAG_LEVELMASK Mask for all level flags. - ETS_INTERNAL_TIMER0_INTR_SOURCE Platform timer 0 interrupt source. The esp_intr_alloc* functions can allocate an int for all ETS_*_INTR_SOURCE interrupt sources that are routed through the interrupt mux. Apart from these sources, each core also has some internal sources that do not pass through the interrupt mux. To allocate an interrupt for these sources, pass these pseudo-sources to the functions. - ETS_INTERNAL_TIMER1_INTR_SOURCE Platform timer 1 interrupt source. - ETS_INTERNAL_TIMER2_INTR_SOURCE Platform timer 2 interrupt source. - ETS_INTERNAL_SW0_INTR_SOURCE Software int source 1. - ETS_INTERNAL_SW1_INTR_SOURCE Software int source 2. - ETS_INTERNAL_PROFILING_INTR_SOURCE Int source for profiling. - ETS_INTERNAL_UNUSED_INTR_SOURCE Interrupt is not assigned to any source. - ETS_INTERNAL_INTR_SOURCE_OFF Provides SystemView with positive IRQ IDs, otherwise scheduler events are not shown properly - ESP_INTR_ENABLE(inum) Enable interrupt by interrupt number - ESP_INTR_DISABLE(inum) Disable interrupt by interrupt number
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/intr_alloc.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Logging library
null
espressif.com
2016-01-01
cd3b355f406f0aa
null
null
Logging library Overview The logging library provides three ways for setting log verbosity: At compile time: in menuconfig, set the verbosity level using the option CONFIG_LOG_DEFAULT_LEVEL. Optionally, also in menuconfig, set the maximum verbosity level using the option CONFIG_LOG_MAXIMUM_LEVEL. By default, this is the same as the default level, but it can be set higher in order to compile more optional logs into the firmware. At runtime: all logs for verbosity levels lower than CONFIG_LOG_DEFAULT_LEVEL are enabled by default. The function esp_log_level_set() can be used to set a logging level on a per-module basis. Modules are identified by their tags, which are human-readable ASCII zero-terminated strings. At runtime: if CONFIG_LOG_MASTER_LEVEL is enabled then a Master logging level can be set using esp_log_set_level_master() . This option adds an additional logging level check for all compiled logs. Note that this will increase application size. This feature is useful if you want to compile in a lot of logs that are selectable at runtime, but also want to avoid the performance hit from looking up the tags and their log level when you don't want log output. There are the following verbosity levels: Error (lowest) Warning Info Debug Verbose (highest) Note The function esp_log_level_set() cannot set logging levels higher than specified by CONFIG_LOG_MAXIMUM_LEVEL. To increase log level for a specific file above this maximum at compile time, use the macro LOG_LOCAL_LEVEL (see the details below). How to use this library In each C file that uses logging functionality, define the TAG variable as shown below: static const char* TAG = "MyModule"; Then use one of logging macros to produce output, e.g: ESP_LOGW(TAG, "Baud rate error %.1f%%. Requested: %d baud, actual: %d baud", error * 100, baud_req, baud_real); Several macros are available for different verbosity levels: ESP_LOGE - error (lowest) ESP_LOGW - warning ESP_LOGI - info ESP_LOGD - debug ESP_LOGV - verbose (highest) Additionally, there are ESP_EARLY_LOGx versions for each of these macros, e.g. ESP_EARLY_LOGE . These versions have to be used explicitly in the early startup code only, before heap allocator and syscalls have been initialized. Normal ESP_LOGx macros can also be used while compiling the bootloader, but they will fall back to the same implementation as ESP_EARLY_LOGx macros. There are also ESP_DRAM_LOGx versions for each of these macros, e.g. ESP_DRAM_LOGE . These versions are used in some places where logging may occur with interrupts disabled or with flash cache inaccessible. Use of this macros should be as sparing as possible, as logging in these types of code should be avoided for performance reasons. Note Inside critical sections interrupts are disabled so it's only possible to use ESP_DRAM_LOGx (preferred) or ESP_EARLY_LOGx . Even though it's possible to log in these situations, it's better if your program can be structured not to require it. To override default verbosity level at file or component scope, define the LOG_LOCAL_LEVEL macro. At file scope, define it before including esp_log.h , e.g.: #define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE #include "esp_log.h" At component scope, define it in the component CMakeLists: target_compile_definitions(${COMPONENT_LIB} PUBLIC "-DLOG_LOCAL_LEVEL=ESP_LOG_VERBOSE") To configure logging output per module at runtime, add calls to the function esp_log_level_set() as follows: esp_log_level_set("*", ESP_LOG_ERROR); // set all components to ERROR level esp_log_level_set("wifi", ESP_LOG_WARN); // enable WARN logs from WiFi stack esp_log_level_set("dhcpc", ESP_LOG_INFO); // enable INFO logs from DHCP client Note The "DRAM" and "EARLY" log macro variants documented above do not support per module setting of log verbosity. These macros will always log at the "default" verbosity level, which can only be changed at runtime by calling esp_log_level("*", level) . Even when logs are disabled by using a tag name they will still require a processing time of around 10.9 microseconds per entry. Master Logging Level To enable the Master logging level feature, the CONFIG_LOG_MASTER_LEVEL option must be enabled. It adds an additional level check for ESP_LOGx macros before calling esp_log_write() . This allows to set a higher CONFIG_LOG_MAXIMUM_LEVEL, but not inflict a performance hit during normal operation (only when directed). An application may set the master logging level ( esp_log_set_level_master() ) globally to enforce a maximum log level. ESP_LOGx macros above this level will be skipped immediately, rather than calling esp_log_write() and doing a tag lookup. It is recommended to only use this in an top-level application and not in shared components as this would override the global log level for any user using the component. By default, at startup, the Master logging level is CONFIG_LOG_DEFAULT_LEVEL. Note that this feature increases application size because the additional check is added into all ESP_LOGx macros. The snippet below shows how it works. Setting the Master logging level to ESP_LOG_NONE disables all logging globally. esp_log_level_set() does not currently affect logging. But after the Master logging level is released, the logs will be printed as set by esp_log_level_set() . // Master logging level is CONFIG_LOG_DEFAULT_LEVEL at start up and = ESP_LOG_INFO ESP_LOGI("lib_name", "Message for print"); // prints a INFO message esp_log_level_set("lib_name", ESP_LOG_WARN); // enables WARN logs from lib_name esp_log_set_level_master(ESP_LOG_NONE); // disables all logs globally. esp_log_level_set has no effect at the moment. ESP_LOGW("lib_name", "Message for print"); // no print, Master logging level blocks it esp_log_level_set("lib_name", ESP_LOG_INFO); // enable INFO logs from lib_name ESP_LOGI("lib_name", "Message for print"); // no print, Master logging level blocks it esp_log_set_level_master(ESP_LOG_INFO); // enables all INFO logs globally. ESP_LOGI("lib_name", "Message for print"); // prints a INFO message Logging to Host via JTAG By default, the logging library uses the vprintf-like function to write formatted output to the dedicated UART. By calling a simple API, all log output may be routed to JTAG instead, making logging several times faster. For details, please refer to Section Logging to Host. Thread Safety The log string is first written into a memory buffer and then sent to the UART for printing. Log calls are thread-safe, i.e., logs of different threads do not conflict with each other. Application Example The logging library is commonly used by most ESP-IDF components and examples. For demonstration of log functionality, check ESP-IDF's examples directory. The most relevant examples that deal with logging are the following: API Reference Header File This header file can be included with: #include "esp_log.h" Functions void esp_log_set_level_master(esp_log_level_t level) Master log level. Optional master log level to check against for ESP_LOGx macros before calling esp_log_write. Allows one to set a higher CONFIG_LOG_MAXIMUM_LEVEL but not impose a performance hit during normal operation (only when instructed). An application may set esp_log_set_level_master(level) to globally enforce a maximum log level. ESP_LOGx macros above this level will be skipped immediately, rather than calling esp_log_write and doing a cache hit. The tradeoff is increased application size. Parameters level -- Master log level Parameters level -- Master log level esp_log_level_t esp_log_get_level_master(void) Returns master log level. Returns Master log level Returns Master log level void esp_log_level_set(const char *tag, esp_log_level_t level) Set log level for given tag. If logging for given component has already been enabled, changes previous setting. Note Note that this function can not raise log level above the level set using CONFIG_LOG_MAXIMUM_LEVEL setting in menuconfig. To raise log level above the default one for a given file, define LOG_LOCAL_LEVEL to one of the ESP_LOG_* values, before including esp_log.h in this file. Parameters tag -- Tag of the log entries to enable. Must be a non-NULL zero terminated string. Value "*" resets log level for all tags to the given value. level -- Selects log level to enable. Only logs at this and lower verbosity levels will be shown. tag -- Tag of the log entries to enable. Must be a non-NULL zero terminated string. Value "*" resets log level for all tags to the given value. level -- Selects log level to enable. Only logs at this and lower verbosity levels will be shown. tag -- Tag of the log entries to enable. Must be a non-NULL zero terminated string. Value "*" resets log level for all tags to the given value. Parameters tag -- Tag of the log entries to enable. Must be a non-NULL zero terminated string. Value "*" resets log level for all tags to the given value. level -- Selects log level to enable. Only logs at this and lower verbosity levels will be shown. esp_log_level_t esp_log_level_get(const char *tag) Get log level for a given tag, can be used to avoid expensive log statements. Parameters tag -- Tag of the log to query current level. Must be a non-NULL zero terminated string. Returns The current log level for the given tag Parameters tag -- Tag of the log to query current level. Must be a non-NULL zero terminated string. Returns The current log level for the given tag vprintf_like_t esp_log_set_vprintf(vprintf_like_t func) Set function used to output log entries. By default, log output goes to UART0. This function can be used to redirect log output to some other destination, such as file or network. Returns the original log handler, which may be necessary to return output to the previous destination. Note Please note that function callback here must be re-entrant as it can be invoked in parallel from multiple thread context. Parameters func -- new Function used for output. Must have same signature as vprintf. Returns func old Function used for output. Parameters func -- new Function used for output. Must have same signature as vprintf. Returns func old Function used for output. uint32_t esp_log_timestamp(void) Function which returns timestamp to be used in log output. This function is used in expansion of ESP_LOGx macros. In the 2nd stage bootloader, and at early application startup stage this function uses CPU cycle counter as time source. Later when FreeRTOS scheduler start running, it switches to FreeRTOS tick count. For now, we ignore millisecond counter overflow. Returns timestamp, in milliseconds Returns timestamp, in milliseconds char *esp_log_system_timestamp(void) Function which returns system timestamp to be used in log output. This function is used in expansion of ESP_LOGx macros to print the system time as "HH:MM:SS.sss". The system time is initialized to 0 on startup, this can be set to the correct time with an SNTP sync, or manually with standard POSIX time functions. Currently, this will not get used in logging from binary blobs (i.e. Wi-Fi & Bluetooth libraries), these will still print the RTOS tick time. Returns timestamp, in "HH:MM:SS.sss" Returns timestamp, in "HH:MM:SS.sss" uint32_t esp_log_early_timestamp(void) Function which returns timestamp to be used in log output. This function uses HW cycle counter and does not depend on OS, so it can be safely used after application crash. Returns timestamp, in milliseconds Returns timestamp, in milliseconds void esp_log_write(esp_log_level_t level, const char *tag, const char *format, ...) Write message into the log. This function is not intended to be used directly. Instead, use one of ESP_LOGE, ESP_LOGW, ESP_LOGI, ESP_LOGD, ESP_LOGV macros. This function or these macros should not be used from an interrupt. void esp_log_writev(esp_log_level_t level, const char *tag, const char *format, va_list args) Write message into the log, va_list variant. This function is provided to ease integration toward other logging framework, so that esp_log can be used as a log sink. See also esp_log_write() Macros ESP_LOG_BUFFER_HEX_LEVEL(tag, buffer, buff_len, level) Log a buffer of hex bytes at specified level, separated into 16 bytes each line. Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes level -- level of the log tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes level -- level of the log tag -- description tag Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes level -- level of the log ESP_LOG_BUFFER_CHAR_LEVEL(tag, buffer, buff_len, level) Log a buffer of characters at specified level, separated into 16 bytes each line. Buffer should contain only printable characters. Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes level -- level of the log tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes level -- level of the log tag -- description tag Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes level -- level of the log ESP_LOG_BUFFER_HEXDUMP(tag, buffer, buff_len, level) Dump a buffer to the log at specified level. The dump log shows just like the one below: W (195) log_example: 0x3ffb4280 45 53 50 33 32 20 69 73 20 67 72 65 61 74 2c 20 |ESP32 is great, | W (195) log_example: 0x3ffb4290 77 6f 72 6b 69 6e 67 20 61 6c 6f 6e 67 20 77 69 |working along wi| W (205) log_example: 0x3ffb42a0 74 68 20 74 68 65 20 49 44 46 2e 00 |th the IDF..| It is highly recommended to use terminals with over 102 text width. Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes level -- level of the log tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes level -- level of the log tag -- description tag Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes level -- level of the log ESP_LOG_BUFFER_HEX(tag, buffer, buff_len) Log a buffer of hex bytes at Info level. See also esp_log_buffer_hex_level Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes tag -- description tag Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes ESP_LOG_BUFFER_CHAR(tag, buffer, buff_len) Log a buffer of characters at Info level. Buffer should contain only printable characters. See also esp_log_buffer_char_level Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes tag -- description tag Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes ESP_EARLY_LOGE(tag, format, ...) macro to output logs in startup code, before heap allocator and syscalls have been initialized. Log at ESP_LOG_ERROR level. See also printf , ESP_LOGE , ESP_DRAM_LOGE In the future, we want to become compatible with clang. Hence, we provide two versions of the following macros which are using variadic arguments. The first one is using the GNU extension ##__VA_ARGS__. The second one is using the C++20 feature VA_OPT(,). This allows users to compile their code with standard C++20 enabled instead of the GNU extension. Below C++20, we haven't found any good alternative to using ##__VA_ARGS__. ESP_EARLY_LOGW(tag, format, ...) macro to output logs in startup code at ESP_LOG_WARN level. See also ESP_EARLY_LOGE , ESP_LOGE , printf ESP_EARLY_LOGI(tag, format, ...) macro to output logs in startup code at ESP_LOG_INFO level. See also ESP_EARLY_LOGE , ESP_LOGE , printf ESP_EARLY_LOGD(tag, format, ...) macro to output logs in startup code at ESP_LOG_DEBUG level. See also ESP_EARLY_LOGE , ESP_LOGE , printf ESP_EARLY_LOGV(tag, format, ...) macro to output logs in startup code at ESP_LOG_VERBOSE level. See also ESP_EARLY_LOGE , ESP_LOGE , printf _ESP_LOG_EARLY_ENABLED(log_level) ESP_LOG_EARLY_IMPL(tag, format, log_level, log_tag_letter, ...) ESP_LOGE(tag, format, ...) ESP_LOGW(tag, format, ...) ESP_LOGI(tag, format, ...) ESP_LOGD(tag, format, ...) ESP_LOGV(tag, format, ...) ESP_LOG_LEVEL(level, tag, format, ...) runtime macro to output logs at a specified level. See also printf Parameters tag -- tag of the log, which can be used to change the log level by esp_log_level_set at runtime. level -- level of the output log. format -- format of the output log. See printf ... -- variables to be replaced into the log. See printf tag -- tag of the log, which can be used to change the log level by esp_log_level_set at runtime. level -- level of the output log. format -- format of the output log. See printf ... -- variables to be replaced into the log. See printf tag -- tag of the log, which can be used to change the log level by esp_log_level_set at runtime. Parameters tag -- tag of the log, which can be used to change the log level by esp_log_level_set at runtime. level -- level of the output log. format -- format of the output log. See printf ... -- variables to be replaced into the log. See printf ESP_LOG_LEVEL_LOCAL(level, tag, format, ...) runtime macro to output logs at a specified level. Also check the level with LOG_LOCAL_LEVEL . If CONFIG_LOG_MASTER_LEVEL set, also check first against esp_log_get_level_master() . See also printf , ESP_LOG_LEVEL ESP_DRAM_LOGE(tag, format, ...) Macro to output logs when the cache is disabled. Log at ESP_LOG_ERROR level. Similar to Usage: ESP_DRAM_LOGE(DRAM_STR("my_tag"), "format", or ESP_DRAM_LOGE(TAG, "format", ...)`, where TAG is a char* that points to a str in the DRAM. See also ESP_EARLY_LOGE , the log level cannot be changed per-tag, however esp_log_level_set("*", level) will set the default level which controls these log lines also. See also esp_rom_printf , ESP_LOGE Note Unlike normal logging macros, it's possible to use this macro when interrupts are disabled or inside an ISR. Note Placing log strings in DRAM reduces available DRAM, so only use when absolutely essential. ESP_DRAM_LOGW(tag, format, ...) macro to output logs when the cache is disabled at ESP_LOG_WARN level. See also ESP_DRAM_LOGW , ESP_LOGW , esp_rom_printf ESP_DRAM_LOGI(tag, format, ...) macro to output logs when the cache is disabled at ESP_LOG_INFO level. See also ESP_DRAM_LOGI , ESP_LOGI , esp_rom_printf ESP_DRAM_LOGD(tag, format, ...) macro to output logs when the cache is disabled at ESP_LOG_DEBUG level. See also ESP_DRAM_LOGD , ESP_LOGD , esp_rom_printf ESP_DRAM_LOGV(tag, format, ...) macro to output logs when the cache is disabled at ESP_LOG_VERBOSE level. See also ESP_DRAM_LOGV , ESP_LOGV , esp_rom_printf Type Definitions typedef int (*vprintf_like_t)(const char*, va_list) Enumerations enum esp_log_level_t Log level. Values: enumerator ESP_LOG_NONE No log output enumerator ESP_LOG_NONE No log output enumerator ESP_LOG_ERROR Critical errors, software module can not recover on its own enumerator ESP_LOG_ERROR Critical errors, software module can not recover on its own enumerator ESP_LOG_WARN Error conditions from which recovery measures have been taken enumerator ESP_LOG_WARN Error conditions from which recovery measures have been taken enumerator ESP_LOG_INFO Information messages which describe normal flow of events enumerator ESP_LOG_INFO Information messages which describe normal flow of events enumerator ESP_LOG_DEBUG Extra information which is not necessary for normal use (values, pointers, sizes, etc). enumerator ESP_LOG_DEBUG Extra information which is not necessary for normal use (values, pointers, sizes, etc). enumerator ESP_LOG_VERBOSE Bigger chunks of debugging information, or frequent messages which can potentially flood the output. enumerator ESP_LOG_VERBOSE Bigger chunks of debugging information, or frequent messages which can potentially flood the output. enumerator ESP_LOG_NONE
Logging library Overview The logging library provides three ways for setting log verbosity: At compile time: in menuconfig, set the verbosity level using the option CONFIG_LOG_DEFAULT_LEVEL. Optionally, also in menuconfig, set the maximum verbosity level using the option CONFIG_LOG_MAXIMUM_LEVEL. By default, this is the same as the default level, but it can be set higher in order to compile more optional logs into the firmware. At runtime: all logs for verbosity levels lower than CONFIG_LOG_DEFAULT_LEVEL are enabled by default. The function esp_log_level_set()can be used to set a logging level on a per-module basis. Modules are identified by their tags, which are human-readable ASCII zero-terminated strings. At runtime: if CONFIG_LOG_MASTER_LEVEL is enabled then a Master logging levelcan be set using esp_log_set_level_master(). This option adds an additional logging level check for all compiled logs. Note that this will increase application size. This feature is useful if you want to compile in a lot of logs that are selectable at runtime, but also want to avoid the performance hit from looking up the tags and their log level when you don't want log output. There are the following verbosity levels: Error (lowest) Warning Info Debug Verbose (highest) Note The function esp_log_level_set() cannot set logging levels higher than specified by CONFIG_LOG_MAXIMUM_LEVEL. To increase log level for a specific file above this maximum at compile time, use the macro LOG_LOCAL_LEVEL (see the details below). How to use this library In each C file that uses logging functionality, define the TAG variable as shown below: static const char* TAG = "MyModule"; Then use one of logging macros to produce output, e.g: ESP_LOGW(TAG, "Baud rate error %.1f%%. Requested: %d baud, actual: %d baud", error * 100, baud_req, baud_real); Several macros are available for different verbosity levels: ESP_LOGE- error (lowest) ESP_LOGW- warning ESP_LOGI- info ESP_LOGD- debug ESP_LOGV- verbose (highest) Additionally, there are ESP_EARLY_LOGx versions for each of these macros, e.g. ESP_EARLY_LOGE. These versions have to be used explicitly in the early startup code only, before heap allocator and syscalls have been initialized. Normal ESP_LOGx macros can also be used while compiling the bootloader, but they will fall back to the same implementation as ESP_EARLY_LOGx macros. There are also ESP_DRAM_LOGx versions for each of these macros, e.g. ESP_DRAM_LOGE. These versions are used in some places where logging may occur with interrupts disabled or with flash cache inaccessible. Use of this macros should be as sparing as possible, as logging in these types of code should be avoided for performance reasons. Note Inside critical sections interrupts are disabled so it's only possible to use ESP_DRAM_LOGx (preferred) or ESP_EARLY_LOGx. Even though it's possible to log in these situations, it's better if your program can be structured not to require it. To override default verbosity level at file or component scope, define the LOG_LOCAL_LEVEL macro. At file scope, define it before including esp_log.h, e.g.: #define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE #include "esp_log.h" At component scope, define it in the component CMakeLists: target_compile_definitions(${COMPONENT_LIB} PUBLIC "-DLOG_LOCAL_LEVEL=ESP_LOG_VERBOSE") To configure logging output per module at runtime, add calls to the function esp_log_level_set() as follows: esp_log_level_set("*", ESP_LOG_ERROR); // set all components to ERROR level esp_log_level_set("wifi", ESP_LOG_WARN); // enable WARN logs from WiFi stack esp_log_level_set("dhcpc", ESP_LOG_INFO); // enable INFO logs from DHCP client Note The "DRAM" and "EARLY" log macro variants documented above do not support per module setting of log verbosity. These macros will always log at the "default" verbosity level, which can only be changed at runtime by calling esp_log_level("*", level). Even when logs are disabled by using a tag name they will still require a processing time of around 10.9 microseconds per entry. Master Logging Level To enable the Master logging level feature, the CONFIG_LOG_MASTER_LEVEL option must be enabled. It adds an additional level check for ESP_LOGx macros before calling esp_log_write(). This allows to set a higher CONFIG_LOG_MAXIMUM_LEVEL, but not inflict a performance hit during normal operation (only when directed). An application may set the master logging level ( esp_log_set_level_master()) globally to enforce a maximum log level. ESP_LOGx macros above this level will be skipped immediately, rather than calling esp_log_write() and doing a tag lookup. It is recommended to only use this in an top-level application and not in shared components as this would override the global log level for any user using the component. By default, at startup, the Master logging level is CONFIG_LOG_DEFAULT_LEVEL. Note that this feature increases application size because the additional check is added into all ESP_LOGx macros. The snippet below shows how it works. Setting the Master logging level to ESP_LOG_NONE disables all logging globally. esp_log_level_set() does not currently affect logging. But after the Master logging level is released, the logs will be printed as set by esp_log_level_set(). // Master logging level is CONFIG_LOG_DEFAULT_LEVEL at start up and = ESP_LOG_INFO ESP_LOGI("lib_name", "Message for print"); // prints a INFO message esp_log_level_set("lib_name", ESP_LOG_WARN); // enables WARN logs from lib_name esp_log_set_level_master(ESP_LOG_NONE); // disables all logs globally. esp_log_level_set has no effect at the moment. ESP_LOGW("lib_name", "Message for print"); // no print, Master logging level blocks it esp_log_level_set("lib_name", ESP_LOG_INFO); // enable INFO logs from lib_name ESP_LOGI("lib_name", "Message for print"); // no print, Master logging level blocks it esp_log_set_level_master(ESP_LOG_INFO); // enables all INFO logs globally. ESP_LOGI("lib_name", "Message for print"); // prints a INFO message Logging to Host via JTAG By default, the logging library uses the vprintf-like function to write formatted output to the dedicated UART. By calling a simple API, all log output may be routed to JTAG instead, making logging several times faster. For details, please refer to Section Logging to Host. Thread Safety The log string is first written into a memory buffer and then sent to the UART for printing. Log calls are thread-safe, i.e., logs of different threads do not conflict with each other. Application Example The logging library is commonly used by most ESP-IDF components and examples. For demonstration of log functionality, check ESP-IDF's examples directory. The most relevant examples that deal with logging are the following: API Reference Header File This header file can be included with: #include "esp_log.h" Functions - void esp_log_set_level_master(esp_log_level_t level) Master log level. Optional master log level to check against for ESP_LOGx macros before calling esp_log_write. Allows one to set a higher CONFIG_LOG_MAXIMUM_LEVEL but not impose a performance hit during normal operation (only when instructed). An application may set esp_log_set_level_master(level) to globally enforce a maximum log level. ESP_LOGx macros above this level will be skipped immediately, rather than calling esp_log_write and doing a cache hit. The tradeoff is increased application size. - Parameters level -- Master log level - esp_log_level_t esp_log_get_level_master(void) Returns master log level. - Returns Master log level - void esp_log_level_set(const char *tag, esp_log_level_t level) Set log level for given tag. If logging for given component has already been enabled, changes previous setting. Note Note that this function can not raise log level above the level set using CONFIG_LOG_MAXIMUM_LEVEL setting in menuconfig. To raise log level above the default one for a given file, define LOG_LOCAL_LEVEL to one of the ESP_LOG_* values, before including esp_log.h in this file. - Parameters tag -- Tag of the log entries to enable. Must be a non-NULL zero terminated string. Value "*" resets log level for all tags to the given value. level -- Selects log level to enable. Only logs at this and lower verbosity levels will be shown. - - esp_log_level_t esp_log_level_get(const char *tag) Get log level for a given tag, can be used to avoid expensive log statements. - Parameters tag -- Tag of the log to query current level. Must be a non-NULL zero terminated string. - Returns The current log level for the given tag - vprintf_like_t esp_log_set_vprintf(vprintf_like_t func) Set function used to output log entries. By default, log output goes to UART0. This function can be used to redirect log output to some other destination, such as file or network. Returns the original log handler, which may be necessary to return output to the previous destination. Note Please note that function callback here must be re-entrant as it can be invoked in parallel from multiple thread context. - Parameters func -- new Function used for output. Must have same signature as vprintf. - Returns func old Function used for output. - uint32_t esp_log_timestamp(void) Function which returns timestamp to be used in log output. This function is used in expansion of ESP_LOGx macros. In the 2nd stage bootloader, and at early application startup stage this function uses CPU cycle counter as time source. Later when FreeRTOS scheduler start running, it switches to FreeRTOS tick count. For now, we ignore millisecond counter overflow. - Returns timestamp, in milliseconds - char *esp_log_system_timestamp(void) Function which returns system timestamp to be used in log output. This function is used in expansion of ESP_LOGx macros to print the system time as "HH:MM:SS.sss". The system time is initialized to 0 on startup, this can be set to the correct time with an SNTP sync, or manually with standard POSIX time functions. Currently, this will not get used in logging from binary blobs (i.e. Wi-Fi & Bluetooth libraries), these will still print the RTOS tick time. - Returns timestamp, in "HH:MM:SS.sss" - uint32_t esp_log_early_timestamp(void) Function which returns timestamp to be used in log output. This function uses HW cycle counter and does not depend on OS, so it can be safely used after application crash. - Returns timestamp, in milliseconds - void esp_log_write(esp_log_level_t level, const char *tag, const char *format, ...) Write message into the log. This function is not intended to be used directly. Instead, use one of ESP_LOGE, ESP_LOGW, ESP_LOGI, ESP_LOGD, ESP_LOGV macros. This function or these macros should not be used from an interrupt. - void esp_log_writev(esp_log_level_t level, const char *tag, const char *format, va_list args) Write message into the log, va_list variant. This function is provided to ease integration toward other logging framework, so that esp_log can be used as a log sink. See also esp_log_write() Macros - ESP_LOG_BUFFER_HEX_LEVEL(tag, buffer, buff_len, level) Log a buffer of hex bytes at specified level, separated into 16 bytes each line. - Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes level -- level of the log - - ESP_LOG_BUFFER_CHAR_LEVEL(tag, buffer, buff_len, level) Log a buffer of characters at specified level, separated into 16 bytes each line. Buffer should contain only printable characters. - Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes level -- level of the log - - ESP_LOG_BUFFER_HEXDUMP(tag, buffer, buff_len, level) Dump a buffer to the log at specified level. The dump log shows just like the one below: W (195) log_example: 0x3ffb4280 45 53 50 33 32 20 69 73 20 67 72 65 61 74 2c 20 |ESP32 is great, | W (195) log_example: 0x3ffb4290 77 6f 72 6b 69 6e 67 20 61 6c 6f 6e 67 20 77 69 |working along wi| W (205) log_example: 0x3ffb42a0 74 68 20 74 68 65 20 49 44 46 2e 00 |th the IDF..| It is highly recommended to use terminals with over 102 text width. - Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes level -- level of the log - - ESP_LOG_BUFFER_HEX(tag, buffer, buff_len) Log a buffer of hex bytes at Info level. See also esp_log_buffer_hex_level - Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes - - ESP_LOG_BUFFER_CHAR(tag, buffer, buff_len) Log a buffer of characters at Info level. Buffer should contain only printable characters. See also esp_log_buffer_char_level - Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes - - ESP_EARLY_LOGE(tag, format, ...) macro to output logs in startup code, before heap allocator and syscalls have been initialized. Log at ESP_LOG_ERRORlevel. See also printf, ESP_LOGE, ESP_DRAM_LOGEIn the future, we want to become compatible with clang. Hence, we provide two versions of the following macros which are using variadic arguments. The first one is using the GNU extension ##__VA_ARGS__. The second one is using the C++20 feature VA_OPT(,). This allows users to compile their code with standard C++20 enabled instead of the GNU extension. Below C++20, we haven't found any good alternative to using ##__VA_ARGS__. - ESP_EARLY_LOGW(tag, format, ...) macro to output logs in startup code at ESP_LOG_WARNlevel. See also ESP_EARLY_LOGE, ESP_LOGE, printf - ESP_EARLY_LOGI(tag, format, ...) macro to output logs in startup code at ESP_LOG_INFOlevel. See also ESP_EARLY_LOGE, ESP_LOGE, printf - ESP_EARLY_LOGD(tag, format, ...) macro to output logs in startup code at ESP_LOG_DEBUGlevel. See also ESP_EARLY_LOGE, ESP_LOGE, printf - ESP_EARLY_LOGV(tag, format, ...) macro to output logs in startup code at ESP_LOG_VERBOSElevel. See also ESP_EARLY_LOGE, ESP_LOGE, printf - _ESP_LOG_EARLY_ENABLED(log_level) - ESP_LOG_EARLY_IMPL(tag, format, log_level, log_tag_letter, ...) - ESP_LOGE(tag, format, ...) - ESP_LOGW(tag, format, ...) - ESP_LOGI(tag, format, ...) - ESP_LOGD(tag, format, ...) - ESP_LOGV(tag, format, ...) - ESP_LOG_LEVEL(level, tag, format, ...) runtime macro to output logs at a specified level. See also printf - Parameters tag -- tag of the log, which can be used to change the log level by esp_log_level_setat runtime. level -- level of the output log. format -- format of the output log. See printf ... -- variables to be replaced into the log. See printf - - ESP_LOG_LEVEL_LOCAL(level, tag, format, ...) runtime macro to output logs at a specified level. Also check the level with LOG_LOCAL_LEVEL. If CONFIG_LOG_MASTER_LEVELset, also check first against esp_log_get_level_master(). See also printf, ESP_LOG_LEVEL - ESP_DRAM_LOGE(tag, format, ...) Macro to output logs when the cache is disabled. Log at ESP_LOG_ERRORlevel. Similar to Usage: ESP_DRAM_LOGE(DRAM_STR("my_tag"), "format", orESP_DRAM_LOGE(TAG, "format", ...)`, where TAG is a char* that points to a str in the DRAM. See also ESP_EARLY_LOGE, the log level cannot be changed per-tag, however esp_log_level_set("*", level) will set the default level which controls these log lines also. See also esp_rom_printf, ESP_LOGE Note Unlike normal logging macros, it's possible to use this macro when interrupts are disabled or inside an ISR. Note Placing log strings in DRAM reduces available DRAM, so only use when absolutely essential. - ESP_DRAM_LOGW(tag, format, ...) macro to output logs when the cache is disabled at ESP_LOG_WARNlevel. See also ESP_DRAM_LOGW, ESP_LOGW, esp_rom_printf - ESP_DRAM_LOGI(tag, format, ...) macro to output logs when the cache is disabled at ESP_LOG_INFOlevel. See also ESP_DRAM_LOGI, ESP_LOGI, esp_rom_printf - ESP_DRAM_LOGD(tag, format, ...) macro to output logs when the cache is disabled at ESP_LOG_DEBUGlevel. See also ESP_DRAM_LOGD, ESP_LOGD, esp_rom_printf - ESP_DRAM_LOGV(tag, format, ...) macro to output logs when the cache is disabled at ESP_LOG_VERBOSElevel. See also ESP_DRAM_LOGV, ESP_LOGV, esp_rom_printf Type Definitions - typedef int (*vprintf_like_t)(const char*, va_list) Enumerations - enum esp_log_level_t Log level. Values: - enumerator ESP_LOG_NONE No log output - enumerator ESP_LOG_ERROR Critical errors, software module can not recover on its own - enumerator ESP_LOG_WARN Error conditions from which recovery measures have been taken - enumerator ESP_LOG_INFO Information messages which describe normal flow of events - enumerator ESP_LOG_DEBUG Extra information which is not necessary for normal use (values, pointers, sizes, etc). - enumerator ESP_LOG_VERBOSE Bigger chunks of debugging information, or frequent messages which can potentially flood the output. - enumerator ESP_LOG_NONE
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/log.html
ESP-IDF Programming Guide v5.2.1 documentation
null
Miscellaneous System APIs
null
espressif.com
2016-01-01
e295f997a061b9c3
null
null
Miscellaneous System APIs Software Reset To perform software reset of the chip, the esp_restart() function is provided. When the function is called, execution of the program stops, both CPUs are reset, the application is loaded by the bootloader and starts execution again. Additionally, the esp_register_shutdown_handler() function can register a routine that will be automatically called before a restart (that is triggered by esp_restart() ) occurs. This is similar to the functionality of atexit POSIX function. Reset Reason ESP-IDF applications can be started or restarted due to a variety of reasons. To get the last reset reason, call esp_reset_reason() function. See description of esp_reset_reason_t for the list of possible reset reasons. Heap Memory Two heap-memory-related functions are provided: esp_get_free_heap_size() returns the current size of free heap memory. esp_get_minimum_free_heap_size() returns the minimum size of free heap memory that has ever been available (i.e., the smallest size of free heap memory in the application's lifetime). Note that ESP-IDF supports multiple heaps with different capabilities. The functions mentioned in this section return the size of heap memory that can be allocated using the malloc family of functions. For further information about heap memory, see Heap Memory Allocation. MAC Address These APIs allow querying and customizing MAC addresses for different supported network interfaces (e.g., Wi-Fi, Bluetooth, Ethernet). To fetch the MAC address for a specific network interface (e.g., Wi-Fi, Bluetooth, Ethernet), call the function esp_read_mac() . In ESP-IDF, the MAC addresses for the various network interfaces are calculated from a single base MAC address. By default, the Espressif base MAC address is used. This base MAC address is pre-programmed into the ESP32 eFuse in the factory during production. Interface MAC Address (4 universally administered, default) MAC Address (2 universally administered) Wi-Fi Station base_mac base_mac Wi-Fi SoftAP base_mac, +1 to the last octet Local MAC (derived from Wi-Fi Station MAC) Bluetooth base_mac, +2 to the last octet base_mac, +1 to the last octet Ethernet base_mac, +3 to the last octet Local MAC (derived from Bluetooth MAC) Note The configuration configures the number of universally administered MAC addresses that are provided by Espressif. Custom Interface MAC Sometimes you may need to define custom MAC addresses that are not generated from the base MAC address. To set a custom interface MAC address, use the esp_iface_mac_addr_set() function. This function allows you to overwrite the MAC addresses of interfaces set (or not yet set) by the base MAC address. Once a MAC address has been set for a particular interface, it will not be affected when the base MAC address is changed. Custom Base MAC The default base MAC is pre-programmed by Espressif in eFuse BLK0. To set a custom base MAC instead, call the function esp_iface_mac_addr_set() with the ESP_MAC_BASE argument (or esp_base_mac_addr_set() ) before initializing any network interfaces or calling the esp_read_mac() function. The custom MAC address can be stored in any supported storage device (e.g., flash, NVS). The custom base MAC addresses should be allocated such that derived MAC addresses will not overlap. Based on the table above, users can configure the option CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES to set the number of valid universal MAC addresses that can be derived from the custom base MAC. Note It is also possible to call the function esp_netif_set_mac() to set the specific MAC used by a network interface after network initialization. But it is recommended to use the base MAC approach documented here to avoid the possibility of the original MAC address briefly appearing on the network before being changed. Custom MAC Address in eFuse When reading custom MAC addresses from eFuse, ESP-IDF provides a helper function esp_efuse_mac_get_custom() . Users can also use esp_read_mac() with the ESP_MAC_EFUSE_CUSTOM argument. This loads the MAC address from eFuse BLK3. The esp_efuse_mac_get_custom() function assumes that the custom base MAC address is stored in the following format: Field # of bits Range of bits Notes Version 8 191:184 0: invalid, others — valid Reserved 128 183:56 MAC address 48 55:8 MAC address CRC 8 7:0 CRC-8-CCITT, polynomial 0x07 Note If the 3/4 coding scheme is enabled, all eFuse fields in this block must be burnt at the same time. Once custom eFuse MAC address has been obtained (using esp_efuse_mac_get_custom() or esp_read_mac() ), you need to set it as the base MAC address. There are two ways to do it: Use an old API: call esp_base_mac_addr_set() . Use a new API: call esp_iface_mac_addr_set() with the ESP_MAC_BASE argument. Local Versus Universal MAC Addresses ESP32 comes pre-programmed with enough valid Espressif universally administered MAC addresses for all internal interfaces. The table above shows how to calculate and derive the MAC address for a specific interface according to the base MAC address. When using a custom MAC address scheme, it is possible that not all interfaces can be assigned with a universally administered MAC address. In these cases, a locally administered MAC address is assigned. Note that these addresses are intended for use on a single local network only. See this article for the definition of locally and universally administered MAC addresses. Function esp_derive_local_mac() is called internally to derive a local MAC address from a universal MAC address. The process is as follows: The U/L bit (bit value 0x2) is set in the first octet of the universal MAC address, creating a local MAC address. If this bit is already set in the supplied universal MAC address (i.e., the supplied "universal" MAC address was in fact already a local MAC address), then the first octet of the local MAC address is XORed with 0x4. Chip Version esp_chip_info() function fills esp_chip_info_t structure with information about the chip. This includes the chip revision, number of CPU cores, and a bit mask of features enabled in the chip. SDK Version esp_get_idf_version() returns a string describing the ESP-IDF version which is used to compile the application. This is the same value as the one available through IDF_VER variable of the build system. The version string generally has the format of git describe output. To get the version at build time, additional version macros are provided. They can be used to enable or disable parts of the program depending on the ESP-IDF version. ESP_IDF_VERSION_MAJOR , ESP_IDF_VERSION_MINOR , ESP_IDF_VERSION_PATCH are defined to integers representing major, minor, and patch version. ESP_IDF_VERSION_VAL and ESP_IDF_VERSION can be used when implementing version checks: #include "esp_idf_version.h" #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0) // enable functionality present in ESP-IDF v4.0 #endif App Version The application version is stored in esp_app_desc_t structure. It is located in DROM sector and has a fixed offset from the beginning of the binary file. The structure is located after esp_image_header_t and esp_image_segment_header_t structures. The type of the field version is string and it has a maximum length of 32 chars. To set the version in your project manually, you need to set the PROJECT_VER variable in the CMakeLists.txt of your project. In application CMakeLists.txt , put set(PROJECT_VER "0.1.0.1") before including project.cmake . If the CONFIG_APP_PROJECT_VER_FROM_CONFIG option is set, the value of CONFIG_APP_PROJECT_VER will be used. Otherwise, if the PROJECT_VER variable is not set in the project, it will be retrieved either from the $(PROJECT_PATH)/version.txt file (if present) or using git command git describe . If neither is available, PROJECT_VER will be set to "1". Application can make use of this by calling esp_app_get_description() or esp_ota_get_partition_description() functions. API Reference Header File This header file can be included with: #include "esp_system.h" Functions esp_err_t esp_register_shutdown_handler(shutdown_handler_t handle) Register shutdown handler. This function allows you to register a handler that gets invoked before the application is restarted using esp_restart function. Parameters handle -- function to execute on restart Returns ESP_OK on success ESP_ERR_INVALID_STATE if the handler has already been registered ESP_ERR_NO_MEM if no more shutdown handler slots are available ESP_OK on success ESP_ERR_INVALID_STATE if the handler has already been registered ESP_ERR_NO_MEM if no more shutdown handler slots are available ESP_OK on success Parameters handle -- function to execute on restart Returns ESP_OK on success ESP_ERR_INVALID_STATE if the handler has already been registered ESP_ERR_NO_MEM if no more shutdown handler slots are available esp_err_t esp_unregister_shutdown_handler(shutdown_handler_t handle) Unregister shutdown handler. This function allows you to unregister a handler which was previously registered using esp_register_shutdown_handler function. ESP_OK on success ESP_ERR_INVALID_STATE if the given handler hasn't been registered before ESP_OK on success ESP_ERR_INVALID_STATE if the given handler hasn't been registered before ESP_OK on success void esp_restart(void) Restart PRO and APP CPUs. This function can be called both from PRO and APP CPUs. After successful restart, CPU reset reason will be SW_CPU_RESET. Peripherals (except for Wi-Fi, BT, UART0, SPI1, and legacy timers) are not reset. This function does not return. esp_reset_reason_t esp_reset_reason(void) Get reason of last reset. Returns See description of esp_reset_reason_t for explanation of each value. Returns See description of esp_reset_reason_t for explanation of each value. uint32_t esp_get_free_heap_size(void) Get the size of available heap. Note Note that the returned value may be larger than the maximum contiguous block which can be allocated. Returns Available heap size, in bytes. Returns Available heap size, in bytes. uint32_t esp_get_free_internal_heap_size(void) Get the size of available internal heap. Note Note that the returned value may be larger than the maximum contiguous block which can be allocated. Returns Available internal heap size, in bytes. Returns Available internal heap size, in bytes. uint32_t esp_get_minimum_free_heap_size(void) Get the minimum heap that has ever been available. Returns Minimum free heap ever available Returns Minimum free heap ever available void esp_system_abort(const char *details) Trigger a software abort. Parameters details -- Details that will be displayed during panic handling. Parameters details -- Details that will be displayed during panic handling. Type Definitions typedef void (*shutdown_handler_t)(void) Shutdown handler type Enumerations enum esp_reset_reason_t Reset reasons. Values: enumerator ESP_RST_UNKNOWN Reset reason can not be determined. enumerator ESP_RST_UNKNOWN Reset reason can not be determined. enumerator ESP_RST_POWERON Reset due to power-on event. enumerator ESP_RST_POWERON Reset due to power-on event. enumerator ESP_RST_EXT Reset by external pin (not applicable for ESP32) enumerator ESP_RST_EXT Reset by external pin (not applicable for ESP32) enumerator ESP_RST_SW Software reset via esp_restart. enumerator ESP_RST_SW Software reset via esp_restart. enumerator ESP_RST_PANIC Software reset due to exception/panic. enumerator ESP_RST_PANIC Software reset due to exception/panic. enumerator ESP_RST_INT_WDT Reset (software or hardware) due to interrupt watchdog. enumerator ESP_RST_INT_WDT Reset (software or hardware) due to interrupt watchdog. enumerator ESP_RST_TASK_WDT Reset due to task watchdog. enumerator ESP_RST_TASK_WDT Reset due to task watchdog. enumerator ESP_RST_WDT Reset due to other watchdogs. enumerator ESP_RST_WDT Reset due to other watchdogs. enumerator ESP_RST_DEEPSLEEP Reset after exiting deep sleep mode. enumerator ESP_RST_DEEPSLEEP Reset after exiting deep sleep mode. enumerator ESP_RST_BROWNOUT Brownout reset (software or hardware) enumerator ESP_RST_BROWNOUT Brownout reset (software or hardware) enumerator ESP_RST_SDIO Reset over SDIO. enumerator ESP_RST_SDIO Reset over SDIO. enumerator ESP_RST_USB Reset by USB peripheral. enumerator ESP_RST_USB Reset by USB peripheral. enumerator ESP_RST_JTAG Reset by JTAG. enumerator ESP_RST_JTAG Reset by JTAG. enumerator ESP_RST_UNKNOWN Header File This header file can be included with: #include "esp_idf_version.h" Functions const char *esp_get_idf_version(void) Return full IDF version string, same as 'git describe' output. Note If you are printing the ESP-IDF version in a log file or other information, this function provides more information than using the numerical version macros. For example, numerical version macros don't differentiate between development, pre-release and release versions, but the output of this function does. Returns constant string from IDF_VER Returns constant string from IDF_VER Macros ESP_IDF_VERSION_MAJOR Major version number (X.x.x) ESP_IDF_VERSION_MINOR Minor version number (x.X.x) ESP_IDF_VERSION_PATCH Patch version number (x.x.X) ESP_IDF_VERSION_VAL(major, minor, patch) Macro to convert IDF version number into an integer To be used in comparisons, such as ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0) ESP_IDF_VERSION Current IDF version, as an integer To be used in comparisons, such as ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0) Header File This header file can be included with: #include "esp_mac.h" Functions esp_err_t esp_base_mac_addr_set(const uint8_t *mac) Set base MAC address with the MAC address which is stored in BLK3 of EFUSE or external storage e.g. flash and EEPROM. Base MAC address is used to generate the MAC addresses used by network interfaces. If using a custom base MAC address, call this API before initializing any network interfaces. Refer to the ESP-IDF Programming Guide for details about how the Base MAC is used. Note Base MAC must be a unicast MAC (least significant bit of first byte must be zero). Note If not using a valid OUI, set the "locally administered" bit (bit value 0x02 in the first byte) to avoid collisions. Parameters mac -- base MAC address, length: 6 bytes. length: 6 bytes for MAC-48 Returns ESP_OK on success ESP_ERR_INVALID_ARG If mac is NULL or is not a unicast MAC Parameters mac -- base MAC address, length: 6 bytes. length: 6 bytes for MAC-48 Returns ESP_OK on success ESP_ERR_INVALID_ARG If mac is NULL or is not a unicast MAC esp_err_t esp_base_mac_addr_get(uint8_t *mac) Return base MAC address which is set using esp_base_mac_addr_set. Note If no custom Base MAC has been set, this returns the pre-programmed Espressif base MAC address. Parameters mac -- base MAC address, length: 6 bytes. length: 6 bytes for MAC-48 Returns ESP_OK on success ESP_ERR_INVALID_ARG mac is NULL ESP_ERR_INVALID_MAC base MAC address has not been set Parameters mac -- base MAC address, length: 6 bytes. length: 6 bytes for MAC-48 Returns ESP_OK on success ESP_ERR_INVALID_ARG mac is NULL ESP_ERR_INVALID_MAC base MAC address has not been set esp_err_t esp_efuse_mac_get_custom(uint8_t *mac) Return base MAC address which was previously written to BLK3 of EFUSE. Base MAC address is used to generate the MAC addresses used by the networking interfaces. This API returns the custom base MAC address which was previously written to EFUSE BLK3 in a specified format. Writing this EFUSE allows setting of a different (non-Espressif) base MAC address. It is also possible to store a custom base MAC address elsewhere, see esp_base_mac_addr_set() for details. Note This function is currently only supported on ESP32. Parameters mac -- base MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for IEEE 802.15.4, if CONFIG_SOC_IEEE802154_SUPPORTED=y) Returns ESP_OK on success ESP_ERR_INVALID_ARG mac is NULL ESP_ERR_INVALID_MAC CUSTOM_MAC address has not been set, all zeros (for esp32-xx) ESP_ERR_INVALID_VERSION An invalid MAC version field was read from BLK3 of EFUSE (for esp32) ESP_ERR_INVALID_CRC An invalid MAC CRC was read from BLK3 of EFUSE (for esp32) Parameters mac -- base MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for IEEE 802.15.4, if CONFIG_SOC_IEEE802154_SUPPORTED=y) Returns ESP_OK on success ESP_ERR_INVALID_ARG mac is NULL ESP_ERR_INVALID_MAC CUSTOM_MAC address has not been set, all zeros (for esp32-xx) ESP_ERR_INVALID_VERSION An invalid MAC version field was read from BLK3 of EFUSE (for esp32) ESP_ERR_INVALID_CRC An invalid MAC CRC was read from BLK3 of EFUSE (for esp32) esp_err_t esp_efuse_mac_get_default(uint8_t *mac) Return base MAC address which is factory-programmed by Espressif in EFUSE. Parameters mac -- base MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for IEEE 802.15.4, if CONFIG_SOC_IEEE802154_SUPPORTED=y) Returns ESP_OK on success ESP_ERR_INVALID_ARG mac is NULL Parameters mac -- base MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for IEEE 802.15.4, if CONFIG_SOC_IEEE802154_SUPPORTED=y) Returns ESP_OK on success ESP_ERR_INVALID_ARG mac is NULL esp_err_t esp_read_mac(uint8_t *mac, esp_mac_type_t type) Read base MAC address and set MAC address of the interface. This function first get base MAC address using esp_base_mac_addr_get(). Then calculates the MAC address of the specific interface requested, refer to ESP-IDF Programming Guide for the algorithm. The MAC address set by the esp_iface_mac_addr_set() function will not depend on the base MAC address. Parameters mac -- base MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for IEEE 802.15.4, if CONFIG_SOC_IEEE802154_SUPPORTED=y) type -- Type of MAC address to return mac -- base MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for IEEE 802.15.4, if CONFIG_SOC_IEEE802154_SUPPORTED=y) type -- Type of MAC address to return mac -- base MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for IEEE 802.15.4, if CONFIG_SOC_IEEE802154_SUPPORTED=y) Returns ESP_OK on success Parameters mac -- base MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for IEEE 802.15.4, if CONFIG_SOC_IEEE802154_SUPPORTED=y) type -- Type of MAC address to return Returns ESP_OK on success esp_err_t esp_derive_local_mac(uint8_t *local_mac, const uint8_t *universal_mac) Derive local MAC address from universal MAC address. This function copies a universal MAC address and then sets the "locally administered" bit (bit 0x2) in the first octet, creating a locally administered MAC address. If the universal MAC address argument is already a locally administered MAC address, then the first octet is XORed with 0x4 in order to create a different locally administered MAC address. Parameters local_mac -- base MAC address, length: 6 bytes. length: 6 bytes for MAC-48 universal_mac -- Source universal MAC address, length: 6 bytes. local_mac -- base MAC address, length: 6 bytes. length: 6 bytes for MAC-48 universal_mac -- Source universal MAC address, length: 6 bytes. local_mac -- base MAC address, length: 6 bytes. length: 6 bytes for MAC-48 Returns ESP_OK on success Parameters local_mac -- base MAC address, length: 6 bytes. length: 6 bytes for MAC-48 universal_mac -- Source universal MAC address, length: 6 bytes. Returns ESP_OK on success esp_err_t esp_iface_mac_addr_set(const uint8_t *mac, esp_mac_type_t type) Set custom MAC address of the interface. This function allows you to overwrite the MAC addresses of the interfaces set by the base MAC address. Parameters mac -- MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for ESP_MAC_IEEE802154 type, if CONFIG_SOC_IEEE802154_SUPPORTED=y) type -- Type of MAC address mac -- MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for ESP_MAC_IEEE802154 type, if CONFIG_SOC_IEEE802154_SUPPORTED=y) type -- Type of MAC address mac -- MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for ESP_MAC_IEEE802154 type, if CONFIG_SOC_IEEE802154_SUPPORTED=y) Returns ESP_OK on success Parameters mac -- MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for ESP_MAC_IEEE802154 type, if CONFIG_SOC_IEEE802154_SUPPORTED=y) type -- Type of MAC address Returns ESP_OK on success size_t esp_mac_addr_len_get(esp_mac_type_t type) Return the size of the MAC type in bytes. If CONFIG_SOC_IEEE802154_SUPPORTED is set then for these types: ESP_MAC_IEEE802154 is 8 bytes. ESP_MAC_BASE, ESP_MAC_EFUSE_FACTORY and ESP_MAC_EFUSE_CUSTOM the MAC size is 6 bytes. ESP_MAC_EFUSE_EXT is 2 bytes. If CONFIG_SOC_IEEE802154_SUPPORTED is not set then for all types it returns 6 bytes. ESP_MAC_IEEE802154 is 8 bytes. ESP_MAC_BASE, ESP_MAC_EFUSE_FACTORY and ESP_MAC_EFUSE_CUSTOM the MAC size is 6 bytes. ESP_MAC_EFUSE_EXT is 2 bytes. If CONFIG_SOC_IEEE802154_SUPPORTED is not set then for all types it returns 6 bytes. Parameters type -- Type of MAC address Returns 0 MAC type not found (not supported) 6 bytes for MAC-48. 8 bytes for EUI-64. Parameters type -- Type of MAC address Returns 0 MAC type not found (not supported) 6 bytes for MAC-48. 8 bytes for EUI-64. ESP_MAC_IEEE802154 is 8 bytes. Macros MAC2STR(a) MACSTR Enumerations enum esp_mac_type_t Values: enumerator ESP_MAC_WIFI_STA MAC for WiFi Station (6 bytes) enumerator ESP_MAC_WIFI_STA MAC for WiFi Station (6 bytes) enumerator ESP_MAC_WIFI_SOFTAP MAC for WiFi Soft-AP (6 bytes) enumerator ESP_MAC_WIFI_SOFTAP MAC for WiFi Soft-AP (6 bytes) enumerator ESP_MAC_BT MAC for Bluetooth (6 bytes) enumerator ESP_MAC_BT MAC for Bluetooth (6 bytes) enumerator ESP_MAC_ETH MAC for Ethernet (6 bytes) enumerator ESP_MAC_ETH MAC for Ethernet (6 bytes) enumerator ESP_MAC_IEEE802154 if CONFIG_SOC_IEEE802154_SUPPORTED=y, MAC for IEEE802154 (8 bytes) enumerator ESP_MAC_IEEE802154 if CONFIG_SOC_IEEE802154_SUPPORTED=y, MAC for IEEE802154 (8 bytes) enumerator ESP_MAC_BASE Base MAC for that used for other MAC types (6 bytes) enumerator ESP_MAC_BASE Base MAC for that used for other MAC types (6 bytes) enumerator ESP_MAC_EFUSE_FACTORY MAC_FACTORY eFuse which was burned by Espressif in production (6 bytes) enumerator ESP_MAC_EFUSE_FACTORY MAC_FACTORY eFuse which was burned by Espressif in production (6 bytes) enumerator ESP_MAC_EFUSE_CUSTOM MAC_CUSTOM eFuse which was can be burned by customer (6 bytes) enumerator ESP_MAC_EFUSE_CUSTOM MAC_CUSTOM eFuse which was can be burned by customer (6 bytes) enumerator ESP_MAC_EFUSE_EXT if CONFIG_SOC_IEEE802154_SUPPORTED=y, MAC_EXT eFuse which is used as an extender for IEEE802154 MAC (2 bytes) enumerator ESP_MAC_EFUSE_EXT if CONFIG_SOC_IEEE802154_SUPPORTED=y, MAC_EXT eFuse which is used as an extender for IEEE802154 MAC (2 bytes) enumerator ESP_MAC_WIFI_STA Header File This header file can be included with: #include "esp_chip_info.h" Functions void esp_chip_info(esp_chip_info_t *out_info) Fill an esp_chip_info_t structure with information about the chip. Parameters out_info -- [out] structure to be filled Parameters out_info -- [out] structure to be filled Structures struct esp_chip_info_t The structure represents information about the chip. Public Members esp_chip_model_t model chip model, one of esp_chip_model_t esp_chip_model_t model chip model, one of esp_chip_model_t uint32_t features bit mask of CHIP_FEATURE_x feature flags uint32_t features bit mask of CHIP_FEATURE_x feature flags uint16_t revision chip revision number (in format MXX; where M - wafer major version, XX - wafer minor version) uint16_t revision chip revision number (in format MXX; where M - wafer major version, XX - wafer minor version) uint8_t cores number of CPU cores uint8_t cores number of CPU cores esp_chip_model_t model Macros CHIP_FEATURE_EMB_FLASH Chip has embedded flash memory. CHIP_FEATURE_WIFI_BGN Chip has 2.4GHz WiFi. CHIP_FEATURE_BLE Chip has Bluetooth LE. CHIP_FEATURE_BT Chip has Bluetooth Classic. CHIP_FEATURE_IEEE802154 Chip has IEEE 802.15.4. CHIP_FEATURE_EMB_PSRAM Chip has embedded psram. Enumerations enum esp_chip_model_t Chip models. Values: enumerator CHIP_ESP32 ESP32. enumerator CHIP_ESP32 ESP32. enumerator CHIP_ESP32S2 ESP32-S2. enumerator CHIP_ESP32S2 ESP32-S2. enumerator CHIP_ESP32S3 ESP32-S3. enumerator CHIP_ESP32S3 ESP32-S3. enumerator CHIP_ESP32C3 ESP32-C3. enumerator CHIP_ESP32C3 ESP32-C3. enumerator CHIP_ESP32C2 ESP32-C2. enumerator CHIP_ESP32C2 ESP32-C2. enumerator CHIP_ESP32C6 ESP32-C6. enumerator CHIP_ESP32C6 ESP32-C6. enumerator CHIP_ESP32H2 ESP32-H2. enumerator CHIP_ESP32H2 ESP32-H2. enumerator CHIP_ESP32P4 ESP32-P4. enumerator CHIP_ESP32P4 ESP32-P4. enumerator CHIP_POSIX_LINUX The code is running on POSIX/Linux simulator. enumerator CHIP_POSIX_LINUX The code is running on POSIX/Linux simulator. enumerator CHIP_ESP32 Header File This header file can be included with: #include "esp_cpu.h" Functions void esp_cpu_stall(int core_id) Stall a CPU core. Parameters core_id -- The core's ID Parameters core_id -- The core's ID void esp_cpu_unstall(int core_id) Resume a previously stalled CPU core. Parameters core_id -- The core's ID Parameters core_id -- The core's ID void esp_cpu_reset(int core_id) Reset a CPU core. Parameters core_id -- The core's ID Parameters core_id -- The core's ID void esp_cpu_wait_for_intr(void) Wait for Interrupt. This function causes the current CPU core to execute its Wait For Interrupt (WFI or equivalent) instruction. After executing this function, the CPU core will stop execution until an interrupt occurs. int esp_cpu_get_core_id(void) Get the current core's ID. This function will return the ID of the current CPU (i.e., the CPU that calls this function). Returns The current core's ID [0..SOC_CPU_CORES_NUM - 1] Returns The current core's ID [0..SOC_CPU_CORES_NUM - 1] void *esp_cpu_get_sp(void) Read the current stack pointer address. Returns Stack pointer address Returns Stack pointer address esp_cpu_cycle_count_t esp_cpu_get_cycle_count(void) Get the current CPU core's cycle count. Each CPU core maintains an internal counter (i.e., cycle count) that increments every CPU clock cycle. Returns Current CPU's cycle count, 0 if not supported. Returns Current CPU's cycle count, 0 if not supported. void esp_cpu_set_cycle_count(esp_cpu_cycle_count_t cycle_count) Set the current CPU core's cycle count. Set the given value into the internal counter that increments every CPU clock cycle. Parameters cycle_count -- CPU cycle count Parameters cycle_count -- CPU cycle count void *esp_cpu_pc_to_addr(uint32_t pc) Convert a program counter (PC) value to address. If the architecture does not store the true virtual address in the CPU's PC or return addresses, this function will convert the PC value to a virtual address. Otherwise, the PC is just returned Parameters pc -- PC value Returns Virtual address Parameters pc -- PC value Returns Virtual address void esp_cpu_intr_get_desc(int core_id, int intr_num, esp_cpu_intr_desc_t *intr_desc_ret) Get a CPU interrupt's descriptor. Each CPU interrupt has a descriptor describing the interrupt's capabilities and restrictions. This function gets the descriptor of a particular interrupt on a particular CPU. Parameters core_id -- [in] The core's ID intr_num -- [in] Interrupt number intr_desc_ret -- [out] The interrupt's descriptor core_id -- [in] The core's ID intr_num -- [in] Interrupt number intr_desc_ret -- [out] The interrupt's descriptor core_id -- [in] The core's ID Parameters core_id -- [in] The core's ID intr_num -- [in] Interrupt number intr_desc_ret -- [out] The interrupt's descriptor void esp_cpu_intr_set_ivt_addr(const void *ivt_addr) Set the base address of the current CPU's Interrupt Vector Table (IVT) Parameters ivt_addr -- Interrupt Vector Table's base address Parameters ivt_addr -- Interrupt Vector Table's base address bool esp_cpu_intr_has_handler(int intr_num) Check if a particular interrupt already has a handler function. Check if a particular interrupt on the current CPU already has a handler function assigned. Note This function simply checks if the IVT of the current CPU already has a handler assigned. Parameters intr_num -- Interrupt number (from 0 to 31) Returns True if the interrupt has a handler function, false otherwise. Parameters intr_num -- Interrupt number (from 0 to 31) Returns True if the interrupt has a handler function, false otherwise. void esp_cpu_intr_set_handler(int intr_num, esp_cpu_intr_handler_t handler, void *handler_arg) Set the handler function of a particular interrupt. Assign a handler function (i.e., ISR) to a particular interrupt on the current CPU. Note This function simply sets the handler function (in the IVT) and does not actually enable the interrupt. Parameters intr_num -- Interrupt number (from 0 to 31) handler -- Handler function handler_arg -- Argument passed to the handler function intr_num -- Interrupt number (from 0 to 31) handler -- Handler function handler_arg -- Argument passed to the handler function intr_num -- Interrupt number (from 0 to 31) Parameters intr_num -- Interrupt number (from 0 to 31) handler -- Handler function handler_arg -- Argument passed to the handler function void *esp_cpu_intr_get_handler_arg(int intr_num) Get a handler function's argument of. Get the argument of a previously assigned handler function on the current CPU. Parameters intr_num -- Interrupt number (from 0 to 31) Returns The the argument passed to the handler function Parameters intr_num -- Interrupt number (from 0 to 31) Returns The the argument passed to the handler function void esp_cpu_intr_enable(uint32_t intr_mask) Enable particular interrupts on the current CPU. Parameters intr_mask -- Bit mask of the interrupts to enable Parameters intr_mask -- Bit mask of the interrupts to enable void esp_cpu_intr_disable(uint32_t intr_mask) Disable particular interrupts on the current CPU. Parameters intr_mask -- Bit mask of the interrupts to disable Parameters intr_mask -- Bit mask of the interrupts to disable uint32_t esp_cpu_intr_get_enabled_mask(void) Get the enabled interrupts on the current CPU. Returns Bit mask of the enabled interrupts Returns Bit mask of the enabled interrupts void esp_cpu_intr_edge_ack(int intr_num) Acknowledge an edge interrupt. Parameters intr_num -- Interrupt number (from 0 to 31) Parameters intr_num -- Interrupt number (from 0 to 31) void esp_cpu_configure_region_protection(void) Configure the CPU to disable access to invalid memory regions. esp_err_t esp_cpu_set_breakpoint(int bp_num, const void *bp_addr) Set and enable a hardware breakpoint on the current CPU. Note This function is meant to be called by the panic handler to set a breakpoint for an attached debugger during a panic. Note Overwrites previously set breakpoint with same breakpoint number. Parameters bp_num -- Hardware breakpoint number [0..SOC_CPU_BREAKPOINTS_NUM - 1] bp_addr -- Address to set a breakpoint on bp_num -- Hardware breakpoint number [0..SOC_CPU_BREAKPOINTS_NUM - 1] bp_addr -- Address to set a breakpoint on bp_num -- Hardware breakpoint number [0..SOC_CPU_BREAKPOINTS_NUM - 1] Returns ESP_OK if breakpoint is set. Failure otherwise Parameters bp_num -- Hardware breakpoint number [0..SOC_CPU_BREAKPOINTS_NUM - 1] bp_addr -- Address to set a breakpoint on Returns ESP_OK if breakpoint is set. Failure otherwise esp_err_t esp_cpu_clear_breakpoint(int bp_num) Clear a hardware breakpoint on the current CPU. Note Clears a breakpoint regardless of whether it was previously set Parameters bp_num -- Hardware breakpoint number [0..SOC_CPU_BREAKPOINTS_NUM - 1] Returns ESP_OK if breakpoint is cleared. Failure otherwise Parameters bp_num -- Hardware breakpoint number [0..SOC_CPU_BREAKPOINTS_NUM - 1] Returns ESP_OK if breakpoint is cleared. Failure otherwise esp_err_t esp_cpu_set_watchpoint(int wp_num, const void *wp_addr, size_t size, esp_cpu_watchpoint_trigger_t trigger) Set and enable a hardware watchpoint on the current CPU. Set and enable a hardware watchpoint on the current CPU, specifying the memory range and trigger operation. Watchpoints will break/panic the CPU when the CPU accesses (according to the trigger type) on a certain memory range. Note Overwrites previously set watchpoint with same watchpoint number. On RISC-V chips, this API uses method0(Exact matching) and method1(NAPOT matching) according to the riscv-debug-spec-0.13 specification for address matching. If the watch region size is 1byte, it uses exact matching (method 0). If the watch region size is larger than 1byte, it uses NAPOT matching (method 1). This mode requires the watching region start address to be aligned to the watching region size. Parameters wp_num -- Hardware watchpoint number [0..SOC_CPU_WATCHPOINTS_NUM - 1] wp_addr -- Watchpoint's base address, must be naturally aligned to the size of the region size -- Size of the region to watch. Must be one of 2^n and in the range of [1 ... SOC_CPU_WATCHPOINT_MAX_REGION_SIZE] trigger -- Trigger type wp_num -- Hardware watchpoint number [0..SOC_CPU_WATCHPOINTS_NUM - 1] wp_addr -- Watchpoint's base address, must be naturally aligned to the size of the region size -- Size of the region to watch. Must be one of 2^n and in the range of [1 ... SOC_CPU_WATCHPOINT_MAX_REGION_SIZE] trigger -- Trigger type wp_num -- Hardware watchpoint number [0..SOC_CPU_WATCHPOINTS_NUM - 1] Returns ESP_ERR_INVALID_ARG on invalid arg, ESP_OK otherwise Parameters wp_num -- Hardware watchpoint number [0..SOC_CPU_WATCHPOINTS_NUM - 1] wp_addr -- Watchpoint's base address, must be naturally aligned to the size of the region size -- Size of the region to watch. Must be one of 2^n and in the range of [1 ... SOC_CPU_WATCHPOINT_MAX_REGION_SIZE] trigger -- Trigger type Returns ESP_ERR_INVALID_ARG on invalid arg, ESP_OK otherwise esp_err_t esp_cpu_clear_watchpoint(int wp_num) Clear a hardware watchpoint on the current CPU. Note Clears a watchpoint regardless of whether it was previously set Parameters wp_num -- Hardware watchpoint number [0..SOC_CPU_WATCHPOINTS_NUM - 1] Returns ESP_OK if watchpoint was cleared. Failure otherwise. Parameters wp_num -- Hardware watchpoint number [0..SOC_CPU_WATCHPOINTS_NUM - 1] Returns ESP_OK if watchpoint was cleared. Failure otherwise. bool esp_cpu_dbgr_is_attached(void) Check if the current CPU has a debugger attached. Returns True if debugger is attached, false otherwise Returns True if debugger is attached, false otherwise void esp_cpu_dbgr_break(void) Trigger a call to the current CPU's attached debugger. intptr_t esp_cpu_get_call_addr(intptr_t return_address) Given the return address, calculate the address of the preceding call instruction This is typically used to answer the question "where was the function called from?". Parameters return_address -- The value of the return address register. Typically set to the value of __builtin_return_address(0). Returns Address of the call instruction preceding the return address. Parameters return_address -- The value of the return address register. Typically set to the value of __builtin_return_address(0). Returns Address of the call instruction preceding the return address. bool esp_cpu_compare_and_set(volatile uint32_t *addr, uint32_t compare_value, uint32_t new_value) Atomic compare-and-set operation. Parameters addr -- Address of atomic variable compare_value -- Value to compare the atomic variable to new_value -- New value to set the atomic variable to addr -- Address of atomic variable compare_value -- Value to compare the atomic variable to new_value -- New value to set the atomic variable to addr -- Address of atomic variable Returns Whether the atomic variable was set or not Parameters addr -- Address of atomic variable compare_value -- Value to compare the atomic variable to new_value -- New value to set the atomic variable to Returns Whether the atomic variable was set or not Structures struct esp_cpu_intr_desc_t CPU interrupt descriptor. Each particular CPU interrupt has an associated descriptor describing that particular interrupt's characteristics. Call esp_cpu_intr_get_desc() to get the descriptors of a particular interrupt. Public Members int priority Priority of the interrupt if it has a fixed priority, (-1) if the priority is configurable. int priority Priority of the interrupt if it has a fixed priority, (-1) if the priority is configurable. esp_cpu_intr_type_t type Whether the interrupt is an edge or level type interrupt, ESP_CPU_INTR_TYPE_NA if the type is configurable. esp_cpu_intr_type_t type Whether the interrupt is an edge or level type interrupt, ESP_CPU_INTR_TYPE_NA if the type is configurable. uint32_t flags Flags indicating extra details. uint32_t flags Flags indicating extra details. int priority Macros ESP_CPU_INTR_DESC_FLAG_SPECIAL Interrupt descriptor flags of esp_cpu_intr_desc_t. The interrupt is a special interrupt (e.g., a CPU timer interrupt) ESP_CPU_INTR_DESC_FLAG_RESVD The interrupt is reserved for internal use Type Definitions typedef uint32_t esp_cpu_cycle_count_t CPU cycle count type. This data type represents the CPU's clock cycle count typedef void (*esp_cpu_intr_handler_t)(void *arg) CPU interrupt handler type. Enumerations enum esp_cpu_intr_type_t CPU interrupt type. Values: enumerator ESP_CPU_INTR_TYPE_LEVEL enumerator ESP_CPU_INTR_TYPE_LEVEL enumerator ESP_CPU_INTR_TYPE_EDGE enumerator ESP_CPU_INTR_TYPE_EDGE enumerator ESP_CPU_INTR_TYPE_NA enumerator ESP_CPU_INTR_TYPE_NA enumerator ESP_CPU_INTR_TYPE_LEVEL Header File This header file can be included with: #include "esp_app_desc.h" This header file is a part of the API provided by the esp_app_format component. To declare that your component depends on esp_app_format , add the following to your CMakeLists.txt: REQUIRES esp_app_format or PRIV_REQUIRES esp_app_format Functions const esp_app_desc_t *esp_app_get_description(void) Return esp_app_desc structure. This structure includes app version. Return description for running app. Returns Pointer to esp_app_desc structure. Returns Pointer to esp_app_desc structure. int esp_app_get_elf_sha256(char *dst, size_t size) Fill the provided buffer with SHA256 of the ELF file, formatted as hexadecimal, null-terminated. If the buffer size is not sufficient to fit the entire SHA256 in hex plus a null terminator, the largest possible number of bytes will be written followed by a null. Parameters dst -- Destination buffer size -- Size of the buffer dst -- Destination buffer size -- Size of the buffer dst -- Destination buffer Returns Number of bytes written to dst (including null terminator) Parameters dst -- Destination buffer size -- Size of the buffer Returns Number of bytes written to dst (including null terminator) char *esp_app_get_elf_sha256_str(void) Return SHA256 of the ELF file which is already formatted as hexadecimal, null-terminated included. Can be used in panic handler or core dump during when cache is disabled. The length is defined by CONFIG_APP_RETRIEVE_LEN_ELF_SHA option. Returns Hexadecimal SHA256 string Returns Hexadecimal SHA256 string Structures struct esp_app_desc_t Description about application. Public Members uint32_t magic_word Magic word ESP_APP_DESC_MAGIC_WORD uint32_t magic_word Magic word ESP_APP_DESC_MAGIC_WORD uint32_t secure_version Secure version uint32_t secure_version Secure version uint32_t reserv1[2] reserv1 uint32_t reserv1[2] reserv1 char version[32] Application version char version[32] Application version char project_name[32] Project name char project_name[32] Project name char time[16] Compile time char time[16] Compile time char date[16] Compile date char date[16] Compile date char idf_ver[32] Version IDF char idf_ver[32] Version IDF uint8_t app_elf_sha256[32] sha256 of elf file uint8_t app_elf_sha256[32] sha256 of elf file uint32_t reserv2[20] reserv2 uint32_t reserv2[20] reserv2 uint32_t magic_word Macros ESP_APP_DESC_MAGIC_WORD The magic word for the esp_app_desc structure that is in DROM.
Miscellaneous System APIs Software Reset To perform software reset of the chip, the esp_restart() function is provided. When the function is called, execution of the program stops, both CPUs are reset, the application is loaded by the bootloader and starts execution again. Additionally, the esp_register_shutdown_handler() function can register a routine that will be automatically called before a restart (that is triggered by esp_restart()) occurs. This is similar to the functionality of atexit POSIX function. Reset Reason ESP-IDF applications can be started or restarted due to a variety of reasons. To get the last reset reason, call esp_reset_reason() function. See description of esp_reset_reason_t for the list of possible reset reasons. Heap Memory Two heap-memory-related functions are provided: esp_get_free_heap_size()returns the current size of free heap memory. esp_get_minimum_free_heap_size()returns the minimum size of free heap memory that has ever been available (i.e., the smallest size of free heap memory in the application's lifetime). Note that ESP-IDF supports multiple heaps with different capabilities. The functions mentioned in this section return the size of heap memory that can be allocated using the malloc family of functions. For further information about heap memory, see Heap Memory Allocation. MAC Address These APIs allow querying and customizing MAC addresses for different supported network interfaces (e.g., Wi-Fi, Bluetooth, Ethernet). To fetch the MAC address for a specific network interface (e.g., Wi-Fi, Bluetooth, Ethernet), call the function esp_read_mac(). In ESP-IDF, the MAC addresses for the various network interfaces are calculated from a single base MAC address. By default, the Espressif base MAC address is used. This base MAC address is pre-programmed into the ESP32 eFuse in the factory during production. | Interface | MAC Address (4 universally administered, default) | MAC Address (2 universally administered) | Wi-Fi Station | base_mac | base_mac | Wi-Fi SoftAP | base_mac, +1 to the last octet | Local MAC (derived from Wi-Fi Station MAC) | Bluetooth | base_mac, +2 to the last octet | base_mac, +1 to the last octet | Ethernet | base_mac, +3 to the last octet | Local MAC (derived from Bluetooth MAC) Note The configuration configures the number of universally administered MAC addresses that are provided by Espressif. Custom Interface MAC Sometimes you may need to define custom MAC addresses that are not generated from the base MAC address. To set a custom interface MAC address, use the esp_iface_mac_addr_set() function. This function allows you to overwrite the MAC addresses of interfaces set (or not yet set) by the base MAC address. Once a MAC address has been set for a particular interface, it will not be affected when the base MAC address is changed. Custom Base MAC The default base MAC is pre-programmed by Espressif in eFuse BLK0. To set a custom base MAC instead, call the function esp_iface_mac_addr_set() with the ESP_MAC_BASE argument (or esp_base_mac_addr_set()) before initializing any network interfaces or calling the esp_read_mac() function. The custom MAC address can be stored in any supported storage device (e.g., flash, NVS). The custom base MAC addresses should be allocated such that derived MAC addresses will not overlap. Based on the table above, users can configure the option CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES to set the number of valid universal MAC addresses that can be derived from the custom base MAC. Note It is also possible to call the function esp_netif_set_mac() to set the specific MAC used by a network interface after network initialization. But it is recommended to use the base MAC approach documented here to avoid the possibility of the original MAC address briefly appearing on the network before being changed. Custom MAC Address in eFuse When reading custom MAC addresses from eFuse, ESP-IDF provides a helper function esp_efuse_mac_get_custom(). Users can also use esp_read_mac() with the ESP_MAC_EFUSE_CUSTOM argument. This loads the MAC address from eFuse BLK3. The esp_efuse_mac_get_custom() function assumes that the custom base MAC address is stored in the following format: | Field | # of bits | Range of bits | Notes | Version | 8 | 191:184 | 0: invalid, others — valid | Reserved | 128 | 183:56 | MAC address | 48 | 55:8 | MAC address CRC | 8 | 7:0 | CRC-8-CCITT, polynomial 0x07 Note If the 3/4 coding scheme is enabled, all eFuse fields in this block must be burnt at the same time. Once custom eFuse MAC address has been obtained (using esp_efuse_mac_get_custom() or esp_read_mac()), you need to set it as the base MAC address. There are two ways to do it: Use an old API: call esp_base_mac_addr_set(). Use a new API: call esp_iface_mac_addr_set()with the ESP_MAC_BASEargument. Local Versus Universal MAC Addresses ESP32 comes pre-programmed with enough valid Espressif universally administered MAC addresses for all internal interfaces. The table above shows how to calculate and derive the MAC address for a specific interface according to the base MAC address. When using a custom MAC address scheme, it is possible that not all interfaces can be assigned with a universally administered MAC address. In these cases, a locally administered MAC address is assigned. Note that these addresses are intended for use on a single local network only. See this article for the definition of locally and universally administered MAC addresses. Function esp_derive_local_mac() is called internally to derive a local MAC address from a universal MAC address. The process is as follows: The U/L bit (bit value 0x2) is set in the first octet of the universal MAC address, creating a local MAC address. If this bit is already set in the supplied universal MAC address (i.e., the supplied "universal" MAC address was in fact already a local MAC address), then the first octet of the local MAC address is XORed with 0x4. Chip Version esp_chip_info() function fills esp_chip_info_t structure with information about the chip. This includes the chip revision, number of CPU cores, and a bit mask of features enabled in the chip. SDK Version esp_get_idf_version() returns a string describing the ESP-IDF version which is used to compile the application. This is the same value as the one available through IDF_VER variable of the build system. The version string generally has the format of git describe output. To get the version at build time, additional version macros are provided. They can be used to enable or disable parts of the program depending on the ESP-IDF version. ESP_IDF_VERSION_MAJOR, ESP_IDF_VERSION_MINOR, ESP_IDF_VERSION_PATCHare defined to integers representing major, minor, and patch version. ESP_IDF_VERSION_VALand ESP_IDF_VERSIONcan be used when implementing version checks: #include "esp_idf_version.h" #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0) // enable functionality present in ESP-IDF v4.0 #endif App Version The application version is stored in esp_app_desc_t structure. It is located in DROM sector and has a fixed offset from the beginning of the binary file. The structure is located after esp_image_header_t and esp_image_segment_header_t structures. The type of the field version is string and it has a maximum length of 32 chars. To set the version in your project manually, you need to set the PROJECT_VER variable in the CMakeLists.txt of your project. In application CMakeLists.txt, put set(PROJECT_VER "0.1.0.1") before including project.cmake. If the CONFIG_APP_PROJECT_VER_FROM_CONFIG option is set, the value of CONFIG_APP_PROJECT_VER will be used. Otherwise, if the PROJECT_VER variable is not set in the project, it will be retrieved either from the $(PROJECT_PATH)/version.txt file (if present) or using git command git describe. If neither is available, PROJECT_VER will be set to "1". Application can make use of this by calling esp_app_get_description() or esp_ota_get_partition_description() functions. API Reference Header File This header file can be included with: #include "esp_system.h" Functions - esp_err_t esp_register_shutdown_handler(shutdown_handler_t handle) Register shutdown handler. This function allows you to register a handler that gets invoked before the application is restarted using esp_restart function. - Parameters handle -- function to execute on restart - Returns ESP_OK on success ESP_ERR_INVALID_STATE if the handler has already been registered ESP_ERR_NO_MEM if no more shutdown handler slots are available - - esp_err_t esp_unregister_shutdown_handler(shutdown_handler_t handle) Unregister shutdown handler. This function allows you to unregister a handler which was previously registered using esp_register_shutdown_handler function. ESP_OK on success ESP_ERR_INVALID_STATE if the given handler hasn't been registered before - - void esp_restart(void) Restart PRO and APP CPUs. This function can be called both from PRO and APP CPUs. After successful restart, CPU reset reason will be SW_CPU_RESET. Peripherals (except for Wi-Fi, BT, UART0, SPI1, and legacy timers) are not reset. This function does not return. - esp_reset_reason_t esp_reset_reason(void) Get reason of last reset. - Returns See description of esp_reset_reason_t for explanation of each value. - uint32_t esp_get_free_heap_size(void) Get the size of available heap. Note Note that the returned value may be larger than the maximum contiguous block which can be allocated. - Returns Available heap size, in bytes. - uint32_t esp_get_free_internal_heap_size(void) Get the size of available internal heap. Note Note that the returned value may be larger than the maximum contiguous block which can be allocated. - Returns Available internal heap size, in bytes. - uint32_t esp_get_minimum_free_heap_size(void) Get the minimum heap that has ever been available. - Returns Minimum free heap ever available - void esp_system_abort(const char *details) Trigger a software abort. - Parameters details -- Details that will be displayed during panic handling. Type Definitions - typedef void (*shutdown_handler_t)(void) Shutdown handler type Enumerations - enum esp_reset_reason_t Reset reasons. Values: - enumerator ESP_RST_UNKNOWN Reset reason can not be determined. - enumerator ESP_RST_POWERON Reset due to power-on event. - enumerator ESP_RST_EXT Reset by external pin (not applicable for ESP32) - enumerator ESP_RST_SW Software reset via esp_restart. - enumerator ESP_RST_PANIC Software reset due to exception/panic. - enumerator ESP_RST_INT_WDT Reset (software or hardware) due to interrupt watchdog. - enumerator ESP_RST_TASK_WDT Reset due to task watchdog. - enumerator ESP_RST_WDT Reset due to other watchdogs. - enumerator ESP_RST_DEEPSLEEP Reset after exiting deep sleep mode. - enumerator ESP_RST_BROWNOUT Brownout reset (software or hardware) - enumerator ESP_RST_SDIO Reset over SDIO. - enumerator ESP_RST_USB Reset by USB peripheral. - enumerator ESP_RST_JTAG Reset by JTAG. - enumerator ESP_RST_UNKNOWN Header File This header file can be included with: #include "esp_idf_version.h" Functions - const char *esp_get_idf_version(void) Return full IDF version string, same as 'git describe' output. Note If you are printing the ESP-IDF version in a log file or other information, this function provides more information than using the numerical version macros. For example, numerical version macros don't differentiate between development, pre-release and release versions, but the output of this function does. - Returns constant string from IDF_VER Macros - ESP_IDF_VERSION_MAJOR Major version number (X.x.x) - ESP_IDF_VERSION_MINOR Minor version number (x.X.x) - ESP_IDF_VERSION_PATCH Patch version number (x.x.X) - ESP_IDF_VERSION_VAL(major, minor, patch) Macro to convert IDF version number into an integer To be used in comparisons, such as ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0) - ESP_IDF_VERSION Current IDF version, as an integer To be used in comparisons, such as ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0) Header File This header file can be included with: #include "esp_mac.h" Functions - esp_err_t esp_base_mac_addr_set(const uint8_t *mac) Set base MAC address with the MAC address which is stored in BLK3 of EFUSE or external storage e.g. flash and EEPROM. Base MAC address is used to generate the MAC addresses used by network interfaces. If using a custom base MAC address, call this API before initializing any network interfaces. Refer to the ESP-IDF Programming Guide for details about how the Base MAC is used. Note Base MAC must be a unicast MAC (least significant bit of first byte must be zero). Note If not using a valid OUI, set the "locally administered" bit (bit value 0x02 in the first byte) to avoid collisions. - Parameters mac -- base MAC address, length: 6 bytes. length: 6 bytes for MAC-48 - Returns ESP_OK on success ESP_ERR_INVALID_ARG If mac is NULL or is not a unicast MAC - esp_err_t esp_base_mac_addr_get(uint8_t *mac) Return base MAC address which is set using esp_base_mac_addr_set. Note If no custom Base MAC has been set, this returns the pre-programmed Espressif base MAC address. - Parameters mac -- base MAC address, length: 6 bytes. length: 6 bytes for MAC-48 - Returns ESP_OK on success ESP_ERR_INVALID_ARG mac is NULL ESP_ERR_INVALID_MAC base MAC address has not been set - esp_err_t esp_efuse_mac_get_custom(uint8_t *mac) Return base MAC address which was previously written to BLK3 of EFUSE. Base MAC address is used to generate the MAC addresses used by the networking interfaces. This API returns the custom base MAC address which was previously written to EFUSE BLK3 in a specified format. Writing this EFUSE allows setting of a different (non-Espressif) base MAC address. It is also possible to store a custom base MAC address elsewhere, see esp_base_mac_addr_set() for details. Note This function is currently only supported on ESP32. - Parameters mac -- base MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for IEEE 802.15.4, if CONFIG_SOC_IEEE802154_SUPPORTED=y) - Returns ESP_OK on success ESP_ERR_INVALID_ARG mac is NULL ESP_ERR_INVALID_MAC CUSTOM_MAC address has not been set, all zeros (for esp32-xx) ESP_ERR_INVALID_VERSION An invalid MAC version field was read from BLK3 of EFUSE (for esp32) ESP_ERR_INVALID_CRC An invalid MAC CRC was read from BLK3 of EFUSE (for esp32) - esp_err_t esp_efuse_mac_get_default(uint8_t *mac) Return base MAC address which is factory-programmed by Espressif in EFUSE. - Parameters mac -- base MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for IEEE 802.15.4, if CONFIG_SOC_IEEE802154_SUPPORTED=y) - Returns ESP_OK on success ESP_ERR_INVALID_ARG mac is NULL - esp_err_t esp_read_mac(uint8_t *mac, esp_mac_type_t type) Read base MAC address and set MAC address of the interface. This function first get base MAC address using esp_base_mac_addr_get(). Then calculates the MAC address of the specific interface requested, refer to ESP-IDF Programming Guide for the algorithm. The MAC address set by the esp_iface_mac_addr_set() function will not depend on the base MAC address. - Parameters mac -- base MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for IEEE 802.15.4, if CONFIG_SOC_IEEE802154_SUPPORTED=y) type -- Type of MAC address to return - - Returns ESP_OK on success - esp_err_t esp_derive_local_mac(uint8_t *local_mac, const uint8_t *universal_mac) Derive local MAC address from universal MAC address. This function copies a universal MAC address and then sets the "locally administered" bit (bit 0x2) in the first octet, creating a locally administered MAC address. If the universal MAC address argument is already a locally administered MAC address, then the first octet is XORed with 0x4 in order to create a different locally administered MAC address. - Parameters local_mac -- base MAC address, length: 6 bytes. length: 6 bytes for MAC-48 universal_mac -- Source universal MAC address, length: 6 bytes. - - Returns ESP_OK on success - esp_err_t esp_iface_mac_addr_set(const uint8_t *mac, esp_mac_type_t type) Set custom MAC address of the interface. This function allows you to overwrite the MAC addresses of the interfaces set by the base MAC address. - Parameters mac -- MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for ESP_MAC_IEEE802154 type, if CONFIG_SOC_IEEE802154_SUPPORTED=y) type -- Type of MAC address - - Returns ESP_OK on success - size_t esp_mac_addr_len_get(esp_mac_type_t type) Return the size of the MAC type in bytes. If CONFIG_SOC_IEEE802154_SUPPORTED is set then for these types: ESP_MAC_IEEE802154 is 8 bytes. ESP_MAC_BASE, ESP_MAC_EFUSE_FACTORY and ESP_MAC_EFUSE_CUSTOM the MAC size is 6 bytes. ESP_MAC_EFUSE_EXT is 2 bytes. If CONFIG_SOC_IEEE802154_SUPPORTED is not set then for all types it returns 6 bytes. - Parameters type -- Type of MAC address - Returns 0 MAC type not found (not supported) 6 bytes for MAC-48. 8 bytes for EUI-64. - Macros - MAC2STR(a) - MACSTR Enumerations - enum esp_mac_type_t Values: - enumerator ESP_MAC_WIFI_STA MAC for WiFi Station (6 bytes) - enumerator ESP_MAC_WIFI_SOFTAP MAC for WiFi Soft-AP (6 bytes) - enumerator ESP_MAC_BT MAC for Bluetooth (6 bytes) - enumerator ESP_MAC_ETH MAC for Ethernet (6 bytes) - enumerator ESP_MAC_IEEE802154 if CONFIG_SOC_IEEE802154_SUPPORTED=y, MAC for IEEE802154 (8 bytes) - enumerator ESP_MAC_BASE Base MAC for that used for other MAC types (6 bytes) - enumerator ESP_MAC_EFUSE_FACTORY MAC_FACTORY eFuse which was burned by Espressif in production (6 bytes) - enumerator ESP_MAC_EFUSE_CUSTOM MAC_CUSTOM eFuse which was can be burned by customer (6 bytes) - enumerator ESP_MAC_EFUSE_EXT if CONFIG_SOC_IEEE802154_SUPPORTED=y, MAC_EXT eFuse which is used as an extender for IEEE802154 MAC (2 bytes) - enumerator ESP_MAC_WIFI_STA Header File This header file can be included with: #include "esp_chip_info.h" Functions - void esp_chip_info(esp_chip_info_t *out_info) Fill an esp_chip_info_t structure with information about the chip. - Parameters out_info -- [out] structure to be filled Structures - struct esp_chip_info_t The structure represents information about the chip. Public Members - esp_chip_model_t model chip model, one of esp_chip_model_t - uint32_t features bit mask of CHIP_FEATURE_x feature flags - uint16_t revision chip revision number (in format MXX; where M - wafer major version, XX - wafer minor version) - uint8_t cores number of CPU cores - esp_chip_model_t model Macros - CHIP_FEATURE_EMB_FLASH Chip has embedded flash memory. - CHIP_FEATURE_WIFI_BGN Chip has 2.4GHz WiFi. - CHIP_FEATURE_BLE Chip has Bluetooth LE. - CHIP_FEATURE_BT Chip has Bluetooth Classic. - CHIP_FEATURE_IEEE802154 Chip has IEEE 802.15.4. - CHIP_FEATURE_EMB_PSRAM Chip has embedded psram. Enumerations - enum esp_chip_model_t Chip models. Values: - enumerator CHIP_ESP32 ESP32. - enumerator CHIP_ESP32S2 ESP32-S2. - enumerator CHIP_ESP32S3 ESP32-S3. - enumerator CHIP_ESP32C3 ESP32-C3. - enumerator CHIP_ESP32C2 ESP32-C2. - enumerator CHIP_ESP32C6 ESP32-C6. - enumerator CHIP_ESP32H2 ESP32-H2. - enumerator CHIP_ESP32P4 ESP32-P4. - enumerator CHIP_POSIX_LINUX The code is running on POSIX/Linux simulator. - enumerator CHIP_ESP32 Header File This header file can be included with: #include "esp_cpu.h" Functions - void esp_cpu_stall(int core_id) Stall a CPU core. - Parameters core_id -- The core's ID - void esp_cpu_unstall(int core_id) Resume a previously stalled CPU core. - Parameters core_id -- The core's ID - void esp_cpu_reset(int core_id) Reset a CPU core. - Parameters core_id -- The core's ID - void esp_cpu_wait_for_intr(void) Wait for Interrupt. This function causes the current CPU core to execute its Wait For Interrupt (WFI or equivalent) instruction. After executing this function, the CPU core will stop execution until an interrupt occurs. - int esp_cpu_get_core_id(void) Get the current core's ID. This function will return the ID of the current CPU (i.e., the CPU that calls this function). - Returns The current core's ID [0..SOC_CPU_CORES_NUM - 1] - void *esp_cpu_get_sp(void) Read the current stack pointer address. - Returns Stack pointer address - esp_cpu_cycle_count_t esp_cpu_get_cycle_count(void) Get the current CPU core's cycle count. Each CPU core maintains an internal counter (i.e., cycle count) that increments every CPU clock cycle. - Returns Current CPU's cycle count, 0 if not supported. - void esp_cpu_set_cycle_count(esp_cpu_cycle_count_t cycle_count) Set the current CPU core's cycle count. Set the given value into the internal counter that increments every CPU clock cycle. - Parameters cycle_count -- CPU cycle count - void *esp_cpu_pc_to_addr(uint32_t pc) Convert a program counter (PC) value to address. If the architecture does not store the true virtual address in the CPU's PC or return addresses, this function will convert the PC value to a virtual address. Otherwise, the PC is just returned - Parameters pc -- PC value - Returns Virtual address - void esp_cpu_intr_get_desc(int core_id, int intr_num, esp_cpu_intr_desc_t *intr_desc_ret) Get a CPU interrupt's descriptor. Each CPU interrupt has a descriptor describing the interrupt's capabilities and restrictions. This function gets the descriptor of a particular interrupt on a particular CPU. - Parameters core_id -- [in] The core's ID intr_num -- [in] Interrupt number intr_desc_ret -- [out] The interrupt's descriptor - - void esp_cpu_intr_set_ivt_addr(const void *ivt_addr) Set the base address of the current CPU's Interrupt Vector Table (IVT) - Parameters ivt_addr -- Interrupt Vector Table's base address - bool esp_cpu_intr_has_handler(int intr_num) Check if a particular interrupt already has a handler function. Check if a particular interrupt on the current CPU already has a handler function assigned. Note This function simply checks if the IVT of the current CPU already has a handler assigned. - Parameters intr_num -- Interrupt number (from 0 to 31) - Returns True if the interrupt has a handler function, false otherwise. - void esp_cpu_intr_set_handler(int intr_num, esp_cpu_intr_handler_t handler, void *handler_arg) Set the handler function of a particular interrupt. Assign a handler function (i.e., ISR) to a particular interrupt on the current CPU. Note This function simply sets the handler function (in the IVT) and does not actually enable the interrupt. - Parameters intr_num -- Interrupt number (from 0 to 31) handler -- Handler function handler_arg -- Argument passed to the handler function - - void *esp_cpu_intr_get_handler_arg(int intr_num) Get a handler function's argument of. Get the argument of a previously assigned handler function on the current CPU. - Parameters intr_num -- Interrupt number (from 0 to 31) - Returns The the argument passed to the handler function - void esp_cpu_intr_enable(uint32_t intr_mask) Enable particular interrupts on the current CPU. - Parameters intr_mask -- Bit mask of the interrupts to enable - void esp_cpu_intr_disable(uint32_t intr_mask) Disable particular interrupts on the current CPU. - Parameters intr_mask -- Bit mask of the interrupts to disable - uint32_t esp_cpu_intr_get_enabled_mask(void) Get the enabled interrupts on the current CPU. - Returns Bit mask of the enabled interrupts - void esp_cpu_intr_edge_ack(int intr_num) Acknowledge an edge interrupt. - Parameters intr_num -- Interrupt number (from 0 to 31) - void esp_cpu_configure_region_protection(void) Configure the CPU to disable access to invalid memory regions. - esp_err_t esp_cpu_set_breakpoint(int bp_num, const void *bp_addr) Set and enable a hardware breakpoint on the current CPU. Note This function is meant to be called by the panic handler to set a breakpoint for an attached debugger during a panic. Note Overwrites previously set breakpoint with same breakpoint number. - Parameters bp_num -- Hardware breakpoint number [0..SOC_CPU_BREAKPOINTS_NUM - 1] bp_addr -- Address to set a breakpoint on - - Returns ESP_OK if breakpoint is set. Failure otherwise - esp_err_t esp_cpu_clear_breakpoint(int bp_num) Clear a hardware breakpoint on the current CPU. Note Clears a breakpoint regardless of whether it was previously set - Parameters bp_num -- Hardware breakpoint number [0..SOC_CPU_BREAKPOINTS_NUM - 1] - Returns ESP_OK if breakpoint is cleared. Failure otherwise - esp_err_t esp_cpu_set_watchpoint(int wp_num, const void *wp_addr, size_t size, esp_cpu_watchpoint_trigger_t trigger) Set and enable a hardware watchpoint on the current CPU. Set and enable a hardware watchpoint on the current CPU, specifying the memory range and trigger operation. Watchpoints will break/panic the CPU when the CPU accesses (according to the trigger type) on a certain memory range. Note Overwrites previously set watchpoint with same watchpoint number. On RISC-V chips, this API uses method0(Exact matching) and method1(NAPOT matching) according to the riscv-debug-spec-0.13 specification for address matching. If the watch region size is 1byte, it uses exact matching (method 0). If the watch region size is larger than 1byte, it uses NAPOT matching (method 1). This mode requires the watching region start address to be aligned to the watching region size. - Parameters wp_num -- Hardware watchpoint number [0..SOC_CPU_WATCHPOINTS_NUM - 1] wp_addr -- Watchpoint's base address, must be naturally aligned to the size of the region size -- Size of the region to watch. Must be one of 2^n and in the range of [1 ... SOC_CPU_WATCHPOINT_MAX_REGION_SIZE] trigger -- Trigger type - - Returns ESP_ERR_INVALID_ARG on invalid arg, ESP_OK otherwise - esp_err_t esp_cpu_clear_watchpoint(int wp_num) Clear a hardware watchpoint on the current CPU. Note Clears a watchpoint regardless of whether it was previously set - Parameters wp_num -- Hardware watchpoint number [0..SOC_CPU_WATCHPOINTS_NUM - 1] - Returns ESP_OK if watchpoint was cleared. Failure otherwise. - bool esp_cpu_dbgr_is_attached(void) Check if the current CPU has a debugger attached. - Returns True if debugger is attached, false otherwise - void esp_cpu_dbgr_break(void) Trigger a call to the current CPU's attached debugger. - intptr_t esp_cpu_get_call_addr(intptr_t return_address) Given the return address, calculate the address of the preceding call instruction This is typically used to answer the question "where was the function called from?". - Parameters return_address -- The value of the return address register. Typically set to the value of __builtin_return_address(0). - Returns Address of the call instruction preceding the return address. - bool esp_cpu_compare_and_set(volatile uint32_t *addr, uint32_t compare_value, uint32_t new_value) Atomic compare-and-set operation. - Parameters addr -- Address of atomic variable compare_value -- Value to compare the atomic variable to new_value -- New value to set the atomic variable to - - Returns Whether the atomic variable was set or not Structures - struct esp_cpu_intr_desc_t CPU interrupt descriptor. Each particular CPU interrupt has an associated descriptor describing that particular interrupt's characteristics. Call esp_cpu_intr_get_desc() to get the descriptors of a particular interrupt. Public Members - int priority Priority of the interrupt if it has a fixed priority, (-1) if the priority is configurable. - esp_cpu_intr_type_t type Whether the interrupt is an edge or level type interrupt, ESP_CPU_INTR_TYPE_NA if the type is configurable. - uint32_t flags Flags indicating extra details. - int priority Macros - ESP_CPU_INTR_DESC_FLAG_SPECIAL Interrupt descriptor flags of esp_cpu_intr_desc_t. The interrupt is a special interrupt (e.g., a CPU timer interrupt) - ESP_CPU_INTR_DESC_FLAG_RESVD The interrupt is reserved for internal use Type Definitions - typedef uint32_t esp_cpu_cycle_count_t CPU cycle count type. This data type represents the CPU's clock cycle count - typedef void (*esp_cpu_intr_handler_t)(void *arg) CPU interrupt handler type. Enumerations - enum esp_cpu_intr_type_t CPU interrupt type. Values: - enumerator ESP_CPU_INTR_TYPE_LEVEL - enumerator ESP_CPU_INTR_TYPE_EDGE - enumerator ESP_CPU_INTR_TYPE_NA - enumerator ESP_CPU_INTR_TYPE_LEVEL Header File This header file can be included with: #include "esp_app_desc.h" This header file is a part of the API provided by the esp_app_formatcomponent. To declare that your component depends on esp_app_format, add the following to your CMakeLists.txt: REQUIRES esp_app_format or PRIV_REQUIRES esp_app_format Functions - const esp_app_desc_t *esp_app_get_description(void) Return esp_app_desc structure. This structure includes app version. Return description for running app. - Returns Pointer to esp_app_desc structure. - int esp_app_get_elf_sha256(char *dst, size_t size) Fill the provided buffer with SHA256 of the ELF file, formatted as hexadecimal, null-terminated. If the buffer size is not sufficient to fit the entire SHA256 in hex plus a null terminator, the largest possible number of bytes will be written followed by a null. - Parameters dst -- Destination buffer size -- Size of the buffer - - Returns Number of bytes written to dst (including null terminator) - char *esp_app_get_elf_sha256_str(void) Return SHA256 of the ELF file which is already formatted as hexadecimal, null-terminated included. Can be used in panic handler or core dump during when cache is disabled. The length is defined by CONFIG_APP_RETRIEVE_LEN_ELF_SHA option. - Returns Hexadecimal SHA256 string Structures - struct esp_app_desc_t Description about application. Public Members - uint32_t magic_word Magic word ESP_APP_DESC_MAGIC_WORD - uint32_t secure_version Secure version - uint32_t reserv1[2] reserv1 - char version[32] Application version - char project_name[32] Project name - char time[16] Compile time - char date[16] Compile date - char idf_ver[32] Version IDF - uint8_t app_elf_sha256[32] sha256 of elf file - uint32_t reserv2[20] reserv2 - uint32_t magic_word Macros - ESP_APP_DESC_MAGIC_WORD The magic word for the esp_app_desc structure that is in DROM.
null
null
null
https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/misc_system_api.html
ESP-IDF Programming Guide v5.2.1 documentation
null